
    #                         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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S jrS rSS jr SS jrS rS rS rS r g)zBUtility function for OS Config Troubleshooter to check cloud logs.    )absolute_import)division)unicode_literalsN)
exceptions)	logs_util)common)utillog)
console_io)files   c                    SnU R                   n[        U5      n[        U5       HZ  nX5   nUSR                  UR                  U(       a  UR
                  R                  OUR
                  5      XTS-
  :X  a  SOS-   -  nM\     US-  nU$ )aE  Converts the property into a JSON string.

This is mainly used for properties that have additional properties under them.
For example, the resource and split properties of LogEntry store objects
containing additional fields. These fields must be elementary and have no
nested objects within.

Args:
  payload: the property to serialize to JSON.
  is_json_payload: only used for the jsonPayload property since the values
                   values are nested in an additional string_value attribute.

Returns:
  The JSON string representation of the provided property of a LogEntry.
z{
z
"{}": "{}"   
z,
})additionalPropertieslenrangeformatkeyvaluestring_value)payloadis_json_payloadpayload_string
propertieslengthifields          Mlib/googlecloudsdk/command_lib/compute/os_config/troubleshoot/log_analysis.py_PayloadToJSONr"   %   s      .++*z?&=aMEl))		%4	!	!%++ qje- -N  C.	    c                 :   [        U S5      (       a&  U R                  (       a  [        U R                  5      $ [        U S5      (       a  U R                  (       a  U R                  $ [        U S5      (       a%  U R                  (       a  [        U R                  SS9$ g)a  Used as a formatter for logs_util.LogPrinter.

If the log has a JSON payload or a proto payload, the payloads will be
JSON-ified. The text payload will be returned as-is.

Args:
  log: the log entry to serialize to json

Returns:
  A JSON serialization of a log's payload.
protoPayloadtextPayloadjsonPayloadT)r   zNo contents found.)hasattrr%   r"   r&   r'   r
   s    r!   _PayloadFormatterr)   B   sn     S.!!c&6&6#**++sM""s??sM""s#//4@@	r#   c                    SnU R                  S5      (       a  [        R                  " U 5      nO<[        R                  R                  U 5      (       a  U nO[        R                  " 5       n[        5       nSnU(       a  SR                  UUU5      nOSR                  X5      n[        R                  R                  X55      $ )zEGets the full path of the destination file to which to download logs.N~ z{}_serial_port_{}_logs_{}.txtz{}_cloud_logging_logs_{}.txt)

startswithr   ExpandHomeDirospathisabsGetCWD_GetDateStrr   join)destinstance_idserial_port_numbase_dirdate_str	file_names         r!   _GenerateLogFilePathr;   W   s    (	__S""4(H	ww}}TH||~H]()/66{7F7?AI /55kLI	h	**r#   c                    [        X R                  U5      nU(       af  UR                  R                  S5      n/ nU H  nSU;   d  M  UR	                  U5        M     [
        R                  " USR                  U5      5        O[        R                  " 5       nUR                  [        5        [
        R                  " UUR                  US   5      S-   5        [
        R                  " USS9 n	USS  H&  n
U	R                  UR                  U
5      S-   5        M(     SSS5        [        R                   " SR#                  U5      5        g! , (       d  f       N4= f)	a  Downloads the logs and puts them in the specified destination.

Args:
  instance: the instance from which to download the logs.
  logs: the list of logs from the instance.
  dest: the destination folder.
  serial_port_num: The serial port from which the logs came
r   OSConfigAgentr   T)appendr   NzLogs downloaded to {}.)r;   idcontentssplitr>   r   WriteFileContentsr4   r   
LogPrinterRegisterFormatterr)   Format
FileWriterwriteloggingPrintr   )instancelogsr5   r7   	dest_filer@   lines_to_downloadline	formatterfr   s              r!   DownloadInstanceLogsrQ   l   s    #4oF)}}""4(H	D	   &  
Ityy1B'CD$$&I 12	a!D(* 
		)D	1Qab#		  %,-  
2 
--(//	:; 
2	1s   /0E
Ec                  `    [         R                   R                  5       n U R                  S5      $ )Nz%Y-%m-%d-%H-%M-%S)datetimenowstrftime)dates    r!   r3   r3      s&    						 $	*	++r#   c           
          U R                   R                  SU R                  R                  UR                  UR                  USUS94nU R                  U/S9S   $ )NGetSerialPortOutputr   )rJ   projectportstartzone)requests)apitools_client	instancesmessages*ComputeInstancesGetSerialPortOutputRequestnameMakeRequests)clientrY   rJ   r\   rZ   requests         r!   _GetSerialLogOutputrf      sg    ##--"__GG"--  H ' 
		wi		0	33r#   c                    [         R                  " S5        SnUR                   H  nSUR                  ;   d  M  Sn  O   U(       d  [         R                  " S5        gSR	                  UR
                  U R                  5      n[        [        R                  " USSS	95      nUR                  5         [        R                  " 5       R                  R                  nS
nSnU H7  n	U	R                  UR                   :  a  US-  nU(       a  M+  U	R"                  nM9     U(       a  Sn
U
SR	                  [%        U5      5      -  n
U
SR	                  XwS:X  a  SOS5      -  n
U
SU(       a  UOS-   S-   -  n
[         R                  " U
5        [&        R(                  " SS9nU(       aK  [&        R*                  " SSS9n[         R                  " S5        [-        X[.        R0                  " U5      5        g[         R                  " S5        g)z:Checks the Cloud logs created by this instance for errors.z9The troubleshooter is now fetching and analyzing logs...
Fz-https://www.googleapis.com/auth/logging.writeTz.Cloud logging is not enabled for this project.zoresource.type="gce_instance" AND resource.labels.instance_id="{}" AND log_name="projects/{}/logs/OSConfigAgent"i  DESC)limitorder_byr   Nr   z:The troubleshooter analyzed Cloud Logging logs and found:
z > {} OSConfigAgent log entries.
z> Among them, {} {} errors.
hashavez> The earliest timestamp is zN/A. Download all OSConfigAgent logs?prompt_stringz#Destination folder for log downloadz~/Downloads/osconfig-logs/messagedefaultzDownloading log entries...zAThe troubleshooter analyzed Cloud Logging logs and found no logs.)rH   rI   serviceAccountsscopesr   r?   rb   listr   	FetchLogsreverselogging_utilGetMessagesLogEntrySeverityValueValuesEnumseverityERROR	timestampr   r   PromptContinuePromptWithDefaultrQ   six	text_type)rY   rJ   cloud_logging_enabledaccount
filter_strrK   severity_enumerror_log_counterearliest_timestampr   response_messagecontr5   s                r!   CheckCloudLogsr      s   	--LM  ))g6'..H" *
 
MMBC<=CVKK>/  
fz(.0 
1$,,.**,55MM-c
||}***1==	  
#;BB3t9MM7>>$:5H H60e=?BC CMM"# $$8:D ))7.0d mm0183==+>?
 
 MM  r#   c                    [         R                  " S5        / n/ n[        S[        S-   5       H  nSnSn [	        XX#U5      n[        [        R                  " SUR                  5      5      nUR                  U5        UbB  [         R                  " SR                  UU5      5        U(       a  UR                  U5        M  M  [         R                  " SR                  U5      5        M     U(       av  [        R                  " SS	9n	U	(       aZ  [        R                  " S
SS9n
[         R                  " S5        U H(  n[!        UXVS-
     ["        R$                  " U
5      US9  M*     ggg! [        R                   a    Sn GNf = f)z>Checks the serial log output of the given instance for errors.z5The troubleshooter is now checking serial log output.r   Nr   zOSConfigAgent Errorz"Port {}: {} OSConfigAgent error(s)zPort {}: N/Arn   ro   zKDestination folder for log download (default is ~/Downloads/osconfig-logs):z~/Downloads/osconfig-logsrq   z!Downloading serial log entries...)r7   )rH   rI   r   _NUM_SERIAL_PORTSrf   r   refindallr@   r   Errorr>   r   r   r   r   rQ   r   r   )rd   rY   rJ   r\   logs_to_downloadserial_logsrZ   
serial_log
num_errorsr   r5   s              r!   CheckSerialLogOutputr      sd   	--GH+A(1,-dJJ&vMjrzz"8*:M:MNOj z"mm8??@JL M	% 
 mmN))$/0! .$ $$8:D))_-/d mm78"$q!MM$ 		" #    js   7E**FF)F)N)!__doc__
__future__r   r   r   rS   r/   r   apitools.base.pyr   googlecloudsdk.api_lib.appr   googlecloudsdk.api_lib.loggingr   r	   ry   googlecloudsdk.corer   rH   googlecloudsdk.core.consoler   googlecloudsdk.core.utilr   r   r   r"   r)   r;   rQ   r3   rf   r   r    r#   r!   <module>r      sj    I &  '  	 	 ' 0 1 ? . 2 * 
 :*+0 *.<B,
	4:z%"r#   