
    )                        S r SSKJr  SSKJr  SSKJr  SSKrSSKrSSKrSSK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rSrSr Sr!Sr"SS0r#Sr$\RJ                  " \RL                  RN                  \RL                  RP                  \RL                  RR                  5       " S S\RT                  5      5       r+g)zATriggers instance to gather logs and upload them to a GCS Bucket.    )absolute_import)division)unicode_literalsN)	HttpError)projects_api)base_classes)diagnose_utils)base)flags)util)	time_util)log)
propertiesdiagnosticszgce-diagnostics-extract-logsdiagnostics_logs_projecta.  Log collection has begun.
It may take several minutes for this operation to complete.

Logs will be made available shortly at:
gs://{0}/{1}

Status has been sent to the serial port and can be viewed by running:
gcloud compute instances get-serial-port-output $VM-NAME$ --project=$PROJECT$ --zone=$ZONE$EXAMPLESz        To export logs and upload them to a Cloud Storage Bucket, run:

          $ {command} example-instance --zone=us-central1
        z
To use this feature you must grant the iam.serviceAccountTokenCreator role on the project.
For more information please refer to Collecting diagnostic information:
[https://cloud.google.com/compute/docs/instances/collecting-diagnostic-information]
c                   f    \ rS rSrSr\r\S 5       rS r	S r
S rSS jrS rS	 rS
 rS rS rSrg)
ExportLogsB   zTriggers instance to gather logs and upload them to a Cloud Storage Bucket.

Gathers logs from a running Compute Engine VM and exports them to a Google
Cloud Storage Bucket. Outputs a path to the logs within the Bucket.
c                     [         R                  R                  U5        UR                  SSSS9  UR                  R                  S5        g)See base class.z--collect-process-traces
store_truezCollect a 10 minute trace of the running system. On Windows, this utilizes Windows Performance Recorder. It records CPU, disk, file, and network activity during that time.)actionhelpnoneN)instance_flagsINSTANCE_ARGAddArgumentadd_argumentdisplay_info	AddFormat)clsparsers     +lib/surface/compute/diagnose/export_logs.pyArgsExportLogs.ArgsM   sQ     ++F3
"C  E !!&)
    c                 L   [         R                  " 5       U l        U R                  U5      n[        R
                  R                  R                  R                  SS9nU R                  U5      nU R                  5       nU R                  U5      nU R                  UR                  5      nU R                  XEXg5      nU R                  XR                   5      n	U R                  R#                  X2[$        U	5        [&        R(                  " [*        R-                  Xg5      5        XgUS.$ )r   T)required)bucketlogPath	signedUrl)r	   DiagnoseClient_diagnose_client_ResolveInstancer   VALUEScoreprojectGet_GetDiagnosticsServiceAccount_GetSignedUrlExpiration_GetLogBucket_GetLogPathinstance_CreateResumableSignedUrl_ConstructDiagnosticsKeyEntrycollect_process_tracesUpdateMetadata_DIAGNOSTICS_METADATA_KEYr   Print_SUCCESS_MSGformat)
selfargsinstance_refr2   service_accountexpiration_timer*   log_pathurldiagnostics_entrys
             r$   RunExportLogs.RunZ   s    *99;D((.L$$,,00$0?G88AO224O(F 5 56H

(
()/;C ::((*((8:KM IIl!!&34DDr'   c                    [         R                  " SR                  X#U5      5      nSn U R                  R	                  X5      n[         R                  " U5      n[        R                  " U5      n	Sn
[         R                  R                  R                  R                  U	5      nU
R                  X4XU5      $ ! [
         a0  nUR                  S:X  a  [        R                  " [        5        e SnAff = f)a  Make a resumable signed url using the SignBlob API of a Service Account.

This creates a signed url that can be used by another program to upload a
single file to the specified bucket with the specified file name.

Args:
  service_account: The email of a service account that has permissions to
    sign a blob and create files within GCS Buckets.
  expiration: The time at which the returned signed url becomes invalid,
    measured in seconds since the epoch.
  bucket: The name of the bucket the signed url will point to.
  filepath: The name or relative path the file will have within the bucket
    once uploaded.

Returns:
  A string url that can be used until its expiration to upload a file.
z*POST


{0}
x-goog-resumable:start
/{1}/{2} i  NzShttps://storage.googleapis.com/{0}/{1}?GoogleAccessId={2}&Expires={3}&Signature={4})sixensure_binaryr@   r.   SignBlobr   status_coder   r>   /_SERVICE_ACCOUNT_TOKEN_CREATOR_ROLE_MISSING_MSGbase64	b64encodemovesurllibparse
quote_plus)rA   rD   
expirationr*   filepathurl_datasigned_blobe	signatureencoded_sigrG   
url_suffixs               r$   r9   $ExportLogs._CreateResumableSignedUrlp   s    (   9@@	*+H K))22?Mk !!+.I""9-KBC !!''22;?J::fZPP  	
#			ABs   B9 9
C3+C..C3c                    SnU R                   R                  U5       HD  nUR                  R                  SR	                  [
        5      5      (       d  M8  UR                  nMF     Uc   U R                   R                  U[
        5      n[        R                  " U5      nSR	                  U5      n[        R                  " XES5        [        R                  " XES5        U$ )a  Locates or creates a service account with the correct permissions.

Attempts to locate the service account meant for creating the signed url.
If not found, it will subsequently create the service account. It will then
give the service account the correct IAM permissions to create a signed url
to a GCS Bucket.

Args:
  project: The project to search for the service account in.

Returns:
  A string email of the service account to use.
Nz{}@zserviceAccount:{}zroles/storage.objectCreatorzroles/storage.objectViewer)r.   ListServiceAccountsemail
startswithr@   _SERVICE_ACCOUNT_NAMECreateServiceAccountprojects_utilParseProjectr   AddIamPolicyBinding)rA   r2   rD   accountproject_refservice_account_refs         r$   r4   (ExportLogs._GetDiagnosticsServiceAccount   s     O((<<WE		!	!%,,/D"E	F	F!-- F --BB
(*o
  ,,W5K-44_E$$[%BD$$[%AC r'   c                     [         R                   R                  5       [         R                  " US9-   n[        R                  " UR                  5       5      n[        R                  " [        U5      5      $ )zGenerate a string expiration time based on some hours in the future.

Args:
  hours: The number of hours in the future for your timestamp to represent
Returns:
  A string timestamp measured in seconds since the epoch.
)hours)	datetimenow	timedeltatimemktime	timetuplerM   	text_typeint)rA   ro   rX   expiration_secondss       r$   r5   "ExportLogs._GetSignedUrlExpiration   sU     ""&&(8+=+=E+JJJZ%9%9%;<==/011r'   c                    U R                  U5      nSR                  [        U5      nU R                  R	                  X5      nUcQ  U R                  R                  SS9nX4l        SnSnU(       a'   U R                  R                  X5        SnU(       a  M'  UR                  $ ! [         a7  nUR                  S:w  a  UeSR                  X55      Ul        US	-  n SnANQSnAff = f)
zLocates or creates the GCS Bucket for logs associated with the project.

Args:
  project_id: The id number of the project the bucket is associated with.
Returns:
  The name of the GCS Bucket.
z{}_{}N
   )days_to_liver   TFi     )
_GetProjectNumberr@   _GCS_LOGS_BUCKET_PREFIXr.   
FindBucketCreateBucketWithLifecyclenameInsertBucketr   rP   )rA   
project_idproject_numberbucket_namer*   suffixbucket_name_takenr\   s           r$   r6   ExportLogs._GetLogBucket   s     ++J7N..!8.IK""--jFF~$$>>B>Ofkf 	



,
,Z
@#
  ;;  	]]c!G{;&+
A+&	s   1B# #
C$--CC$c                 r    [         R                  " U5      n[        R                  " U5      nUR                  $ )z*Converts a project id to a project number.)rg   rh   r   r3   projectNumber)rA   r   rk   r2   s       r$   r~   ExportLogs._GetProjectNumber   s.    ,,Z8K{+G   r'   c                 ~    [         R                   R                  5       R                  S5      nSR                  X5      $ )zCCreates a timestamped filename that should be realistically unique.z%Y-%m-%d-%H-%M-%S-%fz{}-logs-{}.zip)rp   rq   strftimer@   )rA   r8   	timestamps      r$   r7   ExportLogs._GetLogPath   s3    !!%%'001GHI""877r'   c                     [         R                  " U R                  5       5      nUR                  nUR                  n[
        R                  R                  UU[
        R                  " U5      S9nU$ )z~Resolves the arguments into an instance.

Args:
  args: The command line arguments.
Returns:
  An instance reference to a VM.
)scope_lister)	r   ComputeApiHolderReleaseTrackclient	resourcesr   r   ResolveAsResourceGetInstanceZoneScopeLister)rA   rB   holdercompute_clientr   rC   s         r$   r/   ExportLogs._ResolveInstance   sj     **4+<+<+>?F]]N  I!..@@#>>~N A PL r'   c                 d    [         R                  " S5      nUUUS.n[        R                  " USS9$ )a-  Generates a JSON String that is a command for the VM to extract the logs.

Args:
  signed_url: The url where the logs can be uploaded.
  trace: Whether or not to take a 10 minute trace on the VM.
Returns:
  A JSON String that can be written to the metadata server to trigger the
  extraction of logs.
i,  )r,   traceexpireOnT)	sort_keys)r   CalculateExpirationjsondumps)rA   
signed_urlr   
expire_strdiagnostics_key_datas        r$   r:   (ExportLogs._ConstructDiagnosticsKeyEntry  s9     ..s3J
 ::*d;;r'   )r.   N)r}   )__name__
__module____qualname____firstlineno____doc__DETAILED_HELPdetailed_helpclassmethodr%   rI   r9   r4   r5   r6   r~   r7   r/   r:   __static_attributes__ r'   r$   r   r   B   sR      -
 
E,(QT!F
2 D!8
"<r'   r   ),r   
__future__r   r   r   rR   rp   r   rs   apitools.base.py.exceptionsr   +googlecloudsdk.api_lib.cloudresourcemanagerr   googlecloudsdk.api_lib.computer   'googlecloudsdk.api_lib.compute.diagnoser	   googlecloudsdk.callioper
   ,googlecloudsdk.command_lib.compute.instancesr   r   #googlecloudsdk.command_lib.projectsr   rg   googlecloudsdk.command_lib.utilr   googlecloudsdk.corer   r   rM   r=   re   r   r?   r   rQ   ReleaseTracksr   ALPHABETAGABaseCommandr   r   r'   r$   <module>r      s    H &  '     1 D 7 B ( P E 5 # * 
) 6 4 % 	3 / D%%++T->->-C-C%%((*S<)) S<*S<r'   