Exemplo n.º 1
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)
    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 stop completed
          successfully.

    Raises:
      ValueError: if result is None or not a dict
    """
        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 or isinstance(
                result[0], messages.Resource)):
            list_printer.PrintResourceList('deploymentmanagerv2.resources',
                                           result)
        else:
            raise ValueError(
                'result must be an Operation or list of Resources')
Exemplo n.º 3
0
 def Display(self, args, resources):
   """Prints the given resources."""
   if resources:
     resource_printer.Print(
         resources=resources,
         print_format='yaml',
         out=log.out)
    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')
def ExtractErrorMessage(error_details):
  """Extracts error details from an apitools_exceptions.HttpError.

  Args:
    error_details: a python dictionary returned from decoding an error that
        was serialized to json.

  Returns:
    Multiline string containing a detailed error message suitable to show to a
    user.
  """
  error_message = io.BytesIO()
  error_message.write('Error Response: [{code}] {message}'.format(
      code=error_details.get('code', 'UNKNOWN'),  # error_details.code is an int
      message=error_details.get('message', u'').encode('utf-8')))

  if 'url' in error_details:
    error_message.write('\n' + error_details['url'].encode('utf-8'))

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

  return error_message.getvalue()
Exemplo n.º 6
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)
Exemplo n.º 7
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')
    def Display(self, args, resources):
        """Prints the given resources; uses a list printer if Run gave us a list."""
        if not resources:
            return

        if isinstance(resources, list):
            console_io.PrintExtendedList(resources, self.data_format)
        else:
            resource_printer.Print(resources=resources,
                                   print_format='yaml',
                                   out=log.out)
Exemplo n.º 9
0
def ExtractErrorMessage(error_details):
    """Extracts error details from an apitools_exceptions.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('\n\nDetails: ')
        resource_printer.Print(resources=[error_details['details']],
                               print_format='json',
                               out=error_message)

    return error_message.getvalue()
Exemplo 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: 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)
Exemplo n.º 11
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: an Operation object

    Raises:
      TypeError: if result is not of type Operation
    """
    # Note that we expect an empty proto as a result (google.protobuf.Empty).
    # If that's what we receive, we can assume success.
    if not result:
      resource_printer.Print(resources={'key': args.key, 'success': True},
                             print_format=args.format or 'yaml',
                             out=log.out)
Exemplo n.º 12
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 Manifest object to display.

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

        resource_printer.Print(resources=result,
                               print_format=unused_args.format or 'yaml',
                               out=log.out)
Exemplo n.º 13
0
 def Display(self, unused_args, result):
   resource_printer.Print(result, 'json')
 def Display(self, args, resources):
     if not resources:
         return
     resource_printer.Print(resources=resources,
                            print_format='yaml',
                            out=log.out)
Exemplo n.º 15
0
 def Display(self, _, resources):
   resource_printer.Print(
       resources=resources,
       print_format='yaml',
       out=log.out)
Exemplo n.º 16
0
def PrettyPrint(resource, print_format='json'):
  """Prints the given resource."""
  resource_printer.Print(
      resources=[resource],
      print_format=print_format,
      out=log.out)
Exemplo n.º 17
0
    def Run(self, args):
        start = time_utils.CurrentTimeSec()

        # Set up Encryption utilities.
        openssl_executable = files.FindExecutableOnPath('openssl')
        if windows_encryption_utils:
            crypt = windows_encryption_utils.WinCrypt()
        elif openssl_executable:
            crypt = openssl_encryption_utils.OpensslCrypt(openssl_executable)
        else:
            raise utils.MissingDependencyError(
                '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)

        if args.instance == user:
            raise utils.InvalidUserError(
                MACHINE_USERNAME_SAME_ERROR.format(user, args.instance))

        # 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
        }
        # We call resource_printer directly here instead of just returning
        # connection_info because we want to prevent this information from being
        # logged.
        # TODO(user): b/24267426
        resource_printer.Print(connection_info,
                               args.format or 'text',
                               out=None)