Exemplo n.º 1
0
    def _CreateRequests(self, args, instance_refs, project, zone,
                        compute_client, resource_parser, holder):
        # gcloud creates default values for some fields in Instance resource
        # when no value was specified on command line.
        # When --source-instance-template was specified, defaults are taken from
        # Instance Template and gcloud flags are used to override them - by default
        # fields should not be initialized.
        source_instance_template = self.GetSourceInstanceTemplate(
            args, resource_parser)
        skip_defaults = source_instance_template is not None

        source_machine_image = self.GetSourceMachineImage(
            args, resource_parser)
        skip_defaults = skip_defaults or source_machine_image is not None

        scheduling = instance_utils.GetScheduling(
            args,
            compute_client,
            skip_defaults,
            support_node_affinity=True,
            support_min_node_cpu=self._support_min_node_cpu,
            support_location_hint=self._support_location_hint)
        tags = instance_utils.GetTags(args, compute_client)
        labels = instance_utils.GetLabels(args, compute_client)
        metadata = instance_utils.GetMetadata(args, compute_client,
                                              skip_defaults)
        boot_disk_size_gb = instance_utils.GetBootDiskSizeGb(args)

        network_interfaces = create_utils.GetNetworkInterfacesWithValidation(
            args=args,
            resource_parser=resource_parser,
            compute_client=compute_client,
            holder=holder,
            project=project,
            location=zone,
            scope=compute_scopes.ScopeEnum.ZONE,
            skip_defaults=skip_defaults,
            support_public_dns=self._support_public_dns)

        create_boot_disk = not instance_utils.UseExistingBootDisk(args.disk
                                                                  or [])
        image_uri = create_utils.GetImageUri(args, compute_client,
                                             create_boot_disk, project,
                                             resource_parser)

        shielded_instance_config = create_utils.BuildShieldedInstanceConfigMessage(
            messages=compute_client.messages, args=args)

        if self._support_confidential_compute:
            confidential_instance_config = (
                create_utils.BuildConfidentialInstanceConfigMessage(
                    messages=compute_client.messages, args=args))

        csek_keys = csek_utils.CsekKeyStore.FromArgs(
            args, self._support_rsa_encrypted)

        project_to_sa = create_utils.GetProjectToServiceAccountMap(
            args, instance_refs, compute_client, skip_defaults)

        requests = []
        for instance_ref in instance_refs:

            disks = []
            if create_utils.CheckSpecifiedDiskArgs(
                    args=args,
                    skip_defaults=skip_defaults,
                    support_kms=self._support_kms):
                disks = create_utils.CreateDiskMessages(
                    args=args,
                    instance_name=instance_ref.Name(),
                    project=instance_ref.project,
                    location=instance_ref.zone,
                    scope=compute_scopes.ScopeEnum.ZONE,
                    compute_client=compute_client,
                    resource_parser=resource_parser,
                    boot_disk_size_gb=boot_disk_size_gb,
                    image_uri=image_uri,
                    create_boot_disk=create_boot_disk,
                    csek_keys=csek_keys,
                    support_kms=self._support_kms,
                    support_nvdimm=self._support_nvdimm,
                    support_disk_resource_policy=self.
                    _support_disk_resource_policy,
                    support_source_snapshot_csek=self.
                    _support_source_snapshot_csek,
                    support_boot_snapshot_uri=self._support_boot_snapshot_uri,
                    support_image_csek=self._support_image_csek,
                    support_create_disk_snapshots=self.
                    _support_create_disk_snapshots)

            machine_type_uri = None
            if instance_utils.CheckSpecifiedMachineTypeArgs(
                    args, skip_defaults):
                machine_type_uri = instance_utils.CreateMachineTypeUri(
                    args=args,
                    compute_client=compute_client,
                    resource_parser=resource_parser,
                    project=instance_ref.project,
                    location=instance_ref.zone,
                    scope=compute_scopes.ScopeEnum.ZONE)

            can_ip_forward = instance_utils.GetCanIpForward(
                args, skip_defaults)
            guest_accelerators = create_utils.GetAccelerators(
                args=args,
                compute_client=compute_client,
                resource_parser=resource_parser,
                project=instance_ref.project,
                location=instance_ref.zone,
                scope=compute_scopes.ScopeEnum.ZONE)

            instance = compute_client.messages.Instance(
                canIpForward=can_ip_forward,
                deletionProtection=args.deletion_protection,
                description=args.description,
                disks=disks,
                guestAccelerators=guest_accelerators,
                hostname=args.hostname,
                labels=labels,
                machineType=machine_type_uri,
                metadata=metadata,
                minCpuPlatform=args.min_cpu_platform,
                name=instance_ref.Name(),
                networkInterfaces=network_interfaces,
                serviceAccounts=project_to_sa[instance_ref.project],
                scheduling=scheduling,
                tags=tags)

            if args.private_ipv6_google_access_type is not None:
                instance.privateIpv6GoogleAccess = (
                    instances_flags.GetPrivateIpv6GoogleAccessTypeFlagMapper(
                        compute_client.messages).GetEnumForChoice(
                            args.private_ipv6_google_access_type))

            resource_policies = getattr(args, 'resource_policies', None)
            if resource_policies:
                parsed_resource_policies = []
                for policy in resource_policies:
                    resource_policy_ref = maintenance_util.ParseResourcePolicyWithZone(
                        resource_parser,
                        policy,
                        project=instance_ref.project,
                        zone=instance_ref.zone)
                    parsed_resource_policies.append(
                        resource_policy_ref.SelfLink())
                instance.resourcePolicies = parsed_resource_policies

            if shielded_instance_config:
                instance.shieldedInstanceConfig = shielded_instance_config

            if self._support_confidential_compute and confidential_instance_config:
                instance.confidentialInstanceConfig = confidential_instance_config

            if self._support_erase_vss and \
              args.IsSpecified('erase_windows_vss_signature'):
                instance.eraseWindowsVssSignature = args.erase_windows_vss_signature

            if self._support_post_key_revocation_action_type and args.IsSpecified(
                    'post_key_revocation_action_type'):
                instance.postKeyRevocationActionType = arg_utils.ChoiceToEnum(
                    args.post_key_revocation_action_type,
                    compute_client.messages.Instance.
                    PostKeyRevocationActionTypeValueValuesEnum)

            request = compute_client.messages.ComputeInstancesInsertRequest(
                instance=instance,
                project=instance_ref.project,
                zone=instance_ref.zone)

            if source_instance_template:
                request.sourceInstanceTemplate = source_instance_template

            if source_machine_image:
                request.instance.sourceMachineImage = source_machine_image
                if args.IsSpecified('source_machine_image_csek_key_file'):
                    key = instance_utils.GetSourceMachineImageKey(
                        args, self.SOURCE_MACHINE_IMAGE, compute_client,
                        holder)
                    request.instance.sourceMachineImageEncryptionKey = key

            if self._support_machine_image_key and \
                args.IsSpecified('source_machine_image_csek_key_file'):
                if not args.IsSpecified('source_machine_image'):
                    raise exceptions.RequiredArgumentException(
                        '`--source-machine-image`',
                        '`--source-machine-image-csek-key-file` requires '
                        '`--source-machine-image` to be specified`')

            if args.IsSpecified('enable_display_device'):
                request.instance.displayDevice = compute_client.messages.DisplayDevice(
                    enableDisplay=args.enable_display_device)

            request.instance.reservationAffinity = instance_utils.GetReservationAffinity(
                args, compute_client)

            requests.append(
                (compute_client.apitools_client.instances, 'Insert', request))
        return requests
Exemplo n.º 2
0
    def Run(self, args):
        self._ValidateArgs(args)

        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        compute_client = holder.client
        resource_parser = holder.resources

        container_mount_disk = instances_flags.GetValidatedContainerMountDisk(
            holder, args.container_mount_disk, args.disk, args.create_disk)
        source_instance_template = instance_utils.GetSourceInstanceTemplate(
            args, resource_parser, self.SOURCE_INSTANCE_TEMPLATE)
        skip_defaults = instance_utils.GetSkipDefaults(
            source_instance_template)
        scheduling = instance_utils.GetScheduling(args,
                                                  compute_client,
                                                  skip_defaults,
                                                  support_min_node_cpu=False)
        service_accounts = instance_utils.GetServiceAccounts(
            args, compute_client, skip_defaults)
        user_metadata = instance_utils.GetValidatedMetadata(
            args, compute_client)
        boot_disk_size_gb = instance_utils.GetBootDiskSizeGb(args)
        instance_refs = instance_utils.GetInstanceRefs(args, compute_client,
                                                       holder)
        network_interfaces = self.GetNetworkInterfaces(
            args, resource_parser, compute_client, holder,
            instance_refs[0].project, instance_refs[0].zone,
            compute_scopes.ScopeEnum.ZONE, skip_defaults)
        image_uri = self.GetImageUri(args, compute_client, resource_parser,
                                     instance_refs)
        labels = containers_utils.GetLabelsMessageWithCosVersion(
            args.labels, image_uri, resource_parser,
            compute_client.messages.Instance)
        can_ip_forward = instance_utils.GetCanIpForward(args, skip_defaults)
        tags = containers_utils.CreateTagsMessage(compute_client.messages,
                                                  args.tags)
        confidential_vm = (args.IsSpecified('confidential_compute')
                           and args.confidential_compute)

        requests = []
        for instance_ref in instance_refs:
            metadata = containers_utils.CreateKonletMetadataMessage(
                compute_client.messages,
                args,
                instance_ref.Name(),
                user_metadata,
                container_mount_disk_enabled=self.
                _container_mount_disk_enabled,
                container_mount_disk=container_mount_disk)

            disks = []
            if self.CheckDiskMessageArgs(args, skip_defaults):
                disks = create_utils.CreateDiskMessages(
                    args=args,
                    instance_name=instance_ref.Name(),
                    project=instance_ref.project,
                    location=instance_ref.zone,
                    scope=compute_scopes.ScopeEnum.ZONE,
                    compute_client=compute_client,
                    resource_parser=resource_parser,
                    boot_disk_size_gb=boot_disk_size_gb,
                    image_uri=image_uri,
                    create_boot_disk=self._support_create_boot_disk,
                    support_nvdimm=self._support_nvdimm,
                    support_match_container_mount_disks=self.
                    _support_match_container_mount_disks)

            machine_type_uri = None
            if instance_utils.CheckSpecifiedMachineTypeArgs(
                    args, skip_defaults):
                machine_type_uri = create_utils.CreateMachineTypeUri(
                    args=args,
                    compute_client=compute_client,
                    resource_parser=resource_parser,
                    project=instance_ref.project,
                    location=instance_ref.zone,
                    scope=compute_scopes.ScopeEnum.ZONE,
                    confidential_vm=confidential_vm)

            guest_accelerators = create_utils.GetAccelerators(
                args=args,
                compute_client=compute_client,
                resource_parser=resource_parser,
                project=instance_ref.project,
                location=instance_ref.zone,
                scope=compute_scopes.ScopeEnum.ZONE)

            instance = compute_client.messages.Instance(
                canIpForward=can_ip_forward,
                disks=disks,
                guestAccelerators=guest_accelerators,
                description=args.description,
                labels=labels,
                machineType=machine_type_uri,
                metadata=metadata,
                minCpuPlatform=args.min_cpu_platform,
                name=instance_ref.Name(),
                networkInterfaces=network_interfaces,
                serviceAccounts=service_accounts,
                scheduling=scheduling,
                tags=tags)
            if args.private_ipv6_google_access_type is not None:
                instance.privateIpv6GoogleAccess = (
                    instances_flags.GetPrivateIpv6GoogleAccessTypeFlagMapper(
                        compute_client.messages).GetEnumForChoice(
                            args.private_ipv6_google_access_type))

            confidential_instance_config = (
                create_utils.BuildConfidentialInstanceConfigMessage(
                    messages=compute_client.messages, args=args))
            if confidential_instance_config:
                instance.confidentialInstanceConfig = confidential_instance_config

            has_threads_per_core = (self._support_threads_per_core
                                    and args.threads_per_core is not None)
            if (args.enable_nested_virtualization is not None
                    or has_threads_per_core):
                threads_per_core = args.threads_per_core if has_threads_per_core else None
                instance.advancedMachineFeatures = (
                    instance_utils.CreateAdvancedMachineFeaturesMessage(
                        compute_client.messages,
                        args.enable_nested_virtualization, threads_per_core))

            shielded_instance_config = create_utils.BuildShieldedInstanceConfigMessage(
                messages=compute_client.messages, args=args)
            if shielded_instance_config:
                instance.shieldedInstanceConfig = shielded_instance_config

            if self._support_network_performance_configs and \
                args.IsSpecified('network_performance_configs'):
                instance.networkPerformanceConfig = \
                    instance_utils.GetNetworkPerformanceConfig(args, compute_client)

            request = compute_client.messages.ComputeInstancesInsertRequest(
                instance=instance,
                sourceInstanceTemplate=source_instance_template,
                project=instance_ref.project,
                zone=instance_ref.zone)

            requests.append(
                (compute_client.apitools_client.instances, 'Insert', request))

        return compute_client.MakeRequests(requests)
Exemplo n.º 3
0
    def _CreateRequests(self, args, instance_refs, project, zone,
                        compute_client, resource_parser, holder):
        # gcloud creates default values for some fields in Instance resource
        # when no value was specified on command line.
        # When --source-instance-template was specified, defaults are taken from
        # Instance Template and gcloud flags are used to override them - by default
        # fields should not be initialized.
        source_instance_template = self.GetSourceInstanceTemplate(
            args, resource_parser)
        skip_defaults = source_instance_template is not None

        source_machine_image = self.GetSourceMachineImage(
            args, resource_parser)
        skip_defaults = skip_defaults or source_machine_image is not None

        scheduling = instance_utils.GetScheduling(
            args,
            compute_client,
            skip_defaults,
            support_node_affinity=True,
            support_node_project=self._support_node_project,
            support_host_error_timeout_seconds=self.
            _support_host_error_timeout_seconds,
            support_max_run_duration=self._support_max_run_duration)
        tags = instance_utils.GetTags(args, compute_client)
        labels = instance_utils.GetLabels(args, compute_client)
        metadata = instance_utils.GetMetadata(args, compute_client,
                                              skip_defaults)
        boot_disk_size_gb = instance_utils.GetBootDiskSizeGb(args)

        network_interfaces = create_utils.GetNetworkInterfacesWithValidation(
            args=args,
            resource_parser=resource_parser,
            compute_client=compute_client,
            holder=holder,
            project=project,
            location=zone,
            scope=compute_scopes.ScopeEnum.ZONE,
            skip_defaults=skip_defaults,
            support_public_dns=self._support_public_dns,
            support_ipv6_assignment=self._support_ipv6_assignment)

        confidential_vm = (args.IsSpecified('confidential_compute')
                           and args.confidential_compute)

        create_boot_disk = not (
            instance_utils.UseExistingBootDisk((args.disk or []) +
                                               (args.create_disk or [])))

        image_uri = create_utils.GetImageUri(
            args,
            compute_client,
            create_boot_disk,
            project,
            resource_parser,
            confidential_vm,
            image_family_scope=args.image_family_scope,
            support_image_family_scope=True)

        shielded_instance_config = create_utils.BuildShieldedInstanceConfigMessage(
            messages=compute_client.messages, args=args)

        confidential_instance_config = (
            create_utils.BuildConfidentialInstanceConfigMessage(
                messages=compute_client.messages, args=args))

        csek_keys = csek_utils.CsekKeyStore.FromArgs(
            args, self._support_rsa_encrypted)

        project_to_sa = create_utils.GetProjectToServiceAccountMap(
            args, instance_refs, compute_client, skip_defaults)

        requests = []
        for instance_ref in instance_refs:

            disks = []
            if create_utils.CheckSpecifiedDiskArgs(
                    args=args,
                    skip_defaults=skip_defaults,
                    support_kms=self._support_kms):
                disks = create_utils.CreateDiskMessages(
                    args=args,
                    instance_name=instance_ref.Name(),
                    project=instance_ref.project,
                    location=instance_ref.zone,
                    scope=compute_scopes.ScopeEnum.ZONE,
                    compute_client=compute_client,
                    resource_parser=resource_parser,
                    boot_disk_size_gb=boot_disk_size_gb,
                    image_uri=image_uri,
                    create_boot_disk=create_boot_disk,
                    csek_keys=csek_keys,
                    holder=holder,
                    support_kms=self._support_kms,
                    support_nvdimm=self._support_nvdimm,
                    support_source_snapshot_csek=self.
                    _support_source_snapshot_csek,
                    support_boot_snapshot_uri=self._support_boot_snapshot_uri,
                    support_image_csek=self._support_image_csek,
                    support_create_disk_snapshots=self.
                    _support_create_disk_snapshots,
                    support_replica_zones=self._support_replica_zones,
                    support_multi_writer=self._support_multi_writer,
                    support_disk_architecture=self._support_disk_architecture)

            machine_type_uri = None
            if instance_utils.CheckSpecifiedMachineTypeArgs(
                    args, skip_defaults):
                machine_type_uri = instance_utils.CreateMachineTypeUri(
                    args=args,
                    compute_client=compute_client,
                    resource_parser=resource_parser,
                    project=instance_ref.project,
                    location=instance_ref.zone,
                    scope=compute_scopes.ScopeEnum.ZONE,
                    confidential_vm=confidential_vm)

            can_ip_forward = instance_utils.GetCanIpForward(
                args, skip_defaults)
            guest_accelerators = create_utils.GetAccelerators(
                args=args,
                compute_client=compute_client,
                resource_parser=resource_parser,
                project=instance_ref.project,
                location=instance_ref.zone,
                scope=compute_scopes.ScopeEnum.ZONE)

            instance = compute_client.messages.Instance(
                canIpForward=can_ip_forward,
                deletionProtection=args.deletion_protection,
                description=args.description,
                disks=disks,
                guestAccelerators=guest_accelerators,
                hostname=args.hostname,
                labels=labels,
                machineType=machine_type_uri,
                metadata=metadata,
                minCpuPlatform=args.min_cpu_platform,
                name=instance_ref.Name(),
                networkInterfaces=network_interfaces,
                serviceAccounts=project_to_sa[instance_ref.project],
                scheduling=scheduling,
                tags=tags)

            if self._support_instance_kms and args.CONCEPTS.instance_kms_key:
                instance.instanceEncryptionKey = kms_utils.MaybeGetKmsKey(
                    args,
                    compute_client.messages,
                    instance.instanceEncryptionKey,
                    instance_prefix=True)

            if self._support_secure_tag and args.secure_tags:
                instance.secureTags = secure_tags_utils.GetSecureTags(
                    args.secure_tags)

            if args.resource_manager_tags:
                ret_resource_manager_tags = resource_manager_tags_utils.GetResourceManagerTags(
                    args.resource_manager_tags)
                if ret_resource_manager_tags is not None:
                    params = compute_client.messages.InstanceParams
                    instance.params = params(
                        resourceManagerTags=params.ResourceManagerTagsValue(
                            additionalProperties=[
                                params.ResourceManagerTagsValue.
                                AdditionalProperty(key=key, value=value)
                                for key, value in sorted(
                                    six.iteritems(ret_resource_manager_tags))
                            ]))

            if args.private_ipv6_google_access_type is not None:
                instance.privateIpv6GoogleAccess = (
                    instances_flags.GetPrivateIpv6GoogleAccessTypeFlagMapper(
                        compute_client.messages).GetEnumForChoice(
                            args.private_ipv6_google_access_type))

            has_visible_core_count = (self._support_visible_core_count
                                      and args.visible_core_count is not None)
            if (args.enable_nested_virtualization is not None
                    or args.threads_per_core is not None
                    or (self._support_numa_node_count
                        and args.numa_node_count is not None)
                    or has_visible_core_count
                    or args.enable_uefi_networking is not None):
                visible_core_count = args.visible_core_count if has_visible_core_count else None
                instance.advancedMachineFeatures = (
                    instance_utils.CreateAdvancedMachineFeaturesMessage(
                        compute_client.messages,
                        args.enable_nested_virtualization,
                        args.threads_per_core, args.numa_node_count
                        if self._support_numa_node_count else None,
                        visible_core_count, args.enable_uefi_networking))

            resource_policies = getattr(args, 'resource_policies', None)
            if resource_policies:
                parsed_resource_policies = []
                for policy in resource_policies:
                    resource_policy_ref = maintenance_util.ParseResourcePolicyWithZone(
                        resource_parser,
                        policy,
                        project=instance_ref.project,
                        zone=instance_ref.zone)
                    parsed_resource_policies.append(
                        resource_policy_ref.SelfLink())
                instance.resourcePolicies = parsed_resource_policies

            if shielded_instance_config:
                instance.shieldedInstanceConfig = shielded_instance_config

            if confidential_instance_config:
                instance.confidentialInstanceConfig = confidential_instance_config

            if self._support_erase_vss and args.IsSpecified(
                    'erase_windows_vss_signature'):
                instance.eraseWindowsVssSignature = args.erase_windows_vss_signature

            if self._support_post_key_revocation_action_type and args.IsSpecified(
                    'post_key_revocation_action_type'):
                instance.postKeyRevocationActionType = arg_utils.ChoiceToEnum(
                    args.post_key_revocation_action_type,
                    compute_client.messages.Instance.
                    PostKeyRevocationActionTypeValueValuesEnum)

            if self._support_key_revocation_action_type and args.IsSpecified(
                    'key_revocation_action_type'):
                instance.keyRevocationActionType = arg_utils.ChoiceToEnum(
                    args.key_revocation_action_type, compute_client.messages.
                    Instance.KeyRevocationActionTypeValueValuesEnum)

            if args.IsSpecified('network_performance_configs'):
                instance.networkPerformanceConfig = instance_utils.GetNetworkPerformanceConfig(
                    args, compute_client)

            request = compute_client.messages.ComputeInstancesInsertRequest(
                instance=instance,
                project=instance_ref.project,
                zone=instance_ref.zone)

            if source_instance_template:
                request.sourceInstanceTemplate = source_instance_template

            if source_machine_image:
                request.instance.sourceMachineImage = source_machine_image
                if args.IsSpecified('source_machine_image_csek_key_file'):
                    key = instance_utils.GetSourceMachineImageKey(
                        args, self.SOURCE_MACHINE_IMAGE, compute_client,
                        holder)
                    request.instance.sourceMachineImageEncryptionKey = key

            if self._support_machine_image_key and args.IsSpecified(
                    'source_machine_image_csek_key_file'):
                if not args.IsSpecified('source_machine_image'):
                    raise exceptions.RequiredArgumentException(
                        '`--source-machine-image`',
                        '`--source-machine-image-csek-key-file` requires '
                        '`--source-machine-image` to be specified`')

            if args.IsSpecified('enable_display_device'):
                request.instance.displayDevice = compute_client.messages.DisplayDevice(
                    enableDisplay=args.enable_display_device)

            request.instance.reservationAffinity = instance_utils.GetReservationAffinity(
                args, compute_client)

            requests.append(
                (compute_client.apitools_client.instances, 'Insert', request))
        return requests