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. """, }
class ListInstancesAlpha(ListInstances): """List Google Compute Engine instances present in managed instance group.""" _LIST_TABS = [ ('NAME', _InstanceName), ('ZONE', _InstanceScopeName), ('STATUS', property_selector.PropertyGetter('instanceStatus')), ('ACTION', property_selector.PropertyGetter('currentAction')), ('LAST_ERROR', property_selector.PropertyGetter('lastAttempt'))] _FIELD_TRANSFORMS = [ ('instance', path_simplifier.ScopedSuffix), ('lastAttempt', LastAttemptErrorToMessage)] @staticmethod def Args(parser): instance_groups_utils.InstanceGroupListInstancesBase.ListInstancesArgs( parser, multizonal=True) def CreateGroupReference(self, args): return self.CreateInstanceGroupReference( name=args.name, region=args.region, zone=args.zone) def GetResources(self, args): """Retrieves response with instance in the instance group.""" group_ref = self.CreateGroupReference(args) if hasattr(group_ref, 'zone'): service = self.compute.instanceGroupManagers request = service.GetRequestType(self.method)( instanceGroupManager=group_ref.Name(), zone=group_ref.zone, project=self.context['project']) elif hasattr(group_ref, 'region'): service = self.compute.regionInstanceGroupManagers request = service.GetRequestType(self.method)( instanceGroupManager=group_ref.Name(), region=group_ref.region, project=self.context['project']) errors = [] results = list(request_helper.MakeRequests( requests=[(service, self.method, request)], http=self.http, batch_url=self.batch_url, errors=errors, custom_get_requests=None)) return results, 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.ListInstancesArgs(parser, multizonal=False) 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
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)
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 AddArgs(parser, multizonal): 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 (``~''). """ if multizonal: scope_parser = parser.add_mutually_exclusive_group() utils.AddRegionFlag( scope_parser, resource_type='instance or instance group', operation_type='get named ports for', explanation=constants.REGION_PROPERTY_EXPLANATION_NO_DEFAULT) utils.AddZoneFlag( scope_parser, resource_type='instance or instance group', operation_type='get named ports for', explanation=constants.ZONE_PROPERTY_EXPLANATION_NO_DEFAULT) else: 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. """, }
def TestBadProperty(prop): with self.assertRaises(property_selector.IllegalProperty): getter = property_selector.PropertyGetter(prop) getter.Get(self.object)
def TestGetProperty(prop, expected): getter = property_selector.PropertyGetter(prop) self.assertEqual(getter.Get(self.object), expected)