Esempio n. 1
0
class ImageCommand(command_base.GoogleComputeCommand):
  """Base command for working with the images collection."""

  print_spec = command_base.ResourcePrintSpec(
      summary=(
          ('name', 'name'),
          ('description', 'description'),
          ('creation-time', 'creationTimestamp'),
          ('kernel', 'preferredKernel'),
          ('deprecation', 'deprecated.state')),
      detail=(
          ('name', 'name'),
          ('description', 'description'),
          ('creation-time', 'creationTimestamp'),
          ('kernel', 'preferredKernel'),
          ('deprecation', 'deprecated.state'),
          ('replacement', 'deprecated.replacement')),
      sort_by='name')

  resource_collection_name = 'images'

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

  def SetApi(self, api):
    """Set the Google Compute Engine API for the command.

    Args:
      api: The Google Compute Engine API used by this command.

    Returns:
      None.
    """
    self._images_api = api.images()
    self._kernels_api = api.kernels()
Esempio n. 2
0
class NetworkCommand(command_base.GoogleComputeCommand):
    """Base command for working with the networks collection."""

    print_spec = command_base.ResourcePrintSpec(
        summary=(('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)

    def SetApi(self, api):
        """Set the Google Compute Engine API for the command.

    Args:
      api: The Google Compute Engine API used by this command.

    Returns:
      None.

    """
        self._networks_api = api.networks()
Esempio n. 3
0
class SnapshotCommand(command_base.GoogleComputeCommand):
  """Base command for working with the snapshots collection."""

  print_spec = command_base.ResourcePrintSpec(
      summary=(
          ('name', 'name'),
          ('description', 'description'),
          ('creation-time', 'creationTimestamp'),
          ('status', 'status'),
          ('disk-size-gb', 'diskSizeGb'),
          ('source-disk', 'sourceDisk')),
      detail=(
          ('name', 'name'),
          ('description', 'description'),
          ('creation-time', 'creationTimestamp'),
          ('status', 'status'),
          ('disk-size-gb', 'diskSizeGb'),
          ('source-disk', 'sourceDisk')),
      sort_by='name')

  resource_collection_name = 'snapshots'

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

  def SetApi(self, api):
    """Set the Google Compute Engine API for the command.

    Args:
      api: The Google Compute Engine API used by this command.

    Returns:
      None.

    """
    self._snapshots_api = api.snapshots()
    self._disks_api = api.disks()
    self._zones_api = api.zones()

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

    Args:
      snapshot_name: The name of the 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': self._project,
        'snapshot': self.DenormalizeResourceName(snapshot_name)
    }
    for key, value in other_args.items():
      kwargs[key] = value
    return kwargs
Esempio n. 4
0
class DiskCommand(command_base.GoogleComputeCommand):
    """Base command for working with the disks collection."""

    print_spec = command_base.ResourcePrintSpec(
        summary=(('name', 'name'), ('description', 'description'),
                 ('zone', 'zone'), ('status', 'status'),
                 ('source-snapshot', 'sourceSnapshot'), ('size-gb', 'sizeGb')),
        detail=(('name', 'name'), ('description', 'description'),
                ('creation-time',
                 'creationTimestamp'), ('zone', 'zone'), ('status', 'status'),
                ('source-snapshot', 'sourceSnapshot'), ('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 SetApi(self, api):
        """Set the Google Compute Engine API for the command.

    Args:
      api: The Google Compute Engine API used by this command.

    Returns:
      None.

    """
        self._disks_api = api.disks()
        self._zones_api = api.zones()

    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.
    """

        kwargs = {
            'project': self._project,
            'disk': self.DenormalizeResourceName(disk_name)
        }
        if self._IsUsingAtLeastApiVersion('v1beta14') and self._flags.zone:
            kwargs['zone'] = self._flags.zone
        for key, value in other_args.items():
            kwargs[key] = value
        return kwargs
Esempio n. 5
0
class ZoneCommand(command_base.GoogleComputeCommand):
    """Base command for working with the zones collection."""

    print_spec = command_base.ResourcePrintSpec(
        summary=(('name', 'name'), ('description', 'description'),
                 ('status', 'status'), ('next-maintenance-window',
                                        'next_maintenance_window'),
                 ('deprecation', 'deprecated.state')),
        detail=(('name', 'name'), ('description', 'description'),
                ('creation-time', 'creationTimestamp'), ('status', 'status'),
                ('deprecation', 'deprecated.state'),
                ('replacement', 'deprecated.replacement')),
        sort_by='name')

    print_spec_v1beta14 = command_base.ResourcePrintSpec(
        summary=(('name', 'name'), ('description', 'description'),
                 ('status', 'status'), ('deprecation', 'deprecated.state'),
                 ('next-maintenance-window', 'next_maintenance_window'),
                 ('instances-usage', 'instances'), ('cpus-usage', 'cpus'),
                 ('disks-usage', 'disks'), ('disks-total-gb-usage',
                                            'disks_total_gb')),
        detail=(('name', 'name'), ('description', 'description'),
                ('creation-time', 'creationTimestamp'), ('status', 'status'),
                ('deprecation', 'deprecated.state'),
                ('replacement', 'deprecated.replacement')),
        sort_by='name')

    def SetApi(self, api):
        """Set the Google Compute Engine API for the command.

    Args:
      api: The Google Compute Engine API used by this command.

    Returns:
      None.
    """
        self._zones_api = api.zones()

    def GetPrintSpec(self):
        if self._IsUsingAtLeastApiVersion('v1beta14'):
            return self.print_spec_v1beta14
        else:
            return self.print_spec
Esempio n. 6
0
class FirewallCommand(command_base.GoogleComputeCommand):
  """Base command for working with the firewalls collection."""

  print_spec = command_base.ResourcePrintSpec(
      summary=(
          ('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 SetApi(self, api):
    """Set the Google Compute Engine API for the command.

    Args:
      api: The Google Compute Engine API used by this command.

    Returns:
      None.

    """
    self._firewalls_api = api.firewalls()

  def CustomizePrintResult(self, result, table):
    """Customized result printing for this type.

    Args:
      result: json dictionary returned by the server
      table: the pretty printing table to be customized

    Returns:
      None.

    """
    # Add the rules
    for allowed in result.get('allowed', []):
      as_string = str(allowed['IPProtocol'])
      if allowed.get('ports'):
        as_string += ': %s' % ', '.join(allowed['ports'])
      table.AddRow(('allowed', as_string))
Esempio n. 7
0
class MachineTypeCommand(command_base.GoogleComputeCommand):
  """Base command for working with the machine types collection."""

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

  resource_collection_name = 'machineTypes'

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

  def SetApi(self, api):
    """Set the Google Compute Engine API for the command.

    Args:
      api: The Google Compute Engine API used by this command.

    Returns:
      None.

    """
    self._machine_type_api = api.machineTypes()
Esempio n. 8
0
class ProjectCommand(command_base.GoogleComputeCommand):
  """Base command for working with the projects collection."""

  print_spec = command_base.ResourcePrintSpec(
      summary=(
          ('name', 'name'),
          ('description', 'description'),
          ('creation-time', 'creationTimestamp')),
      detail=(
          ('name', 'name'),
          ('description', 'description'),
          ('creation-time', 'creationTimestamp')),
      sort_by='name')

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

  def SetApi(self, api):
    """Set the Google Compute Engine API for the command.

    Args:
      api: The Google Compute Engine API used by this command.

    Returns:
      None.

    """
    self._projects_api = api.projects()

  def CustomizePrintResult(self, result, table):
    """Customized result printing for this type.

    Args:
      result: json dictionary returned by the server
      table: the pretty printing table to be customized

    Returns:
      None.
    """
    # Add the IP addresses
    ips = [ipaddr.IPv4Address(ip) for ip
           in result.get('externalIpAddresses', [])]
    blocks = sorted(ipaddr.collapse_address_list(ips))
    table.AddRow(('', ''))
    table.AddRow(('ips', ''))
    table.AddRow(('  count', len(ips)))
    if blocks:
      table.AddRow(('  blocks', blocks[0]))
      for block in blocks[1:]:
        table.AddRow(('', block))

    # Add the quotas
    table.AddRow(('', ''))
    table.AddRow(('usage', ''))
    for quota in result.get('quotas', []):
      table.AddRow(('  %s' % quota['metric'].lower().replace('_', '-'),
                    '%s/%s' % (str(quota['usage']), str(quota['limit']))))
    # Add the metadata
    if result.get('commonInstanceMetadata', []):
      table.AddRow(('', ''))
      table.AddRow(('common-instance-metadata', ''))
      metadata_container = result.get('commonInstanceMetadata', [])
      if 'kind' in metadata_container:
        metadata_container = metadata_container.get('items', [])
      for metadata_entry in metadata_container:
        table.AddRow(('  %s' % metadata_entry.get('key', ''),
                      self._PresentElement(metadata_entry.get('value', ''))))