Ejemplo n.º 1
0
def CreateMachineTypeUri(args, compute_client, resource_parser, project,
                         location, scope):
  """Create a machine type URI for given args and instance reference."""

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

  # Setting the machine type
  machine_type_name = instance_utils.InterpretMachineType(
      machine_type=machine_type,
      custom_cpu=custom_cpu,
      custom_memory=custom_memory,
      ext=ext,
      vm_type=vm_type)

  # Check to see if the custom machine type ratio is supported
  instance_utils.CheckCustomCpuRamRatio(compute_client, project, location,
                                        machine_type_name)

  machine_type_uri = instance_utils.ParseMachineType(resource_parser,
                                                     machine_type_name, project,
                                                     location, scope)
  return machine_type_uri
Ejemplo n.º 2
0
    def CreateRequests(self, args):
        """Returns a list of request necessary for setting scheduling options."""
        instance_ref = instance_flags.INSTANCE_ARG.ResolveAsResource(
            args,
            self.resources,
            scope_lister=flags.GetDefaultScopeLister(self.compute_client,
                                                     self.project))

        machine_type = instance_utils.InterpretMachineType(
            machine_type=args.machine_type,
            custom_cpu=args.custom_cpu,
            custom_memory=args.custom_memory)

        instance_utils.CheckCustomCpuRamRatio(self.compute_client,
                                              self.project, instance_ref.zone,
                                              machine_type)

        machine_type_uri = self.resources.Parse(
            machine_type,
            collection='compute.machineTypes',
            params={
                'zone': instance_ref.zone
            }).SelfLink()

        set_machine_type_request = self.messages.InstancesSetMachineTypeRequest(
            machineType=machine_type_uri)
        request = self.messages.ComputeInstancesSetMachineTypeRequest(
            instance=instance_ref.Name(),
            project=self.project,
            instancesSetMachineTypeRequest=set_machine_type_request,
            zone=instance_ref.zone)

        return (request, )
Ejemplo n.º 3
0
    def Run(self, args):
        """Invokes request necessary for setting scheduling options."""
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        self._ValidateMachineTypePresence(args)

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

        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))

        instance_utils.CheckCustomCpuRamRatio(client, instance_ref.project,
                                              instance_ref.zone, machine_type)

        machine_type_uri = holder.resources.Parse(
            machine_type,
            collection='compute.machineTypes',
            params={
                'project': instance_ref.project,
                'zone': instance_ref.zone
            }).SelfLink()

        set_machine_type_request = client.messages.InstancesSetMachineTypeRequest(
            machineType=machine_type_uri)
        request = client.messages.ComputeInstancesSetMachineTypeRequest(
            instance=instance_ref.Name(),
            project=instance_ref.project,
            instancesSetMachineTypeRequest=set_machine_type_request,
            zone=instance_ref.zone)

        return client.MakeRequests([(client.apitools_client.instances,
                                     'SetMachineType', request)])
    def CreateRequests(self, args):
        """Returns a list of request necessary for setting scheduling options."""
        instance_ref = self.CreateZonalReference(args.name, args.zone)

        machine_type = instance_utils.InterpretMachineType(args)

        instance_utils.CheckCustomCpuRamRatio(self, instance_ref.zone,
                                              machine_type)

        machine_type_uri = self.CreateZonalReference(
            machine_type, instance_ref.zone,
            resource_type='machineTypes').SelfLink()

        set_machine_type_request = self.messages.InstancesSetMachineTypeRequest(
            machineType=machine_type_uri)
        request = self.messages.ComputeInstancesSetMachineTypeRequest(
            instance=instance_ref.Name(),
            project=self.project,
            instancesSetMachineTypeRequest=set_machine_type_request,
            zone=instance_ref.zone)

        return (request, )
    def CreateRequests(self, args):
        _ValidateDiskFlags(args)
        instance_utils.ValidateLocalSsdFlags(args)

        # TODO(user) drop test after CSEK goes GA
        if hasattr(args, 'csek_key_file'):
            self.csek_keys = csek_utils.CsekKeyStore.FromArgs(args)
        else:
            self.csek_keys = None

        if args.maintenance_policy:
            on_host_maintenance = (
                self.messages.Scheduling.OnHostMaintenanceValueValuesEnum(
                    args.maintenance_policy))
        else:
            on_host_maintenance = None

        # Note: We always specify automaticRestart=False for preemptible VMs. This
        # makes sense, since no-restart-on-failure is defined as "store-true", and
        # thus can't be given an explicit value. Hence it either has its default
        # value (in which case we override it for convenience's sake to the only
        # setting that makes sense for preemptible VMs), or the user actually
        # specified no-restart-on-failure, the only usable setting.
        if args.preemptible:
            scheduling = self.messages.Scheduling(
                automaticRestart=False,
                onHostMaintenance=on_host_maintenance,
                preemptible=True)
        else:
            scheduling = self.messages.Scheduling(
                automaticRestart=args.restart_on_failure,
                onHostMaintenance=on_host_maintenance)

        service_accounts = self.CreateServiceAccountMessages(args)

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

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

        # If the user already provided an initial Windows password and
        # username through metadata, then there is no need to check
        # whether the image or the boot disk is Windows.

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

        instance_refs = self.CreateZonalReferences(args.names, args.zone)

        # Check if the zone is deprecated or has maintenance coming.
        self.WarnForZonalCreation(instance_refs)

        network_interface = self.CreateNetworkInterfaceMessage(
            args, instance_refs)

        # The element at index i is the machine type URI for instance
        # i. We build this list here because we want to delay work that
        # requires API calls as much as possible. This leads to a better
        # user experience because the tool can fail fast upon a spelling
        # mistake instead of delaying the user by making API calls whose
        # purpose has already been rendered moot by the spelling mistake.
        machine_type_uris = []

        # Setting the machine type
        machine_type_name = instance_utils.InterpretMachineType(args)

        for instance_ref in instance_refs:
            # Check to see if the custom machine type ratio is supported
            instance_utils.CheckCustomCpuRamRatio(self, instance_ref.zone,
                                                  machine_type_name)
            machine_type_uris.append(
                self.CreateZonalReference(
                    machine_type_name,
                    instance_ref.zone,
                    resource_type='machineTypes').SelfLink())

        create_boot_disk = not _UseExistingBootDisk(args)
        if create_boot_disk:
            image_uri, _ = self.ExpandImageFlag(args,
                                                return_image_resource=False)
        else:
            image_uri = None

        # A list of lists where the element at index i contains a list of
        # disk messages that should be set for the instance at index i.
        disks_messages = []

        # A mapping of zone to boot disk references for all existing boot
        # disks that are being attached.
        # TODO(user): Simplify this once resources.Resource becomes
        # hashable.
        existing_boot_disks = {}

        for instance_ref in instance_refs:
            persistent_disks, boot_disk_ref = (
                self.CreatePersistentAttachedDiskMessages(args, instance_ref))
            local_ssds = [
                instance_utils.CreateLocalSsdMessage(self,
                                                     x.get('device-name'),
                                                     x.get('interface'),
                                                     instance_ref.zone)
                for x in args.local_ssd or []
            ]
            if create_boot_disk:
                boot_disk = self.CreateDefaultBootAttachedDiskMessage(
                    args, boot_disk_size_gb, image_uri, instance_ref)
                persistent_disks = [boot_disk] + persistent_disks
            else:
                existing_boot_disks[boot_disk_ref.zone] = boot_disk_ref
            disks_messages.append(persistent_disks + local_ssds)

        requests = []
        for instance_ref, machine_type_uri, disks in zip(
                instance_refs, machine_type_uris, disks_messages):
            requests.append(
                self.messages.ComputeInstancesInsertRequest(
                    instance=self.messages.Instance(
                        canIpForward=args.can_ip_forward,
                        disks=disks,
                        description=args.description,
                        machineType=machine_type_uri,
                        metadata=metadata,
                        name=instance_ref.Name(),
                        networkInterfaces=[network_interface],
                        serviceAccounts=service_accounts,
                        scheduling=scheduling,
                        tags=tags,
                    ),
                    project=self.project,
                    zone=instance_ref.zone))

        return requests
    def _CreateRequests(self, args, holder, compute_client, resource_parser,
                        project, location, scope):
        # 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.

        name_pattern = args.name_pattern
        instance_names = args.predefined_names or []
        instance_count = args.count or len(instance_names)
        per_instance_props = encoding.DictToAdditionalPropertyMessage(
            {el: {}
             for el in instance_names}, compute_client.messages.
            BulkInsertInstanceResource.PerInstancePropertiesValue)

        location_policy = self.GetLocationPolicy(args, compute_client.messages)

        instance_min_count = instance_count
        if args.IsSpecified('min_count'):
            instance_min_count = args.min_count

        source_instance_template = self.GetSourceInstanceTemplate(
            args, resource_parser)
        skip_defaults = source_instance_template is not None

        scheduling = instance_utils.GetScheduling(
            args,
            compute_client,
            skip_defaults,
            support_node_affinity=False,
            support_min_node_cpu=self._support_min_node_cpu,
            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,
                                          instance_properties=True)
        metadata = instance_utils.GetMetadata(args, compute_client,
                                              skip_defaults)

        network_interfaces = create_utils.GetBulkNetworkInterfaces(
            args=args,
            resource_parser=resource_parser,
            compute_client=compute_client,
            holder=holder,
            project=project,
            location=location,
            scope=scope,
            skip_defaults=skip_defaults)

        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)

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

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

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

        service_accounts = create_utils.GetProjectServiceAccount(
            args, project, compute_client, skip_defaults)

        boot_disk_size_gb = instance_utils.GetBootDiskSizeGb(args)

        disks = []
        if create_utils.CheckSpecifiedDiskArgs(args=args,
                                               support_disks=False,
                                               skip_defaults=skip_defaults):

            #  Disks in bulk insert should be in READ_ONLY mode
            for disk in args.disk or []:
                disk['mode'] = 'ro'
            disks = create_utils.CreateDiskMessages(
                args=args,
                project=project,
                location=location,
                scope=scope,
                compute_client=compute_client,
                resource_parser=resource_parser,
                image_uri=image_uri,
                create_boot_disk=create_boot_disk,
                boot_disk_size_gb=boot_disk_size_gb,
                support_kms=True,
                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,
                use_disk_type_uri=False)

        machine_type_name = None
        if instance_utils.CheckSpecifiedMachineTypeArgs(args, skip_defaults):
            machine_type_name = instance_utils.CreateMachineTypeName(
                args, confidential_vm)

            # Check to see if the custom machine type ratio is supported
            instance_utils.CheckCustomCpuRamRatio(compute_client, project,
                                                  location, machine_type_name)

        can_ip_forward = instance_utils.GetCanIpForward(args, skip_defaults)
        guest_accelerators = create_utils.GetAcceleratorsForInstanceProperties(
            args=args, compute_client=compute_client)

        # Create an AdvancedMachineFeatures message if any arguments are supplied
        # that require one.
        advanced_machine_features = 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 (self._support_visible_core_count
                    and args.visible_core_count is not None)
                or args.enable_uefi_networking is not None):
            visible_core_count = args.visible_core_count if self._support_visible_core_count else None
            advanced_machine_features = (
                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))

        parsed_resource_policies = []
        resource_policies = getattr(args, 'resource_policies', None)
        if resource_policies:
            for policy in resource_policies:
                resource_policy_ref = maintenance_util.ParseResourcePolicyWithScope(
                    resource_parser,
                    policy,
                    project=project,
                    location=location,
                    scope=scope)
                parsed_resource_policies.append(resource_policy_ref.Name())

        display_device = None
        if self._support_display_device and args.IsSpecified(
                'enable_display_device'):
            display_device = compute_client.messages.DisplayDevice(
                enableDisplay=args.enable_display_device)

        reservation_affinity = instance_utils.GetReservationAffinity(
            args, compute_client)

        instance_properties = compute_client.messages.InstanceProperties(
            canIpForward=can_ip_forward,
            description=args.description,
            disks=disks,
            guestAccelerators=guest_accelerators,
            labels=labels,
            machineType=machine_type_name,
            metadata=metadata,
            minCpuPlatform=args.min_cpu_platform,
            networkInterfaces=network_interfaces,
            serviceAccounts=service_accounts,
            scheduling=scheduling,
            tags=tags,
            resourcePolicies=parsed_resource_policies,
            shieldedInstanceConfig=shielded_instance_config,
            reservationAffinity=reservation_affinity,
            advancedMachineFeatures=advanced_machine_features)

        if self._support_secure_tags and args.secure_tags:
            instance_properties.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:
                properties_message = compute_client.messages.InstanceProperties
                instance_properties.resourceManagerTags = properties_message.ResourceManagerTagsValue(
                    additionalProperties=[
                        properties_message.ResourceManagerTagsValue.
                        AdditionalProperty(key=key, value=value)
                        for key, value in sorted(
                            six.iteritems(ret_resource_manager_tags))
                    ])

        if self._support_display_device and display_device:
            instance_properties.displayDevice = display_device

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

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

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

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

        bulk_instance_resource = compute_client.messages.BulkInsertInstanceResource(
            count=instance_count,
            instanceProperties=instance_properties,
            minCount=instance_min_count,
            perInstanceProperties=per_instance_props,
            sourceInstanceTemplate=source_instance_template,
            namePattern=name_pattern,
            locationPolicy=location_policy)

        if scope == compute_scopes.ScopeEnum.ZONE:
            instance_service = compute_client.apitools_client.instances
            request_message = compute_client.messages.ComputeInstancesBulkInsertRequest(
                bulkInsertInstanceResource=bulk_instance_resource,
                project=project,
                zone=location)
        elif scope == compute_scopes.ScopeEnum.REGION:
            instance_service = compute_client.apitools_client.regionInstances
            request_message = compute_client.messages.ComputeRegionInstancesBulkInsertRequest(
                bulkInsertInstanceResource=bulk_instance_resource,
                project=project,
                region=location)

        return instance_service, request_message