U
    4Je7                     @   s  d Z ddlZddlZddlZddlZddlZddlmZ ddl	m
Z
 ddlmZ ddlmZ ddlmZmZmZ ddlmZ dd	lmZmZ dd
lmZ eZejeef ZeeZ ej!Z!ej"Z"ej#Z#ej$Z$ej%Z%ej&Z&ej'Z'ej(Z(ej)Z)ej*Z*ej+Z+ej,Z,ej-Z-ej.Z.ej/Z/ej0Z0ej1Z1ej2Z2ej3Z4ej5Z6ej7Z8ej9Z:ej;Z<ej=Z>ej?Z@ejAZBejCZDejEZFejGZHejIZJejKZLejMZNejOZPejQZRejSZTejUZUejVZVejWZWejXZXejYZYejZZZej[Z[ej\Z\ej]Z]ej^Z^ej_Z_ej`Z`ejaZaejbZbejcZcejdZdejeZeejfZfejgZgejhZhedZiG dd dZjeji ZkejehdeedefeiiZlG dd dejmZnG dd denZoG dd denZpdejqd ejrej ddddZsdS )a  
This package implements `OpenTelemetry Resources
<https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/sdk.md#resource-sdk>`_:

    *A Resource is an immutable representation of the entity producing
    telemetry. For example, a process producing telemetry that is running in
    a container on Kubernetes has a Pod name, it is in a namespace and
    possibly is part of a Deployment which also has a name. All three of
    these attributes can be included in the Resource.*

Resource objects are created with `Resource.create`, which accepts attributes
(key-values). Resources should NOT be created via constructor, and working with
`Resource` objects should only be done via the Resource API methods. Resource
attributes can also be passed at process invocation in the
:envvar:`OTEL_RESOURCE_ATTRIBUTES` environment variable. You should register
your resource with the  `mysql.opentelemetry.sdk.trace.TracerProvider` by passing
them into their constructors. The `Resource` passed to a provider is available
to the exporter, which can send on this information as it sees fit.

.. code-block:: python

    trace.set_tracer_provider(
        TracerProvider(
            resource=Resource.create({
                "service.name": "shoppingcart",
                "service.instance.id": "instance-12",
            }),
        ),
    )
    print(trace.get_tracer_provider().resource.attributes)

    {'telemetry.sdk.language': 'python',
    'telemetry.sdk.name': 'opentelemetry',
    'telemetry.sdk.version': '0.13.dev0',
    'service.name': 'shoppingcart',
    'service.instance.id': 'instance-12'}

Note that the OpenTelemetry project documents certain `"standard attributes"
<https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/README.md>`_
that have prescribed semantic meanings, for example ``service.name`` in the
above example.
     N)dumps)environ)parse)BoundedAttributes)$OTEL_EXPERIMENTAL_RESOURCE_DETECTORSOTEL_RESOURCE_ATTRIBUTESOTEL_SERVICE_NAME)ResourceAttributes)entry_pointsversion)AttributeValuezopentelemetry-sdkc                   @   s   e Zd ZdZdeeje dddZe	deje eje d dddZ
e	d d	d
dZeed	ddZeed	ddZd d dddZeedddZdd Zded	ddZdS )ResourcezZA Resource is an immutable representation of the entity producing telemetry as Attributes.N
attributes
schema_urlc                 C   s"   t |d| _|d krd}|| _d S )N)r    )r   _attributes_schema_url)selfr   r    r   N/tmp/pip-unpacked-wheel-7_167w8m/mysql/opentelemetry/sdk/resources/__init__.py__init__   s    zResource.__init__)r   r   returnc              	   C   s   | si } g }t }ttdd}d|kr4|d |D ](}|tttd|	 d
   q8t|t t| |}|jtdsd}|jtd}|r|d| 7 }|tt|i|}|S )zCreates a new `Resource` from attributes.

        Args:
            attributes: Optional zero or more key-value pairs.
            schema_url: Optional URL pointing to the schema

        Returns:
            The newly-created Resource.
        Zotel,Zopentelemetry_resource_detector)groupnameNZunknown_service:)_DEFAULT_RESOURCEr   getr   splitappendnextiterr
   striploadget_aggregated_resourcesmerger   r   SERVICE_NAMEPROCESS_EXECUTABLE_NAME)r   r   Zresource_detectorsresourceZ$otel_experimental_resource_detectorsZresource_detectorZdefault_service_nameZprocess_executable_namer   r   r   create   sR     
  zResource.creater   c                   C   s   t S N)_EMPTY_RESOURCEr   r   r   r   	get_empty   s    zResource.get_emptyc                 C   s   | j S r,   )r   r   r   r   r   r      s    zResource.attributesc                 C   s   | j S r,   )r   r/   r   r   r   r      s    zResource.schema_url)otherr   c                 C   sn   | j  }||j  | jdkr(|j}n<|jdkr:| j}n*| j|jkrN|j}ntd| j|j | S t||S )a^  Merges this resource and an updating resource into a new `Resource`.

        If a key exists on both the old and updating resource, the value of the
        updating resource will override the old resource value.

        The updating resource's `schema_url` will be used only if the old
        `schema_url` is empty. Attempting to merge two resources with
        different, non-empty values for `schema_url` will result in an error
        and return the old resource.

        Args:
            other: The other resource to be merged.

        Returns:
            The newly-created Resource.
        r   zEFailed to merge resources: The two schemas %s and %s are incompatible)r   copyupdater   loggererrorr   )r   r0   Zmerged_attributesr   r   r   r   r&      s    


zResource.mergec                 C   s&   t |tsdS | j|jko$| j|jkS )NF)
isinstancer   r   r   )r   r0   r   r   r   __eq__  s
    

zResource.__eq__c                 C   s"   t t| j dd d| j S )NT)	sort_keys|)hashr   r   r1   r   r/   r   r   r   __hash__	  s    zResource.__hash__   c                 C   s   t t| j| jd|dS )Nr   )indent)r   dictr   r   )r   r<   r   r   r   to_json  s    zResource.to_json)N)NN)r;   )__name__
__module____qualname____doc__
AttributestypingOptionalstrr   staticmethodr*   r.   propertyr   r   r&   objectboolr6   r:   r>   r   r   r   r   r      s(     8$r   pythonZopentelemetryc                   @   s*   e Zd Zd	ddZejddddZdS )
ResourceDetectorFc                 C   s
   || _ d S r,   )raise_on_error)r   rM   r   r   r   r   #  s    zResourceDetector.__init__r   r+   c                 C   s
   t  d S r,   )NotImplementedErrorr/   r   r   r   detect&  s    zResourceDetector.detectN)F)r?   r@   rA   r   abcabstractmethodrO   r   r   r   r   rL   "  s   
rL   c                   @   s   e Zd ZddddZdS )OTELResourceDetectorr   r+   c           	      C   s   t t}i }|r|dD ]n}z|jddd\}}W n8 tk
rn } ztd|| W Y qW 5 d }~X Y nX t|	 }|||	 < qt t
}|r||t< t|S )Nr   =   )maxsplitz0Invalid key value resource attribute pair %s: %s)r   r   r   r   
ValueErrorr3   warningr   unquoter#   r   r'   r   )	r   Zenv_resources_itemsZenv_resource_mapitemkeyvalueexcZvalue_url_decodedZservice_namer   r   r   rO   -  s&    

zOTELResourceDetector.detectNr?   r@   rA   rO   r   r   r   r   rR   +  s   rR   c                   @   s   e Zd ZddddZdS )ProcessResourceDetectorr   r+   c                 C   sN   d tttjjdkr*tjjs*tjd d ntj}tttj	t
tjjt|iS )N.final   )joinmaprF   sysversion_inforeleaselevelserialr   PROCESS_RUNTIME_DESCRIPTIONr   PROCESS_RUNTIME_NAMEimplementationr   PROCESS_RUNTIME_VERSION)r   Z_runtime_versionr   r   r   rO   G  s&    

   zProcessResourceDetector.detectNr]   r   r   r   r   r^   E  s   r^      )	detectorsinitial_resourcer   c           
         s   |p
t  }tjjdd  fdd| D }t|D ]r\}}| | }zTz|j|d}W n> tk
r }	 z t	}|j
rx|	td|	| W 5 d}	~	X Y nX W 5 ||}X q6W 5 Q R X |S )a'  Retrieves resources from detectors in the order that they were passed

    :param detectors: List of resources in order of priority
    :param initial_resource: Static resource. This has highest priority
    :param timeout: Number of seconds to wait for each detector to return
    :return:
    r;   )max_workersc                    s   g | ]}  |jqS r   )ZsubmitrO   ).0detectorexecutorr   r   
<listcomp>j  s     z,get_aggregated_resources.<locals>.<listcomp>)timeoutz%Exception %s in detector %s, ignoringN)r   r*   
concurrentfuturesZThreadPoolExecutor	enumerater&   result	Exceptionr-   rM   r3   rW   )
rm   rn   ru   Zdetectors_merged_resourcerw   Zdetector_indfuturerq   Zdetected_resourceexr   rr   r   r%   [  s     $r%   )Nrl   )trB   rP   concurrent.futuresrv   loggingrd   rD   jsonr   osr   urllibr   Zmysql.opentelemetry.attributesr   Z-mysql.opentelemetry.sdk.environment_variablesr   r   r   Z$mysql.opentelemetry.semconv.resourcer	   Z,mysql.opentelemetry.util._importlib_metadatar
   r   Zmysql.opentelemetry.util.typesr   Z
LabelValueDictrF   rC   	getLoggerr?   r3   ZCLOUD_PROVIDERZCLOUD_ACCOUNT_IDZCLOUD_REGIONZCLOUD_AVAILABILITY_ZONEZCONTAINER_NAMEZCONTAINER_IDZCONTAINER_IMAGE_NAMEZCONTAINER_IMAGE_TAGZDEPLOYMENT_ENVIRONMENTZ	FAAS_NAMEZFAAS_IDZFAAS_VERSIONZFAAS_INSTANCEZ	HOST_NAMEZ	HOST_TYPEZHOST_IMAGE_NAMEZHOST_IMAGE_IDZHOST_IMAGE_VERSIONZK8S_CLUSTER_NAMEZKUBERNETES_CLUSTER_NAMEZK8S_NAMESPACE_NAMEZKUBERNETES_NAMESPACE_NAMEZK8S_POD_UIDZKUBERNETES_POD_UIDZK8S_POD_NAMEZKUBERNETES_POD_NAMEZK8S_CONTAINER_NAMEZKUBERNETES_CONTAINER_NAMEZK8S_REPLICASET_UIDZKUBERNETES_REPLICA_SET_UIDZK8S_REPLICASET_NAMEZKUBERNETES_REPLICA_SET_NAMEZK8S_DEPLOYMENT_UIDZKUBERNETES_DEPLOYMENT_UIDZK8S_DEPLOYMENT_NAMEZKUBERNETES_DEPLOYMENT_NAMEZK8S_STATEFULSET_UIDZKUBERNETES_STATEFUL_SET_UIDZK8S_STATEFULSET_NAMEZKUBERNETES_STATEFUL_SET_NAMEZK8S_DAEMONSET_UIDZKUBERNETES_DAEMON_SET_UIDZK8S_DAEMONSET_NAMEZKUBERNETES_DAEMON_SET_NAMEZK8S_JOB_UIDZKUBERNETES_JOB_UIDZK8S_JOB_NAMEZKUBERNETES_JOB_NAMEZK8S_CRONJOB_UIDZKUBERNETES_CRON_JOB_UIDZK8S_CRONJOB_NAMEZKUBERNETES_CRON_JOB_NAMEZOS_TYPEZOS_DESCRIPTIONZPROCESS_PIDr(   ZPROCESS_EXECUTABLE_PATHZPROCESS_COMMANDZPROCESS_COMMAND_LINEZPROCESS_COMMAND_ARGSZPROCESS_OWNERri   rk   rh   r'   ZSERVICE_NAMESPACEZSERVICE_INSTANCE_IDZSERVICE_VERSIONZTELEMETRY_SDK_NAMEZTELEMETRY_SDK_VERSIONZTELEMETRY_AUTO_VERSIONZTELEMETRY_SDK_LANGUAGEZ_OPENTELEMETRY_SDK_VERSIONr   r-   r   ABCrL   rR   r^   ListrE   r%   r   r   r   r   <module>   s   +
 
   		  