Ejemplo n.º 1
0
 def Display(self, args, resources):
   """Prints the given resources."""
   if resources:
     resource_printer.Print(
         resources=resources,
         print_format='yaml',
         out=log.out)
Ejemplo n.º 2
0
    def Display(self, unused_args, result):
        """Display prints information about what just happened to stdout.

    Args:
      unused_args: The same as the args in Run.

      result: an Operation (may be in progress or completed) to display
          or a list of Resources, if a synchronous cancel completed
          successfully.

    Raises:
      ValueError: if result is None or not a dict
    """
        messages = self.context['deploymentmanager-v2beta2-messages']
        if isinstance(result, messages.Operation):
            resource_printer.Print(resources=result,
                                   print_format=unused_args.format or 'yaml',
                                   out=log.out)
        elif isinstance(result, list) and (not result or isinstance(
                result[0], messages.Resource)):
            list_printer.PrintResourceList(
                'deploymentmanagerv2beta2.resources', result)
        else:
            raise ValueError(
                'result must be an Operation or list of Resources')
Ejemplo n.º 3
0
  def Display(self, unused_args, deployment):
    """Display prints information about what just happened to stdout.

    Args:
      unused_args: The same as the args in Run.

      deployment: a Deployment to print

    Raises:
      ValueError: if result is None or not a deployment
    """
    client = self.context['deploymentmanager-client']
    messages = self.context['deploymentmanager-messages']
    if not isinstance(deployment, messages.Deployment):
      raise ValueError('result must be a Deployment')

    # Get resources belonging to the deployment to display
    project = properties.VALUES.core.project.Get(required=True)
    resources = None
    try:
      response = client.resources.List(
          messages.DeploymentmanagerResourcesListRequest(
              project=project, deployment=deployment.name))
      resources = response.resources
    except apitools_base.HttpError:
      pass  # Couldn't get resources, skip adding them to the table.
    resource_printer.Print(resources=deployment,
                           print_format=unused_args.format or 'yaml',
                           out=log.out)
    if resources:
      log.Print('resources:')
      list_printer.PrintResourceList('deploymentmanagerv2.resources',
                                     resources)
Ejemplo n.º 4
0
    def Display(self, unused_args, result):
        """Display prints information about what just happened to stdout.

    Args:
      unused_args: The same as the args in Run.

      result: an Operation (may be in progress or completed) to display
        or a list of Resources, if a synchronous preview or create completed.

    Raises:
      ValueError: if result is not a list of Resources or an Operation
    """
        messages = self.context['deploymentmanager-messages']
        if isinstance(result, messages.Operation):
            resource_printer.Print(resources=result,
                                   print_format=unused_args.format or 'yaml',
                                   out=log.out)
        elif isinstance(result, list) and not result:
            log.Print('No Deployments were found in your project!')
        elif isinstance(result, list) and isinstance(result[0],
                                                     messages.Resource):
            list_printer.PrintResourceList('deploymentmanagerv2.resources',
                                           result)
        else:
            raise ValueError(
                'result must be an Operation or list of Resources')
Ejemplo n.º 5
0
    def format(self, obj):
        """Prints out the given object using the format decided by the format flag.

    Args:
      obj: Object, The object to print.
    """
        if obj:
            resource_printer.Print(obj, self.__format_string, out=log.out)
Ejemplo n.º 6
0
    def Display(self, args, result):
        """Display prints information about what just happened to stdout.

    Args:
      args: The same as the args in Run.
      result: A dict object representing the operations resource describing the
      patch operation if the patch was successful.
    """
        if args.diff:
            resource_printer.Print(result, 'text')
Ejemplo n.º 7
0
 def Display(self, _, resources):
   """Prints the given resources."""
   # The following try/except ensures that we only call
   # resource_printer.Print if there is as least one item in the
   # resources generator.
   try:
     head = next(resources)
     resources = itertools.chain([head], resources)
     resource_printer.Print(
         resources=resources,
         print_format='yaml',
         out=log.out)
   except StopIteration:
     pass
Ejemplo n.º 8
0
def ExtractErrorMessage(error_details):
    """Extracts error details from an apitools_base.HttpError."""
    error_message = cStringIO.StringIO()
    error_message.write('Error Response: [{code}] {message}'.format(
        code=error_details.get('code', 'UNKNOWN'),
        message=error_details.get('message', '')))
    if 'url' in error_details:
        error_message.write('\n{url}'.format(url=error_details['url']))

    if error_details.get('details'):
        error_message.write('\nDetails: ')
        resource_printer.Print(resources=[error_details['details']],
                               print_format='json',
                               out=error_message)

    return error_message.getvalue()
Ejemplo n.º 9
0
    def Display(self, unused_args, result):
        """Display prints information about what just happened to stdout.

    Args:
      unused_args: The same as the args in Run.

      result: a list of delete operations

    Raises:
      ValueError: if result is None or not a list
    """
        if not isinstance(result, list):
            raise ValueError('result must be a list')

        resource_printer.Print(resources=result,
                               print_format=unused_args.format or 'yaml',
                               out=log.out)
Ejemplo n.º 10
0
    def Display(self, unused_args, result):
        """Display prints information about what just happened to stdout.

    Args:
      unused_args: The same as the args in Run.

      result: an Operation to display

    Raises:
      ValueError: if result is None or not an Operation
    """
        messages = self.context['deploymentmanager-v2beta2-messages']
        if not isinstance(result, messages.Operation):
            raise ValueError('result must be an Operation')

        resource_printer.Print(resources=result,
                               print_format=unused_args.format or 'yaml',
                               out=log.out)
Ejemplo n.º 11
0
 def Format(obj):
     if not obj:
         return
     resource_printer.Print(obj, args.format or 'yaml', out=log.out)
    def Run(self, args):
        start = time_utils.CurrentTimeSec()

        # Set up Encryption utilities.
        openssl_executable = files.FindExecutableOnPath('openssl')
        if openssl_executable:
            crypt = openssl_encryption_utils.OpensslCrypt(openssl_executable)
        elif windows_encryption_utils:
            crypt = windows_encryption_utils.WinCrypt()
        else:
            raise exceptions.ToolException(
                'Your platform does not support OpenSSL.')

        # Get Authenticated email address and default username.
        email = gaia_utils.GetAuthenticatedGaiaEmail(self.http)
        if args.user:
            user = args.user
        else:
            user = gaia_utils.MapGaiaEmailToDefaultAccountName(email)

        # Warn user (This warning doesn't show for non-interactive sessions).
        message = RESET_PASSWORD_WARNING.format(user)
        prompt_string = (
            'Would you like to set or reset the password for [{0}]'.format(
                user))
        console_io.PromptContinue(message=message,
                                  prompt_string=prompt_string,
                                  cancel_on_no=True)

        log.status.Print(
            'Resetting and retrieving password for [{0}] on [{1}]'.format(
                user, args.instance))

        # Get Encryption Keys.
        key = crypt.GetKeyPair()
        modulus, exponent = crypt.GetModulusExponentFromPublicKey(
            crypt.GetPublicKey(key))

        # Create Windows key entry.
        self.windows_key_entry = self._ConstructWindowsKeyEntry(
            user, modulus, exponent, email)

        # Call ReadWriteCommad.Run() which will fetch the instance and update
        # the metadata (using the data in self.windows_key_entry).
        objects = super(ResetWindowsPassword, self).Run(args)
        updated_instance = list(objects)[0]

        # Retrieve and Decrypt the password from the serial console.
        enc_password = self._GetEncryptedPasswordFromSerialPort(modulus)
        password = crypt.DecryptMessage(key, enc_password)

        # Get External IP address.
        try:
            access_configs = updated_instance['networkInterfaces'][0][
                'accessConfigs']
            external_ip_address = access_configs[0]['natIP']
        except KeyError:
            log.warn(NO_IP_WARNING.format(updated_instance['name']))
            external_ip_address = None

        # Check for old Windows credentials.
        if self.old_metadata_keys:
            log.warn(
                OLD_KEYS_WARNING.format(self.ref.Name(), self.ref.Name(),
                                        self.ref.zone,
                                        ' '.join(self.old_metadata_keys)))

        log.info('Total Elapsed Time: {0}'.format(time_utils.CurrentTimeSec() -
                                                  start))

        # Display the connection info.
        connection_info = {
            'username': user,
            'password': password,
            'ip_address': external_ip_address
        }
        resource_printer.Print(connection_info,
                               args.format or 'text',
                               out=None)
Ejemplo n.º 13
0
 def Display(self, _, resources):
   resource_printer.Print(
       resources=resources,
       print_format='yaml',
       out=log.out)
Ejemplo n.º 14
0
def PrettyPrint(resource, print_format='json'):
  """Prints the given resource."""
  resource_printer.Print(
      resources=[resource],
      print_format=print_format,
      out=log.out)