def TransformComponentStatus(self, record): """Print the component status of the integration. Args: record: dict, the integration. Returns: The printed output. """ resource_status = record.get('status', {}) resources = resource_status.get('resourceComponentStatuses', {}) redis = self._RedisFromResources(resources) vpc = self._VpcFromResources(resources) return cp.Labeled([ cp.Lines([ ('MemoryStore Redis ({})'.format( redis.get('name', ''))), cp.Labeled([ ('Console link', redis.get('consoleLink', 'n/a')), ('Resource Status', redis.get('state', 'n/a')), ]), ]), cp.Lines([ ('Serverless VPC Connector ({})'.format(vpc.get('name', ''))), cp.Labeled([ ('Console link', vpc.get('consoleLink', 'n/a')), ]), ]) ])
class CustomPrinterTest(test_case.TestCase): def testPrinter(self): case = cp.Lines([ 'this is a header', cp.Labeled([('Foo', 'carrot'), ('Bar', 12), ('Baz', cp.Labeled([('Fun', 'doooodles'), ('Sun', cp.Lines(['toot', 'taaat', 3]))])), ('Quux', cp.Mapped([('hundred', 'lots'), ('two', 'few')]))]) ]) s = io.StringIO() p = MockPrinter(out=s) p.AddRecord(case) self.assertEqual( s.getvalue(), textwrap.dedent("""\ this is a header Foo: carrot Bar: 12 Baz: Fun: doooodles Sun: toot taaat 3 Quux: hundred lots two few ------ """))
def _TransformTrafficPairs(traffic_pairs, service_url, service_ingress=None): """Transforms a List[TrafficTargetPair] into a marker class structure.""" traffic_section = cp.Section( [cp.Table(_TransformTrafficPair(p) for p in traffic_pairs)]) route_section = [cp.Labeled([('URL', service_url)])] if service_ingress is not None: route_section.append(cp.Labeled([('Ingress', service_ingress)])) route_section.append(cp.Labeled([('Traffic', traffic_section)])) return cp.Section(route_section, max_column_width=60)
def Transform(self, record): """Transform a service into the output structure of marker classes.""" fmt = cp.Lines([ k8s_object_printer.GetHeader(record), k8s_object_printer.GetLabels(record.labels), ' ', cp.Section([ traffic_printer.TransformTraffic(record), cp.Labeled([('Ingress', self._GetIngress(record))]), ' ', ], max_column_width=60), cp.Labeled([(k8s_object_printer.GetLastUpdated(record), self._RevisionPrinters(record))]), k8s_object_printer.GetReadyMessage(record) ]) return fmt
def GetVpcConnector(record): return cp.Labeled([ ('Name', record.annotations.get(revision.VPC_ACCESS_ANNOTATION, '')), ('Egress', record.annotations.get(revision.EGRESS_SETTINGS_ANNOTATION, '')) ])
def _RevisionPrinters(self, record): """Adds printers for the revision.""" limits = self._GetLimits(record.template) revision_properties = cp.Labeled([ ('Image', record.UserImage()), ('Command', ' '.join(record.template.container.command)), ('Args', ' '.join(record.template.container.args)), ('Port', ' '.join( six.text_type(cp.containerPort) for cp in record.template.container.ports)), ('Memory', limits['memory']), ('CPU', limits['cpu']), ('Service account', record.template.spec.serviceAccountName), ('Env vars', self._GetUserEnvironmentVariables(record)), ('Secrets', self._GetSecrets(record)), ('Config Maps', self._GetConfigMaps(record)), ('Concurrency', record.template.concurrency), ('SQL connections', self._GetCloudSqlInstances(record)), ('Timeout', self._GetTimeout(record)), ]) if self._GetVpcConnector(record): revision_properties.append( ('VPC connector', self._GetVpcConnector(record))) return cp.Lines([ self._GetRevisionHeader(record), self._GetLabels(record.template.labels), revision_properties, ])
def TransformSpec(record): limits = container_util.GetLimits(record.template) breakglass_value = k8s_util.GetBinAuthzBreakglass(record) return cp.Labeled([ ('Image', record.template.UserImage()), ('Tasks', record.task_count), ('Command', ' '.join(record.template.container.command)), ('Args', ' '.join(record.template.container.args)), ('Binary Authorization', k8s_util.GetBinAuthzPolicy(record)), # pylint: disable=g-explicit-bool-comparison # Empty breakglass string is valid, space is used to force it showing ('Breakglass Justification', ' ' if breakglass_value == '' else breakglass_value), ('Memory', limits['memory']), ('CPU', limits['cpu']), ('Task Timeout', '{}s'.format(record.template.spec.timeoutSeconds) if record.template.spec.timeoutSeconds else None), ('Max Retries', record.max_retries), ('Parallelism', record.parallelism if record.parallelism else 'No limit'), ('Service account', record.template.service_account), ('Env vars', container_util.GetUserEnvironmentVariables(record.template)), ('Secrets', container_util.GetSecrets(record.template)), ('VPC connector', k8s_util.GetVpcConnector(record)), ('SQL connections', k8s_util.GetCloudSqlInstances(record)), ])
def Transform(self, record): """Transform an integration into the output structure of marker classes.""" integration_type = record['type'] formatter = GetFormatter(integration_type) config_block = formatter.TransformConfig(record) component_block = None if 'status' in record and record['status'] is not None: component_block = formatter.TransformComponentStatus(record) if not component_block: component_block = 'Status not available' lines = [ self.Header(record), ' ', config_block, ' ', cp.Labeled([cp.Lines(['Integration Components', component_block])]), ] call_to_action = formatter.CallToAction(record) if call_to_action: lines.append(' ') lines.append(call_to_action) return cp.Lines(lines)
def Transform(self, record): """Transform a service into the output structure of marker classes.""" pairs = traffic_pair.GetTrafficTargetPairs( record.spec_traffic, record.status_traffic, record.is_managed, record.status.latestReadyRevisionName) fmt = cp.Lines([ self._GetServiceHeader(record), self._GetLabels(record.labels), record.status.url, ' ', cp.Labeled([('Traffic', cp.Mapped((p.displayPercent, p.displayRevisionId) for p in pairs))]), ' ', cp.Labeled([(self._GetLastUpdated(record), self._RevisionPrinters(record))]), self._GetReadyMessage(record) ]) return fmt
def testPrintSkipsFollowedByNoOutputMarker(self): labeled = cp.Labeled([ ('aa', 'aaa'), ('bbbb', 'bb'), ('cc', cp.Labeled([('c', )])), ('ddd', 'dd'), ]) with io.StringIO() as out: labeled.Print(out, 0, cp.ColumnWidths(row=('55555', '333'))) self.assertEqual( out.getvalue(), textwrap.dedent("""\ aa: aaa bbbb: bb ddd: dd """))
def Transform(self, record): """Transform a service into the output structure of marker classes.""" return cp.Labeled([ ('Name', record.name), ('Version', record.version), ('Description', record.description), ('Supported Components', self._ComponentTable(record)), ])
def _GetServiceSettings(self, record): """Adds service-level values.""" labels = [ cp.Labeled([('Binary Authorization', k8s_util.GetBinAuthzPolicy(record))]) ] breakglass_value = k8s_util.GetBinAuthzBreakglass(record) if breakglass_value is not None: # Show breakglass even if empty, but only if set. There's no skip_none # option so this the workaround. breakglass_label = cp.Labeled([ ('Breakglass Justification', breakglass_value), ]) breakglass_label.skip_empty = False labels.append(breakglass_label) return cp.Section(labels)
def testPrintIncludesFollowedByMarkerWithOutput(self): labeled = cp.Labeled([ ('aa', 'aaa'), ('bbbb', 'bb'), ('cc', cp.Labeled([('e', 'eee')])), ('ddd', 'dd'), ]) with io.StringIO() as out: labeled.Print(out, 0, cp.ColumnWidths(row=('55555', '333'))) self.assertEqual( out.getvalue(), textwrap.dedent("""\ aa: aaa bbbb: bb cc: e: eee ddd: dd """))
def _ConfigSections(self, record): config = record.get('spec', {}).get('config', {}) sections = [] for section_name, data in sorted(config.items()): title = _ConfigTitle(section_name) section = cp.Section( [cp.Labeled([(title, _ConfigSectionData(data))])]) sections.append(section) return sections
def _SpecSection(self, record): spec = record.get('spec', {}) return cp.Section([ cp.Labeled([ ('Type', spec.get('type', '')), ('DevKit', spec.get('devkit', '')), ('DevKit Version', spec.get('devkit-version', '')), ]) ])
def Transform(self, record): """Transform a service into the output structure of marker classes.""" fmt = cp.Lines([ self._GetServiceHeader(record), self._GetLabels(record.labels), record.status.url, ' ', traffic_printer.TransformTraffic(record), ' ', cp.Labeled([(self._GetLastUpdated(record), self._RevisionPrinters(record))]), self._GetReadyMessage(record) ]) return fmt
def testPrintIncludesSeparator(self): labeled = cp.Labeled([ ('aa', 'aaa'), ('bbbb', 'bb'), ('ccc', 'cc'), ]) with io.StringIO() as out: labeled.Print(out, 0, cp.ColumnWidths(row=('55555', '333'))) self.assertEqual(out.getvalue(), textwrap.dedent("""\ aa: aaa bbbb: bb ccc: cc """))
def Transform(self, record): """Transform a service into the output structure of marker classes.""" service_settings = self._GetServiceSettings(record) fmt = cp.Lines([ k8s_util.BuildHeader(record), k8s_util.GetLabels(record.labels), ' ', traffic_printer.TransformRouteFields(record), ' ', service_settings, (' ' if service_settings.WillPrintOutput() else ''), cp.Labeled([(k8s_util.LastUpdatedMessage(record), self._RevisionPrinters(record))]), k8s_util.FormatReadyMessage(record) ]) return fmt
def Transform(self, record): """Transform ApplicationStatus into the output structure of marker classes. Args: record: a dict object Returns: lines formatted for output """ status = record['status'] results = [ cp.Section([ cp.Labeled([('Environment', record['environment']), ('Ingress IP', status.ingress_ip)]) ]) ] if len(status.modules) == 1: results.append( cp.Section([ cp.Labeled([('Components', _ComponentTable(status.modules[0].components)) ]) ], max_column_width=25)) else: results.append( cp.Section([ cp.Labeled([('Components', _ModulesTable(status.modules))]) ], max_column_width=25)) results.append( cp.Section([ '\n', _INGRESS_EXPLANATION_TEMPLATE.format(status.ingress_ip) ])) return cp.Lines(results)
def TransformComponentStatus(self, record): """Print the component status of the integration. Args: record: dict, the integration. Returns: The printed output. """ resource_status = record.get('status', {}) resource_components = resource_status.get('resourceComponentStatuses', {}) details = resource_status.get('routerDetails', {}) return cp.Labeled([ cp.Lines([ ('Google Cloud Load Balancer ({})'.format( self._GetGCLBName(resource_components))), cp.Labeled([ ('Console link', resource_status.get('consoleLink', 'n/a')), ('Frontend', details.get('ipAddress', 'n/a')), ('SSL Certificate', self.PrintStatus(self._GetSSLStatus(resource_components))), ]), ]) ])
def Transform(self, record): """Converts the record into a custom format. Args: record: dict, contains the keys: 'description', 'example_command', and 'parameters'. Returns: custom_printer_base.Lines, formatted output for types describe command. """ lines = [ record['description'], ' ', cp.Labeled([ cp.Lines( ['Parameters', self._FormatParams(record['parameters'])]) ]), cp.Labeled([ cp.Lines( ['Example Usage', cp.Lines([record['example_command']])]) ]) ] return cp.Lines(lines)
def Transform(self, record): """Transform ComponentStatus into the output structure of marker classes. Args: record: a dict object Returns: lines formatted for output """ con = console_attr.GetConsoleAttr() component = record['status'] status = con.Colorize( pretty_print.GetReadySymbol(component.deployment_state), pretty_print.GetReadyColor(component.deployment_state)) component_url = urlparse(component.url) results = [ cp.Section([ con.Emphasize('{} Component {} in environment {}'.format( status, component.name, record['environment'])), 'Deployed at {} from commit {}\n'.format( component.deployment_time, component.commit_id) ]), cp.Section([ cp.Labeled([('Component Service(s)', cp.Lines(component.services))]), ]), cp.Section([ '\nGet more details about services using kuberun ' 'core services describe SERVICE' ]) ] if component.deployment_state == 'Ready': results.append( cp.Section([ '\nTo invoke this component, run:', ' curl {}'.format(component.url), 'OR', ' curl -H "Host: {}" {}://{}'.format( component_url.netloc, component_url.scheme, record['ingressIp']) ])) elif component.deployment_state == 'Failed': msg = '\n! Deployment failed with message: {}'.format( component.deployment_message) results.append(con.Emphasize(con.Colorize(msg, 'yellow'))) return cp.Lines(results)
def TransformSpec(record): limits = container_util.GetLimits(record) return cp.Labeled([ ('Image', record.image), ('Command', ' '.join(record.container.command)), ('Args', ' '.join(record.container.args)), ('Memory', limits['memory']), ('CPU', limits['cpu']), ('Timeout', '{}s'.format(record.spec.timeoutSeconds) if record.spec.timeoutSeconds else None), ('Max Retries', record.spec.maxRetries), ('Service account', record.service_account), ('Env vars', container_util.GetUserEnvironmentVariables(record)), ('Secrets', container_util.GetSecrets(record)), ('VPC connector', k8s_util.GetVpcConnector(record)), ('SQL connections', k8s_util.GetCloudSqlInstances(record)), ])
def TransformConfig(self, record): """Print the config of the integration. Args: record: dict, the integration. Returns: The printed output. """ res_config = record.get('config', {}).get('redis', {}).get('instance', {}) labeled = [('Memory Size GB', res_config.get('memory-size-gb'))] if 'tier' in res_config: labeled.append(('Tier', res_config.get('tier'))) if 'version' in res_config: labeled.append(('Version', res_config.get('version'))) return cp.Labeled(labeled)
def TransformComponentStatus(self, record): """Print the component status of the integration. Args: record: dict, the integration. Returns: The printed output. """ component_status = record.get('status', {}).get('resourceComponentStatuses', {}) components = [] for r in component_status: components.append( (self.PrintType(r.get('type')), '{} {}'.format(self.StatusSymbolAndColor(r.get('state')), r.get('name')))) return cp.Labeled(components)
def _FormatParam(self, param, setting): """Formats individual parameter for an integration. Example output: param1 [required]: This is a description of param1. Args: param: dict, contains keys such as 'name' and 'description' setting: str, is either 'required' or 'optional' Returns: custom_printer_base.Lines, formatted output of a singular parameter. """ return cp.Labeled([ cp.Lines([ '{} [{}]'.format(param['name'], setting), cp.Lines([param['description'], ' ']) ]) ])
def Transform(self, service_dict): """Transform a service into the output structure of marker classes. Args: service_dict: dictionary object representing a service unmarshalled from json Returns: marker class of the formatted service object. """ record = service.Service(service_dict) fmt = cp.Lines([ k8s_object_printer.FormatHeader(record), k8s_object_printer.FormatLabels(record.labels), ' ', traffic_printer.TransformRouteFields(record), ' ', cp.Labeled([(k8s_object_printer.FormatLastUpdated(record), self._RevisionPrinters(record))]), k8s_object_printer.FormatReadyMessage(record) ]) return fmt
def TransformSpec(self, record): limits = self.GetLimits(record) return cp.Labeled([ ('Image', record.UserImage()), ('Command', ' '.join(record.container.command)), ('Args', ' '.join(record.container.args)), ('Port', ' '.join( six.text_type(p.containerPort) for p in record.container.ports)), ('Memory', limits['memory']), ('CPU', limits['cpu']), ('Service account', record.spec.serviceAccountName), ('Env vars', self.GetUserEnvironmentVariables(record)), ('Secrets', self.GetSecrets(record)), ('Config Maps', self.GetConfigMaps(record)), ('Concurrency', record.concurrency), ('Min Instances', self.GetMinInstances(record)), ('Max Instances', self.GetMaxInstances(record)), ('Timeout', self.GetTimeout(record)), ])
def TransformSpec(self, record): limits = collections.defaultdict(str, record.resource_limits) return cp.Labeled([ ('Image', record.UserImage()), ('Command', ' '.join(record.container.command)), ('Args', ' '.join(record.container.args)), ('Port', ' '.join( six.text_type(p.containerPort) for p in record.container.ports)), ('Memory', limits['memory']), ('CPU', limits['cpu']), ('GPU', limits[revision.NVIDIA_GPU_RESOURCE]), ('Service account', record.spec.serviceAccountName), ('Env vars', self._GetUserEnvironmentVariables(record)), ('Secrets', self._GetSecrets(record)), ('Config Maps', self._GetConfigMaps(record)), ('Concurrency', record.concurrency), ('Initial Instances', self._GetInitInstances(record)), ('Min Instances', self._GetMinInstances(record)), ('Max Instances', self._GetMaxInstances(record)), ('Timeout', self._GetTimeout(record)), ])
def TransformConfig(self, record): """Print the config of the integration. Args: record: dict, the integration. Returns: The printed output. """ res_config = record.get('config', {}).get('router', {}) labeled = [ ('Domain', res_config.get('domain', '')), ] if 'default-route' in res_config: labeled.append(('Path', '/*')) labeled.append( ('Service', self._GetServiceName(res_config.get('default-route', {}).get('ref', '')))) for r in res_config.get('routes', []): labeled.append(('Path', ','.join(r.get('paths', '')))) labeled.append(('Service', self._GetServiceName(r.get('ref', '')))) return cp.Labeled(labeled)