forked from endclothing/prometheus_client_php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPushGateway.php
101 lines (93 loc) · 2.99 KB
/
PushGateway.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
declare(strict_types = 1);
namespace Prometheus;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use RuntimeException;
class PushGateway
{
/**
* @var string
*/
private $address;
/**
* PushGateway constructor.
* @param $address string host:port of the push gateway
*/
public function __construct($address)
{
$this->address = $address;
}
/**
* Pushes all metrics in a Collector, replacing all those with the same job.
* Uses HTTP PUT.
* @param CollectorRegistry $collectorRegistry
* @param string $job
* @param array $groupingKey
* @throws GuzzleException
*/
public function push(CollectorRegistry $collectorRegistry, string $job, array $groupingKey = null): void
{
$this->doRequest($collectorRegistry, $job, $groupingKey, 'put');
}
/**
* Pushes all metrics in a Collector, replacing only previously pushed metrics of the same name and job.
* Uses HTTP POST.
* @param CollectorRegistry $collectorRegistry
* @param $job
* @param $groupingKey
* @throws GuzzleException
*/
public function pushAdd(CollectorRegistry $collectorRegistry, string $job, array $groupingKey = null): void
{
$this->doRequest($collectorRegistry, $job, $groupingKey, 'post');
}
/**
* Deletes metrics from the Push Gateway.
* Uses HTTP POST.
* @param string $job
* @param array $groupingKey
* @throws GuzzleException
*/
public function delete(string $job, array $groupingKey = null): void
{
$this->doRequest(null, $job, $groupingKey, 'delete');
}
/**
* @param CollectorRegistry $collectorRegistry
* @param string $job
* @param array $groupingKey
* @param string $method
* @throws GuzzleException
*/
private function doRequest(CollectorRegistry $collectorRegistry, string $job, array $groupingKey, $method): void
{
$url = "http://" . $this->address . "/metrics/job/" . $job;
if (!empty($groupingKey)) {
foreach ($groupingKey as $label => $value) {
$url .= "/" . $label . "/" . $value;
}
}
$client = new Client();
$requestOptions = [
'headers' => [
'Content-Type' => RenderTextFormat::MIME_TYPE,
],
'connect_timeout' => 10,
'timeout' => 20,
];
if ($method != 'delete') {
$renderer = new RenderTextFormat();
$requestOptions['body'] = $renderer->render($collectorRegistry->getMetricFamilySamples());
}
$response = $client->request($method, $url, $requestOptions);
$statusCode = $response->getStatusCode();
if ($statusCode != 202) {
$msg = "Unexpected status code "
. $statusCode
. " received from push gateway "
. $this->address . ": " . $response->getBody();
throw new RuntimeException($msg);
}
}
}