Пример #1
0
class ImageCommand(command_base.GoogleComputeCommand):
    """Base command for working with the images collection."""

    print_spec = command_base.ResourcePrintSpec(
        summary=['name', 'deprecation', 'status'],
        field_mappings=(('name', 'selfLink'), ('description', 'description'),
                        ('deprecation', 'deprecated.state'), ('status',
                                                              'status')),
        detail=(('name', 'name'), ('description', 'description'),
                ('creation-time', 'creationTimestamp'), ('deprecation',
                                                         'deprecated.state'),
                ('replacement', 'deprecated.replacement'),
                ('status', 'status'), ('disk-size-gb', 'diskSizeGb'),
                ('archive-size-bytes', 'archiveSizeBytes')),
        sort_by='name')

    resource_collection_name = 'images'

    def __init__(self, name, flag_values):
        super(ImageCommand, self).__init__(name, flag_values)

    def _AutoDetectZone(self):
        """Causes this command to auto detect zone."""
        def _GetZoneContext(unused_object_type, context):
            return self.GetZoneForResource(self.api.disks, context['disk'],
                                           context['project'])

        self._context_parser.context_prompt_fxns['zone'] = _GetZoneContext
Пример #2
0
class RouteCommand(command_base.GoogleComputeCommand):
    """Base command for working with the routes collection."""

    print_spec = command_base.ResourcePrintSpec(
        summary=['name', 'network', 'destination-range', 'priority'],
        field_mappings=(('name', 'name'), ('network', 'network'),
                        ('tags', 'tags'), ('destination-range', 'destRange'),
                        ('next-hop-instance', 'nextHopInstance'),
                        ('next-hop-ip', 'nextHopIp'), ('next-hop-gateway',
                                                       'nextHopGateway'),
                        ('next-hop-network', 'nextHopNetwork'),
                        ('priority', 'priority'), ('warning',
                                                   'warnings.code')),
        detail=(('name', 'name'), ('description', 'description'),
                ('creation-time', 'creationTimestamp'), ('network', 'network'),
                ('tags', 'tags'), ('destination-range', 'destRange'),
                ('next-hop-instance', 'nextHopInstance'), ('next-hop-ip',
                                                           'nextHopIp'),
                ('next-hop-gateway', 'nextHopGateway'), ('next-hop-network',
                                                         'nextHopNetwork'),
                ('priority', 'priority'), ('warning', 'warnings.code'),
                ('warning-message', 'warnings.message')),
        sort_by='name')

    resource_collection_name = 'routes'

    def __init__(self, name, flag_values):
        super(RouteCommand, self).__init__(name, flag_values)
Пример #3
0
class SnapshotCommand(command_base.GoogleComputeCommand):
    """Base command for working with the snapshots collection."""

    print_spec = command_base.ResourcePrintSpec(
        summary=['name', 'status', 'disk-size-gb'],
        field_mappings=(('name', 'name'), ('description', 'description'),
                        ('creation-time', 'creationTimestamp'),
                        ('status', 'status'), ('disk-size-gb', 'diskSizeGb'),
                        ('storage-bytes', 'storageBytes'),
                        ('storage-bytes-status',
                         'storageBytesStatus'), ('source-disk', 'sourceDisk')),
        detail=(('name', 'name'), ('description', 'description'),
                ('creation-time', 'creationTimestamp'), ('status', 'status'),
                ('disk-size-gb', 'diskSizeGb'), ('storage-bytes',
                                                 'storageBytes'),
                ('storage-bytes-status',
                 'storageBytesStatus'), ('source-disk', 'sourceDisk')),
        sort_by='name')

    resource_collection_name = 'snapshots'

    def __init__(self, name, flag_values):
        super(SnapshotCommand, self).__init__(name, flag_values)

    def _PrepareRequestArgs(self, snapshot_context, **other_args):
        """Gets the dictionary of API method keyword arguments.

    Args:
      snapshot_context:  Context dict for this snapshot.
      **other_args: Keyword arguments that should be included in the request.

    Returns:
      Dictionary of keyword arguments that should be passed in the API call,
      includes all keyword arguments passed in 'other_args' plus
      common keys such as the name of the resource and the project.
    """

        kwargs = {
            'project': snapshot_context['project'],
            'snapshot': snapshot_context['snapshot']
        }
        for key, value in other_args.items():
            kwargs[key] = value
        return kwargs

    def _AutoDetectZone(self):
        """Causes this command to auto detect zone."""
        def _GetZoneContext(unused_object_type, context):
            return self.GetZoneForResource(self.api.disks, context['disk'],
                                           context['project'])

        self._context_parser.context_prompt_fxns['zone'] = _GetZoneContext
Пример #4
0
class DiskTypeCommand(command_base.GoogleComputeCommand):
  """Base command for working with the disk types collection."""

  print_spec = command_base.ResourcePrintSpec(
      summary=['name', 'zone'],
      field_mappings=(
          ('name', 'name'),
          ('description', 'description'),
          ('valid-disk-size', 'validDiskSize'),
          ('zone', 'zone'),
          ('deprecation', 'deprecated.state')),
      detail=(
          ('name', 'name'),
          ('description', 'description'),
          ('valid-disk-size', 'validDiskSize'),
          ('zone', 'zone'),
          ('creation-time', 'creationTimestamp'),
          ('deprecation', 'deprecated.state'),
          ('replacement', 'deprecated.replacement')),
      sort_by='name')

  resource_collection_name = 'diskTypes'

  def __init__(self, name, flag_values):
    super(DiskTypeCommand, self).__init__(name, flag_values)
    flags.DEFINE_string('zone',
                        None,
                        'The zone for this request.',
                        flag_values=flag_values)

  def _PrepareRequestArgs(self, disk_type_context, **other_args):
    """Gets the dictionary of API method keyword arguments.

    Args:
      disk_type_context: A context dict for the desired disk type.
      **other_args: Keyword arguments that should be included in the request.

    Returns:
      Dictionary of keyword arguments that should be passed in the API call,
      includes all keyword arguments passed in 'other_args' plus common keys
      such as the name of the resource and the project.
    """
    kwargs = {
        'project': disk_type_context['project'],
        'diskType': disk_type_context['diskType']
    }
    if disk_type_context['zone']:
      kwargs['zone'] = disk_type_context['zone']
    for key, value in other_args.items():
      kwargs[key] = value
    return kwargs
Пример #5
0
class HttpHealthCheckCommand(command_base.GoogleComputeCommand):
  """Base command for working with the HTTP health check collection."""

  print_spec = command_base.ResourcePrintSpec(
      summary=['name', 'host', 'port'],
      field_mappings=(
          ('name', 'name'),
          ('description', 'description'),
          ('host', 'host'),
          ('port', 'port'),
          ('request-path', 'requestPath')),
      detail=(
          ('name', 'name'),
          ('description', 'description'),
          ('creation-time', 'creationTimestamp'),
          ('host', 'host'),
          ('port', 'port'),
          ('request-path', 'requestPath'),
          ('check-interval-sec', 'checkIntervalSec'),
          ('check-timeout-sec', 'timeoutSec'),
          ('unhealthy-threshold', 'unhealthyThreshold'),
          ('healthy-threshold', 'healthyThreshold')),
      sort_by='name')

  resource_collection_name = 'httpHealthChecks'

  # The default health check host.
  DEFAULT_HOST = ''

  # The default health check port.
  DEFAULT_PORT = 80

  # The default health check request path.
  DEFAULT_REQUEST_PATH = '/'

  # The default health check interval in seconds.
  DEFAULT_CHECK_INTERVAL_SEC = 5

  # The default health check timeout in seconds.
  DEFAULT_CHECK_TIMEOUT_SEC = 5

  # The default number of failures before marking a VM unhealthy.
  DEFAULT_UNHEALTHY_THRESHOLD = 2

  # The default number of successes before marking a VM healthy.
  DEFAULT_HEALTHY_THRESHOLD = 2

  def __init__(self, name, flag_values):
    super(HttpHealthCheckCommand, self).__init__(name, flag_values)
Пример #6
0
class ZoneCommand(command_base.GoogleComputeCommand):
    """Base command for working with the zones collection."""

    print_spec = command_base.ResourcePrintSpec(
        summary=['name', 'status', 'next-maintenance'],
        field_mappings=(('name', 'name'), ('description', 'description'),
                        ('status', 'status'), ('deprecation',
                                               'deprecated.state'),
                        ('next-maintenance', 'next_maintenance_window'),
                        ('instances', 'instances'), ('cpus', 'cpus'),
                        ('disks', 'disks'), ('disks-total-gb',
                                             'disks_total_gb')),
        detail=(('name', 'name'), ('description', 'description'),
                ('creation-time', 'creationTimestamp'), ('status', 'status'),
                ('deprecation', 'deprecated.state'),
                ('replacement', 'deprecated.replacement')),
        sort_by='name')
Пример #7
0
class RegionCommand(command_base.GoogleComputeCommand):
    """Base command for working with the regions collection."""

    print_spec = command_base.ResourcePrintSpec(
        summary=[
            'name', 'status', 'cpus', 'disks-total-gb', 'static-addresses'
        ],
        field_mappings=(('name', 'name'), ('description', 'description'),
                        ('status', 'status'), ('deprecation',
                                               'deprecated.state'),
                        ('cpus', 'cpus'), ('disks-total-gb', 'disks_total_gb'),
                        ('in-use-addresses', 'in_use_addresses'),
                        ('static-addresses', 'static_addresses')),
        detail=(('name', 'name'), ('description', 'description'),
                ('creation-time', 'creationTimestamp'), ('status', 'status'),
                ('zones', 'zones'), ('deprecation', 'deprecated.state'),
                ('replacement', 'deprecated.replacement')),
        sort_by='name')
Пример #8
0
class NetworkCommand(command_base.GoogleComputeCommand):
  """Base command for working with the networks collection."""

  print_spec = command_base.ResourcePrintSpec(
      summary=['name', 'addresses', 'gateway'],
      field_mappings=(
          ('name', 'name'),
          ('description', 'description'),
          ('addresses', 'IPv4Range'),
          ('gateway', 'gatewayIPv4')),
      detail=(
          ('name', 'name'),
          ('description', 'description'),
          ('creation-time', 'creationTimestamp'),
          ('addresses', 'IPv4Range'),
          ('gateway', 'gatewayIPv4')),
      sort_by='name')

  resource_collection_name = 'networks'

  def __init__(self, name, flag_values):
    super(NetworkCommand, self).__init__(name, flag_values)
Пример #9
0
class FirewallCommand(command_base.GoogleComputeCommand):
    """Base command for working with the firewalls collection."""

    print_spec = command_base.ResourcePrintSpec(
        summary=['name', 'network'],
        field_mappings=(('name', 'name'), ('description', 'description'),
                        ('network', 'network'), ('source-ips', 'sourceRanges'),
                        ('source-tags', 'sourceTags'), ('target-tags',
                                                        'targetTags')),
        detail=(('name', 'name'), ('description', 'description'),
                ('creation-time', 'creationTimestamp'), ('network', 'network'),
                ('source-ips', 'sourceRanges'), ('source-tags', 'sourceTags'),
                ('target-tags', 'targetTags')),
        sort_by='name')

    resource_collection_name = 'firewalls'

    def __init__(self, name, flag_values):
        super(FirewallCommand, self).__init__(name, flag_values)

    def GetDetailRow(self, result):
        """Returns an associative list of items for display in a detail table.

    Args:
      result: A dict returned by the server.

    Returns:
      A list.
    """
        data = []
        # Add the rules
        for allowed in result.get('allowed', []):
            as_string = str(allowed['IPProtocol'])
            if allowed.get('ports'):
                as_string += ': %s' % ', '.join(allowed['ports'])
            data.append(('allowed', as_string))
        return data
class MachineTypeCommand(command_base.GoogleComputeCommand):
  """Base command for working with the machine types collection."""

  print_spec = command_base.ResourcePrintSpec(
      summary=['name', 'zone', 'cpus', 'memory-mb', 'deprecation'],
      field_mappings=(
          ('name', 'name'),
          ('description', 'description'),
          ('zone', 'zone'),
          ('cpus', 'guestCpus'),
          ('memory-mb', 'memoryMb'),
          ('scratch-disk-size-gb',
           ('scratchDisks.diskGb', 'ephemeralDisks.diskGb')),
          ('max-pds', 'maximumPersistentDisks'),
          ('max-total-pd-size-gb', 'maximumPersistentDisksSizeGb'),
          ('deprecation', 'deprecated.state')),
      detail=(
          ('name', 'name'),
          ('description', 'description'),
          ('zone', 'zone'),
          ('creation-time', 'creationTimestamp'),
          ('cpus', 'guestCpus'),
          ('memory-mb', 'memoryMb'),
          ('scratch-disk-size-gb',
           ('scratchDisks.diskGb', 'ephemeralDisks.diskGb')),
          ('max-pds', 'maximumPersistentDisks'),
          ('max-total-pd-size-gb', 'maximumPersistentDisksSizeGb'),
          ('available-zones', 'availableZone'),
          ('deprecation', 'deprecated.state'),
          ('replacement', 'deprecated.replacement')),
      sort_by='cpus')

  resource_collection_name = 'machineTypes'

  def __init__(self, name, flag_values):
    super(MachineTypeCommand, self).__init__(name, flag_values)
    flags.DEFINE_string('zone',
                        None,
                        'The zone for this request.',
                        flag_values=flag_values)

  def _PrepareRequestArgs(self, machine_type_context, **other_args):
    """Gets the dictionary of API method keyword arguments.

    Args:
      machine_type_context: A context dict for the desired machine type.
      **other_args: Keyword arguments that should be included in the request.

    Returns:
      Dictionary of keyword arguments that should be passed in the API call,
      includes all keyword arguments passed in 'other_args' plus common keys
      such as the name of the resource and the project.
    """
    kwargs = {
        'project': machine_type_context['project'],
        'machineType': machine_type_context['machineType']
    }
    if machine_type_context['zone']:
      kwargs['zone'] = machine_type_context['zone']
    for key, value in other_args.items():
      kwargs[key] = value
    return kwargs
class TargetPoolCommand(command_base.GoogleComputeCommand):
    """Base command for working with the target pool collection."""

    print_spec = command_base.ResourcePrintSpec(
        summary=['name', 'region'],
        field_mappings=(('name', 'name'), ('description', 'description'),
                        ('region', 'region')),
        detail=(('name', 'name'), ('description', 'description'),
                ('creation-time', 'creationTimestamp'),
                ('health-checks', 'healthChecks'), ('session-affinity',
                                                    'sessionAffinity'),
                ('failover-ratio', 'failoverRatio'), ('backup-pool',
                                                      'backupPool')),
        sort_by='name')

    resource_collection_name = 'targetPools'

    # The default session affinity option
    DEFAULT_SESSION_AFFINITY = 'NONE'

    def __init__(self, name, flag_values):
        super(TargetPoolCommand, self).__init__(name, flag_values)
        flags.DEFINE_string('region',
                            None,
                            '[Required] The region for this request.',
                            flag_values=flag_values)

    def _PrepareRequestArgs(self, target_pool_context):
        """Gets the dictionary of API method keyword arguments.

    Args:
      target_pool_context:  A context dict for the desired target pool.

    Returns:
      Dictionary of keyword arguments that should be passed in the API call.
    """

        kwargs = {
            'project': target_pool_context['project'],
            'targetPool': target_pool_context['targetPool'],
            'region': target_pool_context['region'],
        }
        return kwargs

    def _AutoDetectZoneForInstances(self):
        """Instruct this command to auto detect zone instead of prompting."""
        def _GetZoneContext(object_type, context):
            if object_type == 'instances':
                return self.GetZoneForResource(self.api.instances,
                                               context['instance'],
                                               project=context['project'])

        self._context_parser.context_prompt_fxns['zone'] = _GetZoneContext

    def _AutoDetectRegion(self):
        """Instruct this command to auto detect region instead of prompting."""
        def _GetRegionContext(unused_object_type, context):
            if self._flags.region:
                return self.DenormalizeResourceName(self._flags.region)
            return self.GetRegionForResource(self.api.target_pools,
                                             context['targetPool'],
                                             project=context['project'])

        self._context_parser.context_prompt_fxns['region'] = _GetRegionContext

    def ParseZoneInstancePair(self, zone_instance):
        """Parses an element of the --instance flag for this command.

    Args:
      zone_instance: The instances as specified in the flag.

    Returns:
      A list of <zone, instance> pairs.

    Raises:
      ValueError: If zone_instance is invalid.
    """
        zone_instance_pair = zone_instance.split('/')

        # Invalid pair.
        if len(zone_instance_pair) != 2:
            raise ValueError('Invalid value for instance: %s' % zone_instance)

        LOGGER.warn('The <zone>/<instance> short form is deprecated. '
                    'Please use a relative or fully-qualified path, such as '
                    '<zone>/instances/<instance>.')

        return zone_instance_pair
Пример #12
0
class DiskCommand(command_base.GoogleComputeCommand):
  """Base command for working with the disks collection."""

  print_spec = command_base.ResourcePrintSpec(
      summary=['name', 'zone', 'status', 'disk-type', 'size-gb'],
      field_mappings=(
          ('name', 'name'),
          ('description', 'description'),
          ('zone', 'zone'),
          ('status', 'status'),
          ('source-snapshot', 'sourceSnapshot'),
          ('disk-type', 'type'),
          ('size-gb', 'sizeGb')),
      detail=(
          ('name', 'name'),
          ('description', 'description'),
          ('creation-time', 'creationTimestamp'),
          ('zone', 'zone'),
          ('status', 'status'),
          ('source-snapshot', 'sourceSnapshot'),
          ('source-image', 'sourceImage'),
          ('source-image-id', 'sourceImageId'),
          ('disk-type', 'type'),
          ('size-gb', 'sizeGb')),
      sort_by='name')

  resource_collection_name = 'disks'

  def __init__(self, name, flag_values):
    super(DiskCommand, self).__init__(name, flag_values)

    flags.DEFINE_string('zone',
                        None,
                        'The zone for this request.',
                        flag_values=flag_values)

  def _AutoDetectZone(self):
    """Causes this command to auto detect zone."""
    def _GetZoneContext(unused_object_type, context):
      return self.GetZoneForResource(
          self.api.disks, context['disk'], context['project'])

    self._context_parser.context_prompt_fxns['zone'] = _GetZoneContext

  def _PromptForZoneOnlyOnce(self):
    """Instruct this command to only prompt for the zone once."""
    def _GetZoneContext(unused_object_type, unused_context):
      if not self._flags.zone:
        self._flags.zone = self._presenter.PromptForZone(self.api.zones)['name']

      return self.DenormalizeResourceName(self._flags.zone)

    self._context_parser.context_prompt_fxns['zone'] = _GetZoneContext

  def _PrepareRequestArgs(self, disk_name, **other_args):
    """Gets the dictionary of API method keyword arguments.

    Args:
      disk_name: The name of the disk.
      **other_args: Keyword arguments that should be included in the request.

    Returns:
      Dictionary of keyword arguments that should be passed in the API call,
      includes all keyword arguments passed in 'other_args' plus
      common keys such as the name of the resource and the project.
    """
    disk_context = self._context_parser.ParseContextOrPrompt('disks', disk_name)

    kwargs = {
        'project': disk_context['project'],
        'disk': disk_context['disk'],
        'zone': disk_context['zone']
    }

    for key, value in other_args.items():
      kwargs[key] = value

    return kwargs
Пример #13
0
class ProjectCommand(command_base.GoogleComputeCommand):
  """Base command for working with the projects collection."""

  print_spec = command_base.ResourcePrintSpec(
      summary=['name', 'description'],
      field_mappings=(
          ('name', 'name'),
          ('description', 'description'),
          ('creation-time', 'creationTimestamp')),
      detail=(
          ('name', 'name'),
          ('description', 'description'),
          ('creation-time', 'creationTimestamp'),
          ('common-instance-metadata-fingerprint',
           'commonInstanceMetadata.fingerprint')),
      sort_by='name')

  def __init__(self, name, flag_values):
    super(ProjectCommand, self).__init__(name, flag_values)

  def GetDetailRow(self, result):
    """Returns an associative list of items for display in a detail table.

    Args:
      result: A dict returned by the server.

    Returns:
      A list.
    """
    data = []
    # Add the IP addresses
    ips = [ipaddr.IPv4Address(ip) for ip
           in result.get('externalIpAddresses', [])]
    if ips:
      blocks = sorted(ipaddr.collapse_address_list(ips))

      ip_info = [('count', len(ips))]
      if blocks:
        ip_info.append(('blocks', blocks))
      data.append(('ips', ip_info))

    # Add the quotas

    quota_info = []
    for quota in result.get('quotas', []):
      quota_info.append((quota['metric'].lower().replace('_', '-'),
                         '%s/%s' % (str(quota['usage']), str(quota['limit']))))
    data.append(('usage', quota_info))

    # Add the metadata
    if result.get('commonInstanceMetadata', []):

      metadata_container = result.get('commonInstanceMetadata', [])
      if 'kind' in metadata_container:
        metadata_container = metadata_container.get('items', [])

      metadata_info = []
      for metadata_entry in metadata_container:
        metadata_info.append((
            metadata_entry.get('key'),
            metadata_entry.get('value')))
      data.append(('common-instance-metadata', metadata_info))
      data.append(('common-instance-metadata-fingerprint',
                   result.get('commonInstanceMetadata', {}).get('fingerprint')))

    usage_export = result.get('usageExportLocation', [])
    if usage_export:
      data.append(('usageExportLocation',
                   [('bucketName', usage_export['bucketName']),
                    ('reportNamePrefix', usage_export['reportNamePrefix'])]))

    return data
class TargetInstanceCommand(command_base.GoogleComputeCommand):
    """Base command for working with the target instance collection."""

    print_spec = command_base.ResourcePrintSpec(
        summary=['name', 'instance'],
        field_mappings=(('name', 'name'), ('description',
                                           'description'), ('zone', 'zone'),
                        ('nat-policy', 'natPolicy'), ('instance', 'instance')),
        detail=(
            ('name', 'name'),
            ('description', 'description'),
            ('creation-time', 'creationTimestamp'),
            ('nat-policy', 'natPolicy'),
            ('instance', 'instance'),
        ),
        sort_by='name')

    resource_collection_name = 'targetInstances'

    DEFAULT_NAT_POLICY = 'NO_NAT'

    def __init__(self, name, flag_values):
        super(TargetInstanceCommand, self).__init__(name, flag_values)
        flags.DEFINE_string('zone',
                            None,
                            '[Required] The zone for this request.',
                            flag_values=flag_values)

    def _PrepareRequestArgs(self, target_instance_context):
        """Gets the dictionary of API method keyword arguments.

    Args:
      target_instance_context: A context dict for this target instance.

    Returns:
      Dictionary of keyword arguments that should be passed in the API call.
    """

        kwargs = {
            'project': target_instance_context['project'],
            'targetInstance': target_instance_context['targetInstance'],
            'zone': target_instance_context['zone']
        }

        return kwargs

    def _AutoDetectZone(self):
        """Instruct this command to auto detect zone instead of prompting."""
        def _GetZoneContext(object_type, context):
            if self._flags.zone:
                return self.DenormalizeResourceName(self._flags.zone)

            if object_type == 'targetInstances':
                return self.GetZoneForResource(self.api.target_instances,
                                               context['targetInstance'])

        self._context_parser.context_prompt_fxns['zone'] = _GetZoneContext

    def _GetZoneOrPrompt(self):
        """Instruct this command to get the zone from flag or by prompting."""
        if self._flags.zone is None:
            self._flags.zone = self._presenter.PromptForZone(
                self.api.zones)['name']
        return self.DenormalizeResourceName(self._flags.zone)
Пример #15
0
class ForwardingRuleCommand(command_base.GoogleComputeCommand):
  """Base command for working with the forwarding rule collection."""

  print_spec = command_base.ResourcePrintSpec(
      summary=['name', 'region', 'ip'],
      field_mappings=(
          ('name', 'name'),
          ('description', 'description'),
          ('region', 'region'),
          ('ip', 'IPAddress'),
          ('protocol', 'IPProtocol'),
          ('port-range', 'portRange'),
          ('target', 'target')),
      detail=(
          ('name', 'name'),
          ('description', 'description'),
          ('creation-time', 'creationTimestamp'),
          ('region', 'region'),
          ('ip', 'IPAddress'),
          ('protocol', 'IPProtocol'),
          ('port-range', 'portRange'),
          ('target', 'target')),
      sort_by='name')

  resource_collection_name = 'forwardingRules'

  # The default IP protocol.
  DEFAULT_IP_PROTOCOL = 'TCP'

  def __init__(self, name, flag_values):
    super(ForwardingRuleCommand, self).__init__(name, flag_values)
    flags.DEFINE_string('region',
                        None,
                        '[Required] The region for this request.',
                        flag_values=flag_values)

  def _PrepareRequestArgs(self, forwarding_rule_context):
    """Gets the dictionary of API method keyword arguments.

    Args:
      forwarding_rule_context: Context dict for a forwarding rule.

    Returns:
      Dictionary of keyword arguments that should be passed in the API call.
    """

    kwargs = {
        'project': forwarding_rule_context['project'],
        'forwardingRule': forwarding_rule_context['forwardingRule'],
        'region': forwarding_rule_context['region']
    }

    return kwargs

  def _VerifyAndGetTargetFromFlags(
      self, target_pool_flag, target_instance_flag):
    """Gets forwarding rule target from flag values.

    Args:
      target_pool_flag: the value of --target_pool flag
      target_instance_flag: the value of --target_instance flag
    Returns:
      (target_pool, target_instance) pair, with one and only one field set.
    """
    if (target_pool_flag is None) == (target_instance_flag is None):
      raise gcutil_errors.CommandError('Please specify exactly one of '
                                       '--target_pool or --target_instance.')
    elif target_pool_flag:
      return target_pool_flag, None
    else:
      if self.api.version < version.get('v1'):
        raise gcutil_errors.CommandError(
            'Version does not support target instance.')
      return None, target_instance_flag

  def _AutoDetectRegion(self):
    """Instruct this command to auto detect region instead of prompting."""
    def _GetRegionContext(object_type, context):
      if self._flags.region:
        return self.DenormalizeResourceName(self._flags.region)
      if object_type == 'forwardingRules':
        return self.GetRegionForResource(self.api.forwarding_rules,
                                         context['forwardingRule'],
                                         project=context['project'])
      elif object_type == 'targetPools':
        return self.GetRegionForResource(self.api.target_pools,
                                         context['targetPool'],
                                         project=context['project'])

    self._context_parser.context_prompt_fxns['region'] = _GetRegionContext

  def _AutoDetectRegionForTargetPoolsOnly(self):
    """Instruct this command to auto detect region for target pools only."""
    def _GetRegionContext(object_type, context):
      if self._flags.region:
        return self.DenormalizeResourceName(self._flags.region)

      if object_type == 'targetPools':
        return self.GetRegionForResource(self.api.target_pools,
                                         context['targetPool'],
                                         project=context['project'])
      else:
        return self._presenter.PromptForRegion(self.api.regions)['name']

    self._context_parser.context_prompt_fxns['region'] = _GetRegionContext

  def _AutoDetectZoneForTargetInstancesOnly(self):
    """Instruct this command to auto-detect zone for target instances only."""
    def _GetZoneContext(object_type, context):
      if object_type == 'targetInstances':
        return self.GetZoneForResource(self.api.target_instances,
                                       context['targetInstance'],
                                       project=context['project'])
      else:
        return self._presenter.PromptForZone(self.api.zones)['name']

    self._context_parser.context_prompt_fxns['zone'] = _GetZoneContext

  def _BuildForwardingRuleTarget(self):
    """Parses commandline flags and constructs a target resource.

    Returns:
      the target resource configured to receive forwarded traffic
    """
    target_pool = None
    target_instance = None
    if self._flags.target:
      gcutil_logging.LOGGER.warn(
          '--target flag is deprecated. Use --target_pool instead.')
      target_pool = self._flags.target
    else:
      target_pool, target_instance = self._VerifyAndGetTargetFromFlags(
          self._flags.target_pool, self._flags.target_instance)

    self._AutoDetectRegion()
    self._AutoDetectZoneForTargetInstancesOnly()

    if target_pool:
      return self._context_parser.NormalizeOrPrompt(
          'targetPools', target_pool)
    else:
      return self._context_parser.NormalizeOrPrompt(
          'targetInstances', target_instance)
Пример #16
0
class AddressCommand(command_base.GoogleComputeCommand):
    """Base command for working with the addresses collection."""

    print_spec = command_base.ResourcePrintSpec(
        summary=['name', 'region', 'status', 'ip'],
        field_mappings=(('name', 'name'), ('description', 'description'),
                        ('region', 'region'), ('status',
                                               'status'), ('ip', 'address')),
        detail=(('name', 'name'), ('description', 'description'),
                ('creation-time', 'creationTimestamp'), ('region', 'region'),
                ('status', 'status'), ('ip', 'address')),
        sort_by='name')

    resource_collection_name = 'addresses'

    def __init__(self, name, flag_values):
        super(AddressCommand, self).__init__(name, flag_values)

        flags.DEFINE_string('region',
                            None,
                            '[Required] The region for this request.',
                            flag_values=flag_values)

    def GetDetailRow(self, result):
        """Returns an associative list of items for display in a detail table.

    Args:
      result: A dict returned by the server.

    Returns:
      A list.
    """
        data = []
        users = []
        if 'users' in result:
            for user in result['users']:
                users.append(self.DenormalizeResourceName(user))
        data.append(('users', users))
        return data

    def _PrepareRequestArgs(self, address_context, **other_args):
        """Gets the dictionary of API method keyword arguments.

    Args:
      address_context: Context dict for this address, including region and name.
      **other_args: Keyword arguments that should be included in the request.

    Returns:
      Dictionary of keyword arguments that should be passed in the API call,
      includes all keyword arguments passed in 'other_args' plus
      common keys such as the name of the resource and the project.
    """

        kwargs = {
            'project': address_context['project'],
            'address': self.DenormalizeResourceName(address_context['address'])
        }
        if address_context['region']:
            kwargs['region'] = address_context['region']
        for key, value in other_args.items():
            kwargs[key] = value
        return kwargs

    def _AutoDetectRegion(self):
        """Instruct this command to auto detect region instead of prompting."""
        def _GetRegionContext(unused_object_type, context):
            if self._flags.region:
                return self.DenormalizeResourceName(self._flags.region)
            return self.GetRegionForResource(self.api.addresses,
                                             context['address'])

        self._context_parser.context_prompt_fxns['region'] = _GetRegionContext