Exemple #1
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

        validate.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.name,
                project=instance_ref.project,
                instance=instance_ref.instance,
            )

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

            operations.OperationsV1Beta4.WaitForOperation(
                sql_client, operation_ref, 'Deleting Cloud SQL instance')

            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
Exemple #2
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']

        validate.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.

        cert_ref = cert.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())

        operations.OperationsV1Beta3.WaitForOperation(sql_client,
                                                      operation_ref,
                                                      'Deleting sslCert')

        log.DeletedResource(cert_ref)
Exemple #3
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.
    """

    client = api_util.SqlClient(api_util.API_VERSION_DEFAULT)
    sql_client = client.sql_client
    sql_messages = client.sql_messages

    validate.ValidateInstanceName(args.restore_instance)
    instance_ref = client.resource_parser.Parse(
        args.restore_instance,
        params={'project': properties.VALUES.core.project.GetOrFail},
        collection='sql.instances')
    if not console_io.PromptContinue(
        'All current data on the instance will be lost when the backup is '
        'restored.'):
      return None
    if not args.backup_instance:
      args.backup_instance = args.restore_instance

    result_operation = sql_client.instances.RestoreBackup(
        sql_messages.SqlInstancesRestoreBackupRequest(
            project=instance_ref.project,
            instance=instance_ref.instance,
            instancesRestoreBackupRequest=(
                sql_messages.InstancesRestoreBackupRequest(
                    restoreBackupContext=sql_messages.RestoreBackupContext(
                        backupRunId=args.backup_id,
                        instanceId=args.backup_instance,)))))

    operation_ref = client.resource_parser.Create(
        'sql.operations',
        operation=result_operation.name,
        project=instance_ref.project)

    if args.async:
      return sql_client.operations.Get(
          sql_messages.SqlOperationsGetRequest(
              project=operation_ref.project,
              operation=operation_ref.operation))

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

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

    return None
Exemple #4
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.
    """
        client = api_util.SqlClient(api_util.API_VERSION_FALLBACK)
        sql_client = client.sql_client
        sql_messages = client.sql_messages

        validate.ValidateInstanceName(args.instance)
        instance_ref = client.resource_parser.Parse(args.instance,
                                                    collection='sql.instances')

        console_io.PromptContinue(
            message=
            'The instance will shut down and start up again immediately if '
            'its activation policy is "always." If "on demand," the instance will '
            'start up again when a new connection request is made.',
            default=True,
            cancel_on_no=True)

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

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

        if args. async:
            return sql_client.operations.Get(
                sql_messages.SqlOperationsGetRequest(
                    project=operation_ref.project,
                    instance=operation_ref.instance,
                    operation=operation_ref.operation))

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

        log.status.write(
            'Restarted [{resource}].\n'.format(resource=instance_ref))
Exemple #5
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']

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

        # TODO(svalentin): support CSV import
        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,
                    fileType='SQL',
                ), ),
        )

        result_operation = sql_client.instances.Import(import_request)

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

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

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

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

        return None
Exemple #6
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']
        sql_messages = self.context['sql_messages']
        resources = self.context['registry']

        validate.ValidateInstanceName(args.restore_instance)
        instance_ref = resources.Parse(args.restore_instance,
                                       collection='sql.instances')

        if not args.backup_instance:
            args.backup_instance = args.restore_instance

        result_operation = sql_client.instances.RestoreBackup(
            sql_messages.SqlInstancesRestoreBackupRequest(
                project=instance_ref.project,
                instance=instance_ref.instance,
                instancesRestoreBackupRequest=(
                    sql_messages.InstancesRestoreBackupRequest(
                        restoreBackupContext=sql_messages.RestoreBackupContext(
                            backupRunId=args.backup_id,
                            instanceId=args.backup_instance,
                        )))))

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

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

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

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

        return None
Exemple #7
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.
    """

        client = api_util.SqlClient(api_util.API_VERSION_DEFAULT)
        sql_client = client.sql_client
        sql_messages = client.sql_messages

        validate.ValidateInstanceName(args.instance)
        instance_ref = client.resource_parser.Parse(
            args.instance,
            params={'project': properties.VALUES.core.project.GetOrFail},
            collection='sql.instances')

        result_operation = sql_client.backupRuns.Insert(
            sql_messages.SqlBackupRunsInsertRequest(
                project=instance_ref.project,
                instance=instance_ref.instance,
                backupRun=sql_messages.BackupRun(
                    description=args.description,
                    instance=instance_ref.instance,
                    kind='sql#backupRun')))

        operation_ref = client.resource_parser.Create(
            'sql.operations',
            operation=result_operation.name,
            project=instance_ref.project)

        if args. async:
            return sql_client.operations.Get(
                sql_messages.SqlOperationsGetRequest(
                    project=operation_ref.project,
                    operation=operation_ref.operation))

        operations.OperationsV1Beta4.WaitForOperation(
            sql_client, operation_ref, 'Backing up Cloud SQL instance')

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

        return None
Exemple #8
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.
    """
    client = api_util.SqlClient(api_util.API_VERSION_DEFAULT)
    sql_client = client.sql_client
    sql_messages = client.sql_messages
    operation_ref = None

    validate.ValidateInstanceName(args.instance)
    instance_ref = client.resource_parser.Parse(
        args.instance,
        params={'project': properties.VALUES.core.project.GetOrFail},
        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 = client.resource_parser.Create(
          'sql.operations', operation=result.name, project=instance_ref.project)

      if args.async:
        return sql_client.operations.Get(
            sql_messages.SqlOperationsGetRequest(
                project=operation_ref.project,
                operation=operation_ref.operation))

      operations.OperationsV1Beta4.WaitForOperation(
          sql_client, operation_ref, 'Deleting Cloud SQL instance')

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

    except exceptions.HttpError:
      log.debug('operation : %s', str(operation_ref))
      raise
Exemple #9
0
    def Run(self, args):
        """Deletes 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 delete
      operation if the api request was successful.
    """

        client = api_util.SqlClient(api_util.API_VERSION_DEFAULT)
        sql_client = client.sql_client
        sql_messages = client.sql_messages

        operation_ref = None

        validate.ValidateInstanceName(args.instance)
        instance_ref = client.resource_parser.Parse(
            args.instance,
            params={'project': properties.VALUES.core.project.GetOrFail},
            collection='sql.instances')

        # TODO(b/36051078): validate on FE that a backup run id is valid.

        console_io.PromptContinue(
            message='The backup will be deleted. You cannot undo this action.',
            default=True,
            cancel_on_no=True)

        result = sql_client.backupRuns.Delete(
            sql_messages.SqlBackupRunsDeleteRequest(
                project=instance_ref.project,
                instance=instance_ref.instance,
                id=args.id))

        operation_ref = client.resource_parser.Create(
            'sql.operations',
            operation=result.name,
            project=instance_ref.project)

        if args. async:
            # Don't wait for the running operation to complete when async is used.
            return sql_client.operations.Get(
                sql_messages.SqlOperationsGetRequest(
                    project=operation_ref.project,
                    operation=operation_ref.operation))

        operations.OperationsV1Beta4.WaitForOperation(sql_client,
                                                      operation_ref,
                                                      'Deleting backup run')

        log.DeletedResource(args.id, 'backup run')
    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.
    """
        client = api_util.SqlClient(api_util.API_VERSION_FALLBACK)
        sql_client = client.sql_client
        sql_messages = client.sql_messages

        validate.ValidateInstanceName(args.replica)
        instance_ref = client.resource_parser.Parse(
            args.replica,
            params={'project': properties.VALUES.core.project.GetOrFail},
            collection='sql.instances')

        console_io.PromptContinue(
            message='Once the read replica has been promoted to a stand-alone '
            'instance it cannot be converted back.',
            default=True,
            cancel_on_no=True)

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

        if args. async:
            return sql_client.operations.Get(
                sql_messages.SqlOperationsGetRequest(
                    project=operation_ref.project,
                    instance=operation_ref.instance,
                    operation=operation_ref.operation))

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

        log.status.write(
            'Promoted [{instance}].\n'.format(instance=instance_ref))
    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.
    """
        client = api_util.SqlClient(api_util.API_VERSION_FALLBACK)
        sql_client = client.sql_client
        sql_messages = client.sql_messages

        validate.ValidateInstanceName(args.instance)
        instance_ref = client.resource_parser.Parse(args.instance,
                                                    collection='sql.instances')

        console_io.PromptContinue(
            message='Resetting your SSL configuration will delete all client '
            'certificates and generate a new server certificate.',
            default=True,
            cancel_on_no=True)

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

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

        if args. async:
            return sql_client.operations.Get(
                sql_messages.SqlOperationsGetRequest(
                    project=operation_ref.project,
                    instance=operation_ref.instance,
                    operation=operation_ref.operation))

        operations.OperationsV1Beta3.WaitForOperation(sql_client,
                                                      operation_ref,
                                                      'Resetting SSL config')

        log.status.write('Reset SSL config for [{resource}].\n'.format(
            resource=instance_ref))
def RunExportCommand(args, client, export_context):
    """Exports data from a Cloud SQL instance.

  Args:
    args: argparse.Namespace, The arguments that this command was invoked with.
    client: SqlClient instance, with sql_client and sql_messages props, for use
        in generating messages and making API calls.
    export_context: ExportContext; format-specific export metadata.

  Returns:
    A dict representing the export operation resource, if '--async' is used,
    or else None.

  Raises:
    HttpException: An HTTP error response was received while executing API
        request.
    ToolException: An error other than HTTP error occurred while executing the
        command.
  """
    sql_client = client.sql_client
    sql_messages = client.sql_messages

    validate.ValidateInstanceName(args.instance)
    instance_ref = client.resource_parser.Parse(
        args.instance,
        params={'project': properties.VALUES.core.project.GetOrFail},
        collection='sql.instances')

    export_request = sql_messages.SqlInstancesExportRequest(
        instance=instance_ref.instance,
        project=instance_ref.project,
        instancesExportRequest=sql_messages.InstancesExportRequest(
            exportContext=export_context))

    result_operation = sql_client.instances.Export(export_request)

    operation_ref = client.resource_parser.Create(
        'sql.operations',
        operation=result_operation.name,
        project=instance_ref.project)

    if args.async_:
        return sql_client.operations.Get(
            sql_messages.SqlOperationsGetRequest(
                project=operation_ref.project,
                operation=operation_ref.operation))

    operations.OperationsV1Beta4.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
Exemple #13
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.
    """
    client = api_util.SqlClient(api_util.API_VERSION_DEFAULT)
    sql_client = client.sql_client
    sql_messages = client.sql_messages

    validate.ValidateInstanceName(args.instance)
    instance_ref = client.resource_parser.Parse(
        args.instance,
        params={'project': properties.VALUES.core.project.GetOrFail},
        collection='sql.instances')

    # TODO(b/36051079): add support for CSV exporting.
    export_request = sql_messages.SqlInstancesExportRequest(
        instance=instance_ref.instance,
        project=instance_ref.project,
        instancesExportRequest=sql_messages.InstancesExportRequest(
            exportContext=sql_messages.ExportContext(
                uri=args.uri,
                databases=args.database or [],
                fileType='SQL',
                sqlExportOptions=(
                    sql_messages.ExportContext.SqlExportOptionsValue(
                        tables=args.table or [],)),),),)

    result_operation = sql_client.instances.Export(export_request)

    operation_ref = client.resource_parser.Create(
        'sql.operations',
        operation=result_operation.name,
        project=instance_ref.project)

    if args.async:
      return sql_client.operations.Get(
          sql_messages.SqlOperationsGetRequest(
              project=operation_ref.project, operation=operation_ref.operation))

    operations.OperationsV1Beta4.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
    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']
        sql_messages = self.context['sql_messages']
        resources = self.context['registry']

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

        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())

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

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

        return None
  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.
    """
    validate.ValidateInstanceName(args.instance)

    return self._GetById(args.id, args)
    def Run(self, args):
        """Deletes 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 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']
        operation_ref = None

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

        # TODO(b/36051078): validate on FE that a backup run id is valid.

        console_io.PromptContinue(
            message='The backup will be deleted. You cannot undo this action.',
            default=True,
            cancel_on_no=True)

        result = sql_client.backupRuns.Delete(
            sql_messages.SqlBackupRunsDeleteRequest(
                project=instance_ref.project,
                instance=instance_ref.instance,
                id=args.id))

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

        operations.OperationsV1Beta4.WaitForOperation(sql_client,
                                                      operation_ref,
                                                      'Deleting backup run')

        log.DeletedResource(args.id, 'backup run')
Exemple #17
0
    def Run(self, args):
        """Calls the failover api method.

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

    Returns:
      A dict object representing the operations resource describing the failover
      operation if the failover 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']

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

        instance = sql_client.instances.Get(instance_ref.Request())

        request = sql_messages.SqlInstancesFailoverRequest(
            project=instance_ref.project,
            instance=instance_ref.instance,
            instancesFailoverRequest=sql_messages.InstancesFailoverRequest(
                failoverContext=sql_messages.FailoverContext(
                    kind='sql#failoverContext',
                    settingsVersion=instance.settings.settingsVersion)))
        result_operation = sql_client.instances.Failover(request)

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

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

        operations.OperationsV1Beta4.WaitForOperation(
            sql_client, operation_ref, 'Failing over Cloud SQL instance')

        return None
Exemple #18
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.
    """
        client = api_util.SqlClient(api_util.API_VERSION_DEFAULT)
        sql_client = client.sql_client
        sql_messages = client.sql_messages

        validate.ValidateInstanceName(args.instance)
        instance_ref = client.resource_parser.Parse(
            args.instance,
            params={'project': properties.VALUES.core.project.GetOrFail},
            collection='sql.instances')

        console_io.PromptContinue(
            message=
            'The instance will shut down and start up again immediately if '
            'its activation policy is "always." If "on demand," the instance will '
            'start up again when a new connection request is made.',
            default=True,
            cancel_on_no=True)

        result_operation = sql_client.instances.Restart(
            sql_messages.SqlInstancesRestartRequest(
                project=instance_ref.project, instance=instance_ref.instance))

        operation_ref = client.resource_parser.Create(
            'sql.operations',
            operation=result_operation.name,
            project=instance_ref.project)

        if args. async:
            return sql_client.operations.Get(
                sql_messages.SqlOperationsGetRequest(
                    project=operation_ref.project,
                    operation=operation_ref.operation))

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

        log.status.write(
            'Restarted [{resource}].\n'.format(resource=instance_ref))
Exemple #19
0
    def Run(self, args):
        """Roll back to the previous server CA cert for a Cloud SQL instance.

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

    Returns:
      The Server CA Cert that was rolled back to, if the operation was
      successful.
    """

        client = api_util.SqlClient(api_util.API_VERSION_DEFAULT)
        sql_client = client.sql_client
        sql_messages = client.sql_messages

        validate.ValidateInstanceName(args.instance)
        instance_ref = client.resource_parser.Parse(
            args.instance,
            params={'project': properties.VALUES.core.project.GetOrFail},
            collection='sql.instances')

        previous_server_ca = server_ca_certs.GetPreviousServerCa(
            sql_client, sql_messages, instance_ref)

        if not previous_server_ca:
            raise exceptions.ResourceNotFoundError(
                'No previous Server CA Certificate exists.')

        result_operation = sql_client.instances.RotateServerCa(
            sql_messages.SqlInstancesRotateServerCaRequest(
                project=instance_ref.project,
                instance=instance_ref.instance,
                instancesRotateServerCaRequest=sql_messages.
                InstancesRotateServerCaRequest(
                    rotateServerCaContext=sql_messages.RotateServerCaContext(
                        nextVersion=previous_server_ca.sha1Fingerprint))))

        operation_ref = client.resource_parser.Create(
            'sql.operations',
            operation=result_operation.name,
            project=instance_ref.project)

        operations.OperationsV1Beta4.WaitForOperation(
            sql_client, operation_ref,
            'Rolling back to previous Server CA Certificate')

        return previous_server_ca
    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.
    """
        client = api_util.SqlClient(api_util.API_VERSION_DEFAULT)
        sql_client = client.sql_client
        sql_messages = client.sql_messages

        validate.ValidateInstanceName(args.instance)
        instance_ref = client.resource_parser.Parse(
            args.instance,
            params={'project': properties.VALUES.core.project.GetOrFail},
            collection='sql.instances')

        console_io.PromptContinue(
            message='Resetting your SSL configuration will delete all client '
            'certificates and generate a new server certificate.',
            default=True,
            cancel_on_no=True)

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

        operation_ref = client.resource_parser.Create(
            'sql.operations',
            operation=result_operation.name,
            project=instance_ref.project)

        if args. async:
            return sql_client.operations.Get(
                sql_messages.SqlOperationsGetRequest(
                    project=operation_ref.project,
                    operation=operation_ref.operation))

        operations.OperationsV1Beta4.WaitForOperation(sql_client,
                                                      operation_ref,
                                                      'Resetting SSL config')

        log.status.write('Reset SSL config for [{resource}].\n'.format(
            resource=instance_ref))
    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']

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

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

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

        if args. async:
            return sql_client.operations.Get(
                sql_messages.SqlOperationsGetRequest(
                    project=operation_ref.project,
                    instance=operation_ref.instance,
                    operation=operation_ref.operation))

        operations.OperationsV1Beta4.WaitForOperation(sql_client,
                                                      operation_ref,
                                                      'Resetting SSL config')

        log.status.write('Reset SSL config for [{resource}].\n'.format(
            resource=instance_ref))
Exemple #22
0
  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']

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

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

    if args.async:
      return sql_client.operations.Get(
          sql_messages.SqlOperationsGetRequest(
              project=operation_ref.project,
              instance=operation_ref.instance,
              operation=operation_ref.operation))

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

    log.status.write(
        'Promoted [{instance}].\n'.format(instance=instance_ref))
    def Run(self, args):
        """Displays configuration and metadata about a Cloud SQL instance.

    Information such as instance name, IP address, region, the CA certificate
    and configuration settings will be displayed.

    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.
    ResourceNotFoundError: The SQL instance was not found.
    """
        client = api_util.SqlClient(api_util.API_VERSION_DEFAULT)
        sql_client = client.sql_client
        sql_messages = client.sql_messages

        validate.ValidateInstanceName(args.instance)
        instance_ref = client.resource_parser.Parse(
            args.instance,
            params={'project': properties.VALUES.core.project.GetOrFail},
            collection='sql.instances')

        try:
            instance = sql_client.instances.Get(
                sql_messages.SqlInstancesGetRequest(
                    project=instance_ref.project,
                    instance=instance_ref.instance))
            instance.state = instance_api_util.GetInstanceState(instance)
            # TODO(b/122660263): Remove when V1 instances are no longer supported.
            if instance_api_util.IsInstanceV1(instance):
                instance_command_util.ShowV1DeprecationWarning()
            return instance
        except apitools_exceptions.HttpError as error:
            if error.status_code == six.moves.http_client.FORBIDDEN:
                raise exceptions.ResourceNotFoundError(
                    'There was no instance found at {} or you are not authorized to '
                    'access it.'.format(instance_ref.RelativeName()))
            raise calliope_exceptions.HttpException(error)
Exemple #24
0
    def Run(self, args):
        """Create a server CA cert for a Cloud SQL instance.

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

    Returns:
      The upcoming Server CA Cert, if the operation was successful.
    """

        client = api_util.SqlClient(api_util.API_VERSION_DEFAULT)
        sql_client = client.sql_client
        sql_messages = client.sql_messages

        validate.ValidateInstanceName(args.instance)
        instance_ref = client.resource_parser.Parse(
            args.instance,
            params={'project': properties.VALUES.core.project.GetOrFail},
            collection='sql.instances')

        result_operation = sql_client.instances.AddServerCa(
            sql_messages.SqlInstancesAddServerCaRequest(
                project=instance_ref.project, instance=instance_ref.instance))

        operation_ref = client.resource_parser.Create(
            'sql.operations',
            operation=result_operation.name,
            project=instance_ref.project)

        operations.OperationsV1Beta4.WaitForOperation(
            sql_client, operation_ref, 'Creating Server CA Certificate')

        next_server_ca = server_ca_certs.GetNextServerCa(
            sql_client, sql_messages, instance_ref)

        cert_ref = client.resource_parser.Create(
            collection='sql.sslCerts',
            project=instance_ref.project,
            instance=instance_ref.instance,
            sha1Fingerprint=next_server_ca.sha1Fingerprint)

        log.CreatedResource(cert_ref)
        return next_server_ca
Exemple #25
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.
    """
    validate.ValidateInstanceName(args.instance)

    return self._GetById(args.id, args)
    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.
    """
        validate.ValidateInstanceName(args.instance)
        console_io.PromptContinue(
            message=('All current data on the instance will be lost when the '
                     'backup is restored'),
            default=True,
            cancel_on_no=True)

        return self._HandleBackupId(args)
Exemple #27
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.
    """

        client = api_util.SqlClient(api_util.API_VERSION_FALLBACK)
        sql_client = client.sql_client
        sql_messages = client.sql_messages

        validate.ValidateInstanceName(args.instance)
        instance_ref = client.resource_parser.Parse(
            args.instance,
            params={'project': properties.VALUES.core.project.GetOrFail},
            collection='sql.instances')

        instance_resource = sql_client.instances.Get(
            sql_messages.SqlInstancesGetRequest(
                project=instance_ref.project, instance=instance_ref.instance))
        config_id = instance_resource.settings.backupConfiguration[0].id

        return list_pager.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),
            limit=args.limit)
    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']
        sql_messages = self.context['sql_messages']
        resources = self.context['registry']

        validate.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
                                            })

            operations.OperationsV1Beta3.WaitForOperation(
                sql_client, operation_ref,
                'Waiting for [{operation}]'.format(operation=operation_ref))
            yield sql_client.operations.Get(
                sql_messages.SqlOperationsGetRequest(
                    project=operation_ref.project,
                    instance=operation_ref.instance,
                    operation=operation_ref.operation))
Exemple #29
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']
    sql_messages = self.context['sql_messages']
    resources = self.context['registry']

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

    instance_resource = sql_client.instances.Get(
        sql_messages.SqlInstancesGetRequest(
            project=instance_ref.project,
            instance=instance_ref.instance))
    config_id = instance_resource.settings.backupConfiguration[0].id

    return list_pager.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),
        limit=args.limit)
Exemple #30
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.
    """
    client = api_util.SqlClient(api_util.API_VERSION_FALLBACK)
    sql_client = client.sql_client
    sql_messages = client.sql_messages

    validate.ValidateInstanceName(args.instance)
    instance_ref = client.resource_parser.Parse(
        args.instance,
        params={'project': properties.VALUES.core.project.GetOrFail},
        collection='sql.instances')

    for op in args.operation:
      operation_ref = client.resource_parser.Parse(
          op, collection='sql.operations',
          params={'project': instance_ref.project,
                  'instance': instance_ref.instance})

      operations.OperationsV1Beta3.WaitForOperation(
          sql_client, operation_ref,
          'Waiting for [{operation}]'.format(operation=operation_ref))
      yield sql_client.operations.Get(
          sql_messages.SqlOperationsGetRequest(
              project=operation_ref.project,
              instance=operation_ref.instance,
              operation=operation_ref.operation))