This repository has been archived by the owner on Dec 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLokiLoggerThread.php
154 lines (127 loc) · 4.55 KB
/
LokiLoggerThread.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
<?php
namespace libLokiLogger;
use pocketmine\thread\Thread;
use pocketmine\utils\Internet;
use pocketmine\utils\InternetException;
use pocketmine\utils\SingletonTrait;
use RuntimeException;
use Threaded;
use function array_merge;
use function explode;
use function igbinary_serialize;
use function igbinary_unserialize;
use function json_encode;
use function microtime;
use function strlen;
class LokiLoggerThread extends Thread
{
use SingletonTrait;
public const PUBLISHING_DELAY = 5;
/** @var Threaded */
private Threaded $buffer;
/** @var string */
private string $labels;
/**
* @param string $endpoint The endpoint to grafana loki
* @param array $labels Default labels that will be used to identify the logs' origin.
*/
public function __construct(
private string $composerPath,
private string $endpoint,
array $labels = [])
{
$this->buffer = new Threaded();
$this->labels = igbinary_serialize($labels);
self::setInstance($this);
}
/**
* @param string $line The line of a particular log.
* @param array $labels Optional label to identify the line information.
* @return void
*/
public function write(string $line, array $labels = []): void
{
$currentTime = sprintf("%d", microtime(true) * 1000000000);
$this->synchronized(function () use ($line, $currentTime, $labels): void {
foreach (explode("\n", $line) as $l) {
if ($l !== '') {
$this->buffer[] = igbinary_serialize([$l, $currentTime, $labels]);
}
}
$this->notify();
});
}
public static function getInstance(): self
{
if (self::$instance === null) {
throw new RuntimeException("Grafana Loki is not initialized properly in this environment.");
}
return self::$instance;
}
protected function onRun(): void
{
if (!empty($this->composerPath)) {
require $this->composerPath;
}
$defaultLabels = igbinary_unserialize($this->labels);
while (!$this->isKilled) {
$start = microtime(true);
$this->tickProcessor($defaultLabels);
$time = microtime(true) - $start;
if ($time < self::PUBLISHING_DELAY) {
$sleepUntil = (int)((self::PUBLISHING_DELAY - $time) * 1000000);
$this->synchronized(function () use ($sleepUntil): void {
$this->wait($sleepUntil);
});
}
}
$this->tickProcessor($defaultLabels);
}
private function tickProcessor(array $defaultLabels): void
{
$hasLogs = false;
$mainStream = [];
$secondaryStream = [];
while ($this->buffer->count() > 0) {
$buffer = $this->buffer->shift();
[$message, $timestamp, $labels] = igbinary_unserialize($buffer);
if (empty($labels)) {
$mainStream[] = [$timestamp, $message];
} else {
$secondaryStream[] = [$labels, $timestamp, $message];
}
$hasLogs = true;
}
if ($hasLogs) {
$mainBody["streams"] = [["stream" => $defaultLabels, "values" => $mainStream]];
foreach ($secondaryStream as [$labels, $timestamp, $message]) {
$mainBody["streams"][] = ["stream" => array_merge($defaultLabels, $labels), "values" => [[$timestamp, $message]]];
}
// Retry one more time, if it fails again, we just ignore it and move on to the next logs.
$this->postContent(json_encode($mainBody), 1);
}
}
private function postContent(string $jsonPayload, int $retries): void
{
try {
$v = Internet::simpleCurl($this->endpoint . '/loki/api/v1/push', 10, [
"User-Agent: NetherGamesMC/libLokiLogger",
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonPayload)
], [
CURLOPT_POST => 1,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $jsonPayload
]);
if ($v->getCode() !== 204 && $retries > 0) {
$this->postContent($jsonPayload, $retries - 1);
}
} catch (InternetException) {
if ($retries > 0) {
$this->postContent($jsonPayload, $retries - 1);
}
}
}
}