B
    .l\9                 @   s  d dl mZ d dlZd dlmZ d dlZd dl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 ddlmZ yPd d	lmZ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 W nZ ek
r   d d	l mZmZ d d
l!mZ d dl"mZmZmZ d dl#mZmZmZ Y nX e$dZ%ej&dk Z'efddZ(G dd deZ)defddZ*efddZ+dd Z,G dd deZ-G dd deeZ.defd d!Z/d"d# Z0d$d% Z1d3d&d'Z2dd(e1fd)d*Z3dd(e1fd+d,Z4dd(e1fd-d.Z5d/d0 Z6d1d2 Z7dS )4    )unicode_literalsN)closing)make_serverWSGIRequestHandler   )
exposition)REGISTRY)floatToGoString)BaseHTTPRequestHandler
HTTPServer)ThreadingMixIn)build_openerRequestHTTPHandler)
quote_plus)parse_qsurlparse)r   r   r   z(text/plain; version=0.0.4; charset=utf-8)      c                s    fdd}|S )z;Create a WSGI app which serves the metrics from a registry.c       	         sj   t | dd} }t| d\}}d|kr<||d }||}td}td|fg}||| |gS )NZQUERY_STRING ZHTTP_ACCEPTzname[]z200 OKzContent-type)r   getchoose_encoderrestricted_registrystr)	environZstart_responseparamsrencodercontent_typeoutputZstatusheaders)registry ;lib/python3.7/site-packages/prometheus_client/exposition.pyprometheus_app'   s    
z%make_wsgi_app.<locals>.prometheus_appr"   )r!   r$   r"   )r!   r#   make_wsgi_app%   s    r%   c               @   s   e Zd ZdZdd ZdS )_SilentHandlerz(WSGI handler that does not log requests.c             G   s   dS )zLog nothing.Nr"   )selfformatargsr"   r"   r#   log_message9   s    z_SilentHandler.log_messageN)__name__
__module____qualname____doc__r*   r"   r"   r"   r#   r&   6   s   r&   r   c             C   s8   t |}t|| |td}tj|jd}d|_|  dS )z?Starts a WSGI server for prometheus metrics as a daemon thread.)Zhandler_class)targetTN)r%   r   r&   	threadingThreadserve_foreverdaemonstart)portaddrr!   Zapphttpdtr"   r"   r#   start_wsgi_server=   s
    r9   c             C   s  dd }g }xv|   D ]h}y|j}|j}|dkr>|d }n>|dkrT|d }d}n(|dkrbd}n|d	krpd
}n|dkr|d}|d||jdddd |d|| i }xR|jD ]H}xBdD ],}|j|j| kr||g || P qW ||| qW W n: t	k
rF }	 z|	j
p*d|f |	_
 W dd}	~	X Y nX x8t| D ](\}}
|d|j| ||
 qVW qW d|dS )zHReturns the metrics from the registry in latest text format as a string.c             S   sn   | j r,dddd t| j  D }nd}d}| jd k	rVdtt| jd }d| j|t	| j
|S )	Nz{{{0}}},c          	   S   s4   g | ],\}}d  ||ddddddqS )z	{0}="{1}"\z\\
z\n"z\")r(   replace).0kvr"   r"   r#   
<listcomp>L   s   z8generate_latest.<locals>.sample_line.<locals>.<listcomp>r   z {0:d}i  z{0}{1} {2}{3}
)labelsr(   joinsorteditems	timestampintfloatnamer	   value)sZlabelstrrG   r"   r"   r#   sample_lineI   s    
z$generate_latest.<locals>.sample_lineZcounterZ_totalinfoZ_infoZgaugeZstatesetZgaugehistogramZ	histogramunknownZuntypedz# HELP {0} {1}
r;   z\\r<   z\nz# TYPE {0} {1}
)Z_createdZ_gsumZ_gcount)r   Nz# TYPE {0}{1} gauge
r   zutf-8)ZcollectrJ   typeappendr(   Zdocumentationr>   Zsamples
setdefault	Exceptionr)   rE   rF   extendrD   encode)r!   rM   r   ZmetricZmnameZmtypeZ
om_samplesrL   suffixZ	exceptionlinesr"   r"   r#   generate_latestF   sD    

rX   c             C   sF   | pd} x4|  dD ]&}| dd  dkrtjtjfS qW ttfS )Nr   r:   ;r   zapplication/openmetrics-text)splitstripopenmetricsrX   CONTENT_TYPE_LATEST)Zaccept_headerZacceptedr"   r"   r#   r      s    r   c               @   s0   e Zd ZdZeZdd Zdd Zedd Z	dS )	MetricsHandlerz2HTTP handler that gives metrics from ``REGISTRY``.c             C   s   | j }tt| jj}t| jd\}}d|kr@||d }y||}W n   | 	dd  Y nX | 
d | d| |   | j| d S )NZAcceptzname[]i  zerror generating metric output   zContent-Type)r!   r   r   pathZqueryr   r    r   r   Z
send_errorZsend_responseZsend_headerZend_headersZwfilewrite)r'   r!   r   r   r   r   r"   r"   r#   do_GET   s    
zMetricsHandler.do_GETc             G   s   dS )zLog nothing.Nr"   )r'   r(   r)   r"   r"   r#   r*      s    zMetricsHandler.log_messagec             C   s"   t | j}t|| tfd|i}|S )zWReturns a dynamic MetricsHandler class tied
           to the passed registry.
        r!   )r   r+   rP   object)clsr!   Zcls_nameZMyMetricsHandlerr"   r"   r#   factory   s    



zMetricsHandler.factoryN)
r+   r,   r-   r.   r   r!   rb   r*   classmethodre   r"   r"   r"   r#   r^      s
   r^   c               @   s   e Zd ZdZdZdS )_ThreadingSimpleServerzThread per request HTTP server.TN)r+   r,   r-   r.   Zdaemon_threadsr"   r"   r"   r#   rg      s   rg   c             C   s8   t |}t|| f|}tj|jd}d|_|  dS )z?Starts an HTTP server for prometheus metrics as a daemon thread)r/   TN)r^   re   rg   r0   r1   r2   r3   r4   )r5   r6   r!   ZCustomMetricsHandlerr7   r8   r"   r"   r#   start_http_server   s
    
rh   c          	   C   sL   d| t  t jf }t|d}|t| W dQ R X t ||  dS )zWrite metrics to the given path.

    This is intended for use with the Node exporter textfile collector.
    The path must end in .prom for the textfile collector to process it.z%s.%s.%swbN)	osgetpidr0   Zcurrent_threadZidentopenra   rX   rename)r`   r!   Ztmppathfr"   r"   r#   write_to_textfile   s    ro   c                s    fdd}|S )zDefault handler that implements HTTP/HTTPS connections.

    Used by the push_to_gateway functions. Can be re-used by other handlers.c                 sl   t  d} fdd| _xD ]\}}| || q W ttj| d}|jdkrhtd|j|j	d S )N)datac                  s    S )Nr"   r"   )methodr"   r#   <lambda>   s    z1default_handler.<locals>.handle.<locals>.<lambda>)timeouti  z%error talking to pushgateway: {0} {1})
r   Z
get_methodZ
add_headerr   r   rl   codeIOErrorr(   msg)Zrequestr@   rA   Zresp)rp   r    rq   rs   urlr"   r#   handle   s    
zdefault_handler.<locals>.handler"   )rw   rq   rs   r    rp   rx   r"   )rp   r    rq   rs   rw   r#   default_handler   s    
ry   c                s    fdd}|S )zHandler that implements HTTP/HTTPS connections with Basic Auth.

    Sets auth headers using supplied 'username' and 'password', if set.
    Used by the push_to_gateway functions. Can be re-used by other handlers.c                 sX   dk	rBdk	rBd d} t| }d| }d|g t   dS )z1Handler that implements HTTP Basic Auth.
        Nz{0}:{1}zutf-8s   Basic ZAuthorization)r(   rU   base64Z	b64encoderQ   ry   )Z
auth_valueZ
auth_tokenZauth_header)rp   r    rq   passwordrs   rw   usernamer"   r#   rx      s    
z"basic_auth_handler.<locals>.handler"   )rw   rq   rs   r    rp   r|   r{   rx   r"   )rp   r    rq   r{   rs   rw   r|   r#   basic_auth_handler   s    
r}      c             C   s   t d| ||||| dS )aN  Push metrics to the given pushgateway.

    `gateway` the url for your push gateway. Either of the form
              'http://pushgateway.local', or 'pushgateway.local'.
              Scheme defaults to 'http' if none is provided
    `job` is the job label to be attached to all pushed metrics
    `registry` is an instance of CollectorRegistry
    `grouping_key` please see the pushgateway documentation for details.
                   Defaults to None
    `timeout` is how long push will attempt to connect before giving up.
              Defaults to 30s, can be set to None for no timeout.
    `handler` is an optional function which can be provided to perform
              requests to the 'gateway'.
              Defaults to None, in which case an http or https request
              will be carried out by a default handler.
              If not None, the argument must be a function which accepts
              the following arguments:
              url, method, timeout, headers, and content
              May be used to implement additional functionality not
              supported by the built-in default handler (such as SSL
              client certicates, and HTTP authentication mechanisms).
              'url' is the URL for the request, the 'gateway' argument
              described earlier will form the basis of this URL.
              'method' is the HTTP method which should be used when
              carrying out the request.
              'timeout' requests not successfully completed after this
              many seconds should be aborted.  If timeout is None, then
              the handler should not set a timeout.
              'headers' is a list of ("header-name","header-value") tuples
              which must be passed to the pushgateway in the form of HTTP
              request headers.
              The function should raise an exception (e.g. IOError) on
              failure.
              'content' is the data which should be used to form the HTTP
              Message Body.

    This overwrites all metrics with the same job and grouping_key.
    This uses the PUT HTTP method.ZPUTN)_use_gateway)gatewayjobr!   grouping_keyrs   handlerr"   r"   r#   push_to_gateway   s    )r   c             C   s   t d| ||||| dS )a"  PushAdd metrics to the given pushgateway.

    `gateway` the url for your push gateway. Either of the form
              'http://pushgateway.local', or 'pushgateway.local'.
              Scheme defaults to 'http' if none is provided
    `job` is the job label to be attached to all pushed metrics
    `registry` is an instance of CollectorRegistry
    `grouping_key` please see the pushgateway documentation for details.
                   Defaults to None
    `timeout` is how long push will attempt to connect before giving up.
              Defaults to 30s, can be set to None for no timeout.
    `handler` is an optional function which can be provided to perform
              requests to the 'gateway'.
              Defaults to None, in which case an http or https request
              will be carried out by a default handler.
              See the 'prometheus_client.push_to_gateway' documentation
              for implementation requirements.

    This replaces metrics with the same name, job and grouping_key.
    This uses the POST HTTP method.ZPOSTN)r   )r   r   r!   r   rs   r   r"   r"   r#   pushadd_to_gateway!  s    r   c             C   s   t d| |d||| dS )a  Delete metrics from the given pushgateway.

    `gateway` the url for your push gateway. Either of the form
              'http://pushgateway.local', or 'pushgateway.local'.
              Scheme defaults to 'http' if none is provided
    `job` is the job label to be attached to all pushed metrics
    `grouping_key` please see the pushgateway documentation for details.
                   Defaults to None
    `timeout` is how long delete will attempt to connect before giving up.
              Defaults to 30s, can be set to None for no timeout.
    `handler` is an optional function which can be provided to perform
              requests to the 'gateway'.
              Defaults to None, in which case an http or https request
              will be carried out by a default handler.
              See the 'prometheus_client.push_to_gateway' documentation
              for implementation requirements.

    This deletes metrics with the given job and grouping_key.
    This uses the DELETE HTTP method.DELETEN)r   )r   r   r   rs   r   r"   r"   r#   delete_from_gateway;  s    r   c       
      C   s   t |}|jrtr&|jdkr&d|}d|t|}d}	| dkrJt|}	|d krVi }|ddd t| D 7 }||| |d	t	fg|	d
  d S )N)ZhttpZhttpsz
http://{0}z{0}/metrics/job/{1}    r   r   c             s   s.   | ]&\}}d  tt|tt|V  qdS )z/{0}/{1}N)r(   r   r   )r?   r@   rA   r"   r"   r#   	<genexpr>`  s   z_use_gateway.<locals>.<genexpr>zContent-Type)rw   rq   rs   r    rp   )
r   ZschemePYTHON26_OR_OLDERr(   r   rX   rD   rE   rF   r]   )
rq   r   r   r!   r   rs   r   Zgateway_urlrw   rp   r"   r"   r#   r   S  s    
r   c           	   C   s:   t ttjtj} | d d|  d iS Q R X dS )z>Grouping key with instance set to the IP Address of this host.)Z	localhostr   instancer   N)r   socketZAF_INETZ
SOCK_DGRAMZconnectZgetsockname)rL   r"   r"   r#   instance_ip_grouping_keyi  s    
r   )NN)8Z
__future__r   rz   
contextlibr   rj   r   sysr0   Zwsgiref.simple_serverr   r   r\   r   r!   r   Zutilsr	   ZBaseHTTPServerr
   r   ZSocketServerr   Zurllib2r   r   r   Zurllibr   r   r   ImportErrorZhttp.serverZsocketserverZurllib.requestZurllib.parser   r]   version_infor   r%   r&   r9   rX   r   r^   rg   rh   ro   ry   r}   r   r   r   r   r   r"   r"   r"   r#   <module>   sR   
	=	'
	
+