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. """ 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') return list_pager.YieldFromList( sql_client.operations, sql_messages.SqlOperationsListRequest( project=instance_ref.project, instance=instance_ref.instance), limit=args.limit)
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. """ client = api_util.SqlClient(api_util.API_VERSION_FALLBACK) sql_client = client.sql_client sql_messages = client.sql_messages instance_ref = client.resource_parser.Parse( args.instance, collection='sql.instances') if args.password_file: with open(args.password_file) as f: password = f.readline().rstrip('\n') 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 = 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, 'Setting Cloud SQL instance password') log.status.write( 'Set password for [{instance}].\n'.format(instance=instance_ref)) return None
def Run(self, args): """Runs the command to import into the Cloud SQL instance.""" if args.prompt_for_pvk_password: args.pvk_password = getpass.getpass('Private Key Password: ') client = api_util.SqlClient(api_util.API_VERSION_DEFAULT) return import_util.RunBakImportCommand(args, client)
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_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') return list_pager.YieldFromList( sql_client.backupRuns, sql_messages.SqlBackupRunsListRequest( project=instance_ref.project, instance=instance_ref.instance), limit=args.limit)
def GetDatabaseInstances(): """Gets SQL instances in a given project. Modifies current state of an individual instance to 'STOPPED' if activationPolicy is 'NEVER'. Returns: List of yielded sql_messages.DatabaseInstance instances. """ client = api_util.SqlClient(api_util.API_VERSION_DEFAULT) sql_client = client.sql_client sql_messages = client.sql_messages project_id = properties.VALUES.core.project.Get(required=True) yielded = list_pager.YieldFromList( sql_client.instances, sql_messages.SqlInstancesListRequest(project=project_id)) def YieldInstancesWithAModifiedState(): for result in yielded: # TODO(b/63139112): Investigate impact of instances without settings. if result.settings and result.settings.activationPolicy == 'NEVER': result.state = 'STOPPED' yield result return YieldInstancesWithAModifiedState()
def Run(self, args): """Lists databases 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 database resources 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 validate.ValidateInstanceName(args.instance) instance_ref = client.resource_parser.Parse( args.instance, params={'project': properties.VALUES.core.project.GetOrFail}, collection='sql.instances') result = sql_client.databases.List( sql_messages.SqlDatabasesListRequest( project=instance_ref.project, instance=instance_ref.instance)) return iter(result.items)
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. """ 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 = sql_client.sslCerts.List( sql_messages.SqlSslCertsListRequest( project=instance_ref.project, instance=instance_ref.instance)) return iter(result.items)
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.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
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. """ client = api_util.SqlClient(api_util.API_VERSION_DEFAULT) sql_client = client.sql_client sql_messages = client.sql_messages operation_ref = client.resource_parser.Parse( args.operation, collection='sql.operations', params={'project': properties.VALUES.core.project.GetOrFail}) return sql_client.operations.Get( sql_messages.SqlOperationsGetRequest( project=operation_ref.project, operation=operation_ref.operation))
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_DEFAULT) sql_client = client.sql_client sql_messages = client.sql_messages for op in args.operation: operation_ref = client.resource_parser.Parse( op, collection='sql.operations', params={'project': properties.VALUES.core.project.GetOrFail}) operations.OperationsV1Beta4.WaitForOperation( sql_client, operation_ref, 'Waiting for [{operation}]'.format(operation=operation_ref)) yield sql_client.operations.Get( sql_messages.SqlOperationsGetRequest( project=operation_ref.project, operation=operation_ref.operation))
def _GetByDatetime(self, datetime, args): # Backwards compatibility during deprecation period. # If user passes DUE_TIME instead of ID, use v1beta3 API. client = api_util.SqlClient(api_util.API_VERSION_FALLBACK) sql_client = client.sql_client sql_messages = client.sql_messages log.warning( 'Starting on 2017-06-30, DUE_TIME will no longer be valid: Use ' 'the ID argument instead to retrieve a backup. You can start ' 'using ID now.') instance_ref = client.resource_parser.Parse( args.instance, params={'project': properties.VALUES.core.project.GetOrFail}, collection='sql.instances') instance = sql_client.instances.Get( sql_messages.SqlInstancesGetRequest( project=instance_ref.project, instance=instance_ref.instance)) backup_config = instance.settings.backupConfiguration[0].id request = sql_messages.SqlBackupRunsGetRequest( project=instance_ref.project, instance=instance_ref.instance, backupConfiguration=backup_config, dueTime=times.FormatDateTime(datetime, tzinfo=times.UTC)) return sql_client.backupRuns.Get(request)
def Run(self, args): """Displays configuration and metadata about a Cloud SQL database. Information such as database name, charset, and collation will be displayed. Args: args: argparse.Namespace, The arguments that this command was invoked with. Returns: A dict object representing the database resource if fetching the database 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') database_request = sql_messages.SqlDatabasesGetRequest( project=instance_ref.project, instance=instance_ref.instance, database=args.database) return sql_client.databases.Get(database_request)
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. """ 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') 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 [], ), ), ) result = sql_client.instances.Export(export_request) 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, '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): """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. 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') return sql_client.instances.Get( sql_messages.SqlInstancesGetRequest( project=instance_ref.project, instance=instance_ref.instance))
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. """ client = api_util.SqlClient(api_util.API_VERSION_DEFAULT) sql_client = client.sql_client sql_messages = client.sql_messages for op in args.operation: operation_ref = client.resource_parser.Parse( op, collection='sql.operations', params={'project': properties.VALUES.core.project.GetOrFail}) operations.OperationsV1Beta4.WaitForOperation( sql_client, operation_ref, 'Waiting for [{operation}]'.format(operation=operation_ref), max_wait_seconds=args.timeout) yield sql_client.operations.Get( sql_messages.SqlOperationsGetRequest( project=operation_ref.project, operation=operation_ref.operation))
def Run(self, args): """List customizable flags for Google Cloud SQL instances. Args: args: argparse.Namespace, The arguments that this command was invoked with. Returns: A dict object that has the list of flag 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_DEFAULT) sql_client = client.sql_client sql_messages = client.sql_messages result = sql_client.flags.List( sql_messages.SqlFlagsListRequest( databaseVersion=args.database_version)) return iter(result.items)
def Run(self, args): """Creates a database 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. """ 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') new_database = sql_messages.Database( project=instance_ref.project, instance=instance_ref.instance, name=args.database, charset=args.charset, collation=args.collation) # TODO(b/36052521): Move this API call logic per b/35386183. result_operation = sql_client.databases.Insert(new_database) operation_ref = client.resource_parser.Create( 'sql.operations', operation=result_operation.name, project=instance_ref.project) if args.async: result = sql_client.operations.Get( sql_messages.SqlOperationsGetRequest( project=operation_ref.project, operation=operation_ref.operation)) else: try: operations.OperationsV1Beta4.WaitForOperation( sql_client, operation_ref, 'Creating Cloud SQL database') # TODO(b/36051979): Refactor when b/35156765 is resolved. except errors.OperationError: log.Print('Database creation failed. Check if a database named {0} ' 'already exists.'.format(args.database)) return result = new_database log.CreatedResource(args.database, kind='database', async=args.async)
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. """ 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='Data from {0} will be imported to {1}.'.format( args.uri, args.instance), default=True, cancel_on_no=True) # TODO(b/36056454): 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 = 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, 'Importing Cloud SQL instance') log.status.write('Imported [{instance}] from [{bucket}].\n'.format( instance=instance_ref, bucket=args.uri)) return None
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. """ client = api_util.SqlClient(api_util.API_VERSION_DEFAULT) sql_client = client.sql_client sql_messages = client.sql_messages instance_ref = client.resource_parser.Parse( args.instance, params={'project': properties.VALUES.core.project.GetOrFail}, collection='sql.instances') if args.password_file: with open(args.password_file) as f: password = f.readline().rstrip('\n') else: password = args.password operation_ref = None result_operation = sql_client.users.Update( sql_messages.SqlUsersUpdateRequest( project=instance_ref.project, instance=instance_ref.Name(), name='root', host='%', user=sql_messages.User( project=instance_ref.project, instance=instance_ref.Name(), name='root', host='%', password=password))) 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, 'Updating Cloud SQL user') log.status.write( 'Set password for [{instance}].\n'.format(instance=instance_ref)) return None
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, instance=operation_ref.instance, 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
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 occurred 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') # 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): """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. """ 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='Failover will be initiated. Existing connections to the ' 'master instance will break and no new connection can be established ' 'during the failover.', default=True, cancel_on_no=True) instance = sql_client.instances.Get( sql_messages.SqlInstancesGetRequest( project=instance_ref.project, instance=instance_ref.instance)) 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 = 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, instance=operation_ref.instance, operation=operation_ref.operation)) operations.OperationsV1Beta4.WaitForOperation( sql_client, operation_ref, 'Failing over Cloud SQL instance') 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. """ 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') # Check if instance has customer-managed key; show warning if so. try: instance_resource = sql_client.instances.Get( sql_messages.SqlInstancesGetRequest( project=instance_ref.project, instance=instance_ref.instance)) if instance_resource.diskEncryptionConfiguration: command_util.ShowCmekWarning('backup', 'this instance') except apitools_exceptions.HttpError: # This is for informational purposes, so don't throw an error if failure. pass 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
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. """ client = api_util.SqlClient(api_util.API_VERSION_DEFAULT) sql_client = client.sql_client sql_messages = client.sql_messages source_instance_ref, destination_instance_ref = ( self._GetInstanceRefsFromArgs(args, client)) request = sql_messages.SqlInstancesCloneRequest( project=source_instance_ref.project, instance=source_instance_ref.instance, instancesCloneRequest=sql_messages.InstancesCloneRequest( cloneContext=sql_messages.CloneContext( destinationInstanceName=destination_instance_ref.instance))) self._UpdateRequestFromArgs(request, args, sql_messages) result = sql_client.instances.Clone(request) operation_ref = client.resource_parser.Create( 'sql.operations', operation=result.name, project=destination_instance_ref.project) if args.async: if not args.IsSpecified('format'): args.format = 'default' return sql_client.operations.Get( sql_messages.SqlOperationsGetRequest( project=operation_ref.project, operation=operation_ref.operation)) operations.OperationsV1Beta4.WaitForOperation(sql_client, operation_ref, 'Cloning Cloud SQL instance') log.CreatedResource(destination_instance_ref) rsource = sql_client.instances.Get( sql_messages.SqlInstancesGetRequest( project=destination_instance_ref.project, instance=destination_instance_ref.instance)) cache = remote_completion.RemoteCompletion() cache.AddToCache(destination_instance_ref.SelfLink()) return rsource
def Run(self, args): """Creates a database 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. """ 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') new_database = sql_messages.Database( kind='sql#database', project=instance_ref.project, instance=instance_ref.instance, name=args.database, charset=args.charset, collation=args.collation) # TODO(b/35386183): Move this API call logic. result_operation = sql_client.databases.Insert(new_database) operation_ref = client.resource_parser.Create( 'sql.operations', operation=result_operation.name, project=instance_ref.project) if args.async_: result = sql_client.operations.Get( sql_messages.SqlOperationsGetRequest( project=operation_ref.project, operation=operation_ref.operation)) else: try: operations.OperationsV1Beta4.WaitForOperation( sql_client, operation_ref, 'Creating Cloud SQL database') except exceptions.OperationError: log.Print('Database creation failed. Check if a database named {0} ' 'already exists.'.format(args.database)) # Must fail with non-zero exit code on API request failure. # TODO(b/35156765): Refactor. raise result = new_database result.kind = None log.CreatedResource(args.database, kind='database', is_async=args.async_) return result
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: ArgumentError: If the file path provided cannot be written to. """ if os.path.exists(args.cert_file): raise exceptions.ArgumentError( '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: files.WriteFileContents( args.cert_file, 'placeholder\n', private=True, create_path=False) except (files.Error, OSError) as e: raise exceptions.ArgumentError('unable to write [{path}]: {error}'.format( path=args.cert_file, error=six.text_type(e))) 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/36049399): 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 files.WriteFileContents(args.cert_file, private_key + '\n', private=True) cert_ref = client.resource_parser.Create( collection='sql.sslCerts', project=instance_ref.project, instance=instance_ref.instance, sha1Fingerprint=result.clientCert.certInfo.sha1Fingerprint) log.CreatedResource(cert_ref) return result.clientCert.certInfo
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( kind='sql#exportContext', uri=args.uri, databases=args.database or [], fileType=sql_messages.ExportContext. FileTypeValueValuesEnum.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 RunBaseCreateCommand(args, release_track): """Creates a user in a given instance. Args: args: argparse.Namespace, The arguments that this command was invoked with. release_track: base.ReleaseTrack, the release track that this was run under. Returns: SQL user resource iterator. """ client = api_util.SqlClient(api_util.API_VERSION_DEFAULT) sql_client = client.sql_client sql_messages = client.sql_messages instance_ref = client.resource_parser.Parse( args.instance, params={'project': properties.VALUES.core.project.GetOrFail}, collection='sql.instances') operation_ref = None host = users.GetHostValue(args) if release_track == base.ReleaseTrack.ALPHA: user_type = users.ParseUserType(sql_messages, args) new_user = sql_messages.User( kind='sql#user', project=instance_ref.project, instance=args.instance, name=args.username, host=host, password=args.password, type=user_type) else: new_user = sql_messages.User( kind='sql#user', project=instance_ref.project, instance=args.instance, name=args.username, host=host, password=args.password) result_operation = sql_client.users.Insert(new_user) operation_ref = client.resource_parser.Create( 'sql.operations', operation=result_operation.name, project=instance_ref.project) if args.async_: result = sql_client.operations.Get( sql_messages.SqlOperationsGetRequest( project=operation_ref.project, operation=operation_ref.operation)) else: operations.OperationsV1Beta4.WaitForOperation(sql_client, operation_ref, 'Creating Cloud SQL user') result = new_user result.kind = None log.CreatedResource(args.username, kind='user', is_async=args.async_) return result
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, 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 = 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))
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, 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 = 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))