
    LL                    h   S r SSKJr  SSKJr  SSKJr  SSKrSSKrSSKrSSKrSSK	r	SSK
r
SSKJr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SS	KJr  SSKJr  SSKJr  SSKJ r   SSKJ!r!  SSK"J#r#  SSK$J%r%  SSK$J&r&  SSK'J(r(  SSK)r)SSK*J+r+  / SQr,/ SQr-/ SQr.\.r/Sr0Sr1 " S S \Rd                  5      r2 " S! S"\25      r3 " S# S$\Rd                  5      r4 " S% S&\25      r5 " S' S(\25      r6SxS) jr7SyS* jr8S+ r9SzS, jr:S- r;SyS. jr<S/ r=S0 r>S1 r?S2 r@S3 rAS4 rBS5 rCS6 rDS7 rES8 rFS9 rGS: rHS; rIS< rJS= rKS> rL SyS? jrMS@ rNSA rOSB rP SySC jrQSD rRSE rSSF rTSG rUSH rVSI rWSJ rXSK rYSL rZS{SM jr[S{SN jr\SO r]SP r^SQ r_SR r`SS raST rbSU rcSV rdS{SW jreSX\
R                  SY\R                  4SZ jrhS[ riS\ rjS] rkS^ rl S|S_ jrmS` rnSzSa jroSb rpSc rqSd rrSe rsSf rtSg ruSh rvSi rwSj rxSk rySl rzSm r{Sn r|So r}Sp r~Sq rSr rSs rSt rSX\
R                  SuS4Sv jrSw rg)}zGCommon functions and classes for dealing with managed instances groups.    )absolute_import)division)unicode_literalsN)	protojson)encoding)
list_pager)
exceptions)instance_utils)lister)path_simplifier)request_helper)utils)arg_parsers)base)parser_extensions)flags)auto_healing_utils)update_instances_utils)	arg_utils)log)
properties)
console_io)range)DELTA_PER_MINUTEDELTA_PER_SECONDGAUGE)zdelta-per-minutezdelta-per-secondgauge)	max_num_replicascool_down_periodcustom_metric_utilizationdescriptionmin_num_replicasscale_based_on_cpuscale_based_on_load_balancingtarget_cpu_utilization!target_load_balancing_utilization?      c                       \ rS rSrSrSrg)ErrorY   z5Base exception for managed instance group exceptions. N__name__
__module____qualname____firstlineno____doc____static_attributes__r,       Clib/googlecloudsdk/api_lib/compute/managed_instance_groups_utils.pyr*   r*   Y   s    =r4   r*   c                       \ rS rSrSrSrg)ResourceNotFoundException]   z?The user tries to get/use/update resource which does not exist.r,   Nr-   r,   r4   r5   r7   r7   ]   s    Gr4   r7   c                       \ rS rSrSrSrg)InvalidArgumentErrora   z$The user provides invalid arguments.r,   Nr-   r,   r4   r5   r:   r:   a   s    ,r4   r:   c                       \ rS rSrSrSrg)ResourceAlreadyExistsExceptione   z7The user tries to create resource which already exists.r,   Nr-   r,   r4   r5   r=   r=   e   s    ?r4   r=   c                       \ rS rSrSrSrg)!ResourceCannotBeResolvedExceptioni   zEThe user uses invalid / partial name to resolve URI for the resource.r,   Nr-   r,   r4   r5   r@   r@   i   s    Mr4   r@   c           	         U R                  S[        R                  " 5       SS9  U R                  SSS9  [        X(       + S9  U R                  SS	S
S9  U R                  SS	SS9  U R                  S[        R                  " SS5      SS9  U R                  S[        R                  " SS5      SS9  SR                  SR                  [        5      5      nU R                  S[        R                  " [        [        [        S.S9SUS9  U(       a  U R                  SSSS9  U R                  S S!S"S9  U R                  S#S!S$S9  U R                  S%S&S'S9  U R                  S(S)[        S*S+9  U R                  S,S-[        S.S/9  U R                  S0S1[        S2S+9  [        5       R                  U 5        [        U 5        [        X5        g)3z%Adds commandline arguments to parser.z--cool-down-perioda  The number of seconds that your application takes to initialize on a VM instance. This is referred to as the [initialization period](https://cloud.google.com/compute/docs/autoscaler#cool_down_period). Specifying an accurate initialization period improves autoscaler decisions. For example, when scaling out, the autoscaler ignores data from VMs that are still initializing because those VMs might not yet represent normal usage of your application. The default initialization period is 60 seconds. See $ gcloud topic datetimes for information on duration formats. Initialization periods might vary because of numerous factors. We recommend that you test how long your application may take to initialize. To do this, create a VM and time your application's startup process.typehelpz--descriptionzNotes about Autoscaler.)rE   )max_requiredz--scale-based-on-cpu
store_truez,Autoscaler will be based on CPU utilization.actionrE   z--scale-based-on-load-balancingz4Use autoscaling based on load balancing utilization.z--target-cpu-utilizationg        g      ?zIAutoscaler aims to maintain CPU utilization at target level (0.0 to 1.0).z#--target-load-balancing-utilizationNzTAutoscaler aims to maintain the load balancing utilization level (greater than 0.0).a[  Adds a target metric value for the Autoscaler to use.

*metric*::: Protocol-free URL of a Google Cloud Monitoring metric.

*utilization-target*::: Value of the metric Autoscaler aims to
  maintain (greater than 0.0).

*utilization-target-type*::: How target is expressed. Valid values: {0}.

Mutually exclusive with `--update-stackdriver-metric`.
, --custom-metric-utilization)metricutilization-targetutilization-target-typespecappend)rD   rI   rE   --autoscaling-filePATHzPath of the file from which autoscaling configuration will be loaded. This flag allows you to atomically setup complex autoscalers.metavarrE   --remove-stackdriver-metricMETRICzStackdriver metric to remove from autoscaling configuration. If the metric is the only input used for autoscaling the command will fail.--update-stackdriver-metricaj  Stackdriver metric to use as an input for autoscaling. When using this flag, the target value of the metric must also be specified by using the following flags: `--stackdriver-metric-single-instance-assignment` or `--stackdriver-metric-utilization-target` and `--stackdriver-metric-utilization-target-type`. Mutually exclusive with `--custom-metric-utilization`.z--stackdriver-metric-filterFILTERzkExpression for filtering samples used to autoscale, see https://cloud.google.com/monitoring/api/v3/filters.z'--stackdriver-metric-utilization-targetTARGETzValue of the metric Autoscaler aims to maintain. When specifying this flag you must also provide `--stackdriver-metric-utilization-target-type`. Mutually exclusive with `--stackdriver-metric-single-instance-assignment` and `--custom-metric-utilization`.rU   rD   rE   ,--stackdriver-metric-utilization-target-typeTARGET_TYPEzValue of the metric Autoscaler aims to maintain. When specifying this flag you must also provide `--stackdriver-metric-utilization-target`. Mutually exclusive with `--stackdriver-metric-single-instance-assignment` and `--custom-metric-utilization`.)rU   choicesrE   /--stackdriver-metric-single-instance-assignment
ASSIGNMENTa8  Value that indicates the amount of work that each instance is expected to handle. Autoscaler maintains enough VMs by dividing the available work by this value. Mutually exclusive with `-stackdriver-metric-utilization-target-type`, `-stackdriver-metric-utilization-target-type`, and `--custom-metric-utilization`.)add_argumentr   DurationAddMinMaxControlBoundedFloatformatjoin!_ALLOWED_UTILIZATION_TARGET_TYPESArgDictstrfloat'_ALLOWED_UTILIZATION_TARGET_TYPES_LOWERGetModeFlagAddToParserAddScaleInControlFlagAddScheduledAutoscaling)parserautoscaling_file_enabled
patch_argscustom_metric_utilization_helps       r5   AddAutoscalerArgsrt   m   sJ   !=	  $ 	o,EF6(DE9  
 	'A  
 	 ##C-'	   	+##C.2	  $ F499678 ! 	#$)), )   
	   	#	   	#C	   	#@	   	/+   	45+   	7+   -F#&-r4   c                     U R                  S[        R                  " S[        R                  5      SS9  U R                  S[        R                  " S[        R                  5      USS9  g)	z9Adds min and max num replicas controls to a given parser.z--min-num-replicasr   z.Minimum number of replicas Autoscaler can set.rC   --max-num-replicasz.Maximum number of replicas Autoscaler can set.)rD   requiredrE   Nra   r   
BoundedIntsysmaxsize)rp   rF   s     r5   rc   rc     sa    !!!S[[1;  
 	!!!S[[1;	  r4   c                  8    [         R                  " SSSSSS.SS9$ )	Nz--modezFPermits autoscaling to scale out and in (default for new autoscalers).z1Permits autoscaling to scale only out and not in.z
              (DEPRECATED) Permits autoscaling to scale only out and not in.

              Value `only-up` is deprecated. Use `--mode only-scale-out`
              instead.
          z;Turns off autoscaling, while keeping the new configuration.)onzonly-scale-outzonly-upoffa            Set the mode of an autoscaler for a managed instance group.

          You can turn off or restrict a group's autoscaler activities without
          affecting your autoscaler configuration. The autoscaler configuration
          persists while the activities are turned off or restricted, and the
          activities resume when the autoscaler is turned on again or when the
          restrictions are lifted.
      )help_str)r   ChoiceArgumentr,   r4   r5   rl   rl     s:     
		" P O
!
 r4   c           	          U nU(       a   U R                  SS9nUR                  SSSS9  UR                  S[        R                  " [        [        [
        S.S	9S
S9  g)z0Adds scale-in-control flags to the given parser.Tmutexz--clear-scale-in-controlrG   z          If specified, the scale-in-control field will be cleared. Using this
          flag will remove any configuration set by `--scale-in-control` flag.
        rH   z--scale-in-control)max-scaled-in-replicasmax-scaled-in-replicas-percenttime-windowrO   a          Configuration that allows slower scale in so that even if Autoscaler
        recommends an abrupt scale in of a managed instance group, it will be
        throttled as specified by the parameters.

        *max-scaled-in-replicas*::: Maximum allowed number of VMs that can be
        deducted from the peak recommendation during the window. Possibly all
        these VMs can be deleted at once so the application needs to be prepared
        to lose that many VMs in one step. Mutually exclusive with
        'max-scaled-in-replicas-percent'.

        *max-scaled-in-replicas-percent*::: Maximum allowed percent of VMs
        that can be deducted from the peak recommendation during the window.
        Possibly all these VMs can be deleted at once so the application needs
        to be prepared to lose that many VMs in one step. Mutually exclusive
        with  'max-scaled-in-replicas'.

        *time-window*::: How long back autoscaling should look when computing
        recommendations. The autoscaler will not resize below the maximum
        allowed deduction subtracted from the peak size observed in this
        period. Measured in seconds.
        rC   N)	add_groupra   r   rh   ri   int)rp   include_clear	arg_groups      r5   rn   rn   <  st    )  t ,I"   (+03   r4   c                 *    U nUR                  SSSS9  g)z9Adds --clear-scale-down-control flag to the given parser.z--clear-scale-down-controlrG   a          If specified, the scale-down-control field will be cleared. Using this
        flag will remove any configuration set by the now-deprecated
        `--scale-down-control` flag. This is only useful if the MIG
        configuration had scale-down-control set in the past.
      rH   Nra   )rp   r   s     r5   AddClearScaleDownControlFlagr   l  s%    )"
  	r4   c                 H    SSS.nU(       a  SUS'   U R                  SUSS9  g	)
z3Add Predictive autoscaling arguments to the parser.zO(Default) No predictions are made when calculating the number of VM
instances.
zPredictive autoscaling predicts the future values of the
scaling metric and scales the group in advance to ensure that new
VM instances are ready in time to cover the predicted peak.
)nonezoptimize-availabilityz
    Standard predictive autoscaling  predicts the future values of
    the scaling metric and then scales the group to ensure that new VM
    instances are ready in time to cover the predicted peak.standardz#--cpu-utilization-predictive-methodzW
      Indicates whether to use a predictive algorithm when scaling based on
      CPU.)r^   rE   Nr   )rp   r   r^   s      r5   AddPredictiveAutoscalingr   {  sE     
' @GJ 	+  r4   c                 j   U(       a  U R                  SS9nU R                  5       nUR                  SSSS9  UR                  SSSS9  UR                  S	SS
S9  UR                  SSSS9  UR                  SSSS9  [        U5        gU nU R                  SSSS9  [        U R                  5       5        g)z1Add parameters controlling scheduled autoscaling.Tr   z--set-scheduleSCHEDULE_NAMEz8A unique name for the scaling schedule to be configured.rT   z--update-schedulez+Name of the scaling schedule to be updated.z--remove-schedulea            Name of the scaling schedule to be removed.

          Be careful with this action as scaling schedule deletion cannot be
          undone.

          You can delete any schedule regardless of its status. If you delete
          a scaling schedule that is currently active, the deleted scaling
          schedule stops being effective immediately after it is deleted.
          If there is no need to maintain capacity, the autoscaler starts
          removing instances after the usual stabilization period and after
          scale-in controls (if configured). For more information, see
          [Delays in scaling in](https://cloud.google.com/compute/docs/autoscaler/understanding-autoscaler-decisions#delays_in_scaling_in) and [Scale-in controls](https://cloud.google.com/compute/docs/autoscaler/understanding-autoscaler-decisions#scale-in_controls).
          This ensures you don't accidentally lose capacity immediately after
          the scaling schedule ends.
          z--enable-schedulezi        Name of the scaling schedule to be enabled.

        See --disable-schedule for details.
        z--disable-schedulea            Name of the scaling schedule to be disabled.

          When a scaling schedule is disabled its configuration persists but
          the scaling schedule itself never becomes active. If you disable a
          scaling schedule that is currently active the disabled scaling
          schedule stops being effective immediately after it moves into
          DISABLED state.
          If there is no need to maintain capacity, the autoscaler starts
          removing instances after the usual stabilization period and after
          scale-in controls (if configured). For more information, see
          [Delays in scaling in](https://cloud.google.com/compute/docs/autoscaler/understanding-autoscaler-decisions#delays_in_scaling_in) and [Scale-in controls](https://cloud.google.com/compute/docs/autoscaler/understanding-autoscaler-decisions#scale-in_controls).
          This ensures you don't accidentally lose capacity immediately after
          the scaling schedule ends.
          z%Unique name for the scaling schedule.N)r   ra   -AddScheduledAutoscalingConfigurationArguments)rp   rr   r   arg_group_configs       r5   ro   ro     s      t ,I'')G  
 :  
   (      & 22BCI
4  
 2&2B2B2DEr4   c                 >   U R                  SSSS9  U R                  SS[        R                  " S[        R                  5      SS	9  U R                  S
S[        R                  " S[        R                  5      SS	9  U R                  SSSS9  U R                  SSSS9  g)zHAdd arguments that are common to adding or modifying a scaling schedule.z--schedule-cronCRON_EXPRESSIONa          Start time of the scaling schedule in cron format.

        This is when the autoscaler starts creating new VMs, if the group's
        current size is less than the minimum required instances. Set the start
        time to allow enough time for new VMs to boot and initialize. For
        example if your workload takes 10 minutes from VM creation to start
        serving then set the start time 10 minutes earlier than the time you
        need VMs to be ready.
        rT   z--schedule-duration-secDURATIONi,  a          How long should the scaling schedule be active, measured in seconds.

        Minimum duration is 5 minutes. A scaling schedule is active from its
        start time and for its configured duration. During this time, the
        autoscaler scales the group to have at least as many VMs as defined by
        the minimum required instances. After the configured duration, if there
        is no need to maintain capacity, the autoscaler starts removing
        instances after the usual stabilization period and after scale-in
        controls (if configured). For more information, see
        [Delays in scaling in](https://cloud.google.com/compute/docs/autoscaler/understanding-autoscaler-decisions#delays_in_scaling_in) and [Scale-in controls](https://cloud.google.com/compute/docs/autoscaler/understanding-autoscaler-decisions#scale-in_controls).
        This ensures you don't accidentally lose capacity immediately after
        the scaling schedule ends.
        r[   z --schedule-min-required-replicasMIN_REQUIRED_REPLICASr   a          How many VMs the autoscaler should provision for the duration of this
        scaling schedule.

        Autoscaler provides at least this number of instances when the scaling
        schedule is active. A managed instance group can have more VMs if there
        are other scaling schedules active with more required instances or if
        another signal (for example, scaling based on CPU) requires more
        instances to meet its target.

        This configuration does not change autoscaling minimum and maximum
        instance limits which are always in effect. Autoscaler does not create
        more than the maximum number of instances configured for a group.
        z--schedule-time-zone	TIME_ZONEa          Name of the timezone that the scaling schedule's start time is in.

        It should be provided as a name from the IANA tz database (for
        example Europe/Paris or UTC). It automatically adjusts for daylight
        savings time (DST). If no time zone is provided, UTC is used as a
        default.

        See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for
        the list of valid timezones.
        z--schedule-descriptionDESCRIPTIONz.A verbose description of the scaling schedule.Nrx   )r   s    r5   r   r     s    	   !!#s{{3	  & (%!!!S[[1	  & 
   ;  r4   c           	         [        U S5      (       as  U R                  S5      (       a\  U HU  nU R                  U5      (       d  M  U Vs/ s H  nSUR                  SS5      -   PM     nn[        R                  " S/U-   6 e   g g g s  snf )Nautoscaling_file--_-rR   )hasattrIsSpecifiedreplacecalliope_exceptionsConflictingArgumentsException)argsconflicting_argsargaconflicting_flagss        r5   $ValidateConflictsWithAutoscalingFiler   ,  s    T%&&4+;+;<N+O+O			#		0@
0@1D199S#&&0@ 	 
 "??#$'88
 	
   ,P&
s   	Bc                     U R                  S5      (       a.  U R                  S5      (       a  [        R                  " SS5      eg g )Nr    update_stackdriver_metricrK   rX   )r   r   r   r   s    r5   9_ValidateCustomMetricUtilizationVsUpdateStackdriverMetricr   8  sL    	122t7G7G!8 8 
;
;%'D 82r4   c                     U R                  S5      (       aI  U R                  S5      (       a2  U R                  U R                  :X  a  [        R                  " SS5      eg g g )Nr   remove_stackdriver_metricrX   z_You can not remove Stackdriver metric you are updating with [--update-stackdriver-metric] flag.)r   r   r   r   InvalidArgumentExceptionr   s    r5   9_ValidateRemoveStackdriverMetricVsUpdateStackdriverMetricr   A  se    
233


6
7
7

(
(D,J,J
J

6
6%	.  K 8 4r4   c                     U R                  S5      (       dN  / SQnU HC  nU R                  U5      (       d  M  [        R                  " SUR                  SS5      -   S5      e   g g )Nr   )stackdriver_metric_filter-stackdriver_metric_single_instance_assignment%stackdriver_metric_utilization_target*stackdriver_metric_utilization_target_typer   r   r   z8[--update-stackdriver-metric] required to use this flag.)r   r   RequiredArgumentExceptionr   )r   requiring_flagsfs      r5   )_ValidateRequiringUpdateStackdriverMetricr   N  sf    			5	6	6O 			!		!;;199S#&&F
 	
  
7r4   c           	      |   U R                  S5      (       a  SS/n[        U Vs/ s H  o R                  U5      PM     sn5      (       dh  U Vs/ s H$  nSR                  UR                  SS5      5      PM&     nnSR                  SR	                  U5      5      n[
        R                  " S	U5      eg g s  snf s  snf )
Nr   r   r   [--{}]r   r   z>You must provide one of {} with [--update-stackdriver-metric].rJ   rX   )r   anyre   r   rf   r   r   )r   one_of_requiredr   r   msgs        r5   *_ValidateRequiredByUpdateStackdriverMetricr   ^  s    	1227/O _=_  #_=>>>MNoxqyyd34oeN++16$))E2B+C 
  99
'  ? 3
 >Ns   B4+B9c           	      r   U R                  S5      (       a  SS/nU Vs/ s H  o R                  U5      (       d  M  UPM     nn[        U5      (       aY  SnU Vs/ s H$  nSR                  UR                  SS5      5      PM&     nn[        R
                  " USR                  XT5      5      eg g s  snf s  snf )	Nr   r   r   r_   r   r   r   z"You cannot use any of {} with `{}`)r   r   re   r   r   r   )r   potential_conflictingr   conflictingassignment_flagr   s         r5   4_ValidateSingleInstanceAssignmentVsUtilizationTargetr   o  s    	EFF/4 4K37G7G7J13KK
;Io8C8C1(//!))C-
.    ==

.
5
5   G
 Ls   B/B/+B4c                     U R                  S5      (       a.  U R                  S5      (       d  [        R                  " SS5      eg g )Nr   r   r\   z8Required with [--stackdriver-metric-utilization-target].)r   r   r   r   s    r5   !_ValidateUtilizationTargetHasTyper     sN    	- IJJ

7
76B  Kr4   c                     [        U 5        [        U 5        [        U 5        [        U 5        [	        U 5        [        U 5        g)z<Perform validations related to .*stackdriver-metric.* flags.N)r   r   r   r   r   r   r   s    r5   ValidateStackdriverMetricsFlagsr     s2    ;DA;DA+D1,T26t<#D)r4   c                    U R                  S5      (       ak  UR                  R                  (       dO  UR                  R                  (       d3  UR                  R                  (       d  [
        R                  " SS5      eg g g g )Nr   rV   zThis would remove the only signal used for autoscaling. If you want to stop autoscaling the Managed Instance Group use `stop-autoscaling` command instead.)r   autoscalingPolicycustomMetricUtilizationscpuUtilizationloadBalancingUtilizationr   r   )r   
autoscalers     r5   "ValidateGeneratedAutoscalerIsValidr     sr    
233**CC**99**CC

6
6%	  D : D 4r4   c                    U R                   (       aB  U R                  (       a1  U R                   U R                  :  a  [        R                  " SS5      eU R                  (       a\  U R                   HK  nS H"  nX!;  d  M
  [        R                  " SUS-   5      e   US   S:  d  M6  [        R                  " SS	5      e   g
g
)zValidates args.rv   z$can't be less than min num replicas.)rM   rL   rN   rK   z not present.rM   r   z.--custom-metric-utilization utilization-targetzless than 0.N)r"   r   r   r   r    )r   r    fields      r5   ValidateAutoscalerArgsr     s    	t44t44488
 F  
##%)%C%C!N%1#<<+U_-D  O
 
##7	81	<!::<n
 	
 &D $r4   c                    [        U S5      (       a'  UR                  R                  nUR                  S5      n[        U S5      (       a'  UR                  R                  nUR                  S5      nW" S	0 U R                  5       D6n/ nUR                  WSU4/US9nU(       d  [        U5      S:w  a  [        R                  " U[        SS9  US   $ )
zRetrieves the given Instance Group Manager if possible.

Args:
  igm_ref: reference to the Instance Group Manager.
  client: The compute client.

Returns:
  Instance Group Manager object.
regionGetzone)errors_to_collect   zCould not fetch resource:error_messager   r,   )r   apitools_clientregionInstanceGroupManagersGetRequestTypeinstanceGroupManagersAsDictMakeRequestslenr   RaiseExceptionr7   )igm_refclientservicerequest_typerequesterrorsigm_detailss          r5   GetInstanceGroupManagerOrThrowr     s     Wh$$@@G))%0LWf$$::G))%0L,7>>+,'& ## !V $ + s;1$	!1
 
Qr4   c                 R    U R                  SUR                  UR                  S.SS9$ )z?Create zone reference from object with project and zone fields.Nprojectr   compute.zonesparams
collection)Parser   r   	resourcesdatas     r5   CreateZoneRefr     s.    	
tyy9  
 
 r4   c                 R    U R                  SUR                  UR                  S.SS9$ )zCCreate region reference from object with project and region fields.N)r   r   compute.regionsr   )r   r   r   r   s     r5   CreateRegionRefr     s.    	
=" 
 
 r4   c                     0 nU =(       d    /  H>  nUR                   U;  a  / XR                   '   XR                      R                  U5        M@     U$ )z!Group locations by project field.)r   rQ   )	locationsresultlocations      r5   GroupByProjectr    sQ    &/r/hv%!#f
##H- " 
-r4   c                    / n/ n[         R                  " [        U 5      5       H`  u  p`U[        R                  " UR
                  R                  U[        [        U  Vs/ s H  owR                  PM     sn5      5      SSS9-  nMb     U(       a  [        UR
                  S5      (       a  [         R                  " [        U5      5       H`  u  paU[        R                  " UR
                  R                  U[        [        U Vs/ s H  oR                  PM     sn5      5      SSS9-  nMb     OU(       a  UR                  S5        UR                  XTS9n	U(       a  [        R                   " USS	9  U	$ s  snf s  snf )
aR  Finds all Autoscalers defined for a given project and locations.

Args:
  zones: iterable of target zone references
  regions: iterable of target region references
  client: The compute client.
  fail_when_api_not_supported: If true, raise tool exception if API does not
    support autoscaling.

Returns:
  A list of Autoscaler objects.
r   N)r   r   scopes
scope_namefilter_exprregionAutoscalersr   )Nz)API does not support regional autoscaling)requestsr   z<Could not check if the Managed Instance Group is Autoscaled.r   )six	iteritemsr  r   FormatListRequestsr   autoscalerssortedsetr   r   r  r   rQ   r   r   RaiseToolException)
zonesregionsr   fail_when_api_not_supportedr   r  r   zone_ref
region_refr  s
             r5   AutoscalersForLocationsr    sK   " & (nU&;<ng))&&22c?X==?@A H = v%%':;;!mmN7,CD
'F--**<<#7K7Z007KLM
 	
 E 
%IJ##X#P+	J 
; @ Ls   E3E8c                 X   / nU  H=  u  p4nUR                  SR                  UR                  US-   [        XT5      US95        M?     [        R
                  " SSR                  U5      -   S-   5      nU Vs/ s H'  nUR                  UR                  5      (       d  M%  UPM)     nnU$ s  snf )zFinds Autoscalers with target amongst given IGMs.

Args:
  migs: List of triples (IGM name, scope type, location reference).
  autoscalers: A list of Autoscalers to search among.

Returns:
  A list of all Autoscalers with target on mig_names list.
zI/projects/{project}/{scopeType}/{scopeName}/instanceGroupManagers/{name}$s)r   	scopeType	scopeNamename(z)|())	rQ   re   r   getattrrecompilerf   searchtarget)	migsr  igm_url_regexesr  
scope_typer   igm_url_regexr   r   s	            r5   AutoscalersForMigsr%  3  s     /$( d	((.$$!C'h3	 )/ )
 %) **S5::o#>>DE- $#*			j//	0 # 	 
 
-s   5$B'B'c                 2   UR                  5       S:X  a  Sn[        X5      nU/SpeONUR                  5       S:X  a  Sn[        X5      nSU/peO([        SR	                  UR                  5       5      5      e[        XeU S9n[        UR                  5       UUUS9$ )	an  Returns autoscaler targeting given instance group manager.

Args:
  client: a GCE client
  resources: a GCE resource registry
  igm_ref: reference to instance group manager

Returns:
  Autoscaler message with autoscaler targeting the IGM refferenced by
  igm_ref or None if there isn't one.
Raises:
  ValueError: if instance group manager collection path is unknown
compute.instanceGroupManagersr   N#compute.regionInstanceGroupManagersr   Unknown reference type {0})r  r  r   mig_namer  r   r#  )
Collectionr   r   
ValueErrorre   r  AutoscalerForMigName)r   r   r   r#  r   r  r  r  s           r5   AutoscalerForMigByRefr0  Q  s     <<JY0HZ7DDJy2HH:7
1889K9K9MN
OO'6+ 
||~	
 r4   c                 n    [        XU4/U5      nU(       a  [        U5      S:X  a  US   $ [        S5      eg)a  Finds Autoscaler targeting given IGM.

Args:
  mig_name: Name of MIG targeted by Autoscaler.
  autoscalers: A list of Autoscalers to search among.
  location: Target location reference.
  scope_type: Target scope type.

Returns:
  Autoscaler object for autoscaling the given Instance Group Manager or None
  when such Autoscaler does not exist.
Raises:
  InvalidArgumentError: if more than one autoscaler provided
r   r   z+More than one Autoscaler with given target.N)r%  r   r:   r*  s       r5   r.  r.  v  sH     #h'(++  ;1^ !NOO	r4   c           	   #     ^#    U4S jnU4S jn[        U 5      n[        U Vs/ s H  nSU;   d  M  U" US   5      PM     sn5      n[        U Vs/ s H  nSU;   d  M  U" US   5      PM     sn5      n	0 n
[        UU	UUS9n[        U5      [        U	5      -    H  n/ XR                  5       '   M     U H  nSnUR                  b  U" UR                  5      n[        US5      (       a  UR                  b  U" UR                  5      nUc  MY  U
R                  UR                  5       / 5        XR                  5          R                  U5        M     U Hl  nSnSnSU;   a  U" US   5      nSnOSU;   a  U" US   5      nSnSnU(       a&  U(       a  [        US   XR                  5          UUS9nU(       a  XS	'   Uv   Mn     gs  snf s  snf 7f)
zCAdd Autoscaler to each IGM object if autoscaling is enabled for it.c                    > TR                  U S[        R                  R                  R                  R
                  0SS9$ )Nr   r   r   r   r   VALUEScorer   	GetOrFail)	zone_linkr   s    r5   	ParseZone'AddAutoscalersToMigs.<locals>.ParseZone  s?    ??:,,1199CCD"   r4   c                    > TR                  U S[        R                  R                  R                  R
                  0SS9$ )Nr   r   r   r4  )region_linkr   s    r5   ParseRegion)AddAutoscalersToMigs.<locals>.ParseRegion  s?    ??:,,1199CCD$   r4   r   r   )r  r  r   r  Nr  r*  r   )
listr  r  r/  r   r   r   
setdefaultrQ   r.  )migs_iteratorr   r   r  r9  r=  r!  migr  r  r  all_autoscalersr   r   autoscaler_scoper#  s     `             r5   AddAutoscalersToMigsrE    s    
 
m	$
G#3%yV%G
H%tOtx3+S]+tOP'++"=	/ u+W-h#%K  . $j"":??3z8$$):):)F$Z%6%67#-224b9'')*11*= $ cHJ3S]+hj	33v;'hjJJ#v;!--/2	j $,
I) / HOs/   !G
GGG
GG.BGCGc                 F   / SQn[         R                  " U /UQ76 (       a  UR                  5       nU R                  (       a  U R                  Ul        U R
                  (       a<  UR                  R                  n[        R                  " U R
                  U5      Ul	        U$ g)z<Builds the CPU Utilization message given relevant arguments.)r%   r#   !cpu_utilization_predictive_methodN)
r
   IsAnySpecifiedAutoscalingPolicyCpuUtilizationr%   utilizationTargetrG  PredictiveMethodValueValuesEnumr   ChoiceToEnumpredictiveMethod)r   messagesflags_to_checkcpu_messagecpu_predictive_enums        r5   _BuildCpuUtilizationrR    s    . ""49.99::<K""&*&A&Ak#--

2
2
R
R  &/%;%;

0
02E&k" 	r4   c                     / nU  HE  nUR                  UR                  US   US   UR                  R                  US   5      S95        MG     U$ )z:Translate --custom-metric-utilization flag to API message.rM   rL   rN   )rJ  rL   utilizationTargetType)rQ   (AutoscalingPolicyCustomMetricUtilization$UtilizationTargetTypeValueValuesEnum)flagrN  r   r    s       r5   =_BuildCustomMetricUtilizationsFromCustomMetricUtilizationFlagrX    sh     &#'
MM9978LM,X6AAff-.GH	 	: 	

 $( 
-r4   c                 T    [        U 5       H  u  p#UR                  U:X  d  M  X	   g    g N)	enumeraterL   )metrics	to_removeirL   s       r5   _RemoveMetricFromListr_     s'    W%ia}}	!
* &r4   c           
         U(       a  UR                   R                  nO/ nU R                  (       a  [        X0R                  5        U R                  (       a  [        X0R                  5        U R
                  (       aD  UR                  R                  U R
                  R                  5       R                  SS5      5      nOSnU R                  (       a&  SU R                  ;   a  [        R                  " S5        UR                  UR                  U R                  U R                  UU R                  U R                  S95        U$ )z9Take apply stackdriver flags to customMetricUtilizations.r   r   N'a  The provided filter contains a single quote character ('). While valid as a metric/resource label value, it's not a control character that is part of the filtering language; if you meant to use it to quote a string value, you need to use a double quote character (") instead.)rJ  rL   rT  singleInstanceAssignmentfilter)r   r   r   r_  r   r   rU  rV  upperr   r   r   warningrQ   r   r   )r   rN  originalr   target_types        r5   5_UpdateCustomMetricUtilizationsFromStackoverflowFlagsrh    s	    ''@@FF	##&"@"@A	##&"@"@A66EEjj

9
9
?
?
A
I
I3k k%%#1O1O*O	kk# MM99"HH11"-BB11 	: 	

 
-r4   c                     U R                   (       a  [        U R                   U5      $ [        U S5      (       a  [        XU5      $ g)zBuilds custom metric utilization policy list from args.

Args:
  args: command line arguments.
  messages: module containing message classes.
  original: original autoscaler message.

Returns:
  AutoscalingPolicyCustomMetricUtilization list.
r   N)r    rX  r   rh  r   rN  rf  s      r5   _BuildCustomMetricUtilizationsrk  2  sL     
##H&&  T.//@  0r4   c                     U R                   (       a  UR                  U R                   S9$ U R                  (       a  UR                  5       $ g )N)rJ  )r&   )AutoscalingPolicyLoadBalancingUtilizationr$   )r   rN  s     r5   _BuildLoadBalancingUtilizationrn  G  sI    	++==@@ >   
''==??	r4   c                 t    UR                   R                  U R                  5       R                  SS5      5      $ )Nr   r   )AutoscalingPolicyModeValueValuesEnumrd  r   )moderN  s     r5   ParseModeStringrs  Q  s1    		#	#	7	7
jjl3$
 r4   c                     U R                   (       d  U(       a  UR                  R                   $ S $ [        U R                   U5      $ rZ  )rr  r   rs  rj  s      r5   
_BuildModeru  W  s3    	.68%%**@D@	H	--r4   c                    U R                  S5      (       a  U R                  R                  S5      nU R                  R                  S5      nU(       a  U(       a  [        S5      eU(       a  UR	                  [        U5      S9nOUR	                  [        U5      S9nUR                  UU R                  R                  S5      S9$ g	)
a0  Builds AutoscalingPolicyScaleInControl.

Args:
  args: command line arguments.
  messages: module containing message classes.

Returns:
  AutoscalingPolicyScaleInControl message object.
Raises:
  InvalidArgumentError:  if both max-scaled-in-replicas and
    max-scaled-in-replicas-percent are specified.
scale_in_controlr   r   zgmax-scaled-in-replicas and max-scaled-in-replicas-percentare mutually exclusive, you can't specify both)percent)fixedr   )maxScaledInReplicastimeWindowSecN)r   rw  getr:   FixedOrPercentr   AutoscalingPolicyScaleInControl)r   rN  replicas_argreplicas_arg_percentmax_replicass        r5   BuildScaleInr  ]  s     
())((,,-EFL0044( , ;  
,,S9M5N,Ol,,3|3D,El33(++//> 4   *r4   c                     U R                    Vs0 s H  o"R                  S_M     nn[        R                  " U5      $ s  snf )ad  Encoder for use when removing a schedule.

It works around issues with proto encoding of AdditionalProperties with null
values by directly encoding a dict of keys with None values into json,
skipping proto-based encoding.

Args:
  message: an instance of AutoscalingPolicy.ScalingSchedulesValue.

Returns:
  Schedule removal request JSON dumped to string.
N)additionalPropertieskeyjsondumps)messageunused_encoderproperty	py_objects       r5   _RemoveScheduleEncoderr    s<     3:2N2NO2Nh||T!2N)O	I	 Ps   =c                     [        S5      e)zPlaceholder decoder for schedule removal message.

It's passed when registering message codec, but it will never be used as
removing schedules is a write-only operation.
z9This should never be called, it's a write-only operation.)NotImplementedError)unused_dataunused_decoders     r5   _RemoveScheduleDecoderr    s     	A	 r4   c           
      R   1 SknSnU H  n[        XS5      c  M  US-  nM     US:X  a  gUS:  a  [        S5      eUR                  R                  R                  nSSSS	S
S.n[        U SS5      b6  UR                  R                  U" U R
                  UR                  SS9S9/S9$ [        U SS5      b6  UR                  R                  U" U R                  UR                  SS9S9/S9$ [        U SS5      b`  [        R                  " [        [        S9" UR                  R                  5        UR                  R                  U" U R                  SS9/S9$ [        U SS5      b1  U R                  n1 SknUR                  5        V	s0 s H  oS_M     n
n	OU R                  n[!        5       n0 n
["        R$                  " U5       H*  u  p[        XS5      nUb  XU	'   M  X;   d  M!  [        S5      e   UR                  R                  U" UUR                  " S0 U
D6S9/S9$ s  sn	f )aw  Builds AutoscalingPolicyScalingSchedules.

Args:
  args: command line arguments.
  messages: module containing message classes.

Returns:
  Dict containing an AutoscalingPolicyScalingSchedule message object.
Raises:
  InvalidArgumentError:  if more than one of --scaling-schedule,
  --update-schedule, --remove-schedule,
  --enable-schedule, --disable-schedule is specified.
>   set_scheduleenable_scheduleremove_scheduleupdate_scheduledisable_scheduler   Nr   z--set-schedule, --update-schedule, --remove-schedule, --enable-schedule, --disable-schedule are mutually exclusive, only one can be specified.scheduledurationSecminRequiredReplicastimeZoner!   )schedule_cronschedule_duration_secschedule_min_required_replicasschedule_time_zoneschedule_descriptionr  F)disabledr  valuer  r  Tr  encoderdecoderr  >   r  r  r  z--set-schedule argument requires --schedule-duration-sec, --schedule-cron, and --schedule-min-required-replicas to be specified.r,   )r  r:   rp  ScalingSchedulesValueAdditionalPropertyr   AutoscalingPolicyScalingScheduler  r   RegisterCustomMessageCodecr  r  r  r  valuesr  r  r  r	  )r   rN  mutex_groupcountpossible_argumentscaling_schedule_wrapperfield_mappingpolicy_namerw   r   scaling_schedulearg_attrr   s                r5   BuildSchedulesr    s   "+ %&t-9qje ' aZ
QY
	     66II  ",(=&+- T$d+7%%;;$((???O
 <   T%t,8%%;;$))???N
 <   T$d+7 ''&0F  668 %%;;$)=)=TJ
 <  
 T>4(4##KH 2?1E1E1GH1Gt1GH&&KuH}5oh
$$
'C
 #u		   6 
	#	#	9	9
"== $ 
: 	
 	# Is   
H$c           
      J   U R                   [        X5      [        XU5      [        X5      U R                  U R
                  S.n[        XU5      US'   [        X5      US'   [        X5      US'   UR                  " S0 [        S [        R                  " U5       5       5      D6$ )zBuilds AutoscalingPolicy from args.

Args:
  args: command line arguments.
  messages: module containing message classes.
  original: original autoscaler message.

Returns:
  AutoscalingPolicy message object.
)coolDownPeriodSecr   r   r   maxNumReplicasminNumReplicasrr  scaleInControlscalingSchedulesc              3   6   #    U  H  u  pUc  M
  X4v   M     g 7frZ  r,   ).0r  r  s      r5   	<genexpr>)_BuildAutoscalerPolicy.<locals>.<genexpr>)  s       6jc 3,6s   	
r,   )r   rR  rk  rn  r   r"   ru  r  r  rp  dictr  r	  )r   rN  rf  policy_dicts       r5   _BuildAutoscalerPolicyr    s      00,T<"@
(# #A
# ----+ #48<+f".t">+$24$B+ !		#	# 
 MM+6 	
 r4   c                    U R                   c  UR                  5       U l         U R                   S[        [        -
  S-
   n[	        [        5       Vs/ s H8  n[
        R                  " [        R                  [        R                  -   5      PM:     nnSR                  U5      nSR                  X%5      nX`l         gs  snf )a  Set name of autoscaler o be created.

If autoscaler name is not None it wNone ill be used as a prefix of name of the
autoscaler to be created. Prefix may be shortened so that the name fits below
length limit. Name prefix is followed by '-' character and four
random letters.

Args:
  autoscaler_resource: Autoscaler resource to be created.
  igm_ref: reference to Instance Group Manager targeted by the Autoscaler.
Nr   r    z{0}-{1})r  r/  _MAX_AUTOSCALER_NAME_LENGTH!_NUM_RANDOM_CHARACTERS_IN_AS_NAMEr   randomchoicestringascii_lowercasedigitsrf   re   )autoscaler_resourcer   trimmed_namer   random_charactersrandom_suffixnew_names          r5   AdjustAutoscalerNameForCreationr  1  s     %&||~$))&)JJQN,
 677! mmF**V]]:;7   ''+,-l:(%s   ?B;c                 n    UR                  [        XU5      U R                  UUR                  5       S9nU$ )z*Builds autoscaler message protocol buffer.)r   r!   r  r   )
Autoscalerr  r!   SelfLink)r   rN  r   r  rf  r   s         r5   BuildAutoscalerr  K  sA    "".txH""	 # * 
r4   c                 l    Uc  Uc  / $ U R                  5       nU(       a  Xl        U(       a  X#l        U/$ )z*Creates autohealing policy list from args.)%InstanceGroupManagerAutoHealingPolicyhealthCheckinitialDelaySec)rN  health_checkinitial_delaypolicys       r5   CreateAutohealingPoliciesr  V  s9    m3I99;&%*
/r4   c                 *   UR                   (       a  UR                  5       /$ U(       d  UR                  (       d  gU (       a  U S   OSnU=(       d    UR                  5       nU(       a  X5l        UR                  (       a  UR                  Ul        U/$ )z/Modifies existing autohealing policy from args.Nr   )clear_autohealingr  r  r  r  )current_policiesrN  r   health_check_urlcurrent_policyr  s         r5   ModifyAutohealingPoliciesr  b  sv     
::<==	$"4"4*:#A&.MXKKM&)	!//F
/r4   c                     U (       d  gU S   nUR                   (       d*  UR                  (       a  Sn[        R                  " USS9  ggg)zhValidates autohealing policies.

Args:
  auto_healing_policies: list of AutoHealingPolicies to validate
Nr   zGWARNING: Health check should be provided when specifying initial delay.T)r  cancel_on_no)r  r  r   PromptContinue)auto_healing_policiesr  r  s      r5   ValidateAutohealingPoliciesr  t  sK     

 !#&			 6 6	  gDA !7	r4   c                    U R                  5       nUR                  S5      (       a\  UR                  (       a&  U R                   R                  R                  Ul        O%U R                   R                  R                  Ul        UR                  S5      (       a:  [        R                  " UR                  U R                   R                  5      Ul        UR                  S5      (       a:  [        R                  " UR                  U R                   R                  5      Ul        UR                  S5      (       aG  U R!                  [        R                  " UR"                  U R                   R$                  5      S9Ul        [)        U5      $ )z1Creates instance lifecycle policy list from args.force_update_on_repairdefault_action_on_vm_failure action_on_vm_failed_health_checkon_repair_allow_changing_zone)allowChangingZone)+InstanceGroupManagerInstanceLifecyclePolicyr   r  "ForceUpdateOnRepairValueValuesEnumYESforceUpdateOnRepairNOIsKnownAndSpecifiedr   rL  r  %DefaultActionOnFailureValueValuesEnumdefaultActionOnFailurer  "OnFailedHealthCheckValueValuesEnumonFailedHealthCheck3InstanceGroupManagerInstanceLifecyclePolicyOnRepairr   AllowChangingZoneValueValuesEnumonRepairValueOrNonerN  r   r  s      r5   CreateInstanceLifecyclePolicyr    sD   ??A&	.//""

>
>
a
a
e
e  
 
>
>
a
a
d
d   
<==$-$:$:))<<bb%F!
 
@AA!*!7!7--<<__"F
 
=>>RR#00..HHii
 S FO 
V	r4   c                 N    [        XU5      nUR                  US9n[        U5      $ )zCreates instance flexibility policy from args.

Args:
  args: arguments of the request
  messages: Compute API messages
  igm_resource: instance group manager resource that is being patched

Returns:
  InstanceFlexibilityPolicy.
)instanceSelections)CreateInstanceSelections-InstanceGroupManagerInstanceFlexibilityPolicyr  )r   rN  igm_resourceinstance_selectionsinstance_flexibility_policys        r5   CreateInstanceFlexibilityPolicyr    s<     1N <<0 =  
 
0	11r4   rN  r   c                     U R                  5       nUR                  S5      (       a  UR                  Ul        O#UR                  S5      (       a  [	        U 5        U$ [        U5      $ )z$Creates resource policies from args.workload_policyremove_workload_policy)$InstanceGroupManagerResourcePoliciesr  r  workloadPolicy%RegisterResourcePoliciesPatchEncodersr  r  s      r5   CreateResourcePoliciesr    s\     88:&	/00 00F 899)(3M	V	r4   c                 &  ^	 / nU R                  S5      (       d  U R                  S5      (       a  [        U5        [        U5      nU R                  S5      (       a=  U H6  m	UR                  UR                  R
                  R                  T	SS95        M8     OU R                  S5      (       aj  U R                   HZ  m	T	U;  a  M  [        U	4S jU 5       5      (       a  M'  UR                  UR                  R
                  R                  T	SS95        M\     U R                  S5      (       a  [        UUSU R                  S5        U R                  S	5      (       a  U R                   H  nS
U;  a  [        S5      eUS
   S   nSU;  d
  US   (       d  [        S5      eUS   nSnSU;   a3  US   S   nUR                  5       (       d  [        S5      e[        U5      n[        XXgU5        M     U(       d  gUR                  R                  US9$ )z7Build a list of InstanceSelection from the given flags.remove_instance_selections_allremove_instance_selectionsNr  c              3   B   >#    U  H  nUR                   T:H  v   M     g 7frZ  )r  )r  instance_selectioninstance_selection_names     r5   r  +CreateInstanceSelections.<locals>.<genexpr>  s%      
&9" ""&==&9s    instance_selection_machine_typeszinstance-selection-1r   r  r  z Missing instance selection name.r   zmachine-typez+Missing machine type in instance selection.rankz-Invalid value for rank in instance selection.r  )r  'RegisterInstanceSelectionsPatchEncoders"_GetExistingInstanceSelectionNamesrQ   r  InstanceSelectionsValuer  r  r   _AddInstanceSelectionr  r  r:   isdigitr   )
r   rN  r  r  !existing_instance_selection_namesr  r  machine_typesr  r  s
            @r5   r  r    sE   	&  <==+H5(J)%  @AA%F
!""BBZZmm+ n 	
 &G 
	!	!">	?	?%)%D%D
!"*KK
 
&9
 
 
 ""BBZZmm+ n 	
 &E 
@AA--	 
233"55	)	)"#EFF'*d  2
2#N3"9
 	
 )8md	%	%!&)!,||~~$=  4y
d+ 62 
		?	?	W	W. 
X 
 r4   c           
         U H`  nUR                   U:X  d  M  UR                  b  [        S5      eUR                  U R                  R
                  R                  USS95        Mb     UbA  UR                  U R                  R
                  R                  UU R                  XCS9S95        gUR                  U R                  R
                  R                  UU R                  US9S95        g)z4Adds instance selection to instance selections list.N?Attempt to add multiple instance selections with the same name.r  r  machineTypes)r!  )	r  r  r:   remover  r  r  rQ   >InstanceGroupManagerInstanceFlexibilityPolicyInstanceSelection)rN  r  r  r  r  r  s         r5   r  r    s
    0!88		!	!	-"M
 	
   

@
@
X
X
k
k) l  0 
>>VVii'YY Z  	j 	
 >>VVii'YY* Z  	j 	
r4   c                 x    U H4  nUR                   U :X  d  M  UR                  b  U(       a  [        S5      e  g   g)Nr  TF)r  r  r:   )intance_selection_namer  is_addr  s       r5   _IsPreviouslyProcessedr'  ?  sD    /!77		!	!	-&"M
 	
  0 
r4   c                     U R                   R                  R                   Vs/ s H  nUR                  PM     sn$ s  snf rZ  )instanceFlexibilityPolicyr   r  r  )r  r  s     r5   r  r  J  sB     !- F F Y Y n n
 n
  n
  
s   <c                     Uc  Uc  gU R                  5       nU(       a  Xl        U(       a@  UR                  5       R                  SS5      nU R                   R	                  U5      Ul        U$ )z!Creates standby policy from args.Nr   r   )!InstanceGroupManagerStandbyPolicyr  rd  r   rq  rr  )rN  initial_delay_secstandby_policy_modestandby_policystandby_policy_mode_enums        r5   CreateStandbyPolicyr0  Q  sp    
 #6#>==?.%6"288:BB3L22FF$	
 
 
r4   c                  N    [        5       nU  H  nUR                  U5        M     U$ rZ  )r  update)versions_listsversions_setversions_lists      r5   _GetInstanceTemplatesSetr6  e  s'    ,%m& &	r4   c                    [        U5      S:X  a+  US   R                  US   R                  :X  a  [        S5      eU(       a  gU R                  (       aD  U R                   Vs/ s H,  nUR	                  UR                  5      R                  5       PM.     nnOGU R                  (       a+  UR	                  U R                  5      R                  5       /nO[        S5      eU Vs/ s H,  nUR	                  UR                  5      R                  5       PM.     nn[        [        XV5      5      nUS:  a  [        S5      egs  snf s  snf )a  Validates whether versions provided by user are consistent.

Args:
  igm_info: instance group manager resource.
  new_versions: list of new versions.
  force: if true, we allow any combination of instance templates, as long as
    they are different. If false, only the following transitions are allowed:
    X -> Y, X -> (X, Y), (X, Y) -> X, (X, Y) -> Y, (X, Y) -> (X, Y)

Raises:
   InvalidArgumentError: if provided arguments are not complete or invalid.
   r   r   z.Provided instance templates must be different.NzREither versions or instance template must be specified for managed instance group.zUpdate inconsistent with current state. The only allowed transitions between versions are: X -> Y, X -> (X, Y), (X, Y) -> X, (X, Y) -> Y, (X, Y) -> (X, Y). Please check versions templates or use --force.)r   instanceTemplater:   versionsParseURLRelativeNamer6  )igm_infonew_versionsr   forceversionigm_templatesnew_templatesversion_counts           r5   ValidateVersionsrD  l  sH    
,1
q/
*
*l1o.N.N
N
O
PP


   (((G 	7334AAC(  M   8445BBDM 	"  "!' 112??A!  
 .}LM-Q
	:  )s   "3D>#3Ec                     / nSn[        [        XU5      UUSS9 HN  n[        X5      nXaR                  R                  R
                  R                  :X  a  SnUR                  U5        MP     XC4$ )a6  Add Autoscaler information if Autoscaler is defined for the MIGs.

Issue additional queries to detect if any given Instange Group Manager is
a target of some autoscaler and add this information to in 'autoscaled'
property.

Args:
  migs: list of dicts, List of IGM resources converted to dictionaries
  client: a GCE client
  resources: a GCE resource registry

Returns:
  Pair of:
  - boolean - True iff any autoscaler has an error
  - Copy of migs list with additional property 'autoscaled' set to 'No'/'Yes'/
  'Yes (*)' for each MIG depending on look-up result.
F)rA  r   r   r  T)rE  _ComputeInstanceGroupSizeResolveAutoscalingStatusForMigrN  r  StatusValueValuesEnumERRORrQ   )r!  r   r   augmented_migs
had_errorsrB  statuss          r5   AddAutoscaledPropertyToMigsrM    sv    & .*!-dIF"'	c ,F8F++AAGGGj# 	%%r4   c                 J   SU;   a  US   b  [        US   S5      (       aO  US   R                  U R                  R                  R                  R
                  :X  a  SUS'   US   R                  $ SUS'   U R                  R                  R                  R                  $ SUS'   g)zResolves 'autoscaled' property for MIG.

Uses 'autoscaler' property of a MIG to resolve 'autoscaled' property for
output.

Args:
  client: a GCE client
  mig: IGM resource as a dict

Returns:
  Status of autoscaler if MIG is autoscaled. None otherwise.
r   NrL  zyes (*)
autoscaledyesno)r   rL  rN  r  rH  rI  ACTIVE)r   rB  s     r5   rG  rG    s     SS.: 	L!8,,$$??%%;;AAB $c,%%%  c,__''==DDDCr4   c              #     #    / nU  Vs/ s HM  nSU;   d  M  UR                  US   S[        R                  R                  R                  R
                  0SS9PMO     nnU  Vs/ s HM  nSU;   d  M  UR                  US   S[        R                  R                  R                  R
                  0SS9PMO     nn/ n[        R                  " [        U5      5       H  u  pUR                  [        R                  " UR                  R                  U[        U V	s/ s H  oR                  PM     sn	5      SUR                  R                   UR"                  US95        M     / n
[%        UR                  S	S5      (       a  [        R                  " [        U5      5       H  u  pU
R                  [        R&                  " UR                  R(                  U[        U Vs/ s H  oR*                  PM     sn5      SUR                  R                   UR"                  US
95        M     Xz-   nU Vs0 s H  oR,                  UR.                  _M     nnU(       a  [0        R2                  " U5        U  H<  nUS   nUR5                  SS5      n[7        UR9                  US5      5      US'   Uv   M>     gs  snf s  snf s  sn	f s  snf s  snf 7f)z*Add information about Instance Group size.r   r   r   r   r   r   N)r   r   requested_zonesr  http	batch_urlr   regionInstanceGroups)r   r   requested_regionsr  rU  rV  r   selfLinkz/instanceGroupManagers/z/instanceGroups/r  size)r   r   r5  r6  r   r7  r  r	  r  extendr   GetZonalResourcesr   instanceGroupsr  r   rU  rV  r  GetRegionalResourcesrW  r   rY  rZ  r   r  r   ri   r|  )itemsr   r   r   rB  	zone_refsregion_refszonal_instance_groupsr   r   regional_instance_groupsr   instance_groupsiginstance_group_uri_to_sizeitem	self_linkgm_self_links                     r5   rF  rF    s    &  #	3ioo
f+Z..33;;EEF$  
     #	Sioo
h-Z..33;;EEF&  
    MM.*CDg    **99y Ayty AB'',,&&	

 E  V##%;TBB #n[.I J%%

%
%,,AA #$Mv]]$M N))..((
 !K *D/?NORWW 4O	V$dZ I$$!#5L 155lBGHDL
J m  !B %N  PsP   K
J/AJ/K#
J41AJ47A"KJ9.B/KJ>2;K- KA;Kc                 h   UR                   (       aQ  [        R                  R                  UU [        R
                  R                  R                  S9nUR                  5       $ UR                  (       aW  U R                  UR                  S[        R                  R                  R                  R                  0SS9R                  5       $ UR                   (       aW  U R                  UR                   S[        R                  R                  R                  R                  0SS9R                  5       $ g)z)Creates health check reference from args.)default_scoper   zcompute.httpHealthChecksr   zcompute.httpsHealthChecksN)r  r   HEALTH_CHECK_ARGResolveAsResourcecompute_flagscompute_scope	ScopeEnumGLOBALr  http_health_checkr   r   r5  r6  r   r7  https_health_check)r   r   refs      r5   GetHealthCheckUriru  '  s    	

-
-
?
?#11;;BB @ C
 <<>	??:,,1199CCD-   hj	
 
??:,,1199CCD.   hj	 r4   c           	         UR                  5       S:X  aN  / nU HD  nUR                  U R                  R                  UUR                  UR
                  S.SS95        MF     U$ UR                  5       S:X  a  U R                  R                  nUR                  UR                  5       UR                  UR                  S9n[        R                  " U R                  R                  R                  SUSS	S
9n/ nU HT  n	[        R                  " U	R                   5      U;   d  U	R                   U;   d  M9  UR                  U	R                   5        MV     U$ [#        SR%                  UR                  5       5      5      e)zFCreates references to instances in instance group (zonal or regional).r'  r   zcompute.instancesr   r(  )instanceGroupManagerr   r   i  ListManagedInstancesmanagedInstances)r   
batch_sizer   methodr   r)  )r,  rQ   r   r   r   r   r   rN  =ComputeRegionInstanceGroupManagersListManagedInstancesRequestr/  r   r   YieldFromListr   r   r   instancer-  re   )
holderr   instance_namesinstance_refsr~  rN  r   managed_instancesinstances_to_returninstance_refs
             r5   CreateInstanceReferencesr  ?  se   <<M"



 
 $__!,, - ! 	 # DD}}%%HNN$\\^~~	 	O   #00--II%  )


|44
5
G""n4""<#8#89 * 
1889K9K9MN
OOr4   c                     U (       a,  U R                   (       a  U R                   R                  (       d  / $ U R                   R                  R                   Vs/ s H  nUR                  PM     sn$ s  snf )zAReturns a list of device names from given StatefulPolicy message.)preservedStatedisksr  r  )stateful_policydisks     r5    GetDeviceNamesFromStatefulPolicyr  k  sa     ++++11I "0066KK
K$ hhK
  
s   A1c                     [        U S 5      $ )z8Returns a list of stateful internal IPs interface names.c                 .    U R                   R                  $ rZ  )r  internalIPsr  s    r5   <lambda>CGetInterfaceNamesFromStatefulPolicyForInternalIPs.<locals>.<lambda>}      o<<HHr4   *_GetInterfaceNamesFromStatefulPolicyForIPsr  s    r5   1GetInterfaceNamesFromStatefulPolicyForInternalIPsr  y      	3H
 r4   c                     [        U S 5      $ )z8Returns a list of stateful external IPs interface names.c                 .    U R                   R                  $ rZ  )r  externalIPsr  s    r5   r  CGetInterfaceNamesFromStatefulPolicyForExternalIPs.<locals>.<lambda>  r  r4   r  r  s    r5   1GetInterfaceNamesFromStatefulPolicyForExternalIPsr    r  r4   c                     U (       a  U R                   (       d  / $ U" U 5      nU(       d  / $ UR                   Vs/ s H  o3R                  PM     sn$ s  snf rZ  )r  r  r  )r  ips_field_lambdaipsips       r5   r  r    sH     
 > >I)#	I33	43R&&3	44	4s   Ac                      [        U SS 5      S L $ )Nr  )r  )r   s    r5   IsAutoscalerNewr    s    	VT	*d	22r4   c                 ,   SnUc  U R                   R                  5       nUR                  S5      (       aD  U R                   R                  R                  UR                  R                  5       5      Ul        UnUR                  S5      (       a3  [        R                  " SUR                  U R                   5      Ul
        UnUR                  S5      (       a4  [        R                  " SSUR                  U R                   5      Ul        UnUR                  S5      (       a4  [        R                  " S	S
UR                  U R                   5      Ul        UnUR                  S5      (       aG  [        R                   " SUR"                  U R                   R                  R$                  5      Ul        UnUR                  S5      (       aG  [        R                   " SUR(                  U R                   R                  R*                  5      Ul        UnUR                  S5      (       a3  [        R.                  " UR0                  U R                   5      nXBl        Un[5        US5      (       a)  UR                  S5      (       a  UR6                  Ul        UnU$ )z;Returns an update_policy with attributes from args applied.Ninstance_redistribution_typeupdate_policy_typez--update-policy-update-typeupdate_policy_max_surgez--update-policy-max-surgez	max-surgeupdate_policy_max_unavailablez--update-policy-max-unavailablezmax-unavailableupdate_policy_minimal_actionz--update-policy-minimal-action$update_policy_most_disruptive_actionz&--update-policy-most-disruptive-action update_policy_replacement_methodupdate_policy_min_ready)rN   InstanceGroupManagerUpdatePolicyr   )InstanceRedistributionTypeValueValuesEnumr  rd  instanceRedistributionTyper   ParseUpdatePolicyTyper  rD   ParseFixedOrPercentr  maxSurger  maxUnavailableParseInstanceActionFlagr  MinimalActionValueValuesEnumminimalActionr  *MostDisruptiveAllowedActionValueValuesEnummostDisruptiveAllowedActionParseReplacementMethodr  replacementMethodr   r  minReadySec)r   r   update_policyr   replacement_methods        r5   PatchUpdatePolicyr    s=   &OODDFM	45588bb
''--/:1 , F	*++/EE%t'>'>M F	/003GG#$$	M F	566#9#M#M)**	$M  F	45566())88UU#M F	<==6601188cc1M- F	899/FF--v '9#FT,--$2B2B3 3 !% < <MF	-r4   c           	         [        U R                  S5      (       d  / $ UR                  5       S:X  aT  U R                  R                  nU R                  R                  UR                  5       UR                  UR                  S9nOUR                  5       S:X  aT  U R                  R                  nU R                  R                  UR                  5       UR                  UR                  S9nO([        SR                  UR                  5       5      5      e/ n[        [        R                   " USU4/U R                  R"                  U R$                  US95      nU(       d  / $ US	   R&                  $ )
z+Lists per-instance-configs for a given IGM.9ComputeInstanceGroupManagersListPerInstanceConfigsRequestr'  )rw  r   r   r(  )rw  r   r   r)  ListPerInstanceConfigs)r  rU  rV  r   r   )r   rN  r,  r   r   r  r/  r   r   r   ?ComputeRegionInstanceGroupManagersListPerInstanceConfigsRequestr   r-  re   r?  r   r   rU  rV  r_  )r   r   r   r   r   resultss         r5   r  r    sR   	ooA
 
 I<<$$::GQQ$\\^\\	 	R   DD$$@@GWW$\\^~~	 	X   1889K9K9MN
OO&!!6@A%%**$$	' 
I			r4   c                     [        U R                  S5      =(       aG    [        U R                  R                  S5      =(       a     U R                  R                  R                  $ )z+For a given IGM, returns if it is stateful.statefulhasStatefulConfig)r   rL  r  r  )r=  s    r5   
IsStatefulr    sI     hooz* 5
(//**,?
@5
//
"
"
4
4r4   c                    U R                   (       d  gUR                  R                  nU R                   R                  UR                  R
                  :H  nU R                   R                  UR                  R                  :H  nU R                   R                  UR                  R
                  :H  nU(       a  U(       a  [        R                  " S5      eU(       a  [        R                  " S5      eg)zFThrows exception if IGM is in state not ready for adding statefulness.NzStateful IGMs cannot use SUBSTITUTE replacement method. Try `gcloud compute instance-groups managed rolling-update stop-proactive-updatezStateful regional IGMs cannot use proactive instance redistribution. Try `gcloud compute instance-groups managed update --instance-redistribution-type=NONE)updatePolicyrN  r  rD   TypeValueValuesEnum	PROACTIVEr   ReplacementMethodValueValuesEnum
SUBSTITUTEr  r  r	   r*   )r  r   client_update_policytype_is_proactive replacement_method_is_substitute)instance_redistribution_type_is_proactives         r5   ValidateIgmReadyForStatefulnessr    s    		"	"
II"//44..88 11

?
?
J
JL # /;.G.G.b.bDDNN/+ ;


	/ 
 /


	5  /r4   c                 >    U c  U $ U R                  5       nX:w  a  U $ S$ )a  Return message if message is a proto with one or more fields set or None.

If message is None or is the default proto, it returns None. In all other
cases, it returns the message.

Args:
  message: A generated proto message object.

Returns:
  message if message is initialized or None
N)	__class__)r  default_objects     r5   r  r  +  s,     _N$$&.-747r4   c                   ^  S nU 4S jnU 4S jn[         R                  " XS9" T R                  R                  R                  5        [         R                  " XS9" T R                  R                  R
                  5        g)ziRegisters decoders and encoders that will handle null values for maps in InstancePropertiesPatch message.c                     [         R                  " U R                   Vs0 s H  nUR                  UR                  _M     sn5      $ s  snf )az  Encoder for use when removing map entries.

It works around issues with proto encoding of AdditionalProperties with null
values by directly encoding a dict of keys with None values into json,
skipping proto-based encoding.

Args:
  message: an instance of InstancePropertiesPatch.MetadataValue or
    InstancePropertiesPatch.LabelsValue

Returns:
  JSON string with null value.
)r  r  r  r  r  )r  r  s     r5   _NullValueEncoderHRegisterCustomInstancePropertiesPatchEncoders.<locals>._NullValueEncoder@  sH     ::444H 	hnn$4   s   !Ac                   > [         R                  " U 5      nTR                  R                  R	                  UR                  5        VVs/ s H2  u  p#TR                  R                  R                  R                  X#S9PM4     snnS9$ s  snnf )zDecoder for metadata map entries.

Args:
  data: JSON representation of metadata map.

Returns:
  Instance of InstancePropertiesPatch.MetadataValue.
r  r  )r  loadsrN  InstancePropertiesPatchMetadataValuer_  r  r   r  r  r  r   s       r5   _NullMetadataDecoderKRegisterCustomInstancePropertiesPatchEncoders.<locals>._NullMetadataDecoderS  s     

4 I??22@@
 (oo/	
 0
 OO33AATT U  0	
 A  
   
9B	
c                   > [         R                  " U 5      nTR                  R                  R	                  UR                  5        VVs/ s H2  u  p#TR                  R                  R                  R                  X#S9PM4     snnS9$ s  snnf )zDecoder for labels map entries.

Args:
  data: JSON representation of labels map.

Returns:
  Instance of InstancePropertiesPatch.LabelsValue.
r  r  )r  r  rN  r  LabelsValuer_  r  r  s       r5   _NullLabelsDecoderIRegisterCustomInstancePropertiesPatchEncoders.<locals>._NullLabelsDecoderf  s     

4 I??22>>
 (oo/	
 0
 OO33??RR S  0	
 ?  
r  r  N)r   r  rN  r  r  r  )r   r  r  r  s   `   r5   -RegisterCustomInstancePropertiesPatchEncodersr  =  sh    &&& %%
OO++99; %%
OO++779r4   c                 ,  ^ ^^^ T R                   R                  T R                   R                  R                  R                  S9T R                   R                  T R                   R                  R                  R                  S9S.mU4S jnS mUU 4S jnUU 4S jnU4S jm[
        R                  " XS9" T R                   R                  R                  5        [
        R                  " XS9" T R                   R                  R                  5        g	)
zzRegisters decoders and encoders that will handle null values for Internal and External IPs maps in StatefulPolicy message.
autoDeleteNEVERON_PERMANENT_INSTANCE_DELETIONc           	         > [         R                  " U R                   Vs0 s H  nUR                  T" U5      _M     sn5      $ s  snf )a  Encoder for Stateful Ips map entries.

It works around issues with proto encoding of StatefulPolicyPreservedState
with null values by directly encoding a dict of keys with None values into
json, skipping proto-based encoding.

Args:
  message: an instance of StatefulPolicyPreservedState.InternalIPsValue or
    StatefulPolicyPreservedState.ExternalIPsValue

Returns:
  JSON string with null value.
r  r  r  r  r  r  _GetAutodeleteOrNones     r5   _StatefulIpsValueEncoderHRegisterCustomStatefulIpsPatchEncoders.<locals>._StatefulIpsValueEncoder  sK     ::444H 	*8444      Ac                 b    U R                   c  g SU R                   R                  R                  0$ Nr  r  r  r  
autodeletes    r5   r  DRegisterCustomStatefulIpsPatchEncoders.<locals>._GetAutodeleteOrNone  .    ***55::;;r4   c                 T   > TR                   R                  R                  nT" X5      $ )zDecoder for Stateful Ips map entries.

Args:
  data: JSON representation of Internal Stateful Ips.

Returns:
  Instance of StatefulPolicyPreservedState.InternalIPsValue.
)rN  StatefulPolicyPreservedStateInternalIPsValuer   	ips_value_CommonStatefulIpsDecoderr   s     r5   _InternalStatefulIpsDecoderKRegisterCustomStatefulIpsPatchEncoders.<locals>._InternalStatefulIpsDecoder  s%     <<MMI$T55r4   c                 T   > TR                   R                  R                  nT" X5      $ )zDecoder for Stateful Ips map entries.

Args:
  data: JSON representation of External Stateful Ips.

Returns:
  Instance of
  StatefulPolicyPreservedState.ExternalIPsValue.AdditionalProperty.
)rN  r  ExternalIPsValuer  s     r5   _ExternalStatefulIpsDecoderKRegisterCustomStatefulIpsPatchEncoders.<locals>._ExternalStatefulIpsDecoder  s%     <<MMI$T55r4   c                    > [         R                  " U 5      nU" UR                  5        VVs/ s H  u  p4UR                  UTUS      S9PM     snnS9$ s  snnf )Nr  r  r  )r  r  r_  r  )r   r  r  r  r  auto_delete_maps        r5   r  IRegisterCustomStatefulIpsPatchEncoders.<locals>._CommonStatefulIpsDecoder  sl    

4 I
 (oo/	
 0
 ((u\/BC )  0	
 
s   "A
r  N)
rN  %StatefulPolicyPreservedStateNetworkIpAutoDeleteValueValuesEnumr  r  r   r  r  r  r  )r   r  r  r  r  r  r  s   `   @@@r5   &RegisterCustomStatefulIpsPatchEncodersr
    s     DD__JJddjj E  )/(](]__JJdd  D  D )^ )	/&<

66	 %%&
OO00AAC %%&
OO00AACr4   c                   ^ ^^ T R                   R                  T R                   R                  R                  R                  S9T R                   R                  T R                   R                  R                  R                  S9S.mU4S jnS mUU 4S jn[
        R                  " XS9" T R                   R                  R                  5        g)znRegisters decoders and encoders that will handle null values for Stateful Disks map in StatefulPolicy message.r  r  c           	         > [         R                  " U R                   Vs0 s H  nUR                  T" U5      _M     sn5      $ s  snf )aV  Encoder for Stateful Disks map entries.

It works around issues with proto encoding of StatefulPolicyPreservedState
with null values by directly encoding a dict of keys with None values into
json, skipping proto-based encoding.

Args:
  message: an instance of StatefulPolicyPreservedState.DisksValue

Returns:
  JSON string with null value.
r  r  s     r5   _StatefulDisksValueEncoderLRegisterCustomStatefulDisksPatchEncoders.<locals>._StatefulDisksValueEncoder  sK     ::444H 	*8444   r  c                 b    U R                   c  g SU R                   R                  R                  0$ r  r  r  s    r5   r  FRegisterCustomStatefulDisksPatchEncoders.<locals>._GetAutodeleteOrNone  r  r4   c                    > TR                   R                  R                  n[        R                  " U 5      nU" UR                  5        VVs/ s H  u  p4UR                  UTUS      S9PM     snnS9$ s  snnf )zDecoder for Stateful Disks map entries.

Args:
  data: JSON representation of Stateful Disks.

Returns:
  Instance of StatefulPolicyPreservedState.DisksValue.
r  r  r  )rN  r  
DisksValuer  r  r_  r  )r   disk_device_valuer  r  r  r  r   s        r5   _StatefulDisksDecoderGRegisterCustomStatefulDisksPatchEncoders.<locals>._StatefulDisksDecoder  s     DDOO

4 I
 (oo/	
 0
 00u\/BC 1  0	
 
s   "A5
r  N)	rN  &StatefulPolicyPreservedStateDiskDevicer	  r  r  r   r  r  r  )r   r  r  r  r  s   `  @@r5   (RegisterCustomStatefulDisksPatchEncodersr    s     EE__KKeekk F  )/(^(^__KKee  E  E )_ )	/$<
( %%(
OO00;;=r4   c                 v   ^  S nU 4S jn[         R                  " UUS9" T R                  R                  5        g)zmRegisters encoders that will handle null values for Instance Selections in InstanceFlexibilityPolicy message.c           	          S n[         R                  " U R                   Vs0 s H  nUR                  U" U5      _M     sn5      $ s  snf )as  Encoder for Instance Selections map entries.

It works around issues with proto encoding of InstanceSelections
with null values by directly encoding a dict of keys with None values into
json, skipping proto-based encoding.

Args:
  message: an instance of
    InstanceGroupManagerInstanceFlexibilityPolicy.InstanceSelectionsValue

Returns:
  JSON string with null value.
c                 x    U R                   c  g U R                   R                  U R                   R                  S.$ )Nr   )r  r  r!  )props    r5    _GetInstanceSelectionValueOrNonezRegisterInstanceSelectionsPatchEncoders.<locals>._InstanceSelectionsValueEncoder.<locals>._GetInstanceSelectionValueOrNone	  s,    		jjootzz7N7NOOr4   r  )r  r  r  s      r5   _InstanceSelectionsValueEncoderPRegisterInstanceSelectionsPatchEncoders.<locals>._InstanceSelectionsValueEncoder	  sP    P
 ::444H 	6x@@4   s   Ac                    > TR                   R                  n[        R                  " U 5      nU" UR	                  5        VVs/ s H  u  p4UR                  X4S9PM     snnS9$ s  snnf )zDecoder for Instance Selections map entries.

Args:
  data: JSON representation of Instance Selections.

Returns:
  Instance of
  InstanceGroupManagerInstanceFlexibilityPolicy.InstanceSelectionsValue.
r  r  )r  r  r  r  r_  r  )r   instance_selections_valuer  r  r  rN  s        r5   _InstanceSelectionsDecoderKRegisterInstanceSelectionsPatchEncoders.<locals>._InstanceSelectionsDecoder)	  so     	>>VV  

4 I$ (oo/
/
 &88S8N/
 
s   A$
r  N)r   r  r  r  )rN  r  r"  s   `  r5   r  r  	  s9    2* %%-( <<TT	r4   returnc                 b   ^  S nU 4S jn[         R                  " UUS9" T R                  5        g)zbRegisters encoders that will handle null values for resource policies in ResourcePolicies message.c                 J    U R                   c  g[        R                  " U 5      $ )a@  Encoder for Resource Policies message.

It works around issues with proto encoding of ResourcePolicies
with null values by directly encoding a message with None value into
json, skipping proto-based encoding.

Args:
  message: an instance of InstanceGroupManagerResourcePolicies

Returns:
  JSON string with null value.
null)r  r   encode_message)r  s    r5   _ResourcePoliciesEncoderGRegisterResourcePoliciesPatchEncoders.<locals>._ResourcePoliciesEncoderI	  s$     %##G,,r4   c                 F   > [         R                  " TR                  U 5      $ )zDecoder for Resource Policies message.

Args:
  data: JSON representation of Resource Policies.

Returns:
  Instance of InstanceGroupManagerResourcePolicies.
)r   decode_messager
  )r   rN  s    r5   _ResourcePoliciesDecoderGRegisterResourcePoliciesPatchEncoders.<locals>._ResourcePoliciesDecoder[	  s#     ##55t r4   r  N)r   r  r
  )rN  r)  r-  s   `  r5   r  r  F	  s3    -$ %%&& 113r4   c                     U R                  5       n[        R                  " U5      nU R                   R                  U5      Ul        U$ )z%Creates target size policy from args.)$InstanceGroupManagerTargetSizePolicyr   ChoiceToEnumNamerq  rr  )rN  rr  target_size_policy	mode_enums       r5   CreateTargetSizePolicyr4  o	  sH    DDF((.)33GG
  
r4   )FF)T)FrZ  )NN)r2   
__future__r   r   r   r  r  r  r  rz   typesapitools.base.protorpcliter   apitools.base.pyr   r   googlecloudsdk.api_lib.computer	   r
   r   r   r   r   googlecloudsdk.callioper   r   r   r   "googlecloudsdk.command_lib.computer   rn  :googlecloudsdk.command_lib.compute.managed_instance_groupsr   r   $googlecloudsdk.command_lib.util.apisr   googlecloudsdk.corer   r   googlecloudsdk.core.consoler   r  	six.movesr   rg   rk   +ARGS_CONFLICTING_WITH_AUTOSCALING_FILE_BETA,ARGS_CONFLICTING_WITH_AUTOSCALING_FILE_ALPHAr  r  r*   r7   r:   r=   r@   rt   rc   rl   rn   r   r   ro   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r%  r0  r.  rE  rR  rX  r_  rh  rk  rn  rs  ru  r  r  r  r  r  r  r  r  r  r  r  r  
ModuleType	Namespacer  r  r  r'  r  r0  r6  rD  rM  rG  rF  ru  r  r  r  r  r  r  r  r  r  r  r  r  r
  r  r  r  r4  r,   r4   r5   <module>rE     s   N &  '   	  
  0 % ' 5 9 1 : 9 0 / ( E 5 E Y ] : # * 2 
 % !+ '
/ + 0 -
 ! 
 %& !>J >H H-:++ -@U @N N^.B>-`6GFTIX	


 "(*
*D 9=7t<"J< CG?D.((V*.D"od!H&4	$B&!H2*&7&A&AJZ!H ;?(3l&D@@F0)PX53=@(V>8$A9HMC`9=x6r&3E4D4D &3 &3R
r4   