예제 #1
0
파일: utils.py 프로젝트: iofh/QA-System
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
예제 #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, )
 def _GetMachineType(self, args):
   return 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))
예제 #4
0
파일: import.py 프로젝트: linsole/CS61A
    def Run(self, args):
        compute_holder = base_classes.ComputeApiHolder(self.ReleaseTrack())

        self._ValidateInstanceName(args)
        self._CheckForExistingInstances(args.instance_name,
                                        compute_holder.client)

        instances_flags.ValidateNicFlags(args)
        instances_flags.ValidateNetworkTierArgs(args)

        log.warning('Importing OVF. This may take 40 minutes for smaller OVFs '
                    'and up to a couple of hours for larger OVFs.')

        machine_type = None
        if args.machine_type or args.custom_cpu or args.custom_memory:
            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))

        try:
            source_uri = daisy_utils.MakeGcsObjectOrPathUri(args.source_uri)
        except storage_util.InvalidObjectNameError:
            raise exceptions.InvalidArgumentException(
                'source-uri',
                'must be a path to an object or a directory in Google Cloud Storage'
            )

        return daisy_utils.RunOVFImportBuild(
            args=args,
            compute_client=compute_holder.client,
            instance_name=args.instance_name,
            source_uri=source_uri,
            no_guest_environment=not args.guest_environment,
            can_ip_forward=args.can_ip_forward,
            deletion_protection=args.deletion_protection,
            description=args.description,
            labels=args.labels,
            machine_type=machine_type,
            network=args.network,
            network_tier=args.network_tier,
            subnet=args.subnet,
            private_network_ip=args.private_network_ip,
            no_restart_on_failure=not args.restart_on_failure,
            os=args.os,
            tags=args.tags,
            zone=properties.VALUES.compute.zone.Get(),
            project=args.project,
            output_filter=_OUTPUT_FILTER,
            compute_release_track=self.ReleaseTrack().id.lower()
            if self.ReleaseTrack() else None)
예제 #5
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, )
예제 #7
0
    def Run(self, args):
        compute_holder = base_classes.ComputeApiHolder(self.ReleaseTrack())

        self._ValidateInstanceNames(args)
        self._CheckForExistingInstances(args.instance_names,
                                        compute_holder.client)

        instances_flags.ValidateNicFlags(args)
        instances_flags.ValidateNetworkTierArgs(args)

        log.warning('Importing OVF. This may take 40 minutes for smaller OVFs '
                    'and up to a couple of hours for larger OVFs.')

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

        return daisy_utils.RunOVFImportBuild(
            args=args,
            instance_names=args.instance_names,
            source_uri=daisy_utils.MakeGcsUri(args.source_uri),
            no_guest_environment=not args.guest_environment,
            can_ip_forward=args.can_ip_forward,
            deletion_protection=args.deletion_protection,
            description=args.description,
            labels=args.labels,
            machine_type=machine_type,
            network=args.network,
            network_tier=args.network_tier,
            subnet=args.subnet,
            private_network_ip=args.private_network_ip,
            no_restart_on_failure=not args.restart_on_failure,
            os=args.os,
            tags=args.tags,
            zone=properties.VALUES.compute.zone.Get(),
            project=args.project,
            output_filter=_OUTPUT_FILTER)
    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
예제 #9
0
  def CreateRequests(self, args):
    """Creates and returns an InstanceTemplates.Insert request.

    Args:
      args: the argparse arguments that this command was invoked with.

    Returns:
      request: a ComputeInstanceTemplatesInsertRequest message object
    """
    instances_flags.ValidateDockerArgs(args)
    instances_flags.ValidateDiskCommonFlags(args)
    instances_flags.ValidateLocalSsdFlags(args)
    instances_flags.ValidateServiceAccountAndScopeArgs(args)
    if instance_utils.UseExistingBootDisk(args.disk or []):
      raise exceptions.InvalidArgumentException(
          '--disk',
          'Boot disk specified for containerized VM.')

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

    instance_template_ref = (
        CreateFromContainer.InstanceTemplateArg.ResolveAsResource(
            args, self.resources))

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

    network_interface = instance_template_utils.CreateNetworkInterfaceMessage(
        resources=self.resources,
        scope_lister=flags.GetDefaultScopeLister(self.compute_client),
        messages=self.messages,
        network=args.network,
        region=args.region,
        subnet=args.subnet,
        address=(instance_template_utils.EPHEMERAL_ADDRESS
                 if not args.no_address and not args.address
                 else args.address))

    scheduling = instance_utils.CreateSchedulingMessage(
        messages=self.messages,
        maintenance_policy=args.maintenance_policy,
        preemptible=args.preemptible,
        restart_on_failure=args.restart_on_failure)

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

    image_uri = containers_utils.ExpandCosImageFlag(self.compute_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))

    metadata = containers_utils.CreateMetadataMessage(
        self.messages, args.run_as_privileged, args.container_manifest,
        args.docker_image, args.port_mappings, args.run_command,
        user_metadata, instance_template_ref.Name())

    request = self.messages.ComputeInstanceTemplatesInsertRequest(
        instanceTemplate=self.messages.InstanceTemplate(
            properties=self.messages.InstanceProperties(
                machineType=machine_type,
                disks=self._CreateDiskMessages(args, boot_disk_size_gb,
                                               image_uri,
                                               instance_template_ref.project),
                canIpForward=args.can_ip_forward,
                metadata=metadata,
                minCpuPlatform=args.min_cpu_platform,
                networkInterfaces=[network_interface],
                serviceAccounts=service_accounts,
                scheduling=scheduling,
                tags=containers_utils.CreateTagsMessage(
                    self.messages, args.tags),
            ),
            description=args.description,
            name=instance_template_ref.Name(),
        ),
        project=instance_template_ref.project)

    return [request]
    def Run(self, args):
        compute_holder = self._GetComputeApiHolder()
        compute_client = compute_holder.client
        messages = compute_client.messages

        self._ValidateArgs(args, compute_client)

        log.warning('Importing OVF. This may take 40 minutes for smaller OVFs '
                    'and up to a couple of hours for larger OVFs.')

        machine_type = None
        if args.machine_type or args.custom_cpu or args.custom_memory:
            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))

        try:
            source_uri = daisy_utils.MakeGcsUri(args.source_uri)
        except resources.UnknownCollectionException:
            raise exceptions.InvalidArgumentException(
                'source-uri',
                'must be a path to an object or a directory in Cloud Storage')

        # The value of the attribute 'guest_os_features' can be can be a list, None,
        # or the attribute may not be present at all.
        # We treat the case when it is None or when it is not present as if the list
        # of features is empty. We need to use the trailing `or ()` rather than
        # give () as a default value to getattr() to handle the case where
        # args.guest_os_features is present, but it is None.
        guest_os_features = getattr(args, 'guest_os_features', None) or ()
        uefi_compatible = (
            messages.GuestOsFeature.TypeValueValuesEnum.UEFI_COMPATIBLE.name
            in guest_os_features)

        return daisy_utils.RunInstanceOVFImportBuild(
            args=args,
            compute_client=compute_client,
            instance_name=args.instance_name,
            source_uri=source_uri,
            no_guest_environment=not args.guest_environment,
            can_ip_forward=args.can_ip_forward,
            deletion_protection=args.deletion_protection,
            description=args.description,
            labels=args.labels,
            machine_type=machine_type,
            network=args.network,
            network_tier=args.network_tier,
            subnet=args.subnet,
            private_network_ip=args.private_network_ip,
            no_restart_on_failure=not args.restart_on_failure,
            os=args.os,
            byol=getattr(args, 'byol', False),
            uefi_compatible=uefi_compatible,
            tags=args.tags,
            zone=properties.VALUES.compute.zone.Get(),
            project=args.project,
            output_filter=_OUTPUT_FILTER,
            release_track=(self.ReleaseTrack().id.lower()
                           if self.ReleaseTrack() else None),
            hostname=getattr(args, 'hostname', None),
            no_address=getattr(args, 'no_address', False),
            compute_service_account=getattr(args, 'compute_service_account',
                                            ''),
            scopes=getattr(args, 'scopes', None),
            no_scopes=getattr(args, 'no_scopes', False),
            service_account=getattr(args, 'service_account', None),
            no_service_account=getattr(args, 'no_service_account', False),
        )
예제 #11
0
def _RunCreate(compute_api,
               args,
               support_source_instance,
               support_kms=False,
               support_location_hint=False,
               support_post_key_revocation_action_type=False,
               support_threads_per_core=False,
               support_multi_writer=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_location_hint: Indicate whether location hint is supported.
      support_post_key_revocation_action_type: Indicate whether
        post_key_revocation_action_type is supported.
      support_threads_per_core: Indicates whether changing the number of threads
        per core is supported.
      support_multi_writer: Indicates whether a disk can have multiple writers.

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

  instance_templates_flags.ValidateServiceProxyFlags(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))

  AddScopesForServiceProxy(args)
  AddServiceProxyArgsToMetadata(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)
    stack_type = getattr(args, 'stack_type', None)
    ipv6_network_tier = getattr(args, 'ipv6_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,
            stack_type=stack_type,
            ipv6_network_tier=ipv6_network_tier)
    ]

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

  confidential_instance_config_message = (
      BuildConfidentialInstanceConfigMessage(
          messages=client.messages, args=args))

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

  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=args.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 []) +
                                         (args.create_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,
          support_multi_writer=support_multi_writer))

  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)

  instance_template.properties.confidentialInstanceConfig = (
      confidential_instance_config_message)

  if support_post_key_revocation_action_type and args.IsSpecified(
      'post_key_revocation_action_type'):
    instance_template.properties.postKeyRevocationActionType = arg_utils.ChoiceToEnum(
        args.post_key_revocation_action_type, client.messages.InstanceProperties
        .PostKeyRevocationActionTypeValueValuesEnum)

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

  # If either enable-nested-virtualization or threads-per-core are specified,
  # make an AdvancedMachineFeatures message.
  has_threads_per_core = (
      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_template.properties.advancedMachineFeatures = (
        instance_utils.CreateAdvancedMachineFeaturesMessage(
            client.messages, args.enable_nested_virtualization,
            threads_per_core))

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

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

  _AddSourceInstanceToTemplate(compute_api, args, instance_template,
                               support_source_instance)

  return client.MakeRequests([(client.apitools_client.instanceTemplates,
                               'Insert', request)])
예제 #12
0
    def CreateRequests(self, args):
        """Creates and returns an InstanceTemplates.Insert request.

    Args:
      args: the argparse arguments that this command was invoked with.

    Returns:
      request: a ComputeInstanceTemplatesInsertRequest message object
    """
        self.ValidateDiskFlags(args)
        instance_utils.ValidateLocalSsdFlags(args)

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

        instance_template_ref = self.CreateGlobalReference(args.name)

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

        network_interface = self.CreateNetworkInterfaceMessage(args)

        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)

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

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

        persistent_disks = self.CreateAttachedPersistentDiskMessages(args)
        if create_boot_disk:
            boot_disk_list = [
                self.CreateDefaultBootAttachedDiskMessage(
                    args, boot_disk_size_gb, image_uri)
            ]
        else:
            boot_disk_list = []

        local_ssds = [
            instance_utils.CreateLocalSsdMessage(self, x.get('device-name'),
                                                 x.get('interface'))
            for x in args.local_ssd or []
        ]

        disks = boot_disk_list + persistent_disks + local_ssds

        machine_type = instance_utils.InterpretMachineType(args)

        request = self.messages.ComputeInstanceTemplatesInsertRequest(
            instanceTemplate=self.messages.InstanceTemplate(
                properties=self.messages.InstanceProperties(
                    machineType=machine_type,
                    disks=disks,
                    canIpForward=args.can_ip_forward,
                    metadata=metadata,
                    networkInterfaces=[network_interface],
                    serviceAccounts=service_accounts,
                    scheduling=scheduling,
                    tags=tags,
                ),
                description=args.description,
                name=instance_template_ref.Name(),
            ),
            project=self.context['project'])

        return [request]
예제 #13
0
    def Run(self, args):
        """Creates and runs an InstanceTemplates.Insert request.

    Args:
      args: argparse.Namespace, An object that contains the values for the
          arguments specified in the .Args() method.

    Returns:
      A resource object dispatched by display.Displayer().
    """
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        self.ValidateDiskFlags(args)
        instances_flags.ValidateLocalSsdFlags(args)
        instances_flags.ValidateNicFlags(args)
        instances_flags.ValidateServiceAccountAndScopeArgs(args)
        instances_flags.ValidateAcceleratorArgs(args)

        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, holder.resources))

        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=holder.resources,
                    scope_lister=flags.GetDefaultScopeLister(client),
                    messages=client.messages,
                    network_interface_arg=args.network_interface,
                    region=args.region)
        else:
            network_interfaces = [
                instance_template_utils.CreateNetworkInterfaceMessage(
                    resources=holder.resources,
                    scope_lister=flags.GetDefaultScopeLister(client),
                    messages=client.messages,
                    network=args.network,
                    region=args.region,
                    subnet=args.subnet,
                    address=(instance_template_utils.EPHEMERAL_ADDRESS
                             if not args.no_address and not args.address else
                             args.address))
            ]

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

        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,
                                                       holder.resources)
            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)
        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, holder.resources, instance_template_ref.project,
                getattr(args, 'create_disk', [])))

        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)
            ]
        else:
            boot_disk_list = []

        local_ssds = []
        for x in args.local_ssd or []:
            local_ssd = instance_utils.CreateLocalSsdMessage(
                holder.resources, client.messages, x.get('device-name'),
                x.get('interface'), x.get('size'))
            local_ssds.append(local_ssd)

        disks = (boot_disk_list + persistent_disks + persistent_create_disks +
                 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))

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

        instance_properties = client.messages.InstanceProperties(
            machineType=machine_type,
            disks=disks,
            canIpForward=args.can_ip_forward,
            metadata=metadata,
            networkInterfaces=network_interfaces,
            serviceAccounts=service_accounts,
            scheduling=scheduling,
            tags=tags,
        )

        # TODO(b/36890961): Pass this directly into guestAccelerators once GA.
        if guest_accelerators:
            instance_properties.guestAccelerators = guest_accelerators

        request = client.messages.ComputeInstanceTemplatesInsertRequest(
            instanceTemplate=client.messages.InstanceTemplate(
                properties=instance_properties,
                description=args.description,
                name=instance_template_ref.Name(),
            ),
            project=instance_template_ref.project)

        if getattr(args, 'min_cpu_platform', None):
            request.instanceTemplate.properties.minCpuPlatform = args.min_cpu_platform

        return client.MakeRequests([(client.apitools_client.instanceTemplates,
                                     'Insert', request)])
예제 #14
0
def RunMachineImageOVFImportBuild(args, output_filter, compute_release_track):
    """Run a OVF into VM instance import build on Google Cloud Builder.

  Args:
    args: an argparse namespace. All the arguments that were provided to this
      command invocation.
    output_filter: A list of strings indicating what lines from the log should
      be output. Only lines that start with one of the strings in output_filter
      will be displayed.
    compute_release_track: release track to be used for Compute API calls. One
      of - "alpha", "beta" or ""

  Returns:
    A build object that either streams the output or is displayed as a
    link to the build.

  Raises:
    FailedBuildException: If the build is completed and not 'SUCCESS'.
  """
    project_id = projects_util.ParseProject(
        properties.VALUES.core.project.GetOrFail())

    _CheckIamPermissions(project_id,
                         IMPORT_ROLES_FOR_CLOUDBUILD_SERVICE_ACCOUNT,
                         IMPORT_ROLES_FOR_COMPUTE_SERVICE_ACCOUNT)

    # Make OVF import time-out before gcloud by shaving off 2% from the timeout
    # time, up to a max of 5m (300s).
    two_percent = int(args.timeout * 0.02)
    ovf_import_timeout = args.timeout - min(two_percent, 300)

    machine_type = None
    if args.machine_type or args.custom_cpu or args.custom_memory:
        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))

    ovf_importer_args = []
    AppendArg(ovf_importer_args, 'machine-image-name', args.IMAGE)
    AppendArg(ovf_importer_args, 'machine-image-storage-location',
              args.storage_location)
    AppendArg(ovf_importer_args, 'client-id', 'gcloud')
    AppendArg(ovf_importer_args, 'ovf-gcs-path', args.source_uri)
    AppendBoolArg(ovf_importer_args, 'no-guest-environment',
                  not args.guest_environment)
    AppendBoolArg(ovf_importer_args, 'can-ip-forward', args.can_ip_forward)
    AppendArg(ovf_importer_args, 'description', args.description)
    if args.labels:
        AppendArg(
            ovf_importer_args, 'labels',
            ','.join(['{}={}'.format(k, v) for k, v in args.labels.items()]))
    AppendArg(ovf_importer_args, 'machine-type', machine_type)
    AppendArg(ovf_importer_args, 'network', args.network)
    AppendArg(ovf_importer_args, 'network-tier', args.network_tier)
    AppendArg(ovf_importer_args, 'subnet', args.subnet)
    AppendBoolArg(ovf_importer_args, 'no-restart-on-failure',
                  not args.restart_on_failure)
    AppendArg(ovf_importer_args, 'os', args.os)
    if args.tags:
        AppendArg(ovf_importer_args, 'tags', ','.join(args.tags))
    AppendArg(ovf_importer_args, 'zone', properties.VALUES.compute.zone.Get())
    AppendArg(ovf_importer_args, 'timeout', ovf_import_timeout, '-{0}={1}s')
    AppendArg(ovf_importer_args, 'project', args.project)
    if compute_release_track:
        AppendArg(ovf_importer_args, 'release-track', compute_release_track)

    build_tags = ['gce-daisy', 'gce-ovf-machine-image-import']

    backoff = lambda elapsed: 2 if elapsed < 30 else 15

    return _RunCloudBuild(args,
                          _OVF_IMPORT_BUILDER.format(args.docker_image_tag),
                          ovf_importer_args,
                          build_tags,
                          output_filter,
                          backoff=backoff)
예제 #15
0
def RunMachineImageOVFImportBuild(args, output_filter, release_track):
  """Run a OVF into VM instance import build on Google Cloud Builder.

  Args:
    args: an argparse namespace. All the arguments that were provided to this
      command invocation.
    output_filter: A list of strings indicating what lines from the log should
      be output. Only lines that start with one of the strings in output_filter
      will be displayed.
    release_track: release track of the command used. One of - "alpha", "beta"
      or "ga"

  Returns:
    A build object that either streams the output or is displayed as a
    link to the build.

  Raises:
    FailedBuildException: If the build is completed and not 'SUCCESS'.
  """
  project_id = projects_util.ParseProject(
      properties.VALUES.core.project.GetOrFail())

  _CheckIamPermissions(project_id,
                       frozenset(IMPORT_ROLES_FOR_CLOUDBUILD_SERVICE_ACCOUNT),
                       frozenset(IMPORT_ROLES_FOR_COMPUTE_SERVICE_ACCOUNT))

  machine_type = None
  if args.machine_type or args.custom_cpu or args.custom_memory:
    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))

  ovf_importer_args = []
  AppendArg(ovf_importer_args, 'machine-image-name', args.IMAGE)
  AppendArg(ovf_importer_args, 'machine-image-storage-location',
            args.storage_location)
  AppendArg(ovf_importer_args, 'client-id', 'gcloud')
  AppendArg(ovf_importer_args, 'ovf-gcs-path', args.source_uri)
  AppendBoolArg(ovf_importer_args, 'no-guest-environment',
                not args.guest_environment)
  AppendBoolArg(ovf_importer_args, 'can-ip-forward', args.can_ip_forward)
  AppendArg(ovf_importer_args, 'description', args.description)
  if args.labels:
    AppendArg(ovf_importer_args, 'labels',
              ','.join(['{}={}'.format(k, v) for k, v in args.labels.items()]))
  AppendArg(ovf_importer_args, 'machine-type', machine_type)
  AppendArg(ovf_importer_args, 'network', args.network)
  AppendArg(ovf_importer_args, 'network-tier', args.network_tier)
  AppendArg(ovf_importer_args, 'subnet', args.subnet)
  AppendBoolArg(ovf_importer_args, 'no-restart-on-failure',
                not args.restart_on_failure)
  AppendArg(ovf_importer_args, 'os', args.os)
  if args.tags:
    AppendArg(ovf_importer_args, 'tags', ','.join(args.tags))
  AppendArg(ovf_importer_args, 'zone', properties.VALUES.compute.zone.Get())
  AppendArg(ovf_importer_args, 'timeout', GetDaisyTimeout(args), '-{0}={1}s')
  AppendArg(ovf_importer_args, 'project', args.project)
  if release_track:
    AppendArg(ovf_importer_args, 'release-track', release_track)
  AppendArg(ovf_importer_args, 'client-version', config.CLOUD_SDK_VERSION)
  AppendBoolArg(ovf_importer_args, 'no-external-ip', args.no_address)
  build_tags = ['gce-daisy', 'gce-ovf-machine-image-import']

  backoff = lambda elapsed: 2 if elapsed < 30 else 15

  builder = _GetBuilder(
      args,
      _OVF_IMPORT_BUILDER_EXECUTABLE,
      args.docker_image_tag,
      release_track,
      _GetMachineImageImportRegion,
      use_regionalized_builder=lambda rt: rt == 'alpha')
  return _RunCloudBuild(
      args,
      builder,
      ovf_importer_args,
      build_tags,
      output_filter,
      backoff=backoff,
      log_location=args.log_location)
예제 #16
0
파일: create.py 프로젝트: gyaresu/dotfiles
def _RunCreate(compute_api,
               args,
               support_source_instance,
               support_network_tier=False,
               support_shielded_vms=False,
               support_node_affinity=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_network_tier: Indicates whether network tier is supported or not.
      support_shielded_vms: Indicate whether a shielded vm config is supported
      or not.
      support_node_affinity: Indicate whether node affinity is supported or not.

  Returns:
      A resource object dispatched by display.Displayer().
  """
    _ValidateInstancesFlags(args)
    if support_network_tier:
        instances_flags.ValidateNetworkTierArgs(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))

    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,
                support_network_tier=support_network_tier)
    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,
                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 shieldedVmConfig message.
    if support_shielded_vms:
        shieldedvm_config_message = BuildShieldedVMConfigMessage(
            messages=client.messages, args=args)

    node_affinities = None
    if support_node_affinity:
        node_affinities = sole_tenancy_util.GetSchedulingNodeAffinityListFromArgs(
            args, client.messages)

    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)

    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', [])))

    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)
        ]
    else:
        boot_disk_list = []

    local_ssds = []
    for x in args.local_ssd or []:
        local_ssd = instance_utils.CreateLocalSsdMessage(
            compute_api.resources, client.messages, x.get('device-name'),
            x.get('interface'), x.get('size'))
        local_ssds.append(local_ssd)

    disks = (boot_disk_list + persistent_disks + persistent_create_disks +
             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))

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

    if support_shielded_vms:
        instance_template.properties.shieldedVmConfig = shieldedvm_config_message

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

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

    _AddSourceInstanceToTemplate(compute_api, args, instance_template,
                                 support_source_instance)

    return client.MakeRequests([(client.apitools_client.instanceTemplates,
                                 'Insert', request)])
    def Run(self, args):
        """Issues an InstanceTemplates.Insert request.

    Args:
      args: the argparse arguments that this command was invoked with.

    Returns:
      an InstanceTemplate message object
    """
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        instances_flags.ValidateKonletArgs(args)
        instances_flags.ValidateDiskCommonFlags(args)
        instances_flags.ValidateLocalSsdFlags(args)
        instances_flags.ValidateServiceAccountAndScopeArgs(args)
        instances_flags.ValidateNetworkTierArgs(args,
                                                support_network_tier=True)
        if instance_utils.UseExistingBootDisk(args.disk or []):
            raise exceptions.InvalidArgumentException(
                '--disk', 'Boot disk specified for containerized VM.')

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

        instance_template_ref = (
            CreateWithContainer.InstanceTemplateArg.ResolveAsResource(
                args, holder.resources))

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

        network_interface = instance_template_utils.CreateNetworkInterfaceMessage(
            resources=holder.resources,
            scope_lister=flags.GetDefaultScopeLister(client),
            messages=client.messages,
            network=args.network,
            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=getattr(args, 'network_tier', None))

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

        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)

        if (args.IsSpecified('image') or args.IsSpecified('image_family')
                or args.IsSpecified('image_project')):
            image_expander = image_utils.ImageExpander(client,
                                                       holder.resources)
            image_uri, _ = image_expander.ExpandImageFlag(
                user_project=instance_template_ref.project,
                image=args.image,
                image_family=args.image_family,
                image_project=args.image_project)
            if holder.resources.Parse(image_uri).project != 'cos-cloud':
                log.warn(
                    'This container deployment mechanism requires a '
                    'Container-Optimized OS image in order to work. Select an '
                    'image from a cos-cloud project (cost-stable, cos-beta, '
                    'cos-dev image families).')
        else:
            image_uri = containers_utils.ExpandKonletCosImageFlag(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))

        metadata = containers_utils.CreateKonletMetadataMessage(
            client.messages, args, instance_template_ref.Name(), user_metadata)

        request = client.messages.ComputeInstanceTemplatesInsertRequest(
            instanceTemplate=client.messages.InstanceTemplate(
                properties=client.messages.InstanceProperties(
                    machineType=machine_type,
                    disks=self._CreateDiskMessages(
                        holder, args, boot_disk_size_gb, image_uri,
                        instance_template_ref.project),
                    canIpForward=args.can_ip_forward,
                    metadata=metadata,
                    minCpuPlatform=args.min_cpu_platform,
                    networkInterfaces=[network_interface],
                    serviceAccounts=service_accounts,
                    scheduling=scheduling,
                    tags=containers_utils.CreateTagsMessage(
                        client.messages, args.tags),
                ),
                description=args.description,
                name=instance_template_ref.Name(),
            ),
            project=instance_template_ref.project)

        return client.MakeRequests([(client.apitools_client.instanceTemplates,
                                     'Insert', request)])
예제 #18
0
    def CreateRequests(self, args):
        """Creates and returns an InstanceTemplates.Insert request.

    Args:
      args: the argparse arguments that this command was invoked with.

    Returns:
      request: a ComputeInstanceTemplatesInsertRequest message object
    """
        self.ValidateDiskFlags(args)
        instances_flags.ValidateLocalSsdFlags(args)
        instances_flags.ValidateNicFlags(args)

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

        instance_template_ref = (
            instance_templates_flags.INSTANCE_TEMPLATE_ARG.ResolveAsResource(
                args, self.resources))

        metadata = metadata_utils.ConstructMetadataMessage(
            self.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)(
                    scope_prompter=self,
                    messages=self.messages,
                    network_interface_arg=args.network_interface,
                    region=args.region)
        else:
            network_interfaces = [
                instance_template_utils.CreateNetworkInterfaceMessage(
                    scope_prompter=self,
                    messages=self.messages,
                    network=args.network,
                    region=args.region,
                    subnet=args.subnet,
                    address=(instance_template_utils.EPHEMERAL_ADDRESS
                             if not args.no_address and not args.address else
                             args.address))
            ]

        scheduling = instance_utils.CreateSchedulingMessage(
            messages=self.messages,
            maintenance_policy=args.maintenance_policy,
            preemptible=args.preemptible,
            restart_on_failure=args.restart_on_failure)

        service_accounts = instance_utils.CreateServiceAccountMessages(
            messages=self.messages,
            scopes=([] if args.no_scopes else args.scopes))

        create_boot_disk = not instance_utils.UseExistingBootDisk(args.disk
                                                                  or [])
        if create_boot_disk:
            image_uri, _ = self.ExpandImageFlag(
                image=args.image,
                image_family=args.image_family,
                image_project=args.image_project,
                return_image_resource=True)
        else:
            image_uri = None

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

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

        persistent_create_disks = (
            instance_template_utils.CreatePersistentCreateDiskMessages(
                self, self.messages, getattr(args, 'create_disk', [])))

        if create_boot_disk:
            boot_disk_list = [
                instance_template_utils.CreateDefaultBootAttachedDiskMessage(
                    messages=self.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)
            ]
        else:
            boot_disk_list = []

        local_ssds = []
        for x in args.local_ssd or []:
            local_ssd = instance_utils.CreateLocalSsdMessage(
                self.resources, self.messages, x.get('device-name'),
                x.get('interface'))
            local_ssds.append(local_ssd)

        disks = (boot_disk_list + persistent_disks + persistent_create_disks +
                 local_ssds)

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

        request = self.messages.ComputeInstanceTemplatesInsertRequest(
            instanceTemplate=self.messages.InstanceTemplate(
                properties=self.messages.InstanceProperties(
                    machineType=machine_type,
                    disks=disks,
                    canIpForward=args.can_ip_forward,
                    metadata=metadata,
                    networkInterfaces=network_interfaces,
                    serviceAccounts=service_accounts,
                    scheduling=scheduling,
                    tags=tags,
                ),
                description=args.description,
                name=instance_template_ref.Name(),
            ),
            project=self.project)

        return [request]
def _RunCreate(compute_api,
               args,
               support_source_instance,
               support_kms=False,
               support_post_key_revocation_action_type=False,
               support_multi_writer=False,
               support_mesh=False,
               support_host_error_timeout_seconds=False,
               support_numa_node_count=False,
               support_visible_core_count=False,
               support_disk_architecture=False,
               support_key_revocation_action_type=False,
               support_max_run_duration=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_post_key_revocation_action_type: Indicate whether
        post_key_revocation_action_type is supported.
      support_multi_writer: Indicates whether a disk can have multiple writers.
      support_mesh: Indicates whether adding VM to a Anthos Service Mesh is
        supported.
      support_host_error_timeout_seconds: Indicate the timeout in seconds for
        host error detection.
      support_numa_node_count: Indicates whether setting NUMA node count is
        supported.
      support_visible_core_count: Indicates whether setting a custom visible
      support_disk_architecture: Storage resources can be used to create boot
        disks compatible with ARM64 or X86_64 machine architectures. If this
        field is not specified, the default is ARCHITECTURE_UNSPECIFIED.
      support_key_revocation_action_type: Indicate whether
        key_revocation_action_type is supported.
      support_max_run_duration: Indicate whether max-run-duration or
        termination-time issupported.

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

  instance_templates_flags.ValidateServiceProxyFlags(args)
  if support_mesh:
    instance_templates_flags.ValidateMeshFlag(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))

  AddScopesForServiceProxy(args)
  AddServiceProxyArgsToMetadata(args)

  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)
    stack_type = getattr(args, 'stack_type', None)
    ipv6_network_tier = getattr(args, 'ipv6_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,
            stack_type=stack_type,
            ipv6_network_tier=ipv6_network_tier)
    ]

  if support_mesh:
    ConfigureMeshTemplate(args, instance_template_ref, network_interfaces)

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

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

  confidential_instance_config_message = (
      BuildConfidentialInstanceConfigMessage(
          messages=client.messages, args=args))

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

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

  provisioning_model = None
  if (hasattr(args, 'provisioning_model') and
      args.IsSpecified('provisioning_model')):
    provisioning_model = args.provisioning_model

  termination_action = None
  if (hasattr(args, 'instance_termination_action') and
      args.IsSpecified('instance_termination_action')):
    termination_action = args.instance_termination_action

  max_run_duration = None
  if (hasattr(args, 'max_run_duration') and
      args.IsSpecified('max_run_duration')):
    max_run_duration = args.max_run_duration

  termination_time = None
  if (hasattr(args, 'termination_time') and
      args.IsSpecified('termination_time')):
    termination_time = args.termination_time

  host_error_timeout_seconds = None
  if support_host_error_timeout_seconds and args.IsSpecified(
      'host_error_timeout_seconds'):
    host_error_timeout_seconds = args.host_error_timeout_seconds
  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=args.min_node_cpu,
      location_hint=location_hint,
      provisioning_model=provisioning_model,
      instance_termination_action=termination_action,
      host_error_timeout_seconds=host_error_timeout_seconds,
      max_run_duration=max_run_duration,
      termination_time=termination_time)

  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 []) +
                                         (args.create_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,
          support_multi_writer=support_multi_writer,
          support_disk_architecture=support_disk_architecture))

  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,
            disk_provisioned_iops=args.boot_disk_provisioned_iops)
    ]
  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)

  instance_template.properties.confidentialInstanceConfig = (
      confidential_instance_config_message)

  if args.IsSpecified('network_performance_configs'):
    instance_template.properties.networkPerformanceConfig = (
        instance_utils.GetNetworkPerformanceConfig(args, client))

  if args.IsSpecified('resource_policies'):
    instance_template.properties.resourcePolicies = getattr(
        args, 'resource_policies', [])

  if support_post_key_revocation_action_type and args.IsSpecified(
      'post_key_revocation_action_type'):
    instance_template.properties.postKeyRevocationActionType = arg_utils.ChoiceToEnum(
        args.post_key_revocation_action_type, client.messages.InstanceProperties
        .PostKeyRevocationActionTypeValueValuesEnum)

  if support_key_revocation_action_type and args.IsSpecified(
      'key_revocation_action_type'):
    instance_template.properties.keyRevocationActionType = arg_utils.ChoiceToEnum(
        args.key_revocation_action_type, client.messages.InstanceProperties
        .KeyRevocationActionTypeValueValuesEnum)

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

  # Create an AdvancedMachineFeatures message if any of the features requiring
  # one have been specified.
  has_visible_core_count = (
      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
      (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_template.properties.advancedMachineFeatures = (
        instance_utils.CreateAdvancedMachineFeaturesMessage(
            client.messages, args.enable_nested_virtualization,
            args.threads_per_core,
            args.numa_node_count if support_numa_node_count else None,
            visible_core_count, args.enable_uefi_networking))

  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 = client.messages.InstanceProperties
      instance_template.properties.resourceManagerTags = properties.ResourceManagerTagsValue(
          additionalProperties=[
              properties.ResourceManagerTagsValue.AdditionalProperty(
                  key=key, value=value) for key, value in sorted(
                      six.iteritems(ret_resource_manager_tags))
          ])

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

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

  _AddSourceInstanceToTemplate(compute_api, args, instance_template,
                               support_source_instance)

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