
                         T   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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SKJr  SrSrS rS rS rS"S jrS r " S S\5      r " S S\5      r  " S S\5      r! " S S\5      r"S r#S r$S r%S r& " S  S!\'5      r(g)#zDebug apis layer.    )absolute_import)division)unicode_literalsN)
exceptions)errors)apis)config)log)	resources)retry)urllibdefaultc                    / nSnSnSnSnU  H  nU(       a  UR                  5       (       a  US-  nSnUS:X  a  U(       a  X6-  nOSnUS-  nMA  U(       d/  US:X  a  [        R                  " S5      eUS	:X  a  US
-  nMq  X&-  nMw  US:w  a  X6-  nM  US-  nUS:X  aK  X1;   a  UR                  U5      nO[	        U5      nUR                  U5        USR                  U5      -  nSnM  X6-  nM     U(       a  [        R                  " S5      eX!4$ )ap  Extracts {expression} substrings into a separate array.

Each substring of the form {expression} will be extracted into an array, and
each {expression} substring will be replaced with $N, where N is the index
of the extraced expression in the array. Any '$' sequence outside an
expression will be escaped with '$$'.

For example, given the input:
  'a={a}, b={b}'
 The return value would be:
  ('a=$0, b=$1', ['a', 'b'])

Args:
  format_string: The string to process.
Returns:
  string, [string] - The new format string and the array of expressions.
Raises:
  InvalidLogFormatException: if the string has unbalanced braces.
 r   F {   }z:There are too many "}" characters in the log format string$$$z${0}Tz:There are too many "{" characters in the log format string)isdigitr   InvalidLogFormatExceptionindexlenappendformat)format_stringexpressions
log_formatcurrent_expressionbrace_countneed_separatorcis           )lib/googlecloudsdk/api_lib/debug/debug.pySplitLogExpressionsr&   /   sI   ( +*+.a!))++CjNCx	  Qk	
c..HJ 	J8d
 	
 
cQk		, 23!+!


/
0fmmA&&
  	W Z 

*
*DF F		      c                 j   ^^ U4S jmU R                  S5      nSR                  U4S jU 5       5      $ )aD  Replaces each $N substring with the corresponding {expression}.

This function is intended for reconstructing an input expression string that
has been split using SplitLogExpressions. It is not intended for substituting
the expression results at log time.

Args:
  log_format: A string containing 0 or more $N substrings, where N is any
    valid index into the expressions array. Each such substring will be
    replaced by '{expression}', where "expression" is expressions[N].
  expressions: The expressions to substitute into the format string.
Returns:
  The combined string.
c                    >  SR                  T[        U R                  S5      SS  5         5      $ ! [         a    U R                  S5      s $ f = f)Nz{{{0}}}r   r   )r   intgroup
IndexError)mr   s    r%   GetExpression*MergeLogExpressions.<locals>.GetExpression   sN    k#aggajn*=>?? WWQZs   .2 AAr   r   c              3   T   >#    U  H  n[         R                  " S TU5      v   M     g7f)z\$\d+N)resub).0partr.   s     r%   	<genexpr>&MergeLogExpressions.<locals>.<genexpr>   s!     JED"&&=$77Es   %()splitjoin)r   r   partsr.   s    ` @r%   MergeLogExpressionsr:   |   s/     

4
 %	JEJ	JJr'   c                     SnSU R                   4SU R                  4SU R                  4/nU[        R                  R                  U5      -   $ )aA  Returns a URL to view a breakpoint in the browser.

Given a breakpoint, this transform will return a URL which will open the
snapshot's location in a debug view pointing at the snapshot.

Args:
  breakpoint: A breakpoint object with added information on project and
  debug target.
Returns:
  The URL for the breakpoint.
z2https://console.cloud.google.com/debug/fromgcloud?projectdbgeebp)r<   	target_ididr   parse	urlencode
breakpointdebug_view_urldatas      r%   DebugViewUrlrG      sU     H.*$$%
$$%Z]]
$
 
&,,006	66r'   c           
         SR                  U R                  U R                  U R                  =(       d    SUS9nU R                  (       a?  USR                  [
        R                  " SS[        U R                  5      S   5      US9-  nU$ )	a|  Returns an advanced log query string for use with gcloud logging read.

Args:
  breakpoint: A breakpoint object with added information on project, service,
    and debug target.
  separator: A string to append between conditions
Returns:
  A log query suitable for use with gcloud logging read.
Raises:
  InvalidLogFormatException if the breakpoint has an invalid log expression.
zresource.type=gae_app{sep}logName:request_log{sep}resource.labels.module_id="{service}"{sep}resource.labels.version_id="{version}"{sep}severity={logLevel}INFO)serviceversionlogLevelsepz{sep}"{text}"z
\$([0-9]+)z" "r   )textrM   )r   rJ   rK   rL   logMessageFormatr1   r2   r&   )rD   	separatorquerys      r%   LogQueryV2StringrR      s     $V$$j.@.@&&0&i $ A     
_##VVM6'
(C(CDQGI $  E 
,r'   c                     SnSU R                   4S[        U SS9S-   4/nU[        R                  R	                  U5      -   $ )ad  Returns a URL to view the output for a logpoint.

Given a breakpoint in an appengine service, this transform will return a URL
which will open the log viewer to the request log for the service.

Args:
  breakpoint: A breakpoint object with added information on project, service,
    debug target, and logQuery.
Returns:
  The URL for the appropriate logs.
z&https://console.cloud.google.com/logs?r<   advancedFilter
)rP   )r<   rR   r   rA   rB   rC   s      r%   
LogViewUrlrV      sO     <.*$$%)*ELM
$ 
&,,006	66r'   c                       \ rS rSrSr\R                  " 5       rSrSr	S r
SR                  \R                  5      r  S
S jrS	rg)DebugObject   z"Base class for debug api wrappers.SNAPSHOTLOGPOINTc                    XR                   :X  a*  U R                  R                  R                  R                  $ XR
                  :X  a*  U R                  R                  R                  R                  $ [        R                  " U5      eN)	SNAPSHOT_TYPE_debug_messages
BreakpointActionValueValuesEnumCAPTURELOGPOINT_TYPELOGr   InvalidBreakpointTypeError)self	type_names     r%   BreakpointActionDebugObject.BreakpointAction   sg    &&&!!,,BBJJJ&&&!!,,BBFFF

+
+I
66r'   zgoogle.com/gcloud/{0}Nc                    U=(       d    [         R                  " SS5      U l        U=(       d    [         R                  " SS5      U l        U=(       d    [         R                  " SS5      U l        U=(       d    [         R                  " SS5      U l        [        R                  R                  5       U l
        U R                  R                  SS5        g)z+Sets up class with instantiated api client.clouddebuggerv2cloudresourcemanagerv1beta1N)r   GetClientInstance_debug_clientGetMessagesModuler_   _resource_client_resource_messagesr   REGISTRYClone_resource_parserRegisterApiByName)rf   debug_clientdebug_messagesresource_clientresource_messagess        r%   __init__DebugObject.__init__   s     	E..E 	 	G$00$G 	 	 	B5yA 	 	 	B5yA 	 &..446D++OTBr'   )rp   r_   rr   rs   rv   NNNN)__name__
__module____qualname____firstlineno____doc__	threadingLock_client_lockr^   rc   rh   r   r	   CLOUD_SDK_VERSIONCLIENT_VERSIONr|   __static_attributes__ r'   r%   rX   rX      sH    *
 !, --7 +11&2J2JK.7;7;Cr'   rX   c                   ^   ^  \ rS rSrSr  S
U 4S jjrSS jrS rSS jrS r	SS jr
S	rU =r$ )Debuggeri  z/Abstracts Cloud Debugger service for a project.c                 6   > [         [        U ]  X#XES9  Xl        g N)rx   ry   rz   r{   )superr   r|   _project)rf   r<   rx   ry   rz   r{   	__class__s         r%   r|   Debugger.__init__  s%    	(D"!' # N Mr'   c                    U R                   R                  U R                  UU R                  S9n U R                  R
                  R                  U5      nUR                   Vs/ s H  n[        U5      PM     nnU(       d  [        U5      $ U$ ! [        R                   a  n[        R                  " U5      eSnAff = fs  snf )a  Lists all debug targets registered with the debug service.

Args:
  include_inactive: If true, also include debuggees that are not currently
    running.
  include_stale: If false, filter out any debuggees that refer to
    stale minor versions. A debugge represents a stale minor version if it
    meets the following criteria:
        1. It has a minorversion label.
        2. All other debuggees with the same name (i.e., all debuggees with
           the same module and version, in the case of app engine) have a
           minorversion label.
        3. The minorversion value for the debuggee is less than the
           minorversion value for at least one other debuggee with the same
           name.
Returns:
  [Debuggee] A list of debuggees.
)r<   includeInactiveclientVersionN)r_   )ClouddebuggerDebuggerDebuggeesListRequestr   r   rp   debugger_debuggeesListapitools_exceptions	HttpErrorr   UnknownHttpError	debuggeesDebuggee_FilterStaleMinorVersions)rf   include_inactiveinclude_stalerequestresponseerrordebuggeeresults           r%   ListDebuggeesDebugger.ListDebuggees  s    & ""LL/?)) M +G+##66;;GDh 2:1C1CD1CXhx 1CFD&v..M (( +##E**+ Es   %B $CB>#B99B>c                     U R                  5       n[        U5      S:X  a  US   $ U(       d  [        R                  " 5       e[        R                  " SU5      e)aM  Find the default debuggee.

Returns:
  The default debug target, which is either the only target available
  or the latest minor version of the application, if all targets have the
  same module and version.
Raises:
  errors.NoDebuggeeError if no debuggee was found.
  errors.MultipleDebuggeesError if there is not a unique default.
r   r   N)r   r   r   NoDebuggeeErrorMultipleDebuggeesError)rf   r   s     r%   DefaultDebuggeeDebugger.DefaultDebuggee.  sO     ""$I
9~q\""$$ 
'
'i
88r'   c                 ^   U(       dJ  U R                  5       n[        R                  R                  SR	                  UR
                  5      5        U$  U R                  5       nU R                  X15      $ ! [        R                   a     Of = fU R                  SSS9nU R                  X15      $ )a  Find the unique debuggee matching the given pattern.

Args:
  pattern: A string containing a debuggee ID or a regular expression that
    matches a single debuggee's name or description. If it matches any
    debuggee name, the description will not be inspected.
Returns:
  The matching Debuggee.
Raises:
  errors.MultipleDebuggeesError if the pattern matches multiple debuggees.
  errors.NoDebuggeeError if the pattern matches no debuggees.
z6Debug target not specified. Using default target: {0}
T)r   r   )
r   r
   statuswriter   namer   _FilterDebuggeeListr   r   )rf   patternr   all_debuggeess       r%   FindDebuggeeDebugger.FindDebuggeeD  s     %%'h	jj
C
J
Jmm o ((*m%%m==!! 
 &&59 ' ;M##M;;s    A4 4B
Bc                    U(       d  [         R                  " 5       e[        U5      nU Vs/ s H  oDR                  U:X  d  M  UPM     snU Vs/ s H  oBUR                  :X  d  M  UPM     sn-   nU(       d  [
        R                  " U5      nU Vs/ s H&  oFR                  UR                  5      (       d  M$  UPM(     snU Vs/ s H:  nUR                  (       d  M  UR                  UR                  5      (       d  M8  UPM<     sn-   nU(       d  [         R                  " X!S9e[        S U 5       5      n[        U5      S:  a  [         R                  " X%5      eUS   $ s  snf s  snf s  snf s  snf )a  Finds the debuggee which matches the given pattern.

Args:
  all_debuggees: A list of debuggees to search.
  pattern: A string containing a debuggee ID or a regular expression that
    matches a single debuggee's name or description. If it matches any
    debuggee name, the description will not be inspected.
Returns:
  The matching Debuggee.
Raises:
  errors.MultipleDebuggeesError if the pattern matches multiple debuggees.
  errors.NoDebuggeeError if the pattern matches no debuggees.
)r   c              3   8   #    U  H  oR                   v   M     g 7fr]   )r?   )r3   ds     r%   r5   /Debugger._FilterDebuggeeList.<locals>.<genexpr>  s     6Iq{{Is   r   r   )r   r   r   r?   r   r1   compilesearchdescriptionsetr   r   )rf   r   r   latest_debuggeesr   r   match_redebuggee_idss           r%   r   Debugger._FilterDebuggeeListd  s@    ""$$0? +E]kkW.D!]E-C-AFF1B!-CDI G$h&
B&//!&&*A1&
B& @&mm  ( > & @@ 
 ""7DD6I66L
<1))'== Q<' FC C@s5   E"E"E'&E'#E,9E,E1E1 E1c           	      z   U(       d  U R                   nU R                  R                  U R                  R                  U R                  UX#S9S9n U R
                  R                  R                  U5      n[        UR                  5      $ ! [        R                   a  n[        R                  " U5      eSnAff = f)a  Register a debuggee with the Cloud Debugger.

This method is primarily intended to simplify testing, since it registering
a debuggee is only a small part of the functionality of a debug agent, and
the rest of the API is not supported here.
Args:
  description: A concise description of the debuggee.
  uniquifier: A string uniquely identifying the debug target. Note that the
    uniquifier distinguishes between different deployments of a service,
    not between different replicas of a single deployment. I.e., all
    replicas of a single deployment should report the same uniquifier.
  agent_version: A string describing the program registering the debuggee.
    Defaults to "google.com/gcloud/NNN" where NNN is the gcloud version.
Returns:
  The registered Debuggee.
)r<   r   
uniquifieragentVersion)r   N)r   r_   RegisterDebuggeeRequestr   r   rp   controller_debuggeesRegisterr   r   r   r   r   )rf   r   r   agent_versionr   r   r   s          r%   RegisterDebuggeeDebugger.RegisterDebuggee  s    " ))m""::%%..MM{! / ? ; @G+##88AA'Jh H%%&& (( +##E**+s   %B B:B55B:)r   r~   )FFr]   )r   r   r   r   r   r|   r   r   r   r   r   r   __classcell__r   s   @r%   r   r     s2    7@D7; D9,<@(T' 'r'   r   c                     ^  \ rS rSrSr  SU 4S jjrS rS rS r\	S 5       r
\	S 5       r\	S	 5       r\	S
 5       rS rS rS r   SS jr  SS jr  SS jrS r  SS jr  SS jrSS jrS rS rS rSrU =r$ )r   i  zRepresents a single debuggee.c                 0  > [         [        U ]  X#XES9  UR                  U l        UR                  U l        UR                  U l        UR                  U l        UR                  U l
        UR                  U l        UR                  U l        UR                  U l        UR"                  U l        UR$                  U l        0 U l        UR(                  (       aA  UR(                  R*                   H&  nUR,                  U R(                  UR.                  '   M(     g g r   )r   r   r|   r<   r   r   r   extSourceContextsext_source_contextsr@   r?   
isDisabledis_disabled
isInactiveis_inactivesourceContextssource_contextsr   r   target_uniquifierlabelsadditionalPropertiesvaluekey)rf   messagerx   ry   rz   r{   lr   s          r%   r|   Debuggee.__init__  s    	(D"!' # N ??DL --D**D&88DZZDN))D))D"11D..DK$//DDK~~~~22!WWAEE 3 r'   c                 l    [        XR                  5      =(       a    U R                  UR                  :H  $ r]   )
isinstancer   r?   rf   others     r%   __eq__Debuggee.__eq__  s(    unn- .NNeoo-/r'   c                 .    U R                  U5      (       + $ r]   )r   r   s     r%   __ne__Debuggee.__ne__  s    {{5!!!r'   c                     SR                  U R                  U R                  U R                  (       a  SR                  U R                  5      5      $ S5      $ )Nz<id={0}, name={1}{2}>z, description={0}r   )r   r?   r   r   rf   s    r%   __repr__Debuggee.__repr__  sN    "))		 $7#=#=d>N>N#O% %!#% %r'   c                 :    U R                   R                  SS 5      $ )Nmoduler   getr   s    r%   rJ   Debuggee.service  s    ;;??8T**r'   c                 :    U R                   R                  SS 5      $ )NrK   r   r   s    r%   rK   Debuggee.version  s    ;;??9d++r'   c                 :    U R                   R                  SS 5      $ )Nminorversionr   r   s    r%   r   Debuggee.minorversion  s    ;;??>400r'   c                     U R                   nU R                  nU(       d  U(       a"  U=(       d    [        S-   U=(       d    [        -   $ U R                  $ )N-)rJ   rK   DEFAULT_MODULEDEFAULT_VERSIONr   )rf   rJ   rK   s      r%   r   Debuggee.name  s?    llGllG''3.'2L_MMr'   c                 4    U(       d  gXR                   :X  a  gg)NrD   snapshotlogpoint)r^   )rf   restrict_to_types     r%   _BreakpointDescriptionDebuggee._BreakpointDescription  s    	//	/r'   c                 D   U R                   R                  XR                  U R                  S9n U R                  R
                  R                  U5      nU R                  UR                  5      $ ! [        R                   a  n[        R                  " U5      eSnAff = f)zGets the details for a breakpoint.

Args:
  breakpoint_id: A breakpoint ID.
Returns:
  The full Breakpoint message for the ID.
breakpointId
debuggeeIdr   N)r_   3ClouddebuggerDebuggerDebuggeesBreakpointsGetRequestr?   r   rp   debugger_debuggees_breakpointsGetr   r   r   r   AddTargetInforD   )rf   breakpoint_idr   r   r   s        r%   GetBreakpointDebuggee.GetBreakpoint  s     ##BB -..!%!4!4 C 6 +##BBFFwOh h1122 (( +##E**+s   %A0 0BBBc                    U R                   R                  XR                  U R                  S9n U R                  R
                  R                  U5        g! [        R                   a  n[        R                  " U5      eSnAff = f)z?Deletes a breakpoint.

Args:
  breakpoint_id: A breakpoint ID.
r  N)r_   6ClouddebuggerDebuggerDebuggeesBreakpointsDeleteRequestr?   r   rp   r  Deleter   r   r   r   )rf   r	  r   r   s       r%   DeleteBreakpointDebuggee.DeleteBreakpoint  sy     ##EE -..!%!4!4 F 6 +
77>>wG(( +##E**+s   %A B*B  Bc                   ^  U=(       d    / nU=(       d    / n[        U Vs/ s H8  nT R                  R                  UST R                  0SS9R	                  5       PM:     sn5      n/ n	U H/  n U	R                  [        R                  " SU-   S-   5      5        M1     T R                  R                  T R                  UU=(       d    [        U5      T R                  S9n T R                   R"                  R%                  U5      nU	(       d#  U(       d  T R-                  UR.                  U5      $ U(       a0  UR.                   Vs/ s H  n[1        XU	5      (       d  M  UPM     nnOBUR.                   Vs/ s H+  n[1        XUR2                  (       a  / OU	5      (       d  M)  UPM-     nnU[        U Vs/ s H  oR4                  PM     sn5      -
  nU(       a&  [        R6                  " UT R9                  U5      5      eU	 H`  nU Vs/ s H  n[1        U/ U/5      (       d  M  UPM     sn(       a  M2  [        R:                  " T R9                  U5      UR<                  5      e   T R-                  X5      nU(       a@  U 4S	 jnU Vs/ s H-  nU" U5      (       a  T R?                  UR4                  5      OUPM/     nnU$ s  snf ! [        R                   a*  n
[        R                  " SR                  Xz5      5      eSn
A
ff = f! [&        R(                   a  n[        R*                  " U5      eSnAff = fs  snf s  snf s  snf s  snf s  snf )
aY  Returns all breakpoints matching the given IDs or patterns.

Lists all breakpoints for this debuggee, and returns every breakpoint
where the location field contains the given pattern or the ID is exactly
equal to the pattern (there can be at most one breakpoint matching by ID).

Args:
  location_regexp: A list of regular expressions to compare against the
    location ('path:line') of the breakpoints. If both location_regexp and
    resource_ids are empty or None, all breakpoints will be returned.
  resource_ids: Zero or more resource IDs in the form expected by the
    resource parser. These breakpoints will be retrieved regardless
    of the include_all_users or include_inactive flags
  include_all_users: If true, search breakpoints created by all users.
  include_inactive: If true, search breakpoints that are in the final state.
    This option controls whether regular expressions can match inactive
    breakpoints. If an object is specified by ID, it will be returned
    whether or not this flag is set.
  restrict_to_type: An optional breakpoint type (LOGPOINT_TYPE or
    SNAPSHOT_TYPE)
  full_details: If true, issue a GetBreakpoint request for every result to
    get full details including the call stack and variable table.
Returns:
  A list of all matching breakpoints.
Raises:
  InvalidLocationException if a regular expression is not valid.
r  z,clouddebugger.debugger.debuggees.breakpoints)params
collectionz^(.*/)?(z)$zHThe location pattern "{0}" is not a valid Python regular expression: {1}N)r  includeAllUsersr   r   c                   > U R                   (       + =(       d(    U R                   TR                  TR                  5      :H  =(       aA    U R                  =(       a.    U R                  =(       a    U R                  R
                  (       + $ r]   )actionrh   r^   isFinalStater   isError)r>   rf   s    r%   IsCompletedSnapshot5Debuggee.ListBreakpoints.<locals>.IsCompletedSnapshotf  sa    YY Hd33D4F4FGGJJ)+)Hryy7H7H$I	Kr'   ) r   rv   Parser?   Namer   r1   r   r   r   InvalidLocationExceptionr   r_   4ClouddebuggerDebuggerDebuggeesBreakpointsListRequestboolr   rp   r  r   r   r   r   _FilteredDictListWithInfobreakpoints_BreakpointMatchesIdOrRegexpr  r@   BreakpointNotFoundErrorr   NoMatchErrorr   r
  )rf   location_regexpresource_idsinclude_all_usersr   r   full_detailsridspatternser   r   r   r>   r   missing_idspr  s   `                  r%   ListBreakpointsDebuggee.ListBreakpoints  s4   <  %2L%+O
 	  Q 
			$	$|T^^4E 
% 
GGKtv
N 	 !C
 H,

;?T#9:;  ##CC"nn#4#3#@tCy!%!4!4	 D 6 +##BBGGPh C++H,@,@,<> >  &11 D1r/B 1f Df &11 C1r/2??RB 1f C V4VrUUV455K**
t223CDF F ! <6R-b"qc: 6 < <!!$"="=>N"O"#))- 	- 
 ++FEFK b (;2'>'>$

RUU
#B
F   MC	  XX ,--$fQl, 	,, (( +##E**+DC 5<se   ?J>/+K!%L L6L65(L;!L;3M 
M"M4M
L%K<<LL3L..L3c                 
   SnU(       aw  U R                   R                  R                  [        R                  " U5       VVs/ s H2  u  pxU R                   R                  R                  R                  XxS9PM4     snnS9nU R                  U5      nU(       d  / nU R                   R                  U R                  U R                   R                  XUXdU R                   R                  R                  R                  S9U R                  S9n	 U R                  R                  R                  U	5      n
U R'                  U
R(                  5      $ s  snnf ! [        R                    a  n["        R$                  " U5      eSnAff = f)a  Creates a "snapshot" breakpoint.

Args:
  location: The breakpoint source location, which will be interpreted by
    the debug agents on the machines running the Debuggee. Usually of the
    form file:line-number
  condition: An optional conditional expression in the target's programming
    language. The snapshot will be taken when the expression is true.
  expressions: A list of expressions to evaluate when the snapshot is
    taken.
  user_email: The email of the user who created the snapshot.
  labels: A dictionary containing key-value pairs which will be stored
    with the snapshot definition and reported when the snapshot is queried.
Returns:
  The created Breakpoint message.
Nr   r   r   )location	conditionr   r   	userEmailr  r  rD   r   )r_   r`   LabelsValuesix	iteritemsAdditionalProperty_LocationFromString3ClouddebuggerDebuggerDebuggeesBreakpointsSetRequestr?   ra   rb   r   rp   r  Setr   r   r   r   r  rD   )rf   r4  r5  r   
user_emailr   labels_valuer   r   r   r   r   s               r%   CreateSnapshotDebuggee.CreateSnapshotp  sj   $ L))44@@ !$f 5 7 !6*# ""--99LL M ( 5 7 A 8l
 ''1Hk;;~~++66!K#,,77--gg	 7 8
 -- 	< 	/ +##BBFFwOh h1122+ 7& (( +##E**+s   9E
%E F'E==Fc                    U(       d  [         R                  " S5      eU(       d  [         R                  " S5      eSnU(       aw  U R                  R                  R                  [        R                  " U5       VV	s/ s H2  u  pU R                  R                  R
                  R                  XS9PM4     sn	nS9nU R                  U5      nU(       a3  U R                  R                  R                  UR                  5       5      n[        U5      u  pU R                  R                  U R                  U R                  R	                  XUXXuU R                  R                  R                  R                   S9U R"                  S9n U R$                  R&                  R)                  U5      nU R1                  UR2                  5      $ s  sn	nf ! [*        R,                   a  n[         R.                  " U5      eSnAff = f)a  Creates a logpoint in the debuggee.

Args:
  location: The breakpoint source location, which will be interpreted by
    the debug agents on the machines running the Debuggee. Usually of the
    form file:line-number
  log_format_string: The message to log, optionally containin {expression}-
    style formatting.
  log_level: String (case-insensitive), one of 'info', 'warning', or
    'error', indicating the log level that should be used for logging.
  condition: An optional conditional expression in the target's programming
    language. The snapshot will be taken when the expression is true.
  user_email: The email of the user who created the snapshot.
  labels: A dictionary containing key-value pairs which will be stored
    with the snapshot definition and reported when the snapshot is queried.
Returns:
  The created Breakpoint message.
Raises:
  InvalidLocationException: if location is empty or malformed.
  InvalidLogFormatException: if log_format is empty or malformed.
zThe location must not be empty.z(The log format string must not be empty.Nr2  r3  )r4  r5  rL   rO   r   r   r6  r  r7  )r   r  r   r_   r`   r8  r9  r:  r;  r<  LogLevelValueValuesEnumupperr&   r=  r?   ra   rd   r   rp   r  r>  r   r   r   r  rD   )rf   r4  log_format_string	log_levelr5  r?  r   r@  r   r   log_message_formatr   r   r   r   s                  r%   CreateLogpointDebuggee.CreateLogpoint  s   . ++
+- -,,
46 6L))44@@ !$f 5 7 !6*# ""--99LL M ( 5 7 A 8l
 ''1H



)
)
A
Aoo!  '::K&L#;;~~++66!!3#,,77--cc 7 4 -- 	< 	/ +##BBFFwOh h11223 7. (( +##E**+s   <9G
%G G; G66G;c                     U R                      U R                  R                  R                  U5      sS S S 5        $ ! , (       d  f       g = fr]   )r   rp   r  r  )rf   r   s     r%   _CallGetDebuggee._CallGet  s1    			>>BB7K 
		s	   %<
A
c                    ^ U4S jn U R                  XUUS9$ ! [        R                   a  n[        R                  " U5      eSnAff = f)a  Waits for a breakpoint to be set by at least one agent.

  Breakpoint set can be detected in two ways: it can be completed, or the
  location may change if the breakpoint could not be set at the specified
  location. A breakpoint may also be set without any change being reported
  to the server, in which case this function will wait until the timeout
  is reached.
Args:
  breakpoint_id: A breakpoint ID.
  original_location: string, the user-specified breakpoint location. If a
    response has a different location, the function will return immediately.
  timeout: The number of seconds to wait for completion.
  retry_ms: Milliseconds to wait betweeen retries.
Returns:
  The Breakpoint message, or None if the breakpoint did not get set before
  the timeout.
c                    > U R                   R                  =(       d+    T=(       a"    T[        U R                   R                  5      :g  $ r]   )rD   r  _FormatLocationr4  )r)  original_locations    r%   MovedOrFinal3Debuggee.WaitForBreakpointSet.<locals>.MovedOrFinal  s<    
,,
#
# H G0E0E FFIr'   )r	  timeoutretry_mscompletion_testN)WaitForBreakpointr   r   r   r   )rf   r	  rQ  rT  rU  rR  r   s     `    r%   WaitForBreakpointSetDebuggee.WaitForBreakpointSet  sW    &I
+##%& $ ( ( (( +##E**+s    A	AA	c                   ^ T(       d  S mU4S jn[         R                  " Ub  SU-  OSSS9nU R                  R                  XR                  U R
                  S9n UR                  U R                  U/UUS9nT" U5      (       d  gU R                  UR                  5      $ ! [         R                   a     g[        R                   a  n	[        R                  " U	5      eSn	A	ff = f)a  Waits for a breakpoint to be completed.

Args:
  breakpoint_id: A breakpoint ID.
  timeout: The number of seconds to wait for completion.
  retry_ms: Milliseconds to wait betweeen retries.
  completion_test: A function that accepts a Breakpoint message and
    returns True if the breakpoint wait is not finished. If not specified,
    defaults to a function which just checks the isFinalState flag.
Returns:
  The Breakpoint message, or None if the breakpoint did not complete before
  the timeout,
c                 .    U R                   R                  $ r]   )rD   r  )r)  s    r%   <lambda>,Debuggee.WaitForBreakpoint.<locals>.<lambda>
  s    !,,";";r'   c                    > T" U 5      (       + $ r]   r   )r)  _rV  s     r%   r\  r]    s     22r'   Ni  )max_wait_mswait_ceiling_msr  )should_retry_ifsleep_ms)r   Retryerr_   r  r?   r   RetryOnResultrL  RetryExceptionr   r   r   r   r  rD   )
rf   r	  rT  rU  rV  retry_ifretryerr   r   r   s
       `     r%   rW  Debuggee.WaitForBreakpoint  s     ;o2Hmm$+$7DLTG ##BB -..!%!4!4 C 6 +$$T]]WI5=.6 % 8f 6""f//00  (( +##E**+s   B$ $C(:C(C##C(c                     [        X#5      nU H  nUR                  X5        M     UR                  5       nU Vs/ s H  oUU;   d  M
  Xe   PM     sn$ s  snf )a  Waits for one or more breakpoints to complete.

Args:
  ids: A list of breakpoint IDs.
  wait_all: If True, wait for all breakpoints to complete. Otherwise, wait
    for any breakpoint to complete.
  timeout: The number of seconds to wait for completion.
Returns:
  The completed Breakpoint messages, in the order requested. If wait_all was
  specified and the timeout was reached, the result will still comprise the
  completed Breakpoints.
)_BreakpointWaiter	AddTargetWait)rf   r*  wait_allrT  waiterr$   resultss          r%   WaitForMultipleBreakpoints#Debuggee.WaitForMultipleBreakpoints!  sQ     x1Ft kkmG #41G|JGJ444s   	AAc           	         [        UU R                  U R                  U R                  U R                  U R
                  S.S9nUR                  U R                  R                  R                  R                  :X  a>  UR                  (       d-  U R                  R                  R                  R                  US'   UR                  c  SUS'   UR                  (       a  [!        UR                  5      US'   UR"                  (       a4  [%        UR"                  UR&                  5      US'   UR)                  S5        UR*                  (       a  UR*                  R,                  (       df  UR                  U R/                  U R0                  5      :X  a/  U R2                  (       a  [5        U5      US	'   [7        U5      US
'   U$ [9        U5      US'   U$ )a  Converts a message into an object with added debuggee information.

Args:
  message: A message returned from a debug API call.
Returns:
  An object including the fields of the original object plus the following
  fields: project, target_uniquifier, and target_id.
)r<   r   r?   rJ   rK   )hidden_fieldsrL   Fr  r4  rO   r   logQuery
logViewUrlconsoleViewUrl)_MessageDictr<   r   r?   rJ   rK   r  r_   r`   ra   rd   rL   rD  rI   r  r4  rP  rO   r:   r   HideExistingFieldr   r  rh   rc   r   rR   rV   rG   )rf   r   r   s      r%   r  Debuggee.AddTargetInfo4  sz    '<<!33^^<<<<2! "F 	''==AA	B



)
)
A
A
F
F Z #$f^ *7+;+;<fZ#6w7O7O7>7J7J$Lf }->>!7!7	4001C1CD	D /7&
!+F!3&
 M $0#7 Mr'   c                 
   UR                  S5      n[        U5      S:w  a  [        R                  " S5      e U R                  R                  US   [        US   5      S9$ ! [         a    [        R                  " S5      ef = f)zConverts a file:line location string into a SourceLocation.

Args:
  location: A string of the form file:line.
Returns:
  The corresponding SourceLocation message.
Raises:
  InvalidLocationException: if the line is not of the form path:line
:   z(Location must be of the form "path:line"r   r   )pathlinezJLocation must be of the form "path:line", where "line" must be an integer.)r7   r   r   r  r_   SourceLocationr*   
ValueError)rf   r4  
componentss      r%   r<  Debuggee._LocationFromStringb  s     $J
:!++
46 6!!00jm69*Q-6H 1 J J ++ s   (A! !!Bc                     U Vs/ s H^  nU(       aC  UR                   U R                  U5      :X  d$  UR                   (       a  M<  X R                  :X  d  MM  U R                  U5      PM`     sn$ s  snf )a<  Filters a result list to contain only breakpoints of the given type.

Args:
  result: A list of breakpoint messages, to be filtered.
  restrict_to_type: An optional breakpoint type. If None, no filtering
    will be done.
Returns:
  The filtered result, converted to equivalent dicts with debug info fields
  added.
)r  rh   r^   r  )rf   r   r   r)  s       r%   r   "Debuggee._FilteredDictListWithInfox  sm     ,2 J6a#xx4001ABBHH " "25G5G!G "Dq!6 J J Js   ;A-A-A-)r   r   r   r   r   r   r<   r   r   r?   r   r~   )NNFFNF)N  )Nr  N)FN)r   r   r   r   r   r|   r   r   r   propertyrJ   rK   r   r   r   r
  r  r/  rA  rI  rL  rX  rW  rq  r  r<  r   r   r   r   s   @r%   r   r     s    %@D7;%(/"%
 + + , , 1 1  3$+ @D@E:?bH BF-1*3X CG=A93vL LP$'+> EH(,%1N5&,\,J Jr'   r   c                   6    \ rS rSrSrS rS rS rS rS r	Sr
g	)
rk  i  as  Waits for multiple breakpoints.

Attributes:
  _result_lock: Lock for modifications to all fields
  _done: Flag to indicate that the wait condition is satisfied and wait
      should stop even if some threads are not finished.
  _threads: The list of active threads
  _results: The set of completed breakpoints.
  _failures: All exceptions which caused any thread to stop waiting.
  _wait_all: If true, wait for all breakpoints to complete, else wait for
      any breakpoint to complete. Controls whether to set _done after any
      breakpoint completes.
  _timeout: Mazimum time (in ms) to wait for breakpoints to complete.
c                     [         R                  " 5       U l        SU l        / U l        0 U l        / U l        Xl        X l        g )NF)	r   r   _result_lock_done_threads_results	_failures	_wait_all_timeout)rf   rn  rT  s      r%   r|   _BreakpointWaiter.__init__  s7    !(DDJDMDMDNNMr'   c                     UR                   R                  (       a  gU R                     U R                  sS S S 5        $ ! , (       d  f       g = f)NT)rD   r  r  r  )rf   r   s     r%   _IsComplete_BreakpointWaiter._IsComplete  s0    ''			ZZ 
		s	   ?
Ac                 p    UR                  X R                  U R                  S9nU(       d.  U R                     U R                  (       d  SU l        S S S 5        g UR                  (       a<  U R                     X0R                  U'   U R                  (       d  SU l        S S S 5        g g ! , (       d  f       g = f! , (       d  f       g = f! [        R                   aV  nU R                     U R                  R                  U5        SU l        S S S 5         S nAg ! , (       d  f        S nAg = fS nAff = f)N)rT  rV  T)rW  r  r  r  r  r  r  r  r   
DebugErrorr  r   )rf   r   r	  rD   r,  s        r%   _WaitForOne_BreakpointWaiter._WaitForOne  s    --
** . ,j DJ  			 	 )3--
&DJ  
!	  	  a 
 sv   7C B)C C 8'B:C )
B73C 7C :
CC C D5D0+#DD0
D-	%D0-D00D5c                 v    U R                   R                  [        R                  " U R                  X4S95        g )N)targetargs)r  r   r   Threadr  )rf   r   r	  s      r%   rl  _BreakpointWaiter.AddTarget  s0    MM 0 0'7	9:r'   c                     U R                    H  nUR                  5         M     U R                    H  nUR                  5         M     U R                  (       a  U R                  S   eU R                  $ )Nr   )r  startr8   r  r  )rf   ts     r%   rm  _BreakpointWaiter.Wait  sP    ]]ggi ]]ffh ~~NN1==r'   )r  r  r  r  r  r  r  N)r   r   r   r   r   r|   r  r  rl  rm  r   r   r'   r%   rk  rk    s     *:
r'   rk  c                 ^    U (       d  g SR                  U R                  U R                  5      $ )Nz{0}:{1})r   r~  r  )r4  s    r%   rP  rP    s#    				(--	77r'   c                     U R                   U;   a  gU R                  (       d  g[        U R                  5      nU H  nUR                  U5      (       d  M    g   g)ao  Check if a breakpoint matches any of the given IDs or regexps.

Args:
  breakpoint: Any _debug_messages.Breakpoint message object.
  ids: A set of strings to search for exact matches on breakpoint ID.
  patterns: A list of regular expressions to match against the file:line
    location of the breakpoint.
Returns:
  True if the breakpoint matches any ID or pattern.
TF)r@   r4  rP  match)rD   r*  r+  r4  r.  s        r%   r"  r"    sP     ]]c			Z001(awwx  
r'   c                 6   0 nU  HA  nUR                   U;   a  XR                      R                  U5        M2  U/XR                   '   MC     / nUR                  5        H9  n[        U5      nU(       a  UR                  U5        M(  UR	                  U5        M;     U$ )am  Filter out any debugees referring to a stale minor version.

Args:
  debuggees: A list of Debuggee objects.
Returns:
  A filtered list containing only the debuggees denoting the most recent
  minor version with the given name. If any debuggee with a given name does
  not have a 'minorversion' label, the resulting list will contain all
  debuggees with that name.
)r   r   values_FindLatestMinorVersionextend)r   bynamer   r   	name_listlatests         r%   r   r     s     &h}}]]""8,'jf]]	  &==?i$Y/FmmFmmI # 
-r'   c                 &   U (       d  gSnSnSnU  Hk  nU(       d  UR                   nOX4R                   :w  a    gUR                  R                  SS5      nU(       d    g [        U5      nU(       a  XR:  a  UnUnMk  Mm     U$ ! [         a       gf = f)aq  Given a list of debuggees, find the one with the highest minor version.

Args:
  debuggees: A list of Debuggee objects.
Returns:
  If all debuggees have the same name, return the one with the highest
  integer value in its 'minorversion' label. If any member of the list does
  not have a minor version, or if elements of the list have different
  names, returns None.
Nr   r   )r   r   r   r*   r  )r   bestbest_versionr   r   minor_versions         r%   r  r    s     
	$,	$aVVd	HHLL3M-(m]9$ :   
+  s   B
BBc                   <   ^  \ rS rSrSrSU 4S jjrS rS rSrU =r	$ )rx  i*  zqAn extensible wrapper around message data.

Fields can be added as dictionary items and retrieved as attributes.
c                 >  > [         [        U ]  5         [        U5      R                  U l        U(       a  X l        O0 U l        UR                  5        HG  n[        XR                  5      nU(       d  X@R                  UR                  '   M9  X@UR                  '   MI     g r]   )
r   rx  r|   typer   
_orig_type_hidden_fields
all_fieldsgetattrr   )rf   r   rt  fieldr   r   s        r%   r|   _MessageDict.__init__0  st    	,&(7m,,DO)d##%gzz*e*/EJJ' UZZ &r'   c                     X;   a  X   $ XR                   ;   a  U R                   U   $ [        SR                  U R                  U5      5      e)Nz(Type "{0}" does not have attribute "{1}")r  AttributeErrorr   r  )rf   attrs     r%   __getattr___MessageDict.__getattr__>  sP    |Z"""  &&
CJJ    r'   c                 b    XR                   ;   a  g U R                  US 5      U R                   U'   g r]   )r  pop)rf   
field_names     r%   ry  _MessageDict.HideExistingFieldF  s,    (((&*hhz4&@D
#r'   )r  r  r]   )
r   r   r   r   r   r|   r  ry  r   r   r   s   @r%   rx  rx  *  s    
! A Ar'   rx  )r   ))r   
__future__r   r   r   r1   r   apitools.base.pyr   r   googlecloudsdk.api_lib.debugr   googlecloudsdk.api_lib.utilr   googlecloudsdk.corer	   r
   r   googlecloudsdk.core.utilr   r9  	six.movesr   r   r   r&   r:   rG   rR   rV   objectrX   r   r   rk  rP  r"  r   r  dictrx  r   r'   r%   <module>r     s      &  ' 	  > / , & # ) * 
  J!ZK27*<7(#C& #CLg'{ g'TZJ{ ZJzA AH8,< FA4 Ar'   