
    0                        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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rSrSrSrSrSrSrSrSrSrSr\S-   \-   S-   \-   rSrS r  S S jr! S S jr"S r#S r$g)!zUtils for GKE Hub commands.    )absolute_import)division)print_function)unicode_literals)api_util)	kube_util)util)
exceptions)log)
propertiesencoding)fileszgke-connect-agentzgke-connect-agent-installerz	creds-gcpzconnect-image-pull-secretzhub.gke.io/projectzgke-connecta  Manifest saved to [{0}]. Please apply the manifest to your cluster with `kubectl apply -f {0}`. You must have `cluster-admin` privilege in order to deploy the manifest.

**This file contains sensitive data; please treat it with the same discretion as your service account key file.**zapiVersion: v1
kind: Secret
metadata:
  name: {gcp_sa_key_secret_name}
  namespace: {namespace}
data:
  {gcp_sa_key_secret_name}.json: "{gcp_sa_key}"
zrapiVersion: v1
kind: Namespace
metadata:
  name: {namespace}
  labels:
    {connect_resource_label}: {project_id}
a#  apiVersion: v1
kind: ConfigMap
metadata:
  name: user-config
  namespace: {namespace}
data:
  project_id: "{project_id}"
  project_number: "{project_number}"
  membership_name: "{membership_name}"
  proxy: "{proxy}"
  image: "{image}"
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: {project_id}-gke-connect-agent-role-binding
  labels:
    {connect_resource_label}: {project_id}
subjects:
- kind: ServiceAccount
  name: default
  namespace: {namespace}
roleRef:
  kind: ClusterRole
  name: cluster-admin
  apiGroup: rbac.authorization.k8s.io
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {agent_install_deployment_name}
  namespace: {namespace}
  labels:
    app: {agent_install_app_label}
spec:
  selector:
    matchLabels:
      app: {agent_install_app_label}
  template:
    metadata:
      labels:
        app: {agent_install_app_label}
    spec:
      containers:
      - name: connect-agent-installer
        image: {image}
        command:
          - gkeconnect_bin/bin/gkeconnect_agent
          - --install
          - --sleep-after-install
          - --config
          - user-config
        imagePullPolicy: Always
        env:
        - name: MY_POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
---
zapiVersion: v1
kind: Secret
metadata:
  name: {name}
  namespace: {namespace}
  labels:
    {connect_resource_label}: {project_id}
data:
  .dockerconfigjson: {image_pull_secret}
type: kubernetes.io/dockerconfigjsonc                    [         R                  " U5      nU R                  [        R	                  U[
        UUSSSS[        [        [        S95      nU(       a,  SU;  a%  [        R                  " SR	                  U5      5      egg)a
  Purge the Alpha installation resources if exists.

Args:
  kube_client: Kubernetes client to operate on the cluster.
  namespace: the namespace of Alpha installation.
  project_id: the GCP project ID.

Raises:
  exceptions.Error: if Alpha resources deletion failed.
 )	namespaceconnect_resource_label
project_idproject_numbermembership_nameproxyimage
gcp_sa_keygcp_sa_key_secret_nameagent_install_deployment_nameagent_install_app_labelNotFoundz'failed to delete Alpha installation: {}N)p_utilGetProjectNumberDeleteINSTALL_ALPHA_TEMPLATEformatCONNECT_RESOURCE_LABELGCP_SA_KEY_SECRET_NAMEAGENT_INSTALL_DEPLOYMENT_NAMEAGENT_INSTALL_APP_LABELr
   Error)kube_clientr   r   r   errs        <lib/googlecloudsdk/command_lib/container/fleet/agent_util.py_PurgeAlphaInstallerr,      s     **:6.1883#3$A5 9  		# 	FMM
    	    Nc                 6   SnSn[         R                  " UUU[        U R                  U R                  U R
                  US9nUR                   H  n	XyR                  -   U-   nM     U[        R                  [        [        [        R                  " USS9S9-   nU$ )ay  Generate the manifest for connect agent from API.

Args:
  args: arguments of the command.
  service_account_key_data: The contents of a Google IAM service account JSON
    file.
  image_pull_secret_data: The image pull secret content to use for private
    registries.
  upgrade: if this is an upgrade operation.
  membership_ref: The membership associated with the connect agent in the
    format of `projects/[PROJECT]/locations/global/memberships/[MEMBERSHIP]`
  release_track: the release_track used in the gcloud command,
    or None if it is not available.

Returns:
  The full manifest to deploy the connect agent resources.
r   r   )image_pull_secret_content
is_upgrader   r   registryversionrelease_trackutf8r   )r   r   r   )r   GenerateConnectAgentManifestDEFAULT_NAMESPACEr   docker_registryr2   manifestCREDENTIAL_SECRET_TEMPLATEr#   r%   r   Decode)
argsservice_account_key_dataimage_pull_secret_dataupgrademembership_refr3   	delimiterfull_manifestmanifest_resourcesresources
             r+   _GenerateManifestrD      s    & )-
  << 6!JJ##ll!# %--h!$5$55	AM .  "<"C"C!3!9FK #D #M M- 
r-   c                    [         R                  R                  R                  R	                  5       n[
        R                  R                  S5        [        UUUSXE5      nUR                  (       ar   [        R                  " [        R                  " UR                  5      USS9  [
        R                  R                  [         R                  UR                  5      5        g[#        X5      n	[%        U	5      S:  a/  [        R                  " SR                  XR&                  5      5      eU	S	   n
[
        R                  R                  S
R                  UR&                  U
5      5        [(        R*                  " X
5        [-        X
U5        U R/                  U5      u  pU(       a%  [        R                  " SR                  U5      5      e[
        R                  R                  SR                  UR&                  U
5      5        g! [        R                   a*  n[        R                  " SR                  U5      5      eSnAff = f)a  Deploys the Connect Agent to the cluster.

Args:
  kube_client: A Kubernetes Client for the cluster to be registered.
  args: arguments of the command.
  service_account_key_data: The contents of a Google IAM service account JSON
    file
  image_pull_secret_data: The contents of image pull secret to use for
    private registries.
  membership_ref: The membership should be associated with the connect agent
    in the format of
    `project/[PROJECT]/location/global/memberships/[MEMBERSHIP]`.
  release_track: the release_track used in the gcloud command,
    or None if it is not available.
Raises:
  exceptions.Error: If the agent cannot be deployed properly
  calliope_exceptions.MinimumArgumentException: If the agent cannot be
  deployed properly
z(Generating the Connect Agent manifest...FT)privatez"Could not create manifest file: {}N   zmMultiple namespaces [{}] containing the Connect Agent found incluster [{}]. Cannot deploy a new Connect Agentr   z@Deploying the Connect Agent on cluster [{}] in namespace [{}]...z'Failed to apply manifest to cluster: {}z=Deployed the Connect Agent on cluster [{}] in namespace [{}].)r   VALUEScoreproject	GetOrFailr   statusPrintrD   manifest_output_filer   WriteFileContentsExpandHomeDirr(   r
   r#   MANIFEST_SAVED_MESSAGE_GKEConnectNamespacelenMEMBERSHIP_NAMEr   DeleteNamespacer,   Apply)r)   r;   r<   r=   r?   r3   r   rA   e
namespacesr   _r*   s                r+   DeployConnectAgentrZ      s   .   %%--779***=>#D$<$:$)$2	C- 
M


d77
8
 JJ+2243L3LMN
#K<*_q


	::@&,,;./ / m)**Hvd""I.0 K3{z:]+&!


188=? ? **Evd""I.07 ;; MAHHKLLMs   34H I%H??Ic                    [        U [        R                  R                  R                  R                  5       5      n[        U5      S:  a1  [        R                  " SR                  UR                  U5      5        gUS   nSR                  U5      n [        R                  " X5        g! [        R                   a    [        R                  " U5         gf = f)a  Delete the namespace in the cluster that contains the connect agent.

Args:
  kube_client: A Kubernetes Client for the cluster to be registered.
  args: an argparse namespace. All arguments that were provided to this
    command invocation.

Raises:
  calliope_exceptions.MinimumArgumentException: if a kubeconfig file cannot
    be deduced from the command line flags or environment
rG   zgcloud will not remove any namespaces containing the Connect Agent since it was found running in multiple namespaces on cluster: [{}]. Please delete these namespaces [{}] maually in your clusterNr   z6Please delete namespace [{}] manually in your cluster.)rR   r   rH   rI   rJ   rK   rS   r   warningr#   rT   r   rU   r
   r(   )r)   r;   rX   r   cleanup_msgs        r+   DeleteConnectNamespacer^   =  s     $K$.$5$5$:$:$B$B$L$L$NP* 	_qKK	G 
$$j	1	3
 m)HOO+k5			 KKs   B+ +*CCc                 p    SR                  [        U5      nU R                  U5      nU(       d  [        /$ U$ )a  Returns the namespaces into which to install or update the connect agent.

Connect namespaces are identified by the presence of the hub.gke.io/project
label. If there are existing namespaces with this label in the cluster,
then a list of all those namespaces is returned; otherwise, a list with the
default connect namespace is returned.

Args:
  kube_client: a KubernetesClient.
  project_id: A GCP project identifier.

Returns:
  List of namespaces with hub.gke.io/project label.
z{}={})r#   r$   NamespacesWithLabelSelectorr6   )r)   r   selectorrX   s       r+   rR   rR   _  s7     ^^2J?(66x@*		r-   )N)%__doc__
__future__r   r   r   r   *googlecloudsdk.command_lib.container.fleetr   r   #googlecloudsdk.command_lib.projectsr	   r   googlecloudsdk.corer
   r   r   googlecloudsdk.core.utilr   r   %RUNTIME_CONNECT_AGENT_DEPLOYMENT_NAMEr'   r&   r%   IMAGE_PULL_SECRET_NAMEr$   r6   rQ   r9   NAMESPACE_TEMPLATEr"   INSTALL_MANIFEST_TEMPLATEIMAGE_PULL_SECRET_TEMPLATEr,   rD   rZ   r^   rR    r-   r+   <module>rn      s    " &  % ' ? @ > * # * - * )< % 8  !> 
 %  5 - ! '   ; H / 2  !$ 	 
( @ >B+b 6:D0NDr-   