
    O                     |   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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 ej2                  d      Zd Zd Zd Zd Z	 	 	 	 	 	 	 	 	 d dZ	 	 	 	 	 	 	 d!dZ d"dZ!d"dZ"d Z#d"dZ$	 d"dZ%	 d"dZ&	 	 	 	 	 	 	 d!dZ'd#dZ(d Z)d Z*y)$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                  X    t        j                  d      } t        j                  d|       S )Ncompute)	core_apisResolveVersionGetClientInstance)api_versions    :lib/googlecloudsdk/command_lib/container/fleet/api_util.py_ComputeClientr   &   s%    ((3+		$	$Y	<<    c                  .    t        j                  dd      S )Nstoragev1)r   r    r   r   _StorageClientr   +   s    		$	$Y	55r   c                 :    dj                  t        | |      |      S )a^  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     
	#	#Igx$@-	PPr   c                 &    dj                  | |      S )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     
$	*	*7H	==r   c                    t        j                  |      }|j                  }|j                  || |      }|	rj|j	                  |	      |j
                  _        |
r+|
j                  d      |j
                  j                  _        n-d|j
                  j                  _        nd|j
                  _        |r|j                  |      }|j                  |      }|j                  |      }|j
                  j                  r|j
                  j                  j                  r|j
                  j                  j                  j                  r0||j
                  j                  j                  j                  _        nS||j
                  j                  j                  _        n-||j
                  j                  _        n||j
                  _        |r||j
                  _        |dk(  r0|j"                  j$                  j&                  |j
                  _        n4|d	k(  r/|j"                  j$                  j*                  |j
                  _        |s|s|r i }|sS|j,                  rG|j,                  j.                  D ].  }t1        j2                  |j4                        ||j6                  <   0 |r+t9        t1        j:                  |            D ]
  \  }}|||<    |r|D ]  }||v s|j=                  |        |j"                  j?                         }t9        t1        j:                  |            D ]1  \  }}|j.                  jA                  |jC                  ||
             3 ||j
                  _        |jD                  jG                  |      }tH        jJ                  jM                  djO                  |              |r:tH        jJ                  jM                  djO                  |jP                               |S tR        jT                  jW                  |jP                  d      }tY        jZ                  tY        j\                  |jD                  |j^                        |djO                  |jP                              S )a0  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!$/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   t        j                  |      }	|	j                  }
t        | |      }|
j	                  |
j                         ||      }|r4|
j                  |
j                  |            }||j                  _	        nI|rG|
j                  |      }|
j                  |      }|
j                  |      }||j                  _	        |r||j                  _        |rM|
j                  |      |j                  _        |r*|j                  d      |j                  j                  _        |	j"                  j%                  |      }t&        j(                  j+                  |j,                  d	
      }t/        j0                  t/        j2                  |	j"                  |	j4                        |d      S )aT  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"*G !11=O1P$77* 8 ,,,0 - 2h$,g!$/G!#+#5#5Z#5#HG .7.>.>w.Gg""+,,33G<"""44gg@ 5 B+	!!&"G"G"("F"FH9
; ;r   c                     t         j                  |       t        |       t        j                  |      }|j
                  j                  |j                  j                  |             S )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                 0   t        j                  |      }|D ]|  }|sdj                  |      }|j                  j	                  |j
                  j                  |            }|j                  D ]"  }t        |j                        }|| k(  s|c c S  ~ y)ay  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-44W=f"AAFF

 
 
N
N O  ,55*7
Hd". 6  
r   c                 h    t         j                  |       }t        |      dk7  rt        |       |d   S )aH  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                 V   t        j                  |      }|j                  j                  |j                  j                  |             }t        j                  j                  |j                  d      }t        j                  t        j                  |j                        |d       y)ac  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                     t         j                  j                  }t        j                  |      }|j
                  j                  |j                  j                  || |            S )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                     t         j                  j                  }t        j                  |      }|j
                  j                  |j                  j                  || |            S )a6  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                 F   t        j                  |      }|j                  }	|	j                  |       }
|r|j	                  d      |
_        |r||
_        |r||
_        |r|j	                  d      |
_        |r||
_	        |r||
_
        |j                  j                  |
      S )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""G!G
LL)GMGGO		.	.	F	Fw	OOr   c                    t        j                  dd      }|j                  j                  t        j
                  j                  d            }t               fd}t        j                  |j                  |dd|	      }| r0|D cg c]$  }t        |j                        r|j                  & }}n|D cg c]  }|j                   }}|t              fS c c}w c c}w )
aX  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                 R    j                  | j                         t        | |      S N)updateunreachablegetattr)message	attributer   s     r   _GetFieldFuncz*ListMembershipsFull.<locals>._GetFieldFunc  s$    w**+7I&&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   $**6a1666K*	d;'	'' +s   C&C;C"c                 \    dD ]'  }t        | |      st        t        | |      dd      c S  y )N)rv   multiCloudClusteronPremClusterclusterMissingF)hasattrr   )r   ts     r   r   r     s,    ?aq!}WQ]$4e<< @r   c                 J    t        j                  dj                  |             S )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   