Example #1
0
class ListInstances(instance_groups_utils.InstanceGroupListInstancesBase):
    """List Google Compute Engine instances present in managed instance group."""

    _LIST_TABS = [
        ('NAME', property_selector.PropertyGetter('instance')),
        ('STATUS', property_selector.PropertyGetter('instanceStatus')),
        ('ACTION', property_selector.PropertyGetter('currentAction')),
        ('LAST_ERROR', property_selector.PropertyGetter('lastAttempt'))
    ]

    _FIELD_TRANSFORMS = [('instance', path_simplifier.Name),
                         ('lastAttempt', LastAttemptErrorToMessage)]

    @property
    def service(self):
        return self.compute.instanceGroupManagers

    @property
    def resource_type(self):
        return 'instanceGroups'

    @property
    def method(self):
        return 'ListManagedInstances'

    @property
    def list_field(self):
        return 'managedInstances'

    def GetResources(self, args):
        """Retrieves response with instance in the instance group."""
        group_ref = self.CreateZonalReference(args.name, args.zone)

        request = self.service.GetRequestType(self.method)(
            instanceGroupManager=group_ref.Name(),
            zone=group_ref.zone,
            project=self.context['project'])

        errors = []
        results = list(
            request_helper.MakeRequests(requests=[(self.service, self.method,
                                                   request)],
                                        http=self.http,
                                        batch_url=self.batch_url,
                                        errors=errors,
                                        custom_get_requests=None))

        return results, errors

    detailed_help = {
        'brief':
        'List instances present in the managed instance group',
        'DESCRIPTION':
        """\
          *{command}* list instances in a managed instance group.
          """,
    }
Example #2
0
def GetSpec(resource_type, message_classes, api_version):
  """Returns a Spec for the given resource type."""
  spec = _GetSpecsForVersion(api_version)

  if resource_type not in spec:
    raise KeyError('"%s" not found in Specs for version "%s"' %
                   (resource_type, api_version))

  spec = spec[resource_type]

  table_cols = []
  for name, action in spec.table_cols:
    if isinstance(action, basestring):
      table_cols.append((name, property_selector.PropertyGetter(action)))
    elif callable(action):
      table_cols.append((name, action))
    else:
      raise ValueError('expected function or property in table_cols list: {0}'
                       .format(spec))

  message_class = getattr(message_classes, spec.message_class_name)
  fields = list(_ProtobufDefinitionToFields(message_class))
  return Spec(message_class=message_class,
              fields=fields,
              table_cols=table_cols,
              transformations=spec.transformations,
              editables=spec.editables)
Example #3
0
  def Run(self, args):
    """Yields JSON-serializable dicts of resources or self links."""
    # Data structures used to perform client-side filtering of
    # resources by their names and/or URIs.
    self.self_links = set()
    self.names = set()
    self.resource_refs = []

    if args.uri:
      field_selector = None
    else:
      # The field selector should be constructed before any resources
      # are fetched, so if there are any syntactic errors with the
      # fields, we can fail fast.
      field_selector = property_selector.PropertySelector(
          properties=None,
          transformations=self.transformations)

    if args.sort_by:
      if args.sort_by.startswith('~'):
        sort_by = args.sort_by[1:]
        descending = True
      else:
        sort_by = args.sort_by
        descending = False

      for col_name, path in self._resource_spec.table_cols:
        if sort_by == col_name:
          sort_by = path
          break

      if isinstance(sort_by, property_selector.PropertyGetter):
        property_getter = sort_by
      else:
        property_getter = property_selector.PropertyGetter(sort_by)
      sort_key_fn = property_getter.Get

    else:
      sort_key_fn = None
      descending = False

    errors = []

    self.PopulateResourceFilteringStructures(args)
    items = self.FilterResults(args, self.GetResources(args, errors))
    items = lister.ProcessResults(
        resources=items,
        field_selector=field_selector,
        sort_key_fn=sort_key_fn,
        reverse_sort=descending,
        limit=args.limit)

    for item in items:
      if args.uri:
        yield item['selfLink']
      else:
        yield item

    if errors:
      utils.RaiseToolException(errors)
class InstanceGroupListInstances(InstanceGroupListInstancesBase):
    """List Google Compute Engine instances present in instance group."""

    _LIST_TABS = [('NAME', property_selector.PropertyGetter('instance')),
                  ('STATUS', property_selector.PropertyGetter('status'))]

    _FIELD_TRANSFORMS = [('instance', path_simplifier.Name)]

    @staticmethod
    def Args(parser):
        InstanceGroupListInstancesBase.Args(parser)
        regexp = parser.add_argument(
            '--regexp',
            '-r',
            help='A regular expression to filter the names of the results on.')
        regexp.detailed_help = """\
        A regular expression to filter the names of the results on. Any names
        that do not match the entire regular expression will be filtered out.
        """

    def GetResources(self, args):
        """Retrieves response with instance in the instance group."""
        group_ref = self.CreateZonalReference(args.name, args.zone)

        if args.regexp:
            filter_expr = 'instance eq {0}'.format(args.regexp)
        else:
            filter_expr = None

        request = self.service.GetRequestType(self.method)(
            instanceGroup=group_ref.Name(),
            instanceGroupsListInstancesRequest=(
                self.messages.InstanceGroupsListInstancesRequest()),
            zone=group_ref.zone,
            filter=filter_expr,
            project=self.context['project'])

        errors = []
        results = list(
            request_helper.MakeRequests(requests=[(self.service, self.method,
                                                   request)],
                                        http=self.http,
                                        batch_url=self.batch_url,
                                        errors=errors,
                                        custom_get_requests=None))

        return results, errors
Example #5
0
class InstanceGroupGetNamedPorts(base_classes.BaseCommand):
  """Get named ports in Google Compute Engine instance groups."""

  _COLUMNS = [
      ('NAME', property_selector.PropertyGetter('name')),
      ('PORT', property_selector.PropertyGetter('port'))]

  @staticmethod
  def Args(parser):
    parser.add_argument(
        'name',
        help='The name of the instance group.')

    parser.add_argument(
        '--limit',
        type=arg_parsers.BoundedInt(1, sys.maxint),
        help='The maximum number of results.')

    sort_by = parser.add_argument(
        '--sort-by',
        help='A field to sort by.')
    sort_by.detailed_help = """\
        A field to sort by. To perform a descending-order sort, prefix
        the value of this flag with a tilde (``~'').
        """

    utils.AddZoneFlag(
        parser,
        resource_type='instance or instance group',
        operation_type='get named ports for')

  @property
  def service(self):
    return self.compute.instanceGroups

  @property
  def resource_type(self):
    return 'instanceGroups'

  @property
  def method(self):
    return 'GetNamedPorts'

  def Run(self, args):
    field_selector = property_selector.PropertySelector(
        properties=None,
        transformations=[])

    sort_key_fn, descending = GetSortKey(args.sort_by, self._COLUMNS)
    responses, errors = self._GetResources(args)
    if errors:
      utils.RaiseToolException(errors)
    return lister.ProcessResults(
        resources=list(_UnwrapResponse(responses, 'namedPorts')),
        field_selector=field_selector,
        sort_key_fn=sort_key_fn,
        reverse_sort=descending,
        limit=args.limit)

  def _GetResources(self, args):
    """Retrieves response with named ports."""
    group_ref = self.CreateZonalReference(args.name, args.zone)
    request = self.service.GetRequestType('Get')(
        instanceGroup=group_ref.Name(),
        zone=group_ref.zone,
        project=self.project)

    errors = []
    results = list(request_helper.MakeRequests(
        requests=[(self.service, 'Get', request)],
        http=self.http,
        batch_url=self.batch_url,
        errors=errors,
        custom_get_requests=None))

    return results, errors

  def Display(self, args, resources):
    base_classes.PrintTable(resources, self._COLUMNS)

  detailed_help = {
      'brief': 'Lists the named ports for an instance group resource',
      'DESCRIPTION': """\
          Named ports are key:value pairs metadata representing
          the service name and the port that it's running on. Named ports
          can be assigned to an instance group, which indicates that the service
          is available on all instances in the group. This information is used
          by the HTTP Load Balancing service.

          *{command}* lists the named ports (name and port tuples)
          for an instance group.
          """,
      'EXAMPLES': """\
          For example, to list named ports for an instance group:

            $ {command} example-instance-group --zone us-central1-a

          The above example lists named ports assigned to an instance
          group named 'example-instance-group' in the ``us-central1-a'' zone.
          """,
  }