o
    ga                  
   @  s  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rAddlmZ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 zddlm Z  ddl!m"Z" ddl#m$Z$ W n e%y Z& zej'(de&dZ&[&ww ddlm)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4 e5dZ6de7d< dCddZ8dDd d!Z9dEd$d%Z:	dFdGd+d,Z;dHd/d0Z<dHd1d2Z=dHd3d4Z>G d5d6 d6eZ?G d7d8 d8e?Z@G d9d: d:e?ZA	dFdId?d@ZBG dAdB dBZCdS )Jz1MySQL instrumentation supporting mysql-connector.    )annotationsN)ABCabstractmethod)nullcontext)TYPE_CHECKINGAnyCallable
CollectionDictOptionalUnion   )MySQLConnectionAbstractMySQLCursorAbstract)PooledMySQLConnection   )	connector)CNX_POOL_ARGSDEFAULT_CONFIGURATION)logger)VERSION_TEXT)trace)TracerProvider)SpanAttributeszGOpenTelemetry installation not found. You must install the API and SDK.   )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_removerspan
trace.SpanexcOptional[Exception]returnNonec                 C  s6   | r|   r|s
dS | ttjj | | dS )zRecords an exeception event.N)is_recording
set_statusr   Status
StatusCodeERRORrecord_exception)r(   r*    r4   g/var/www/html/api-tag/env/lib/python3.10/site-packages/mysql/connector/opentelemetry/instrumentation.pyrecord_exception_eventX   s   r6   c                 C  s   | r|   sdS |   dS )z
Ends span.N)r.   end)r(   r4   r4   r5   end_spana   s   r8   	operationstrc                 C  s&   | rt | trtd|  d S dS )z&Parse query to extract operation name. r   )
isinstancer:   r'   subsplit)r9   r4   r4   r5   get_operation_namei   s   r?   cnx#Optional['MySQLConnectionAbstract']cnx_span
cnx_kwargsOptional[Dict[str, Any]]c              
   C  s  |r|  sdS |du ri }| r| j nd|v}tjttj|r!dndt|r'dndi}|r| r1| jn|dtd |tj	< | rA| j
n|dtd |tj< t| d	r| jrz| jj \|t< }| jj \|t< |t< W n ty } ztd
| W Y d}~nHd}~ww |tj |kr||t< n7| r| jn|d|t< t| d	r| jrz
| jj |t< W n ty } ztd
| W Y d}~nd}~ww || dS )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hasattrrL   sockgetpeernamer#   getsocknamer!   r"   	Exceptionr   warningr$   set_attributes)r@   rB   rC   is_tcpattrssock_peer_portsock_errr4   r4   r5   set_connection_span_attrsq   sR   


r_   methodr   c                      d
 fdd}|S )zAAttach the connection span while executing the connection method.r@   'MySQLConnectionAbstract'argsr   kwargsr,   c                   s`   | j r| j  rtj| j ddnt   | g|R i |W  d   S 1 s)w   Y  dS )z#Connection span attacher decorator.Fend_on_exitN)_spanr.   r   use_spanr   )r@   rc   rd   r`   r4   r5   wrapper   s   $z'with_cnx_span_attached.<locals>.wrapperN)r@   rb   rc   r   rd   r   r,   r   r4   r`   rj   r4   ri   r5   with_cnx_span_attached   s   rl   c                   ra   )z:Create a query span while executing the connection method.r@   TracedMySQLConnectionrc   r   rd   r,   c                   s   t d j tjttj| jtjttj	t
d|  i}| jr8| j r8| jj j tjjt| j g|dnt   | g|R i |W  d   S 1 sQw   Y  dS )Query span creator decorator.z%Creating query span for connection.%sconnection_typenamekindlinks
attributesN)r   info__name__r   r   DB_USER_user	THREAD_IDr   THREAD_NAMEr   get_wrapped_classrg   r.   _tracerstart_as_current_spanupperr   SpanKindCLIENTLinkget_span_contextr   )r@   rc   rd   query_span_attributesri   r4   r5   rj      s(   $z$with_cnx_query_span.<locals>.wrapperN)r@   rm   rc   r   rd   r   r,   r   r4   rk   r4   ri   r5   with_cnx_query_span   s   r   c                   ra   )z6Create a query span while executing the cursor method.curTracedMySQLCursorrc   r   rd   r,   c                   s   t d j t| jdrt| jdnt| jd}tjttj|j	tj
ttjtd|  i}| jjt|d p6dtjj| jg|d  | g|R i |W  d   S 1 sVw   Y  dS )	rn   z!Creating query span for cursor.%s_connection_cnxcursor_typer   zSQL statementrp   N)r   ru   rv   rT   _wrappedgetattrr   r   rw   rx   ry   r   rz   r   r{   r|   r}   r?   r   r   r   _connection_span_link)r   rc   rd   
connectionr   ri   r4   r5   rj      s&   

$z'with_cursor_query_span.<locals>.wrapperN)r   r   rc   r   rd   r   r,   r   r4   rk   r4   ri   r5   with_cursor_query_span   s   r   c                      sX   e Zd ZdZedddZdd	d
Zd fddZdddZdddZ	dddZ
  ZS )BaseMySQLTracerz<Base class that provides basic object wrapper functionality.r,   r-   c                 C  s   dS )z"Must be implemented by subclasses.Nr4   selfr4   r4   r5   __init__  s    zBaseMySQLTracer.__init__attrr:   r   c                 C  s    || 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__r   r   )r   r   r4   r4   r5   __getattr__  s   

zBaseMySQLTracer.__getattr__rq   valuec                   sN   d| j vr|| j d< d S || j v s|dkrt || d S | j|| d S )Nr   
autocommit)r   super__setattr__r   )r   rq   r   	__class__r4   r5   r   !  s   

zBaseMySQLTracer.__setattr__c                 C  s   | j   | S )Magic method.)r   	__enter__r   r4   r4   r5   r   -  s   
zBaseMySQLTracer.__enter__rc   rd   c                 O  s   | j j|i | dS )r   N)r   __exit__r   rc   rd   r4   r4   r5   r   2  s   zBaseMySQLTracer.__exit__c                 C  s
   | j jjS )zGets the wrapped class name.)r   r   rv   r   r4   r4   r5   r{   6  s   
z!BaseMySQLTracer.get_wrapped_class)r,   r-   )r   r:   r,   r   )rq   r:   r   r   r,   r-   )r,   r   )rc   r   rd   r   r,   r-   r,   r:   )rv   
__module____qualname____doc__r   r   r   r   r   r   r{   __classcell__r4   r4   r   r5   r     s    


r   c                   @  sD   e Zd ZdZddd	ZedddZedddZedddZdS )r   z;Wrapper class for a `MySQLCursor` or `CMySQLCursor` object.wrapped'MySQLCursorAbstract'tracertrace.Tracerconnection_spanr)   c                 C  s    || _ || _t| | _dS zConstructor.N)r   r|   r   r   r   r   )r   r   r   r   r4   r4   r5   r   >  s
   
zTracedMySQLCursor.__init__rc   r   rd   r,   c                 O     | j j|i |S Instrument method.)r   executer   r4   r4   r5   r   K     zTracedMySQLCursor.executec                 O  r   r   )r   executemanyr   r4   r4   r5   r   P  r   zTracedMySQLCursor.executemanyc                 O  r   r   )r   callprocr   r4   r4   r5   r   U  r   zTracedMySQLCursor.callprocN)r   r   r   r   r   r)   rc   r   rd   r   r,   r   )	rv   r   r   r   r   r   r   r   r   r4   r4   r4   r5   r   ;  s    
r   c                   @  s  e Zd ZdZdKddZdLddZedMddZedMddZedMddZ	edMddZ
edMddZedMddZedMddZedMddZedMddZedMd d!ZedMd"d#ZedMd$d%ZeedNd'd(ZedMd)d*ZedMd+d,ZedMd-d.ZedMd/d0ZedMd1d2ZedMd3d4ZedMd5d6ZedMd7d8ZedMd9d:ZedMd;d<ZeedNd=d>ZeedNd?d@Z eedOdBdCZ!e!j"edPdEdCZ!edMdFdGZ#edMdHdIZ$dJS )Qrm   zCWrapper class for a `MySQLConnection` or `CMySQLConnection` object.r   rb   r,   r-   c                 C  s   || _ | j j}dS r   r   sql_mode)r   r   _r4   r4   r5   r   ^  s   zTracedMySQLConnection.__init__rc   r   rd   r   c                 O  s    t | jj|i || j| jdS )zWraps the object method.)r   r   r   )r   r   cursorr|   rg   r   r4   r4   r5   r   f  s
   zTracedMySQLConnection.cursorc                 O  r   r   )r   cmd_change_userr   r4   r4   r5   r   n  r   z%TracedMySQLConnection.cmd_change_userc                 O  r   r   )r   commitr   r4   r4   r5   r   s  r   zTracedMySQLConnection.commitc                 O  r   r   )r   rollbackr   r4   r4   r5   r   x  r   zTracedMySQLConnection.rollbackc                 O  r   r   )r   	cmd_queryr   r4   r4   r5   r   }  r   zTracedMySQLConnection.cmd_queryc                 O  r   r   )r   cmd_init_dbr   r4   r4   r5   r     r   z!TracedMySQLConnection.cmd_init_dbc                 O  r   r   )r   cmd_refreshr   r4   r4   r5   r     r   z!TracedMySQLConnection.cmd_refreshc                 O  r   r   )r   cmd_quitr   r4   r4   r5   r     r   zTracedMySQLConnection.cmd_quitc                 O  r   r   )r   cmd_shutdownr   r4   r4   r5   r     r   z"TracedMySQLConnection.cmd_shutdownc                 O  r   r   )r   cmd_statisticsr   r4   r4   r5   r     r   z$TracedMySQLConnection.cmd_statisticsc                 O  r   r   )r   cmd_process_killr   r4   r4   r5   r     r   z&TracedMySQLConnection.cmd_process_killc                 O  r   r   )r   	cmd_debugr   r4   r4   r5   r     r   zTracedMySQLConnection.cmd_debugc                 O  r   r   )r   cmd_pingr   r4   r4   r5   r     r   zTracedMySQLConnection.cmd_pingr:   c                 C     | j jS r   )r   databaser   r4   r4   r5   r        zTracedMySQLConnection.databasec                 O  r   r   )r   is_connectedr   r4   r4   r5   r     r   z"TracedMySQLConnection.is_connectedc                 O  r   r   )r   reset_sessionr   r4   r4   r5   r     r   z#TracedMySQLConnection.reset_sessionc                 O  r   r   )r   pingr   r4   r4   r5   r     r   zTracedMySQLConnection.pingc                 O  r   r   )r   
info_queryr   r4   r4   r5   r     r   z TracedMySQLConnection.info_queryc                 O  r   r   )r   cmd_stmt_preparer   r4   r4   r5   r     r   z&TracedMySQLConnection.cmd_stmt_preparec                 O  r   r   )r   cmd_stmt_executer   r4   r4   r5   r     r   z&TracedMySQLConnection.cmd_stmt_executec                 O  r   r   )r   cmd_stmt_closer   r4   r4   r5   r     r   z$TracedMySQLConnection.cmd_stmt_closec                 O  r   r   )r   cmd_stmt_send_long_datar   r4   r4   r5   r     r   z-TracedMySQLConnection.cmd_stmt_send_long_datac                 O  r   r   )r   cmd_stmt_resetr   r4   r4   r5   r     r   z$TracedMySQLConnection.cmd_stmt_resetc                 O  r   r   )r   cmd_reset_connectionr   r4   r4   r5   r     r   z*TracedMySQLConnection.cmd_reset_connectionc                 C  r   r   )r   	time_zoner   r4   r4   r5   r     r   zTracedMySQLConnection.time_zonec                 C  r   r   r   r   r4   r4   r5   r     r   zTracedMySQLConnection.sql_modeboolc                 C  r   r   r   r   r   r4   r4   r5   r     r   z TracedMySQLConnection.autocommitr   c                 C  s   || j _dS )r   Nr   )r   r   r4   r4   r5   r     s   c                 O  r   r   )r   set_charset_collationr   r4   r4   r5   r     r   z+TracedMySQLConnection.set_charset_collationc                 O  r   r   )r   start_transactionr   r4   r4   r5   r     r   z'TracedMySQLConnection.start_transactionN)r   rb   r,   r-   )rc   r   rd   r   r,   r   r   r   )r,   r   )r   r   r,   r-   )%rv   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   propertyr   r   r   r   r   r   r   r   r   r   r   r   r   r   setterr   r   r4   r4   r4   r5   rm   [  s    

rm   connectHCallable[..., Union['MySQLConnectionAbstract', 'PooledMySQLConnection']]tracer_providerOptional[trace.TracerProvider]c                   s   t  d	 fdd}|S )
z.Retrurn the instrumented version of `connect`.rc   r   rd   r,   9Union['MySQLConnectionAbstract', 'PooledMySQLConnection']c                    s   t  fddtD rtd | i  S tjdtd}|jttj	j
d t< | t< tj t dd }td	|  | i  }t||  t|d
W  d	   S 1 sZw   Y  d	S )zWraps the connection object returned by the method `connect`.

        Instrumentation for PooledConnections is not supported.
        c                 3  s    | ]}| v V  qd S Nr4   ).0keyrd   r4   r5   	<genexpr>  s    z7_instrument_connect.<locals>.wrapper.<locals>.<genexpr>z4Instrumentation for pooled connections not supportedMySQL Connector/Pythoninstrumenting_module_nameinstrumenting_library_versionr   rq   rr   Fre   Nr   )anyr   r   rY   r   
get_tracerr   
start_spanr   r   r   r%   r&   rh   r_   rm   )rc   rd   r   rB   r@   r   r   r   r5   rj     s(   

$z$_instrument_connect.<locals>.wrapperN)rc   r   rd   r   r,   r   )	functoolswraps)r   r   rj   r4   r   r5   _instrument_connect  s   (r   c                   @  s^   e Zd ZU dZdZded< dd	d
ZdddZdddZ	ddddZ	dddZ
d ddZdS )!MySQLInstrumentorz8MySQL instrumentation supporting mysql-connector-python.NzOptional[MySQLInstrumentor]	_instancerc   r   rd   r,   c                 O  s:   | j du rtj| g|R i || _ t| j dtj | j S )zQSinglenton.

        Restricts the instantiation to a singular instance.
        N_original_connect)r   object__new__setattrr   r   )clsrc   rd   r4   r4   r5   r   =  s   
zMySQLInstrumentor.__new__Collection[str]c                 C  s   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   r4   r4   r5   instrumentation_dependenciesI  s   z.MySQLInstrumentor.instrumentation_dependenciesr-   c                 K  s<   t jt| dkrtd dS tt| d|ddt _dS )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   r   rY   r   rP   r   rd   r4   r4   r5   
instrumentN  s   	
zMySQLInstrumentor.instrumentr   rb   r   r   c                 C  s   t |trtd |S t|drt|ds td|jj |S tjdt	|d}|j
ttjjd|_||_t||j t|d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.rg   r|   z+Instrumentation for class %s not supported.r   r   r   r   )r<   rm   r   rY   rT   r   rv   r   r   r   r   r   r   r   rg   r|   r_   )r   r   r   r   r4   r4   r5   instrument_connection_  s(   


z'MySQLInstrumentor.instrument_connectionc                 K  s.   t jt| dkrtd dS t| dt _dS )zUninstrument the library.r   z5MySQL Connector/Python module already uninstrumented.N)r   r   r   r   rY   r   r4   r4   r5   uninstrument  s   
zMySQLInstrumentor.uninstrumentc                 C  s\   t |dstd|jj |S t|tstd |S |jr+|j r+|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.
        rg   z-Uninstrumentation for class %s not supported.z"Connection already uninstrumented.N)rT   r   rY   r   rv   r<   rm   rg   r.   r7   r   )r   r   r4   r4   r5   uninstrument_connection  s   



z)MySQLInstrumentor.uninstrument_connection)rc   r   rd   r   r,   r   )r,   r   )rd   r   r,   r-   r   )r   rb   r   r   r,   rb   )r   rb   r,   rb   )rv   r   r   r   r   __annotations__r   r   r   r   r   r   r4   r4   r4   r5   r   8  s   
 



*r   )r(   r)   r*   r+   r,   r-   )r(   r)   r,   r-   )r9   r:   r,   r:   r   )r@   rA   rB   r)   rC   rD   r,   r-   )r`   r   r,   r   )r   r   r   r   r,   r   )Dr   
__future__r   r   reabcr   r   
contextlibr   typingr   r   r   r	   r
   r   r   	abstractsr   r   poolingr   r;   r   	constantsr   r   r   versionr   opentelemetryr   opentelemetry.sdk.tracer   opentelemetry.semconv.tracer   ImportErrormissing_dependencies_errerrorsProgrammingErrorr   r   r   r   r   r    r!   r"   r#   r$   r%   r&   compiler'   r   r6   r8   r?   r_   rl   r   r   r   r   rm   r   r   r4   r4   r4   r5   <module>   sV   $8

	

U

 .  -3