
    &                     4   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mZ ddlmZ ddlmZ d	Zd
Ze	j*                  j-                  dd      Zd Zej2                  ej4                   G d dej6                                      Zy)z!The `gcloud meta daemon` command.    )absolute_import)division)unicode_literalsN)gcloud_main)base)filesz0.0.0.0i  GCLOUD_DAEMON_PRECOMPUTE_DATACLIc           
         t        j                          }t        j                         }t        j                  d||       | t        j
                  d|       ddiS 	 | j                  |      }|j                  |j                  |j                  j                         D ci c]&  \  }}|j                  d      |j                  d      ( c}}t        |j                  t              r|j                  j                  d      n|j                  d}t        j                  d|       |t        j                          }||z
  }	t        j                  d	||	       S c c}}w # t        $ r}
t        j                   d
||
       t        |
j"                  t$              r|
j"                  nd}d|
z  |dcY d}
~
t        j                          }||z
  }	t        j                  d	||	       S d}
~
wt&        $ r`}t        j
                  d|       ddt)        |      z  icY d}~t        j                          }||z
  }	t        j                  d	||	       S d}~ww xY w# t        j                          }||z
  }	t        j                  d	||	       w xY w)z=Executes the gcloud command using the precomputed CLI object.z<PID: %s - Starting perform_gcloud_execution with input: '%s'Nz)PID: %s - Precomputed CLI object is None!errorz/Internal Server Error: CLI object not availableutf-8)urimethodheadersbodyzPID: %s - Execution successful.z<PID: %s - Completed perform_gcloud_execution in %.4f secondsz+PID: %s - SystemExit processing request: %s   z"Command failed with SystemExit: %s)r   	exit_codez-PID: %s - Exception during command execution:z&Exception during command execution: %s)timeosgetpidlogginginfor   Executer   r   r   itemsdecode
isinstancer   bytes
SystemExit	exceptioncodeint	Exceptionstr)cli_objcommand_list
start_timepidrequestkvresponse_dataend_timecomputation_timeexcr   es                lib/surface/meta/daemon.pyperform_gcloud_executionr1   )   s6   yy{*
		#	,,D	 _MM=sCFGG"ool+G{{..  --/
/1 HHWqxx00/
 ',,. LL(M LL2C8 yy{H*,LLF3
 
 CS#N&sxx51I5;  yy{H*,LLF 
 HMMA3G=AFGGyy{H*,LLFH yy{H*,LLFs]   AE  !+E
AE  E   	I)AG%/I0I %I1%III II 2Jc                        e Zd ZdZdddZd Zy)DaemonzE(DEBUG MODE) Precomputes gcloud CLI and runs a single-request server.a  
            (DEBUG MODE) Initializes the gcloud CLI environment based on PRECOMPUTE_DATA,
            starts an HTTP server in the FOREGROUND, serves exactly one POST
            request to the root path ('/'), executes the requested gcloud command
            using the precomputed environment, returns the result, and then exits.

            The command will BLOCK until the single request is received and processed.
        a  
            To run the foreground daemon precomputing the basic CLI:

            $ gcloud meta daemon

            (The command will now wait here)

            Open another terminal and send a request (e.g., using curl):

            $ curl -X POST -H "Content-Type: application/json" -d '{"command_list": ["projects", "list", "--limit=1", "--format=json"]}' http://localhost:8080/

            (The original 'gcloud meta daemon' command will process this, print logs, and then exit)
        )DESCRIPTIONEXAMPLESc                   
 t        j                  t         j                  d       t        j                  d       t	        j                         }	 dt
        j                  d<   dt
        j                  d<   dt
        j                  d<   dt
        j                  d<   dt
        j                  d	<   dt
        j                  d
<   dt
        j                  d<   dt
        j                  d<   dt
        j                  d<   dt
        j                  d<   t        j                  g       
t        j                  d       t        j                  d       	 g d}
j                  |       t	        j                         }t        j                  d||z
          G 
fddt        j                  j                         }t        j                  d       	 dt"        j$                  _        t#        j$                  t(        t*        f|      5 }d}t-        j.                  |      5 }	|	j1                  d       d d d        t        j                  d|       t        j                  d t(        t*        t2               |j5                          t        j                  d!       |j7                          d d d        t        j                  d$       t        j8                          t        j                  d%       t        j                  d&       y # t        $ r Y w xY w# t        $ r8}t        j                  d       t        j                  d|z         Y d }~d }~ww xY w# 1 sw Y   )xY w# 1 sw Y   xY w# t        $ r7}t        j                  d"       t        j                  d#|z         Y d }~d }~ww xY w# t        j                  d$       t        j8                          w xY w)'Nz<%(asctime)s - PID: %(process)d - %(levelname)s - %(message)s)levelformatzStarting precomputation...1CLOUDSDK_CORE_DRY_RUN!CLOUDSDK_AUTH_DISABLE_CREDENTIALSCLOUDSDK_CORE_DISABLE_PROMPTS%CLOUDSDK_CORE_DISABLE_USAGE_REPORTING/CLOUDSDK_COMPONENT_MANAGER_DISABLE_UPDATE_CHECK"CLOUDSDK_CORE_DISABLE_FILE_LOGGINGalways"CLOUDSDK_CORE_SHOW_STRUCTURED_LOGSr   CLOUDSDK_CORE_VERBOSITYgaasCLOUDSDK_METRICS_ENVIRONMENT0!CLOUDSDK_CORE_USER_OUTPUT_ENABLEDzPrecomputing basic CLI...zLoading frequent commands)compute	instanceslistz--project=fake-projectz(Precomputation complete in %.4f seconds.z!Failed during CLI precomputation:z#Error during CLI precomputation: %sc                   "    e Zd ZdZ fdZd Zy)(Daemon.Run.<locals>.SingleRequestHandlerz<Handles ONE incoming POST request and then signals shutdown.c                 H   t        j                         }t        j                  d|| j                         | j                  dk(  rQt        | j                  d         }| j                  j                  |      }	 t        j                  |j                  d            }|j                  d      }|rt        |t              s)t        j                  d|       | j!                  dd       y		 t        j                  d||       t%        |      }d}| j'                  |       | j)                  dd       | j+                          | j,                  j/                  t        j0                  |      j3                  d             t        j                  d|       n2t        j4                  d|| j                         | j!                  d       t        j                  d|       y	# t        j"                  $ r- t        j                  d
|d       | j!                  dd       Y y	w xY w)z Handles the single POST request.z&PID: %s - Request received at path: %s/zContent-Lengthr   r%   zGPID: %s - Missing or invalid 'command_list' (must be a list) in requesti  z=Missing or invalid 'command_list' (must be a list) in requestNzPID: %s - Invalid JSON requestT)exc_infozInvalid JSON requestz3PID: %s - Received compute request with command: %s   zContent-typezapplication/jsonz"PID: %s - Response sent to client.z/PID: %s - Received request for unknown path: %si  z5PID: %s - Request handled. Signaling server shutdown.)r   r   r   r   pathr!   r   rfilereadjsonloadsr   getr   rI   r   
send_errorJSONDecodeErrorr1   send_responsesend_headerend_headerswfilewritedumpsencodewarning)	selfr'   content_length	post_datarequest_datar%   r+   status_codeprecomputed_clis	           r0   do_POSTz0Daemon.Run.<locals>.SingleRequestHandler.do_POST   s   iik=sDIIN99t||,<=>.jjoon5)::i&6&6w&?@L'++N;Lz,'Emm 
 oo
  (F" ,,C 3|-
 +


[
)


>+=
>




**

4::m4;;GD
E
,,;S
A //?dii //#
 	CS	
? %% MM:C$OOOC!78s   ;A/G! !=H! H!c                 \    t        j                  dt        j                         ||z         y)z'Log messages using the standard logger.zPID: %s - HTTP Server: %sN)r   r   r   r   )r`   r8   argss      r0   log_messagez4Daemon.Run.<locals>.SingleRequestHandler.log_message   s     	0"))+v}M    N)__name__
__module____qualname____doc__rf   ri   )re   s   r0   SingleRequestHandlerrK      s    H8
vNrj   ro   z"Starting foreground HTTP server...Tz/tmp/gcloud_daemon.readyreadyz
Created %sz3Server started on http://%s:%s (PRECOMPUTE_DATA=%s)z&Request handled. Server shutting down.z/Unhandled exception occurred in server process:zServer error: %sz Server process function exiting.z7Daemon command finished normally after serving request.r   )r   basicConfigINFOr   r   r   environr   	CreateCLIr   r"   r   sysexithttpserverBaseHTTPRequestHandlersocketserver	TCPServerallow_reuse_addressHOSTPORTr   
FileWriterr\   PRECOMPUTE_DATAhandle_requestserver_closeshutdown)r`   rh   precomputation_start_timecompute_instances_list_commandprecomputation_end_timer/   ro   httpdgcloud_daemon_ready_filefre   s             @r0   Runz
Daemon.Runy   s    llM LL-. $		#:,/bjj()8;bjj4547bjj01<?bjj89FIbjjBC9<bjj569Abjj56.5bjj*+39bjj/08;bjj45#--b1oll./ll./	*
& 	 >? !%		ll
4
!$=
=BNt{{AA BNJ LL5637l0!!4,0DE#= 671
'''
 8\#;<A		
 	=># F0 ll56LLJKHHQKc    :;<	hh4q899:` 87 FE&  'IJ	hh!A%&&'
 ll56s   C=L K> $-L 5M+ MM+A7M"M+ >	LL 
LL 	M-M

MM	MM($M+ +	N+4-N&!N. &N++N. .+ON)rk   rl   rm   rn   detailed_helpr    rj   r0   r3   r3   \   s     N-0Urj   r3   )rn   
__future__r   r   r   http.serverrw   rS   r   r   rz   ru   r   googlecloudsdkr   googlecloudsdk.callioper   googlecloudsdk.core.utilr   r}   r~   rs   rU   r   r1   HiddenDefaultUniverseOnlyCommandr3   r   rj   r0   <module>r      s    ( &  '    	  
  & ( * **..#U
0f pT\\ p  prj   