Esempio n. 1
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)

        try:
            return apitools_base.YieldFromList(
                sql_client.instances,
                sql_messages.SqlInstancesListRequest(project=project_id),
                args.limit)
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetErrorMessage(error))
Esempio n. 2
0
  def Run(self, args):
    """Lists all instance operations that have been performed on an instance.

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

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

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

    try:
      return apitools_base.YieldFromList(
          sql_client.operations,
          sql_messages.SqlOperationsListRequest(
              project=instance_ref.project,
              instance=instance_ref.instance),
          args.limit)
    except apitools_base.HttpError as error:
      raise exceptions.HttpException(util.GetErrorMessage(error))
Esempio n. 3
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.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. 4
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.YieldFromList(
            dns_client.managedZones,
            dns_messages.DnsManagedZonesListRequest(project=project_id),
            limit=args.limit,
            field='managedZones')
Esempio n. 5
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.YieldFromList(dns_client.changes,
                                      dns_messages.DnsChangesListRequest(
                                          project=project_id,
                                          managedZone=args.zone,
                                          sortOrder=args.sort_order),
                                      limit=args.limit,
                                      field='changes')
Esempio n. 6
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.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.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. 7
0
    def Run(self, args):
        """Run the list command."""

        projects = self.context['projects_client']
        messages = self.context['projects_messages']
        try:
            for project in apitools_base.YieldFromList(
                    projects.projects,
                    messages.CloudresourcemanagerProjectsListRequest(),
                    limit=args.limit,
                    field='projects',
                    predicate=util.IsActive,
                    batch_size_attribute='pageSize'):
                yield project
        except exceptions.HttpError as error:
            raise util.GetError(error)
Esempio n. 8
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.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. 9
0
    def Run(self, args):
        """Lists all backups associated with a given instance.

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

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

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

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

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

        try:
            return apitools_base.YieldFromList(
                sql_client.backupRuns,
                sql_messages.SqlBackupRunsListRequest(
                    project=instance_ref.project,
                    instance=instance_ref.instance,
                    # At this point we support only one backup-config. So, we just use
                    # that id.
                    backupConfiguration=config_id),
                args.limit)
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetErrorMessage(error))
Esempio n. 10
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.HttpError as error:
            raise exceptions.HttpException(util.GetErrorMessage(error))

        # Get all the record-sets.
        record_sets = []
        for record_set in apitools.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. 11
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.HttpError as error:
            raise exceptions.HttpException(util.GetErrorMessage(error))

        # Get the current record-sets.
        current = {}
        for record in apitools.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)
        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