
    G)fI                       U d Z ddlmZ ddlZddlZddlmZmZ ddlm	Z	 ddl
mZmZmZmZmZmZmZ erddlmZmZ dd	lmZ dd
lmZ 	 ddlmZ ddlmZ ddlmZm Z  ddl!m!Z! ddl"m#Z# 	 ddl$m%Z% ddl&m'Z' ddl(m)Z) dZ*ddlm0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;  ejx                  d      Z=de>d<   d+dZ?d,dZ@d-dZA	 d.	 	 	 	 	 	 	 d/dZBd0d ZC	 	 	 	 	 	 	 	 	 	 	 	 	 	 d1d!ZD G d" d#e      ZE G d$ d%eE      ZF G d& d'eE      ZG	 d.	 	 	 	 	 d2d(ZH G d) d*      ZIy# e$ r Y w xY w# e$ r< 	 ddl+m%Z% ddl,m)Z) dZ*n)# e$ r!Z-ej\                  j_                  d      e-dZ-[-ww xY wY w xY w)3z1MySQL instrumentation supporting mysql-connector.    )annotationsN)ABCabstractmethod)nullcontext)TYPE_CHECKINGAnyCallable
CollectionDictOptionalUnion   )MySQLConnectionAbstractMySQLCursorAbstract)MySQLConnection)PooledMySQLConnection)CMySQLConnection   )	connector)CNX_POOL_ARGSDEFAULT_CONFIGURATION)logger)VERSION_TEXT)trace)TracerProvider)SpanAttributesTFzBundled installation has missing dependencies. Please use `pip install mysql-connector-python[opentelemetry]`, or for an editable install use `pip install -e '.[opentelemetry]'`, to install the dependencies required by the bundled opentelemetry package.   )CONNECTION_SPAN_NAME	DB_SYSTEMDEFAULT_THREAD_IDDEFAULT_THREAD_NAMEFIRST_SUPPORTED_VERSIONNET_SOCK_FAMILYNET_SOCK_HOST_ADDRNET_SOCK_HOST_PORTNET_SOCK_PEER_ADDRNET_SOCK_PEER_PORTOPTION_CNX_SPANOPTION_CNX_TRACERz
^/\*.*?\*/z
re.Patternleading_comment_removerc                    | r| j                         r|sy| j                  t        j                  t        j                  j
                               | j                  |       y)zRecords an exeception event.N)is_recording
set_statusr   Status
StatusCodeERRORrecord_exception)spanexcs     j/var/www/html/flask-app/venv/lib/python3.12/site-packages/mysql/connector/opentelemetry/instrumentation.pyrecord_exception_eventr5   O   sD    t((*#OOELL!1!1!7!789#    c                J    | r| j                         sy| j                          y)z
Ends span.N)r,   end)r2   s    r4   end_spanr9   X   s    t((*HHJr6   c                v    | r7t        | t              r't        j                  d|       j	                         d   S y)z&Parse query to extract operation name. r   )
isinstancestrr*   subsplit)	operations    r4   get_operation_namerA   `   s2    Z	3/&**2y9??A!DDr6   c                   |r|j                         sy|i }| r| j                   nd|v}t        j                  t        t        j                  |rdndt
        |rdndi}|r| r| j                  n|j                  dt        d         |t        j                  <   | r| j                  n|j                  dt        d         |t        j                  <   t        | d	      r| j                  r	 | j                  j                  j                         \  |t         <   }| j                  j                  j#                         \  |t$        <   |t&        <   |t        j                     |k7  rt||t(        <   nj| r| j                  n|j                  d      |t         <   t        | d	      r8| j                  r,	 | j                  j                  j#                         |t$        <   |j1                  |       y# t*        $ r }t-        j.                  d
|       Y d}~6d}~ww xY w# t*        $ r }t-        j.                  d
|       Y d}~bd}~ww xY w)a  Defines connection span attributes. If `cnx` is None then we use `cnx_kwargs`
    to get basic net information. Basic net attributes are defined such as:

    * DB_SYSTEM
    * NET_TRANSPORT
    * NET_SOCK_FAMILY

    Socket-level attributes [*] are also defined [**].

    [*]: Socket-level attributes identify peer and host that are directly connected to
    each other. Since instrumentations may have limited knowledge on network
    information, instrumentations SHOULD populate such attributes to the best of
    their knowledge when populate them at all.

    [**]: `CMySQLConnection` connections have no access to socket-level
    details so socket-level attributes aren't included. `MySQLConnection`
    connections, on the other hand, do include socket-level attributes.

    References:
        [1]: https://github.com/open-telemetry/opentelemetry-specification/blob/main/            specification/trace/semantic_conventions/span-general.md
    Nunix_socketip_tcpinprocinetunixhostport_socketzConnection socket is down %s)r,   _unix_socketr   r   NET_TRANSPORTr#   _hostgetr   NET_PEER_NAME_portNET_PEER_PORThasattrrJ   sockgetpeernamer&   getsocknamer$   r%   r'   	Exceptionr   warningset_attributes)cnxcnx_span
cnx_kwargsis_tcpattrssock_peer_portsock_errs          r4   set_connection_span_attrsr`   h   s   8 8002
%(!!!m:.MF 	  )$$&hh6vE CII*..9Nv9V"W 	n**+ CII*..9Nv9V"W 	n**+ 3	"s{{? KK$$002,-" KK$$002,-,-
 556.H 1?E,-
 !$C)F 	 ! 3	"s{{I,/KK,<,<,H,H,J() E")  I=xHHI"  I=xHHIs1   +A#G* -+H *	H3HH	H?H::H?c                $     	 	 	 	 	 	 	 	 d fd}|S )z?Attach the connection span while executing a connection method.c                    | j                   r;| j                   j                         r!t        j                  | j                   d      n	t	               5   | g|i |cddd       S # 1 sw Y   yxY w)z#Connection span attacher decorator.Fend_on_exitN)_spanr,   r   use_spanr   )rY   argskwargsmethods      r4   wrapperz.with_connection_span_attached.<locals>.wrapper   s`     YY399113 ^^II5
9D	0 #///	0 	0 	0s   A))A2)rY   z,Union['MySQLConnection', 'CMySQLConnection']rg   r   rh   r   returnr    )ri   rj   s   ` r4   with_connection_span_attachedrm      s/    090BE0QT0	0 Nr6   c           
        t        |d      rt        |d      nt        |d      }t        j                  t        t        j                  |j
                  t        j                  t        t        j                  t        d|j                  j                  i}|j                  t        |d         xs dt        j                  j                   |g|      5   | |i |cddd       S # 1 sw Y   yxY w)zInstruments the execution of `query_method`.

    A query span with a link to the corresponding connection span is generated.
    _connection_cnxcursor_typer   zSQL statement)namekindlinks
attributesN)rR   getattrr   r   DB_USER_user	THREAD_IDr    THREAD_NAMEr!   	__class____name__start_as_current_spanrA   r   SpanKindCLIENT)query_methodtracerconnection_span_linkwrappedrg   rh   
connectionquery_span_attributess           r4   _instrument_executionr      s     7M* 	'Wf%  	  )
 0 0  "3""$7w((11# 
	%	%Q(;O^^""#$(	 
& 
 - T,V,- - -s   C##C,c                  V     e Zd ZdZedd       Zd	dZd
 fdZddZddZ	ddZ
 xZS )BaseMySQLTracerz<Base class that provides basic object wrapper functionality.c                     y)z"Must be implemented by subclasses.Nrl   selfs    r4   __init__zBaseMySQLTracer.__init__   s    r6   c                b    || j                   v rt        | |      S t        | j                  |      S )zGets an attribute.

        Attributes defined in the wrapper object have higher precedence
        than those wrapped object equivalent. Attributes not found in
        the wrapper are then searched in the wrapped object.
        )__dict__rv   _wrapped)r   attrs     r4   __getattr__zBaseMySQLTracer.__getattr__   s.     4== 4&&t}}d++r6   c                    d| j                   vr|| j                   d<   y || j                   v rt        | 	  ||       y | j                  j                  ||       y )Nr   )r   super__setattr__r   )r   rr   valuer{   s      r4   r   zBaseMySQLTracer.__setattr__  sR    T]]*(-DMM*%4== Ge,!!$.r6   c                :    | j                   j                          | S )Magic method.)r   	__enter__r   s    r4   r   zBaseMySQLTracer.__enter__  s    !r6   c                <     | j                   j                  |i | y)r   N)r   __exit__r   rg   rh   s      r4   r   zBaseMySQLTracer.__exit__  s    //r6   c                B    | j                   j                  j                  S )zGets the wrapped class name.)r   r{   r|   r   s    r4   get_wrapped_classz!BaseMySQLTracer.get_wrapped_class  s    }}&&///r6   )rk   None)r   r=   rk   r   )rr   r=   r   r   rk   r   )rk   r   )rg   r   rh   r   rk   r   )rk   r=   )r|   
__module____qualname____doc__r   r   r   r   r   r   r   __classcell__)r{   s   @r4   r   r      s1    F1 1,
/
00r6   r   c                  <    e Zd ZdZ	 	 	 	 	 	 ddZddZddZddZy)	TracedMySQLCursorz;Wrapper class for a `MySQLCursor` or `CMySQLCursor` object.c                p    || _         || _        t        j                  |j	                               | _        yzConstructor.N)r   _tracerr   Linkget_span_context_connection_span_link)r   r   r   connection_spans       r4   r   zTracedMySQLCursor.__init__"  s/     07%+16,,.2
"r6   c                    t        | j                  j                  | j                  | j                  | j                  g|i |S )zInstruments execute method.)r   r   executer   r   r   s      r4   r   zTracedMySQLCursor.execute/  sG    $MM!!LL&&MM	

 
 
 	
r6   c                    t        | j                  j                  | j                  | j                  | j                  g|i |S )zInstruments executemany method.)r   r   executemanyr   r   r   s      r4   r   zTracedMySQLCursor.executemany:  sG    $MM%%LL&&MM	

 
 
 	
r6   c                    t        | j                  j                  | j                  | j                  | j                  g|i |S )zInstruments callproc method.)r   r   callprocr   r   r   s      r4   r   zTracedMySQLCursor.callprocE  sG    $MM""LL&&MM	

 
 
 	
r6   N)r   'MySQLCursorAbstract'r   trace.Tracerr   
trace.Spanrg   r   rh   r   rk   r   )r|   r   r   r   r   r   r   r   rl   r6   r4   r   r     s5    E
&
 
 $	
	
	
	
r6   r   c                  2    e Zd ZdZddZddZedd       Zy)	TracedMySQLConnectionzCWrapper class for a `MySQLConnection` or `CMySQLConnection` object.c                >    || _         | j                   j                  }yr   )r   sql_mode)r   r   _s      r4   r   zTracedMySQLConnection.__init__T  s    3: MM""r6   c                z    t         | j                  j                  |i || j                  | j                        S )Wraps the object method.)r   r   r   )r   r   cursorr   re   r   s      r4   r   zTracedMySQLConnection.cursor\  s6     (DMM(($9&9<< JJ
 	
r6   c                :     | j                   j                  |i |S )r   )r   cmd_change_userr   s      r4   r   z%TracedMySQLConnection.cmd_change_userd  s      -t}},,d=f==r6   N)r   'MySQLConnectionAbstract'rk   r   )rg   r   rh   r   rk   r   r   )r|   r   r   r   r   r   rm   r   rl   r6   r4   r   r   Q  s#    M#
 #> #>r6   r   c                T     t        j                         	 	 	 	 	 	 d fd       }|S )z.Retrurn the instrumented version of `connect`.c                    t        fdt        D              rt        j                  d        | i S t	        j
                  dt              }|j                  t        t        j                  j                        t        <   |t        <   t	        j                  t           d      5 }t        d|        | i }t        ||       t        |	      cddd       S # 1 sw Y   yxY w)
zWraps the connection object returned by the method `connect`.

        Instrumentation for PooledConnections is not supported.
        c              3  &   K   | ]  }|v  
 y wNrl   ).0keyrh   s     r4   	<genexpr>z7_instrument_connect.<locals>.wrapper.<locals>.<genexpr>y  s     6sf}6s   z4Instrumentation for pooled connections not supportedMySQL Connector/Pythoninstrumenting_module_nameinstrumenting_library_versiontracer_providerrr   rs   Frc   Nr   )anyr   r   rW   r   
get_tracerr   
start_spanr   r~   r   r(   r)   rf   r`   r   )rg   rh   r   rZ   rY   connectr   s    `   r4   rj   z$_instrument_connect.<locals>.wrapperq  s     666NNQRD+F++!!&>*6+
 #)"3"3%ENN,A,A #4 #
 %+ ! ^^F?3G 	8%dHf= 4*6*C &c8V<(	 	 	s   1.C))C2)rg   r   rh   r   rk   z9Union['MySQLConnectionAbstract', 'PooledMySQLConnection'])	functoolswraps)r   r   rj   s   `` r4   _instrument_connectr   j  s@     __W&&!&	B& &P Nr6   c                  f    e Zd ZU dZdZded<   ddZddZddZ	 d	 	 	 	 	 ddZ	dd	Z
	 	 	 	 dd
Zy)MySQLInstrumentorz8MySQL instrumentation supporting mysql-connector-python.NzOptional[MySQLInstrumentor]	_instancec                    | j                   Ct        j                  | g|i || _         t        | j                   dt        j
                         | j                   S )zQSinglenton.

        Restricts the instantiation to a singular instance.
        _original_connect)r   object__new__setattrr   r   )clsrg   rh   s      r4   r   zMySQLInstrumentor.__new__  sI    
 == "NN3@@@CMCMM#6	8I8IJ}}r6   c                    dt          gS )zoReturn a list of python packages with versions
        that the will be instrumented (e.g., versions >= 8.1.0).zmysql-connector-python >= )r"   r   s    r4   instrumentation_dependenciesz.MySQLInstrumentor.instrumentation_dependencies  s     --D,EFGGr6   c                    t         j                  t        | d      k7  rt        j                  d       yt        t        | d      |j                  d            t         _        y)a  Instrument the library.

        Args:
            trace_module: reference to the 'trace' module from opentelemetry.
            tracer_provider (optional): TracerProvider instance.

        NOTE: Instrumentation for pooled connections not supported.
        r   z3MySQL Connector/Python module already instrumented.Nr   )r   r   )r   r   rv   r   rW   r   rN   r   rh   s     r4   
instrumentzMySQLInstrumentor.instrument  sO     .A BBNNPQ/D"56"JJ'89
	r6   c                   t        |t              rt        j                  d       |S t	        |d      rt	        |d      s,t        j                  d|j
                  j                         |S t        j                  dt        |      }|j                  t        t        j                  j                        |_        ||_        t!        ||j                         t        |      S )	a  Enable instrumentation in a MySQL connection.

        Args:
            connection: uninstrumented connection instance.
            trace_module: reference to the 'trace' module from opentelemetry.
            tracer_provider (optional): TracerProvider instance.

        Returns:
            connection: instrumented connection instace.

        NOTE: Instrumentation for pooled connections not supported.
        z Connection already instrumented.re   r   z+Instrumentation for class %s not supported.r   r   r   r   )r<   r   r   rW   rR   r{   r|   r   r   r   r   r   r~   r   re   r   r`   )r   r   r   r   s       r4   instrument_connectionz'MySQLInstrumentor.instrument_connection  s    " j"78NN=>z7+7:y3QNN=$$-- !!&>*6+

 ",,%ENN,A,A - 

 $
!*j.>.>?$Z88r6   c                    t         j                  t        | d      k(  rt        j                  d       yt        | d      t         _        y)zUninstrument the library.r   z5MySQL Connector/Python module already uninstrumented.N)r   r   rv   r   rW   r   s     r4   uninstrumentzMySQLInstrumentor.uninstrument  s:     .A BBNNRS#D*=>	r6   c                f   t        |d      s,t        j                  d|j                  j                         |S t        |t              st        j                  d       |S |j                  r;|j                  j                         r!|j                  j                          d|_        |j                  S )a  Disable instrumentation in a MySQL connection.

        Args:
            connection: instrumented connection instance.

        Returns:
            connection: uninstrumented connection instace.

        NOTE: Instrumentation for pooled connections not supported.
        re   z-Uninstrumentation for class %s not supported.z"Connection already uninstrumented.N)rR   r   rW   r{   r|   r<   r   re   r,   r8   r   )r   r   s     r4   uninstrument_connectionz)MySQLInstrumentor.uninstrument_connection  s     z7+NN?$$-- *&;<NN?@ 
 0 0 = = ?  "#J"""r6   )rg   r   rh   r   rk   r   )rk   zCollection[str])rh   r   rk   r   r   )r   r   r   Optional[trace.TracerProvider]rk   r   )r   r   rk   r   )r|   r   r   r   r   __annotations__r   r   r   r   r   r   rl   r6   r4   r   r     sa    B-1I*1
H

( ;?(9-(9 8(9 
#	(9T?#3#	"#r6   r   )r2   r   r3   zOptional[Exception]rk   r   )r2   r   rk   r   )r@   r=   rk   r=   r   )rY   z#Optional['MySQLConnectionAbstract']rZ   r   r[   zOptional[Dict[str, Any]]rk   r   )ri   r	   rk   r	   )r   r	   r   r   r   z
trace.Linkr   r   rg   r   rh   r   rk   r	   )r   HCallable[..., Union['MySQLConnectionAbstract', 'PooledMySQLConnection']]r   r   rk   r   )Jr   
__future__r   r   reabcr   r   
contextlibr   typingr   r   r	   r
   r   r   r   	abstractsr   r   r   r   poolingr   connection_cextr   ImportErrorr;   r   	constantsr   r   r   versionr   opentelemetryr   opentelemetry.sdk.tracer   opentelemetry.semconv.tracer   OTEL_SYSTEM_AVAILABLEmysql.opentelemetry!mysql.opentelemetry.semconv.tracemissing_dependencies_errerrorsProgrammingErrorr   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   compiler*   r   r5   r9   rA   r`   rm   r   r   r   r   r   r   rl   r6   r4   <module>r     s   7 #  	 # " R R R  I,/6
  <  "( $6: "    '1bjj&?  ? ,0R#	,R#R# )R# 
	R#j"-"-"- %"- #	"-
 "- "- "-J+0c +0\/
 /
d>O >6 7;0U030 N0fv# v#C  "  ((-D % (//Y

 (	(( 	(sH   	D *D" DD"E#(D76E#7E<EEE#"E#