
    \)                     d   d Z ddlmZ ddlmZ ddlmZ ddlmZ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Z(dZ)dgZ*g dZ+ G d dejX                  ejZ                        Z.d Z/y)z7Utilities for interacting with the Connect Gateway API.    )absolute_import)division)unicode_literals)ListUnion)projects_api)util)client)
enable_api)apis)base)api_util)gwkubeconfig_util)	overrides)errors)log)
properties)	platformsz0connectgateway_{project}_{location}_{membership}zihttps://{service_name}/{version}/projects/{project_number}/locations/{location}/{collection}/{membership}gkehub.gateway.get)zgkehub.memberships.getr   zserviceusage.services.getc                   ~    e Zd ZdZddZ	 	 ddedededeedf   fdZdd	Z	d
ede
e   fdZd Z	 ddZed        Zy)GetCredentialsCommandzeGetCredentialsCommand is a base class with util functions for Gateway credential generating commands.Nc                 l   t        j                          t        j                  j	                         }t
        j                  j                  d       t
        j                  j                  d|z          | j                  |t               	 t        j                  j                  j                  d      j                         }t!        |t#        j$                  |d              | j'                  |||      }d}|dk(  rn:t)        |d      r.t)        |j*                  d      r|j*                  j,                  rd}| j/                  t#        j$                  ||      |||||       d	| j1                  ||||      z   d
z   }t
        j                  j                  |       y # t        j                  $ r d }Y w xY w)Nz'Starting to build Gateway kubeconfig...zCurrent project_id: gkehubmembershipszgkeconnect-proberendpoint
gkeClustergkeMembershipsA new kubeconfig entry "4" has been generated and set as the current context.)container_utilCheckKubectlInstalledhub_base
HubCommandProjectr   statusPrintRunIamCheckREQUIRED_CLIENT_PERMISSIONSr   VALUESapi_endpoint_overridesPropertyGetNoSuchPropertyErrorCheckGatewayApiEnablementr	   GetConnectGatewayServiceNameReadClusterMembershiphasattrr   r   GenerateKubeconfigKubeContext)	selfmembership_idarg_locationarg_namespace
project_idhub_endpoint_override
membership
collectionmsgs	            9lib/googlecloudsdk/command_lib/container/fleet/gateway.pyRunGetCredentialsz'GetCredentialsCommand.RunGetCredentials9   s   ((*$$,,.JJJ>?JJ+j89Z!<=#(//FFOO
  ))*?F
 ++L-J J ((

J'J''6**#j))*?N 	#


m]
	
 A		A  JJSU )) #"#s   7F F32F3r5   r6   force_use_agentr7   c           	      
   t         j                  j                  d       t        j                          t
        j                  j                         }t
        j                  j                  d      }| j                  |t               d}t        j                  j                         r#t        j                  | j                               }t!        j"                  |      5  t%        j&                  | j                               }|j)                  d| d| d| |||      }	ddd       t*        j,                  j/                  	j0                        }
t*        j,                  j3                         }|j5                  |
d	       |j7                  t9        |
j:                  j=                               d
          |j?                          d|j@                   d}t         j                  j                  |       y# 1 sw Y   xY w)a  RunServerSide generates credentials using server-side kubeconfig generation.

    Args:
      membership_id: The short name of the membership to generate credentials
        for.
      arg_location: The location of the membership to generate credentials for.
      force_use_agent: Whether to force the use of Connect Agent in generated
        credentials.
      arg_namespace: The namespace to use in the kubeconfig context.
    zFetching Gateway kubeconfig...T)numberNz	projects/z/locations/z/memberships/)namer?   kubernetes_namespaceoperating_system)	overwriter   r   r   )!r   r%   r&   r    r!   r"   r#   r$   r'   REQUIRED_SERVER_PERMISSIONSr   OperatingSystem	IsWindowsgateway_utilWindowsOperatingSystemReleaseTrackr   RegionalGatewayEndpointgateway_clientGatewayClientGenerateCredentialskconfig
KubeconfigLoadFromBytes
kubeconfigDefaultMergeSetCurrentContextlistcontextskeys
SaveToFilecurrent_context)r4   r5   r6   r?   r7   r8   project_numberrD   r
   respnewrS   r<   s                r=   RunServerSidez#GetCredentialsCommand.RunServerSideq   s   " JJ56((*$$,,.J((000=N
 	Z!<=  **,%<<



 
	*	*<	8++D,=,=,?@f''>*+l^=Q^P_`),+	 ( d 
9 


*
*4??
;C##++-JSD)  cll&7&7&9!:1!=> #:#=#="> ?5 	5  JJS) 
9	8s    AG99Hc                 J    t         j                  |||      }|r|d|z   z  }|S )N)projectlocationr:   z_ns-)KUBECONTEXT_FORMATformat)r4   r8   rb   r:   	namespacekcs         r=   r3   z!GetCredentialsCommand.KubeContext   s7    		"	"X* 
# 
B FYbI    r8   permissionsc                     t        j                  |      }t        j                  ||      }|j                  }t        |      j                  t        |            st        j                         y)z^Run an IAM check, making sure the caller has the necessary permissions to use the Gateway API.N)	project_utilParseProjectr   TestIamPermissionsrh   setissubsetmemberships_errorsInsufficientPermissionsError)r4   r8   rh   project_refresultgranted_permissionss         r=   r'   z!GetCredentialsCommand.RunIamCheck   s]    ++J7K,,[+FF ,,{$$S)<%=>;;== ?rg   c                 Z    t        j                  |||      }t        j                  |      S N)hubapi_utilMembershipRefGetMembership)r4   r8   rb   r:   resource_names        r=   r0   z+GetCredentialsCommand.ReadClusterMembership   s'    --j(JOM$$]33rg   c                 D   t        j                  |      }|||t        j                  || j	                         ||||      dd}ddi}	i }
| j                  ||||      }| j                  |||      }t        j                  j                         }t        j                  ||||      |j                  |<   t        j                  |fi |	|j                  |<   t        j                  ||d   fi |
|j                  |<   |j                  |       |j!                          |S )N)service_nameversionr\   rb   r;   r:   gcp)r:   rb   r8   serverauth_providerr   r~   )rj   GetProjectNumberSERVER_FORMATrd   
GetVersionr3   rP   rQ   rT   ContextrX   UserusersClusterclustersrV   rZ   )r4   r{   r8   rb   r;   r:   re   r\   kwargsuser_kwargscluster_kwargscontextclusterrS   s                 r=   r2   z(GetCredentialsCommand.GenerateKubeconfig   s7    "22:>N  &&%OO%)!! ' 
 F 	K Nz8ZKGz8Z@G##++-J#*??'9$J  !(W D DJW#*??!$%3$J    )rg   c                    | j                         t        j                   j                  u ry| j                         t        j                   j                  u ry| j                         t        j                   j                  u ryy)Nv1alpha1v1beta1v1 )rK   r   ALPHABETAGA)clss    r=   r   z GetCredentialsCommand.GetVersion   se    
T..444				t0055	5				t0033	3rg   ru   )FN)__name__
__module____qualname____doc__r>   strboolr   r_   r3   r   r'   r0   r2   classmethodr    rg   r=   r   r   5   s    m6x $(,55 5 	5
 39%5n>C >d3i >4 *X  rg   r   c           	          t        j                  | |      s.	 t        j                  | |t	        j
                  d||              yy# t        j                  j                  $ r Y yw xY w)a  Checks if the Connect Gateway API is enabled for a given project.

  Prompts the user to enable the API if the API is not enabled. Defaults to
  "No". Throws an error if the user declines to enable the API.

  Args:
    project_id: The ID of the project on which to check/enable the API.
    service_name: The name of the service to check/enable the API.

  Raises:
    memberships_errors.ServiceNotEnabledError: if the user declines to attempt
      to enable the API.
    exceptions.GetServicesPermissionDeniedException: if a 403 or 404 error is
      returned by the Get request.
    apitools_exceptions.HttpError: Another miscellaneous error with the
      listing service.
    api_exceptions.HttpException: API not enabled error if the user chooses to
      not enable the API.
  zConnect Gateway APIN)r   IsServiceEnabledr   PromptToEnableApiro   ServiceNotEnabledErrorapitools_exceptionsRequestError)r8   r{   s     r=   r.   r.      si    ( 
	$	$Z	>




3
3#\: 
? ##00  s   ,A A&%A&N)0r   
__future__r   r   r   typingr   r   +googlecloudsdk.api_lib.cloudresourcemanagerr    googlecloudsdk.api_lib.containerr	   r    5googlecloudsdk.api_lib.container.fleet.connectgatewayr
   rM   rI   googlecloudsdk.api_lib.servicesr   googlecloudsdk.api_lib.utilr   googlecloudsdk.callioper   *googlecloudsdk.command_lib.container.fleetr   rv   r"   r   rP   r   6googlecloudsdk.command_lib.container.fleet.membershipsr   ro   #googlecloudsdk.command_lib.projectsrj   googlecloudsdk.corer   r   googlecloudsdk.core.utilr   rc   r   rF   r(   r#   Commandr   r.   r   rg   r=   <module>r      s    > &  '  D C Z V 6 , ( N G S @ _ G D # * .G {  ~H// ~B rg   