Beispiel #1
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client
        igm_ref = (instance_groups_flags.MULTISCOPE_INSTANCE_GROUP_MANAGER_ARG.
                   ResolveAsResource)(
                       args,
                       holder.resources,
                       default_scope=compute_scope.ScopeEnum.ZONE,
                       scope_lister=flags.GetDefaultScopeLister(client))

        if igm_ref.Collection() not in [
                'compute.instanceGroupManagers',
                'compute.regionInstanceGroupManagers'
        ]:
            raise ValueError('Unknown reference type {0}'.format(
                igm_ref.Collection()))

        igm_resource = managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
            igm_ref, client)

        auto_healing_policies = self._GetValidatedAutohealingPolicies(
            holder, client, args, igm_resource)

        if auto_healing_policies is not None:
            return self._MakePatchRequest(
                client, igm_ref,
                client.messages.InstanceGroupManager(
                    autoHealingPolicies=auto_healing_policies))
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        managed_instance_groups_utils.ValidateAutoscalerArgs(args)

        igm_ref = self.CreateGroupReference(client, holder.resources, args)
        service = self.GetAutoscalerServiceForGroup(client, igm_ref)

        # Assert that Instance Group Manager exists.
        managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
            igm_ref, client)

        autoscaler_resource, is_new = self.CreateAutoscalerResource(
            client, holder.resources, igm_ref, args)

        if is_new:
            method = 'Insert'
            request = service.GetRequestType(method)(project=igm_ref.project)
            managed_instance_groups_utils.AdjustAutoscalerNameForCreation(
                autoscaler_resource)
            request.autoscaler = autoscaler_resource
        else:
            method = 'Update'
            request = service.GetRequestType(method)(project=igm_ref.project)
            request.autoscaler = autoscaler_resource.name
            request.autoscalerResource = autoscaler_resource

        self.ScopeRequest(request, igm_ref)
        return client.MakeRequests([(service, method, request)])
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client
        managed_instance_groups_utils.ValidateAutoscalerArgs(args)
        managed_instance_groups_utils.ValidateStackdriverMetricsFlags(args)
        managed_instance_groups_utils.ValidateConflictsWithAutoscalingFile(
            args, (managed_instance_groups_utils.
                   ARGS_CONFLICTING_WITH_AUTOSCALING_FILE_ALPHA))
        igm_ref = self.CreateGroupReference(client, holder.resources, args)

        # Assert that Instance Group Manager exists.
        managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
            igm_ref, client)

        autoscaler_resource, is_new = self.CreateAutoscalerResource(
            client, holder.resources, igm_ref, args)

        managed_instance_groups_utils.ValidateGeneratedAutoscalerIsValid(
            args, autoscaler_resource)

        if args.IsSpecified('autoscaling_file'):
            if is_new:
                existing_autoscaler_name = None
            else:
                existing_autoscaler_name = autoscaler_resource.name
            return self._SetAutoscalerFromFile(args.autoscaling_file, client,
                                               igm_ref,
                                               existing_autoscaler_name)

        if is_new:
            managed_instance_groups_utils.AdjustAutoscalerNameForCreation(
                autoscaler_resource, igm_ref)
            return self._InsertAutoscaler(client, igm_ref, autoscaler_resource)
        return self._UpdateAutoscaler(client, igm_ref, autoscaler_resource)
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client
        igm_ref = (instance_groups_flags.MULTISCOPE_INSTANCE_GROUP_MANAGER_ARG.
                   ResolveAsResource)(
                       args,
                       holder.resources,
                       default_scope=compute_scope.ScopeEnum.ZONE,
                       scope_lister=flags.GetDefaultScopeLister(client))

        igm_resource = managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
            igm_ref, client)

        device_names = instance_groups_flags.GetValidatedUpdateStatefulPolicyParams(
            args, igm_resource.statefulPolicy)

        if not device_names and args.IsSpecified('stateful_names'):
            # TODO(b/70314588): Use Patch instead of manual Update.
            if not args.GetValue('stateful_names'):
                igm_resource.reset('statefulPolicy')
            else:
                igm_resource.statefulPolicy = self._UpdateStatefulPolicy(
                    client, [])
            return self._MakeUpdateRequest(client, igm_ref, igm_resource)

        stateful_policy = self._UpdateStatefulPolicy(client, device_names)
        igm_updated_resource = client.messages.InstanceGroupManager(
            statefulPolicy=stateful_policy)

        return self._MakePatchRequest(client, igm_ref, igm_updated_resource)
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client
        igm_ref = instance_groups_flags.CreateGroupReference(
            client, holder.resources, args)

        # Assert that Instance Group Manager exists.
        mig_utils.GetInstanceGroupManagerOrThrow(igm_ref, client)

        old_autoscaler = mig_utils.AutoscalerForMigByRef(
            client, holder.resources, igm_ref)
        if mig_utils.IsAutoscalerNew(old_autoscaler):
            raise NoMatchingAutoscalerFoundError(
                'Instance group manager [{}] has no existing autoscaler; '
                'cannot update.'.format(igm_ref.Name()))

        autoscalers_client = autoscalers_api.GetClient(client, igm_ref)
        new_autoscaler = autoscalers_client.message_type(
            name=old_autoscaler.name,  # PATCH needs this
            autoscalingPolicy=client.messages.AutoscalingPolicy())
        if args.IsSpecified('mode'):
            mode = mig_utils.ParseModeString(args.mode, client.messages)
            new_autoscaler.autoscalingPolicy.mode = mode
        if self.scale_down:
            new_autoscaler.autoscalingPolicy.scaleDownControl = \
              mig_utils.BuildScaleDown(args, client.messages)

        return autoscalers_client.Patch(igm_ref, new_autoscaler)
Beispiel #6
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        managed_instance_groups_utils.ValidateAutoscalerArgs(args)

        igm_ref = instance_groups_flags.CreateGroupReference(
            client, holder.resources, args)

        # Assert that Instance Group Manager exists.
        managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
            igm_ref, client)

        # Require confirmation if autoscaling a GKE node group.
        self._PromptToAutoscaleGKENodeGroup(args)

        autoscaler_resource, is_new = self.CreateAutoscalerResource(
            client, holder.resources, igm_ref, args)

        autoscalers_client = autoscalers_api.GetClient(client, igm_ref)
        if is_new:
            managed_instance_groups_utils.AdjustAutoscalerNameForCreation(
                autoscaler_resource, igm_ref)
            return autoscalers_client.Insert(igm_ref, autoscaler_resource)
        return autoscalers_client.Update(igm_ref, autoscaler_resource)
    def CreateRequests(self, args):
        managed_instance_groups_utils.ValidateAutoscalerArgs(args)

        igm_ref = self.CreateGroupReference(args)
        service = self.GetAutoscalerServiceForGroup(igm_ref)

        # Assert that Instance Group Manager exists.
        managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
            igm_ref, self.project, self.compute, self.http, self.batch_url)

        autoscaler_resource, is_new = self.CreateAutoscalerResource(
            igm_ref, args)

        if is_new:
            method = 'Insert'
            request = service.GetRequestType(method)(project=self.project)
            managed_instance_groups_utils.AdjustAutoscalerNameForCreation(
                autoscaler_resource)
            request.autoscaler = autoscaler_resource
        else:
            method = 'Update'
            request = service.GetRequestType(method)(project=self.project)
            request.autoscaler = autoscaler_resource.name
            request.autoscalerResource = autoscaler_resource

        self.ScopeRequest(request, igm_ref)
        return ((service, method, request), )
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client
        igm_ref = instance_groups_flags.CreateGroupReference(
            client, holder.resources, args)

        # Assert that Instance Group Manager exists.
        mig_utils.GetInstanceGroupManagerOrThrow(igm_ref, client)

        old_autoscaler = mig_utils.AutoscalerForMigByRef(
            client, holder.resources, igm_ref)
        if mig_utils.IsAutoscalerNew(old_autoscaler):
            raise NoMatchingAutoscalerFoundError(
                'Instance group manager [{}] has no existing autoscaler; '
                'cannot update.'.format(igm_ref.Name()))

        autoscalers_client = autoscalers_api.GetClient(client, igm_ref)
        new_autoscaler = autoscalers_client.message_type(
            name=old_autoscaler.name,  # PATCH needs this
            autoscalingPolicy=client.messages.AutoscalingPolicy())
        if args.IsSpecified('mode'):
            mode = mig_utils.ParseModeString(args.mode, client.messages)
            new_autoscaler.autoscalingPolicy.mode = mode

        if args.IsSpecified('clear_scale_in_control'):
            new_autoscaler.autoscalingPolicy.scaleInControl = None
        else:
            new_autoscaler.autoscalingPolicy.scaleInControl = \
              mig_utils.BuildScaleIn(args, client.messages)

        if self.clear_scale_down and args.IsSpecified(
                'clear_scale_down_control'):
            new_autoscaler.autoscalingPolicy.scaleDownControl = None

        if args.IsSpecified('cpu_utilization_predictive_method'):
            cpu_predictive_enum = client.messages.AutoscalingPolicyCpuUtilization.PredictiveMethodValueValuesEnum
            new_autoscaler.autoscalingPolicy.cpuUtilization = client.messages.AutoscalingPolicyCpuUtilization(
            )
            new_autoscaler.autoscalingPolicy.cpuUtilization.predictiveMethod = arg_utils.ChoiceToEnum(
                args.cpu_utilization_predictive_method, cpu_predictive_enum)

        scheduled = mig_utils.BuildSchedules(args, client.messages)
        if scheduled:
            new_autoscaler.autoscalingPolicy.scalingSchedules = scheduled

        if args.IsSpecified('min_num_replicas'):
            new_autoscaler.autoscalingPolicy.minNumReplicas = args.min_num_replicas
        if args.IsSpecified('max_num_replicas'):
            new_autoscaler.autoscalingPolicy.maxNumReplicas = args.max_num_replicas

        return self._SendPatchRequest(args, client, autoscalers_client,
                                      igm_ref, new_autoscaler)
Beispiel #9
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client
        igm_ref = (instance_groups_flags.MULTISCOPE_INSTANCE_GROUP_MANAGER_ARG.
                   ResolveAsResource)(
                       args,
                       holder.resources,
                       default_scope=compute_scope.ScopeEnum.ZONE,
                       scope_lister=flags.GetDefaultScopeLister(client))

        if igm_ref.Collection() not in [
                'compute.instanceGroupManagers',
                'compute.regionInstanceGroupManagers'
        ]:
            raise ValueError('Unknown reference type {0}'.format(
                igm_ref.Collection()))

        instance_groups_flags.ValidateMigInstanceRedistributionTypeFlag(
            args.GetValue('instance_redistribution_type'), igm_ref)

        igm_resource = managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
            igm_ref, client)

        device_names = instance_groups_flags.GetValidatedUpdateStatefulPolicyParams(
            args, igm_resource.statefulPolicy)

        update_policy = (managed_instance_groups_utils.
                         ApplyInstanceRedistributionTypeToUpdatePolicy)(
                             client,
                             args.GetValue('instance_redistribution_type'),
                             igm_resource.updatePolicy)

        if not device_names:
            # TODO(b/70314588): Use Patch instead of manual Update.
            if args.IsSpecified(
                    'stateful_names') and not args.GetValue('stateful_names'):
                igm_resource.reset('statefulPolicy')
            elif igm_resource.statefulPolicy or args.GetValue(
                    'stateful_names'):
                igm_resource.statefulPolicy = self._UpdateStatefulPolicy(
                    client, [])
            igm_resource.updatePolicy = update_policy
            return self._MakeUpdateRequest(client, igm_ref, igm_resource)

        stateful_policy = self._UpdateStatefulPolicy(client, device_names)
        igm_updated_resource = client.messages.InstanceGroupManager(
            statefulPolicy=stateful_policy, updatePolicy=update_policy)

        return self._MakePatchRequest(client, igm_ref, igm_updated_resource)
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        igm_ref = self.CreateGroupReference(client, holder.resources, args)
        service = self.GetAutoscalerServiceForGroup(client, igm_ref)

        # Assert that Instance Group Manager exists.
        managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
            igm_ref, client)

        autoscaler = self.GetAutoscalerResource(client, holder.resources,
                                                igm_ref, args)
        request = service.GetRequestType('Delete')(project=igm_ref.project,
                                                   autoscaler=autoscaler.name)
        self.ScopeRequest(request, igm_ref)
        return client.MakeRequests([(service, 'Delete', request)])
    def CreateRequests(self, args):
        igm_ref = self.CreateGroupReference(args)
        service = self.GetAutoscalerServiceForGroup(igm_ref)

        # Assert that Instance Group Manager exists.
        managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
            igm_ref, self.project, self.compute, self.http, self.batch_url)

        autoscaler = self.GetAutoscalerResource(igm_ref, args)
        request = service.GetRequestType(self.method)(
            project=self.project, autoscaler=autoscaler.name)
        self.ScopeRequest(request, igm_ref)
        return [(
            service,
            self.method,
            request,
        )]
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        managed_instance_groups_utils.ValidateAutoscalerArgs(args)

        igm_ref = self.CreateGroupReference(client, holder.resources, args)

        # Assert that Instance Group Manager exists.
        managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
            igm_ref, client)

        autoscaler_resource, is_new = self.CreateAutoscalerResource(
            client, holder.resources, igm_ref, args)

        if is_new:
            managed_instance_groups_utils.AdjustAutoscalerNameForCreation(
                autoscaler_resource, igm_ref)
            return self._InsertAutoscaler(client, igm_ref, autoscaler_resource)
        return self._UpdateAutoscaler(client, igm_ref, autoscaler_resource)
Beispiel #13
0
  def Run(self, args):
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client
    igm_ref = (instance_groups_flags.MULTISCOPE_INSTANCE_GROUP_MANAGER_ARG
               .ResolveAsResource)(
                   args,
                   holder.resources,
                   default_scope=compute_scope.ScopeEnum.ZONE,
                   scope_lister=flags.GetDefaultScopeLister(client))

    if igm_ref.Collection() not in [
        'compute.instanceGroupManagers', 'compute.regionInstanceGroupManagers'
    ]:
      raise ValueError('Unknown reference type {0}'.format(
          igm_ref.Collection()))

    igm_resource = managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
        igm_ref, client)

    patch_instance_group_manager = self._CreateInstanceGroupManagerPatch(
        args, igm_ref, igm_resource, client, holder)
    return self._MakePatchRequest(client, igm_ref, patch_instance_group_manager)
Beispiel #14
0
def CreateRequest(args,
                  cleared_fields,
                  client,
                  resources,
                  minimal_action,
                  max_surge=None):
    """Create request helper for compute instance-groups managed rolling-action.

  Args:
    args: argparse namespace
    cleared_fields: Fields which are left cleared, but should be send in request
    client: The compute client
    resources: The compute resources
    minimal_action: MinimalActionValueValuesEnum value
    max_surge: InstanceGroupManagerUpdatePolicy.maxSurge value

  Returns:
    ComputeInstanceGroupManagersPatchRequest or
    ComputeRegionInstanceGroupManagersPatchRequest instance
  """
    resource_arg = instance_groups_flags.MULTISCOPE_INSTANCE_GROUP_MANAGER_ARG
    default_scope = compute_scope.ScopeEnum.ZONE
    scope_lister = flags.GetDefaultScopeLister(client)
    igm_ref = resource_arg.ResolveAsResource(args,
                                             resources,
                                             default_scope=default_scope,
                                             scope_lister=scope_lister)

    update_policy_type = (client.messages.InstanceGroupManagerUpdatePolicy.
                          TypeValueValuesEnum.PROACTIVE)
    max_unavailable = update_instances_utils.ParseFixedOrPercent(
        '--max-unavailable', 'max-unavailable', args.max_unavailable,
        client.messages)

    igm_info = managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
        igm_ref, client)

    versions = (igm_info.versions or [
        client.messages.InstanceGroupManagerVersion(
            instanceTemplate=igm_info.instanceTemplate)
    ])
    current_time_str = str(times.Now(times.UTC))
    for i, version in enumerate(versions):
        version.name = '%d/%s' % (i, current_time_str)

    update_policy = client.messages.InstanceGroupManagerUpdatePolicy(
        maxSurge=max_surge,
        maxUnavailable=max_unavailable,
        minReadySec=args.min_ready,
        minimalAction=minimal_action,
        type=update_policy_type)
    igm_resource = client.messages.InstanceGroupManager(
        instanceTemplate=None, updatePolicy=update_policy, versions=versions)
    if igm_ref.Collection() == 'compute.instanceGroupManagers':
        service = client.apitools_client.instanceGroupManagers
        request = client.messages.ComputeInstanceGroupManagersPatchRequest(
            instanceGroupManager=igm_ref.Name(),
            instanceGroupManagerResource=igm_resource,
            project=igm_ref.project,
            zone=igm_ref.zone)
    elif igm_ref.Collection() == 'compute.regionInstanceGroupManagers':
        service = client.apitools_client.regionInstanceGroupManagers
        request = client.messages.ComputeRegionInstanceGroupManagersPatchRequest(
            instanceGroupManager=igm_ref.Name(),
            instanceGroupManagerResource=igm_resource,
            project=igm_ref.project,
            region=igm_ref.region)
    # Due to 'Patch' semantics, we have to clear either 'fixed' or 'percent'.
    # Otherwise, we'll get an error that both 'fixed' and 'percent' are set.
    if max_surge is not None:
        cleared_fields.append('updatePolicy.maxSurge.fixed' if max_surge.fixed
                              is None else 'updatePolicy.maxSurge.percent')
    if max_unavailable is not None:
        cleared_fields.append(
            'updatePolicy.maxUnavailable.fixed' if max_unavailable.
            fixed is None else 'updatePolicy.maxUnavailable.percent')
    return (service, 'Patch', request)
Beispiel #15
0
  def CreateRequest(self, args, cleared_fields, client, resources):
    resource_arg = instance_groups_flags.MULTISCOPE_INSTANCE_GROUP_MANAGER_ARG
    default_scope = compute_scope.ScopeEnum.ZONE
    scope_lister = flags.GetDefaultScopeLister(client)
    igm_ref = resource_arg.ResolveAsResource(
        args, resources, default_scope=default_scope, scope_lister=scope_lister)

    update_policy_type = update_instances_utils.ParseUpdatePolicyType(
        '--type', args.type, client.messages)
    max_surge = update_instances_utils.ParseFixedOrPercent(
        '--max-surge', 'max-surge', args.max_surge, client.messages)
    max_unavailable = update_instances_utils.ParseFixedOrPercent(
        '--max-unavailable', 'max-unavailable', args.max_unavailable,
        client.messages)

    igm_info = managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
        igm_ref, client)

    versions = []
    versions.append(
        update_instances_utils.ParseVersion(igm_ref.project, '--version',
                                            args.version, resources,
                                            client.messages))
    if args.canary_version:
      versions.append(
          update_instances_utils.ParseVersion(
              igm_ref.project, '--canary-version', args.canary_version,
              resources, client.messages))
    managed_instance_groups_utils.ValidateVersions(igm_info, versions,
                                                   args.force)

    # TODO(b/36049787): Decide what we should do when two versions have the same
    #              instance template (this can happen with canary restart
    #              performed using tags).
    igm_version_names = {
        version.instanceTemplate: version.name
        for version in igm_info.versions
    }
    for version in versions:
      if not version.name:
        version.name = igm_version_names.get(version.instanceTemplate)
    minimal_action = (client.messages.InstanceGroupManagerUpdatePolicy.
                      MinimalActionValueValuesEnum.REPLACE)

    update_policy = client.messages.InstanceGroupManagerUpdatePolicy(
        maxSurge=max_surge,
        maxUnavailable=max_unavailable,
        minReadySec=args.min_ready,
        minimalAction=minimal_action,
        type=update_policy_type)
    igm_resource = client.messages.InstanceGroupManager(
        instanceTemplate=None, updatePolicy=update_policy, versions=versions)
    if hasattr(igm_ref, 'zone'):
      service = client.apitools_client.instanceGroupManagers
      request = (client.messages.ComputeInstanceGroupManagersPatchRequest(
          instanceGroupManager=igm_ref.Name(),
          instanceGroupManagerResource=igm_resource,
          project=igm_ref.project,
          zone=igm_ref.zone))
    elif hasattr(igm_ref, 'region'):
      service = client.apitools_client.regionInstanceGroupManagers
      request = (client.messages.ComputeRegionInstanceGroupManagersPatchRequest(
          instanceGroupManager=igm_ref.Name(),
          instanceGroupManagerResource=igm_resource,
          project=igm_ref.project,
          region=igm_ref.region))
    # Due to 'Patch' semantics, we have to clear either 'fixed' or 'percent'.
    # Otherwise, we'll get an error that both 'fixed' and 'percent' are set.
    if max_surge is not None:
      cleared_fields.append('updatePolicy.maxSurge.fixed' if max_surge.fixed is
                            None else 'updatePolicy.maxSurge.percent')
    if max_unavailable is not None:
      cleared_fields.append('updatePolicy.maxUnavailable.fixed'
                            if max_unavailable.fixed is None else
                            'updatePolicy.maxUnavailable.percent')
    return (service, 'Patch', request)
Beispiel #16
0
  def CreateRequest(self, args, client, resources):
    resource_arg = instance_groups_flags.MULTISCOPE_INSTANCE_GROUP_MANAGER_ARG
    default_scope = compute_scope.ScopeEnum.ZONE
    scope_lister = flags.GetDefaultScopeLister(client)
    igm_ref = resource_arg.ResolveAsResource(
        args, resources, default_scope=default_scope, scope_lister=scope_lister)

    if igm_ref.Collection() not in [
        'compute.instanceGroupManagers', 'compute.regionInstanceGroupManagers'
    ]:
      raise ValueError('Unknown reference type {0}'.format(
          igm_ref.Collection()))

    update_policy_type = update_instances_utils.ParseUpdatePolicyType(
        '--type', args.type, client.messages)
    max_surge = update_instances_utils.ParseFixedOrPercent(
        '--max-surge', 'max-surge', args.max_surge, client.messages)
    max_unavailable = update_instances_utils.ParseFixedOrPercent(
        '--max-unavailable', 'max-unavailable', args.max_unavailable,
        client.messages)

    igm_info = managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
        igm_ref, client)

    versions = []
    versions.append(
        update_instances_utils.ParseVersion(igm_ref.project, '--version',
                                            args.version, resources,
                                            client.messages))
    if args.canary_version:
      versions.append(
          update_instances_utils.ParseVersion(igm_ref.project,
                                              '--canary-version',
                                              args.canary_version, resources,
                                              client.messages))
    managed_instance_groups_utils.ValidateVersions(igm_info, versions,
                                                   resources, args.force)

    # TODO(b/36049787): Decide what we should do when two versions have the same
    #              instance template (this can happen with canary restart
    #              performed using tags).
    igm_version_names = {
        version.instanceTemplate: version.name
        for version in igm_info.versions
    }
    for version in versions:
      if not version.name:
        version.name = igm_version_names.get(version.instanceTemplate)
    minimal_action = (client.messages.InstanceGroupManagerUpdatePolicy.
                      MinimalActionValueValuesEnum.REPLACE)

    update_policy = client.messages.InstanceGroupManagerUpdatePolicy(
        maxSurge=max_surge,
        maxUnavailable=max_unavailable,
        minimalAction=minimal_action,
        type=update_policy_type)
    # min_ready is available in alpha and beta APIs only
    if hasattr(args, 'min_ready'):
      update_policy.minReadySec = args.min_ready
    # replacement_method is available in alpha API only
    if hasattr(args, 'replacement_method'):
      replacement_method = update_instances_utils.ParseReplacementMethod(
          args.replacement_method, client.messages)
      update_policy.replacementMethod = replacement_method

    rolling_action.ValidateAndFixUpdaterAgainstStateful(update_policy, igm_ref,
                                                        igm_info, client, args)

    igm_resource = client.messages.InstanceGroupManager(
        instanceTemplate=None, updatePolicy=update_policy, versions=versions)
    if hasattr(igm_ref, 'zone'):
      service = client.apitools_client.instanceGroupManagers
      request = (client.messages.ComputeInstanceGroupManagersPatchRequest(
          instanceGroupManager=igm_ref.Name(),
          instanceGroupManagerResource=igm_resource,
          project=igm_ref.project,
          zone=igm_ref.zone))
    elif hasattr(igm_ref, 'region'):
      service = client.apitools_client.regionInstanceGroupManagers
      request = (client.messages.ComputeRegionInstanceGroupManagersPatchRequest(
          instanceGroupManager=igm_ref.Name(),
          instanceGroupManagerResource=igm_resource,
          project=igm_ref.project,
          region=igm_ref.region))
    return service, 'Patch', request
Beispiel #17
0
    def CreateRequest(self, args, cleared_fields):
        resource_arg = instance_groups_flags.MULTISCOPE_INSTANCE_GROUP_MANAGER_ARG
        default_scope = compute_scope.ScopeEnum.ZONE
        scope_lister = flags.GetDefaultScopeLister(self.compute_client,
                                                   self.project)
        igm_ref = resource_arg.ResolveAsResource(args,
                                                 self.resources,
                                                 default_scope=default_scope,
                                                 scope_lister=scope_lister)

        update_instances_utils.ValidateUpdateInstancesArgs(args)
        update_policy_type = update_instances_utils.ParseUpdatePolicyType(
            '--type', args.type, self.messages)
        max_surge = update_instances_utils.ParseFixedOrPercent(
            '--max-surge', 'max-surge', args.max_surge, self.messages)
        max_unavailable = update_instances_utils.ParseFixedOrPercent(
            '--max-unavailable', 'max-unavailable', args.max_unavailable,
            self.messages)

        igm_info = managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
            igm_ref, self.compute_client)
        if args.action == 'replace':
            versions = []
            if args.version_original:
                versions.append(
                    update_instances_utils.ParseVersion(
                        '--version-original', args.version_original,
                        self.resources, self.messages))
            versions.append(
                update_instances_utils.ParseVersion('--version-new',
                                                    args.version_new,
                                                    self.resources,
                                                    self.messages))
            managed_instance_groups_utils.ValidateVersions(
                igm_info, versions, args.force)

            # TODO(b/36056457): Decide what we should do when two versions have the
            # same instance template (this can happen with canary restart performed
            # using tags).
            igm_version_names = {
                version.instanceTemplate: version.name
                for version in igm_info.versions
            }
            for version in versions:
                version.name = igm_version_names.get(version.instanceTemplate)
                version.tag = version.name
            minimal_action = (self.messages.InstanceGroupManagerUpdatePolicy.
                              MinimalActionValueValuesEnum.REPLACE)
        elif args.action == 'restart' and igm_info.versions is not None:
            versions = (igm_info.versions or [
                self.messages.InstanceGroupManagerVersion(
                    instanceTemplate=igm_info.instanceTemplate)
            ])
            current_time_str = str(times.Now(times.UTC))
            for i, version in enumerate(versions):
                version.name = '%d/%s' % (i, current_time_str)
                version.tag = version.name
            minimal_action = (self.messages.InstanceGroupManagerUpdatePolicy.
                              MinimalActionValueValuesEnum.RESTART)
        else:
            raise exceptions.InvalidArgumentException('--action',
                                                      'unknown action type.')

        update_policy = self.messages.InstanceGroupManagerUpdatePolicy(
            maxSurge=max_surge,
            maxUnavailable=max_unavailable,
            minReadySec=args.min_ready,
            minimalAction=minimal_action,
            type=update_policy_type)
        igm_resource = self.messages.InstanceGroupManager(
            instanceTemplate=None,
            updatePolicy=update_policy,
            versions=versions)
        if hasattr(igm_ref, 'zone'):
            service = self.compute.instanceGroupManagers
            request = (self.messages.ComputeInstanceGroupManagersPatchRequest(
                instanceGroupManager=igm_ref.Name(),
                instanceGroupManagerResource=igm_resource,
                project=self.project,
                zone=igm_ref.zone))
        elif hasattr(igm_ref, 'region'):
            service = self.compute.regionInstanceGroupManagers
            request = (
                self.messages.ComputeRegionInstanceGroupManagersPatchRequest(
                    instanceGroupManager=igm_ref.Name(),
                    instanceGroupManagerResource=igm_resource,
                    project=self.project,
                    region=igm_ref.region))
        # Due to 'Patch' semantics, we have to clear either 'fixed' or 'percent'.
        # Otherwise, we'll get an error that both 'fixed' and 'percent' are set.
        if max_surge is not None:
            cleared_fields.append(
                'updatePolicy.maxSurge.fixed' if max_surge.fixed is None else
                'updatePolicy.maxSurge.percent')
        if max_unavailable is not None:
            cleared_fields.append(
                'updatePolicy.maxUnavailable.fixed' if max_unavailable.
                fixed is None else 'updatePolicy.maxUnavailable.percent')
        return (service, 'Patch', request)
Beispiel #18
0
    def CreateRequests(self, args):
        resource_arg = instance_groups_flags.ZONAL_INSTANCE_GROUP_MANAGER_ARG
        default_scope = flags.ScopeEnum.ZONE
        scope_lister = flags.GetDefaultScopeLister(self.compute_client,
                                                   self.project)
        igm_ref = resource_arg.ResolveAsResource(args,
                                                 self.resources,
                                                 default_scope=default_scope,
                                                 scope_lister=scope_lister)

        update_instances_utils.ValidateUpdateInstancesArgs(args)
        update_policy_type = update_instances_utils.ParseUpdatePolicyType(
            '--type', args.type, self.messages)
        max_surge = update_instances_utils.ParseFixedOrPercent(
            '--max-surge', 'max-surge', args.max_surge, self.messages)
        max_unavailable = update_instances_utils.ParseFixedOrPercent(
            '--max-unavailable', 'max-unavailable', args.max_unavailable,
            self.messages)

        igm_info = managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
            igm_ref, self.project, self.compute, self.http, self.batch_url)
        if args.action == 'replace':
            versions = []
            if args.version_original:
                versions.append(
                    update_instances_utils.ParseVersion(
                        '--version-original', args.version_original,
                        self.resources, self.messages))
            versions.append(
                update_instances_utils.ParseVersion('--version-new',
                                                    args.version_new,
                                                    self.resources,
                                                    self.messages))
            managed_instance_groups_utils.ValidateVersions(
                igm_info, versions, args.force)

            igm_tags = dict((version.instanceTemplate, version.tag)
                            for version in igm_info.versions)
            for version in versions:
                version.tag = igm_tags.get(version.instanceTemplate)
            minimal_action = (self.messages.InstanceGroupManagerUpdatePolicy.
                              MinimalActionValueValuesEnum.REPLACE)
        elif args.action == 'restart' and igm_info.versions is not None:
            versions = (igm_info.versions or [
                self.messages.InstanceGroupManagerVersion(
                    instanceTemplate=igm_info.instanceTemplate)
            ])
            for version in versions:
                version.tag = str(times.Now(times.UTC))
            minimal_action = (self.messages.InstanceGroupManagerUpdatePolicy.
                              MinimalActionValueValuesEnum.RESTART)
        else:
            raise exceptions.InvalidArgumentException('--action',
                                                      'unknown action type.')

        update_policy = self.messages.InstanceGroupManagerUpdatePolicy(
            maxSurge=max_surge,
            maxUnavailable=max_unavailable,
            minReadySec=args.min_ready,
            minimalAction=minimal_action,
            type=update_policy_type,
        )
        service = self.compute.instanceGroupManagers
        request = (self.messages.ComputeInstanceGroupManagersPatchRequest(
            instanceGroupManager=igm_ref.Name(),
            instanceGroupManagerResource=(self.messages.InstanceGroupManager(
                instanceTemplate=None,
                updatePolicy=update_policy,
                versions=versions)),
            project=self.project,
            zone=igm_ref.zone))

        return [(service, self.method, request)]
Beispiel #19
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client
        igm_ref = (instance_groups_flags.MULTISCOPE_INSTANCE_GROUP_MANAGER_ARG.
                   ResolveAsResource)(
                       args,
                       holder.resources,
                       default_scope=compute_scope.ScopeEnum.ZONE,
                       scope_lister=flags.GetDefaultScopeLister(client))

        if igm_ref.Collection() not in [
                'compute.instanceGroupManagers',
                'compute.regionInstanceGroupManagers'
        ]:
            raise ValueError('Unknown reference type {0}'.format(
                igm_ref.Collection()))

        instance_groups_flags.ValidateMigInstanceRedistributionTypeFlag(
            args.GetValue('instance_redistribution_type'), igm_ref)

        igm_resource = managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
            igm_ref, client)
        if self._StatefulnessIntroduced(args):
            managed_instance_groups_utils.ValidateIgmReadyForStatefulness(
                igm_resource, client)

        device_names = instance_groups_flags.ValidateUpdateStatefulPolicyParams(
            args, igm_resource.statefulPolicy)

        update_policy = (managed_instance_groups_utils.
                         ApplyInstanceRedistributionTypeToUpdatePolicy)(
                             client,
                             args.GetValue('instance_redistribution_type'),
                             igm_resource.updatePolicy)

        auto_healing_policies = self._GetValidatedAutohealingPolicies(
            holder, client, args, igm_resource)

        if not self._StatefulArgsSet(args):
            igm_updated_resource = client.messages.InstanceGroupManager(
                updatePolicy=update_policy)
            if auto_healing_policies is not None:
                igm_updated_resource.autoHealingPolicies = auto_healing_policies
            return self._MakePatchRequest(client, igm_ref,
                                          igm_updated_resource)

        if not device_names:
            # TODO(b/70314588): Use Patch instead of manual Update.
            if igm_resource.statefulPolicy:
                igm_resource.statefulPolicy = self._UpdateStatefulPolicy(
                    client, igm_resource.statefulPolicy,
                    args.update_stateful_disk, args.remove_stateful_disks)
            igm_resource.updatePolicy = update_policy
            if auto_healing_policies is not None:
                igm_resource.autoHealingPolicies = auto_healing_policies
            return self._MakeUpdateRequest(client, igm_ref, igm_resource)

        stateful_policy = self._UpdateStatefulPolicy(
            client, igm_resource.statefulPolicy, args.update_stateful_disk,
            args.remove_stateful_disks)
        igm_updated_resource = client.messages.InstanceGroupManager(
            statefulPolicy=stateful_policy, updatePolicy=update_policy)
        if auto_healing_policies is not None:
            igm_updated_resource.autoHealingPolicies = auto_healing_policies

        return self._MakePatchRequest(client, igm_ref, igm_updated_resource)
Beispiel #20
0
def CreateRequest(args,
                  client,
                  resources,
                  minimal_action,
                  max_surge=None):
  """Create request helper for compute instance-groups managed rolling-action.

  Args:
    args: argparse namespace
    client: The compute client
    resources: The compute resources
    minimal_action: MinimalActionValueValuesEnum value
    max_surge: InstanceGroupManagerUpdatePolicy.maxSurge value

  Returns:
    ComputeInstanceGroupManagersPatchRequest or
    ComputeRegionInstanceGroupManagersPatchRequest instance

  Raises:
    ValueError: if instance group manager collection path is unknown
  """
  resource_arg = instance_groups_flags.MULTISCOPE_INSTANCE_GROUP_MANAGER_ARG
  default_scope = compute_scope.ScopeEnum.ZONE
  scope_lister = flags.GetDefaultScopeLister(client)
  igm_ref = resource_arg.ResolveAsResource(
      args, resources, default_scope=default_scope, scope_lister=scope_lister)

  if igm_ref.Collection() not in [
      'compute.instanceGroupManagers', 'compute.regionInstanceGroupManagers'
  ]:
    raise ValueError('Unknown reference type {0}'.format(igm_ref.Collection()))

  update_policy_type = (client.messages.InstanceGroupManagerUpdatePolicy.
                        TypeValueValuesEnum.PROACTIVE)
  max_unavailable = update_instances_utils.ParseFixedOrPercent(
      '--max-unavailable', 'max-unavailable', args.max_unavailable,
      client.messages)

  igm_info = managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
      igm_ref, client)

  versions = (igm_info.versions or [
      client.messages.InstanceGroupManagerVersion(
          instanceTemplate=igm_info.instanceTemplate)
  ])
  current_time_str = str(times.Now(times.UTC))
  for i, version in enumerate(versions):
    version.name = '%d/%s' % (i, current_time_str)

  update_policy = client.messages.InstanceGroupManagerUpdatePolicy(
      maxSurge=max_surge,
      maxUnavailable=max_unavailable,
      minimalAction=minimal_action,
      type=update_policy_type)
  # min_ready is available in alpha and beta APIs only
  if hasattr(args, 'min_ready'):
    update_policy.minReadySec = args.min_ready
  # replacement_method is available in alpha API only
  if hasattr(args, 'replacement_method'):
    replacement_method = update_instances_utils.ParseReplacementMethod(
        args.replacement_method, client.messages)
    update_policy.replacementMethod = replacement_method

  igm_resource = client.messages.InstanceGroupManager(
      instanceTemplate=None, updatePolicy=update_policy, versions=versions)
  if igm_ref.Collection() == 'compute.instanceGroupManagers':
    service = client.apitools_client.instanceGroupManagers
    request = client.messages.ComputeInstanceGroupManagersPatchRequest(
        instanceGroupManager=igm_ref.Name(),
        instanceGroupManagerResource=igm_resource,
        project=igm_ref.project,
        zone=igm_ref.zone)
  else:
    service = client.apitools_client.regionInstanceGroupManagers
    request = client.messages.ComputeRegionInstanceGroupManagersPatchRequest(
        instanceGroupManager=igm_ref.Name(),
        instanceGroupManagerResource=igm_resource,
        project=igm_ref.project,
        region=igm_ref.region)
  return (service, 'Patch', request)