コード例 #1
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      A serialized object (dict) describing the results of the operation.
      This description fits the Resource described in the ResourceRegistry under
      'pubsub.projects.subscriptions'.

    Raises:
      An HttpException if there was a problem calling the
      API subscriptions.Patch command.
    """
        msgs = self.context['pubsub_msgs']
        pubsub = self.context['pubsub']

        name = util.SubscriptionFormat(args.subscription)

        mask = []
        subscription = msgs.Subscription(name=name)
        if args.ack_deadline is not None:
            mask.append('ackDeadlineSeconds')
            subscription.ackDeadlineSeconds = args.ack_deadline
        if args.push_endpoint is not None:
            mask.append('pushConfig')
            subscription.pushConfig = msgs.PushConfig(
                pushEndpoint=args.push_endpoint)
        if args.retain_acked_messages is not None:
            mask.append('retainAckedMessages')
            subscription.retainAckedMessages = args.retain_acked_messages
        if args.message_retention_duration is not None:
            mask.append('messageRetentionDuration')
            if args.message_retention_duration != DEFAULT_MESSAGE_RETENTION_VALUE:
                subscription.messageRetentionDuration = args.message_retention_duration

        patch_req = msgs.PubsubProjectsSubscriptionsPatchRequest(
            updateSubscriptionRequest=msgs.UpdateSubscriptionRequest(
                subscription=subscription, updateMask=','.join(mask)),
            name=name)

        # TODO(b/32275310): Conform to gcloud error handling guidelines.  This is
        # currently consistent with the rest of the gcloud pubsub commands.
        try:
            result = pubsub.projects_subscriptions.Patch(patch_req)
            failed = None
        except api_ex.HttpError as error:
            result = subscription
            exc = exceptions.HttpException(error)
            failed = exc.payload.status_message

        result = util.SubscriptionDisplayDict(result, failed)
        log.UpdatedResource(name, kind='subscription', failed=failed)
        return result
コード例 #2
0
  def Run(self, args):
    """Returns a request for moving a disk."""
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())

    target_disk = Move.disk_arg.ResolveAsResource(
        args, holder.resources,
        scope_lister=flags.GetDefaultScopeLister(holder.client))
    destination_zone = holder.resources.Parse(
        args.destination_zone,
        params={
            'project': properties.VALUES.core.project.GetOrFail,
        },
        collection='compute.zones')

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

    request = messages.ComputeProjectsMoveDiskRequest(
        diskMoveRequest=messages.DiskMoveRequest(
            destinationZone=destination_zone.SelfLink(),
            targetDisk=target_disk.SelfLink(),
        ),
        project=target_disk.project,
    )

    result = client.projects.MoveDisk(request)
    operation_ref = resources.REGISTRY.Parse(
        result.name,
        params={
            'project': properties.VALUES.core.project.GetOrFail,
        },
        collection='compute.globalOperations')

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

    destination_disk_ref = holder.resources.Parse(
        target_disk.Name(),
        params={
            'project': destination_zone.project,
            'zone': destination_zone.Name()
        },
        collection='compute.disks')

    operation_poller = poller.Poller(client.disks, destination_disk_ref)

    return waiter.WaitFor(
        operation_poller, operation_ref,
        'Moving disk {0}'.format(target_disk.Name()))
コード例 #3
0
    def Run(self, args):
        """Updates settings of a Cloud SQL instance using the patch api method.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A dict object representing the operations resource describing the patch
      operation if the patch was successful.
    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing the
          command.
    """

        sql_client = self.context['sql_client']
        sql_messages = self.context['sql_messages']
        resources = self.context['registry']

        validate.ValidateInstanceName(args.instance)
        instance_ref = resources.Parse(args.instance,
                                       collection='sql.instances')

        original_instance_resource = sql_client.instances.Get(
            instance_ref.Request())

        patch_instance = instances.InstancesV1Beta3.ConstructInstanceFromArgs(
            sql_messages, args, original=original_instance_resource)
        patch_instance.project = instance_ref.project
        patch_instance.instance = instance_ref.instance

        cleared_fields = self._GetConfirmedClearedFields(args, patch_instance)

        with sql_client.IncludeFields(cleared_fields):
            result = sql_client.instances.Patch(patch_instance)

        operation_ref = resources.Create(
            'sql.operations',
            operation=result.operation,
            project=instance_ref.project,
            instance=instance_ref.instance,
        )

        if args. async:
            return sql_client.operations.Get(operation_ref.Request())

        operations.OperationsV1Beta3.WaitForOperation(
            sql_client, operation_ref, 'Patching Cloud SQL instance')

        log.UpdatedResource(instance_ref)

        changed_instance_resource = sql_client.instances.Get(
            instance_ref.Request())
        return _Result(changed_instance_resource, original_instance_resource)
コード例 #4
0
ファイル: upgrade.py プロジェクト: bopopescu/dotfiles-2
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """
        adapter = self.context['api_adapter']
        location_get = self.context['location_get']
        location = location_get(args)
        cluster_ref = adapter.ParseCluster(args.name, location)
        concurrent_node_count = getattr(args, 'concurrent_node_count', None)

        try:
            cluster = adapter.GetCluster(cluster_ref)
        except apitools_exceptions.HttpError as error:
            log.warning(
                'Problem loading details of cluster to upgrade: {}'.format(
                    console_attr.SafeText(error)))
            cluster = None

        upgrade_message = container_command_util.ClusterUpgradeMessage(
            name=args.name,
            cluster=cluster,
            master=args.master,
            node_pool_name=args.node_pool,
            new_version=args.cluster_version,
            concurrent_node_count=concurrent_node_count)

        console_io.PromptContinue(message=upgrade_message,
                                  throw_if_unattended=True,
                                  cancel_on_no=True)

        options = api_adapter.UpdateClusterOptions(
            version=args.cluster_version,
            update_master=args.master,
            update_nodes=(not args.master),
            node_pool=args.node_pool,
            image_type=args.image_type,
            image=args.image,
            image_project=args.image_project,
            concurrent_node_count=concurrent_node_count)

        try:
            op_ref = adapter.UpdateCluster(cluster_ref, options)
        except apitools_exceptions.HttpError as error:
            raise exceptions.HttpException(error, util.HTTP_ERROR_FORMAT)

        if not args. async:
            adapter.WaitForOperation(
                op_ref, 'Upgrading {0}'.format(cluster_ref.clusterId))

            log.UpdatedResource(cluster_ref)
コード例 #5
0
  def Run(self, args):
    client = self.context['dataproc_client']
    messages = self.context['dataproc_messages']

    cluster_ref = util.ParseCluster(args.name, self.context)

    cluster_config = messages.ClusterConfiguration()
    changed_fields = []

    has_changes = False

    if args.new_num_workers is not None:
      log.warn('--new-num-workers parameter is deprecated and will be removed '
               'in a future release. Please use --num-workers instead')
      args.num_workers = args.new_num_workers

    if args.num_workers is not None:
      worker_config = messages.InstanceGroupConfiguration(
          numInstances=args.num_workers)
      cluster_config.workerConfiguration = worker_config
      changed_fields.append('configuration.worker_configuration.num_instances')
      has_changes = True

    if args.num_preemptible_workers is not None:
      worker_config = messages.InstanceGroupConfiguration(
          numInstances=args.num_preemptible_workers)
      cluster_config.secondaryWorkerConfiguration = worker_config
      changed_fields.append(
          'configuration.secondary_worker_configuration.num_instances')
      has_changes = True

    if not has_changes:
      raise exceptions.ToolException(
          'Must specify at least one cluster parameter to update.')

    cluster = messages.Cluster(
        configuration=cluster_config,
        clusterName=cluster_ref.clusterName,
        projectId=cluster_ref.projectId)

    request = messages.DataprocProjectsClustersPatchRequest(
        clusterName=cluster_ref.clusterName,
        projectId=cluster_ref.projectId,
        cluster=cluster,
        updateMask=','.join(changed_fields))

    operation = client.projects_clusters.Patch(request)
    util.WaitForOperation(
        operation,
        self.context,
        message='Waiting for cluster update operation',
        timeout_s=3600 * 3)

    cluster = client.projects_clusters.Get(cluster_ref.Request())
    log.UpdatedResource(cluster_ref)
    return cluster
コード例 #6
0
  def Run(self, args):
    """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      A serialized object (dict) describing the results of the operation. This
      description fits the Resource described in the ResourceRegistry under
      'pubsub.projects.subscriptions'.

    Raises:
      An HttpException if there was a problem calling the
      API subscriptions.Patch command.
    """
    client = subscriptions.SubscriptionsClient()
    subscription_ref = args.CONCEPTS.subscription.Parse()
    dead_letter_topic = getattr(args, 'dead_letter_topic', None)
    max_delivery_attempts = getattr(args, 'max_delivery_attempts', None)
    clear_dead_letter_policy = getattr(args, 'clear_dead_letter_policy', None)

    labels_update = labels_util.ProcessUpdateArgsLazy(
        args, client.messages.Subscription.LabelsValue,
        orig_labels_thunk=lambda: client.Get(subscription_ref).labels)

    no_expiration = False
    expiration_period = getattr(args, 'expiration_period', None)
    if expiration_period:
      if expiration_period == subscriptions.NEVER_EXPIRATION_PERIOD_VALUE:
        no_expiration = True
        expiration_period = None

    try:
      result = client.Patch(
          subscription_ref,
          ack_deadline=args.ack_deadline,
          push_config=util.ParsePushConfig(args),
          retain_acked_messages=args.retain_acked_messages,
          labels=labels_update.GetOrNone(),
          message_retention_duration=args.message_retention_duration,
          no_expiration=no_expiration,
          expiration_period=expiration_period,
          dead_letter_topic=dead_letter_topic,
          max_delivery_attempts=max_delivery_attempts,
          clear_dead_letter_policy=clear_dead_letter_policy)
    except subscriptions.NoFieldsSpecifiedError:
      if not any(args.IsSpecified(arg) for arg in ('clear_labels',
                                                   'update_labels',
                                                   'remove_labels')):
        raise
      log.status.Print('No update to perform.')
      result = None
    else:
      log.UpdatedResource(subscription_ref.RelativeName(), kind='subscription')
    return result
コード例 #7
0
ファイル: update.py プロジェクト: Akiho-Yasuda/wip
    def Run(self, args):
        resource_name = iam_util.EmailToAccountResourceName(
            args.service_account)
        client, messages = util.GetClientAndMessages()

        result = client.projects_serviceAccounts.Update(
            messages.ServiceAccount(name=resource_name,
                                    displayName=args.display_name))
        log.UpdatedResource(args.service_account, kind='serviceAccount')
        return result
コード例 #8
0
 def Run(self, args):
   projects = self.context['projects_client']
   messages = self.context['projects_messages']
   project_ref = self.GetProject(args.id)
   result = projects.projects.Update(
       messages.Project(
           projectId=project_ref.Name(),
           name=args.name))
   log.UpdatedResource(project_ref)
   return result
コード例 #9
0
 def Run(self, args):
     projects = self.context['projects_client']
     messages = self.context['projects_messages']
     resources = self.context['projects_resources']
     project_ref = resources.Parse(
         args.id, collection='cloudresourcemanager.projects')
     result = projects.projects.Update(
         messages.Project(projectId=project_ref.Name(), name=args.name))
     log.UpdatedResource(project_ref)
     return result
コード例 #10
0
 def Run(self, args):
     versions_client = versions_api.VersionsClient()
     operations_client = operations.OperationsClient()
     version_ref = args.CONCEPTS.version.Parse()
     versions_util.Update(versions_client,
                          operations_client,
                          version_ref,
                          args,
                          enable_user_code=True)
     log.UpdatedResource(args.version, kind='ML Engine version')
コード例 #11
0
  def Run(self, args):
    client = BmsClient()
    volume = args.CONCEPTS.volume.Parse()
    labels_update = None
    labels_diff = labels_util.Diff.FromUpdateArgs(args)

    if not labels_diff.MayHaveUpdates():
      raise exceptions.NoConfigurationChangeError(
          'No configuration change was requested. Did you mean to include the '
          'flags `--update-labels`, `--remove-labels`, or `--clear-labels?`')

    orig_resource = client.GetVolume(volume)
    labels_update = labels_diff.Apply(
        client.messages.Volume.LabelsValue,
        orig_resource.labels).GetOrNone()

    op_ref = client.UpdateVolume(
        volume_resource=volume,
        labels=labels_update,
        snapshot_schedule_policy_resource=None,
        remove_snapshot_schedule_policy=None,
        snapshot_auto_delete=None)

    if op_ref.done:
      log.UpdatedResource(volume.Name(), kind='volume')
      return op_ref

    if args.async_:
      log.status.Print('Update request issued for: [{}]\nCheck operation '
                       '[{}] for status.'.format(volume.Name(), op_ref.name))
      return op_ref

    op_resource = resources.REGISTRY.ParseRelativeName(
        op_ref.name,
        collection='baremetalsolution.operations',
        api_version='v1')
    poller = waiter.CloudOperationPollerNoResources(
        client.operation_service)
    res = waiter.WaitFor(poller, op_resource,
                         'Waiting for operation [{}] to complete'.format(
                             op_ref.name))
    log.UpdatedResource(volume.Name(), kind='volume')
    return res
コード例 #12
0
    def Run(self, args):
        client = devices.DevicesClient()

        device_ref = args.CONCEPTS.device.Parse()
        data = util.ReadConfigData(args)

        response = client.ModifyConfig(device_ref, data,
                                       args.version_to_update)
        log.UpdatedResource(device_ref.Name(), 'configuration for device')
        return response
コード例 #13
0
    def Run(self, args):
        client = services.ServicesClient()
        service_ref = args.CONCEPTS.service.Parse()
        annotations = util.ParseAnnotationsArg(args.annotations,
                                               _RESOURCE_TYPE)

        result = client.Update(service_ref, annotations)
        log.UpdatedResource(service_ref.servicesId, _RESOURCE_TYPE)

        return result
コード例 #14
0
 def Run(self, args):
   labels_diff = labels_util.Diff.FromUpdateArgs(args)
   if args.name is None and not labels_diff.MayHaveUpdates():
     raise ArgumentError('At least one of --name, --update-labels or '
                         '--remove-labels must be specified.')
   project_ref = command_lib_util.ParseProject(args.id)
   result = projects_api.Update(project_ref, name=args.name,
                                labels_diff=labels_diff)
   log.UpdatedResource(project_ref)
   return result
コード例 #15
0
    def Run(self, args):
        """Creates or updates a policy from a JSON or YAML file.

    This first converts the contents of the specified file into a policy object.
    It then fetches the current policy using GetPolicy. If it does not exist,
    the policy is created using CreatePolicy. If it does, the retrieved policy
    is checked to see if it needs to be updated. If so, the policy is updated
    using UpdatePolicy.

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

    Returns:
      The created or updated policy.
    """
        policy_service = org_policy_service.PolicyService()
        org_policy_messages = org_policy_service.OrgPolicyMessages()

        input_policy = utils.GetMessageFromFile(
            args.policy_file,
            org_policy_messages.GoogleCloudOrgpolicyV2alpha1Policy)

        if not input_policy.name:
            raise exceptions.InvalidInputError(
                'Name field not present in the organization policy.')

        get_request = org_policy_messages.OrgpolicyPoliciesGetRequest(
            name=input_policy.name)
        try:
            policy = policy_service.Get(get_request)
        except api_exceptions.HttpNotFoundError:
            constraint = org_policy_utils.GetConstraintFromPolicyName(
                input_policy.name)
            parent = org_policy_utils.GetResourceFromPolicyName(
                input_policy.name)

            create_request = org_policy_messages.OrgpolicyPoliciesCreateRequest(
                constraint=constraint,
                parent=parent,
                googleCloudOrgpolicyV2alpha1Policy=input_policy)
            create_response = policy_service.Create(create_request)
            log.CreatedResource(input_policy.name, 'policy')
            return create_response

        if policy == input_policy:
            return policy

        update_request = org_policy_messages.OrgpolicyPoliciesPatchRequest(
            name=input_policy.name,
            forceUnconditionalWrite=False,
            googleCloudOrgpolicyV2alpha1Policy=input_policy)
        update_response = policy_service.Patch(update_request)
        log.UpdatedResource(input_policy.name, 'policy')
        return update_response
コード例 #16
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Cluster message for the successfully updated node pool.

    Raises:
      util.Error, if creation failed.
    """
        adapter = self.context['api_adapter']
        location_get = self.context['location_get']
        location = location_get(args)
        pool_ref = adapter.ParseNodePool(args.name, location)
        options = self.ParseUpdateNodePoolOptions(args)

        if options.node_labels is not None:
            console_io.PromptContinue(message=(
                'The previous user-specified labels on this node pool will be '
                'replaced by \'{labels}\'').format(
                    labels=args.GetValue('node_labels')),
                                      throw_if_unattended=True,
                                      cancel_on_no=True)

        if options.node_taints is not None:
            console_io.PromptContinue(message=(
                'The previous user-specified taints on this node pool will be '
                'replaced by \'{taints}\'').format(
                    taints=args.GetValue('node_taints')),
                                      throw_if_unattended=True,
                                      cancel_on_no=True)

        if options.tags is not None:
            console_io.PromptContinue(message=(
                'The previous user-specified tags on this node pool will be '
                'replaced by \'{tags}\'').format(tags=args.GetValue('tags')),
                                      throw_if_unattended=True,
                                      cancel_on_no=True)

        try:
            operation_ref = adapter.UpdateNodePool(pool_ref, options)

            adapter.WaitForOperation(operation_ref,
                                     'Updating node pool {0}'.format(
                                         pool_ref.nodePoolId),
                                     timeout_s=args.timeout)
            pool = adapter.GetNodePool(pool_ref)
        except apitools_exceptions.HttpError as error:
            raise exceptions.HttpException(error, util.HTTP_ERROR_FORMAT)

        log.UpdatedResource(pool_ref)
        return pool
コード例 #17
0
ファイル: update.py プロジェクト: PrateekKhatri/gcloud_cli
    def Run(self, args):
        api_version = util.GetApiFromTrack(self.ReleaseTrack())
        client = util.GetApiClient(api_version)
        messages = apis.GetMessagesModule('dns', api_version)

        # Get Response Policy Rule
        response_policy_rule_ref = args.CONCEPTS.response_policy_rule.Parse()
        response_policy_rule_name = response_policy_rule_ref.Name()

        response_policy_rule = messages.ResponsePolicyRule(
            ruleName=response_policy_rule_name)

        response_policy = messages.ResponsePolicy(
            responsePolicyName=args.response_policy)

        to_update = _FetchResponsePolicyRule(response_policy.responsePolicyName, \
                                                  response_policy_rule.ruleName,\
                                                  api_version)

        if not args.IsSpecified('local_data') and not args.IsSpecified(
                'behavior'):
            log.status.Print('Nothing to update.')
            return to_update

        if args.IsSpecified('local_data'):
            to_update.behavior = None
            rrsets = []
            for rrset in args.local_data:
                resource_record_set = messages.ResourceRecordSet(
                    name=rrset.get('name'),
                    type=rrset.get('type'),
                    ttl=rrset.get('ttl'),
                    rrdatas=rrset.get('rrdatas').split('|'))
                rrsets.append(resource_record_set)
            to_update.localData = messages.ResponsePolicyRuleLocalData(
                localDatas=rrsets)

        if args.IsSpecified('behavior'):
            to_update.localData = None
            to_update.behavior = command_util\
                .ParseResponsePolicyRulesBehavior(args, api_version)

        update_req = messages.DnsResponsePolicyRulesUpdateRequest(
            responsePolicy=response_policy.responsePolicyName,
            responsePolicyRule=response_policy_rule.ruleName,
            responsePolicyRuleResource=to_update,
            project=properties.VALUES.core.project.Get())

        updated_response_policy_rule = client.responsePolicyRules.Update(
            update_req)

        log.UpdatedResource(updated_response_policy_rule.responsePolicyRule,
                            kind='ResponsePolicyRule')

        return updated_response_policy_rule
コード例 #18
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        messages = holder.client.messages
        service = holder.client.apitools_client.networks

        network_ref = self.NETWORK_ARG.ResolveAsResource(
            args, holder.resources)

        if args.switch_to_custom_subnet_mode:
            prompt_msg = 'Network [{0}] will be switched to custom mode. '.format(
                network_ref.Name()) + 'This operation cannot be undone.'
            console_io.PromptContinue(message=prompt_msg,
                                      default=True,
                                      cancel_on_no=True)
            result = service.SwitchToCustomMode(
                messages.ComputeNetworksSwitchToCustomModeRequest(
                    project=network_ref.project, network=network_ref.Name()))
            operation_ref = resources.REGISTRY.Parse(
                result.name,
                params={'project': network_ref.project},
                collection='compute.globalOperations')

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

            operation_poller = poller.Poller(service, network_ref)
            return waiter.WaitFor(operation_poller, operation_ref,
                                  'Switching network to custom-mode')

        if args.bgp_routing_mode or getattr(args, 'multicast_mode', None):
            network_resource = messages.Network()
            if args.bgp_routing_mode:
                network_resource.routingConfig = messages.NetworkRoutingConfig(
                )
                network_resource.routingConfig.routingMode = (
                    messages.NetworkRoutingConfig.RoutingModeValueValuesEnum(
                        args.bgp_routing_mode.upper()))
            if getattr(args, 'multicast_mode', None):
                network_resource.multicastMode = (
                    messages.Network.MulticastModeValueValuesEnum(
                        args.multicast_mode.upper()))
            resource = service.Patch(
                messages.ComputeNetworksPatchRequest(
                    project=network_ref.project,
                    network=network_ref.Name(),
                    networkResource=network_resource))

        return resource
コード例 #19
0
    def Run(self, args):
        network = args.CONCEPTS.vmware_engine_network.Parse()
        client = NetworksClient()
        is_async = args.async_
        operation = client.Update(network, description=args.description)
        if is_async:
            log.UpdatedResource(operation.name,
                                kind='VMware Engine network',
                                is_async=True)
            return operation

        resource = client.WaitForOperation(
            operation_ref=client.GetOperationRef(operation),
            message='waiting for VMware Engine network [{}] to be updated'.
            format(network.RelativeName()),
            has_result=True)
        log.UpdatedResource(resource,
                            kind='VMware Engine network',
                            is_async=False)
        return resource
コード例 #20
0
  def Run(self, args):
    client = registrations.RegistrationsClient()
    args.registration = util.NormalizeResourceName(args.registration)
    registration_ref = args.CONCEPTS.registration.Parse()

    registration = client.Get(registration_ref)
    util.AssertRegistrationOperational(registration)

    contacts = contacts_util.ParseContactData(args.contact_data_from_file)
    contact_privacy = contacts_util.ParseContactPrivacy(args.contact_privacy)
    public_contacts_ack = contacts_util.ParsePublicContactsAck(args.notices)

    if contacts is None:
      contacts = contacts_util.PromptForContacts(registration.contactSettings)

    if contact_privacy is None:
      choices = list(
          map(flags.CONTACT_PRIVACY_ENUM_MAPPER.GetChoiceForEnum,
              registration.supportedPrivacy))
      contact_privacy = contacts_util.PromptForContactPrivacy(
          choices, registration.contactSettings.privacy)

    if contacts is None and contact_privacy is None:
      # Nothing to update.
      return None

    new_privacy = contact_privacy or registration.contactSettings.privacy
    if not public_contacts_ack and new_privacy == client.messages.ContactSettings.PrivacyValueValuesEnum.PUBLIC_CONTACT_DATA:
      merged_contacts = contacts_util.MergeContacts(
          prev_contacts=registration.contactSettings, new_contacts=contacts)
      public_contacts_ack = contacts_util.PromptForPublicContactsAck(
          registration.domainName, merged_contacts)

    response = client.ConfigureContacts(
        registration_ref,
        contacts,
        contact_privacy,
        public_contacts_ack,
        validate_only=args.validate_only)

    if args.validate_only:
      log.status.Print('The command will not have any effect because '
                       'validate-only flag is present.')
    else:
      response = util.WaitForOperation(response, args.async_)
      note = None
      if not args.async_ and self.CheckPendingContacts(registration_ref):
        note = ('Note:\nThe contact settings are currently pending.\nIn order '
                'to finalize the update you need to confirm the '
                'change using an email sent to the registrant.')
      log.UpdatedResource(
          registration_ref.Name(), 'registration', args.async_, details=note)

    return response
コード例 #21
0
ファイル: update.py プロジェクト: bopopescu/packmybot
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      The updated sink with its new destination.
    """
        # One of the flags is required to update the sink.
        # log_filter can be an empty string, so check explicitly for None.
        if not args.destination and args.log_filter is None:
            raise exceptions.ToolException(
                '[destination] or --log-filter argument is required')

        # Calling Update on a non-existing sink creates it.
        # We need to make sure it exists, otherwise we would create it.
        try:
            if args.log:
                sink = self.GetLogSink()
            elif args.service:
                sink = self.GetLogServiceSink()
            else:
                sink = self.GetProjectSink()
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))

        # Only update fields that were passed to the command.
        if args.destination:
            destination = args.destination
        else:
            destination = sink.destination

        if args.log_filter is not None:
            log_filter = args.log_filter
        else:
            log_filter = sink.filter

        sink_ref = self.context['sink_reference']
        updated_sink = self.context['logging_messages'].LogSink(
            name=sink_ref.sinksId, destination=destination, filter=log_filter)

        try:
            if args.log:
                result = self.UpdateLogSink(updated_sink)
            elif args.service:
                result = self.UpdateLogServiceSink(updated_sink)
            else:
                result = self.UpdateProjectSink(updated_sink)
            log.UpdatedResource(sink_ref)
            return result
        except apitools_base.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
コード例 #22
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        messages = holder.client.messages
        service = holder.client.apitools_client.routers

        router_ref = self.ROUTER_ARG.ResolveAsResource(args, holder.resources)

        request_type = messages.ComputeRoutersGetRequest
        replacement = service.Get(request_type(**router_ref.AsDict()))

        # Retrieve specified NAT and update base fields.
        existing_nat = nats_utils.FindNatOrRaise(replacement, args.name)
        nat = nats_utils.UpdateNatMessage(existing_nat, args, holder,
                                          self.with_private_nat,
                                          self.with_subnet_all)

        request_type = messages.ComputeRoutersPatchRequest
        result = service.Patch(
            request_type(project=router_ref.project,
                         region=router_ref.region,
                         router=router_ref.Name(),
                         routerResource=replacement))

        operation_ref = resources.REGISTRY.Parse(
            result.name,
            collection='compute.regionOperations',
            params={
                'project': router_ref.project,
                'region': router_ref.region,
            })

        if args.async_:
            log.UpdatedResource(
                operation_ref,
                kind='nat [{0}] in router [{1}]'.format(
                    nat.name, router_ref.Name()),
                is_async=True,
                details='Run the [gcloud compute operations describe] command '
                'to check the status of this operation.')
            return result

        target_router_ref = holder.resources.Parse(
            router_ref.Name(),
            collection='compute.routers',
            params={
                'project': router_ref.project,
                'region': router_ref.region,
            })

        operation_poller = poller.Poller(service, target_router_ref)
        return waiter.WaitFor(
            operation_poller, operation_ref,
            'Updating nat [{0}] in router [{1}]'.format(
                nat.name, router_ref.Name()))
コード例 #23
0
  def Run(self, args):
    client = devices.DevicesClient()

    device_ref = args.CONCEPTS.device.Parse()

    metadata = util.ParseMetadata(args.metadata, args.metadata_from_file,
                                  client.messages)

    device = client.Patch(device_ref, blocked=args.blocked, metadata=metadata)
    log.UpdatedResource(device_ref.Name(), 'device')
    return device
コード例 #24
0
ファイル: update.py プロジェクト: AlexisMarie8330/Doll
 def Run(self, args):
     service = self.OrganizationsClient()
     org_ref = self.GetOrganizationRef(args.id)
     request = (service.client.MESSAGES_MODULE.
                CloudresourcemanagerOrganizationsGetRequest(
                    organizationsId=org_ref.organizationsId))
     org = service.Get(request)
     org.displayName = args.display_name
     result = service.Update(org)
     log.UpdatedResource(org_ref)
     return result
コード例 #25
0
ファイル: delete.py プロジェクト: Guliux10/bchacks_deepbreath
    def Run(self, args):
        """Deletes a whole policy or removes rules containing the specified condition from the policy.

    If --condition is not specified, then the policy is deleted using
    DeletePolicy.

    If --condition is specified, then the policy is fetched using GetPolicy. It
    then searches for and removes the rules that contain the specified condition
    from the policy. If the policy is empty after this operation and
    inheritFromParent is False, the policy is deleted using DeletePolicy. If
    not, the policy is updated using UpdatePolicy.

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

    Returns:
       If the policy is deleted, then messages.GoogleProtobufEmpty. If only
       a partial delete is issued, then the updated policy.
    """
        policy_service = org_policy_service.PolicyService()
        org_policy_messages = org_policy_service.OrgPolicyMessages()

        policy_name = utils.GetPolicyNameFromArgs(args)

        if args.IsSpecified('condition') and args.IsSpecified('label_parent'):
            utils.TransformLabelDisplayNameConditionToLabelNameCondition(args)

        if args.condition is not None:
            get_request = org_policy_messages.OrgpolicyPoliciesGetRequest(
                name=policy_name)
            policy = policy_service.Get(get_request)

            new_policy = copy.deepcopy(policy)
            new_policy.spec.rules = org_policy_utils.GetNonMatchingRulesFromPolicy(
                policy, args.condition)

            if policy == new_policy:
                return policy

            if new_policy.spec.rules or new_policy.spec.inheritFromParent:
                update_request = org_policy_messages.OrgpolicyPoliciesPatchRequest(
                    name=policy_name,
                    forceUnconditionalWrite=False,
                    googleCloudOrgpolicyV2alpha1Policy=new_policy)
                update_response = policy_service.Patch(update_request)
                log.UpdatedResource(policy_name, 'policy')
                return update_response

        delete_request = org_policy_messages.OrgpolicyPoliciesDeleteRequest(
            name=policy_name)
        delete_response = policy_service.Delete(delete_request)
        log.DeletedResource(policy_name, 'policy')
        return delete_response
コード例 #26
0
    def Run(self, args):
        resource_name = iam_util.EmailToAccountResourceName(args.name)
        current = self.iam_client.projects_serviceAccounts.Get(
            self.messages.IamProjectsServiceAccountsGetRequest(
                name=resource_name))

        result = self.iam_client.projects_serviceAccounts.Update(
            self.messages.ServiceAccount(name=resource_name,
                                         etag=current.etag,
                                         displayName=args.display_name))
        log.UpdatedResource(args.name, kind='service account')
        return result
コード例 #27
0
ファイル: update.py プロジェクト: sarahdactyl71/gneiss-rocks
    def Run(self, args):
        client = devices.DevicesClient()

        device_ref = util.ParseDevice(args.id,
                                      registry=args.registry,
                                      region=args.region)
        enabled_state = util.ParseEnableDevice(args.enable_device,
                                               client=client)

        device = client.Patch(device_ref, enabled_state=enabled_state)
        log.UpdatedResource(device_ref.Name(), 'device')
        return device
コード例 #28
0
 def Run(self, args):
     with endpoint_util.MlEndpointOverrides(region=args.region):
         versions_client = versions_api.VersionsClient()
         operations_client = operations.OperationsClient()
         version_ref = args.CONCEPTS.version.Parse()
         versions_util.Update(
             versions_client,
             operations_client,
             version_ref,
             args,
         )
         log.UpdatedResource(args.version, kind='AI Platform version')
コード例 #29
0
ファイル: update.py プロジェクト: saranraju90/multik8s
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        messages = holder.client.messages
        service = holder.client.apitools_client.routers

        router_ref = self.ROUTER_ARG.ResolveAsResource(args, holder.resources)

        request_type = messages.ComputeRoutersGetRequest
        router = service.Get(request_type(**router_ref.AsDict()))

        rule_number = args.rule_number
        nat_name = args.nat

        nat = nats_utils.FindNatOrRaise(router, nat_name)
        rule = rules_utils.FindRuleOrRaise(nat, rule_number)

        rules_utils.UpdateRuleMessage(rule, args, holder)

        result = service.Patch(
            messages.ComputeRoutersPatchRequest(project=router_ref.project,
                                                region=router_ref.region,
                                                router=router_ref.Name(),
                                                routerResource=router))

        operation_ref = resources.REGISTRY.Parse(
            result.name,
            collection='compute.regionOperations',
            params={
                'project': router_ref.project,
                'region': router_ref.region,
            })

        if args.async_:
            log.UpdatedResource(
                operation_ref,
                kind='Rule [{0}] in NAT [{1}]'.format(rule_number, nat_name),
                is_async=True,
                details='Run the [gcloud compute operations describe] command '
                'to check the status of this operation.')
            return result

        target_router_ref = holder.resources.Parse(
            router_ref.Name(),
            collection='compute.routers',
            params={
                'project': router_ref.project,
                'region': router_ref.region,
            })

        operation_poller = poller.Poller(service, target_router_ref)
        return waiter.WaitFor(
            operation_poller, operation_ref,
            'Updating Rule [{0}] in NAT [{1}]'.format(rule_number, nat_name))
コード例 #30
0
  def Run(self, args):
    client = devices.DevicesClient()

    device_ref = util.ParseDevice(args.id, registry=args.registry,
                                  region=args.region)
    blocked = util.ParseDeviceBlocked(args.blocked, args.enable_device)
    metadata = util.ParseMetadata(args.metadata, args.metadata_from_file,
                                  client.messages)

    device = client.Patch(device_ref, blocked=blocked, metadata=metadata)
    log.UpdatedResource(device_ref.Name(), 'device')
    return device