o
    ghL                  	   @   s>  U 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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mZmZ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! dZ"ee e#d< zddl"Z$e$Z"W n	 e%y   Y nw e!Z&e	j'e(e&f Z)e*e+Z,ej-Z-ej.Z.ej/Z/ej0Z0ej1Z1ej2Z2ej3Z3ej4Z4ej5Z5ej6Z6ej7Z7ej8Z8ej9Z9ej:Z:ej;Z;ej<Z<ej=Z=ej>Z>ej?Z?ej@ZAejBZCejDZEejFZGejHZIejJZKejLZMejNZOejPZQejRZSejTZUejVZWejXZYejZZ[ej\Z]ej^Z_ej`ZaejbZbejcZcejdZdejeZeejfZfejgZgejhZhejiZiejjZjejkZkejlZlejmZmejnZnejoZoejpZpejqZqejrZrejsZsejtZtejuZuejvZvejwZwedZxe(e#d< G dd dZyeyi ZzeyewdetdeuexiZ{G dd dej|Z}G dd de}Z~G dd de}ZG dd de}ZG dd de}Z		d%de	jd d e	jey d!ed"dfd#d$Zd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 except by `ResourceDetector`
instances which can't use `Resource.create` to avoid infinite loops. 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  `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)
ModuleType)ListMutableMappingOptionalcast)parse)BoundedAttributes)$OTEL_EXPERIMENTAL_RESOURCE_DETECTORSOTEL_RESOURCE_ATTRIBUTESOTEL_SERVICE_NAME)ResourceAttributes)entry_pointsversion)AttributeValuepsutilzopentelemetry-sdk_OPENTELEMETRY_SDK_VERSIONc                   @   s   e Zd ZU dZeed< eed< 	ddedej	e fddZ
e		ddej	e dej	e d	d fd
dZedddZed	efddZed	efddZd ddZded	efddZd	efddZd!ded	efddZdS )"ResourcezZA Resource is an immutable representation of the entity producing telemetry as Attributes._attributes_schema_urlN
attributes
schema_urlc                 C   s"   t |d| _|d u rd}|| _d S )N)r    )r
   r   r   )selfr   r    r   [/var/www/visachat/venv/lib/python3.10/site-packages/opentelemetry/sdk/resources/__init__.py__init__   s   
zResource.__init__returnc              	   C   s   | si } dh dd ttddD }g }|D ]}|tttd|	 d
   qt|tt| |}|jtdsad	}ttt |jtd}|rW|d
| 7 }|tt|i|}|S )a9  Creates a new `Resource` from attributes.

        `ResourceDetector` instances should not call this method.

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

        Returns:
            The newly-created Resource.
        otelc                 S   s   h | ]}|r|  qS r   )strip).0#otel_experimental_resource_detectorr   r   r   	<setcomp>   s    z"Resource.create.<locals>.<setcomp>r   ,opentelemetry_resource_detector)groupnameNunknown_service:)unionr   getr   splitappendnextiterr   r    loadget_aggregated_resources_DEFAULT_RESOURCEmerger   r   SERVICE_NAMEr   r   strPROCESS_EXECUTABLE_NAME)r   r   $otel_experimental_resource_detectorsresource_detectorsresource_detectorresourcedefault_service_nameprocess_executable_namer   r   r   create   sR   

zResource.createc                   C   s   t S N)_EMPTY_RESOURCEr   r   r   r   	get_empty   s   zResource.get_emptyc                 C      | j S r>   )r   r   r   r   r   r         zResource.attributesc                 C   rA   r>   )r   rB   r   r   r   r      rC   zResource.schema_urlotherc                 C   sn   | j  }||j  | jdkr|j}n|jdkr| j}n| j|jkr'|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   rD   merged_attributesr   r   r   r   r3      s   



zResource.mergec                 C   s&   t |tsdS | j|jko| j|jkS )NF)
isinstancer   r   r   )r   rD   r   r   r   __eq__  s
   

zResource.__eq__c                 C   s"   t t| j dd d| j S )NT)	sort_keys|)hashr   r   rE   r   rB   r   r   r   __hash__   s   zResource.__hash__   indentc                 C   s   t | j}t|| jd|dS )N)r   r   )rQ   )dictr   r   r   )r   rQ   r   r   r   r   to_json%  s   zResource.to_jsonr>   )NNr   r   )rD   r   r   r   )rP   )__name__
__module____qualname____doc__r
   __annotations__r5   
Attributestypingr   r   staticmethodr=   r@   propertyr   r   r3   objectboolrK   intrO   rS   r   r   r   r   r      s<   
 
<
#r   pythonopentelemetryc                   @   s0   e Zd Zd
deddfddZejddd	ZdS )ResourceDetectorFraise_on_errorr   Nc                 C   s
   || _ d S r>   )rd   )r   rd   r   r   r   r   =  s   
zResourceDetector.__init__r   c                 C   s   t  )zdDon't call `Resource.create` here to avoid an infinite loop, instead instantiate `Resource` directly)NotImplementedErrorrB   r   r   r   detect@  s   zResourceDetector.detect)FrT   )rU   rV   rW   r_   r   abcabstractmethodrf   r   r   r   r   rc   <  s    rc   c                   @      e Zd ZdddZdS )OTELResourceDetectorr   r   c           	      C   s   t t}i }|rC|dD ]4}z|jddd\}}W n ty4 } ztd|| W Y d }~qd }~ww t|	 }|||	 < qt t
}|rN||t< t|S )Nr$   =   )maxsplitz0Invalid key value resource attribute pair %s: %s)r   r+   r   r,   
ValueErrorrG   warningr	   unquoter    r   r4   r   )	r   env_resources_itemsenv_resource_mapitemkeyvalueexcvalue_url_decodedservice_namer   r   r   rf   H  s*   

zOTELResourceDetector.detectNrT   rU   rV   rW   rf   r   r   r   r   rj   F      rj   c                   @   ri   )ProcessResourceDetectorr   r   c                 C   s   d tttjjdkrtjjstjd d ntj}t }tj	}tj
|}tjd }d tj}tj}ttjttjjt|t|t|t|t|t|t|i	}ttdrWt |t< td urgt }	|	 }
|
|t< t |S )N.final   r    getppid)!joinmapr5   sysversion_inforeleaselevelserialosgetpid
executablepathdirnameargvPROCESS_RUNTIME_DESCRIPTIONr   PROCESS_RUNTIME_NAMEimplementationr'   PROCESS_RUNTIME_VERSIONPROCESS_PIDr6   PROCESS_EXECUTABLE_PATHPROCESS_COMMANDPROCESS_COMMAND_LINEPROCESS_COMMAND_ARGShasattrr   PROCESS_PARENT_PIDr   ProcessusernamePROCESS_OWNERr   )r   _runtime_version_process_pid_process_executable_name_process_executable_path_process_command_process_command_line_process_command_argsresource_infoprocessr   r   r   r   rf   b  sB   

zProcessResourceDetector.detectNrT   ry   r   r   r   r   r{   `  rz   r{   c                   @      e Zd ZdZdddZdS )OsResourceDetectorzxDetect os resources based on `Operating System conventions <https://opentelemetry.io/docs/specs/semconv/resource/os/>`_.r   r   c                 C   sJ   t   }t  }|dkrt  }n
|dkrd}t  }tt|t|iS )a  Returns a resource with with ``os.type`` and ``os.version``.

        Python's platform library
        ~~~~~~~~~~~~~~~~~~~~~~~~~

        To grab this information, Python's ``platform`` does not return what a
        user might expect it to. Below is a breakdown of its return values in
        different operating systems.

        .. code-block:: python
            :caption: Linux

            >>> platform.system()
            'Linux'
            >>> platform.release()
            '6.5.0-35-generic'
            >>> platform.version()
            '#35~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Tue May  7 09:00:52 UTC 2'

        .. code-block:: python
            :caption: MacOS

            >>> platform.system()
            'Darwin'
            >>> platform.release()
            '23.0.0'
            >>> platform.version()
            'Darwin Kernel Version 23.0.0: Fri Sep 15 14:42:57 PDT 2023; root:xnu-10002.1.13~1/RELEASE_ARM64_T8112'

        .. code-block:: python
            :caption: Windows

            >>> platform.system()
            'Windows'
            >>> platform.release()
            '2022Server'
            >>> platform.version()
            '10.0.20348'

        .. code-block:: python
            :caption: FreeBSD

            >>> platform.system()
            'FreeBSD'
            >>> platform.release()
            '14.1-RELEASE'
            >>> platform.version()
            'FreeBSD 14.1-RELEASE releng/14.1-n267679-10e31f0946d8 GENERIC'

        .. code-block:: python
            :caption: Solaris

            >>> platform.system()
            'SunOS'
            >>> platform.release()
            '5.11'
            >>> platform.version()
            '11.4.0.15.0'

        windowssunossolaris)platformsystemlowerreleaser   r   OS_TYPE
OS_VERSION)r   os_type
os_versionr   r   r   rf     s   >
zOsResourceDetector.detectNrT   rU   rV   rW   rX   rf   r   r   r   r   r     s    r   c                   @   r   )_HostResourceDetectorzT
    The HostResourceDetector detects the hostname and architecture attributes.
    r   r   c                 C   s   t tt tt iS r>   )r   	HOST_NAMEsocketgethostname	HOST_ARCHr   machinerB   r   r   r   rf     s
   z_HostResourceDetector.detectNrT   r   r   r   r   r   r     s    r      	detectorsinitial_resourcetimeoutr   c           
         s  |pt  }tjjddt  fdd| D }t|D ]]\}}| | }t}zMz|j|d}W n= tjjyN }	 z|j	r=|	t
d|| W Y d}	~	n"d}	~	w tyk }	 z|j	rZ|	t
d|	| W Y d}	~	nd}	~	ww W ||}q||}w W d   |S 1 sw   Y  |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:
    rP   )max_workersc                    s   g | ]}  |jqS r   )submitrf   )r!   detectorexecutorr   r   
<listcomp>  s    z,get_aggregated_resources.<locals>.<listcomp>)r   z1Detector %s took longer than %s seconds, skippingNz%Exception %s in detector %s, ignoring)r   r=   
concurrentfuturesThreadPoolExecutor	enumerater?   resultTimeoutErrorrd   rG   ro   	Exceptionr3   )
r   r   r   detectors_merged_resourcer   detector_indfuturer   detected_resourceexr   r   r   r1     sH   

r1   )Nr   )rX   rg   concurrent.futuresr   loggingr   r   r   r   r[   jsonr   r   typesr   r   r   r   r   urllibr	   opentelemetry.attributesr
   'opentelemetry.sdk.environment_variablesr   r   r   opentelemetry.semconv.resourcer   &opentelemetry.util._importlib_metadatar   r   opentelemetry.util.typesr   r   rY   psutil_moduleImportError
LabelValueMappingr5   rZ   	getLoggerrU   rG   CLOUD_PROVIDERCLOUD_ACCOUNT_IDCLOUD_REGIONCLOUD_AVAILABILITY_ZONECONTAINER_NAMECONTAINER_IDCONTAINER_IMAGE_NAMECONTAINER_IMAGE_TAGDEPLOYMENT_ENVIRONMENT	FAAS_NAMEFAAS_IDFAAS_VERSIONFAAS_INSTANCEr   r   	HOST_TYPEHOST_IMAGE_NAMEHOST_IMAGE_IDHOST_IMAGE_VERSIONK8S_CLUSTER_NAMEKUBERNETES_CLUSTER_NAMEK8S_NAMESPACE_NAMEKUBERNETES_NAMESPACE_NAMEK8S_POD_UIDKUBERNETES_POD_UIDK8S_POD_NAMEKUBERNETES_POD_NAMEK8S_CONTAINER_NAMEKUBERNETES_CONTAINER_NAMEK8S_REPLICASET_UIDKUBERNETES_REPLICA_SET_UIDK8S_REPLICASET_NAMEKUBERNETES_REPLICA_SET_NAMEK8S_DEPLOYMENT_UIDKUBERNETES_DEPLOYMENT_UIDK8S_DEPLOYMENT_NAMEKUBERNETES_DEPLOYMENT_NAMEK8S_STATEFULSET_UIDKUBERNETES_STATEFUL_SET_UIDK8S_STATEFULSET_NAMEKUBERNETES_STATEFUL_SET_NAMEK8S_DAEMONSET_UIDKUBERNETES_DAEMON_SET_UIDK8S_DAEMONSET_NAMEKUBERNETES_DAEMON_SET_NAMEK8S_JOB_UIDKUBERNETES_JOB_UIDK8S_JOB_NAMEKUBERNETES_JOB_NAMEK8S_CRONJOB_UIDKUBERNETES_CRON_JOB_UIDK8S_CRONJOB_NAMEKUBERNETES_CRON_JOB_NAMEOS_DESCRIPTIONr   r   r   r   r6   r   r   r   r   r   r   r   r   r4   SERVICE_NAMESPACESERVICE_INSTANCE_IDSERVICE_VERSIONTELEMETRY_SDK_NAMETELEMETRY_SDK_VERSIONTELEMETRY_AUTO_VERSIONTELEMETRY_SDK_LANGUAGEr   r   r?   r2   ABCrc   rj   r{   r   r   r`   r1   r   r   r   r   <module>   s   ,
 	
+T