def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        # Retrieve the specified compute instance.
        instance_ref = flags.INSTANCE_ARG.ResolveAsResource(
            args,
            holder.resources,
            scope_lister=flags.GetInstanceZoneScopeLister(client))

        request = client.messages.ComputeInstancesGetRequest(
            **instance_ref.AsDict())
        instance = client.MakeRequests([(client.apitools_client.instances,
                                         'Get', request)])[0]

        # Get JSON Schema for Compute Engine instances (located in
        # third_party/py/googlecloudsdk/schemas/...).
        schema_path = self.GetSchemaPath(for_help=False)

        # Write configuration data to either designated file or stdout.
        if args.destination:
            with files.FileWriter(args.destination) as stream:
                export_util.Export(message=instance,
                                   stream=stream,
                                   schema_path=schema_path)
            return log.status.Print('Exported [{}] to \'{}\'.'.format(
                instance.name, args.destination))
        else:
            export_util.Export(message=instance,
                               stream=sys.stdout,
                               schema_path=schema_path)
Exemple #2
0
  def Run(self, args):
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client

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

    request = (client.apitools_client.instances,
               'GetSerialPortOutput',
               client.messages.ComputeInstancesGetSerialPortOutputRequest(
                   instance=instance_ref.Name(),
                   project=instance_ref.project,
                   port=args.port,
                   start=args.start,
                   zone=instance_ref.zone))

    errors = []
    objects = client.MakeRequests(
        requests=[request],
        errors_to_collect=errors)
    if errors:
      raise GetSerialPortOutputException(
          'Could not fetch serial port output: ' +
          ','.join([error[1] for error in errors]))

    response = objects[0]
    self._start = args.start
    self._response = response
    return response
Exemple #3
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client
        messages = client.messages

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

        maintenance_policy_ref = util.ParseMaintenancePolicy(
            holder.resources,
            args.resource_maintenance_policies,
            project=instance_ref.project,
            region=util.GetRegionFromZone(instance_ref.zone))

        add_request = messages.ComputeInstancesAddMaintenancePoliciesRequest(
            instance=instance_ref.Name(),
            project=instance_ref.project,
            zone=instance_ref.zone,
            instancesAddMaintenancePoliciesRequest=messages.
            InstancesAddMaintenancePoliciesRequest(
                maintenancePolicies=[maintenance_policy_ref.SelfLink()]))

        return client.MakeRequests([(client.apitools_client.instances,
                                     'AddMaintenancePolicies', add_request)])
Exemple #4
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

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

        policy = client.MakeRequests([
            (client.apitools_client.instances, 'GetIamPolicy',
             client.messages.ComputeInstancesGetIamPolicyRequest(
                 resource=instance_ref.instance,
                 zone=instance_ref.zone,
                 project=instance_ref.project))
        ])[0]
        iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)
        return client.MakeRequests([
            (client.apitools_client.instances, 'SetIamPolicy',
             client.messages.ComputeInstancesSetIamPolicyRequest(
                 policy=policy,
                 project=instance_ref.project,
                 resource=instance_ref.instance,
                 zone=instance_ref.zone))
        ])[0]
Exemple #5
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client
        self._ValidateArgs(args, client)

        ref = flags.INSTANCES_ARG_FOR_OS_UPGRADE.ResolveAsResource(
            args,
            holder.resources,
            scope_lister=instances_flags.GetInstanceZoneScopeLister(client))
        instance_uri = 'projects/{0}/zones/{1}/instances/{2}'.format(
            ref.project, ref.zone, ref.Name())

        _PromptForUpgrade(ref, args)
        args.zone = ref.zone

        log.warning(
            'Upgrading OS. This usually takes around 40 minutes but may '
            'take up to 90 minutes.')

        return daisy_utils.RunOsUpgradeBuild(
            args=args,
            output_filter=_OUTPUT_FILTER,
            instance_uri=instance_uri,
            release_track=self.ReleaseTrack().id.lower()
            if self.ReleaseTrack() else None)
    def Run(self, args):
        """Issues request necessary for setting scheduling options."""
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

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

        scheduling_options = client.messages.Scheduling()

        scheduling_options.automaticRestart = args.restart_on_failure

        if args.maintenance_policy:
            scheduling_options.onHostMaintenance = (
                client.messages.Scheduling.OnHostMaintenanceValueValuesEnum(
                    args.maintenance_policy))

        request = client.messages.ComputeInstancesSetSchedulingRequest(
            instance=instance_ref.Name(),
            project=instance_ref.project,
            scheduling=scheduling_options,
            zone=instance_ref.zone)

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

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

        resource_policies = []
        for policy in args.resource_policies:
            resource_policy_ref = util.ParseResourcePolicyWithZone(
                holder.resources,
                policy,
                project=instance_ref.project,
                zone=instance_ref.zone)
            resource_policies.append(resource_policy_ref.SelfLink())

        add_request = messages.ComputeInstancesAddResourcePoliciesRequest(
            instance=instance_ref.Name(),
            project=instance_ref.project,
            zone=instance_ref.zone,
            instancesAddResourcePoliciesRequest=messages.
            InstancesAddResourcePoliciesRequest(
                resourcePolicies=resource_policies))

        return client.MakeRequests([(client.apitools_client.instances,
                                     'AddResourcePolicies', add_request)])
    def Run(self, args):
        """Issues requests necessary to update Container."""
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

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

        instance = client.apitools_client.instances.Get(
            client.messages.ComputeInstancesGetRequest(
                **instance_ref.AsDict()))

        container_mount_disk = instances_flags.GetValidatedContainerMountDisk(
            holder,
            args.container_mount_disk,
            instance.disks, [],
            for_update=True,
            client=client.apitools_client)

        containers_utils.UpdateInstance(
            holder,
            client,
            instance_ref,
            instance,
            args,
            container_mount_disk_enabled=True,
            container_mount_disk=container_mount_disk)
Exemple #9
0
    def CreateReference(self, client, resources, args):
        flags.ValidatePublicDnsFlags(args)

        return flags.INSTANCE_ARG.ResolveAsResource(
            args,
            resources,
            scope_lister=flags.GetInstanceZoneScopeLister(client))
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

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

        policy = client.MakeRequests([
            (client.apitools_client.instances, 'GetIamPolicy',
             client.messages.ComputeInstancesGetIamPolicyRequest(
                 resource=instance_ref.instance,
                 zone=instance_ref.zone,
                 project=instance_ref.project))
        ])[0]
        iam_util.AddBindingToIamPolicy(client.messages.Binding, policy,
                                       args.member, args.role)
        # TODO(b/78371568): Construct the ZoneSetPolicyRequest directly
        # out of the parsed policy.
        return client.MakeRequests([
            (client.apitools_client.instances, 'SetIamPolicy',
             client.messages.ComputeInstancesSetIamPolicyRequest(
                 zoneSetPolicyRequest=client.messages.ZoneSetPolicyRequest(
                     bindings=policy.bindings, etag=policy.etag),
                 project=instance_ref.project,
                 resource=instance_ref.instance,
                 zone=instance_ref.zone))
        ])[0]
    def Run(self, args):
        compute_holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = compute_holder.client

        flags.ValidateServiceAccountAndScopeArgs(args)

        instance_ref = flags.INSTANCE_ARG.ResolveAsResource(
            args,
            compute_holder.resources,
            default_scope=compute_scope.ScopeEnum.ZONE,
            scope_lister=flags.GetInstanceZoneScopeLister(client))

        email = self._email(args, instance_ref, client)
        scopes = self._scopes(args, instance_ref, client)

        if scopes and not email:
            raise exceptions.ScopesWithoutServiceAccountException(
                'Can not set scopes when there is no service acoount.')

        request = client.messages.ComputeInstancesSetServiceAccountRequest(
            instancesSetServiceAccountRequest=(
                client.messages.InstancesSetServiceAccountRequest(
                    email=email, scopes=scopes)),
            project=instance_ref.project,
            zone=instance_ref.zone,
            instance=instance_ref.Name())

        return client.MakeRequests([(client.apitools_client.instances,
                                     'SetServiceAccount', request)])
Exemple #12
0
    def Run(self, args):
        """Issue API requests for route creation, callable from multiple tracks."""
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        network_uri = self.NETWORK_ARG.ResolveAsResource(
            args, holder.resources).SelfLink()

        route_ref = self.ROUTE_ARG.ResolveAsResource(args, holder.resources)

        if args.next_hop_instance:
            next_hop_instance_uri = self.INSTANCE_ARG.ResolveAsResource(
                args,
                holder.resources,
                scope_lister=instance_flags.GetInstanceZoneScopeLister(
                    client)).SelfLink()
        else:
            if args.next_hop_instance_zone:
                raise exceptions.ToolException(
                    '[--next-hop-instance-zone] can only be specified in conjunction '
                    'with [--next-hop-instance].')
            next_hop_instance_uri = None

        if args.next_hop_gateway:
            next_hop_gateway_ref = flags.NEXT_HOP_GATEWAY_ARG.ResolveAsResource(
                args, holder.resources)
            next_hop_gateway_uri = next_hop_gateway_ref.SelfLink()
        else:
            next_hop_gateway_uri = None

        next_hop_vpn_tunnel_uri = None

        if args.next_hop_vpn_tunnel:
            next_hop_vpn_tunnel_uri = self.VPN_TUNNEL_ARG.ResolveAsResource(
                args,
                holder.resources,
                scope_lister=compute_flags.GetDefaultScopeLister(
                    client)).SelfLink()
        elif args.next_hop_vpn_tunnel_region:
            raise exceptions.ToolException(
                '[--next-hop-vpn-tunnel-region] can only be specified in '
                'conjunction with [--next-hop-vpn-tunnel].')

        request = client.messages.ComputeRoutesInsertRequest(
            project=route_ref.project,
            route=client.messages.Route(
                description=args.description,
                destRange=args.destination_range,
                name=route_ref.Name(),
                network=network_uri,
                nextHopInstance=next_hop_instance_uri,
                nextHopIp=args.next_hop_address,
                nextHopGateway=next_hop_gateway_uri,
                nextHopVpnTunnel=next_hop_vpn_tunnel_uri,
                priority=args.priority,
                tags=args.tags,
            ))
        return client.MakeRequests([(client.apitools_client.routes, 'Insert',
                                     request)])
Exemple #13
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client.apitools_client
        messages = holder.client.messages

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

        result = None

        labels_operation_ref = None
        min_cpu_platform_operation_ref = None
        deletion_protection_operation_ref = None
        shielded_vm_config_ref = None

        labels_diff = labels_util.Diff.FromUpdateArgs(args)
        if labels_diff.MayHaveUpdates():
            instance = client.instances.Get(
                messages.ComputeInstancesGetRequest(**instance_ref.AsDict()))
            result = instance
            labels_operation_ref = self._GetLabelsOperationRef(
                labels_diff, instance, instance_ref, holder)
        if hasattr(args,
                   'min_cpu_platform') and args.min_cpu_platform is not None:
            min_cpu_platform_operation_ref = self._GetMinCpuPlatformOperationRef(
                args.min_cpu_platform, instance_ref, holder)
        if args.deletion_protection is not None:
            deletion_protection_operation_ref = (
                self._GetDeletionProtectionOperationRef(
                    args.deletion_protection, instance_ref, holder))

        operation_poller = poller.Poller(client.instances)
        result = self._WaitForResult(operation_poller, labels_operation_ref,
                                     'Updating labels of instance [{0}]',
                                     instance_ref.Name()) or result
        result = self._WaitForResult(
            operation_poller, min_cpu_platform_operation_ref,
            'Changing minimum CPU platform of instance [{0}]',
            instance_ref.Name()) or result
        result = self._WaitForResult(
            operation_poller, deletion_protection_operation_ref,
            'Setting deletion protection of instance [{0}] to [{1}]',
            instance_ref.Name(), args.deletion_protection) or result
        if self.ReleaseTrack() == base.ReleaseTrack.ALPHA:
            if (hasattr(args, 'shielded_vm_secure_boot')
                    or hasattr(args, 'shielded_vm_vtpm')):
                shielded_vm_config_ref = self._GetShieldedVMConfigRef(
                    instance_ref, args, holder)
                result = self._WaitForResult(
                    operation_poller, shielded_vm_config_ref,
                    'Setting shieldedVMConfig  of instance [{0}]',
                    instance_ref.Name()) or result

        return result
 def GetInstance(cls, holder, args):
     instance_ref = flags.INSTANCE_ARG.ResolveAsResource(
         args,
         holder.resources,
         scope_lister=flags.GetInstanceZoneScopeLister(holder.client))
     request = holder.client.messages.ComputeInstancesGetRequest(
         **instance_ref.AsDict())
     return holder.client.MakeRequests([
         (holder.client.apitools_client.instances, "Get", request)
     ])[0]
Exemple #15
0
  def Run(self, args):
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client

    csek_key_file = args.csek_key_file
    request_list = []
    instance_refs = flags.INSTANCES_ARG.ResolveAsResource(
        args, holder.resources,
        scope_lister=flags.GetInstanceZoneScopeLister(client))
    if csek_key_file:
      instances = self.GetInstances(client, instance_refs)
    else:
      instances = [None for _ in instance_refs]
    for instance_ref, instance in zip(instance_refs, instances):
      disks = []

      if csek_key_file:
        allow_rsa_encrypted = self.ReleaseTrack() in [base.ReleaseTrack.ALPHA,
                                                      base.ReleaseTrack.BETA]
        csek_keys = csek_utils.CsekKeyStore.FromArgs(args, allow_rsa_encrypted)
        for disk in instance.disks:
          disk_resource = resources.REGISTRY.Parse(disk.source)

          disk_key_or_none = csek_utils.MaybeLookupKeyMessage(
              csek_keys, disk_resource, client.apitools_client)

          if disk_key_or_none:
            disks.append(client.messages.CustomerEncryptionKeyProtectedDisk(
                diskEncryptionKey=disk_key_or_none,
                source=disk.source))

      if disks:
        encryption_req = client.messages.InstancesStartWithEncryptionKeyRequest(
            disks=disks)

        request = (
            client.apitools_client.instances,
            'StartWithEncryptionKey',
            client.messages.ComputeInstancesStartWithEncryptionKeyRequest(
                instance=instance_ref.Name(),
                instancesStartWithEncryptionKeyRequest=encryption_req,
                project=instance_ref.project,
                zone=instance_ref.zone))
      else:
        request = (
            client.apitools_client.instances,
            'Start',
            client.messages.ComputeInstancesStartRequest(
                instance=instance_ref.Name(),
                project=instance_ref.project,
                zone=instance_ref.zone))

      request_list.append(request)
    return client.MakeRequests(request_list)
    def _FetchInstance(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client
        ssh_helper = ssh_utils.BaseSSHCLIHelper()

        instance_ref = flags.SSH_INSTANCE_RESOLVER.ResolveResources(
            [args.instance_name],
            scope.ScopeEnum.ZONE,
            args.zone,
            holder.resources,
            scope_lister=flags.GetInstanceZoneScopeLister(client))[0]
        return instance_ref, ssh_helper.GetInstance(client, instance_ref)
Exemple #17
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

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

        requests = []
        for instance_ref in instance_refs:
            discard_local_ssd = None
            if self.ReleaseTrack() != base.ReleaseTrack.GA:
                discard_local_ssd = args.discard_local_ssd
            requests.append(
                (client.apitools_client.instances, 'Suspend',
                 self._CreateSuspendRequest(client, instance_ref,
                                            discard_local_ssd)))

        errors_to_collect = []
        responses = client.BatchRequests(requests, errors_to_collect)
        if errors_to_collect:
            raise exceptions.MultiError(errors_to_collect)

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

        if args.async_:
            for operation_ref in operation_refs:
                log.status.Print(
                    'Suspend instance in progress for [{}].'.format(
                        operation_ref.SelfLink()))
            log.status.Print(
                'Use [gcloud compute operations describe URI] command to check the '
                'status of the operation(s).')
            return responses

        operation_poller = poller.BatchPoller(client,
                                              client.apitools_client.instances,
                                              instance_refs)

        result = waiter.WaitFor(operation_poller,
                                poller.OperationBatch(operation_refs),
                                'Suspending instance(s) {0}'.format(', '.join(
                                    i.Name() for i in instance_refs)),
                                max_wait_ms=None)

        for instance_ref in instance_refs:
            log.status.Print('Updated [{0}].'.format(instance_ref))

        return result
Exemple #18
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 Run(self, args):
        """Issues requests necessary to update Container."""
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

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

        # fetch the Instance resource
        instance = client.apitools_client.instances.Get(
            client.messages.ComputeInstancesGetRequest(
                **instance_ref.AsDict()))

        # find gce-container-declaration metadata entry
        for metadata in instance.metadata.items:
            if metadata.key == containers_utils.GCE_CONTAINER_DECLARATION:
                # update gce-container-declaration
                containers_utils.UpdateMetadata(metadata, args)

                # update Google Compute Engine resource
                operation = client.apitools_client.instances.SetMetadata(
                    client.messages.ComputeInstancesSetMetadataRequest(
                        metadata=instance.metadata, **instance_ref.AsDict()))

                operation_ref = holder.resources.Parse(
                    operation.selfLink, collection='compute.zoneOperations')

                operation_poller = poller.Poller(
                    client.apitools_client.instances)
                waiter.WaitFor(
                    operation_poller, operation_ref,
                    'Updating specification of container [{0}]'.format(
                        instance_ref.Name()))

                # restart the Virtual Machine
                operation = client.apitools_client.instances.Reset(
                    client.messages.ComputeInstancesResetRequest(
                        **instance_ref.AsDict()))

                operation_ref = holder.resources.Parse(
                    operation.selfLink, collection='compute.zoneOperations')

                operation_poller = poller.Poller(
                    client.apitools_client.instances)
                return waiter.WaitFor(
                    operation_poller, operation_ref,
                    'Restarting container [{0}]'.format(instance_ref.Name()))

        raise containers_utils.NoGceContainerDeclarationMetadataKey()
Exemple #20
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        target_instance = flags.INSTANCE_ARG.ResolveAsResource(
            args,
            holder.resources,
            scope_lister=flags.GetInstanceZoneScopeLister(holder.client))
        destination_zone = holder.resources.Parse(
            args.destination_zone,
            params={'project': target_instance.project},
            collection='compute.zones')

        client = holder.client.apitools_client
        messages = holder.client.messages

        request = messages.ComputeProjectsMoveInstanceRequest(
            instanceMoveRequest=messages.InstanceMoveRequest(
                destinationZone=destination_zone.SelfLink(),
                targetInstance=target_instance.SelfLink(),
            ),
            project=target_instance.project,
        )

        result = client.projects.MoveInstance(request)
        operation_ref = resources.REGISTRY.Parse(
            result.name,
            params={'project': target_instance.project},
            collection='compute.globalOperations')

        if args.async_:
            log.UpdatedResource(
                operation_ref,
                kind='gce instance {0}'.format(target_instance.Name()),
                is_async=True,
                details='Use [gcloud compute operations describe] command '
                'to check the status of this operation.')
            return result

        destination_instance_ref = holder.resources.Parse(
            target_instance.Name(),
            collection='compute.instances',
            params={
                'project': target_instance.project,
                'zone': destination_zone.Name()
            })

        operation_poller = poller.Poller(client.instances,
                                         destination_instance_ref)
        return waiter.WaitFor(
            operation_poller, operation_ref,
            'Moving gce instance {0}'.format(target_instance.Name()))
Exemple #21
0
    def _Run(self,
             args,
             support_disk_scope=False,
             support_force_attach=False,
             support_boot=False):
        """Invokes a request for attaching a disk to an instance."""
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

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

        disk_ref = self.ParseDiskRef(holder.resources, args, instance_ref,
                                     support_disk_scope)

        if args.mode == 'rw':
            mode = client.messages.AttachedDisk.ModeValueValuesEnum.READ_WRITE
        else:
            mode = client.messages.AttachedDisk.ModeValueValuesEnum.READ_ONLY

        allow_rsa_encrypted = self.ReleaseTrack() in [
            base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA
        ]
        csek_keys = csek_utils.CsekKeyStore.FromArgs(args, allow_rsa_encrypted)
        disk_key_or_none = csek_utils.MaybeLookupKeyMessage(
            csek_keys, disk_ref, client.apitools_client)

        attached_disk = client.messages.AttachedDisk(
            deviceName=args.device_name,
            mode=mode,
            source=disk_ref.SelfLink(),
            type=client.messages.AttachedDisk.TypeValueValuesEnum.PERSISTENT,
            diskEncryptionKey=disk_key_or_none)

        if support_boot and args.boot:
            attached_disk.boot = args.boot

        request = client.messages.ComputeInstancesAttachDiskRequest(
            instance=instance_ref.Name(),
            project=instance_ref.project,
            attachedDisk=attached_disk,
            zone=instance_ref.zone)

        if support_force_attach and args.force_attach:
            request.forceAttach = args.force_attach

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

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

        request = client.messages.ComputeInstancesGetRequest(
            **instance_ref.AsDict())

        return client.MakeRequests([(client.apitools_client.instances, 'Get',
                                     request)])[0]
Exemple #23
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        instance_refs = flags.INSTANCES_ARG.ResolveAsResource(
            args,
            holder.resources,
            scope_lister=flags.GetInstanceZoneScopeLister(client))
        return client.MakeRequests([
            (client.apitools_client.instances, 'Stop',
             self._CreateStopRequest(client, instance_ref,
                                     args.discard_local_ssd))
            for instance_ref in instance_refs
        ])
  def Run(self, args):
    """Issues requests necessary to update Container."""
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client

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

    instance = client.apitools_client.instances.Get(
        client.messages.ComputeInstancesGetRequest(**instance_ref.AsDict()))

    containers_utils.UpdateInstance(holder, client, instance_ref, instance,
                                    args)
  def _Run(self, args):
    """Issues request necessary for setting scheduling options."""
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client

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

    scheduling_options = client.messages.Scheduling()

    scheduling_options.automaticRestart = args.restart_on_failure

    if args.IsSpecified('preemptible'):
      scheduling_options.preemptible = args.preemptible

    cleared_fields = []

    if args.IsSpecified('min_node_cpu'):
      scheduling_options.minNodeCpus = int(args.min_node_cpu)
    elif args.IsSpecified('clear_min_node_cpu'):
      scheduling_options.minNodeCpus = None
      cleared_fields.append('minNodeCpus')

    if args.IsSpecified('maintenance_policy'):
      scheduling_options.onHostMaintenance = (
          client.messages.Scheduling.OnHostMaintenanceValueValuesEnum(
              args.maintenance_policy))

    if instance_utils.IsAnySpecified(args, 'node', 'node_affinity_file',
                                     'node_group'):
      affinities = sole_tenancy_util.GetSchedulingNodeAffinityListFromArgs(
          args, client.messages)
      scheduling_options.nodeAffinities = affinities
    elif args.IsSpecified('clear_node_affinities'):
      scheduling_options.nodeAffinities = []
      cleared_fields.append('nodeAffinities')

    with holder.client.apitools_client.IncludeFields(cleared_fields):
      request = client.messages.ComputeInstancesSetSchedulingRequest(
          instance=instance_ref.Name(),
          project=instance_ref.project,
          scheduling=scheduling_options,
          zone=instance_ref.zone)

      return client.MakeRequests([(client.apitools_client.instances,
                                   'SetScheduling', request)])
Exemple #26
0
  def Run(self, args):
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client

    instance_refs = flags.INSTANCES_ARG.ResolveAsResource(
        args, holder.resources,
        scope_lister=flags.GetInstanceZoneScopeLister(client))
    request_list = []
    for instance_ref in instance_refs:
      request = client.messages.ComputeInstancesResetRequest(
          instance=instance_ref.Name(),
          project=instance_ref.project,
          zone=instance_ref.zone)

      request_list.append((client.apitools_client.instances, 'Reset', request))
    return client.MakeRequests(request_list)
Exemple #27
0
    def Run(self, args):
        """See base.UpdateCommand."""
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())

        instance_ref = None
        if args.instance is not None:
            instance_ref = self.INSTANCE_ARG.ResolveAsResource(
                args,
                holder.resources,
                scope_lister=instance_flags.GetInstanceZoneScopeLister(
                    holder.client))
        return self._Run(args,
                         support_bfd=True,
                         support_enable=True,
                         support_bfd_mode=True,
                         instance_ref=instance_ref)
Exemple #28
0
  def _ResolveInstance(self, args):
    """Resolves the arguments into an instance.

    Args:
      args: The command line arguments.
    Returns:
      An instance reference to a VM.
    """
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    compute_client = holder.client
    resources = holder.resources
    instance_ref = instance_flags.INSTANCE_ARG.ResolveAsResource(
        args,
        resources,
        scope_lister=instance_flags.GetInstanceZoneScopeLister(compute_client))
    return instance_ref
Exemple #29
0
  def Run(self, args):
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client.apitools_client
    messages = holder.client.messages

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

    update_labels = labels_util.GetUpdateLabelsDictFromArgs(args)
    remove_labels = labels_util.GetRemoveLabelsListFromArgs(args)

    result = None

    labels_operation_ref = None
    min_cpu_platform_operation_ref = None
    deletion_protection_operation_ref = None

    if update_labels or remove_labels:
      instance = client.instances.Get(
          messages.ComputeInstancesGetRequest(**instance_ref.AsDict()))
      result = instance
      labels_operation_ref = self._GetLabelsOperationRef(
          update_labels, remove_labels, instance, instance_ref, holder)
    if hasattr(args, 'min_cpu_platform') and args.min_cpu_platform is not None:
      min_cpu_platform_operation_ref = self._GetMinCpuPlatformOperationRef(
          args.min_cpu_platform, instance_ref, holder)
    deletion_protection = getattr(args, 'deletion_protection', None)
    if deletion_protection is not None:
      deletion_protection_operation_ref = (
          self._GetDeletionProtectionOperationRef(
              args.deletion_protection, instance_ref, holder))

    operation_poller = poller.Poller(client.instances)
    result = self._WaitForResult(
        operation_poller, labels_operation_ref,
        'Updating labels of instance [{0}]', instance_ref.Name()) or result
    result = self._WaitForResult(
        operation_poller, min_cpu_platform_operation_ref,
        'Changing minimum CPU platform of instance [{0}]',
        instance_ref.Name()) or result
    result = self._WaitForResult(
        operation_poller, deletion_protection_operation_ref,
        'Setting deletion protection of instance [{0}] to [{1}]',
        instance_ref.Name(), deletion_protection) or result
    return result
Exemple #30
0
  def _GetHostKeyFromInstance(self, zone, ssh_helper, instance):
    """Wrapper around SSH Utils to get the host keys for SSH."""
    instance_ref = instance_flags.SSH_INSTANCE_RESOLVER.ResolveResources(
        [instance.name], compute_scope.ScopeEnum.ZONE, zone,
        self.resources,
        scope_lister=instance_flags.GetInstanceZoneScopeLister(self.client))[0]
    project = ssh_helper.GetProject(self.client, instance_ref.project)
    host_keys = ssh_helper.GetHostKeysFromGuestAttributes(
        self.client, instance_ref, instance, project)

    if host_keys is not None and not host_keys:
      # Only display this message if there was an attempt to retrieve
      # host keys but it was unsuccessful(yielded empty dict). If Guest
      # Attributes is disabled, there is no attempt to retrieve host keys.
      log.status.Print('Unable to retrieve host keys from instance metadata. '
                       'Continuing.')
    return host_keys