def Run(self, args):
        """Run 'rolling-updates list-instance-updates'.

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

    Returns:
      List of all the instance updates.

    Raises:
      HttpException: An http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.
    """
        client = self.context['updater_api']
        messages = self.context['updater_messages']
        resources = self.context['updater_resources']

        ref = resources.Parse(args.update,
                              collection='replicapoolupdater.rollingUpdates')
        request = (messages.
                   ReplicapoolupdaterRollingUpdatesListInstanceUpdatesRequest(
                       project=ref.project,
                       zone=ref.zone,
                       rollingUpdate=ref.rollingUpdate))

        try:
            return apitools_base.YieldFromList(client.rollingUpdates,
                                               request,
                                               method='ListInstanceUpdates')
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(updater_util.GetError(error))
Esempio n. 2
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')

        return apitools_base.YieldFromList(
            sql_client.backupRuns,
            sql_messages.SqlBackupRunsListRequest(
                project=instance_ref.project, instance=instance_ref.instance),
            args.limit)
Esempio n. 3
0
    def Run(self, args):
        """Run 'rolling-updates list'.

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

    Returns:
      List of all the updates.

    Raises:
      HttpException: An http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.
    """
        client = self.context['updater_api']
        messages = self.context['updater_messages']

        request = messages.ReplicapoolupdaterRollingUpdatesListRequest(
            project=properties.VALUES.core.project.Get(required=True),
            zone=properties.VALUES.compute.zone.Get(required=True))
        if args.group:
            request.filter = 'instanceGroup eq %s' % args.group
        limit = updater_util.SanitizeLimitFlag(args.limit)

        try:
            return apitools_base.YieldFromList(client.rollingUpdates,
                                               request,
                                               limit=limit)
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(updater_util.GetError(error))
Esempio n. 4
0
  def Run(self, args):
    """Lists Cloud SQL instances in a given project.

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

    Returns:
      SQL instance resource iterator.
    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']

    project_id = properties.VALUES.core.project.Get(required=True)

    remote_completion.SetGetInstanceFun(self.GetRef)
    return apitools_base.YieldFromList(
        sql_client.instances,
        sql_messages.SqlInstancesListRequest(project=project_id),
        args.limit)
Esempio n. 5
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Yields:
      Objects representing user functions.
    """
        client = self.context['functions_client']
        list_generator = apitools_base.YieldFromList(
            service=client.projects_regions_functions,
            request=self.BuildRequest(args),
            limit=args.limit,
            field='functions',
            batch_size_attribute='pageSize')
        # Decorators (e.g. util.CatchHTTPErrorRaiseHTTPException) don't work
        # for generators. We have to catch the exception above the iteration loop,
        # but inside the function.
        try:
            for item in list_generator:
                yield item
        except apitools_base.HttpError as error:
            msg = util.GetHttpErrorMessage(error)
            unused_type, unused_value, traceback = sys.exc_info()
            raise base_exceptions.HttpException, msg, traceback
Esempio n. 6
0
    def Run(self, args):
        dns_client = self.context['dns_client']
        dns_messages = self.context['dns_messages']

        project_id = properties.VALUES.core.project.Get(required=True)
        remote_completion.SetGetInstanceFun(self.GetRef)

        return apitools_base.YieldFromList(
            dns_client.managedZones,
            dns_messages.DnsManagedZonesListRequest(project=project_id),
            limit=args.limit,
            field='managedZones')
Esempio n. 7
0
  def Run(self, args):
    dns_client = self.context['dns_client']
    dns_messages = self.context['dns_messages']

    project_id = properties.VALUES.core.project.Get(required=True)

    return apitools_base.YieldFromList(
        dns_client.changes,
        dns_messages.DnsChangesListRequest(
            project=project_id,
            managedZone=args.zone,
            sortOrder=args.sort_order),
        limit=args.limit, field='changes')
Esempio n. 8
0
  def Run(self, args):
    """Run the list command."""

    projects = self.context['projects_client']
    messages = self.context['projects_messages']
    remote_completion.SetGetInstanceFun(self.ProjectIdToLink)
    for project in apitools_base.YieldFromList(
        projects.projects,
        messages.CloudresourcemanagerProjectsListRequest(),
        limit=args.limit,
        field='projects',
        predicate=util.IsActive,
        batch_size_attribute='pageSize'):
      yield project
Esempio n. 9
0
    def Run(self, args):
        if os.path.isfile(args.transaction_file):
            raise exceptions.ToolException(
                'transaction already exists at [{0}]'.format(
                    args.transaction_file))

        dns = self.context['dns_client']
        messages = self.context['dns_messages']
        resources = self.context['dns_resources']
        project_id = properties.VALUES.core.project.Get(required=True)

        # Get the managed-zone.
        zone_ref = resources.Parse(args.zone, collection='dns.managedZones')
        try:
            zone = dns.managedZones.Get(zone_ref.Request())
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetErrorMessage(error))

        # Initialize an empty change
        change = messages.Change()

        # Get the SOA record, there will be one and only one.
        # Add addition and deletion for SOA incrementing to change.
        records = [
            record for record in apitools_base.YieldFromList(
                dns.resourceRecordSets,
                messages.DnsResourceRecordSetsListRequest(
                    project=project_id,
                    managedZone=zone_ref.Name(),
                    name=zone.dnsName,
                    type='SOA'),
                field='rrsets')
        ]
        change.deletions.append(records[0])
        change.additions.append(import_util.NextSOARecordSet(records[0]))

        # Write change to transaction file
        try:
            with files.Context(open(args.transaction_file,
                                    'w')) as transaction_file:
                transaction_util.WriteToYamlFile(transaction_file, change)
        except Exception as exp:
            msg = 'unable to write transaction [{0}] because [{1}]'
            msg = msg.format(args.transaction_file, exp)
            raise exceptions.ToolException(msg)

        log.status.Print('Transaction started [{0}].'.format(
            args.transaction_file))
Esempio n. 10
0
    def Run(self, args):
        log.warn('Please use instead [gcloud compute instance-groups '
                 'managed list].')
        client = self.context['autoscaler-client']
        messages = self.context['autoscaler_messages_module']
        resources = self.context['autoscaler_resources']
        try:
            request = messages.AutoscalerAutoscalersListRequest()
            request.project = properties.VALUES.core.project.Get(required=True)
            request.zone = resources.Parse(args.zone,
                                           collection='compute.zones').zone
            return apitools_base.YieldFromList(client.autoscalers, request)

        except exceptions.HttpError as error:
            raise calliope_exceptions.HttpException(
                util.GetErrorMessage(error))
        except ValueError as error:
            raise calliope_exceptions.HttpException(error)
Esempio n. 11
0
    def Run(self, args):
        dns_client = self.context['dns_client']
        dns_messages = self.context['dns_messages']

        project_id = properties.VALUES.core.project.Get(required=True)

        if args.type and not args.name:
            raise exceptions.ToolException(
                '--name should also be provided when --type is used')

        return apitools_base.YieldFromList(
            dns_client.resourceRecordSets,
            dns_messages.DnsResourceRecordSetsListRequest(
                project=project_id,
                managedZone=args.zone,
                name=util.AppendTrailingDot(args.name),
                type=args.type),
            limit=args.limit,
            field='rrsets')
Esempio n. 12
0
    def Run(self, args):
        dns = self.context['dns_client']
        messages = self.context['dns_messages']
        resources = self.context['dns_resources']
        project_id = properties.VALUES.core.project.Get(required=True)

        # Get the managed-zone.
        zone_ref = resources.Parse(args.zone, collection='dns.managedZones')
        try:
            zone = dns.managedZones.Get(zone_ref.Request())
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetErrorMessage(error))

        # Get all the record-sets.
        record_sets = []
        for record_set in apitools_base.YieldFromList(
                dns.resourceRecordSets,
                messages.DnsResourceRecordSetsListRequest(
                    project=project_id, managedZone=zone_ref.Name()),
                field='rrsets'):
            record_sets.append(record_set)

        # Export the record-sets.
        try:
            with files.Context(open(args.records_file, 'w')) as export_file:
                if args.zone_file_format:
                    export_util.WriteToZoneFile(export_file, record_sets,
                                                zone.dnsName)
                else:
                    export_util.WriteToYamlFile(export_file, record_sets)
        except Exception as exp:
            msg = 'unable to export record-sets to file [{0}]: {1}'.format(
                args.records_file, exp)
            raise exceptions.ToolException(msg)

        log.status.Print('Exported record-sets to [{0}].'.format(
            args.records_file))
Esempio n. 13
0
    def Run(self, args):
        with trans_util.TransactionFile(args.transaction_file) as trans_file:
            change = trans_util.ChangeFromYamlFile(trans_file)

        dns = self.context['dns_client']
        messages = self.context['dns_messages']
        resources = self.context['dns_resources']
        project_id = properties.VALUES.core.project.Get(required=True)

        record_to_remove = trans_util.CreateRecordSetFromArgs(args)

        # Ensure the record to be removed exists
        zone_ref = resources.Parse(args.zone, collection='dns.managedZones')
        existing_records = [
            record for record in apitools_base.YieldFromList(
                dns.resourceRecordSets,
                messages.DnsResourceRecordSetsListRequest(
                    project=project_id,
                    managedZone=zone_ref.Name(),
                    name=args.name,
                    type=args.type),
                field='rrsets')
        ]
        if not existing_records or existing_records[0] != record_to_remove:
            raise exceptions.ToolException(
                'Record to be removed does not exist')

        change.deletions.append(record_to_remove)

        with trans_util.TransactionFile(args.transaction_file,
                                        'w') as trans_file:
            trans_util.WriteToYamlFile(trans_file, change)

        log.status.Print(
            'Record removal appended to transaction at [{0}].'.format(
                args.transaction_file))
Esempio n. 14
0
    def Run(self, args):
        if not os.path.isfile(args.records_file):
            raise exceptions.ToolException('no such file [{0}]'.format(
                args.records_file))

        dns = self.context['dns_client']
        messages = self.context['dns_messages']
        resources = self.context['dns_resources']
        project_id = properties.VALUES.core.project.Get(required=True)

        # Get the managed-zone.
        zone_ref = resources.Parse(args.zone, collection='dns.managedZones')
        try:
            zone = dns.managedZones.Get(zone_ref.Request())
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetErrorMessage(error))

        # Get the current record-sets.
        current = {}
        for record in apitools_base.YieldFromList(
                dns.resourceRecordSets,
                messages.DnsResourceRecordSetsListRequest(
                    project=project_id, managedZone=zone_ref.Name()),
                field='rrsets'):
            current[(record.name, record.type)] = record

        # Get the imported record-sets.
        try:
            with files.Context(open(args.records_file)) as import_file:
                if args.zone_file_format:
                    imported = import_util.RecordSetsFromZoneFile(
                        import_file, zone.dnsName)
                else:
                    imported = import_util.RecordSetsFromYamlFile(import_file)
        except Exception as exp:
            msg = (
                'unable to read record-sets from specified records-file [{0}] '
                'because [{1}]')
            msg = msg.format(args.records_file, exp.message)
            raise exceptions.ToolException(msg)

        # Get the change resulting from the imported record-sets.
        change = import_util.ComputeChange(current, imported,
                                           args.delete_all_existing,
                                           zone.dnsName,
                                           args.replace_origin_ns)
        if not change:
            msg = 'Nothing to do, all the records in [{0}] already exist.'.format(
                args.records_file)
            log.status.Print(msg)
            return None

        # Send the change to the service.
        result = dns.changes.Create(
            messages.DnsChangesCreateRequest(change=change,
                                             managedZone=zone.name,
                                             project=project_id))
        change_ref = resources.Create(collection='dns.changes',
                                      project=project_id,
                                      managedZone=zone.name,
                                      changeId=result.id)
        msg = 'Imported record-sets from [{0}] into managed-zone [{1}].'.format(
            args.records_file, zone_ref.Name())
        log.status.Print(msg)
        log.CreatedResource(change_ref)
        return result