private void waitForManagementWebServices(
      final boolean isSecureConnection,
      final String username,
      final String password,
      final Integer restPort,
      final Integer webuiPort,
      final long end,
      final MachineDetails[] servers)
      throws MalformedURLException, URISyntaxException, InterruptedException, TimeoutException,
          CLIException {
    // Wait for rest to become available
    // When the rest gateway is up and running, the cloud is ready to go
    for (final MachineDetails server : servers) {
      String ipAddress = null;
      if (cloud.getConfiguration().isBootstrapManagementOnPublicIp()) {
        ipAddress = server.getPublicAddress();
      } else {
        ipAddress = server.getPrivateAddress();
      }

      final URL restAdminUrl =
          new URI(
                  ShellUtils.getRestProtocol(isSecureConnection),
                  null,
                  ipAddress,
                  restPort,
                  null,
                  null,
                  null)
              .toURL();
      final URL webUIUrl =
          new URI(
                  ShellUtils.getRestProtocol(isSecureConnection),
                  null,
                  ipAddress,
                  webuiPort,
                  null,
                  null,
                  null)
              .toURL();

      // We are relying on start-management command to be run on the
      // new machine, so everything should be up if the rest admin is up
      waitForConnection(
          username,
          password,
          restAdminUrl,
          isSecureConnection,
          CalcUtils.millisUntil(end),
          TimeUnit.MILLISECONDS);

      logger.info("Rest service is available at: " + restAdminUrl + '.');
      logger.info("Webui service is available at: " + webUIUrl + '.');
    }
  }
Ejemplo n.º 2
0
 /**
  * prompts the user with the given question.
  *
  * @param session the command session.
  * @param messageKey the message key.
  * @param messageArgs the message arguments.
  * @return true if user hits 'y' OR 'yes' else returns false
  * @throws IOException Indicates a failure while accessing the session's stdout.
  */
 public static boolean promptUser(
     final CommandSession session, final String messageKey, final Object... messageArgs)
     throws IOException {
   if ((Boolean) session.get(Constants.INTERACTIVE_MODE)) {
     session.getConsole().print(Ansi.ansi().eraseLine(Erase.ALL));
     final String confirmationQuestion = ShellUtils.getFormattedMessage(messageKey, messageArgs);
     session.getConsole().print(confirmationQuestion + " ");
     session.getConsole().flush();
     char responseChar = '\0';
     final StringBuilder responseBuffer = new StringBuilder();
     while (true) {
       responseChar = (char) session.getKeyboard().read();
       if (responseChar == '\u007F') { // backspace
         if (responseBuffer.length() > 0) {
           responseBuffer.deleteCharAt(responseBuffer.length() - 1);
           session.getConsole().print(Ansi.ansi().cursorLeft(1).eraseLine());
         }
       } else if (responseChar == WIN_RETURN_CHAR || responseChar == LINUX_RETURN_CHAR) {
         session.getConsole().println();
         break;
       } else {
         session.getConsole().print(responseChar);
         responseBuffer.append(responseChar);
       }
       session.getConsole().flush();
     }
     final String responseStr = responseBuffer.toString().trim();
     return "y".equalsIgnoreCase(responseStr) || "yes".equalsIgnoreCase(responseStr);
   }
   // Shell is running in nonInteractive mode. we skip the question.
   return true;
 }
  /**
   * Gets the latest events of this deployment id. Events are sorted by event index.
   *
   * @return A list of events. If this is the first time events are requested, all events are
   *     retrieved. Otherwise, only new events (that were not reported earlier) are retrieved.
   * @throws RestClientException Indicates a failure to get events from the server.
   */
  @Override
  public boolean lifeCycleEnded() throws RestClientException, CLIException {

    boolean serviceIsInstalled;
    try {
      ServiceDescription serviceDescription =
          restClient.getServiceDescription(applicationName, serviceName);
      logger.fine("Service description is : " + serviceDescription);
      CloudifyConstants.DeploymentState serviceState = serviceDescription.getServiceState();
      if (serviceState.equals(CloudifyConstants.DeploymentState.FAILED)) {
        throw new CLIException(
            ShellUtils.getFormattedMessage(
                CloudifyErrorMessages.FAILED_TO_DEPLOY_SERVICE.getName(), serviceName));
      }
      serviceIsInstalled = serviceState.equals(CloudifyConstants.DeploymentState.STARTED);
    } catch (final RestClientResponseException e) {
      if (e.getStatusCode() == RESOURCE_NOT_FOUND_EXCEPTION_CODE) {
        // the service is not available yet
        serviceIsInstalled = false;
      } else {
        throw e;
      }
    }

    return serviceIsInstalled;
  }
Ejemplo n.º 4
0
 /**
  * Checks if the latest version is used.
  *
  * @param session the command session.
  */
 public static void doVersionCheck(final CommandSession session) {
   String currentBuildStr = PlatformVersion.getBuildNumber();
   if (currentBuildStr.contains("-")) {
     currentBuildStr = currentBuildStr.substring(0, currentBuildStr.indexOf("-"));
   }
   final int currentVersion = Integer.parseInt(currentBuildStr);
   final int latestBuild = getLatestBuildNumber(currentVersion);
   String message;
   if (latestBuild == -1) {
     message = ShellUtils.getFormattedMessage("could_not_get_version");
   } else if (latestBuild > currentVersion) {
     message = ShellUtils.getFormattedMessage("newer_version_exists");
   } else {
     message = ShellUtils.getFormattedMessage("version_up_to_date");
   }
   session.getConsole().println(message);
   session.getConsole().println();
 }
  /**
   * @param timeout The number of {@link TimeUnit}s to wait before timing out
   * @param timeoutUnit The time unit to use (seconds, minutes etc.)
   * @throws TimeoutException Indicates the time out was reached before the tear-down completed
   * @throws CLIException Indicates a basic failure tear-down the cloud. a detailed message is
   *     included
   * @throws InterruptedException Indicates a thread was interrupted while waiting
   */
  public void teardownCloudAndWait(final long timeout, final TimeUnit timeoutUnit)
      throws TimeoutException, CLIException, InterruptedException {

    final long end = System.currentTimeMillis() + timeoutUnit.toMillis(timeout);

    createProvisioningDriver();

    ShellUtils.checkNotNull("providerDirectory", providerDirectory);

    destroyManagementServers(CalcUtils.millisUntil(end), TimeUnit.MILLISECONDS);
  }
Ejemplo n.º 6
0
  /**
   * ****** .
   *
   * @param url .
   * @param isSecureConnection .
   * @return .
   * @throws MalformedURLException .
   */
  public static String getFormattedRestUrl(final String url, final boolean isSecureConnection)
      throws MalformedURLException {
    String formattedURL = url;
    if (!formattedURL.endsWith("/")) {
      formattedURL = formattedURL + '/';
    }

    final String protocolPrefix = ShellUtils.getRestProtocol(isSecureConnection) + "://";
    if (!formattedURL.startsWith("http://") && !formattedURL.startsWith("https://")) {
      formattedURL = protocolPrefix + formattedURL;
    }

    URL urlObj;
    urlObj = new URL(formattedURL);
    if (urlObj.getPort() == -1) {
      final StringBuilder urlSB = new StringBuilder(formattedURL);
      final int portIndex = formattedURL.indexOf("/", protocolPrefix.length() + 1);
      urlSB.insert(portIndex, ':' + ShellUtils.getDefaultRestPortAsString(isSecureConnection));
      formattedURL = urlSB.toString();
      urlObj = new URL(formattedURL);
    }

    return formattedURL;
  }
Ejemplo n.º 7
0
  private String colorLogTail(final String logTail) {

    String result = logTail;
    result = result.replaceAll(" WARNING ", ShellUtils.getBoldMessage(" WARNING "));
    result = result.replaceAll(" FINE ", ShellUtils.getBoldMessage(" FINE "));
    result = result.replaceAll(" FINER ", ShellUtils.getBoldMessage(" FINER "));
    result = result.replaceAll(" FINEST ", ShellUtils.getBoldMessage(" FINEST "));
    result = result.replaceAll(" INFO ", ShellUtils.getBoldMessage(" INFO "));
    result = result.replaceAll(" SEVERE ", ShellUtils.getColorMessage(" SEVERE ", Color.RED));

    return result;
  }
Ejemplo n.º 8
0
  /**
   * returns true if the last version check was done more than two weeks ago.
   *
   * @param session the command session.
   * @return true if a version check is required else returns false.
   */
  public static boolean shouldDoVersionCheck(final CommandSession session) {
    final boolean interactive = (Boolean) session.get(Constants.INTERACTIVE_MODE);
    if (!interactive) {
      return false;
    }

    final long lastAskedTS = getLastTimeAskedAboutVersionCheck();
    // check only if checked over a two weeks ago and user agrees
    try {
      if (lastAskedTS <= System.currentTimeMillis() - TWO_WEEKS_IN_MILLIS) {
        final boolean userConfirms = ShellUtils.promptUser(session, "version_check_confirmation");
        registerVersionCheck();
        return userConfirms;
      }
    } catch (final IOException e) {
      logger.log(Level.FINE, "Failed to prompt user", e);
    }
    return false;
  }
  /**
   * Bootstraps and waits until the management machines are running, or until the timeout is
   * reached.
   *
   * @param securityProfile set security profile (nonsecure/secure/ssl)
   * @param username The username for a secure connection to the server
   * @param password The password for a secure connection to the server
   * @param keystorePassword The password to the keystore to set on the rest server
   * @param timeout The number of {@link TimeUnit}s to wait before timing out
   * @param timeoutUnit The time unit to use (seconds, minutes etc.)
   * @throws InstallerException Indicates the provisioning driver failed to start management
   *     machines or that the management processes failed to start
   * @throws CLIException Indicates a basic failure or a time out. a detailed message is included
   * @throws InterruptedException Indicates a thread was interrupted while waiting
   */
  public void bootstrapCloudAndWait(
      final String securityProfile,
      final String username,
      final String password,
      final String keystorePassword,
      final long timeout,
      final TimeUnit timeoutUnit)
      throws InstallerException, CLIException, InterruptedException {

    final long end = System.currentTimeMillis() + timeoutUnit.toMillis(timeout);

    createProvisioningDriver();

    // Start the cloud machines!!!
    MachineDetails[] servers;
    try {
      servers = provisioning.startManagementMachines(timeout, timeoutUnit);
    } catch (final CloudProvisioningException e) {
      final CLIStatusException cliStatusException =
          new CLIStatusException(
              e, CloudifyErrorMessages.CLOUD_API_ERROR.getName(), e.getMessage());
      throw cliStatusException;
    } catch (final TimeoutException e) {
      throw new CLIException(
          "Cloudify bootstrap on provider "
              + this.cloud.getProvider().getProvider()
              + " timed-out. "
              + "Please try to run again using the –timeout option.",
          e);
    }

    // from this point on - close machines if an exception is thrown (to
    // avoid leaks).
    try {

      // log details in FINE
      if (logger.isLoggable(Level.FINE)) {
        for (final MachineDetails server : servers) {
          logServerDetails(server);
        }
      }

      validateServers(servers);

      // Start the management agents and other processes
      if (servers[0].isAgentRunning()) {
        // must be using existing machines.
        throw new IllegalStateException(
            "Cloud bootstrapper found existing management machines with the same name. "
                + "Please shut them down before continuing");
      }

      startManagememntProcesses(servers, securityProfile, keystorePassword, end);

      if (!isNoWebServices()) {
        final Integer restPort =
            getRestPort(
                cloud.getConfiguration().getComponents().getRest().getPort(),
                ShellUtils.isSecureConnection(securityProfile));
        final Integer webuiPort =
            getWebuiPort(
                cloud.getConfiguration().getComponents().getWebui().getPort(),
                ShellUtils.isSecureConnection(securityProfile));
        waitForManagementWebServices(
            ShellUtils.isSecureConnection(securityProfile),
            username,
            password,
            restPort,
            webuiPort,
            end,
            servers);
      }

    } catch (final IOException e) {
      stopManagementMachines();
      throw new CLIException(
          "Cloudify bootstrap on provider "
              + this.cloud.getProvider().getProvider()
              + " failed. Reason: "
              + e.getMessage(),
          e);
    } catch (final URISyntaxException e) {
      stopManagementMachines();
      throw new CLIException("Bootstrap-cloud failed. Reason: " + e.getMessage(), e);
    } catch (final TimeoutException e) {
      stopManagementMachines();
      throw new CLIException(
          "Cloudify bootstrap on provider "
              + this.cloud.getProvider().getProvider()
              + " timed-out. "
              + "Please try to run again using the –timeout option.",
          e);
    } catch (final CLIException e) {
      stopManagementMachines();
      throw e;
    } catch (final InstallerException e) {
      stopManagementMachines();
      throw e;
    } catch (final InterruptedException e) {
      stopManagementMachines();
      throw e;
    }
  }
Ejemplo n.º 10
0
 private boolean promptWouldYouLikeToContinueQuestion() throws IOException {
   return ShellUtils.promptUser(
       session, "would_you_like_to_continue_service_installation", serviceName);
 }