def _TransformGclbTargets(targets, undefined=''):
  r"""Transforms GclbTargets to more compact form.

  It uses following format: IP_1:port_1\nIP_2:port_2\n...IP_n:port_n.

  Args:
    targets: GclbTargets API representation.
    undefined: str, value to be returned if no IP:port pair is found.

  Returns:
    String representation to be shown in table view.
  """
  if not targets:
    return undefined
  result = []
  for target in targets:
    ip_configs = resource_transform.GetKeyValue(target, 'ipConfigs', None)
    if ip_configs is None:
      return undefined
    for ip_config in ip_configs:
      ip_address = resource_transform.GetKeyValue(ip_config, 'ipAddress', None)
      ports = resource_transform.GetKeyValue(ip_config, 'ports', None)
      if ip_address is None or ports is None:
        continue
      for port in ports:
        result.append('{}:{}'.format(ip_address, port))
  return '\n'.join(result) if result else undefined
Esempio n. 2
0
def TransformOperationHttpStatus(r, undefined=''):
    """Returns the HTTP response code of an operation.

  Args:
    r: JSON-serializable object.
    undefined: Returns this value if there is no response code.

  Returns:
    The HTTP response code of the operation in r.
  """
    if resource_transform.GetKeyValue(r, 'status', None) == 'DONE':
        return (resource_transform.GetKeyValue(r, 'httpErrorStatusCode', None)
                or 200)  # httplib.OK
    return undefined
Esempio n. 3
0
def TransformStatus(r, undefined=''):
    """Returns the machine status with deprecation information if applicable.

  Args:
    r: JSON-serializable object.
    undefined: Returns this value if the resource cannot be formatted.

  Returns:
    The machine status in r with deprecation information if applicable.
  """
    status = resource_transform.GetKeyValue(r, 'status', None)
    deprecated = resource_transform.GetKeyValue(r, 'deprecated', '')
    if deprecated:
        return '{0} ({1})'.format(status, deprecated.get('state', ''))
    return status or undefined
Esempio n. 4
0
    def _GetJsonValueForKey(self, json_object, key_path):
        """Extracts the value from a Json like object for a given key.

    Uses core.resource filter expressions to identify object sub-structure to be
    returned. If path is empty returns the entire json_object.

    Args:
      json_object: {}, The json object.
      key_path: str, The dotted path of attributes to extract.

    Raises:
      AttributeError: If the attribute doesn't exist on the object.

    Returns:
      The desired attribute or None if any of the parent attributes were
      None.
    """
        if not key_path:
            return json_object

        value = resource_transform.GetKeyValue(json_object,
                                               key_path,
                                               undefined=Assertion.ABSENT)
        if value is Assertion.ABSENT:
            raise AttributeError(
                'Attribute path [{}] not found on type [{}]'.format(
                    key_path, json_object))

        return value
Esempio n. 5
0
  def Extract(self, json_data, resource_ref_resolver):
    resource_id = resource_transform.GetKeyValue(json_data, self._field)
    if resource_id is None:
      raise Error(
          'Unable to extract resource reference for field: [{}] from data: [{}]'
          .format(self._field, json_data))

    if self._basename:
      resource_id = os.path.basename(resource_id)
    resource_ref_resolver.SetExtractedId(self._reference, resource_id)
Esempio n. 6
0
def TransformVpnTunnelGateway(vpn_tunnel, undefined=''):
  """Returns the gateway for the specified VPN tunnel resource if applicable.

  Args:
    vpn_tunnel: JSON-serializable object of a VPN tunnel.
    undefined: Returns this value if the resource cannot be formatted.

  Returns:
    The VPN gateway information in the VPN tunnel object.
  """
  target_vpn_gateway = resource_transform.GetKeyValue(vpn_tunnel,
                                                      'targetVpnGateway', None)
  if target_vpn_gateway is not None:
    return target_vpn_gateway

  vpn_gateway = resource_transform.GetKeyValue(vpn_tunnel, 'vpnGateway', None)
  if vpn_gateway is not None:
    return vpn_gateway

  return undefined
Esempio n. 7
0
def TransformImageAlias(r, undefined=''):
  """Returns a comma-separated list of alias names for an image.

  Args:
    r: JSON-serializable object.
    undefined: Returns this value if the resource cannot be formatted.

  Returns:
    A comma-separated list of alias names for the image in r.
  """
  name = resource_transform.GetKeyValue(r, 'name', None)
  if name is None:
    return undefined
  project = resource_transform.TransformScope(
      resource_transform.GetKeyValue(r, 'selfLink', ''),
      'projects').split('/')[0]
  aliases = [alias for alias, value in constants.IMAGE_ALIASES.items()
             if name.startswith(value.name_prefix)
             and value.project == project]
  return ','.join(aliases)
Esempio n. 8
0
def TransformZone(r, undefined=''):
  """Returns a zone name from a selfLink.

  Args:
    r: JSON-serializable object.
    undefined: Returns this value if the resource cannot be formatted.

  Returns:
    A zone name for selfLink from r.
  """
  project = resource_transform.TransformScope(
      resource_transform.GetKeyValue(r, 'selfLink', ''), 'zones').split('/')[0]
  return project or undefined
Esempio n. 9
0
def TransformQuota(r, undefined=''):
    """Formats a quota as usage/limit.

  Args:
    r: JSON-serializable object.
    undefined: Returns this value if the resource cannot be formatted.

  Returns:
    The quota in r as usage/limit.
  """
    usage = resource_transform.GetKeyValue(r, 'usage', None)
    if usage is None:
        return undefined
    limit = resource_transform.GetKeyValue(r, 'limit', None)
    if limit is None:
        return undefined
    try:
        if usage == int(usage) and limit == int(limit):
            return '{0}/{1}'.format(int(usage), int(limit))
        return '{0:.2f}/{1:.2f}'.format(usage, limit)
    except (TypeError, ValueError):
        pass
    return undefined
Esempio n. 10
0
def TransformLocation(r, undefined=''):
    """Return the region or zone name.

  Args:
    r: JSON-serializable object.
    undefined: Returns this value if the resource cannot be formatted.

  Returns:
    The region or zone name.
  """
    for scope in ('zone', 'region'):
        location = resource_transform.GetKeyValue(r, scope, None)
        if location:
            return resource_transform.TransformBaseName(location, undefined)
    return undefined
Esempio n. 11
0
def TransformFirewallRule(r, undefined=''):
    """Returns a compact string describing a firewall rule.

  The compact string is a comma-separated list of PROTOCOL:PORT_RANGE items.
  If a particular protocol has no port ranges then only the protocol is listed.

  Args:
    r: JSON-serializable object.
    undefined: Returns this value if the resource cannot be formatted.

  Returns:
    A compact string describing the firewall rule in r.
  """
    protocol = resource_transform.GetKeyValue(r, 'IPProtocol', None)
    if protocol is None:
        return undefined
    rule = []
    port_ranges = resource_transform.GetKeyValue(r, 'ports', None)
    try:
        for port_range in port_ranges:
            rule.append('{0}:{1}'.format(protocol, port_range))
    except TypeError:
        rule.append(protocol)
    return ','.join(rule)