
    K                     *   d Z ddlmZ ddlmZ ddlmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZ dd	lmZ ddlmZ dd
lmZ dd	lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlZ G d dej@                        Z! G d de!      Z" G d de"ejF                        Z$ G d de!ejJ                        Z% G d de!      Z& G d de&ejN                        Z' G d de&ejP                        Z)	 	 	 	 d%dZ*	 	 	 	 	 d&d Z+d! Z,d" Z-d'd#Z.d$ Z/y)(zIBase classes for [enable|disable|describe] commands for Feature resource.    )absolute_import)division)unicode_literals)
exceptions)util)
enable_api)apis)base)api_util)	resources)info)log)
properties)retryNc                   P     e Zd ZdZdZed        Zd fd	ZddZddZ	ddZ
 xZS )	FeatureCommandzFFeatureCommand is a mixin adding common utils to the Feature commands. c                 @    t        j                  | j                        S )z2The Feature info entry for this command's Feature.)r   Getfeature_name)selfs    ?lib/googlecloudsdk/command_lib/container/fleet/features/base.pyfeaturezFeatureCommand.feature+   s     88D%%&&    c                 @    t         t        |   | j                  |      S )zZBuilds the full resource name, using the core project property if no project is specified.)superr   FeatureResourceNamer   )r   project	__class__s     r   r   z"FeatureCommand.FeatureResourceName0   s$    ++/+<+<gFGr   c                     |xs2 t         j                  j                  j                  j	                         }t        j                  dj                  | j                  j                  |            S )zFConstructs a new Error for reporting when this Feature is not enabled.z*{} Feature for project [{}] is not enabled
r   VALUEScorer   	GetOrFailr   Errorformatr   display_namer   r   s     r   FeatureNotEnabledErrorz%FeatureCommand.FeatureNotEnabledError5   sW    C**//77AACGHOO!!7, - -r   c                     |xs2 t         j                  j                  j                  j	                         }t        j                  dj                  | j                  j                  |            S )zSConstructs a new Error for reporting when accessing this Feature is not authorized.z4Not authorized to access {} Feature for project [{}]r!   r(   s     r   NotAuthorizedErrorz!FeatureCommand.NotAuthorizedError;   sW    C**//77AACG>EELL%%w	01 1r   c                     	 | j                   j                  | j                  |            S # t        j                  $ r | j                  |      t        j                  $ r | j                  |      w xY w)zBFetch this command's Feature from the API, handling common errors.)	hubclient
GetFeaturer   apitools_exceptionsHttpNotFoundErrorr)   HttpUnauthorizedErrorr+   r(   s     r   r.   zFeatureCommand.GetFeatureB   sl    -^^&&t'?'?'HII00 1''0044 -##G,,-s
   ), AA4N)__name__
__module____qualname____doc__r   propertyr   r   r)   r+   r.   __classcell__)r   s   @r   r   r   '   s2    N,' 'G
-1-r   r   c                       e Zd ZdZd Zd Zy)EnableCommandMixinz.A mixin for functionality to enable a Feature.c                    t         j                  j                  j                  j	                         }| j
                  j                  r*t        j                  || j
                  j                         t        j                  |      }	 t        j                  dd      }|j                  | j                  j                  || j                   |f| j"                  d      }d	j+                  | j
                  j,                        }| j?                  | j                  j@                  ||
      S # t        j$                  $ r9 t'        j(                  dj+                  | j
                  j,                              t.        j0                  $ rr}t3        j4                  |      }|j6                  dk7  r t8        j:                  j=                  dj+                  | j
                  j,                  |             Y d }~y d }~ww xY w)N   g      ?)max_retrialsexponential_sleep_multiplieri  )argsshould_retry_ifsleep_msz-Retry limit exceeded waiting for {} to enableALREADY_EXISTSz.{} Feature for project [{}] is already enabledz$Waiting for Feature {} to be created)opmessage)!r   r"   r#   r   r$   r   apir   EnableServiceIfDisabledr   LocationResourceNamer   RetryerRetryOnExceptionr-   CreateFeaturer   _FeatureAPINotEnabledMaxRetrialsExceptionr   r%   r&   r'   r/   HttpConflictErrorcore_api_exceptionsHttpErrorPayloadstatus_descriptionr   statusPrintWaitForHubOpfeature_waiter)	r   r   r   parentretryerrC   eerrormsgs	            r   EnablezEnableCommandMixin.EnableO   s   $$,,668G||(($,,2B2BC&&w/F 14Pg##
..
&
&))7344	 $ b" 1
7
7!!#CT^^::r3OO %% *
9
@
@ll'')* * 00 !2215e		!	!%5	5	jjGNN
,,
#
#W. /s   	AD- -AG<
A(G77G<c                 F   ~~| j                   j                  sy|t        j                  k7  ryt	        j
                  |      }|j                  dk(  r0| j                   j                  |j                  v rd|j                  v syt        j                  j                  d       y)NFFAILED_PRECONDITIONzis not enabledz/Waiting for service API enablement to finish...T)r   rE   r/   HttpBadRequestErrorrN   rO   rP   rD   r   rQ   rR   )r   exc_type	exc_value	tracebackstaterX   s         r   rK   z(EnableCommandMixin._FeatureAPINotEnabledm   s    5<<&:::00;E$$(==LL--JJFGr   N)r3   r4   r5   r6   rZ   rK    r   r   r:   r:   L   s    6P<r   r:   c                       e Zd ZdZd Zy)EnableCommandz2Base class for the command that enables a Feature.c                 T    | j                  | j                  j                               S r2   )rZ   messagesFeaturer   _s     r   RunzEnableCommand.Run   s    ;;t}},,.//r   N)r3   r4   r5   r6   rj   rb   r   r   rd   rd   |   s
    :0r   rd   c                       e Zd ZdZd Zd Zy)DescribeCommandzBBase class for the command that describes the status of a Feature.c                 "    | j                         S r2   )r.   rh   s     r   rj   zDescribeCommand.Run   s    ??r   c                    |D ci c]  }t        j                  |      | }}i }|j                  rb|j                  j                  D ci c]C  }t        j                  |j                        |v r t        j                  |j                        |E }}|j                         D cg c]  \  }}||vr| }}}|r9t        j                  dj                  | j                  j                  |            i }	|j                  rb|j                  j                  D ci c]C  }t        j                  |j                        |v r t        j                  |j                        |E }	}| j                  j                  j                  t        |j!                                     |_        | j                  j                  j#                  |D cg c]  }||	v r|	|    c}      |_        yc c}w c c}w c c}}w c c}w c c}w )a  Leave only specs and states of Memberships in the Feature.

    Respects the order of the Membership specs in the original Feature.

    Args:
      feature: Feature in the v1 API.
      memberships: List of resource names according to go/resource-names.
        Ideally, the existence of these Memberships will have been verified.
    Returns:
      None
    Raises:
      exceptions.Error: if any of Memberships does not have a spec in Feature.
    zcThe following requested memberships are not configured on the {} feature, under membershipSpecs: {})additionalPropertiesN)r   MembershipPartialNamemembershipSpecsro   keyitemsr   r%   r&   r   r'   membershipStatesrf   rg   MembershipSpecsValuelistvaluesMembershipStatesValue)
r   r   membershipsm memberships_by_location_and_name%membership_specs_by_location_and_nameentrylocation_namemissing_memberships&membership_states_by_location_and_names
             r   filter_feature_for_membershipsz.DescribeCommand.filter_feature_for_memberships   s   " 3>(2=Q""1%q(+ % ( -/) ..CC/Ce''		2-. 
$
$UYY
/
6C , / !A F F H HM1 EE 	
 H  
 1F4<<,,.AB 
 .0* //DD0De''		223 
$
$UYY
/
6D - 0 #mm33HH!188:
 I G
  $}}44JJ ;
::: 315:
  K  GK(
/0
s   G(
AG-'G2AG8
G=N)r3   r4   r5   r6   rj   r   rb   r   r   rl   rl      s    J;r   rl   c                       e Zd ZdZd Zy)UpdateCommandMixinz.A mixin for functionality to update a Feature.c                 D   	 | j                   j                  | j                         ||      }dj                  | j                  j                        }| j                  | j                   j                  ||d      S # t        j                  $ r | j                         w xY w)z>Update provides common API, display, and error handling logic.z$Waiting for Feature {} to be updatedFrD   warnings)r-   UpdateFeaturer   r/   r0   r)   r&   r   r'   rS   rT   )r   maskpatchrC   rY   s        r   UpdatezUpdateCommandMixin.Update   s    *>>''(@(@(BD%Pb 1
7
7!!#C%%r3    00 *''))*s   +A; ;$BN)r3   r4   r5   r6   r   rb   r   r   r   r      s
    6r   r   c                       e Zd ZdZy)UpdateCommandzBase class for the command that updates a Feature.

  Because Features updates are often bespoke actions, there is no default
  `Run` override like some of the other classes.
  N)r3   r4   r5   r6   rb   r   r   r   r      s    r   r   c                       e Zd ZdZ ej
                  ddd      Z ej
                  ddd      ZdZe	d	        Z
d
 Zd Zd Zy)DisableCommandzLBase class for the command that disables an entire or parts of a Feature.
  z--force
store_truezForce disablement. Bypasses any prompts for confirmation. When disabling the entire feature, proceeds even if the feature is in use. Might result in unexpected behavior.)actionhelpz--fleet-default-member-configzDisable the [fleet-default membership configuration](https://cloud.google.com/kubernetes-engine/fleet-management/docs/manage-features). Does not change existing membership configurations. Does nothing if the feature is disabled.Fc                     | j                   j                  |       | j                  r| j                  j                  |       y y r2   )
FORCE_FLAGAddToParsersupport_fleet_default FLEET_DEFAULT_MEMBER_CONFIG_FLAG)clsparsers     r   ArgszDisableCommand.Args  s6    NNv&
  	**66v> !r   c                     | j                   r|j                  r| j                          y | j                  |j                         y r2   )r   fleet_default_member_configclear_fleet_defaultDisableforce)r   r?   s     r   rj   zDisableCommand.Run  s/    !!d&F&F
 
ll4::r   c                 *   	 | j                   j                  | j                         |      }dj                  | j                  j                        }| j                  | j                   j                  ||d       y # t        j                  $ r Y y w xY w)N)r   z$Waiting for Feature {} to be deletedFr   )
r-   DeleteFeaturer   r/   r0   r&   r   r'   rS   resourceless_waiter)r   r   rC   rD   s       r   r   zDisableCommand.Disable  s    >>''(@(@(B%'Pb 5;;!!#G**B%  Q	 00 s   +A< <BBc                    dg}| j                   j                  d      }	 | j                  ||      S # t        j                  $ rE}t        j                  |      t        j                  | j                               k7  r|Y d }~y d }~ww xY w)Nr   placeholder)name)rf   rg   r   r   r%   six	text_typer)   )r   r   r   rW   s       r   r   z"DisableCommand.clear_fleet_default  s}    )*D MM!!}!5E[[u%% 	q	S]]4+F+F+HI	I 
Js   3 B;BBN)r3   r4   r5   r6   calliope_baseArgumentr   r   r   classmethodr   rj   r   r   rb   r   r   r   r      sr     &}%%2	
* &<]%;%;% 6&"  ? ?
Qr   r   c                 l   | j                  d      s"| j                  d      s| j                  |      rFt        j                  | |      s|st        j                  | |      S t        j                  | |d      S |s|st        | |      t        j                  d      \  }}|r$t        j                  dj                  |            |rDt        |      dk(  r6t        j                  j                  dj                  |d                |d   S |rt        j                  |      }||S t        | |      )	a*  Returns a membership on which to run the command, given the arguments.

  Allows for a `--membership` flag or a `MEMBERSHIP_NAME` positional flag.

  Args:
    args: object containing arguments passed as flags with the command
    prompt: whether to prompt in console for a membership when none are provided
      in args
    autoselect: if no membership is provided and only one exists,
      automatically use that one
    search: whether to search for the membership and error if it does not exist
      (not recommended)
    flag_override: to use a custom membership flag name

  Returns:
    membership: A membership resource name string

  Raises:
    exceptions.Error: no memberships were found or memberships are invalid
    calliope_exceptions.RequiredArgumentException: membership was not provided
  
membershipMEMBERSHIP_NAMETfilter_cluster_missingLocations {} are currently unreachable. Please specify memberships using `--location` or the full resource name (projects/*/locations/*/memberships/*)   Selecting membership [{}].r   )IsKnownAndSpecifiedr   MembershipLocationSpecifiedMembershipResourceNameSearchMembershipResourceMembershipRequiredErrorr   ListMembershipsFullr   r%   r&   lenr   rQ   rR   PromptForMembership)r?   prompt
autoselectsearchflag_overrideall_membershipsunreachabler   s           r   ParseMembershipr   '  s1   8 
l+t/G/G0 44]C,,T-:<CI--dMBB//
d< < 


!$
66!)!=!=!"#/;



2396+3FH H C(A-JJ1889KLM1..?Jm44r   c                 >   g }t        | d      rd| j                  rXt        j                  d      \  }}|r$t	        j
                  dj                  |            |st	        j
                  d      |S | j                  d      rt        j                  |       r|t        j                  |       z  }|r@|D ];  }	t        j                  |	      rt	        j
                  dj                  |	             |sYt        t        j                  |            dkD  r8t        t        j                  |            |t        j                  | d      z  }|r|S |s|st!        |       t        j                  d      \  }}|r$t	        j
                  d	j                  |            |rEt        |      dk(  r7t"        j$                  j'                  d
j                  |d                |d   gS |r+t        j(                  |      }	|	r|j+                  |	       |S t!        |       )aV  Parses a list of membership resources from args.

  Allows for a `--memberships` flag and a `--all-memberships` flag.

  Args:
    args: object containing arguments passed as flags with the command
    prompt: whether to prompt in console for a membership when none are provided
      in args
    prompt_cancel: whether to include a 'cancel' option in the prompt
    autoselect: if no memberships are provided and only one exists,
      automatically use that one
    allow_cross_project: whether to allow memberships from different projects
    search: whether to check that the membership exists in the fleet

  Returns:
    memberships: A list of membership resource name strings

  Raises:
    exceptions.Error if no memberships were found or memberships are invalid
    calliope_exceptions.RequiredArgumentException if membership was not provided
  r   Tr   zaLocations {} are currently unreachable. Please try again or specify memberships for this command.z&No Memberships available in the fleet.ry   z*Membership {} does not exist in the fleet.r   r   r   r   )cancel)hasattrr   r   r   r   r%   r&   r   r   r   PluralMembershipsResourceNamesGetMembershipr   GetMembershipProjectsCrossProjectErrorSearchMembershipResourcesPluralr   r   rQ   rR   r   append)
r?   r   prompt_cancelr   allow_cross_projectr   ry   r   r   r   s
             r   ParseMembershipsPluralr   a  s   6 + T$%$*>*>#+#?#?#$% O[228&2EG G EFF 
m,,,T2Y==dCCk	%J''
3""<CCJOQ Q &
 !S

)
)+
6&8:;&<	 ? ? LMM Y>>
t- -k  


!$
''!)!=!=!"#/;



2396+3FH H C(A-JJ1889KLMA..mDJ$%%r   c                  r   t        j                  dd      } | j                  j                  | j                  j                  t        j                  j                                     }|j                  D cg c]6  }t        |j                        st        j                  |j                        8 c}S c c}w )z}Lists Membership IDs in the fleet for the current project.

  Returns:
    A list of Membership resource IDs in the fleet.
  gkehubv1beta)rU   )	core_apisGetClientInstanceprojects_locations_membershipsListMESSAGES_MODULE-GkehubProjectsLocationsMembershipsListRequesthub_base
HubCommandrG   r   _ClusterMissingendpointr   MembershipShortnamer   )clientresponserz   s      r   ListMembershipsr     s     &&x:&2277JJ$$99; K =>( !!
!!QZZ( qvv&!
  
s   6;B4c                 J    t        j                  dj                  |             S )NzoMemberships for this command must belong to the same project and cannot mix project number and project ID ({}).)r   r%   r&   )projectss    r   r   r     s$    			 --3VH-=
? ?r   c                 d    |r|}n| j                  d      rd}nd}t        j                  |d      S )a	  Parses a list of membership resources from args.

  Assumes a `--memberships` flag or a `MEMBERSHIP_NAME` flag unless overridden.

  Args:
    args: argparse.Namespace arguments provided for the command
    flag_override: set to override the name of the membership flag

  Returns:
    memberships: A list of membership resource name strings

  Raises:
    exceptions.Error: if no memberships were found or memberships are invalid
    calliope_exceptions.RequiredArgumentException: if membership was not
      provided
  r   ry   z5At least one membership is required for this command.)r   calliope_exceptionsRequiredArgumentException)r?   r   flags      r   r   r     s@    " D 12DD		6	6
C
E Er   c                 \    dD ]'  }t        | |      st        t        | |      dd      c S  y )N)
gkeClustermultiCloudClusteronPremClusterclusterMissingF)r   getattr)rz   ts     r   r   r     s,    ?aq!}WQ]$4e<< @r   )FFFr   )FTFFF)r   )0r6   
__future__r   r   r   apitools.base.pyr   r/   &googlecloudsdk.api_lib.container.fleetr   googlecloudsdk.api_lib.servicesr   googlecloudsdk.api_lib.utilr	   r   rN   googlecloudsdk.callioper
   r   r   *googlecloudsdk.command_lib.container.fleetr   r   r   3googlecloudsdk.command_lib.container.fleet.featuresr   googlecloudsdk.corer   r   googlecloudsdk.core.utilr   r   r   r   r:   CreateCommandrd   rl   r   r   DeleteCommandr   r   r   r   r   r   r   rb   r   r   <module>r      s
   P &  ' > 7 6 9 I 9 E ? G @ D * # * * 
"-X(( "-J- -`0&(C(C 0Dnm&C&C DN "&(C(C A')D)D AJ !$ "$	75v #()-&+/4"'Q&l$?E6=r   