
    O                        S 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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\R2                  " S5      rS rS rS rS r         S S jr       S!S jr S"S jr!S"S jr"S r#S"S jr$ S"S jr% S"S jr&       S!S jr'S#S jr(S r)S r*g)$z3Util functions using GKEHub API for fleet commands.    )absolute_import)division)print_function)unicode_literalsN)
list_pager)gkehub_api_util)apis)waiter)base)
exceptions)log)	resourcesz'projects/.+/locations/.+/memberships/.+c                  \    [         R                  " S5      n [         R                  " SU 5      $ )Ncompute)	core_apisResolveVersionGetClientInstance)api_versions    :lib/googlecloudsdk/command_lib/container/fleet/api_util.py_ComputeClientr   &   s%    ((3+		$	$Y	<<    c                  0    [         R                  " SS5      $ )Nstoragev1)r   r    r   r   _StorageClientr   +   s    		$	$Y	55r   c                 8    SR                  [        X5      U5      $ )aN  Get the resource name of a membership.

Args:
  project: the project in which to create the membership
  location: the GCP region of the membership.
  membership_id: the ID of the membership.

Returns:
  the full resource name of the membership in the format of
  `projects/{project}/locations/{location}/memberships/{membership_id}`
z{}/memberships/{})format	ParentRef)projectlocationmembership_ids      r   MembershipRefr#   /   s     
	#	#Ig$@-	PPr   c                 $    SR                  X5      $ )a  Get the resource name of the parent collection of a membership.

Args:
  project: the project of the parent collection.
  location: the GCP region of the membership.

Returns:
  the resource name of the parent collection in the format of
  `projects/{project}/locations/{location}`.
zprojects/{}/locations/{})r   )r    r!   s     r   r   r   ?   s     
$	*	*7	==r   c                 	   [         R                  " U5      nUR                  nUR                  XUS9nU	(       al  UR	                  U	S9UR
                  l        U
(       a+  U
R                  S5      UR
                  R                  l        O-SUR
                  R                  l        OSUR
                  l        U(       Ga  UR                  US9nUR                  US9nUR                  US9nUR
                  R                  (       a  UR
                  R                  R                  (       a  UR
                  R                  R                  R                  (       a/  XR
                  R                  R                  R                  l        OSUUR
                  R                  R                  l        O-UUR
                  R                  l        OUUR
                  l        U(       a  XOR
                  l        US:X  a0  UR"                  R$                  R&                  UR
                  l        O5US	:X  a/  UR"                  R$                  R*                  UR
                  l        U(       d  U(       d  U(       Ga?  0 nU(       d[  UR,                  (       aJ  UR,                  R.                   H0  n[0        R2                  " UR4                  5      UUR6                  '   M2     U(       a.  [9        [0        R:                  " U5      5       H  u  nnUUU'   M     U(       a"  U H  nUU;   d  M  UR=                  U5        M     UR"                  R?                  5       n[9        [0        R:                  " U5      5       H/  u  nnUR.                  RA                  URC                  UUS
95        M1     UUR
                  l        URD                  RG                  U5      n[H        RJ                  RM                  SRO                  U 5      5        U(       a:  [H        RJ                  RM                  SRO                  URP                  5      5        U$ [R        RT                  RW                  URP                  SS9n[X        RZ                  " [X        R\                  " URD                  UR^                  5      USRO                  URP                  5      5      $ )a  UpdateMembership updates membership resource in the GKE Hub API.

Args:
  name: The full resource name of the membership to update, e.g.
    projects/foo/locations/global/memberships/name.
  membership: Membership resource that needs to be updated.
  update_mask: Field names of membership resource to be updated.
  release_track: The release_track used in the gcloud command.
  external_id: the unique id associated with the cluster, or None if it is not
    available.
  infra_type: The infrastructure type that the cluster is running on
  clear_labels: Whether labels should be cleared
  update_labels: Labels to be updated,
  remove_labels: Labels to be removed,
  issuer_url: The discovery URL for the cluster's service account token
    issuer.
  oidc_jwks: The JSON Web Key Set string containing public keys for validating
    service account tokens. Set to None if the issuer_url is
    publicly-reachable. Still requires issuer_url to be set.
  api_server_version: api_server_version of the cluster
  async_flag: Whether to return the update operation instead of polling

Returns:
  The updated Membership resource or the update operation if async.

Raises:
  - apitools.base.py.HttpError: if the request returns an HTTP error
  - exceptions raised by waiter.WaitFor()
)
membershipname
updateMaskissuerutf-8N
k8sVersionresourceOptionskubernetesResourcezon-premzmulti-cloud)keyvaluezrequest issued for: [{}]z Check operation [{}] for status.$gkehub.projects.locations.operations
collectionz&Waiting for operation [{}] to complete)0r   GetApiClientForTrackMESSAGES_MODULE.GkehubProjectsLocationsMembershipsPatchRequest	Authorityr&   	authorityencodeoidcJwksResourceOptionsKubernetesResourceMembershipEndpointendpointr1   r/   r-   
externalId
Membership!InfrastructureTypeValueValuesEnumON_PREMinfrastructureTypeMULTI_CLOUDlabelsadditionalPropertiessix	text_typer3   r2   sorted	iteritemspopLabelsValueappendAdditionalPropertyprojects_locations_membershipsPatchr   statusPrintr   r'   r   REGISTRYParseRelativeNamer
   WaitForCloudOperationPollerprojects_locations_operations)r'   r&   update_maskrelease_trackexternal_id
infra_typeclear_labelsupdate_labelsremove_labels
issuer_url	oidc_jwksapi_server_version
async_flagclientmessagesrequestresource_optionskubernetes_resourcerA   
mem_labelsitemkvrH   opop_resources                             r   UpdateMembershiprq   N   s   V //>&##(CC; D @' #+#5#5Z#5#HG .7.>.>w.Gg""+ /3g""+#'G  //;M/N"55( 6 ***. + 0H""				$	$	7	7&&99IIVh


%
%
8
8
H
H
SK['


%
%
8
8
H9L##6$,g!$/!9,4,?,?,a,a,i,iG)]",4,?,?,a,a,m,mG)]mJJ--##88$"}}TZZ8
488 9}56$!Q
1 7!
?
..
    ,,.Fs}}Z011!!((

#
#
#
35 2 !'G,,227;"**-44T:;JJ7>>rwwGHI""44gg@ 5 B+	!!&"G"G"("F"FH;BB277K
M Mr   c	                 l   [         R                  " U5      n	U	R                  n
[        X5      nU
R	                  U
R                  5       UUS9nU(       a-  U
R                  U
R                  US9S9nXR                  l	        ODU(       a=  U
R                  US9nU
R                  US9nU
R                  US9nXR                  l	        U(       a  XLR                  l        U(       aO  U
R                  US9UR                  l        U(       a*  UR                  S5      UR                  R                  l        U	R"                  R%                  U5      n[&        R(                  R+                  UR,                  S	S
9n[.        R0                  " [.        R2                  " U	R"                  U	R4                  5      US5      $ )a(  Creates a Membership resource in the GKE Hub API.

Args:
  project: the project in which to create the membership
  membership_id: the value to use for the membership_id
  location: the location for the membership
  gke_cluster_self_link: the selfLink for the cluster if it is a GKE cluster,
    or None if it is not
  external_id: the unique id associated with the cluster, or None if it is not
    available.
  release_track: the release_track used in the gcloud command, or None if it
    is not available.
  issuer_url: the discovery URL for the cluster's service account token
    issuer. Set to None to skip enabling Workload Identity.
  oidc_jwks: the JSON Web Key Set containing public keys for validating
    service account tokens. Set to None if the issuer_url is
    publicly-routable. Still requires issuer_url to be set.
  api_server_version: api server version of the cluster for CRD

Returns:
  the created Membership resource.

Raises:
  - apitools.base.py.HttpError: if the request returns an HTTP error
  - exceptions raised by waiter.WaitFor()
)r&   parentmembershipId)resourceLink)
gkeClusterr,   r.   r0   r)   r+   r4   r5   z$Waiting for membership to be created)r   r7   r8   r   /GkehubProjectsLocationsMembershipsCreateRequestrC   r@   
GkeClusterr&   rA   r>   r?   rB   r:   r;   r<   r=   rR   Creater   rV   rW   r'   r
   rX   rY   rZ   )r    r"   r!   gke_cluster_self_linkr]   r\   rb   rc   rd   rf   rg   
parent_refrh   rA   ri   rj   ro   rp   s                     r   CreateMembershipr|      s   F //>&##(+*DD$$&  E '
 **&&4I&J + LH"* !11=O1P$77* 8 ,,,0 - 2h$,!$/!#+#5#5Z#5#HG .7.>.>w.Gg""+,,33G<"""44gg@ 5 B+	!!&"G"G"("F"FH9
; ;r   c                     [         R                  U 5      c  [        U 5      e[        R                  " U5      nUR
                  R                  UR                  R                  U S95      $ )a  Gets a Membership resource from the GKE Hub API.

Args:
  name: the full resource name of the membership to get, e.g.,
    projects/foo/locations/global/memberships/name.
  release_track: the release_track used in the gcloud command, or None if it
    is not available.

Returns:
  a Membership resource

Raises:
  apitools.base.py.HttpError: if the request returns an HTTP error
  exceptions.Error: if the membership name is missing the ID or improperly
    formatted
r'   )	_MEMBERSHIP_REmatchInvalidMembershipFormatErrorr   r7   rR   Getr8   ,GkehubProjectsLocationsMembershipsGetRequest)r'   r\   rf   s      r   GetMembershipr     sf    $ $'
&t
,,//>&		.	.	2	2II J 
 r   c                 @   [         R                  " U5      nU H  nU(       d  M  SR                  U5      nUR                  R	                  UR
                  R                  US95      nUR                   H#  n[        UR                  5      nX:X  d  M  Us  s  $    M     g)ae  Retrieves the project that the cluster UUID has a Membership with.

Args:
  uuid: the UUID of the cluster.
  projects: sequence of project IDs to consider.
  release_track: the release_track used in the gcloud command, or None if it
    is not available.

Returns:
  a project ID.

Raises:
  apitools.base.py.HttpError: if any request returns an HTTP error
zprojects/{}/locations/globalrs   N)
r   r7   r   rR   Listr8   -GkehubProjectsLocationsMembershipsListRequestr   _ClusterUUIDForMembershipNamer'   )	uuidprojectsr\   rf   r    rs   membership_responser&   membership_uuids	            r   ProjectForClusterUUIDr   %  s     //>&gw-44W=f"AAFF

 
 
N
N O  ,55*7
H". 6  
r   c                 j    [         R                  U 5      n[        U5      S:w  a  [        U 5      eUS   $ )a8  Extracts the cluster UUID from the Membership resource name.

Args:
  membership_name: the full resource name of a membership, e.g.,
    projects/foo/locations/global/memberships/name.

Returns:
  the name in the membership resource, a cluster UUID.

Raises:
  exceptions.Error: if the membership was malformed.
   r   )r   findalllenr   )membership_namematchess     r   r   r   B  s5     ""?3'\Q
&
77	r   c                 P   [         R                  " U5      nUR                  R                  UR                  R                  U S95      n[        R                  R                  UR                  SS9n[        R                  " [        R                  " UR                  5      US5        g)aS  Deletes a membership from the GKE Hub.

Args:
  name: the full resource name of the membership to delete, e.g.,
    projects/foo/locations/global/memberships/name.
  release_track: the release_track used in the gcloud command, or None if it
    is not available.

Raises:
  apitools.base.py.HttpError: if the request returns an HTTP error
r~   r4   r5   z$Waiting for membership to be deletedN)r   r7   rR   Deleter8   /GkehubProjectsLocationsMembershipsDeleteRequestr   rV   rW   r'   r
   rX   CloudOperationPollerNoResourcesrZ   )r'   r\   rf   ro   rp   s        r   DeleteMembershipr   W  s     //>&,,33LL M " ""44gg@ 5 B+..,,

.
.01<,.r   c                     [         R                  R                  n[        R                  " U5      nUR
                  R                  UR                  R                  UU US95      $ )a  Validate the exclusivity state of the cluster.

Args:
  cr_manifest: the YAML manifest of the Membership CR fetched from the
    cluster.
  parent_ref: the parent collection that the cluster is to be registered to.
  intended_membership: the ID of the membership to be created.
  release_track: the release_track used in the gcloud command, or None if it
    is not available.

Returns:
  the ValidateExclusivityResponse from API.

Raises:
  apitools.base.py.HttpError: if the request returns an HTTP error.
)rs   
crManifestintendedMembership)	calliope_baseReleaseTrackALPHAr   r7   rR   ValidateExclusivityr8   <GkehubProjectsLocationsMembershipsValidateExclusivityRequest)cr_manifestr{   intended_membershipr\   rf   s        r   r   r   p  sa    *  ,,22-//>&		.	.	B	BCC 0 D 2
3 3r   c                     [         R                  R                  n[        R                  " U5      nUR
                  R                  UR                  R                  X US95      $ )a  Generate the CR(D) manifests to apply to the registered cluster.

Args:
  crd_manifest: the YAML manifest of the Membership CRD fetched from the
    cluster.
  cr_manifest: the YAML manifest of the Membership CR fetched from the
    cluster.
  membership_ref: the full resource name of the membership.
  release_track: the release_track used in the gcloud command, or None if it
    is not available.

Returns:
  the GenerateExclusivityManifestResponse from API.

Raises:
  apitools.base.py.HttpError: if the request returns an HTTP error.
)r'   crdManifestr   )	r   r   r   r   r7   rR   GenerateExclusivityManifestr8   DGkehubProjectsLocationsMembershipsGenerateExclusivityManifestRequest)crd_manifestr   membership_refr\   rf   s        r   r   r     s^    ,  ,,22-//>&		.	.	J	JKK  L "
# #r   c                 v   [         R                  " U5      nUR                  n	U	R                  U S9n
U(       a  UR	                  S5      U
l        U(       a  X*l        U(       a  X:l        U(       a  UR	                  S5      U
l        U(       a  XZl	        U(       a  Xjl
        UR                  R                  U
5      $ )a  Generated the Connect Agent to apply to the registered cluster.

Args:
  membership_ref: the full resource name of the membership.
  image_pull_secret_content: The image pull secret content to use for private
    registries or None if it is not available.
  is_upgrade: Is this is an upgrade operation, or None if it is not available.
  namespace: The namespace of the Connect Agent, or None if it is not
    available.
  proxy: The proxy address or None if it is not available.
  registry: The registry to pull the Connect Agent image if not using
    gcr.io/gkeconnect, or None if it is not available.
  version: The version of the Connect Agent to install/upgrade, or None if it
    is not available.
  release_track: the release_track used in the gcloud command, or None if it
    is not available.

Returns:
  the GenerateConnectManifest from API.

Raises:
  apitools.base.py.HttpError: if the request returns an HTTP error.
r~   r+   ascii)r   r7   r8   @GkehubProjectsLocationsMembershipsGenerateConnectManifestRequestr<   imagePullSecretContent	isUpgrade	namespaceproxyregistryversionrR   GenerateConnectManifest)r   image_pull_secret_content
is_upgrader   r   r   r   r\   rf   rg   rh   s              r   GenerateConnectAgentManifestr     s    @ //>&##(UU V ' %>%E%Eg%NG""!
LL)GMO		.	.	F	Fw	OOr   c                   ^ [         R                  " SS5      nUR                  R                  [        R
                  R                  SS9S9n[        5       mU4S jn[        R                  " UR                  USSUS	9nU (       a9  U Vs/ s H+  n[        UR                  5      (       a  M  UR                  PM-     nnOU Vs/ s H  oUR                  PM     nnU[        T5      4$ s  snf s  snf )
aH  Lists full Membership names in the fleet for the current project.

Args:
  filter_cluster_missing: whether to filter out memberships that are missing
  a cluster.
Returns:
  A list of full membership resource names in the fleet in the form
  'projects/*/locations/*/memberships/*'.
  A list of locations which were unreachable.
gkehubv1beta-)r!   r   c                 P   > TR                  U R                  5        [        X5      $ N)updateunreachablegetattr)message	attributer   s     r   _GetFieldFunc*ListMembershipsFull.<locals>._GetFieldFunc  s"    w**+7&&r   r   N)fieldbatch_size_attributeget_field_func)r   r   r8   r   hub_base
HubCommandLocationResourceNamesetr   YieldFromListrR   _ClusterMissingrA   r'   list)filter_cluster_missingrf   reqr   resultmmembershipsr   s          @r   ListMembershipsFullr     s     &&x:&LL  55s5C 	M 	# +' ##++	"& 1oajj&A  K $**6a666K*	d;'	'' +s   
C',C'C,c                 f    S H+  n[        X5      (       d  M  [        [        X5      SS5      s  $    g )N)rv   multiCloudClusteronPremClusterclusterMissingF)hasattrr   )r   ts     r   r   r     s*    ?aq}}WQ]$4e<< @r   c                 L    [         R                  " SR                  U 5      5      $ )zReturns error for invalid membership resource names.

Args:
  name: The membership resource name.

Returns:
 An exceptions.Error for malformed membership names.
zsFailed to get membership: {} does not match format projects/PROJECT_ID/locations/LOCATION/memberships/MEMBERSHIP_ID)r   Errorr   r~   s    r   r   r     s&     
		Jt
 r   )	NNFNNNNNF)NNNNNNNr   )F)+__doc__
__future__r   r   r   r   reapitools.base.pyr   &googlecloudsdk.api_lib.container.fleetr   googlecloudsdk.api_lib.utilr	   r   r
   googlecloudsdk.callioper   r   *googlecloudsdk.command_lib.container.fleetr   googlecloudsdk.corer   r   r   rJ   compiler   r   r   r#   r   rq   r|   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>r      s    : &  % ' 	 ' B 9 . 9 G * # ) 
EF=
6Q >& "& $"'#'#' $#(, %qMl #+/!%#' $#(,F;R4:*.8 '+3D /3#@ <@,0+/'+*.)-/31Pn#(L=r   