Ejemplo n.º 1
0
def _ReplaceUriCache(uris):
    """Replaces the URI cache with the uris list.

  Args:
    uris: The list of URIs that replaces the cache.
  """
    remote_completion.RemoteCompletion().StoreInCache(uris)
Ejemplo n.º 2
0
 def Display(self, args, result):
   instance_refs = []
   items = remote_completion.Iterate(result, instance_refs,
                                     self.ProjectIdToLink)
   list_printer.PrintResourceList('cloudresourcemanager.projects', items)
   cache = remote_completion.RemoteCompletion()
   cache.StoreInCache(instance_refs)
Ejemplo n.º 3
0
def ProcessResults(resources, field_selector, sort_key_fn=None,
                   reverse_sort=False, limit=None):
  """Process the results from the list query.

  Args:
    resources: The list of returned resources.
    field_selector: Select the primary key for sorting.
    sort_key_fn: Sort the key using this comparison function.
    reverse_sort: Sort the resources in reverse order.
    limit: Limit the number of resourses returned.
  Yields:
    The resource.
  """
  resources = _ConvertProtobufsToDicts(resources)
  if sort_key_fn:
    resources = sorted(resources, key=sort_key_fn, reverse=reverse_sort)

  if limit > 0:
    resources = itertools.islice(resources, limit)
  cache = remote_completion.RemoteCompletion()
  self_links = []
  for resource in resources:
    if 'selfLink' in resource:
      self_links.append(resource['selfLink'])
    if field_selector:
      yield field_selector.Apply(resource)
    else:
      yield resource
  if self_links:
    cache.StoreInCache(self_links)
Ejemplo n.º 4
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(
                    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
Ejemplo n.º 5
0
    def Run(self, args):
        """Creates a new Cloud SQL instance.

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

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

        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 = instances.InstancesV1Beta4.ConstructInstanceFromArgs(
            sql_messages, args, instance_ref=instance_ref)

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

        operation_ref = None
        try:
            result_operation = sql_client.instances.Insert(instance_resource)

            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, 'Creating Cloud SQL instance')

            log.CreatedResource(instance_ref)

            new_resource = sql_client.instances.Get(instance_ref.Request())
            cache = remote_completion.RemoteCompletion()
            cache.AddToCache(instance_ref.SelfLink())
            return new_resource
        except apitools_base.HttpError:
            log.debug('operation : %s', str(operation_ref))
            raise
Ejemplo n.º 6
0
  def Run(self, args):
    """Clones a Cloud SQL instance.

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

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

    source_instance_ref, destination_instance_ref = (
        self._GetInstanceRefsFromArgs(args))

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

    self._UpdateRequestFromArgs(request, args)

    result = sql_client.instances.Clone(request)

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

    if args.async:
      return sql_client.operations.Get(
          sql_messages.SqlOperationsGetRequest(
              project=operation_ref.project,
              instance=operation_ref.instance,
              operation=operation_ref.operation))
    operations.OperationsV1Beta3.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
Ejemplo n.º 7
0
def _AddToUriCache(uris):
    """Add the uris list to the URI cache.

  Args:
    uris: The list of URIs to add.
  """
    update = remote_completion.RemoteCompletion().AddToCache
    for uri in uris:
        update(uri)
Ejemplo n.º 8
0
def _DeleteFromUriCache(uris):
    """Deletes the uris list from the URI cache.

  Args:
    uris: The list of URIs to delete.
  """
    update = remote_completion.RemoteCompletion().DeleteFromCache
    for uri in uris:
        update(uri)
Ejemplo n.º 9
0
  def Run(self, args):
    """Deletes a Cloud SQL instance.

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

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

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

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

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

      # TODO(b/21998524) Once the V1Beta4 APIs are used, the delete call itself
      # will return the operation status and that can be checked for errors
      # unused_operation = sql_client.operations.Get(operation_ref.Request())

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

    except apitools_base.HttpError:
      log.debug('operation : %s', str(operation_ref))
      raise
Ejemplo n.º 10
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_FALLBACK)
        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.operation,
                project=instance_ref.project,
                instance=instance_ref.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
Ejemplo n.º 11
0
 def Done(self):
     if self._uris is not None:
         if isinstance(self._update_cache_op,
                       cache_update_ops.AddToCacheOp):
             update_cache_op = remote_completion.AddToCacheOp
         elif isinstance(self._update_cache_op,
                         cache_update_ops.DeleteFromCacheOp):
             update_cache_op = remote_completion.DeleteFromCacheOp
         elif isinstance(self._update_cache_op,
                         cache_update_ops.ReplaceCacheOp):
             update_cache_op = remote_completion.ReplaceCacheOp
         else:
             return
         remote_completion.RemoteCompletion().UpdateCache(
             update_cache_op, self._uris)
Ejemplo n.º 12
0
def PrintResourceList(collection, items):
  """Print a list of cloud resources.

  Args:
    collection: str, The name of the collection to which the items belong.
    items: iterable, A list or otherwise iterable object that generates the
        rows of the list.
  """
  options = []
  cache = remote_completion.RemoteCompletion()

  class Iter(object):
    """Create an iterator that steals the names of objects.

    Args:
      items: List of items to iterate
      options: List of names of the items created by iterator.
    """

    def __init__(self, items, options):
      self.items = items
      self.options = options

    def next(self):
      item = self.items.next()
      fun = cache.ITEM_NAME_FUN['sql']
      if fun:
        self.options.append(fun(item))
      return item

    def __iter__(self):
      return self

  if cache.ResourceIsCached(collection):
    items = Iter(iter(items), options)
  console_io.PrintExtendedList(items, COLLECTION_COLUMNS[collection])
  if options:
    cache.StoreInCache(collection, options, None)
Ejemplo n.º 13
0
 def Done(self):
     if self._uris is not None:
         remote_completion.RemoteCompletion().UpdateCache(
             self._update_cache_op, self._uris)
Ejemplo n.º 14
0
 def Display(self, args, result):
     instance_refs = []
     items = remote_completion.Iterate(result, instance_refs, self.GetRef)
     list_printer.PrintResourceList('dns.managedZones', items)
     cache = remote_completion.RemoteCompletion()
     cache.StoreInCache(instance_refs)
Ejemplo n.º 15
0
    def Run(self, args):
        """Creates a new Cloud SQL instance.

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

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

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

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

        instance_resource = util.ConstructInstanceFromArgs(sql_messages, args)

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

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

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

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

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

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

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

            log.CreatedResource(instance_ref)

            rsource = sql_client.instances.Get(instance_ref.Request())
            cache = remote_completion.RemoteCompletion()
            cache.AddToCache(instance_ref.SelfLink())
            return rsource
        except apitools_base.HttpError:
            log.debug('operation : %s', str(operation_ref))
            raise
Ejemplo n.º 16
0
  def Run(self, args):
    """Clones a Cloud SQL instance.

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

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

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

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

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

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

    result = sql_client.instances.Clone(request)

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

    if args.async:
      return sql_client.operations.Get(operation_ref.Request())
    util.WaitForOperation(sql_client, operation_ref,
                          'Cloning Cloud SQL instance')
    log.CreatedResource(destination_instance_ref)
    rsource = sql_client.instances.Get(destination_instance_ref.Request())
    cache = remote_completion.RemoteCompletion()
    cache.AddToCache(destination_instance_ref.SelfLink())
    return rsource
Ejemplo n.º 17
0
 def Display(self, unused_args, result):
   instance_refs = []
   items = remote_completion.Iterate(result, instance_refs, self.GetRef)
   list_printer.PrintResourceList('sql.instances.v1beta4', items)
   cache = remote_completion.RemoteCompletion()
   cache.StoreInCache(instance_refs)