This repository has been archived by the owner on May 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrometheusExportingServer.php
70 lines (62 loc) · 2 KB
/
PrometheusExportingServer.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
<?php
declare(strict_types=1);
namespace libPrometheus;
use Exception;
use pocketmine\thread\Thread;
use Socket;
class PrometheusExportingServer extends Thread
{
/** @var array<string, PrometheusStatistic> */
private array $datasets = [];
/** @var Socket */
private Socket $socket;
/**
* @throws Exception
*/
public function __construct(int $port)
{
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if(!$socket) throw new Exception("Cannot create socket.");
/** @var Socket $socket */
$this->socket = $socket;
if (!socket_bind($this->socket, "0.0.0.0", $port)) {
throw new Exception("Failed to bind to 0.0.0.0:" . $port);
}
socket_set_option($this->socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_listen($this->socket);
}
protected function onRun(): void
{
$this->registerClassLoader();
while ($this->isRunning()) {
$client = socket_accept($this->socket);
if ($client instanceof Socket) {
$session = new WebSession($client);
$buffer = "";
foreach (((array) $this->datasets) as $dataset) {
$buffer .= $dataset->toReturnableWebString();
}
$session->read();
$session->sendData("text/plain", $buffer);
$session->close();
}
}
}
/**
* @param PrometheusStatistic $statistic
* Add a statistic to the map, or overwrite if existant
*/
public function addStatistic(PrometheusStatistic $statistic): void
{
$this->datasets[$statistic->getIdentifier()] = $statistic;
}
/**
* @param string $identifier
* @return PrometheusStatistic|null
* Get a statistic object
*/
public function getStatistic(string $identifier): ?PrometheusStatistic
{
return array_key_exists($identifier, (array)$this->datasets) ? ((array)$this->datasets)[$identifier] : null;
}
}