bgV~ddlZddlmZddlZddlZddlmZddlmZm Z m Z ddl m Z m Z mZmZddlmZddlmZmZejd kr eZejZnd Zd Zd ZGd deZGddeZGddeZGddeZ GddeZ!GddeZ"GddeZ#dS)N)Lock)values)ExceptionCounterInprogressTrackerTimer)MetricMETRIC_LABEL_NAME_REMETRIC_NAME_RERESERVED_METRIC_LABEL_NAME_RE)REGISTRY)floatToGoStringINF)c8tj|||jSN)types MethodType __class__)funcobjs j/builddir/build/BUILD/cloudlinux-venv-1.0.7/venv/lib/python3.11/site-packages/prometheus_client/metrics.pycreate_bound_methodrsc3=999cd}|r||dzz }|r||dzz }||z }|dkr|dr |dd}|r |d|zs|d|zz }|r|dvrtd|z|S)N_counter_totali)infostatesetz2Metric name is of a type that cannot have a unit: )endswith ValueError) metric_typename namespace subsystemunit full_names r_build_full_namer*sI%Y_$ %Y_$  IiI$6$6x$@$@crcN   I&&sTz22 S4Z  [ 333MPYYZZZ rct|}|D]i}tj|std|zt j|rtd|z||jvrtd|zj|S)NzInvalid label metric name: zReserved label metric name: )tupler matchr#r _reserved_labelnames)cls labelnamesls r_validate_labelnamesr2'sz""J AA#)!,, @:Q>?? ? ( .q 1 1 A;a?@@ @ ( ( (;a?@@ @ ) rc~eZdZdZdZdZdZdZdZdZ dZ d Z d Z dd d d e dfd Zd ZdZdZdZdZdZdS)MetricWrapperBaseNc.|j p |jo|jSr _labelnames _labelvaluesselfs r_is_observablez MetricWrapperBase._is_observable7s ##O(8(NT=NOrcv|s$tdt|jzdS)Nz!%s metric is missing label values)r<r#str_typer:s r_raise_if_not_observablez*MetricWrapperBase._raise_if_not_observable=sA""$$ T@3tz??RSS S T Trc |jo|j Srr7r:s r _is_parentzMetricWrapperBase._is_parentDs9(9$99rcNt|j|j|j|jSr)r _name_documentationr?_unitr:s r _get_metriczMetricWrapperBase._get_metricGsdj$"5tz4:NNNrc,|gSr)rGr:s rdescribezMetricWrapperBase.describeJs  ""##rc|}|D]%\}}}||j|z||&|gSr)rG_samples add_samplerD)r;metricsuffixlabelsvalues rcollectzMetricWrapperBase.collectMs\!!##%)]]__ B B !FFE   dj6165 A A A AxrcBd|j|jS)Nz{0}:{1})formatr?rDr:s r__str__zMetricWrapperBase.__str__Ss DJ777rclt|}d|j|j|jS)Nz {0}.{1}({2}))typerS __module____name__rD)r;r$s r__repr__zMetricWrapperBase.__repr__Vs/4jj $$[%;[=QSWS]^^^rrc t|j|||||_t|||_t |pd|_i|_||_||_ tj |jstd|jz| rt|_i|_|r||js|r||dSdSdS)Nr5zInvalid metric name: )r*r?rDr2r8r,r9_kwargsrErFr r-r#rBr_lock_metricsr< _metric_initregister) r;r% documentationr0r&r'r(registry labelvaluess r__init__zMetricWrapperBase.__init__Zs&dj$ 9dSS /jAA!+"344 + #DJ// C4tzABB B ??   DJDM            ( (!!$''''' ( ( ( (rc |jstd|z|jr:t|dtt |j|jd|rrtdrUt t |jkrtdt fd|jD}nMt|t|jkrtdt d|D}|j5||j vr4|j |j f|j |j|j |d |j|j |<|j |cd d d S#1swxYwYd S) arReturn the child for the given labelset. All metrics can have labels, allowing grouping of related time series. Taking a counter as an example: from prometheus_client import Counter c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) c.labels('get', '/').inc() c.labels('post', '/submit').inc() Labels can also be provided as keyword arguments: from prometheus_client import Counter c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) c.labels(method='get', endpoint='/').inc() c.labels(method='post', endpoint='/submit').inc() See the best practices on [naming](http://prometheus.io/docs/practices/naming/) and [labels](http://prometheus.io/docs/practices/instrumentation/#use-labels). ,No label names were set when constructing %sz already has labels set (z#); can not chain calls to .labels()z"Can't pass both *args and **kwargszIncorrect label namesc3BK|]}t|VdSrunicode).0r1 labelkwargss r z+MetricWrapperBase.labels..s/RRA A 7 7RRRRRRrzIncorrect label countc34K|]}t|VdSrrgrir1s rrkz+MetricWrapperBase.labels..s(@@q @@@@@@r)r`r0r(rbN)r8r#r9dictzipsortedr,lenr\r]rrDrErFr[)r;rbrjs `rrOzMetricWrapperBase.labels{s. TKdRSS S   S)4+<==>>>>   C; CABB B  Ak""fT-=&>&>>> !8999RRRRAQRRRRRKK;3t'7#8#888 !8999@@K@@@@@K Z . .$-//-;T^J."&"5#/ + .. l .. k*=- . . . . . . . . . . . . . . . . . .sA E11E58E5cR|jstd|z t|t|jkr&tdt|j|fztd|D}|j5|j|=ddddS#1swxYwYdS)Nrez+Incorrect label count (expected %d, got %s)c34K|]}t|VdSrrgrms rrkz+MetricWrapperBase.remove..s(<<1GAJJ<<<<<!>??M060A0A Y Y, utMD9L9L9N9N4O4O$OPPRWXXXXX Y Y Ys 044c&td|z)Nz*_child_samples() must be implemented by %rNotImplementedErrorr:s rrwz MetricWrapperBase._child_sampless!"NQU"UVVVrc&td|z)z Initialize the metric object as a child, i.e. when it has labels (if any) set. This is factored as a separate function to allow for deferred initialization. z(_metric_init() must be implemented by %rrr:s rr^zMetricWrapperBase._metric_inits ""Lt"STTTr)rXrW __qualname__r?r.r<r@rBrGrIrQrTrYr rcrOrtrKrvrwr^r5rrr4r43s2 EPPP TTT:::OOO$$$ 888___"!((((B5.5.5.n + + +))) YYYWWWUUUUUrr4c4eZdZdZdZdZd dZefdZdZ dS) CounterarA Counter tracks counts of events or running totals. Example use cases for Counters: - Number of requests processed - Number of items that were inserted into a queue - Total amount of data that a system has processed Counters can only go up (and be reset when the process restarts). If your use case can go down, you should use a Gauge instead. An example for a Counter: from prometheus_client import Counter c = Counter('my_failures_total', 'Description of counter') c.inc() # Increment by 1 c.inc(1.6) # Increment by given value There are utilities to count exceptions raised: @c.count_exceptions() def f(): pass with c.count_exceptions(): pass # Count only one type of exception with c.count_exceptions(ValueError): pass rctj|j|j|jdz|j|j|_tj|_dS)Nr) r ValueClassr?rDr8r9_valuetime_createdr:s rr^zCounter._metric_initsD' DJ X@UW[Wg(,(9;;   rrcd|dkrtd|j|dS)z&Increment counter by the given amount.rz9Counters can only be incremented by non-negative amounts.N)r#rincr;amounts rrz Counter.incs4 A::XYY Y rcJ|t||S)zCount exceptions in a block of code or function. Can be used as a function decorator or context manager. Increments the counter when an exception of the given type is raised up out of the code. )r@r)r; exceptions rcount_exceptionszCounter.count_exceptionss& %%'''i000rcNdi|jfdi|jffS)Nrr)rgetrr:s rrwzCounter._child_sampless. r4;??,, - T] +  rNr) rXrWr__doc__r?r^r Exceptionrrwr5rrrrsp> E$$$     *31111     rrceZdZdZdZedZddddeddffd Zd Z dd Z dd Z d Z dZ dZdZdZdZxZS)GaugeaGauge metric, to report instantaneous values. Examples of Gauges include: - Inprogress requests - Number of items in a queue - Free memory - Total memory - Temperature Gauges can go both up and down. from prometheus_client import Gauge g = Gauge('my_inprogress_requests', 'Description of gauge') g.inc() # Increment by 1 g.dec(10) # Decrement by given value g.set(4.2) # Set to a given value There are utilities for common use cases: g.set_to_current_time() # Set to current unixtime # Increment when entered, decrement when exited. @g.track_inprogress() def f(): pass with g.track_inprogress(): pass A Gauge can also take its value from a callback: d = Gauge('data_objects', 'Number of objects') my_dict = {} d.set_function(lambda: len(my_dict)) gauge)minmaxlivesumliveallallr5rNrc | |_| |jvrtd| ztt||||||||||j|jd<dS)NzInvalid multiprocess mode: r%r`r0r&r'r(rarbmultiprocess_mode)_multiprocess_mode_MULTIPROC_MODESr#superrrcr[) r;r%r`r0r&r'r(rarbrrs rrczGauge.__init__=s#4 D$9 9 9:=NNOO O eT##'!# $ -1,C ()))rctj|j|j|j|j|j|j|_dS)N)r)rrr?rDr8r9rrr:s rr^zGauge._metric_initWs<' J DJ0@$BS"5    rrc:|j|dS)z$Increment gauge by the given amount.Nrrrs rrz Gauge.inc]s rc<|j| dS)z$Decrement gauge by the given amount.Nrrs rdecz Gauge.decas      rcT|jt|dS)zSet gauge to the given value.N)rsetfloat)r;rPs rrz Gauge.setes" e %%%%%rcR|tjdS)z"Set gauge to the current unixtime.N)rrr:s rset_to_current_timezGauge.set_to_current_timeis  rcH|t|S)zTrack inprogress blocks of code or functions. Can be used as a function decorator or context manager. Increments the gauge when the code is entered, and decrements when it is exited. )r@rr:s rtrack_inprogresszGauge.track_inprogressms$ %%''' &&&rcR|t|jS)zTime a block of code or function, and set the duration in seconds. Can be used as a function decorator or context manager. )r@rrr:s rrz Gauge.timews$ %%'''TXrc<fd}t|||_dS)zCall the provided function to return the Gauge value. The function must return a float, and may be called from multiple threads. All other methods of the Gauge become NOOPs. c:ditffSNrr)r;fs rsamplesz#Gauge.set_function..samplessU1133ZZ(* *rN)rrw)r;rrs ` r set_functionzGauge.set_functions6 + + + + +2'4@@rc<di|jffSr)rrr:s rrwzGauge._child_samplessR**+--rr)rXrWrrr? frozensetrr rcr^rrrrrrrrw __classcell__rs@rrrs##H E y!LMM "!#(DDDDDD4       !!!!&&&''' A A A.......rrc4eZdZdZdZdgZdZdZdZdZ dS) SummaryaA Summary tracks the size and number of events. Example use cases for Summaries: - Response latency - Request size Example for a Summary: from prometheus_client import Summary s = Summary('request_size_bytes', 'Request size (bytes)') s.observe(512) # Observe 512 (bytes) Example for a Summary using time: from prometheus_client import Summary REQUEST_TIME = Summary('response_latency_seconds', 'Response latency (seconds)') @REQUEST_TIME.time() def create_response(request): '''A dummy function''' time.sleep(1) Example for using the same Summary object as a context manager: with REQUEST_TIME.time(): pass # Logic to be timed summaryquantilectj|j|j|jdz|j|j|_tj|j|j|jdz|j|j|_tj|_ dS)N_count_sum) rrr?rDr8r9rrrrr:s rr^zSummary._metric_initsq' DJ X@UW[Wg(,(9;; %dj$*dj6>QSWSceievww   rcn|jd|j|dSzObserve the given amount.rN)rrrrs robservezSummary.observes0  frcR|t|jSzTime a block of code or function, and observe the duration in seconds. Can be used as a function decorator or context manager. )r@rrr:s rrz Summary.times& %%'''T\"""rcdi|jfdi|jfdi|jffS)Nrrr)rrrrr:s rrwzSummary._child_samplessB r4;??,, - R ) T] +- -rN) rXrWrrr?r.r^rrrwr5rrrrsi: E&<$$$  ###-----rrc|eZdZdZdZdgZdddddd d d d d ddddefZddddedeffd Z dZ dZ dZ dZ dZxZS) HistogramaA Histogram tracks the size and number of events in buckets. You can use Histograms for aggregatable calculation of quantiles. Example use cases: - Response latency - Request size Example for a Histogram: from prometheus_client import Histogram h = Histogram('request_size_bytes', 'Request size (bytes)') h.observe(512) # Observe 512 (bytes) Example for a Histogram using time: from prometheus_client import Histogram REQUEST_TIME = Histogram('response_latency_seconds', 'Response latency (seconds)') @REQUEST_TIME.time() def create_response(request): '''A dummy function''' time.sleep(1) Example of using the same Histogram object as a context manager: with REQUEST_TIME.time(): pass # Logic to be timed The default buckets are intended to cover a typical web/rpc request from milliseconds to seconds. They can be overridden by passing `buckets` keyword argument to `Histogram`. histogramleg{Gzt?g{Gz?g?g?g333333?g?g?g?g??g@g@g@g$@r5rNc || tt|||||||||| |jd<dS)Nrbuckets)_prepare_bucketsrrrcr[) r;r%r`r0r&r'r(rarbrrs rrczHistogram.__init__sl g&&& i'''!# ( #* Yrcd|D}|t|krtd|r+|dtkr|tt |dkrtd||_dS)Nc,g|]}t|Sr5r)ribs r z.Histogram._prepare_buckets.. s---588---rzBuckets not in sorted orderzMust have at least two buckets)rpr#rappendrq _upper_bounds)r;rs rrzHistogram._prepare_buckets s--W--- fWoo % %:;; ;  wr{c)) NN3    w<> >$rc g|_tj|_|jdz}t j|j|j|jdz|j|j|_ |j D]Z}|j t j|j|j|jdz||jt|fz[dS)N)rr_bucket) _bucketsrrr8rrr?rDr9rrrr)r;bucket_labelnamesrs rr^zHistogram._metric_inits    ,w6%dj$*dj6>QSWSceievww #  A M !2   Y&!!_Q%7%7$99 ";";      rc|j|t|jD].\}}||kr#|j|ddS/dSr)rr enumeraterr)r;ribounds rrzHistogram.observe#sn f!$"455  HAu a $$Q'''  rc*t|jSr)rrr:s rrzHistogram.time+s T\"""rcg}d}t|jD]N\}}||j|z }|ddt |i|fO|di|f|jddkr/|di|jf|di|jft|S)Nrrrrrr) rrrrrrrrr,)r;raccrrs rrwzHistogram._child_samples2s!$"455 M MHAu 4=#'')) )C NNIoe.D.D'EsK L L L L"c*+++  a A % % NNFB 8 9 9 9 B 6777W~~r)rXrWrrr?r.rDEFAULT_BUCKETSr rcrr^rrrwrrs@rrrs!!D E 6S$T2sBS#sTWY]_bcO "!(******0 % % %   ###       rrc(eZdZdZdZdZdZdZdS)InfoaInfo metric, key-value pairs. Examples of Info include: - Build information - Version information - Potential target metadata Example usage: from prometheus_client import Info i = Info('my_build', 'Description of info') i.info({'version': '1.2.3', 'buildhost': 'foo@bar'}) Info metrics do not work in multiprocess mode. r clt|j|_t|_i|_dSr)rr8_labelname_setrr\rr:s rr^zInfo._metric_initQs+!$"233VV  rc|j|rtd|jd||j5t ||_ddddS#1swxYwYdS)zSet info metric.z,Overlapping labels for Info metric, metric: z child: N)r intersectionkeysr#r8r\rnr)r;vals rr z Info.infoVs   + +CHHJJ 7 7 (*   ##'(( ( Z $ $s))DK $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $sA00A47A4cZ|j5d|jdffcdddS#1swxYwYdS)N_infor)r\rr:s rrwzInfo._child_samples^s} Z 3 3dk302 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3s $$N)rXrWrrr?r^r rwr5rrrr?sR E $$$33333rrcHeZdZdZdZddddeddffd ZdZdZd Z xZ S) Enuma`Enum metric, which of a set of states is true. Example usage: from prometheus_client import Enum e = Enum('task_state', 'Description of enum', states=['starting', 'running', 'stopped']) e.state('running') The first listed state will be the default. Enum metrics do not work in multiprocess mode. r!r5rNc tt|||||||||||vrtd|| std|| x|jd<|_dS)Nrz$Overlapping labels for Enum metric: z$No states provided for Enum metric: states)rrrcr#r[_states) r;r%r`r0r&r'r(rarbrrs rrcz Enum.__init__rs dD""'!# #  :  *OPP P Q*OPP P066 Xrc:d|_t|_dS)Nr)rrr\r:s rr^zEnum._metric_inits VV rc||j5|j||_ddddS#1swxYwYdS)zSet enum metric state.N)r@r\rindexr)r;states rrz Enum.states %%''' Z 4 4,,,U33DK 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4s A  A A cj5fdtjDcdddS#1swxYwYdS)NcHg|]\}}dj|i|jkrdndfS)rrr)rDr)rirsr;s rrz'Enum._child_samples..sJAqdj!_1 +;+;aaDr)r\rrr:s`rrwzEnum._child_sampless Z  T\**                  s 6::) rXrWrrr?r rcr^rrwrrs@rrrcs   E "!7777776444 rr)$sys threadingrrrrrcontext_managersrrr metrics_corer r r r rar utilsrr version_infor>rhrrr*r2objectr4rrrrrrr5rrrsr  HHHHHHHHHH''''''''dG*:::      aUaUaUaUaUaUaUaUH; ; ; ; ; ; ; ; |w.w.w.w.w. w.w.w.t8-8-8-8-8-8-8-8-vrrrrr!rrrj!3!3!3!3!3 !3!3!3H::::: :::::r