Exemplo n.º 1
0
 private static void handleResolverExpression() {
   final Resolver resolver = cloudname.getResolver();
   try {
     System.out.println(
         "Added a resolver listener for expression: "
             + resolverExpression
             + ". Will print out all events for the given expression.");
     resolver.addResolverListener(
         resolverExpression,
         new ResolverListener() {
           @Override
           public void endpointEvent(Event event, Endpoint endpoint) {
             System.out.println("Received event: " + event + " for endpoint: " + endpoint);
           }
         });
   } catch (CloudnameException e) {
     System.err.println("Problem with cloudname: " + e.getMessage());
   }
   final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   while (true) {
     System.out.println("Press enter to exit");
     String s = null;
     try {
       s = br.readLine();
     } catch (IOException e) {
       e.printStackTrace();
     }
     if (s.length() == 0) {
       System.out.println("Exiting");
       System.exit(0);
     }
   }
 }
Exemplo n.º 2
0
  public static void main(final String[] args) {

    // Disable log system, we want full control over what is sent to console.
    final ConsoleAppender consoleAppender = new ConsoleAppender();
    consoleAppender.activateOptions();
    consoleAppender.setLayout(new PatternLayout("%p %t %C:%M %m%n"));
    consoleAppender.setThreshold(Level.OFF);
    BasicConfigurator.configure(consoleAppender);

    // Parse the flags.
    Flags flags = new Flags().loadOpts(ZkTool.class).parse(args);

    // Check if we wish to print out help text
    if (flags.helpFlagged()) {
      flags.printHelp(System.out);
      System.out.println("Must specify one of the following options:");
      System.out.println(actionSelectingFlagNames);
      return;
    }

    checkArgumentCombinationValid(flags);

    ZkCloudname.Builder builder = new ZkCloudname.Builder();
    if (zooKeeperFlag == null) {
      builder.setDefaultConnectString();
    } else {
      builder.setConnectString(zooKeeperFlag);
    }
    try {
      cloudname = builder.build().connect();
    } catch (CloudnameException e) {
      System.err.println("Could not connect to zookeeper " + e.getMessage());
      return;
    }

    try {
      if (filePath != null) {
        handleFilepath();
      } else if (coordinateFlag != null) {
        handleCoordinateOperation();
      } else if (resolverExpression != null) {
        handleResolverExpression();
      } else if (listFlag) {
        listCoordinates();
      } else {
        System.err.println("No action specified");
      }
    } catch (Exception e) {
      System.err.println("An error occurred: " + e.getMessage());
      e.printStackTrace();
    } finally {
      cloudname.close();
    }
  }
Exemplo n.º 3
0
  private static void listCoordinates() {
    try {
      final List<String> nodeList = new ArrayList<String>();
      cloudname.listRecursively(nodeList);
      for (final String node : nodeList) {
        final Matcher m = instanceConfigPattern.matcher(node);

        /*
         *  We only parse config paths, and we convert these to
         *  Cloudname coordinates to not confuse the user.
         */
        if (m.matches()) {
          System.out.printf("%s.%s.%s.%s\n", m.group(4), m.group(3), m.group(2), m.group(1));
        }
      }
    } catch (final CloudnameException e) {
      System.err.println("Got error: " + e.getMessage());
    } catch (final InterruptedException e) {
      System.err.println("Got error: " + e.getMessage());
    }
  }
Exemplo n.º 4
0
  private static void handleCoordinateOperation() {
    final Resolver resolver = cloudname.getResolver();
    final Coordinate coordinate = Coordinate.parse(coordinateFlag);
    switch (operationFlag) {
      case CREATE:
        try {
          cloudname.createCoordinate(coordinate);
        } catch (CloudnameException e) {
          System.err.println("Got error: " + e.getMessage());
          break;
        } catch (CoordinateExistsException e) {
          e.printStackTrace();
          break;
        }
        System.err.println("Created coordinate.");
        break;
      case DELETE:
        try {
          cloudname.destroyCoordinate(coordinate);
        } catch (CoordinateDeletionException e) {
          System.err.println("Got error: " + e.getMessage());
          return;
        } catch (CoordinateMissingException e) {
          System.err.println("Got error: " + e.getMessage());
          break;
        } catch (CloudnameException e) {
          System.err.println("Got error: " + e.getMessage());
          break;
        }
        System.err.println("Deleted coordinate.");
        break;
      case STATUS:
        {
          ServiceStatus status;
          try {
            status = cloudname.getStatus(coordinate);
          } catch (CloudnameException e) {
            System.err.println(
                "Problems loading status, is service running? Error:\n" + e.getMessage());
            break;
          }
          System.err.println(
              "Status:\n" + status.getState().toString() + " " + status.getMessage());
          List<Endpoint> endpoints = null;
          try {
            endpoints =
                resolver.resolve(
                    "all."
                        + coordinate.getService()
                        + "."
                        + coordinate.getUser()
                        + "."
                        + coordinate.getCell());
          } catch (CloudnameException e) {
            System.err.println("Got error: " + e.getMessage());
            break;
          }
          System.err.println("Endpoints:");
          for (Endpoint endpoint : endpoints) {
            if (endpoint.getCoordinate().getInstance() == coordinate.getInstance()) {
              System.err.println(
                  endpoint.getName()
                      + "-->"
                      + endpoint.getHost()
                      + ":"
                      + endpoint.getPort()
                      + " protocol:"
                      + endpoint.getProtocol());
              System.err.println("Endpoint data:\n" + endpoint.getEndpointData());
            }
          }
          break;
        }
      case HOST:
        {
          List<Endpoint> endpoints = null;
          try {
            endpoints = resolver.resolve(coordinate.asString());
          } catch (CloudnameException e) {
            System.err.println(
                "Could not resolve " + coordinate.asString() + " Error:\n" + e.getMessage());
            break;
          }
          for (Endpoint endpoint : endpoints) {
            System.out.println("Host: " + endpoint.getHost());
          }
        }
        break;
      case SET_CONFIG:
        try {
          cloudname.setConfig(coordinate, configFlag, null);
        } catch (CloudnameException e) {
          System.err.println("Got error: " + e.getMessage());
          break;

        } catch (CoordinateMissingException e) {
          System.err.println("Non-existing coordinate.");
        }
        System.err.println("Config updated.");
        break;

      case READ_CONFIG:
        try {
          System.out.println("Config is:" + cloudname.getConfig(coordinate));
        } catch (CoordinateMissingException e) {
          System.err.println("Non-existing coordinate.");
        } catch (CloudnameException e) {
          System.err.println("Problem with cloudname: " + e.getMessage());
        }
        break;
      default:
        System.out.println("Unknown command " + operationFlag);
    }
  }
Exemplo n.º 5
0
    @Override
    public void processResult(int rawReturnCode, String notUsed, Object parent, String notUsed2) {

      KeeperException.Code returnCode = KeeperException.Code.get(rawReturnCode);
      ClaimedCoordinate claimedCoordinate = (ClaimedCoordinate) parent;
      LOG.fine(
          "Claim callback with "
              + returnCode.name()
              + " "
              + claimedCoordinate.path
              + " synched: "
              + isSynchronizedWithZooKeeper.get()
              + " thread: "
              + this);
      switch (returnCode) {
          // The claim was successful. This means that the node was created. We need to
          // populate the status and endpoints.
        case OK:

          // We should be the first one to write to the new node, or fail.
          // This requires that the first version is 0, have not seen this documented
          // but it should be a fair assumption and is verified by unit tests.
          synchronized (lastStatusVersionMonitor) {
            lastStatusVersion = 0;
          }

          // We need to set this to synced or updateCoordinateData will complain.
          // updateCoordinateData will set it to out-of-sync in case of problems.
          isSynchronizedWithZooKeeper.set(true);

          try {
            registerWatcher();
          } catch (CloudnameException e) {
            LOG.fine(
                "Failed register watcher after claim. Going to state out of sync: "
                    + e.getMessage());

            isSynchronizedWithZooKeeper.set(false);
            return;

          } catch (InterruptedException e) {

            LOG.fine("Interrupted while setting up new watcher. Going to state out of sync.");
            isSynchronizedWithZooKeeper.set(false);
            return;
          }
          // No exceptions, let's celebrate with a log message.
          LOG.info("Claim processed ok, path: " + path);
          claimedCoordinate.sendEventToCoordinateListener(
              CoordinateListener.Event.COORDINATE_OK, "claimed");
          return;

        case NODEEXISTS:
          // Someone has already claimed the coordinate. It might have been us in a
          // different thread. If we already have claimed the coordinate then don't care.
          // Else notify the client. If everything is fine, this is not a true negative,
          // so ignore it. It might happen if two attempts to tryClaim the coordinate run
          // in parallel.
          if (isSynchronizedWithZooKeeper.get() && started.get()) {
            LOG.fine("Everything is fine, ignoring NODEEXISTS message, path: " + path);
            return;
          }

          LOG.info("Claimed fail, node already exists, will retry: " + path);
          claimedCoordinate.sendEventToCoordinateListener(
              CoordinateListener.Event.NOT_OWNER, "Node already exists.");
          LOG.info("isSynchronizedWithZooKeeper: " + isSynchronizedWithZooKeeper.get());
          checkVersion.set(true);
          return;
        case NONODE:
          LOG.info("Could not claim due to missing coordinate, path: " + path);
          claimedCoordinate.sendEventToCoordinateListener(
              CoordinateListener.Event.NOT_OWNER,
              "No node on claiming coordinate: " + returnCode.name());
          return;

        default:
          // Random problem, report the problem to the client.
          claimedCoordinate.sendEventToCoordinateListener(
              CoordinateListener.Event.NO_CONNECTION_TO_STORAGE,
              "Could not reclaim coordinate. Return code: " + returnCode.name());
          return;
      }
    }