Ejemplo n.º 1
0
    def _ValidateArgs(self, args, compute_client):
        self._ValidateInstanceName(args)
        self._CheckForExistingInstances(args.instance_name, compute_client)

        instances_flags.ValidateNicFlags(args)
        instances_flags.ValidateNetworkTierArgs(args)
        daisy_utils.ValidateZone(args, compute_client)
Ejemplo n.º 2
0
  def Run(self, args):
    instances_flags.ValidateDiskFlags(
        args, enable_kms=self.ReleaseTrack() in [base.ReleaseTrack.ALPHA])
    instances_flags.ValidateLocalSsdFlags(args)
    instances_flags.ValidateNicFlags(args)
    instances_flags.ValidateServiceAccountAndScopeArgs(args)
    instances_flags.ValidateAcceleratorArgs(args)
    if self._support_network_tier:
      instances_flags.ValidateNetworkTierArgs(args)

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

    instance_refs = instances_flags.INSTANCES_ARG.ResolveAsResource(
        args, resource_parser,
        scope_lister=flags.GetDefaultScopeLister(compute_client))

    requests = self._CreateRequests(args, instance_refs,
                                    compute_client, resource_parser)

    if not args.async:
      # TODO(b/63664449): Replace this with poller + progress tracker.
      try:
        # Using legacy MakeRequests (which also does polling) here until
        # replaced by api_lib.utils.waiter.
        return compute_client.MakeRequests(requests)
      except exceptions.ToolException as e:
        invalid_machine_type_message_regex = (
            r'Invalid value for field \'resource.machineType\': .+. '
            r'Machine type with name \'.+\' does not exist in zone \'.+\'\.')
        if re.search(invalid_machine_type_message_regex, e.message):
          raise exceptions.ToolException(
              e.message +
              '\nUse `gcloud compute machine-types list --zones` to see the '
              'available machine  types.')
        raise

    errors_to_collect = []
    responses = compute_client.BatchRequests(requests, errors_to_collect)
    for r in responses:
      err = getattr(r, 'error', None)
      if err:
        errors_to_collect.append(poller.OperationErrors(err.errors))
    if errors_to_collect:
      raise core_exceptions.MultiError(errors_to_collect)

    operation_refs = [holder.resources.Parse(r.selfLink) for r in responses]

    for instance_ref, operation_ref in zip(instance_refs, operation_refs):
      log.status.Print('Instance creation in progress for [{}]: {}'
                       .format(instance_ref.instance, operation_ref.SelfLink()))
    log.status.Print('Use [gcloud compute operations describe URI] command '
                     'to check the status of the operation(s).')
    if not args.IsSpecified('format'):
      # For async output we need a separate format. Since we already printed in
      # the status messages information about operations there is nothing else
      # needs to be printed.
      args.format = 'disable'
    return responses
Ejemplo n.º 3
0
    def Run(self, args):
        flags.ValidatePublicPtrFlags(args)
        if self._support_public_dns:
            flags.ValidatePublicDnsFlags(args)
        if self._support_network_tier:
            flags.ValidateNetworkTierArgs(args)
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        instance_ref = self.CreateReference(client, holder.resources, args)
        get_request = self.GetGetRequest(client, instance_ref)

        objects = client.MakeRequests([get_request])

        new_object = self.Modify(client, args, objects[0])

        # If existing object is equal to the proposed object or if
        # Modify() returns None, then there is no work to be done, so we
        # print the resource and return.
        if not new_object or objects[0] == new_object:
            log.status.Print(
                'No change requested; skipping update for [{0}].'.format(
                    objects[0].name))
            return objects

        return client.MakeRequests(requests=[
            self.GetSetRequest(client, args, instance_ref, new_object)
        ])
Ejemplo n.º 4
0
    def Run(self, args):
        instances_flags.ValidateBulkDiskFlags(
            args,
            enable_snapshots=True,
            enable_source_snapshot_csek=self._support_source_snapshot_csek,
            enable_image_csek=self._support_image_csek)
        instances_flags.ValidateImageFlags(args)
        instances_flags.ValidateLocalSsdFlags(args)
        instances_flags.ValidateNicFlags(args)
        instances_flags.ValidateServiceAccountAndScopeArgs(args)
        instances_flags.ValidateAcceleratorArgs(args)
        instances_flags.ValidateNetworkTierArgs(args)
        instances_flags.ValidateReservationAffinityGroup(args)

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

        project = properties.VALUES.core.project.GetOrFail()
        location = None
        scope = None

        if args.IsSpecified('zone'):
            location = args.zone
            scope = compute_scopes.ScopeEnum.ZONE
        elif args.IsSpecified('region'):
            location = args.region
            scope = compute_scopes.ScopeEnum.REGION

        instances_service, request = self._CreateRequests(
            args, holder, compute_client, resource_parser, project, location,
            scope)

        self._errors = []
        self._log_async = False
        self._status_message = None

        if args.async_:
            self._log_async = True
            try:
                response = instances_service.BulkInsert(request)
                self._operation_selflink = response.selfLink
                return
            except exceptions.HttpError as error:
                raise error

        errors_to_collect = []
        response = compute_client.MakeRequests(
            [(instances_service, 'BulkInsert', request)],
            errors_to_collect=errors_to_collect,
            log_result=False,
            always_return_operation=True,
            no_followup=True)

        self._errors = errors_to_collect
        if response:
            self._status_message = response[0].statusMessage

        return
Ejemplo n.º 5
0
 def _ValidateArgs(self, args):
     instances_flags.ValidateNetworkTierArgs(args)
     instances_flags.ValidateKonletArgs(args)
     instances_flags.ValidateDiskCommonFlags(args)
     instances_flags.ValidateServiceAccountAndScopeArgs(args)
     if instance_utils.UseExistingBootDisk(args.disk or []):
         raise exceptions.InvalidArgumentException(
             '--disk', 'Boot disk specified for containerized VM.')
    def Run(self, args):
        self._ValidateBetaArgs(args)
        instances_flags.ValidateNetworkTierArgs(args)
        instances_flags.ValidatePublicDnsFlags(args)
        instances_flags.ValidatePublicPtrFlags(args)

        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client
        source_instance_template = instance_utils.GetSourceInstanceTemplate(
            args, holder.resources, self.SOURCE_INSTANCE_TEMPLATE)
        skip_defaults = instance_utils.GetSkipDefaults(
            source_instance_template)
        scheduling = instance_utils.GetScheduling(args, client, skip_defaults)
        service_accounts = instance_utils.GetServiceAccounts(
            args, client, skip_defaults)
        user_metadata = instance_utils.GetValidatedMetadata(args, client)
        boot_disk_size_gb = instance_utils.GetBootDiskSizeGb(args)
        instance_refs = instance_utils.GetInstanceRefs(args, client, holder)
        network_interfaces = instance_utils.GetNetworkInterfacesAlpha(
            args, client, holder, instance_refs, skip_defaults)
        machine_type_uris = instance_utils.GetMachineTypeUris(
            args, client, holder, instance_refs, skip_defaults)
        image_uri = self.GetImageUri(args, client, holder, instance_refs)
        labels = containers_utils.GetLabelsMessageWithCosVersion(
            args.labels, image_uri, holder.resources, client.messages.Instance)
        can_ip_forward = instance_utils.GetCanIpForward(args, skip_defaults)
        tags = containers_utils.CreateTagsMessage(client.messages, args.tags)

        requests = []
        for instance_ref, machine_type_uri in zip(instance_refs,
                                                  machine_type_uris):
            metadata = containers_utils.CreateKonletMetadataMessage(
                client.messages, args, instance_ref.Name(), user_metadata)
            disks = instance_utils.CreateDiskMessages(holder, args,
                                                      boot_disk_size_gb,
                                                      image_uri, instance_ref,
                                                      skip_defaults)
            request = client.messages.ComputeInstancesInsertRequest(
                instance=client.messages.Instance(
                    canIpForward=can_ip_forward,
                    disks=disks,
                    description=args.description,
                    labels=labels,
                    machineType=machine_type_uri,
                    metadata=metadata,
                    minCpuPlatform=args.min_cpu_platform,
                    name=instance_ref.Name(),
                    networkInterfaces=network_interfaces,
                    serviceAccounts=service_accounts,
                    scheduling=scheduling,
                    tags=tags),
                sourceInstanceTemplate=source_instance_template,
                project=instance_ref.project,
                zone=instance_ref.zone)

            requests.append(
                (client.apitools_client.instances, 'Insert', request))
        return client.MakeRequests(requests)
    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
    """
        self._ValidateBetaArgs(args)
        instances_flags.ValidateNetworkTierArgs(args)

        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client
        instance_template_ref = self._GetInstanceTemplateRef(args, holder)
        image_uri = self._GetImageUri(args, client, holder,
                                      instance_template_ref)
        labels = containers_utils.GetLabelsMessageWithCosVersion(
            None, image_uri, holder.resources,
            client.messages.InstanceProperties)
        argument_labels = labels_util.ParseCreateArgs(
            args, client.messages.InstanceProperties.LabelsValue)
        if argument_labels:
            labels.additionalProperties.extend(
                argument_labels.additionalProperties)

        metadata = self._GetUserMetadata(args, client, instance_template_ref)
        network_interface = self._GetNetworkInterface(args, client, holder)
        scheduling = self._GetScheduling(args, client)
        service_accounts = self._GetServiceAccounts(args, client)
        machine_type = self._GetMachineType(args)
        disks = self._GetDisks(args, client, holder, instance_template_ref,
                               image_uri)

        request = client.messages.ComputeInstanceTemplatesInsertRequest(
            instanceTemplate=client.messages.InstanceTemplate(
                properties=client.messages.InstanceProperties(
                    machineType=machine_type,
                    disks=disks,
                    canIpForward=args.can_ip_forward,
                    labels=labels,
                    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)])
Ejemplo n.º 8
0
 def _ValidateArgs(self, args, compute_client):
     instances_flags.ValidateNicFlags(args)
     instances_flags.ValidateNetworkTierArgs(args)
     daisy_utils.ValidateZone(args, compute_client)
     try:
         args.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')
Ejemplo n.º 9
0
    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)
Ejemplo n.º 10
0
    def Run(self, args):
        """Invokes request necessary for adding an access config."""
        if self._support_network_tier:
            flags.ValidateNetworkTierArgs(args)

        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

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

        access_config = client.messages.AccessConfig(
            name=args.access_config_name,
            natIP=args.address,
            type=client.messages.AccessConfig.TypeValueValuesEnum.
            ONE_TO_ONE_NAT)

        if self._support_public_dns:
            flags.ValidatePublicDnsFlags(args)
            if args.no_public_dns is True:
                access_config.setPublicDns = False
            elif args.public_dns is True:
                access_config.setPublicDns = True

        if self._support_public_ptr:
            flags.ValidatePublicPtrFlags(args)
            if args.no_public_ptr is True:
                access_config.setPublicPtr = False
            elif args.public_ptr is True:
                access_config.setPublicPtr = True

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

        network_tier = getattr(args, 'network_tier', None)
        if network_tier is not None:
            access_config.networkTier = (
                client.messages.AccessConfig.NetworkTierValueValuesEnum(
                    network_tier))

        request = client.messages.ComputeInstancesAddAccessConfigRequest(
            accessConfig=access_config,
            instance=instance_ref.Name(),
            networkInterface=args.network_interface,
            project=instance_ref.project,
            zone=instance_ref.zone)

        return client.MakeRequests([(client.apitools_client.instances,
                                     'AddAccessConfig', request)])
 def _ValidateArgs(self, args):
   self._ValidateTrackSpecificArgs(args)
   instances_flags.ValidateAcceleratorArgs(args)
   instances_flags.ValidateNicFlags(args)
   instances_flags.ValidateNetworkTierArgs(args)
   instances_flags.ValidateKonletArgs(args)
   instances_flags.ValidateDiskCommonFlags(args)
   instances_flags.ValidateServiceAccountAndScopeArgs(args)
   instances_flags.ValidatePublicPtrFlags(args)
   instances_flags.ValidateNetworkPerformanceConfigsArgs(args)
   instances_flags.ValidateInstanceScheduling(args)
   if instance_utils.UseExistingBootDisk(args.disk or []):
     raise exceptions.InvalidArgumentException(
         '--disk', 'Boot disk specified for containerized VM.')
Ejemplo n.º 12
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)
Ejemplo n.º 13
0
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 _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)])
Ejemplo n.º 15
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)])
  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
    """
    self._ValidateArgs(args)
    instances_flags.ValidateNetworkTierArgs(args)

    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    container_mount_disk = instances_flags.GetValidatedContainerMountDisk(
        holder, args.container_mount_disk, args.disk, args.create_disk)

    client = holder.client
    instance_template_ref = self._GetInstanceTemplateRef(args, holder)
    image_uri = self._GetImageUri(args, client, holder, instance_template_ref)
    labels = containers_utils.GetLabelsMessageWithCosVersion(
        None, image_uri, holder.resources, client.messages.InstanceProperties)
    argument_labels = labels_util.ParseCreateArgs(
        args, client.messages.InstanceProperties.LabelsValue)
    if argument_labels:
      labels.additionalProperties.extend(argument_labels.additionalProperties)

    metadata = self._GetUserMetadata(
        args,
        client,
        instance_template_ref,
        container_mount_disk_enabled=True,
        container_mount_disk=container_mount_disk)
    network_interfaces = self._GetNetworkInterfaces(args, client, holder)
    scheduling = self._GetScheduling(args, client)
    service_accounts = self._GetServiceAccounts(args, client)
    machine_type = self._GetMachineType(args)
    disks = self._GetDisks(
        args,
        client,
        holder,
        instance_template_ref,
        image_uri,
        match_container_mount_disks=True)
    guest_accelerators = (
        instance_template_utils.CreateAcceleratorConfigMessages(
            client.messages, getattr(args, 'accelerator', None)))

    properties = client.messages.InstanceProperties(
        machineType=machine_type,
        disks=disks,
        canIpForward=args.can_ip_forward,
        labels=labels,
        metadata=metadata,
        minCpuPlatform=args.min_cpu_platform,
        networkInterfaces=network_interfaces,
        serviceAccounts=service_accounts,
        scheduling=scheduling,
        tags=containers_utils.CreateTagsMessage(client.messages, args.tags),
        guestAccelerators=guest_accelerators)

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

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

    return client.MakeRequests([(client.apitools_client.instanceTemplates,
                                 'Insert', request)])
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        source_instance_template = self.GetSourceInstanceTemplate(
            args, holder.resources)
        # 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.
        skip_defaults = source_instance_template is not None

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

        if (skip_defaults and not args.IsSpecified('maintenance_policy')
                and not args.IsSpecified('preemptible')
                and not args.IsSpecified('restart_on_failure')):
            scheduling = None
        else:
            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
        if (skip_defaults and not args.IsSpecified('scopes')
                and not args.IsSpecified('no_scopes')
                and not args.IsSpecified('service_account')
                and not args.IsSpecified('no_service_account')):
            service_accounts = []
        else:
            service_accounts = instance_utils.CreateServiceAccountMessages(
                messages=client.messages,
                scopes=[] if args.no_scopes else args.scopes,
                service_account=service_account)

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

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

        instance_refs = instances_flags.INSTANCES_ARG.ResolveAsResource(
            args,
            holder.resources,
            scope_lister=flags.GetDefaultScopeLister(client))

        # Check if the zone is deprecated or has maintenance coming.
        zone_resource_fetcher = zone_utils.ZoneResourceFetcher(client)
        zone_resource_fetcher.WarnForZonalCreation(instance_refs)

        instances_flags.ValidatePublicDnsFlags(args)
        instances_flags.ValidatePublicPtrFlags(args)

        if (skip_defaults and not args.IsSpecified('network')
                and not args.IsSpecified('subnet')
                and not args.IsSpecified('private_network_ip')
                and not args.IsSpecified('no_address')
                and not args.IsSpecified('address')
                and not args.IsSpecified('network_tier')
                and not args.IsSpecified('no_public_dns')
                and not args.IsSpecified('public_dns')
                and not args.IsSpecified('no_public_ptr')
                and not args.IsSpecified('public_ptr')
                and not args.IsSpecified('no_public_ptr_domain')
                and not args.IsSpecified('public_ptr_domain')):
            network_interfaces = []
        else:
            network_interfaces = [
                instance_utils.CreateNetworkInterfaceMessage(
                    resources=holder.resources,
                    compute_client=client,
                    network=args.network,
                    subnet=args.subnet,
                    private_network_ip=args.private_network_ip,
                    no_address=args.no_address,
                    address=args.address,
                    instance_refs=instance_refs,
                    network_tier=args.network_tier,
                    no_public_dns=getattr(args, 'no_public_dns', None),
                    public_dns=getattr(args, 'public_dns', None),
                    no_public_ptr=getattr(args, 'no_public_ptr', None),
                    public_ptr=getattr(args, 'public_ptr', None),
                    no_public_ptr_domain=getattr(args, 'no_public_ptr_domain',
                                                 None),
                    public_ptr_domain=getattr(args, 'public_ptr_domain', None))
            ]

        if (skip_defaults and not args.IsSpecified('machine_type')
                and not args.IsSpecified('custom_cpu')
                and not args.IsSpecified('custom_memory')):
            machine_type_uris = [None for _ in instance_refs]
        else:
            machine_type_uris = instance_utils.CreateMachineTypeUris(
                resources=holder.resources,
                compute_client=client,
                machine_type=args.machine_type,
                custom_cpu=args.custom_cpu,
                custom_memory=args.custom_memory,
                ext=getattr(args, 'custom_extensions', None),
                instance_refs=instance_refs)

        image_uri = containers_utils.ExpandCosImageFlag(client)

        args_labels = getattr(args, 'labels', None)
        labels = None
        if args_labels:
            labels = client.messages.Instance.LabelsValue(
                additionalProperties=[
                    client.messages.Instance.LabelsValue.AdditionalProperty(
                        key=key, value=value)
                    for key, value in sorted(args.labels.iteritems())
                ])

        if skip_defaults and not args.IsSpecified('can_ip_forward'):
            can_ip_forward = None
        else:
            can_ip_forward = args.can_ip_forward

        requests = []
        for instance_ref, machine_type_uri in zip(instance_refs,
                                                  machine_type_uris):
            metadata = containers_utils.CreateMetadataMessage(
                client.messages, args.run_as_privileged,
                args.container_manifest, args.docker_image, args.port_mappings,
                args.run_command, user_metadata, instance_ref.Name())
            request = client.messages.ComputeInstancesInsertRequest(
                instance=client.messages.Instance(
                    canIpForward=can_ip_forward,
                    disks=(self._CreateDiskMessages(holder, args,
                                                    boot_disk_size_gb,
                                                    image_uri, instance_ref,
                                                    skip_defaults)),
                    description=args.description,
                    machineType=machine_type_uri,
                    metadata=metadata,
                    minCpuPlatform=args.min_cpu_platform,
                    name=instance_ref.Name(),
                    networkInterfaces=network_interfaces,
                    serviceAccounts=service_accounts,
                    scheduling=scheduling,
                    tags=containers_utils.CreateTagsMessage(
                        client.messages, args.tags)),
                project=instance_ref.project,
                zone=instance_ref.zone)
            if labels:
                request.instance.labels = labels
            if source_instance_template:
                request.sourceInstanceTemplate = source_instance_template

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

        return client.MakeRequests(requests)
    def Run(self, args):
        """Runs bulk create command.

    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().
    """

        instances_flags.ValidateBulkCreateArgs(args)
        if self._support_enable_target_shape:
            instances_flags.ValidateBulkTargetShapeArgs(args)
        instances_flags.ValidateLocationPolicyArgs(args)
        instances_flags.ValidateBulkDiskFlags(
            args,
            enable_source_snapshot_csek=self._support_source_snapshot_csek,
            enable_image_csek=self._support_image_csek)
        instances_flags.ValidateImageFlags(args)
        instances_flags.ValidateLocalSsdFlags(args)
        instances_flags.ValidateNicFlags(args)
        instances_flags.ValidateServiceAccountAndScopeArgs(args)
        instances_flags.ValidateAcceleratorArgs(args)
        instances_flags.ValidateNetworkTierArgs(args)
        instances_flags.ValidateReservationAffinityGroup(args)
        instances_flags.ValidateNetworkPerformanceConfigsArgs(args)
        instances_flags.ValidateInstanceScheduling(
            args, support_max_run_duration=self._support_max_run_duration)

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

        project = properties.VALUES.core.project.GetOrFail()
        location = None
        scope = None

        if args.IsSpecified('zone'):
            location = args.zone
            scope = compute_scopes.ScopeEnum.ZONE
        elif args.IsSpecified('region'):
            location = args.region
            scope = compute_scopes.ScopeEnum.REGION

        instances_service, request = self._CreateRequests(
            args, holder, compute_client, resource_parser, project, location,
            scope)

        self._errors = []
        self._log_async = False
        self._status_message = None

        if args.async_:
            self._log_async = True
            try:
                response = instances_service.BulkInsert(request)
                self._operation_selflink = response.selfLink
                return {'operationGroupId': response.operationGroupId}
            except exceptions.HttpException as error:
                raise error

        errors_to_collect = []
        response = compute_client.MakeRequests(
            [(instances_service, 'BulkInsert', request)],
            errors_to_collect=errors_to_collect,
            log_result=False,
            always_return_operation=True,
            no_followup=True)

        self._errors = errors_to_collect
        if response:
            operation_group_id = response[0].operationGroupId
            result = _GetResult(compute_client, request, operation_group_id)
            if result['createdInstanceCount'] is not None and result[
                    'failedInstanceCount'] is not None:
                self._status_message = 'VM instances created: {}, failed: {}.'.format(
                    result['createdInstanceCount'],
                    result['failedInstanceCount'])
            return result
        return
Ejemplo n.º 19
0
    def Run(self, args):
        instances_flags.ValidateDiskFlags(
            args,
            enable_kms=self._support_kms,
            enable_snapshots=True,
            enable_source_snapshot_csek=self._support_source_snapshot_csek,
            enable_image_csek=self._support_image_csek)
        instances_flags.ValidateImageFlags(args)
        instances_flags.ValidateLocalSsdFlags(args)
        instances_flags.ValidateNicFlags(args)
        instances_flags.ValidateServiceAccountAndScopeArgs(args)
        instances_flags.ValidateAcceleratorArgs(args)
        instances_flags.ValidateNetworkTierArgs(args)
        instances_flags.ValidateReservationAffinityGroup(args)

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

        instance_refs = instance_utils.GetInstanceRefs(args, compute_client,
                                                       holder)

        requests = self._CreateRequests(args, instance_refs,
                                        instance_refs[0].project,
                                        instance_refs[0].zone, compute_client,
                                        resource_parser, holder)
        if not args.async_:
            # TODO(b/63664449): Replace this with poller + progress tracker.
            try:
                # Using legacy MakeRequests (which also does polling) here until
                # replaced by api_lib.utils.waiter.
                return compute_client.MakeRequests(requests)
            except exceptions.ToolException as e:
                invalid_machine_type_message_regex = (
                    r'Invalid value for field \'resource.machineType\': .+. '
                    r'Machine type with name \'.+\' does not exist in zone \'.+\'\.'
                )
                if re.search(invalid_machine_type_message_regex,
                             six.text_type(e)):
                    raise exceptions.ToolException(
                        six.text_type(e) +
                        '\nUse `gcloud compute machine-types list --zones` to see the '
                        'available machine  types.')
                raise

        errors_to_collect = []
        responses = compute_client.BatchRequests(requests, errors_to_collect)
        for r in responses:
            err = getattr(r, 'error', None)
            if err:
                errors_to_collect.append(poller.OperationErrors(err.errors))
        if errors_to_collect:
            raise core_exceptions.MultiError(errors_to_collect)

        operation_refs = [
            holder.resources.Parse(r.selfLink) for r in responses
        ]

        log.status.Print(
            'NOTE: The users will be charged for public IPs when VMs '
            'are created.')

        for instance_ref, operation_ref in zip(instance_refs, operation_refs):
            log.status.Print(
                'Instance creation in progress for [{}]: {}'.format(
                    instance_ref.instance, operation_ref.SelfLink()))
        log.status.Print(
            'Use [gcloud compute operations describe URI] command '
            'to check the status of the operation(s).')
        if not args.IsSpecified('format'):
            # For async output we need a separate format. Since we already printed in
            # the status messages information about operations there is nothing else
            # needs to be printed.
            args.format = 'disable'
        return responses
  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.ValidateDockerArgs(args)
    instances_flags.ValidateDiskCommonFlags(args)
    instances_flags.ValidateLocalSsdFlags(args)
    instances_flags.ValidateServiceAccountAndScopeArgs(args)
    instances_flags.ValidateNetworkTierArgs(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, 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=args.network_tier)

    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)

    image_uri = containers_utils.ExpandCosImageFlag(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(
        client.messages, args.run_as_privileged, args.container_manifest,
        args.docker_image, args.port_mappings, args.run_command,
        user_metadata, instance_template_ref.Name())

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