Example #1
0
    def Run(self, args):
        """Retrieves information about an SSL cert for a Cloud SQL instance.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object representing the sslCerts resource if the api request was
      successful.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """
        sql_client = self.context['sql_client']
        sql_messages = self.context['sql_messages']
        resources = self.context['registry']

        util.ValidateInstanceName(args.instance)
        instance_ref = resources.Parse(args.instance,
                                       collection='sql.instances')

        # sha1fingerprint, so that things can work with the resource parser.
        return util.GetCertFromName(sql_client, sql_messages, instance_ref,
                                    args.common_name)
Example #2
0
    def Run(self, args):
        """Lists all SSL certs for a Cloud SQL instance.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object that has the list of sslCerts resources if the api request
      was successful.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """
        sql_client = self.context['sql_client']
        sql_messages = self.context['sql_messages']
        resources = self.context['registry']

        util.ValidateInstanceName(args.instance)
        instance_ref = resources.Parse(args.instance,
                                       collection='sql.instances')

        result = sql_client.sslCerts.List(
            sql_messages.SqlSslCertsListRequest(
                project=instance_ref.project, instance=instance_ref.instance))
        return iter(result.items)
Example #3
0
  def Run(self, args):
    """Retrieves information about a backup.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object that has the backup run resource if the command ran
      successfully.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """
    sql_client = self.context['sql_client']
    resources = self.context['registry']

    util.ValidateInstanceName(args.instance)
    instance_ref = resources.Parse(args.instance, collection='sql.instances')

    instance = sql_client.instances.Get(instance_ref.Request())
    # At this point we support only one backup-config. So, just use that id.
    backup_config = instance.settings.backupConfiguration[0].id
    request = sqladmin_v1beta3.SqlBackupRunsGetRequest(
        project=instance_ref.project,
        instance=instance_ref.instance,
        backupConfiguration=backup_config,
        dueTime=args.due_time)
    return sql_client.backupRuns.Get(request)
Example #4
0
    def Run(self, args):
        """Retrieves information about a Cloud SQL instance operation.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object representing the operations resource if the api request was
      successful.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """
        sql_client = self.context['sql_client-v1beta3']
        resources = self.context['registry-v1beta3']

        util.ValidateInstanceName(args.instance)
        instance_ref = resources.Parse(args.instance,
                                       collection='sql.instances')

        operation_ref = resources.Parse(args.operation,
                                        collection='sql.operations',
                                        params={
                                            'project': instance_ref.project,
                                            'instance': instance_ref.instance
                                        })
        try:
            result = sql_client.operations.Get(operation_ref.Request())
            return result
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetErrorMessage(error))
Example #5
0
    def Run(self, args):
        """Retrieves information about a Cloud SQL instance.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object representing the instance resource if fetching the instance
      was successful.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """
        sql_client = self.context['sql_client']
        resources = self.context['registry']

        util.ValidateInstanceName(args.instance)
        instance_ref = resources.Parse(args.instance,
                                       collection='sql.instances')

        try:
            return sql_client.instances.Get(instance_ref.Request())
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetErrorMessage(error))
Example #6
0
  def Run(self, args):
    """Lists all instance operations that have been performed on an instance.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object that has the list of operation resources if the command ran
      successfully.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """
    sql_client = self.context['sql_client']
    sql_messages = self.context['sql_messages']
    resources = self.context['registry']

    util.ValidateInstanceName(args.instance)
    instance_ref = resources.Parse(args.instance, collection='sql.instances')

    try:
      return apitools_base.YieldFromList(
          sql_client.operations,
          sql_messages.SqlOperationsListRequest(
              project=instance_ref.project,
              instance=instance_ref.instance),
          args.limit)
    except apitools_base.HttpError as error:
      raise exceptions.HttpException(util.GetErrorMessage(error))
Example #7
0
    def Run(self, args):
        """Sets the password of the MySQL root user.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object representing the operations resource describing the
      setRootPassword operation if the setRootPassword was successful.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """
        sql_client = self.context['sql_client']
        sql_messages = self.context['sql_messages']
        resources = self.context['registry']

        util.ValidateInstanceName(args.instance)
        instance_ref = resources.Parse(args.instance,
                                       collection='sql.instances')

        try:
            if args.password_file:
                with open(args.password_file) as f:
                    password = f.readline()
            else:
                password = args.password

            result = sql_client.instances.SetRootPassword(
                sql_messages.SqlInstancesSetRootPasswordRequest(
                    project=instance_ref.project,
                    instance=instance_ref.instance,
                    instanceSetRootPasswordRequest=(
                        sql_messages.InstanceSetRootPasswordRequest(
                            setRootPasswordContext=(
                                sql_messages.SetRootPasswordContext(
                                    password=password))))))

            operation_ref = resources.Create(
                'sql.operations',
                operation=result.operation,
                project=instance_ref.project,
                instance=instance_ref.instance,
            )

            if args. async:
                return sql_client.operations.Get(operation_ref.Request())

            util.WaitForOperation(sql_client, operation_ref,
                                  'Setting Cloud SQL instance password')

            log.status.write('Set password for [{instance}].\n'.format(
                instance=instance_ref))

            return None
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetErrorMessage(error))
Example #8
0
    def Run(self, args):
        """Deletes an SSL certificate for a Cloud SQL instance.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object representing the operations resource describing the delete
      operation if the api request was successful.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """
        sql_client = self.context['sql_client']
        sql_messages = self.context['sql_messages']
        resources = self.context['registry']

        util.ValidateInstanceName(args.instance)
        instance_ref = resources.Parse(args.instance,
                                       collection='sql.instances')

        # TODO(user): figure out how to rectify the common_name and the
        # sha1fingerprint, so that things can work with the resource parser.
        try:

            cert_ref = util.GetCertRefFromName(sql_client, sql_messages,
                                               resources, instance_ref,
                                               args.common_name)
            if not cert_ref:
                raise exceptions.ToolException(
                    'no ssl cert named [{name}] for instance [{instance}]'.
                    format(name=args.common_name, instance=instance_ref))

            result = sql_client.sslCerts.Delete(
                sql_messages.SqlSslCertsDeleteRequest(
                    project=cert_ref.project,
                    instance=cert_ref.instance,
                    sha1Fingerprint=cert_ref.sha1Fingerprint))

            operation_ref = resources.Create(
                'sql.operations',
                operation=result.operation,
                project=cert_ref.project,
                instance=cert_ref.instance,
            )

            if args. async:
                return sql_client.operations.Get(operation_ref.Request())

            util.WaitForOperation(sql_client, operation_ref,
                                  'Deleting sslCert')

            log.DeletedResource(cert_ref)

        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetErrorMessage(error))
Example #9
0
    def Run(self, args):
        """Exports data from a Cloud SQL instance.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object representing the operations resource describing the export
      operation if the export was successful.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """
        sql_client = self.context['sql_client']
        sql_messages = self.context['sql_messages']
        resources = self.context['registry']

        util.ValidateInstanceName(args.instance)
        instance_ref = resources.Parse(args.instance,
                                       collection='sql.instances')

        export_request = sql_messages.SqlInstancesExportRequest(
            instance=instance_ref.instance,
            project=instance_ref.project,
            instancesExportRequest=sql_messages.InstancesExportRequest(
                exportContext=sql_messages.ExportContext(
                    uri=args.uri,
                    database=args.database or [],
                    table=args.table or [],
                ), ),
        )

        try:
            result = sql_client.instances.Export(export_request)

            operation_ref = resources.Create(
                'sql.operations',
                operation=result.operation,
                project=instance_ref.project,
                instance=instance_ref.instance,
            )

            if args. async:
                return sql_client.operations.Get(operation_ref.Request())

            util.WaitForOperation(sql_client, operation_ref,
                                  'Exporting Cloud SQL instance')

            log.status.write('Exported [{instance}] to [{bucket}].\n'.format(
                instance=instance_ref, bucket=args.uri))

            return None
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetErrorMessage(error))
Example #10
0
    def Run(self, args):
        """Restores a backup of a Cloud SQL instance.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object representing the operations resource describing the
      restoreBackup operation if the restoreBackup was successful.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """
        sql_client = self.context['sql_client-v1beta3']
        sql_messages = self.context['sql_messages-v1beta3']
        resources = self.context['registry-v1beta3']

        util.ValidateInstanceName(args.instance)
        instance_ref = resources.Parse(args.instance,
                                       collection='sql.instances')

        try:
            instance_resource = sql_client.instances.Get(
                instance_ref.Request())
            # At this point we support only one backup-config. So, just use that id.
            backup_config = instance_resource.settings.backupConfiguration[
                0].id

            result = sql_client.instances.RestoreBackup(
                sql_messages.SqlInstancesRestoreBackupRequest(
                    project=instance_ref.project,
                    instance=instance_ref.instance,
                    backupConfiguration=backup_config,
                    dueTime=args.due_time))

            operation_ref = resources.Create(
                'sql.operations',
                operation=result.operation,
                project=instance_ref.project,
                instance=instance_ref.instance,
            )

            if args. async:
                return sql_client.operations.Get(operation_ref.Request())

            util.WaitForOperation(sql_client, operation_ref,
                                  'Restoring Cloud SQL instance')

            log.status.write(
                'Restored [{instance}].\n'.format(instance=instance_ref))

            return None
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetErrorMessage(error))
Example #11
0
    def Run(self, args):
        """Imports data into a Cloud SQL instance from Google Cloud Storage.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object representing the operations resource describing the import
      operation if the import was successful.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """
        sql_client = self.context['sql_client']
        sql_messages = self.context['sql_messages']
        resources = self.context['registry']

        util.ValidateInstanceName(args.instance)
        instance_ref = resources.Parse(args.instance,
                                       collection='sql.instances')

        import_request = sql_messages.SqlInstancesImportRequest(
            instance=instance_ref.instance,
            project=instance_ref.project,
            instancesImportRequest=sql_messages.InstancesImportRequest(
                importContext=sql_messages.ImportContext(
                    uri=args.uri,
                    database=args.database,
                ), ),
        )

        result = sql_client.instances.Import(import_request)

        operation_ref = resources.Create(
            'sql.operations',
            operation=result.operation,
            project=instance_ref.project,
            instance=instance_ref.instance,
        )

        if args. async:
            return sql_client.operations.Get(operation_ref.Request())

        util.WaitForOperation(sql_client, operation_ref,
                              'Importing Cloud SQL instance')

        log.status.write('Imported [{instance}] from [{buckets}].\n'.format(
            instance=instance_ref, buckets=','.join(args.uri)))

        return None
Example #12
0
    def Run(self, args):
        """Deletes a Cloud SQL instance.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object representing the operations resource describing the delete
      operation if the delete was successful.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """
        sql_client = self.context['sql_client']
        sql_messages = self.context['sql_messages']
        resources = self.context['registry']
        operation_ref = None

        util.ValidateInstanceName(args.instance)
        instance_ref = resources.Parse(args.instance,
                                       collection='sql.instances')

        if not console_io.PromptContinue(
                'All of the instance data will be lost when the instance is deleted.'
        ):
            return None
        try:
            result = sql_client.instances.Delete(
                sql_messages.SqlInstancesDeleteRequest(
                    instance=instance_ref.instance,
                    project=instance_ref.project))

            operation_ref = resources.Create(
                'sql.operations',
                operation=result.operation,
                project=instance_ref.project,
                instance=instance_ref.instance,
            )

            unused_operation = sql_client.operations.Get(
                operation_ref.Request())

            log.DeletedResource(instance_ref)
            cache = remote_completion.RemoteCompletion()
            cache.DeleteFromCache(instance_ref.SelfLink())

        except apitools_base.HttpError:
            log.debug('operation : %s', str(operation_ref))
            raise
Example #13
0
    def Run(self, args):
        """Restarts a Cloud SQL instance.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object representing the operations resource describing the restart
      operation if the restart was successful.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """
        sql_client = self.context['sql_client-v1beta3']
        sql_messages = self.context['sql_messages-v1beta3']
        resources = self.context['registry-v1beta3']

        util.ValidateInstanceName(args.instance)
        instance_ref = resources.Parse(args.instance,
                                       collection='sql.instances')

        try:
            result = sql_client.instances.Restart(
                sql_messages.SqlInstancesRestartRequest(
                    project=instance_ref.project,
                    instance=instance_ref.instance))

            operation_ref = resources.Create(
                'sql.operations',
                operation=result.operation,
                project=instance_ref.project,
                instance=instance_ref.instance,
            )

            if args. async:
                return sql_client.operations.Get(operation_ref.Request())

            util.WaitForOperation(sql_client, operation_ref,
                                  'Restarting Cloud SQL instance')

            log.status.write(
                'Restarted [{resource}].\n'.format(resource=instance_ref))
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetErrorMessage(error))
    def Run(self, args):
        """Promotes Cloud SQL read replica to a stand-alone instance.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object representing the operations resource describing the
      promote-replica operation if the promote-replica was successful.
    Raises:
      HttpException: An HTTP error response was received while executing api
          request.
      ToolException: An error other than an HTTP error occured while executing
          the command.
    """
        sql_client = self.context['sql_client']
        sql_messages = self.context['sql_messages']
        resources = self.context['registry']

        util.ValidateInstanceName(args.replica)
        instance_ref = resources.Parse(args.replica,
                                       collection='sql.instances')

        try:
            result = sql_client.instances.PromoteReplica(
                sql_messages.SqlInstancesPromoteReplicaRequest(
                    project=instance_ref.project,
                    instance=instance_ref.instance))
            operation_ref = resources.Create(
                'sql.operations',
                operation=result.operation,
                project=instance_ref.project,
                instance=instance_ref.instance,
            )

            if args. async:
                return sql_client.operations.Get(operation_ref.Request())

            util.WaitForOperation(sql_client, operation_ref,
                                  'Promoting Cloud SQL replica')

            log.status.write(
                'Promoted [{instance}].\n'.format(instance=instance_ref))
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetErrorMessage(error))
    def Run(self, args):
        """Deletes all certificates and generates a new server SSL certificate.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object representing the operations resource describing the
      resetSslConfig operation if the reset was successful.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """
        sql_client = self.context['sql_client']
        sql_messages = self.context['sql_messages']
        resources = self.context['registry']

        util.ValidateInstanceName(args.instance)
        instance_ref = resources.Parse(args.instance,
                                       collection='sql.instances')

        result = sql_client.instances.ResetSslConfig(
            sql_messages.SqlInstancesResetSslConfigRequest(
                project=instance_ref.project, instance=instance_ref.instance))

        operation_ref = resources.Create(
            'sql.operations',
            operation=result.operation,
            project=instance_ref.project,
            instance=instance_ref.instance,
        )

        if args. async:
            return sql_client.operations.Get(operation_ref.Request())

        util.WaitForOperation(sql_client, operation_ref,
                              'Resetting SSL config')

        log.status.write('Reset SSL config for [{resource}].\n'.format(
            resource=instance_ref))
Example #16
0
    def Run(self, args):
        """Lists all backups associated with a given instance.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object that has the list of backup run resources if the command ran
      successfully.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """

        sql_client = self.context['sql_client-v1beta3']
        sql_messages = self.context['sql_messages-v1beta3']
        resources = self.context['registry-v1beta3']

        util.ValidateInstanceName(args.instance)
        instance_ref = resources.Parse(args.instance,
                                       collection='sql.instances')

        instance_resource = sql_client.instances.Get(instance_ref.Request())
        config_id = instance_resource.settings.backupConfiguration[0].id

        try:
            return apitools_base.YieldFromList(
                sql_client.backupRuns,
                sql_messages.SqlBackupRunsListRequest(
                    project=instance_ref.project,
                    instance=instance_ref.instance,
                    # At this point we support only one backup-config. So, we just use
                    # that id.
                    backupConfiguration=config_id),
                args.limit)
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetErrorMessage(error))
Example #17
0
    def Run(self, args):
        """Wait for a Cloud SQL instance operation.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Yields:
      Operations that were waited for.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """
        sql_client = self.context['sql_client']
        resources = self.context['registry']

        util.ValidateInstanceName(args.instance)
        instance_ref = resources.Parse(args.instance,
                                       collection='sql.instances')

        for op in args.operation:
            operation_ref = resources.Parse(op,
                                            collection='sql.operations',
                                            params={
                                                'project':
                                                instance_ref.project,
                                                'instance':
                                                instance_ref.instance
                                            })
            try:
                util.WaitForOperation(
                    sql_client, operation_ref,
                    'Waiting for [{operation}]'.format(
                        operation=operation_ref))
                yield sql_client.operations.Get(operation_ref.Request())
            except apitools_base.HttpError as error:
                raise exceptions.HttpException(util.GetErrorMessage(error))
Example #18
0
    def Run(self, args):
        """Creates an SSL certificate for a Cloud SQL instance.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object representing the operations resource describing the create
      operation if the create was successful.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """

        if os.path.exists(args.cert_file):
            raise exceptions.ToolException(
                'file [{path}] already exists'.format(path=args.cert_file))

        # First check if args.out_file is writeable. If not, abort and don't create
        # the useless cert.
        try:
            with files.OpenForWritingPrivate(args.cert_file) as cf:
                cf.write('placeholder\n')
        except OSError as e:
            raise exceptions.ToolException(
                'unable to write [{path}]: {error}'.format(path=args.cert_file,
                                                           error=str(e)))

        sql_client = self.context['sql_client']
        sql_messages = self.context['sql_messages']
        resources = self.context['registry']

        util.ValidateInstanceName(args.instance)
        instance_ref = resources.Parse(args.instance,
                                       collection='sql.instances')

        # TODO(user): figure out how to rectify the common_name and the
        # sha1fingerprint, so that things can work with the resource parser.

        result = sql_client.sslCerts.Insert(
            sql_messages.SqlSslCertsInsertRequest(
                project=instance_ref.project,
                instance=instance_ref.instance,
                sslCertsInsertRequest=sql_messages.SslCertsInsertRequest(
                    commonName=args.common_name)))

        private_key = result.clientCert.certPrivateKey

        with files.OpenForWritingPrivate(args.cert_file) as cf:
            cf.write(private_key)
            cf.write('\n')

        cert_ref = resources.Create(
            collection='sql.sslCerts',
            project=instance_ref.project,
            instance=instance_ref.instance,
            sha1Fingerprint=result.clientCert.certInfo.sha1Fingerprint)

        log.CreatedResource(cert_ref)
        return result
Example #19
0
    def Run(self, args):
        """Updates settings of a Cloud SQL instance using the patch api method.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object representing the operations resource describing the patch
      operation if the patch was successful.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """

        sql_client = self.context['sql_client']
        sql_messages = self.context['sql_messages']
        resources = self.context['registry']

        util.ValidateInstanceName(args.instance)
        instance_ref = resources.Parse(args.instance,
                                       collection='sql.instances')

        try:
            original_instance_resource = sql_client.instances.Get(
                instance_ref.Request())
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetErrorMessage(error))

        cleared_fields = []

        if args.clear_gae_apps:
            cleared_fields.append('settings.authorizedGaeApplications')
        if args.clear_authorized_networks:
            cleared_fields.append(
                'settings.ipConfiguration.authorizedNetworks')
        if args.clear_database_flags:
            cleared_fields.append('settings.databaseFlags')

        patch_instance = util.ConstructInstanceFromArgs(
            sql_messages, args, original=original_instance_resource)
        patch_instance.project = instance_ref.project
        patch_instance.instance = instance_ref.instance

        log.status.write(
            'The following message will be used for the patch API method.\n')
        log.status.write(
            apitools_base.MessageToJson(patch_instance,
                                        include_fields=cleared_fields) + '\n')

        self.PrintAndConfirmWarningMessage(args)

        with sql_client.IncludeFields(cleared_fields):
            result = sql_client.instances.Patch(patch_instance)

        operation_ref = resources.Create(
            'sql.operations',
            operation=result.operation,
            project=instance_ref.project,
            instance=instance_ref.instance,
        )

        if args. async:
            return sql_client.operations.Get(operation_ref.Request())

        util.WaitForOperation(sql_client, operation_ref,
                              'Patching Cloud SQL instance')

        log.UpdatedResource(instance_ref)

        if args.diff:
            try:
                changed_instance_resource = sql_client.instances.Get(
                    instance_ref.Request())
            except apitools_base.HttpError as error:
                raise exceptions.HttpException(util.GetErrorMessage(error))
            return resource_printer.ResourceDiff(original_instance_resource,
                                                 changed_instance_resource)

        return sql_client.instances.Get(instance_ref.Request())
Example #20
0
    def Run(self, args):
        """Clones a Cloud SQL instance.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object representing the operations resource describing the
      clone operation if the clone was successful.
    Raises:
      InvalidArgumentException: If one of the simulateneously required arguments
          is not specified.
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """
        sql_client = self.context['sql_client-v1beta3']
        sql_messages = self.context['sql_messages-v1beta3']
        resources = self.context['registry-v1beta3']

        util.ValidateInstanceName(args.source)
        util.ValidateInstanceName(args.destination)
        source_instance_ref = resources.Parse(args.source,
                                              collection='sql.instances')
        destination_instance_ref = resources.Parse(args.destination,
                                                   collection='sql.instances')

        if source_instance_ref.project != destination_instance_ref.project:
            raise exceptions.ToolException(
                'The source and the clone instance must belong to the same project:'
                ' "{src}" != "{dest}".'.format(
                    src=source_instance_ref.project,
                    dest=destination_instance_ref.project))

        request = sql_messages.SqlInstancesCloneRequest(
            project=source_instance_ref.project,
            instancesCloneRequest=sql_messages.
            InstancesCloneRequest(cloneContext=sql_messages.CloneContext(
                sourceInstanceName=source_instance_ref.instance,
                destinationInstanceName=destination_instance_ref.instance)))

        if args.bin_log_file_name and args.bin_log_position:
            request.cloneContext.binLogCoordinates = sql_messages.BinLogCoordinates(
                binLogFileName=args.bin_log_file_name,
                binLogPosition=args.bin_log_position)
        elif args.bin_log_file_name or args.bin_log_position:
            raise exceptions.ToolException(
                'Both --bin-log-file and --bin-log-file-name must be specified to'
                ' represent a valid binary log coordinate up to which the source is'
                ' cloned.')

        try:
            result = sql_client.instances.Clone(request)

            operation_ref = resources.Create(
                'sql.operations',
                operation=result.operation,
                project=destination_instance_ref.project,
                instance=destination_instance_ref.instance,
            )

            if args. async:
                return sql_client.operations.Get(operation_ref.Request())

            util.WaitForOperation(sql_client, operation_ref,
                                  'Cloning Cloud SQL instance')
            log.CreatedResource(destination_instance_ref)
            return sql_client.instances.Get(destination_instance_ref.Request())
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetErrorMessage(error))
Example #21
0
    def Run(self, args):
        """Creates a new Cloud SQL instance.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object representing the operations resource describing the create
      operation if the create was successful.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """

        # Added this temporarily for debugging SQL instance creation failures
        log.SetVerbosity(logging.DEBUG)
        sql_client = self.context['sql_client']
        sql_messages = self.context['sql_messages']
        resources = self.context['registry']

        util.ValidateInstanceName(args.instance)
        instance_ref = resources.Parse(args.instance,
                                       collection='sql.instances')

        instance_resource = util.ConstructInstanceFromArgs(sql_messages, args)

        if args.master_instance_name:
            replication = 'ASYNCHRONOUS'
            activation_policy = 'ALWAYS'
        else:
            replication = 'SYNCHRONOUS'
            activation_policy = 'ON_DEMAND'
        if not args.replication:
            instance_resource.settings.replicationType = replication
        if not args.activation_policy:
            instance_resource.settings.activationPolicy = activation_policy

        instance_resource.project = instance_ref.project
        instance_resource.instance = instance_ref.instance
        operation_ref = None

        if args.pricing_plan == 'PACKAGE':
            if not console_io.PromptContinue(
                    'Charges will begin accruing immediately. Really create Cloud '
                    'SQL instance?'):
                raise exceptions.ToolException('canceled by the user.')

        try:
            result = sql_client.instances.Insert(instance_resource)

            operation_ref = resources.Create(
                'sql.operations',
                operation=result.operation,
                project=instance_ref.project,
                instance=instance_ref.instance,
            )

            if args. async:
                return sql_client.operations.Get(operation_ref.Request())

            util.WaitForOperation(sql_client, operation_ref,
                                  'Creating Cloud SQL instance')

            log.CreatedResource(instance_ref)

            rsource = sql_client.instances.Get(instance_ref.Request())
            cache = remote_completion.RemoteCompletion()
            cache.AddToCache(instance_ref.SelfLink())
            return rsource
        except apitools_base.HttpError:
            log.debug('operation : %s', str(operation_ref))
            raise