-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathRedisTxn.php
More file actions
300 lines (261 loc) · 8.01 KB
/
RedisTxn.php
File metadata and controls
300 lines (261 loc) · 8.01 KB
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
<?php
declare(strict_types=1);
namespace Prometheus\Storage;
use Prometheus\Exception\StorageException;
use Prometheus\Histogram;
use Prometheus\MetricFamilySamples;
use Prometheus\Storage\RedisTxn\Collecter\CounterCollecter;
use Prometheus\Storage\RedisTxn\Collecter\GaugeCollecter;
use Prometheus\Storage\RedisTxn\Collecter\HistogramCollecter;
use Prometheus\Storage\RedisTxn\Collecter\SummaryCollecter;
use Prometheus\Storage\RedisTxn\Updater\CounterUpdater;
use Prometheus\Storage\RedisTxn\Updater\GaugeUpdater;
use Prometheus\Storage\RedisTxn\Updater\HistogramUpdater;
use Prometheus\Storage\RedisTxn\Updater\SummaryUpdater;
use function \sort;
/**
* This is a storage adapter that persists Prometheus metrics in Redis.
*
* This library currently has two alternative Redis adapters:
* - {@see \Prometheus\Storage\Redis}: Initial Redis adapter written for this library.
* - {@see \Prometheus\Storage\RedisNg}: "Next-generation" adapter refactored to avoid use of the KEYS command to improve performance.
*
* While the next-generation adapter was an enormous performance improvement over the first, it still suffers from
* performance degradation that scales significantly as the number of metrics grows. This is largely due to the fact
* that the "collect" phase for metrics generally involves at least one network request per metric of each type.
*
* This adapter refactors the {@see \Prometheus\Storage\RedisNg} adapter to generally try and execute the "update" and
* "collect" operations of each metric type within a single Redis transaction.
*
* @todo Reimplement wipeStorage() to account for reorganized keys in Redis.
* @todo Reimplement all Redis scripts with redis.pcall() to trap runtime errors that are ignored by redis.call().
*/
class RedisTxn implements Adapter
{
/**
* @var mixed[]
*/
private static $defaultOptions = [
'host' => '127.0.0.1',
'port' => 6379,
'timeout' => 0.1,
'read_timeout' => '10',
'persistent_connections' => false,
'password' => null,
];
/**
* @var string
*/
private static $prefix = 'PROMETHEUS_';
/**
* @var mixed[]
*/
private $options = [];
/**
* @var \Redis
*/
private $redis;
/**
* @var boolean
*/
private $connectionInitialized = false;
/**
* Redis constructor.
* @param mixed[] $options
*/
public function __construct(array $options = [])
{
$this->options = array_merge(self::$defaultOptions, $options);
$this->redis = new \Redis();
}
/**
* @param \Redis $redis
* @return self
* @throws StorageException
*/
public static function fromExistingConnection(\Redis $redis): self
{
if ($redis->isConnected() === false) {
throw new StorageException('Connection to Redis server not established');
}
$self = new self();
$self->connectionInitialized = true;
$self->redis = $redis;
return $self;
}
/**
* @throws StorageException
* @deprecated use replacement method wipeStorage from Adapter interface
*/
public function flushRedis(): void
{
$this->wipeStorage();
}
/**
* @inheritDoc
*/
public function wipeStorage(): void
{
$this->ensureOpenConnection();
$searchPattern = "";
$globalPrefix = $this->redis->getOption(\Redis::OPT_PREFIX);
// @phpstan-ignore-next-line false positive, phpstan thinks getOptions returns int
if (is_string($globalPrefix)) {
$searchPattern .= $globalPrefix;
}
$searchPattern .= self::$prefix;
$searchPattern .= '*';
$this->redis->eval(
<<<LUA
local cursor = "0"
repeat
local results = redis.call('SCAN', cursor, 'MATCH', ARGV[1])
cursor = results[1]
for _, key in ipairs(results[2]) do
redis.call('DEL', key)
end
until cursor == "0"
LUA
,
[$searchPattern],
0
);
}
/**
* @return MetricFamilySamples[]
* @throws StorageException
*/
public function collect(): array
{
// Ensure Redis connection
$this->ensureOpenConnection();
// Collect all metrics
$counters = $this->collectCounters();
$histograms = $this->collectHistograms();
$gauges = $this->collectGauges();
$summaries = $this->collectSummaries();
return array_merge(
$counters,
$histograms,
$gauges,
$summaries
);
}
/**
* @throws StorageException
*/
private function ensureOpenConnection(): void
{
if ($this->connectionInitialized === true) {
return;
}
$this->connectToServer();
if ($this->options['password'] !== null) {
$this->redis->auth($this->options['password']);
}
if (isset($this->options['database'])) {
$this->redis->select($this->options['database']);
}
$this->redis->setOption(\Redis::OPT_READ_TIMEOUT, $this->options['read_timeout']);
$this->connectionInitialized = true;
}
/**
* @throws StorageException
*/
private function connectToServer(): void
{
try {
$connection_successful = false;
if ($this->options['persistent_connections'] !== false) {
$connection_successful = $this->redis->pconnect(
$this->options['host'],
(int)$this->options['port'],
(float)$this->options['timeout']
);
} else {
$connection_successful = $this->redis->connect($this->options['host'], (int)$this->options['port'], (float)$this->options['timeout']);
}
if (!$connection_successful) {
throw new StorageException("Can't connect to Redis server", 0);
}
} catch (\RedisException $e) {
throw new StorageException("Can't connect to Redis server", 0, $e);
}
}
/**
* @inheritDoc
*/
public function updateHistogram(array $data): void
{
// Ensure Redis connection
$this->ensureOpenConnection();
// Update metric
$updater = new HistogramUpdater($this->redis);
$updater->update($data);
}
/**
* @inheritDoc
*/
public function updateSummary(array $data): void
{
// Ensure Redis connection
$this->ensureOpenConnection();
// Update metric
$updater = new SummaryUpdater($this->redis);
$updater->update($data);
}
/**
* @inheritDoc
*/
public function updateGauge(array $data): void
{
// Ensure Redis connection
$this->ensureOpenConnection();
// Update metric
$updater = new GaugeUpdater($this->redis);
$updater->update($data);
}
/**
* @inheritDoc
*/
public function updateCounter(array $data): void
{
// Ensure Redis connection
$this->ensureOpenConnection();
// Update metric
$updater = new CounterUpdater($this->redis);
$updater->update($data);
}
/**
* @return MetricFamilySamples[]
*/
private function collectHistograms(): array
{
$collector = new HistogramCollecter($this->redis);
return $collector->getMetricFamilySamples();
}
/**
* @return MetricFamilySamples[]
*/
private function collectSummaries(): array
{
$collector = new SummaryCollecter($this->redis);
return $collector->getMetricFamilySamples();
}
/**
* @return MetricFamilySamples[]
*/
private function collectGauges(): array
{
$collector = new GaugeCollecter($this->redis);
return $collector->getMetricFamilySamples();
}
/**
* @return MetricFamilySamples[]
*/
private function collectCounters(): array
{
$collector = new CounterCollecter($this->redis);
return $collector->getMetricFamilySamples();
}
}