Beispiel #1
0
  def Run(self, args):
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client.apitools_client
    messages = holder.client.messages

    disk_ref = self.DISK_ARG.ResolveAsResource(
        args, holder.resources,
        scope_lister=flags.GetDefaultScopeLister(holder.client))
    update_labels, remove_labels = labels_util.GetAndValidateOpsFromArgs(args)

    service = self.GetDisksService(disk_ref, client)
    disk = service.Get(self.GetDiskGetRequest(disk_ref, messages))

    set_labels_request = self.GetLabelsReplacementRequest(
        disk_ref, disk, messages, update_labels, remove_labels)

    if not set_labels_request:
      return disk

    operation = service.SetLabels(set_labels_request)
    operation_ref = holder.resources.Parse(
        operation.selfLink, collection=self.GetOperationCollection(disk_ref))

    operation_poller = poller.Poller(service)
    return waiter.WaitFor(
        operation_poller, operation_ref,
        'Updating labels of disk [{0}]'.format(
            disk_ref.Name()))
Beispiel #2
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client.apitools_client
        messages = holder.client.messages

        snapshot_ref = Update.SnapshotArg.ResolveAsResource(
            args, holder.resources)

        update_labels, remove_labels = labels_util.GetAndValidateOpsFromArgs(
            args)

        snapshot = client.snapshots.Get(
            messages.ComputeSnapshotsGetRequest(**snapshot_ref.AsDict()))

        replacement = labels_util.Diff(update_labels, remove_labels).Apply(
            messages.GlobalSetLabelsRequest.LabelsValue, snapshot.labels)

        if not replacement:
            return snapshot

        request = messages.ComputeSnapshotsSetLabelsRequest(
            project=snapshot_ref.project,
            resource=snapshot_ref.snapshot,
            globalSetLabelsRequest=messages.GlobalSetLabelsRequest(
                labelFingerprint=snapshot.labelFingerprint,
                labels=replacement))

        operation = client.snapshots.SetLabels(request)
        operation_ref = holder.resources.Parse(
            operation.selfLink, collection='compute.globalOperations')

        operation_poller = poller.Poller(client.snapshots)
        return waiter.WaitFor(
            operation_poller, operation_ref,
            'Updating labels of snapshot [{0}]'.format(snapshot_ref.Name()))
Beispiel #3
0
    def _ConstructLabelsFromArgs(cls, sql_messages, args, instance=None):
        """Constructs the labels message for the instance.

    Args:
      sql_messages: module, The messages module that should be used.
      args: Flags specified on the gcloud command; looking for
          args.labels, args.update_labels, args.remove_labels, ags.clear_labels.
      instance: sql_messages.DatabaseInstance, The original instance, if
          the original labels are needed.

    Returns:
      sql_messages.Settings.UserLabelsValue, the labels message for the patch.
    """
        # Parse labels args
        update_labels, remove_labels = {}, []
        if hasattr(args, 'labels'):
            update_labels = args.labels
        elif (hasattr(args, 'update_labels')
              and args.update_labels) or (hasattr(args, 'remove_labels')
                                          and args.remove_labels):
            update_labels, remove_labels = labels_util.GetAndValidateOpsFromArgs(
                args)
        elif hasattr(args, 'clear_labels') and args.clear_labels:
            remove_labels = [
                label.key
                for label in instance.settings.userLabels.additionalProperties
            ]

        # Removing labels with a patch request requires explicitly setting values
        # to null. If the user did not specify labels in this patch request, we
        # keep their existing labels.
        if remove_labels:
            if not update_labels:
                update_labels = {}
            for key in remove_labels:
                update_labels[key] = None

        # Generate the actual UserLabelsValue message.
        existing_labels = None
        if instance:
            existing_labels = instance.settings.userLabels
        return labels_util.UpdateLabels(existing_labels,
                                        sql_messages.Settings.UserLabelsValue,
                                        update_labels)
Beispiel #4
0
  def Run(self, args):
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client.apitools_client
    messages = holder.client.messages

    disk_ref = self.DISK_ARG.ResolveAsResource(
        args, holder.resources,
        scope_lister=flags.GetDefaultScopeLister(holder.client))

    update_labels, remove_labels = labels_util.GetAndValidateOpsFromArgs(args)

    service = client.disks
    request_type = messages.ComputeDisksGetRequest

    disk = service.Get(request_type(**disk_ref.AsDict()))

    replacement = labels_util.UpdateLabels(
        disk.labels,
        messages.ZoneSetLabelsRequest.LabelsValue,
        update_labels=update_labels,
        remove_labels=remove_labels)
    request = messages.ComputeDisksSetLabelsRequest(
        project=disk_ref.project,
        resource=disk_ref.disk,
        zone=disk_ref.zone,
        zoneSetLabelsRequest=messages.ZoneSetLabelsRequest(
            labelFingerprint=disk.labelFingerprint,
            labels=replacement))

    if not replacement:
      return disk

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

    operation_poller = poller.Poller(service)
    return waiter.WaitFor(
        operation_poller, operation_ref,
        'Updating labels of disk [{0}]'.format(
            disk_ref.Name()))
Beispiel #5
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client.apitools_client
        messages = holder.client.messages

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

        update_labels, remove_labels = labels_util.GetAndValidateOpsFromArgs(
            args)

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

        replacement = labels_util.UpdateLabels(
            instance.labels,
            messages.InstancesSetLabelsRequest.LabelsValue,
            update_labels=update_labels,
            remove_labels=remove_labels)

        if not replacement:
            return instance

        request = messages.ComputeInstancesSetLabelsRequest(
            project=instance_ref.project,
            instance=instance_ref.instance,
            zone=instance_ref.zone,
            instancesSetLabelsRequest=messages.InstancesSetLabelsRequest(
                labelFingerprint=instance.labelFingerprint,
                labels=replacement))

        operation = client.instances.SetLabels(request)
        operation_ref = holder.resources.Parse(
            operation.selfLink, collection='compute.zoneOperations')

        operation_poller = poller.Poller(client.instances)
        return waiter.WaitFor(
            operation_poller, operation_ref,
            'Updating labels of instance [{0}]'.format(instance_ref.Name()))
Beispiel #6
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client.apitools_client
        messages = holder.client.messages

        image_ref = self.DISK_IMAGE_ARG.ResolveAsResource(
            args,
            holder.resources,
            scope_lister=flags.GetDefaultScopeLister(holder.client))

        labels_diff = labels_util.GetAndValidateOpsFromArgs(args)

        image = client.images.Get(
            messages.ComputeImagesGetRequest(**image_ref.AsDict()))

        labels_update = labels_diff.Apply(
            messages.GlobalSetLabelsRequest.LabelsValue, image.labels)

        if not labels_update.needs_update:
            return image

        request = messages.ComputeImagesSetLabelsRequest(
            project=image_ref.project,
            resource=image_ref.image,
            globalSetLabelsRequest=messages.GlobalSetLabelsRequest(
                labelFingerprint=image.labelFingerprint,
                labels=labels_update.labels))

        operation = client.images.SetLabels(request)
        operation_ref = holder.resources.Parse(
            operation.selfLink, collection='compute.globalOperations')

        operation_poller = poller.Poller(client.images)
        return waiter.WaitFor(
            operation_poller, operation_ref,
            'Updating labels of image [{0}]'.format(image_ref.Name()))
Beispiel #7
0
    def _ConstructPatchSettingsFromArgs(cls,
                                        sql_messages,
                                        args,
                                        instance=None,
                                        release_track=DEFAULT_RELEASE_TRACK):
        """Constructs create settings object from base settings and args."""
        original_settings = instance.settings if instance else None
        settings = cls._ConstructBaseSettingsFromArgs(sql_messages, args,
                                                      instance, release_track)

        if args.clear_gae_apps:
            settings.authorizedGaeApplications = []

        if any([args.follow_gae_app, args.gce_zone]):
            settings.locationPreference = sql_messages.LocationPreference(
                followGaeApplication=args.follow_gae_app, zone=args.gce_zone)

        if args.clear_authorized_networks:
            if not settings.ipConfiguration:
                settings.ipConfiguration = sql_messages.IpConfiguration()
            settings.ipConfiguration.authorizedNetworks = []

        if args.enable_database_replication is not None:
            settings.databaseReplicationEnabled = args.enable_database_replication

        backup_configuration = (reducers.BackupConfiguration(
            sql_messages,
            instance,
            no_backup=args.no_backup,
            backup_start_time=args.backup_start_time,
            enable_bin_log=args.enable_bin_log))
        if backup_configuration:
            cls.AddBackupConfigToSettings(settings, backup_configuration)

        settings.databaseFlags = (reducers.DatabaseFlags(
            sql_messages,
            original_settings,
            database_flags=args.database_flags,
            clear_database_flags=args.clear_database_flags))

        settings.maintenanceWindow = (reducers.MaintenanceWindow(
            sql_messages,
            instance,
            maintenance_release_channel=args.maintenance_release_channel,
            maintenance_window_day=args.maintenance_window_day,
            maintenance_window_hour=args.maintenance_window_hour))

        # BETA args.
        if release_track == base.ReleaseTrack.BETA:
            update_labels, remove_labels = {}, []
            if args.update_labels or args.remove_labels:
                update_labels, remove_labels = labels_util.GetAndValidateOpsFromArgs(
                    args)
            labels = reducers.UserLabels(sql_messages,
                                         instance,
                                         update_labels=update_labels,
                                         remove_labels=remove_labels,
                                         clear_labels=args.clear_labels)
            if labels:
                settings.userLabels = labels

        return settings
Beispiel #8
0
    def _ConstructSettingsFromArgs(cls, sql_messages, args, instance=None):
        """Constructs instance settings from the command line arguments.

    Args:
      sql_messages: module, The messages module that should be used.
      args: argparse.Namespace, The arguments that this command was invoked
          with.
      instance: sql_messages.DatabaseInstance, The original instance, for
          settings that depend on the previous state.

    Returns:
      A settings object representing the instance settings.

    Raises:
      ToolException: An error other than http error occured while executing the
          command.
    """
        settings = sql_messages.Settings(
            tier=reducers.MachineType(instance, args.tier, args.memory,
                                      args.cpu),
            pricingPlan=args.pricing_plan,
            replicationType=args.replication,
            activationPolicy=args.activation_policy)

        labels = None
        if hasattr(args, 'labels'):
            labels = reducers.UserLabels(sql_messages,
                                         instance,
                                         labels=args.labels)
        elif (hasattr(args, 'update_labels') and args.update_labels
              or hasattr(args, 'remove_labels') and args.remove_labels):
            update_labels, remove_labels = labels_util.GetAndValidateOpsFromArgs(
                args)
            labels = reducers.UserLabels(sql_messages,
                                         instance,
                                         update_labels=update_labels,
                                         remove_labels=remove_labels)
        elif hasattr(args, 'clear_labels'):
            labels = reducers.UserLabels(sql_messages,
                                         instance,
                                         clear_labels=args.clear_labels)
        if labels:
            settings.userLabels = labels

        # these args are only present for the patch command
        clear_authorized_networks = getattr(args, 'clear_authorized_networks',
                                            False)
        clear_gae_apps = getattr(args, 'clear_gae_apps', False)

        if args.authorized_gae_apps:
            settings.authorizedGaeApplications = args.authorized_gae_apps
        elif clear_gae_apps:
            settings.authorizedGaeApplications = []

        if any([
                args.assign_ip is not None, args.require_ssl is not None,
                args.authorized_networks, clear_authorized_networks
        ]):
            settings.ipConfiguration = sql_messages.IpConfiguration()
            if args.assign_ip is not None:
                if hasattr(settings.ipConfiguration, 'enabled'):
                    # v1beta3 is being used; use 'enabled' instead of 'ipv4Enabled'.
                    settings.ipConfiguration.enabled = args.assign_ip
                else:
                    settings.ipConfiguration.ipv4Enabled = args.assign_ip

            if args.authorized_networks:
                # AclEntry is only available in the v1beta4 version of the API. If it is
                # present, the API expects an AclEntry for the authorizedNetworks list;
                # otherwise, it expects a string.
                if getattr(sql_messages, 'AclEntry', None) is not None:
                    authorized_networks = [
                        sql_messages.AclEntry(value=n)
                        for n in args.authorized_networks
                    ]
                else:
                    authorized_networks = args.authorized_networks
                settings.ipConfiguration.authorizedNetworks = authorized_networks
            if clear_authorized_networks:
                # For patch requests, this field needs to be labeled explicitly cleared.
                settings.ipConfiguration.authorizedNetworks = []

            if args.require_ssl is not None:
                settings.ipConfiguration.requireSsl = args.require_ssl

        if any([args.follow_gae_app, args.gce_zone]):
            settings.locationPreference = sql_messages.LocationPreference(
                followGaeApplication=args.follow_gae_app, zone=args.gce_zone)

        if getattr(args, 'enable_database_replication', None) is not None:
            settings.databaseReplicationEnabled = args.enable_database_replication

        return settings