1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Aptarus\PromClient; |
4
|
|
|
|
5
|
|
|
use PDO; |
6
|
|
|
use Aptarus\PromClient\Utility as U; |
7
|
|
|
|
8
|
|
|
class Metric |
9
|
|
|
{ |
10
|
|
|
protected static $metrics_db = null; |
11
|
|
|
|
12
|
|
|
public function __construct($typ, $var, $help, $labels, $label_values) |
13
|
|
|
{ |
14
|
|
|
if (!preg_match('/^[a-zA-Z_:][a-zA-Z0-9_:]*$/', $var)) { |
15
|
|
|
throw new Exceptions\InvalidName(sprintf( |
16
|
|
|
"Metric name '%s' is invalid", |
17
|
|
|
$var |
18
|
|
|
)); |
19
|
|
|
} |
20
|
|
|
$this->typ = $typ; |
|
|
|
|
21
|
|
|
$this->var = $var; |
|
|
|
|
22
|
|
|
$this->help = $help; |
|
|
|
|
23
|
|
|
$this->labels = $labels; |
|
|
|
|
24
|
|
|
$this->label_values = $label_values; |
|
|
|
|
25
|
|
|
if (!self::$metrics_db) { |
26
|
|
|
self::$metrics_db = U\PromClientOpenDB(Configuration::$storage_dir); |
27
|
|
|
} |
28
|
|
|
$sth = self::$metrics_db-> |
29
|
|
|
prepare('INSERT INTO meta (var, typ, help) VALUES (?, ?, ?)'); |
30
|
|
|
$sth->execute(array($this->var, $this->typ, $this->help)); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
protected function metricInc($var_value) |
34
|
|
|
{ |
35
|
|
|
$sth = self::$metrics_db-> |
36
|
|
|
prepare('INSERT OR IGNORE INTO metrics |
37
|
|
|
(value,label_values,var,labels) VALUES (?, ?, ?, ?)'); |
38
|
|
|
$sth->execute(array(0, serialize($this->label_values), |
39
|
|
|
$this->var, serialize($this->labels))); |
40
|
|
|
$sth = self::$metrics_db-> |
41
|
|
|
prepare('UPDATE metrics |
42
|
|
|
SET value = value + ?, |
43
|
|
|
label_values = ? |
44
|
|
|
WHERE var = ? AND labels = ?'); |
45
|
|
|
$sth->execute(array($var_value, serialize($this->label_values), |
46
|
|
|
$this->var, serialize($this->labels))); |
47
|
|
|
$this->label_values = []; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
protected function metricSet($var_value) |
51
|
|
|
{ |
52
|
|
|
$sth = self::$metrics_db-> |
53
|
|
|
prepare( |
54
|
|
|
'INSERT INTO metrics (value, label_values, var, labels) |
55
|
|
|
VALUES (?, ?, ?, ?)' |
56
|
|
|
); |
57
|
|
|
|
58
|
|
|
$sth->execute(array($var_value, serialize($this->label_values), |
59
|
|
|
$this->var, serialize($this->labels))); |
60
|
|
|
$this->label_values = []; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
// vim:sw=4 ts=4 et |
65
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: