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)
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 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')), ]), ]) ])
def Transform(self, record): """Transform a service into the output structure of marker classes.""" sections = [ self._Header(record), self._SpecSection(record), ] + self._ConfigSections(record) return cp.Lines(_Spaced(sections))
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 _RevisionPrinters(self, record): """Adds printers for the revision.""" return cp.Lines([ self._GetRevisionHeader(record), k8s_object_printer.FormatLabels(record.template.labels), revision_printer.RevisionPrinter().TransformSpec(record.template), ])
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 Transform(self, record): """Transform a job into the output structure of marker classes.""" return cp.Lines([ k8s_util.BuildHeader(record), self.TransformStatus(record), ' ', self.TransformSpec(record), k8s_util.FormatReadyMessage(record) ])
def Transform(self, record): """Transform a revision into the output structure of marker classes.""" fmt = cp.Lines([ k8s_object_printer.GetHeader(record), k8s_object_printer.GetLabels(record.labels), ' ', self.TransformSpec(record), k8s_object_printer.GetReadyMessage(record) ]) return fmt
def Transform(self, record): """Transform a service into the output structure of marker classes.""" fmt = cp.Lines([ self._GetHeader(record), self._GetLabels(record.labels), ' ', self.TransformSpec(record), self._GetReadyMessage(record) ]) return fmt
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 _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 TransformStatus(record): if record.status is None: return '' lines = [ 'Executed {}'.format( _PluralizedWord('time', record.status.executionCount)) ] if record.status.latestCreatedExecution is not None: lines.append('Last executed {} with execution {}'.format( record.status.latestCreatedExecution.creationTimestamp, record.status.latestCreatedExecution.name)) return cp.Lines(lines)
def TransformStatus(record): if record.status is None: return '' lines = [] if record.ready_condition['status'] is None: lines.append('{} currently running'.format( _PluralizedWord('task', record.status.runningCount))) lines.append('{} completed successfully'.format( _PluralizedWord('task', record.status.succeededCount))) if record.status.failedCount is not None and record.status.failedCount > 0: lines.append('{} failed to complete'.format( _PluralizedWord('task', record.status.failedCount))) return cp.Lines(lines)
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 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 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 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 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 _FormatParams(self, params): """Formats all the required and optional parameters for an integration. Required parameters should come before optional parameters as defined in the PRD. Args: params: describe.Params. Class contains a list of required and optional params. Returns: custom_printer_base.Lines, formatted output of all the parameters. """ formatted = [] for param in params.required: formatted.append(self._FormatParam(param, 'required')) for param in params.optional: formatted.append(self._FormatParam(param, 'optional')) return cp.Lines(formatted)
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 _SpecSection(self, record): return cp.Section( [cp.Labeled([('Refs', cp.Lines(record['spec']['refs']))])])
with io.StringIO() as out: p = MockPrinter(out=out) p.AddRecord('') self.assertEqual(out.getvalue(), textwrap.dedent("""\ ------ """)) def testPrinterAlignsTablesInLines(self): case = cp.Lines([ 'title', cp.Table([ ('aaa', 'bbbbbbbb', 'c'), ('a', 'bb', 'ccc'), ]), 'middle', cp.Table([ ('a', 'b', 'c'), ('a', 'b', 'c'), ]), 'end', ]) with io.StringIO() as out: p = MockPrinter(out=out) p.AddRecord(case) self.assertEqual( out.getvalue(), textwrap.dedent("""\ title aaa bbbbbbbb c a bb ccc
def _FormatRowTable(self, resp): """Formats rows in a [QueryAssetsResponse]'s queryResults into a table. Args: resp: The [QueryAssetsResponse] that contains 0 or more rows. Returns: A 'Lines' custom printer object that corresponds to the formatted table when printed out. The response.queryResult.rows in response: { "jobReference": "CiBqb2JfdDR2SFgwa3BPNFpQVDFudVJJaW5TdVNfS1N0YxIBAxjH8ZmAo6qckik", "done": true, "queryResult": { "rows": [ { "f": [ { "v": "//cloudresourcemanager.googleapis.com/folders/417243649856" } ] } ], "schema": { "fields": [ { "field": "name", "type": "STRING", "mode": "NULLABLE" } ] }, "total_rows": 1 } } Will return a custom printer Lines object holding the following string: ┌────────────────────────────────────────────────────────────┐ │ name │ ├────────────────────────────────────────────────────────────┤ │ //cloudresourcemanager.googleapis.com/folders/417243649856 │ └────────────────────────────────────────────────────────────┘ """ # pylint: enable=line-too-long # Used to catch and stop the unexpected secondary call of the # Display() function with invalid data. if not hasattr(resp, 'queryResult') or not hasattr( resp.queryResult, 'schema'): return None schema = resp.queryResult.schema rows = resp.queryResult.rows row_list = [] # Create a list of base-level schema keys, # and populate the table formatting string used by printer at the same time. if not schema.fields: # Received an empty schema, nothing to process. return None schemabuf = io.StringIO() schemabuf.write('table[box]({})'.format(', '.join( '{}:label={}'.format(field.field, field.field) for field in schema.fields))) for row in rows: # Convert from 'f' 'v' key:value representations to an appropriate struct # to pass to ConvertFromFV() row_json = extra_types.encoding.MessageToPyValue(row) schema_json = extra_types.encoding.MessageToPyValue(schema) row_list.append(self._ConvertFromFV(schema_json, row_json, False)) raw_out = io.StringIO() resource_printer.Print(row_list, schemabuf.getvalue(), out=raw_out) # cp.Lines simply tells the custom printer to print the provided # strings as is with no modification. return cp.Lines([raw_out.getvalue()])
def TransformStatus(record): return cp.Lines(['Running state: {}'.format(record.running_state)])
def _TransformTrafficPair(pair): """Transforms a single TrafficTargetPair into a marker class structure.""" console = console_attr.GetConsoleAttr() return (pair.displayPercent, console.Emphasize(pair.displayRevisionId), pair.displayTags, cp.Lines(pair.urls))
def _ConfigSectionData(data): if isinstance(data, list): # These items are rendered with a line of space between them because # otherwise it is hard to tell that the items are distinct. return cp.Lines(_Spaced([_ConfigItem(item) for item in data])) return _ConfigItem(data)