
    ֏                        d Z ddlmZ ddlmZ ddlmZ ddlZddlZddlZddlZddl	Z	ddl
Z
ddl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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jR                  jU                  ejR                  jW                  e,      d      Z-d Z.	 	 d6dZ/d Z0 G d de1      Z2d Z3d Z4d7dZ5d Z6	 	 d8dZ7 G d  d!e1      Z8	 	 	 	 	 d9d"Z9d# Z:d$ Z;d% Z<d& Z=d' Z>d( Z?d) Z@d* ZAd:d+ZBd, ZCd- ZDd. ZEd/ ZF G d0 d1e1      ZGd:d2ZHd3 ZId4 ZJd5 ZKy);z.Common utilities for the gcloud dataproc tool.    )absolute_import)division)unicode_literalsN)encoding)
exceptions)
list_pager)storage_helpers)arg_parsers)util)log)
properties)requests)console_attr)
console_io)progress_tracker)creds)store)retryschemasc                 p    t        j                  dt        j                  |       z          | j                  S )zReturns a printable representation of a failed Google API's status.proto.

  Args:
    error: the failed Status to print.

  Returns:
    A ready-to-print string representation of the error.
  zError:
)r   debugr   MessageToJsonmessageerrors    +lib/googlecloudsdk/api_lib/dataproc/util.pyFormatRpcErrorr   3   s*     ))J//667	    c                 .   t        j                  |d      5  t        j                         }|t        j                         |z
  kD  r9	  | |       t        j                  |       |t        j                         |z
  kD  r9ddd       t        j                  dj                  |            # t        j                  $ r Y ddd       yt        j
                  $ r-}t        j                  d||       t        |      r Y d}~d}~ww xY w# 1 sw Y   xY w)z1Poll Dataproc resource until it no longer exists.TautotickNz!Get request for [{0}] failed:
{1}z"Deleting resource [{0}] timed out.)r   ProgressTrackertimeapitools_exceptionsHttpNotFoundError	HttpErrorr   r   IsClientHttpExceptionsleepr   OperationTimeoutErrorformat)request_methodresource_refr   	timeout_spoll_period_s
start_timer   s          r   WaitForResourceDeletionr0   @   s     ''$?J
tyy{Z/
0
|$ jj tyy{Z/
0 @ 	((*11,?	A A !22  @? !** 		6eL !'
 (	 @?sA   /DB,/D,D?D	D#D>DDDDc                  >    t        j                         j                  S N)uuiduuid4hex r   r   GetUniqueIdr7   Y   s    			r   c                       e Zd ZdZd Zy)Bunchz}Class that converts a dictionary to javascript like object.

  For example:
      Bunch({'a': {'b': {'c': 0}}}).a.b.c == 0
  c                     t        j                  |      D ]/  \  }}t        |t              rt	        |      }|| j
                  |<   1 y r2   )six	iteritems
isinstancedictr9   __dict__)self
dictionarykeyvalues       r   __init__zBunch.__init__d   s:    mmJ/
U	E4	 e dmmC 0r   N)__name__
__module____qualname____doc__rD   r6   r   r   r9   r9   ]   s    !r   r9   c                 T    | j                  ddd       | j                  ddd       y )Nz--jarmain_jarz3The HCFS URI of jar file containing the driver jar.)desthelpz--class
main_classzuThe class containing the main method of the driver. Must be in a provided jar or jar that is already on the classpath)add_argument)parsers    r   AddJvmDriverFlagsrP   k   sA    @  B 	D  Fr   c                 B    | j                   dk\  xr | j                   dk  S )z>Returns true if the http exception given is an HTTP 4xx error.i  i  )status_code)http_exceptions    r   r'   r'   w   s#    		#	#s	*	O~/I/IC/OOr   c                 |   | j                   j                  |j                        }t        j                  j                  dj                  |j                               t        j                         }dt        j                  d      }|rdndfd}t        j                  |d	      5  |t        j                         |z
  kD  r	 | j                  j                  j                  |      }t        |j                   | j                   j"                        }	 ||	j$                         t'        |	j$                        |j(                  rn1	 t        j0                  |       |t        j                         |z
  kD  rd
d
d
       t        |j                   | j                   j"                        }	 ||	j$                         |j(                  s.t3        j4                  dj                  |j                              |j6                  rBt3        j8                  dj                  |j                  t;        |j6                                    t        j<                  d|j                  t        j                         |z
         |S # t*        j,                  $ r}
t/        |
      r Y d
}
~
Yd
}
~
ww xY w# 1 sw Y   3xY w)aI  Poll dataproc Operation until its status is done or timeout reached.

  Args:
    dataproc: wrapper for Dataproc messages, resources, and client
    operation: Operation, message of the operation to be polled.
    message: str, message to display to user while polling.
    timeout_s: number, seconds to poll with retries before timing out.
    poll_period_s: number, delay in seconds between requests.

  Returns:
    Operation: the return value of the last successful operations.get
    request.

  Raises:
    OperationError: if the operation times out or finishes with an error.
  nameWaiting on operation [{0}].r   Tr   
 c                     | d  }|r<t         j                  j                         |D ]  }t        j                  |        y y r2   )r   errwritewarning)warningsnew_warningsr]   tracker_separatorwarnings_so_fars      r   _LogWarningsz&WaitForOperation.<locals>._LogWarnings   s?    O,-L	ggmm%&!'G " r   r    NOperation [{0}] timed out.Operation [{0}] failed: {1}.*Operation [%s] finished after %.3f seconds)messages+DataprocProjectsRegionsOperationsGetRequestrV   r   statusPrintr*   r#   r   IsInteractiver   r"   clientprojects_regions_operationsGetParseOperationJsonMetadatametadataClusterOperationMetadatar^   lendoner$   r&   r'   r(   r   r)   r   OperationErrorr   info)dataproc	operationr   r-   r.   requestr/   is_ttyrb   ro   rS   r`   ra   s              @@r   WaitForOperationry   }   s-   " II>> J '**077	GHyy{*/##$/&$d" ''$?
tyy{Z/
0OO??CCGL	- 1 1 J JLX&&'h//0>>
  jj tyy{Z/
0 @ ((++DDF(x  !	

*
*+G+N+N,  

#
#$B$I$Iy7%9 : : ((7IIK*$'	# !**  0
 1 @?s7   0J1BJ1J1J.J)#J1)J..J11J;c                 n	   d}||vs| j                   ||   k7  r| j                  Dt        j                  j	                  dj                  | j                  | j                                n8t        j                  j	                  dj                  | j                                | j                   ||<   | j                  |d   k7  rBt        | j                  d      rJ| j                  j                  4t        j                  j	                  | j                  j                         nt        | j                  d      rO| j                  j                  9t        j                  j	                  dj                  | j                               nnt        | j                  d	      rX| j                  j                  Bt        j                  j	                  d
j                  | j                  j                               | j                  |d<   t        | j                  d      rD| j                  j                  D ]*  }|j                  s|j                  |vs||j                     |j                   k7  r\t        j                  j	                  dj                  |j                  |j                                |j                   ||j                  <   |j                  s|j                  |vs||j                     |j                  k7  st        j                  j	                  dj                  |j                  |j                               |j                  ||j                  <   - | j                  |d   k7  rCt        | j                  d      rJ| j                  j                  4t        j                  j	                  | j                  j                         nt        | j                  d      rO| j                  j                  9t        j                  j	                  dj                  | j                               nnt        | j                  d	      rX| j                  j                  Bt        j                  j	                  dj                  | j                  j                               | j                  |d<   yy)ah  Print workflow and job status for the running workflow template.

  This method will detect any changes of state in the latest metadata and print
  all the new states in a workflow template.

  For example:
    Workflow template template-name RUNNING
    Creating cluster: Operation ID create-id.
    Job ID job-id-1 RUNNING
    Job ID job-id-1 COMPLETED
    Deleting cluster: Operation ID delete-id.
    Workflow template template-name DONE

  Args:
    metadata: Dataproc WorkflowMetadata message object, contains the latest
      states of a workflow template.
    status: Dictionary, stores all jobs' status in the current workflow
      template, as well as the status of the overarching workflow.
    operations: Dictionary, stores cluster operation status for the workflow
      template.
    errors: Dictionary, stores errors from the current workflow template.
  wtNzWorkflowTemplate [{0}] {1}zWorkflowTemplate {0}createClusterr   rr   zCreated cluster: {0}.operationIdz%Creating cluster: Operation ID [{0}].nodeszJob ID {0} {1}zJob ID {0} error: {1}deleteClusterzDeleted cluster: {0}.z%Deleting cluster: Operation ID [{0}].)statetemplater   rh   ri   r*   r|   hasattrr   rr   clusterNamer}   graphr~   jobIdr   )ro   rh   
operationserrorstemplate_keynodes         r   PrintWorkflowMetadatar      s   0 ,8>>VL5I#I$	jj3::


X^^- . 
jj-44X^^DE#>>F<z/::x%%$2288D	jjx--334	''
%3388D	jj.55h6J6JKL	
#11==I	jj>EE

 
 
,
,. /"*"8"8JX^^W%$$ZZ	6	!VDJJ%74::%E

)00TZZHI!ZZtzz	61

+tzz9

077

DJJOP!ZZtzz % z/::x%%$2288D	jjx--334	''
%3388D	jj.55h6J6JKL	
#11==I	jj>EE

 
 
,
,. /"*"8"8J ;r   c                 \   | j                   j                  |j                        }t        j                  j                  dj                  |j                               t        j                         }ddd}i }i }||t        j                         |z
  kD  r	 | j                  j                  j                  |      }t        |j                  | j                   j                        }	t        |	|||       |j                  rn4	 t        j&                  |       ||t        j                         |z
  kD  rt        |j                  | j                   j                        }	|j                  s.t)        j*                  dj                  |j                              |j,                  rBt)        j.                  dj                  |j                  t1        |j,                                    dD ][  }||v s||   ||   j,                  st)        j.                  dj                  ||   j2                  ||   j,                               t        j4                  d|j                  t        j                         |z
         |S # t         j"                  $ r}
t%        |
      r Y d}
~
d}
~
ww xY w)a  Poll dataproc Operation until its status is done or timeout reached.

  Args:
    dataproc: wrapper for Dataproc messages, resources, and client
    operation: Operation, message of the operation to be polled.
    timeout_s: number, seconds to poll with retries before timing out.
    poll_period_s: number, delay in seconds between requests.

  Returns:
    Operation: the return value of the last successful operations.get
    request.

  Raises:
    OperationError: if the operation times out or finishes with an error.
  rU   rW   N)r|   r   rc   rd   re   )rf   rg   rV   r   rh   ri   r*   r#   rk   rl   rm   rn   ro   WorkflowMetadatar   rr   r$   r&   r'   r(   r   r)   r   rs   r   r}   rt   )ru   rv   r-   r.   rw   r/   r   rh   r   ro   rS   ops               r    WaitForWorkflowTemplateOperationr     sM   & II>> J '**077	GHyy{*!%=*&& 	Y$))+
*BC//==AA'Ji+I,>,>,4,=,=,N,NPh Hfj&A	 
 	JJ} 	Y$))+
*BC (	(:(:(0(9(9(J(JL( 


*
*+G+N+N,  

#
#$B$I$Iy7%9 : :.b	ZJrN6:b>;O;O%%&D&K&K
R.
$
$jn&:&:'< = = /
 ((7IIK*$'	+ (( 	~	. 
/s   A)J J+J&&J+c                       e Zd ZdZd Zd Zy)NoOpProgressDisplayz8For use in place of a ProgressTracker in a 'with' block.c                      y r2   r6   r@   s    r   	__enter__zNoOpProgressDisplay.__enter__E      r   c                      y r2   r6   )r@   unused_argss     r   __exit__zNoOpProgressDisplay.__exit__H  r   r   N)rE   rF   rG   rH   r   r   r6   r   r   r   r   B  s    @		r   r   c
           	         | j                   j                  |j                  |j                  |j                        }
dd}d}d}d}fd}d }|r*t
        j                  j                  d       t               }nt        j                  |d	      }t        j                         x}}|5  |	r	|	||z
  kD  r: |        xr j                   }|s,|j                  j                  | j                  v r
d}||z
  d
z   }	|r|r|rn| xr |||z   k\  }|xr  }| xr |}|s|s|r|}	 | j                  j                   j#                  |
      }|rk|j2                  r_|j2                  |k7  rP|r# |        t        j(                  d        |        |j2                  }t5        j6                  |j2                        t        j8                  |       t        j                         }|	s0|	||z
  kD  r:ddd       |j                  j                  }|| j                  v r@|r9st        j(                  d       n!j                  rt        j(                  d       ||u r|S |r||u r|j                  j:                  rCt=        j>                  dj+                  |j                  |j                  j:                              t=        j>                  dj+                  |j                              |j                  j:                  r,t        j@                  d|j                  j:                  z          t=        j>                  dj+                  |j                  ||            t=        jB                  dj+                  |j                  |            # t$        j&                  $ rN}t        j(                  dj+                  t-        j.                  |                   t1        |      r Y d}~d}~ww xY w# 1 sw Y   xY w)a  Poll dataproc Job until its status is terminal or timeout reached.

  Args:
    dataproc: wrapper for dataproc resources, client and messages
    job: The job to wait to finish.
    job_ref: Parsed dataproc.projects.regions.jobs resource containing a
      projectId, region, and jobId.
    message: str, message to display to user while polling.
    goal_state: JobStatus.StateValueValuesEnum, the state to define success
    error_state: JobStatus.StateValueValuesEnum, the state to define failure
    stream_driver_log: bool, Whether to show the Job's driver's output.
    log_poll_period_s: number, delay in seconds between checking on the log.
    dataproc_poll_period_s: number, delay in seconds between requests to the
      Dataproc API.
    timeout_s: number, time out for job completion. None means no timeout.

  Returns:
    Job: the return value of the last successful jobs.get request.

  Raises:
    JobError: if the job finishes with an error.
  )	projectIdregionr   Nr   Fc                  d     r- j                   r  j                  t        j                         y y y r2   )openReadIntoWritabler   r[   )driver_log_streams   r   ReadDriverLogIfPresentz5WaitForJobTermination.<locals>.ReadDriverLogIfPresentt  s)    .33((1 4r   c                      t        j                         } t        j                  j	                  d| j                         d   z         y )N=r   )r   GetConsoleAttrr   r[   ri   GetTermSize)attrs    r   PrintEqualsLinez.WaitForJobTermination.<locals>.PrintEqualsLiney  s3    &&(DGGMM#((*1--.r   zWaiting for job output...Tr    
   zGetJob failed:
{}z3Job attempt failed. Streaming new attempt's output.zExpected job output not found.z4Job terminated, but output did not finish streaming.z Job [{0}] failed with error:
{1}zJob [{0}] failed.z	Details:
z6Job [{0}] entered state [{1}] while waiting for [{2}].z)Job [{0}] timed out while in state [{1}].)"rf   %DataprocProjectsRegionsJobsGetRequestr   r   r   r   rh   ri   r   r   r"   r#   r   r   terminal_job_statesrk   projects_regions_jobsrm   r$   r&   r]   r*   r;   	text_typer'   driverOutputResourceUrir	   StorageObjectSeriesStreamr(   detailsr   JobErrorrt   JobTimeoutError)ru   jobjob_refr   
goal_stateerror_statestream_driver_loglog_poll_period_sdataproc_poll_period_sr-   rw   last_job_poll_timejob_completewait_displaydriver_output_urir   r   r/   nowlog_stream_closedregular_job_pollexpecting_output_streamexpecting_job_doner   r   r   s                            @r   WaitForJobTerminationr   L  s   @ CC!!'.. D O',,2
/ JJ01&(L#33GdKLYY[ *s9j(89+J4E4J4J0J
**

h::
:*$r)		04E 
 A'*@@@  !2 K:K6K++A0A	48J 	5599'B# #"="=''+<<KKMN!99
-GG))+

jj"#IIKcS 9j(89 X **

% h***45!!JK
ju+			!!"E"L"LMM3::--#/ 0 	0 3 : :7== IJJ
zz	hh|cjj0001


@GGMM5*	./ / 	""188N	P PM #,, 	
++*11#--2FG
H"5) *	7 |s?   +A<O1(%NBO1'O1O. AO)#O1)O..O11O;c                  f    t         j                  j                  j                  j	                         S r2   )r   VALUESru   r   	GetOrFailr6   r   r   ResolveRegionr     s#    				#	#	*	*	4	4	66r   c                  f    t         j                  j                  j                  j	                         S r2   )r   r   ru   locationr   r6   r   r   ResolveLocationr     s#    				#	#	,	,	6	6	88r   c                     |j                   j                  | t        t        j                  j
                  j                  j                  dd      }|S )Nr   r   z"dataproc.projects.regions.clustersparams
collection	resourcesParser   r   r   coreprojectr   )rV   ru   refs      r   ParseClusterr     sO      
!!((--55?? 6 	! 	7# 
*r   c                     |j                   j                  | t        t        j                  j
                  j                  j                  dd      }|S )Nr   zdataproc.projects.regions.jobsr   r   )job_idru   r   s      r   ParseJobr     sO      !!((--55?? 2 	! 	3# 
*r   c                 f    | s |       S t        j                  |t        j                  |             S )z2Returns an Operation message for a metadata value.)r   JsonToMessager   )metadata_valuemetadata_types     r   rn   rn     s2    	?			 ( 6 6~ F
H Hr   c                     | j                   j                  d t        t        j                  j
                  j                  j                  dd      }|S )N)regionIdr   zdataproc.projects.regionsr   r   ru   r   s     r   ParseRegionr      sO      
#!((--55?? - 	! 	.# 
*r   c                     | j                   j                  d t        t        j                  j
                  j                  j                  dd      }|S N)locationsId
projectsIdzdataproc.projects.locationsr   r   r   s     r   ParseProjectsLocationsr     sO      
&"))..66@@ / 	! 	0# 
*r   c                     | j                   j                  d t               t        j                  j
                  j                  j                  dd      }|S r   )r   r   r   r   r   r   r   r   r   s     r    ParseProjectsLocationsForSessionr     sR      
(*"))..66@@ / 	! 	0# 
*r   c                    t        j                  |xs dd      }t        j                  | j                  j
                  |      }||_        d|_        |j                  |j                  j                  Lt         t        j                  dd      |j                  j                              d	z   |j                  _	        |j                  j                  j                  `t         t        j                  d
d      |j                  j                  j                              d	z   |j                  j                  _        |S )a  Returns autoscaling policy read from YAML file.

  Args:
    dataproc: wrapper for dataproc resources, client and messages.
    policy_id: The autoscaling policy id (last piece of the resource name).
    policy_file_name: if set, location of the YAML file to read from. Otherwise,
      reads from stdin.

  Raises:
    argparse.ArgumentError if duration formats are invalid or out of bounds.
  -Fbinarymessage_typestreamN2m1d)lower_boundupper_bounds0s)r   ReadFromFileOrStdinexport_utilImportrf   AutoscalingPolicyidrV   basicAlgorithmcooldownPeriodstrr
   Duration
yarnConfiggracefulDecommissionTimeout)ru   	policy_idpolicy_file_namedatapolicys        r   ReadAutoscalingPolicyr  %  s$    
	'	'(8(?C	N$$$66tE&
 &) &+ &++7-0
B+

4T
B##224.57:.;f* ''CCOEH
B+

4T
B  ++GGIFJLOFPf&&B 
-r   c                 @   dj                  |j                  d      dd       }| j                  j                  ||      }| j                  j
                  j                  |      }t        j                  j                  dj                  |j                               |S )zReturns the server-resolved policy after creating the given policy.

  Args:
    dataproc: wrapper for dataproc resources, client and messages.
    name: The autoscaling policy resource name.
    policy: The AutoscalingPolicy message to create.
  /r      )parentautoscalingPolicyCreated [{0}].)joinsplitrf   7DataprocProjectsRegionsAutoscalingPoliciesCreateRequestrk   $projects_regions_autoscalingPoliciesCreater   rh   ri   r*   r   )ru   rV   r  r  rw   s        r   CreateAutoscalingPolicyr  K  s     88DJJsOAa()& MM  N " 
 ????FFwO&**#**69956	-r   c                     ||_         | j                  j                  j                  |      }t        j
                  j                  dj                  |j                               |S )zReturns the server-resolved policy after updating the given policy.

  Args:
    dataproc: wrapper for dataproc resources, client and messages.
    name: The autoscaling policy resource name.
    policy: The AutoscalingPolicy message to create.
  Updated [{0}].)	rV   rk   r  Updater   rh   ri   r*   r   )ru   rV   r  s      r   UpdateAutoscalingPolicyr  b  sQ     &+ OO88??G 	**#**69956	-r   c                 l   ddd| |d}t         j                  j                  j                  j	                         }d| d}ddi}t        j                         j                  |||      }|j                  d	k7  rt        d
      t        j                  |j                        }|j                  dd      S )zDownscope the given credentials to the given access boundary.

  Args:
    token: The credentials to downscope.
    access_boundary_json: The JSON-formatted access boundary.

  Returns:
    A downscopded credential with the given access-boundary.
  z/urn:ietf:params:oauth:grant-type:token-exchangez-urn:ietf:params:oauth:token-type:access_token)
grant_typerequested_token_typesubject_token_typesubject_tokenoptionszhttps://sts.z	/v1/tokenzContent-Typez!application/x-www-form-urlencoded)headersr      zError downscoping credentialsaccess_tokenN)r   r   r   universe_domainrm   r   
GetSessionpostrR   
ValueErrorjsonloadscontentget)tokenaccess_boundary_jsonpayloadr  cab_token_urlr  downscope_response	cab_tokens           r   _DownscopeCredentialsr*  t  s     FMK%' %%**::>>@/  1;-@A'**,11W7 2 4##s*
4
55jj+334)	~t	,,r   c                     t        j                  ddd      }t        j                  |       t        j                  |      r|j
                  }n|j                  }|st        j                  d      t        ||       S )a<  Get an access token for the user's current credentials.

  Args:
    access_boundary_json: JSON string holding the definition of the access
      boundary to apply to the credentials.

  Raises:
    PersonalAuthError: If no access token could be fetched for the user.

  Returns:
    An access token for the user.
  NT)allow_account_impersonationuse_google_authz?No access token could be obtained from the current credentials.)
c_storeLoadRefreshc_credsIsOauth2ClientCredentialsr  r$  r   PersonalAuthErrorr*  )r%  credr$  s      r   GetCredentialsr5    sq     

d
D$	//$&&t,EJJE	

&
&IK K	u&:	;;r   c                   h    e Zd ZdZd ZddZd Zd Z ej                  d      d	        Z
d
 Zd Zy)PersonalAuthUtilsz2Util functions for enabling personal auth session.c                      y r2   r6   r   s    r   rD   zPersonalAuthUtils.__init__  r   r   Nc                    |g}|j                  |       d}	 t        t        dd      r{t        j                  ||t        j                  t        j                  d      }|j
                  j                  d      j                         }|j                          |j                  S t        j                  |t        j                  t        j                  t        j                        }|j                  |      \  }}	|S # t        $ rm}
|r&t        j                  dd	j                  |      |       t!        j"                  d
d	j                  |      z   dz   t%        j&                  |
      z         d}
~
ww xY w)ai  Run the specified command, capturing and returning output as appropriate.

    Args:
      openssl_executable: The path to the openssl executable.
      args: The arguments to the openssl command to run.
      stdin: The input to the command.

    Returns:
      The output of the command.

    Raises:
      PersonalAuthError: If the call to openssl fails
    NrunF)inputstdoutstderrcheckutf-8)stdinr<  r=  )r;  z3OpenSSL command "%s" failed with error message "%s" z"Failure running openssl command: "z": )extendgetattr
subprocessr:  PIPEr=  decodestripcheck_returncoder<  Popencommunicate	Exceptionr   r   r	  r   r3  r;   r   )r@   openssl_executableargsr@  commandr=  procpr<  _exs              r   _RunOpensslCommandz$PersonalAuthUtils._RunOpensslCommand  s>    ""GNN4F!<	UD	)~~???? ##G,224 	{{//????	$
 MMM.	 <			G((7#V	-(()M),'):*;=B*C),r):*; < <	<s    BC> $AC> >	E4A(E//E4c                    | j                  |ddd|g|      j                  d      }	 |j                         j                  d      d   }t	        |      dk7  rt        d	      t        |d
       |dz   j                  d      S # t        $ r0}t        j                  dt        j                  |      z         d}~ww xY w)zCompute HMAC tag using OpenSSL.dgstz-sha256z-hmacr@  r?  rA     @   z1HMAC output is expected to be 64 characters long.   z'Failure due to invalid openssl output: NrX   )rS  rF  rG  r
  rq   r  intrK  r   r3  r;   r   encode)r@   rB   r   rL  
cmd_outputstripped_outputrR  s          r   _ComputeHmaczPersonalAuthUtils._ComputeHmac  s    ((VY= ) F7O I"((*005a8o	_		#LMM	/2 d"**733  I((
3cmmB6G
GI IIs   AB 	B=+B88B=c                 "   t        |      dk7  rt        d      t        j                  |      j	                  d      }| j                  |d|      }t        |      }|j                  |       |j                  d       | j                  |||      S )a}  Derives HMAC-based Key Derivation Function (HKDF) key through expansion on the initial pseudorandom key.

    Args:
      prk: a pseudorandom key.
      info: optional context and application specific information (can be
        empty).
      openssl_executable: The path to the openssl executable.

    Returns:
      Output keying material, expected to be of 256-bit length.
        zCThe given initial pseudorandom key is expected to be 32 bytes long.r?  r      )rq   r  base64	b16encoderF  r^  	bytearrayrB  )r@   prkrt   rL  
base16_prkt1t2datas          r   _DeriveHkdfKeyz PersonalAuthUtils._DeriveHkdfKey  s     3x2~
OQ Q!!#&--g6J			:s,>	?Br]F
MM$
MM'Z1CDDr   rW  )max_retrialsc           
         t        j                  |dz   j                  d            j                         }t	        j
                  t        j                  d            }|j                  d      }t        j                  d      }| j                  |dj                  d      |      }t	        j
                  | j                  |dj                  d      |            j                  d      }	t        j                         5 }
|
j                  |j                  d             |
j                  d       | j                  |dd	d
dd|
j                  gt	        j                   |            }ddd       t#              dk7  rt%        d      t	        j                   |      j                  d      }t        j                         5 }|j                  |       |j                  d       dddd|ddj'                  |j                        g}| j                  |||j                  d            }ddd       t#        |      dk7  rt%        d      t	        j                         j                  d      }t)        |      }|j+                  |       | j-                  |	||      j                  d      dd }dj'                  |||||      S # 1 sw Y   ^xY w# 1 sw Y   xY w)zEncode token using OpenSSL.

    Args:
      public_key: The public key for the session/cluster.
      secret: Token to be encrypted.
      openssl_executable: The path to the openssl executable.

    Returns:
      Encrypted token.
    rX   r?  rY  r`  encryption_keyauth_keyr   rsautlz-oaepz-encryptz-pubinz-inkeyrV  Ni   z3The encrypted key is expected to be 512 bytes long.encz-aes-256-ctrz-saltz-ivz-passzfile:{}z{}:{}:{}:{}:{})hashlibsha256r[  	hexdigestrb  rc  osurandomrF  ri  tempfileNamedTemporaryFiler\   seekrS  rV   	b64encoderq   r  r*   rd  rB  r^  )r@   
public_keysecretrL  key_hashiv_bytesinitialization_vectorinitial_keyrl  rm  kfencrypted_keyencoded_keypfencrypt_argsencrypted_tokenencoded_token
hmac_inputhmac_tags                      r   _EncodeTokenUsingOpensslz*PersonalAuthUtils._EncodeTokenUsingOpenssl  s    ~~zD088ABLLNH

2/H$OOG4**R.K(()9)@)@)I);=N K):):7)C.	0117  
	$	$	&"hhz  )*ggaj--
Wj(Hbgg
F  - . /m 
' =S LMM""=188AK		$	$	&"hh~ggaj
%1F


277
#l //
l&--2H 0 Jo 
' =S LMM$$_5<<WEM8$Jo&  :!355;VG_%&r+H ""8]K#8(D D; 
'	& 
'	&s   >A)K A(KKKc                 ~   |r| j                  |||      S 	 ddl}ddlm} |j                          d}t        j                  |      d   d   d   d   }t        j                  |d	z   j                  d
            j                         }|j                  |      }	|j                  |	      }
|
j                  |j                         }|j#                  |j                  d
      |      }t%        j&                  |      j)                  d
      }dj+                  ||      S # t        $ r t	        j
                  d      w xY w)zEncrypt secret with resource public key.

    Args:
      public_key: The public key for the session/cluster.
      secret: Token to be encrypted.
      openssl_executable: The path to the openssl executable.

    Returns:
      Encrypted token.
    r   NhybridaC  Cannot load the Tink cryptography library. Either the library is not installed, or site packages are not enabled for the Google Cloud SDK. Please consult Cloud Dataproc Personal Auth documentation on adding Tink to Google Cloud SDK for further instructions.
https://cloud.google.com/dataproc/docs/concepts/iam/personal-authr   rB   keyDatarC   rX   r?  z{}:{})r  tinkr  ImportErrorr   r3  registerr   r!  rp  rq  r[  rr  JsonKeysetReaderread_no_secret_keyset_handle	primitiveHybridEncryptencryptrb  rx  rF  r*   )r@   ry  rz  rL  r  r  contextpublic_key_valuer{  readerkh_pub	encrypter
ciphertextr  s                 r   EncryptWithPublicKeyz&PersonalAuthUtils.EncryptWithPublicKeyG  s=    **:v+=? ?O OOG zz*-e4Q7	B7K~~	D	 ((133<9;  "":.F..v6F   !5!56I""6==#97CJ$$Z077@M>>(M223  O((NO OOs   
D D<c                 8    	 ddl }ddl m} y# t        $ r Y yw xY w)z1Check if Tink cryptography library can be loaded.r   Nr  TF)r  r  r  )r@   r  r  s      r   IsTinkLibraryInstalledz(PersonalAuthUtils.IsTinkLibraryInstalledu  s&    	   s   
 	r2   )rE   rF   rG   rH   rD   rS  r^  ri  r   RetryOnExceptionr  r  r  r6   r   r   r7  r7    sJ    :	2<h4 E: 5q)3D *3Dj,3\r   r7  c                     t        j                  |xs dd      }t        j                  | j                  j
                  |      }|S )a?  Returns session template read from YAML file.

  Args:
    dataproc: Wrapper for dataproc resources, client and messages.
    template_file_name: If set, location of the YAML file to read from.
      Otherwise, reads from stdin.

  Raises:
    argparse.ArgumentError if duration formats are invalid or out of bounds.
  r   Fr   r   )r   r   r   r   rf   SessionTemplate)ru   template_file_namer   r   s       r   ReadSessionTemplater    sE     
	'	'(:(Ac%	P$$$44TC( 
/r   c                 N   dj                  |j                  d      dd       }||_        | j                  j	                  ||      }| j
                  j                  j                  |      }t        j                  j                  dj                  |j                               |S )zReturns the server-resolved template after creating the given template.

  Args:
    dataproc: Wrapper for dataproc resources, client and messages.
    name: The session template resource name.
    template: The SessionTemplate message to create.
  r  r   r  )r  sessionTemplater  )r	  r
  rV   rf   6DataprocProjectsLocationsSessionTemplatesCreateRequestrk   #projects_locations_sessionTemplatesr  r   rh   ri   r*   )ru   rV   r   r  rw   s        r   CreateSessionTemplater    s     88DJJsOAa()&(- NN" O $ 
 __@@GGP(**#**8==9:	/r   c                     ||_         | j                  j                  j                  |      }t        j
                  j                  dj                  |j                                |S )zReturns the server-resolved template after updating the given template.

  Args:
    dataproc: Wrapper for dataproc resources, client and messages.
    name: The session template resource name.
    template: The SessionTemplate message to create.
  r  )rV   rk   r  Patchr   rh   ri   r*   )ru   rV   r   s      r   UpdateSessionTemplater    sL     (-__@@FFxP(**#**8==9:	/r   c              /      K   t               fd}t        j                  |d|i|}|D ]  }|  r/t        j                  | dj                  t                           yyw)z7Yields from paged List calls handling unreachable list.c                 R    j                  | j                         t        | |      S r2   )updateunreachablerC  )r   r   r  s     r   _GetFieldFnz5YieldFromListWithUnreachableList.<locals>._GetFieldFn  s$    w**+7D!!r   get_field_funcz, N)setr   YieldFromListr   r]   r	  sorted)unreachable_warning_msgrM  kwargsr  resultitemr  s         @r    YieldFromListWithUnreachableListr    sf     +" ##P;PP&d
J KK		&%& s   A$A')<      )r  )Nr  )NFrW  r   Nr2   )LrH   
__future__r   r   r   rb  rp  r   rs  rD  ru  r#   r3   apitools.base.pyr   r   r$   r   googlecloudsdk.api_lib.dataprocr	   googlecloudsdk.callioper
   !googlecloudsdk.command_lib.exportr   r   googlecloudsdk.corer   r   r   googlecloudsdk.core.consoler   r   r   googlecloudsdk.core.credentialsr   r1  r   r.  googlecloudsdk.core.utilr   r;   pathr	  dirname__file__
SCHEMA_DIRr   r0   r7   objectr9   rP   r'   ry   r   r   r   r   r   r   r   r   rn   r   r   r   r  r  r  r*  r5  r7  r  r  r  r  r6   r   r   <module>r     sU   5 &  '    	     % > ' 6 ; / A # * ( 4 2 8 < < * 
WW\\"''//(3Y?

  ')*+	A2!F !	FP<~E9V 0434:z	& 	 '+,1,-13$(yP~79 H#L.$-8<4V Vr$(r   