Exemple #1
0
def AddMeshArgsToMetadata(args):
  """Inserts the Mesh mode arguments provided by the user to the instance metadata.

  Args:
      args: argparse.Namespace, An object that contains the values for the
        arguments specified in the .Args() method.
  """
  if getattr(args, 'mesh', False):
    instance_templates_flags.ValidateMeshModeFlags(args)

    mesh_mode_config = collections.OrderedDict()

    # add --mesh flag data to metadata.
    mesh_mode_config['mode'] = args.mesh['mode']
    if 'workload-ports' in args.mesh:
      # convert list of strings to list of integers.
      workload_ports = list(map(int, args.mesh['workload-ports'].split(';')))
      # find unique ports by converting list of integers to set of integers.
      unique_workload_ports = set(workload_ports)
      # convert it back to list of integers.
      # this is done to make it JSON serializable.
      workload_ports = list(unique_workload_ports)
      mesh_mode_config['service'] = {
          'workload-ports': workload_ports,
      }

    # add --mesh_labels flag to metadata as described by go/gce-envoy-gcloud
    if getattr(args, 'mesh_labels', False):
      mesh_mode_config['labels'] = args.mesh_labels

    # add --mesh-proxy-config flag to metadata
    # as described by go/gce-envoy-gcloud
    if getattr(args, 'mesh_proxy_config', False):
      mesh_mode_config['proxy-spec'] = {
          'trafficdirector-config': args.mesh_proxy_config
      }

    if args.mesh['mode'] == mesh_mode_aux_data.MeshModes.ON:
      if 'startup-script' not in args.metadata:
        args.metadata['startup-script'] = mesh_mode_aux_data.startup_script
      else:
        args.metadata['startup-script'] = (
            mesh_mode_aux_data.startup_script + '\n' +
            args.metadata['startup-script'][mesh_mode_aux_data.shebang_len:])

      args.metadata['enable-guest-attributes'] = 'TRUE'

    args.metadata['gce-mesh'] = json.dumps(mesh_mode_config)
Exemple #2
0
def _RunCreate(compute_api,
               args,
               support_source_instance,
               support_kms=False,
               support_min_node_cpu=False,
               support_confidential_compute=False,
               support_location_hint=False,
               support_private_ipv6_google_access=False):
    """Common routine for creating instance template.

  This is shared between various release tracks.

  Args:
      compute_api: The compute api.
      args: argparse.Namespace, An object that contains the values for the
        arguments specified in the .Args() method.
      support_source_instance: indicates whether source instance is supported.
      support_kms: Indicate whether KMS is integrated or not.
      support_min_node_cpu: Indicate whether the --min-node-cpu flag for
        sole tenancy overcommit is supported.
      support_confidential_compute: Indicate whether confidential compute is
        supported.
      support_location_hint: Indicate whether location hint is supported.
      support_private_ipv6_google_access: Indicate whether private ipv6 google
        access is supported.

  Returns:
      A resource object dispatched by display.Displayer().
  """
    _ValidateInstancesFlags(args, support_kms=support_kms)
    instances_flags.ValidateNetworkTierArgs(args)

    instance_templates_flags.ValidateMeshModeFlags(args)

    client = compute_api.client

    boot_disk_size_gb = utils.BytesToGb(args.boot_disk_size)
    utils.WarnIfDiskSizeIsTooSmall(boot_disk_size_gb, args.boot_disk_type)

    instance_template_ref = (Create.InstanceTemplateArg.ResolveAsResource(
        args, compute_api.resources))

    AddScopesForMeshMode(args)
    AddMeshArgsToMetadata(args)

    metadata = metadata_utils.ConstructMetadataMessage(
        client.messages,
        metadata=args.metadata,
        metadata_from_file=args.metadata_from_file)

    if hasattr(args, 'network_interface') and args.network_interface:
        network_interfaces = (
            instance_template_utils.CreateNetworkInterfaceMessages)(
                resources=compute_api.resources,
                scope_lister=flags.GetDefaultScopeLister(client),
                messages=client.messages,
                network_interface_arg=args.network_interface,
                region=args.region)
    else:
        network_tier = getattr(args, 'network_tier', None)
        network_interfaces = [
            instance_template_utils.CreateNetworkInterfaceMessage(
                resources=compute_api.resources,
                scope_lister=flags.GetDefaultScopeLister(client),
                messages=client.messages,
                network=args.network,
                private_ip=args.private_network_ip,
                region=args.region,
                subnet=args.subnet,
                address=(instance_template_utils.EPHEMERAL_ADDRESS
                         if not args.no_address and not args.address else
                         args.address),
                network_tier=network_tier)
        ]

    # Compute the shieldedInstanceConfig message.
    shieldedinstance_config_message = BuildShieldedInstanceConfigMessage(
        messages=client.messages, args=args)

    if support_confidential_compute:
        confidential_instance_config_message = (
            BuildConfidentialInstanceConfigMessage(messages=client.messages,
                                                   args=args))

    node_affinities = sole_tenancy_util.GetSchedulingNodeAffinityListFromArgs(
        args, client.messages)

    min_node_cpu = None
    if support_min_node_cpu and args.IsSpecified('min_node_cpu'):
        min_node_cpu = args.min_node_cpu

    location_hint = None
    if support_location_hint and args.IsSpecified('location_hint'):
        location_hint = args.location_hint

    scheduling = instance_utils.CreateSchedulingMessage(
        messages=client.messages,
        maintenance_policy=args.maintenance_policy,
        preemptible=args.preemptible,
        restart_on_failure=args.restart_on_failure,
        node_affinities=node_affinities,
        min_node_cpu=min_node_cpu,
        location_hint=location_hint)

    if args.no_service_account:
        service_account = None
    else:
        service_account = args.service_account
    service_accounts = instance_utils.CreateServiceAccountMessages(
        messages=client.messages,
        scopes=[] if args.no_scopes else args.scopes,
        service_account=service_account)

    create_boot_disk = not instance_utils.UseExistingBootDisk(args.disk or [])
    if create_boot_disk:
        image_expander = image_utils.ImageExpander(client,
                                                   compute_api.resources)
        try:
            image_uri, _ = image_expander.ExpandImageFlag(
                user_project=instance_template_ref.project,
                image=args.image,
                image_family=args.image_family,
                image_project=args.image_project,
                return_image_resource=True)
        except utils.ImageNotFoundError as e:
            if args.IsSpecified('image_project'):
                raise e
            image_uri, _ = image_expander.ExpandImageFlag(
                user_project=instance_template_ref.project,
                image=args.image,
                image_family=args.image_family,
                image_project=args.image_project,
                return_image_resource=False)
            raise utils.ImageNotFoundError(
                'The resource [{}] was not found. Is the image located in another '
                'project? Use the --image-project flag to specify the '
                'project where the image is located.'.format(image_uri))
    else:
        image_uri = None

    if args.tags:
        tags = client.messages.Tags(items=args.tags)
    else:
        tags = None

    persistent_disks = (
        instance_template_utils.CreatePersistentAttachedDiskMessages(
            client.messages, args.disk or []))

    persistent_create_disks = (
        instance_template_utils.CreatePersistentCreateDiskMessages(
            client,
            compute_api.resources,
            instance_template_ref.project,
            getattr(args, 'create_disk', []),
            support_kms=support_kms))

    if create_boot_disk:
        boot_disk_list = [
            instance_template_utils.CreateDefaultBootAttachedDiskMessage(
                messages=client.messages,
                disk_type=args.boot_disk_type,
                disk_device_name=args.boot_disk_device_name,
                disk_auto_delete=args.boot_disk_auto_delete,
                disk_size_gb=boot_disk_size_gb,
                image_uri=image_uri,
                kms_args=args,
                support_kms=support_kms)
        ]
    else:
        boot_disk_list = []

    local_nvdimms = create_utils.CreateLocalNvdimmMessages(
        args,
        compute_api.resources,
        client.messages,
    )

    local_ssds = create_utils.CreateLocalSsdMessages(
        args,
        compute_api.resources,
        client.messages,
    )

    disks = (boot_disk_list + persistent_disks + persistent_create_disks +
             local_nvdimms + local_ssds)

    machine_type = instance_utils.InterpretMachineType(
        machine_type=args.machine_type,
        custom_cpu=args.custom_cpu,
        custom_memory=args.custom_memory,
        ext=getattr(args, 'custom_extensions', None),
        vm_type=getattr(args, 'custom_vm_type', None))

    guest_accelerators = (
        instance_template_utils.CreateAcceleratorConfigMessages(
            client.messages, getattr(args, 'accelerator', None)))

    instance_template = client.messages.InstanceTemplate(
        properties=client.messages.InstanceProperties(
            machineType=machine_type,
            disks=disks,
            canIpForward=args.can_ip_forward,
            metadata=metadata,
            minCpuPlatform=args.min_cpu_platform,
            networkInterfaces=network_interfaces,
            serviceAccounts=service_accounts,
            scheduling=scheduling,
            tags=tags,
            guestAccelerators=guest_accelerators,
        ),
        description=args.description,
        name=instance_template_ref.Name(),
    )

    instance_template.properties.shieldedInstanceConfig = shieldedinstance_config_message

    instance_template.properties.reservationAffinity = instance_utils.GetReservationAffinity(
        args, client)

    if support_confidential_compute:
        instance_template.properties.confidentialInstanceConfig = (
            confidential_instance_config_message)

    if (support_private_ipv6_google_access
            and args.private_ipv6_google_access_type is not None):
        instance_template.properties.privateIpv6GoogleAccess = (
            instances_flags.
            GetPrivateIpv6GoogleAccessTypeFlagMapperForTemplate(
                client.messages).GetEnumForChoice(
                    args.private_ipv6_google_access_type))

    request = client.messages.ComputeInstanceTemplatesInsertRequest(
        instanceTemplate=instance_template,
        project=instance_template_ref.project)

    request.instanceTemplate.properties.labels = ParseCreateArgsWithMeshMode(
        args, client.messages.InstanceProperties.LabelsValue)

    _AddSourceInstanceToTemplate(compute_api, args, instance_template,
                                 support_source_instance)

    return client.MakeRequests([(client.apitools_client.instanceTemplates,
                                 'Insert', request)])