
    0                     
   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ZdZdZdZdZdZdZdZdZdZdZedz   ez   dz   ez   ZdZd Z 	 d dZ!	 d dZ"d Z#d Z$y)!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                    t        j                  |      }| j                  t        j	                  |t
        ||ddddt        t        t                    }|r)d|vr$t        j                  dj	                  |            yy)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           
      B   d}d}t        j                  |||t        | j                  | j                  | j
                  |      }|j                  D ]  }	||	j                  z   |z   } |t        j                  t        t        t        j                  |d            z   }|S )a  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!H$5$55	AM .  "<"C"C!3!9FK #D #M M- 
r-   c                 |   t         j                  j                  j                  j	                         }t
        j                  j                  d       t        |||d||      }|j                  rs	 t        j                  t        j                  |j                        |d       t
        j                  j                  t         j                  |j                               yt#        | |      }	t%        |	      dkD  r/t        j                  dj                  |	|j&                              |	d	   }
t
        j                  j                  d
j                  |j&                  |
             t)        j*                  | |
       t-        | |
|       | j/                  |      \  }}|r$t        j                  dj                  |            t
        j                  j                  dj                  |j&                  |
             y# t        j                  $ r)}t        j                  dj                  |            d}~ww xY w)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$<$:$)$2M	C- 
M


d77
8
 JJ+2243L3LMN
#K<*_q


	::@&,,;./ / m)**Hvd""I.0 K3{Iz:]+&!S


188=? ? **Evd""I.07 ;; MAHHKLLMs   /5G? ?H;$H66H;c                    t        | t        j                  j                  j                  j                               }t        |      dkD  r0t        j                  dj                  |j                  |             y|d   }dj                  |      }	 t        j                  | |       y# t        j                  $ r t        j                  |       Y yw xY w)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+k95			 KKs   B) )(CCc                 f    dj                  t        |      }| j                  |      }|st        gS |S )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-   