Example #1
0
def CreateNetworkInterfaceMessage(
    resources, scope_lister, messages, network, region, subnet, address,
    alias_ip_ranges_string=None):
  """Creates and returns a new NetworkInterface message.

  Args:
    resources: generates resource references,
    scope_lister: function, provides scopes for prompting subnet region,
    messages: GCE API messages,
    network: network,
    region: region for subnetwork,
    subnet: regional subnetwork,
    address: specify static address for instance template
               * None - no address,
               * EPHEMERAL_ADDRESS - ephemeral address,
               * string - address name to be fetched from GCE API.
    alias_ip_ranges_string: command line string specifying a list of alias
        IP ranges.
  Returns:
    network_interface: a NetworkInterface message object
  """
  # By default interface is attached to default network. If network or subnet
  # are specified they're used instead.
  network_interface = messages.NetworkInterface()
  if subnet is not None:
    subnet_ref = subnet_flags.SubnetworkResolver().ResolveResources(
        [subnet], compute_scope.ScopeEnum.REGION, region, resources,
        scope_lister=scope_lister)[0]
    network_interface.subnetwork = subnet_ref.SelfLink()
  if network is not None:
    network_ref = resources.Parse(
        network,
        params={'project': properties.VALUES.core.project.GetOrFail},
        collection='compute.networks')
    network_interface.network = network_ref.SelfLink()
  elif subnet is None:
    network_ref = resources.Parse(
        constants.DEFAULT_NETWORK,
        params={'project': properties.VALUES.core.project.GetOrFail},
        collection='compute.networks')
    network_interface.network = network_ref.SelfLink()

  if address:
    access_config = messages.AccessConfig(
        name=constants.DEFAULT_ACCESS_CONFIG_NAME,
        type=messages.AccessConfig.TypeValueValuesEnum.ONE_TO_ONE_NAT)

    # If the user provided an external IP, populate the access
    # config with it.
    if address != EPHEMERAL_ADDRESS:
      access_config.natIP = address

    network_interface.accessConfigs = [access_config]

  if alias_ip_ranges_string:
    network_interface.aliasIpRanges = (
        alias_ip_range_utils.CreateAliasIpRangeMessagesFromString(
            messages, False, alias_ip_ranges_string))

  return network_interface
Example #2
0
def CreateNetworkInterfaceMessage(
    resources, compute_client,
    network, subnet, private_network_ip, no_address, address,
    instance_refs, alias_ip_ranges_string=None):
  """Returns a new NetworkInterface message."""
  # TODO(b/30460572): instance reference should have zone name, not zone URI.
  region = utils.ZoneNameToRegionName(instance_refs[0].zone.split('/')[-1])
  messages = compute_client.messages
  network_interface = messages.NetworkInterface()
  # By default interface is attached to default network. If network or subnet
  # are specified they're used instead.
  if subnet is not None:
    subnet_ref = resources.Parse(
        subnet,
        collection='compute.subnetworks',
        params={'region': region})
    network_interface.subnetwork = subnet_ref.SelfLink()
  if network is not None:
    network_ref = resources.Parse(network, collection='compute.networks')
    network_interface.network = network_ref.SelfLink()
  elif subnet is None:
    network_ref = resources.Parse(
        constants.DEFAULT_NETWORK, collection='compute.networks')
    network_interface.network = network_ref.SelfLink()

  if private_network_ip is not None:
    network_interface.networkIP = private_network_ip

  if alias_ip_ranges_string:
    network_interface.aliasIpRanges = (
        alias_ip_range_utils.CreateAliasIpRangeMessagesFromString(
            messages, True, alias_ip_ranges_string))

  if not no_address:
    access_config = messages.AccessConfig(
        name=constants.DEFAULT_ACCESS_CONFIG_NAME,
        type=messages.AccessConfig.TypeValueValuesEnum.ONE_TO_ONE_NAT)

    # If the user provided an external IP, populate the access
    # config with it.
    # TODO(b/25278937): plays poorly when creating multiple instances
    if len(instance_refs) == 1:
      address_resource = flags.ExpandAddressFlag(
          resources, compute_client, address, region)
      if address_resource:
        access_config.natIP = address_resource

    network_interface.accessConfigs = [access_config]

  return network_interface
Example #3
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client.apitools_client
        messages = holder.client.messages

        instance_ref = instances_flags.INSTANCE_ARG.ResolveAsResource(
            args,
            holder.resources,
            scope_lister=flags.GetDefaultScopeLister(holder.client))

        instance = client.instances.Get(
            messages.ComputeInstancesGetRequest(**instance_ref.AsDict()))
        for i in instance.networkInterfaces:
            if i.name == args.network_interface:
                fingerprint = i.fingerprint
                break
        else:
            raise exceptions.UnknownArgumentException(
                'network-interface',
                'Instance does not have a network interface [{}], '
                'present interfaces are [{}].'.format(
                    args.network_interface,
                    ', '.join([i.name for i in instance.networkInterfaces])))

        patch_network_interface = messages.NetworkInterface(
            aliasIpRanges=(
                alias_ip_range_utils.CreateAliasIpRangeMessagesFromString(
                    messages, True, args.aliases)),
            fingerprint=fingerprint)

        request = messages.ComputeInstancesUpdateNetworkInterfaceRequest(
            project=instance_ref.project,
            instance=instance_ref.instance,
            zone=instance_ref.zone,
            networkInterface=args.network_interface,
            networkInterfaceResource=patch_network_interface)

        cleared_fields = []
        if not patch_network_interface.aliasIpRanges:
            cleared_fields.append('aliasIpRanges')
        with client.IncludeFields(cleared_fields):
            operation = client.instances.UpdateNetworkInterface(request)
        operation_ref = holder.resources.Parse(
            operation.selfLink, collection='compute.zoneOperations')

        operation_poller = poller.Poller(client.instances)
        return waiter.WaitFor(
            operation_poller, operation_ref,
            'Updating network interface [{0}] of instance [{1}]'.format(
                args.network_interface, instance_ref.Name()))
def CreateNetworkInterfaceMessage(resources,
                                  compute_client,
                                  network,
                                  subnet,
                                  private_network_ip,
                                  no_address,
                                  address,
                                  instance_refs,
                                  alias_ip_ranges_string=None,
                                  network_tier=None,
                                  no_public_dns=None,
                                  public_dns=None,
                                  no_public_ptr=None,
                                  public_ptr=None,
                                  no_public_ptr_domain=None,
                                  public_ptr_domain=None):
    """Returns a new NetworkInterface message."""
    # TODO(b/30460572): instance reference should have zone name, not zone URI.
    region = utils.ZoneNameToRegionName(instance_refs[0].zone.split('/')[-1])
    messages = compute_client.messages
    network_interface = messages.NetworkInterface()
    # By default interface is attached to default network. If network or subnet
    # are specified they're used instead.
    if subnet is not None:
        subnet_ref = resources.Parse(subnet,
                                     collection='compute.subnetworks',
                                     params={
                                         'project': instance_refs[0].project,
                                         'region': region
                                     })
        network_interface.subnetwork = subnet_ref.SelfLink()
    if network is not None:
        network_ref = resources.Parse(network,
                                      params={
                                          'project': instance_refs[0].project,
                                      },
                                      collection='compute.networks')
        network_interface.network = network_ref.SelfLink()
    elif subnet is None:
        network_ref = resources.Parse(
            constants.DEFAULT_NETWORK,
            params={'project': instance_refs[0].project},
            collection='compute.networks')
        network_interface.network = network_ref.SelfLink()

    if private_network_ip is not None:
        # Try interpreting the address as IPv4 or IPv6.
        try:
            ipaddr.IPAddress(private_network_ip)
            network_interface.networkIP = private_network_ip
        except ValueError:
            # ipaddr could not resolve as an IPv4 or IPv6 address.
            network_interface.networkIP = flags.GetAddressRef(
                resources, private_network_ip, region).SelfLink()

    if alias_ip_ranges_string:
        network_interface.aliasIpRanges = (
            alias_ip_range_utils.CreateAliasIpRangeMessagesFromString(
                messages, True, alias_ip_ranges_string))

    if not no_address:
        access_config = messages.AccessConfig(
            name=constants.DEFAULT_ACCESS_CONFIG_NAME,
            type=messages.AccessConfig.TypeValueValuesEnum.ONE_TO_ONE_NAT)
        if network_tier is not None:
            access_config.networkTier = (
                messages.AccessConfig.NetworkTierValueValuesEnum(network_tier))

        # If the user provided an external IP, populate the access
        # config with it.
        # TODO(b/25278937): plays poorly when creating multiple instances
        if len(instance_refs) == 1:
            address_resource = flags.ExpandAddressFlag(resources,
                                                       compute_client, address,
                                                       region)
            if address_resource:
                access_config.natIP = address_resource

        if no_public_dns is True:
            access_config.setPublicDns = False
        elif public_dns is True:
            access_config.setPublicDns = True

        if no_public_ptr is True:
            access_config.setPublicPtr = False
        elif public_ptr is True:
            access_config.setPublicPtr = True

        if no_public_ptr_domain is not True and public_ptr_domain is not None:
            access_config.publicPtrDomainName = public_ptr_domain

        network_interface.accessConfigs = [access_config]

    return network_interface
Example #5
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client.apitools_client
        messages = holder.client.messages
        resources = holder.resources

        instance_ref = instances_flags.INSTANCE_ARG.ResolveAsResource(
            args,
            holder.resources,
            scope_lister=flags.GetDefaultScopeLister(holder.client))

        instance = client.instances.Get(
            messages.ComputeInstancesGetRequest(**instance_ref.AsDict()))
        for i in instance.networkInterfaces:
            if i.name == args.network_interface:
                fingerprint = i.fingerprint
                break
        else:
            raise exceptions.UnknownArgumentException(
                'network-interface',
                'Instance does not have a network interface [{}], '
                'present interfaces are [{}].'.format(
                    args.network_interface,
                    ', '.join([i.name for i in instance.networkInterfaces])))

        network_uri = None
        if getattr(args, 'network', None) is not None:
            network_uri = resources.Parse(
                args.network, {
                    'project': instance_ref.project
                },
                collection='compute.networks').SelfLink()

        subnetwork_uri = None
        if getattr(args, 'subnetwork', None) is not None:
            region = api_utils.ZoneNameToRegionName(instance_ref.zone)
            subnetwork_uri = resources.Parse(
                args.subnetwork, {
                    'project': instance_ref.project,
                    'region': region
                },
                collection='compute.subnetworks').SelfLink()

        stack_type = getattr(args, 'stack_type', None)
        if stack_type is not None:
            stack_type_enum = (
                messages.NetworkInterface.StackTypeValueValuesEnum(stack_type))
            ipv6_network_tier = getattr(args, 'ipv6_network_tier', None)

            ipv6_access_configs = []
            if ipv6_network_tier is not None:
                # If provide IPv6 network tier then set IPv6 access config in request.
                ipv6_access_config = messages.AccessConfig(
                    name=constants.DEFAULT_IPV6_ACCESS_CONFIG_NAME,
                    type=messages.AccessConfig.TypeValueValuesEnum.DIRECT_IPV6)
                ipv6_access_config.networkTier = (
                    messages.AccessConfig.NetworkTierValueValuesEnum(
                        ipv6_network_tier))
                ipv6_access_configs = [ipv6_access_config]
            patch_network_interface = messages.NetworkInterface(
                aliasIpRanges=(
                    alias_ip_range_utils.CreateAliasIpRangeMessagesFromString(
                        messages, True, args.aliases)),
                network=network_uri,
                subnetwork=subnetwork_uri,
                networkIP=getattr(args, 'private_network_ip', None),
                stackType=stack_type_enum,
                ipv6AccessConfigs=ipv6_access_configs,
                fingerprint=fingerprint)
        else:
            patch_network_interface = messages.NetworkInterface(
                aliasIpRanges=(
                    alias_ip_range_utils.CreateAliasIpRangeMessagesFromString(
                        messages, True, args.aliases)),
                network=network_uri,
                subnetwork=subnetwork_uri,
                networkIP=getattr(args, 'private_network_ip', None),
                fingerprint=fingerprint)

        request = messages.ComputeInstancesUpdateNetworkInterfaceRequest(
            project=instance_ref.project,
            instance=instance_ref.instance,
            zone=instance_ref.zone,
            networkInterface=args.network_interface,
            networkInterfaceResource=patch_network_interface)

        cleared_fields = []
        if not patch_network_interface.aliasIpRanges:
            cleared_fields.append('aliasIpRanges')
        with client.IncludeFields(cleared_fields):
            operation = client.instances.UpdateNetworkInterface(request)
        operation_ref = holder.resources.Parse(
            operation.selfLink, collection='compute.zoneOperations')

        operation_poller = poller.Poller(client.instances)
        return waiter.WaitFor(
            operation_poller, operation_ref,
            'Updating network interface [{0}] of instance [{1}]'.format(
                args.network_interface, instance_ref.Name()))
Example #6
0
def CreateNetworkInterfaceMessage(resources,
                                  compute_client,
                                  network,
                                  subnet,
                                  project,
                                  location,
                                  scope,
                                  nic_type=None,
                                  no_address=None,
                                  address=None,
                                  private_network_ip=None,
                                  alias_ip_ranges_string=None,
                                  network_tier=None,
                                  no_public_dns=None,
                                  public_dns=None,
                                  no_public_ptr=None,
                                  public_ptr=None,
                                  no_public_ptr_domain=None,
                                  public_ptr_domain=None,
                                  stack_type=None,
                                  ipv6_network_tier=None,
                                  ipv6_public_ptr_domain=None):
    """Returns a new NetworkInterface message."""
    # TODO(b/30460572): instance reference should have zone name, not zone URI.
    if scope == compute_scopes.ScopeEnum.ZONE:
        region = utils.ZoneNameToRegionName(location.split('/')[-1])
    elif scope == compute_scopes.ScopeEnum.REGION:
        region = location
    messages = compute_client.messages
    network_interface = messages.NetworkInterface()
    # By default interface is attached to default network. If network or subnet
    # are specified they're used instead.
    if subnet is not None:
        subnet_ref = resources.Parse(subnet,
                                     collection='compute.subnetworks',
                                     params={
                                         'project': project,
                                         'region': region
                                     })
        network_interface.subnetwork = subnet_ref.SelfLink()
    if network is not None:
        network_ref = resources.Parse(network,
                                      params={
                                          'project': project,
                                      },
                                      collection='compute.networks')
        network_interface.network = network_ref.SelfLink()
    elif subnet is None:
        network_ref = resources.Parse(constants.DEFAULT_NETWORK,
                                      params={'project': project},
                                      collection='compute.networks')
        network_interface.network = network_ref.SelfLink()

    if private_network_ip is not None:
        # Try interpreting the address as IPv4 or IPv6.
        try:
            # ipaddress only allows unicode input
            ipaddress.ip_address(six.text_type(private_network_ip))
            network_interface.networkIP = private_network_ip
        except ValueError:
            # ipaddress could not resolve as an IPv4 or IPv6 address.
            network_interface.networkIP = instances_flags.GetAddressRef(
                resources, private_network_ip, region).SelfLink()

    if nic_type is not None:
        network_interface.nicType = (
            messages.NetworkInterface.NicTypeValueValuesEnum(nic_type))

    if alias_ip_ranges_string:
        network_interface.aliasIpRanges = (
            alias_ip_range_utils.CreateAliasIpRangeMessagesFromString(
                messages, True, alias_ip_ranges_string))

    if stack_type is not None:
        network_interface.stackType = messages.NetworkInterface.StackTypeValueValuesEnum(
            stack_type)

    if not no_address:
        access_config = messages.AccessConfig(
            name=constants.DEFAULT_ACCESS_CONFIG_NAME,
            type=messages.AccessConfig.TypeValueValuesEnum.ONE_TO_ONE_NAT)
        if network_tier is not None:
            access_config.networkTier = (
                messages.AccessConfig.NetworkTierValueValuesEnum(network_tier))

        # If the user provided an external IP, populate the access
        # config with it.
        address_resource = instances_flags.ExpandAddressFlag(
            resources, compute_client, address, region)
        if address_resource:
            access_config.natIP = address_resource

        if no_public_dns:
            access_config.setPublicDns = False
        elif public_dns:
            access_config.setPublicDns = True

        if no_public_ptr:
            access_config.setPublicPtr = False
        elif public_ptr:
            access_config.setPublicPtr = True

        if not no_public_ptr_domain and public_ptr_domain is not None:
            access_config.publicPtrDomainName = public_ptr_domain

        network_interface.accessConfigs = [access_config]

    if ipv6_network_tier is not None or ipv6_public_ptr_domain is not None:
        ipv6_access_config = messages.AccessConfig(
            name=constants.DEFAULT_IPV6_ACCESS_CONFIG_NAME,
            type=messages.AccessConfig.TypeValueValuesEnum.DIRECT_IPV6)
        network_interface.ipv6AccessConfigs = [ipv6_access_config]

    if ipv6_network_tier is not None:
        ipv6_access_config.networkTier = (
            messages.AccessConfig.NetworkTierValueValuesEnum(ipv6_network_tier)
        )

    if ipv6_public_ptr_domain is not None:
        ipv6_access_config.setPublicPtr = True
        ipv6_access_config.publicPtrDomainName = ipv6_public_ptr_domain

    return network_interface
def CreateNetworkInterfaceMessage(resources,
                                  scope_lister,
                                  messages,
                                  network,
                                  private_ip,
                                  region,
                                  subnet,
                                  address,
                                  alias_ip_ranges_string=None,
                                  network_tier=None,
                                  stack_type=None,
                                  ipv6_network_tier=None):
    """Creates and returns a new NetworkInterface message.

  Args:
    resources: generates resource references,
    scope_lister: function, provides scopes for prompting subnet region,
    messages: GCE API messages,
    network: network,
    private_ip: IPv4 internal IP address to assign to the instance.
    region: region for subnetwork,
    subnet: regional subnetwork,
    address: specify static address for instance template
               * None - no address,
               * EPHEMERAL_ADDRESS - ephemeral address,
               * string - address name to be fetched from GCE API.
    alias_ip_ranges_string: command line string specifying a list of alias
        IP ranges.
    network_tier: specify network tier for instance template
               * None - no network tier
               * PREMIUM - network tier being PREMIUM
               * SELECT - network tier being SELECT
               * STANDARD - network tier being STANDARD
    stack_type: identify whether IPv6 features are enabled
               * IPV4_ONLY - can only have IPv4 address
               * IPV4_IPV6 - can have both IPv4 and IPv6 address
    ipv6_network_tier: specify network tier for IPv6 access config
               * PREMIUM - network tier being PREMIUM
               * STANDARD - network tier being STANDARD
  Returns:
    network_interface: a NetworkInterface message object
  """
    # By default interface is attached to default network. If network or subnet
    # are specified they're used instead.
    network_interface = messages.NetworkInterface()
    if subnet is not None:
        subnet_ref = subnet_flags.SubnetworkResolver().ResolveResources(
            [subnet],
            compute_scope.ScopeEnum.REGION,
            region,
            resources,
            scope_lister=scope_lister)[0]
        network_interface.subnetwork = subnet_ref.SelfLink()
    if network is not None:
        network_ref = resources.Parse(
            network,
            params={'project': properties.VALUES.core.project.GetOrFail},
            collection='compute.networks')
        network_interface.network = network_ref.SelfLink()
    elif subnet is None:
        network_ref = resources.Parse(
            constants.DEFAULT_NETWORK,
            params={'project': properties.VALUES.core.project.GetOrFail},
            collection='compute.networks')
        network_interface.network = network_ref.SelfLink()

    if private_ip is not None:
        network_interface.networkIP = private_ip

    if stack_type is not None:
        network_interface.stackType = (
            messages.NetworkInterface.StackTypeValueValuesEnum(stack_type))

    if address:
        access_config = messages.AccessConfig(
            name=constants.DEFAULT_ACCESS_CONFIG_NAME,
            type=messages.AccessConfig.TypeValueValuesEnum.ONE_TO_ONE_NAT)

        # If the user provided an external IP, populate the access
        # config with it.
        if address != EPHEMERAL_ADDRESS:
            access_config.natIP = address

        if network_tier is not None:
            access_config.networkTier = (
                messages.AccessConfig.NetworkTierValueValuesEnum(network_tier))

        network_interface.accessConfigs = [access_config]

    if ipv6_network_tier is not None:
        ipv6_access_config = messages.AccessConfig(
            name=constants.DEFAULT_IPV6_ACCESS_CONFIG_NAME,
            type=messages.AccessConfig.TypeValueValuesEnum.DIRECT_IPV6)
        ipv6_access_config.networkTier = (
            messages.AccessConfig.NetworkTierValueValuesEnum(ipv6_network_tier)
        )

        network_interface.ipv6AccessConfigs = [ipv6_access_config]

    if alias_ip_ranges_string:
        network_interface.aliasIpRanges = (
            alias_ip_range_utils.CreateAliasIpRangeMessagesFromString(
                messages, False, alias_ip_ranges_string))

    return network_interface