fj-]dZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl mZmZmZddl mZmZmZmZddlmZddlZddlmZddlmZdd lmZdd lm Z m!Z!m"Z"dd l#m$Z$m%Z%dd l&m'Z'dd l(m)Z)m*Z*m+Z+ddl,m-Z-ddl.m/Z/ddl0m1Z1m2Z2e j3r ddl4m5Z5m6Z6m7Z7eGddZ8ej9e:Z;GddZ'>kz~k$ v/&.1ABBB=Gylogginginfosi_pid_flush_mongodb_countersroskillOSErrorwarning)rMsiginfos r)_wait_for_sigusr2zAgent._wait_for_sigusr2os$fn%566 9:A. J J J $$&&& RSSS U GGNFN 3 3 3 3 3 U U U OS T T T T T T Us1$BB98B9ctjtjtjh |n$#t $rt jdYnwxYw;)z Setup SIGUSR2 handler that starts in-memory storage flush when received. When flushed, send SIGUSR2 back to the process that send signal. Tz4Unable to process signal, see traceback for details.)r;r<r=r>r\ ExceptionrS exception)rMs r)_setup_signal_handlerzAgent._setup_signal_handler}s} v/&.1ABBB Z Z&&(((( Z Z Z!"XYYYYY Z ZsAA#"A#c||gn t}|D]}td| ||\}}n%#t$rt jd|YXwxYwt|5}||j dddn #1swxYwY|j dkr| ||j | ||j |j dS)Nz7Updating task requests counters in mongo for task_id=%sz Unable to get client and task %snext_request_idtime)rloggerrTget_cached_or_loadrrSrZrupdate_with_local_datarc tracing_by update_counts request_count tracing_count)rMtask_idtasks_to_flush apiclientr"storages r)rVzAgent._flush_mongodb_counterss{&-&9'|~~% 7 7G KKQSZ [ [ [ "&"9"9'"B"B 44    BGLLL  $G,, U++G">">D    % % ' ' ' " ,!.000 3? ! 0     " ,%,,,&*kkmm# G'$++7"L2222z'''LL"`aaa$$&&&&&' $QJE!,%,,,                                 sZE%5E C10E 1=D1.E 0D11E  E% E E%E E%%E),E)cD|||\|d<|d<dS)zj Calculate throttling values and update given data with resulting throttling stat hitting_limitsthrottled_timeN)rE)rMdatat_key cpu_values r)add_limit_faultszAgent.add_limit_faultss5 :>9L9L 9::6 %5 6 6 6r(php_pid cpu_usage caller_uidctd||||j|||jdS)z Called when php request starts and sends us welcome request meaning that request started on the php side. z=Received request init trigger from php=%s uid=%s cpu_usage=%sN)rerTrEsaveflush)rMrrrs r)_handle_request_initzAgent._handle_request_initsZ  SZ 4 4 4   )444 !!#####r( request_datac2|d||||tdt j|d|d|||dS)Nrz&[%s] Processing trace for task %s (%s)tracing_task_idurl)getrrerTrnameprocess_request_data)rMrrrrs r)_handle_request_endzAgent._handle_request_ends   , - - 5  ! !, C C C <"$$) $$%677 $$U++ - - - !!, ;;;;;r(i@g@rrcJ t|\}}}n?#t$r2td|YdSwxYw|j5|j|d|jkr=td|| ddddS|j|xxdz cc<dddn #1swxYwY | |||||j5|j|xxdzcc<|j|dkr|j|=ddddS#1swxYwYdS#|j5|j|xxdzcc<|j|dkr|j|=dddw#1swxYwYwxYw)a Handle incoming connection :param connection: socket object usable to send and receive data on the connection :param workers_pool: pool where we can place tasks for the futher processing z1Failed to extract credentials, closing connectionNrz6Too many concurrent connections from uid=%s, rejectingr ) rrYrerZrrJrIrr:_process_connection)rMrr_pid_uid_gids r)rz Agent.handle_incoming_connections ,Z88 D$    NNN O O O       FF   ' - -$((q11T5QQQWY]^^^  """  - - - - - - - -  !$ ' ' '1 , ' ' '  - - - - - - - - - - - - - - - 4  $ $ZtT J J J+ 4 4%d+++q0+++(.!33-d3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4+ 4 4%d+++q0+++(.!33-d3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4sj8AAAC>CC#&C#+E /EE  E F"/F F"F F"F F"rrc`t|}||j|d} ||}n#t j$r\}tdt|dtj iYd}~| dSd}~wttjf$r4td||Y| dSwxYw | n#| wxYw | ||j|||dS||j||||dS#t(j$rtd YdSwxYw) Nignore)errorszJSON decode failed: %st_nameextraz5Connection read timed out or failed for pid=%s uid=%s)rrr)rrrrzRequest %s was rejected because our workers thread pool is full of tasks. Increase queuemaxsize or max_threads in configuration.)r settimeout _READ_TIMEOUTmakefile read_inputjsonJSONDecodeErrorrerstrrrrrYsockettimeoutrZrrrrr) rMrrrr current_cpufileobj input_dataes r)rzAgent._process_connection0s16d;; d0111!+!4!4H!4!E!E 11JJ#    LL1!!ffX~7G7G7L,M  O O O FFF        (    NNR ' ' '                  J       e!##D$=t.9d$LLLLL##D$#t$r1}t t dt|zd}~wwxYw| |j |S)z< Initialize MongoDB client for current task z9Cannot resolve tracing_task_id: no match found in storage)idall_idsrNz"Cannot resolve tracing_task_id: %s)r4r) rrdecodeKeyErrorr_keys RuntimeErrorrrAr6)rMr task_storagereal_idrs r)instantiate_mongo_clientzAgent.instantiate_mongo_client^so N011 @\@*<8??AAGG@@@#UVV%1*6*;*;*=*=??@@@@@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ N N NABCCc!ffLMM M N&&7>'@@ @sNB B3B>A11B5 B BB B B C,CCctd|j|j|}||j|jfS||}|}td||||j5|j|}||j|jfcdddSt|j|j kritt|j}t dt|j||j|t|||j|<dddn #1swxYwY||fS)z Returns a client and task from cache of API data or initialize client and GET task from MongoDB and add to cache zCached API data: %sNz,Adding new container in cache: %s --> %s, %sz9api_data_cache at capacity (%d), evicting oldest entry %s)r!r")rerrDrr!r"rget_taskrBr_MAX_CACHE_ENTRIESnextiterrTpopr )rMr cached_datarn_t oldest_keys r)rfzAgent.get_cached_or_loadss  *D,?@@@)--l;;  "%{'77 711,??    ! ! C&I 7 7 7  % J J -11,??K&");+;; J J J J J J J J4&''4+BBB!$t':";";<<  W 344jBBB#'' 3330@ FH1J1J1JD  - J J J J J J J J J J J J J J J "}s*E:BE::E>E>c tt5}d|D}dddn #1swxYwYn+#t$rtdYdSwxYwt |jD]c}|j5||jvr9||vr5t d||j |dddn #1swxYwYddS)z Cleanup an API data im-memory cache dict in order not store inactive (stopped, already completed) tasks there c6g|]}|Sr')r).0ks r) z0Agent.cleanup_api_data_cache..s HHHq HHHr(Nz,Unable to cleanup cache, storage unavailablez!Cleaning up inactive container %s) rrrrrerZlistrDrBrTr)rMr active_tasks_tasks r)rvzAgent.cleanup_api_data_caches  011 I\HHL4E4E4G4GHHH  I I I I I I I I I I I I I I I    NN> @ @ @ FF  $-224455 3 3E) 3 3D///E4M4MKK CUKKK'++E222 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3sFA A A AA A A $A54A5'AC66C: =C: c|d}|tj|std|dStjtt||}tj |std||dS| |\}}t d|j t|d|j5}||j|jdkr(t d  ddddS|||}t d || t d ||n#t*$rYnwxYw|xjd z c_||jdddn #1swxYwY|jr||j|jd kr"|jdkr||dSdSdS)aK Increment request ID in /usr/share/alt-php-xray/requests/{tracing_task_id} file Substitute request_id and tracing_task_id in request_data. Send request_data to ClickHouse :param request_data: original request data :param caller_uid: UID of the connecting process (from SO_PEERCRED) rNz*Rejecting request with invalid task id: %szSRejecting request from uid=%s for task %s: no matching task file in per-UID storagezProcessing task: %s)rrbrz*Tracing count is 0, nothing should be donezSending to ClickHousezSending to SmartAdvicer rd)rmatchrerZrWpathjoinrrisfilerfrTrlr is_manualrgrcrkupdate_request_datar?r@rrVfake_idrh complete_task) rMrrrowner_task_filerr"roupdated_request_datas r)rzAgent.process_request_datas$$56  !"(66 K+--- gll"C OO\CCO7>>/22 ? ...)),774 )4<888  -> ?&*n666 Q9@  ' '8O ' P P P!Q&& HIII Q Q Q Q Q Q Q Q$(#;#;L<@$B$B  KK/ 0 0 0   1 2 2 2  4555##$89999      # #q ( # #  ' '8O ' P P P1 Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q4 > 7  ( ( 6 6 6 ?f $ $);q)@)@   t $ $ $ $ $ % $)@)@s>AH AH /GH  GH G.H  HHrr"c|jdz|d<|j|d<|dD]C}|jdz|d<|j|d<|ddkr||d|d<Dtd|d|dtd ||S) z Substitute request_id and tracing_task_id :param data: original input :param task: a Task instance :return: updated input r request_idrrtype mysql_queryqueryz5Input updated: tracing_task_id = %s & request_id = %szFull updated input %s)rjrl hide_symbolsrerTrr)rMrr"items r)rzAgent.update_request_datas"/!3\"&, L A AD!%!3a!7D &*lD" #F|},, $ 1 1$w- @ @W  K"344dhh|6L6L N N N ,d333 r(r!zAPIClient instancerjrkc4|||dS)z: Update task counters in mongodb instance )rkrjN)update_counts_only)rMr!rjrks r)rizAgent.update_countss0 !! 0= " ? ? ? ? ?r(rctd|jtjd||jdS)z_ Stop and complete request_qty task :param _task: tracing task to stop zTask %s should be completedr N)rerTrlrdrr_run_complete_task_cmd)rMrs r)rzAgent.complete_tasksM  1 ( ( ( 1  ##EM22222r(c tjddd|jd|gdtjdS#tjtjf$r'}t d||Yd}~dSd}~wwxYw)Nzcloudlinux-xray-managerstopz --system_idz--tracing_task_idx)rstderrzFailed to complete task %s: %s) subprocess check_outputr6PIPETimeoutExpiredCalledProcessErrorrer)rMrlrs r)rzAgent._run_complete_task_cmds G  #)6t{#W%:?  4 4 4 4 4 4 ):+HI G G G LL97A F F F F F F F F F Gs,0A2 A--A2rc\d}tjd}tj|||S)zA Sanitize data in single quotes from MySQL query c|d}|d}d}tjd||d}|||p|S)zL Works with whole string in single or double quotes quotetrunccb|drdS|drdSdS)zE Works with characters inside quotes digit0symbolxN)group)inner_ms r) inner_replz8Agent.hide_symbols..replacer..inner_repl$s@==))3]]8,,3r(z.((?P\d)|(?P[^0-9_:;\-/',. \\]))in_quote)rresub)mqtr  sanitizeds r)replacerz$Agent.hide_symbols..replacersz  A  A   P)177:+>+>@@I,,AF,, ,r(zH(?P['"])(?P.*?)((?\.{3})))r compiler )rrpatterns r)rzAgent.hide_symbolss7  - - -2*lmmvgx555r()N)FN)r}N).r#r$r%__doc__rsrtrurpsutil cpu_countrPr\r`rVryrboolrrHrrrrCrrrr rrio TextIOBaserrrrr rrfrvrrrirr staticmethodrr'r(r)r+r+@s!"2!1!3!3a!7-V-//!3.f.0025)- "5"5"5"5J U U U Z Z Z77774333.*/%)))M)"&)c])/3))))V:> $ $C $C $)1# $ $ $ $ <3 <3 <*. <B???? 34 3D 3 3 3 3GGG6#6#666\666r(r+)=rrFrrrSrWrr r;rrrdtyping threadingrrrrrrr dataclassesr rexecutorr xrayr rxray.apiclientrxray.internal.constantsrrrxray.internal.exceptionsrrrErxray.internal.local_countersrrrxray.internal.typesrxray.internal.user_plugin_utilsrxray.internal.utilsrr TYPE_CHECKINGxray.apiclient.api_clientrrrr getLoggerr#rer+r'r(r)r+s   2222222222------------!!!!!! ++++++%%%%%%\\\\\\\\\\<<<<<<<<)))))) %$$$$$999999      8 $ $w6w6w6w6w6w6w6w6w6w6r(