QueueAgePlugin::createFromGlobals()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 13
rs 10
cc 3
nc 2
nop 0
1
<?php
2
3
/**
4
 * @file
5
 * Munin plugin for Beanstalkd "age of waiting jobs in tubes" monitoring
6
 *
7
 * @author: Frédéric G. MARAND <[email protected]>
8
 * @copyright (c) 2014-2020 Ouest Systèmes Informatiques (OSInet)
9
 * @license Apache License 2.0 or later
10
 */
11
12
declare(strict_types=1);
13
14
namespace OSInet\Beanstalkd\Munin;
15
16
use Pheanstalk\Exception;
17
use Pheanstalk\Exception\CommandException;
18
19
class QueueAgePlugin extends BasePlugin
20
{
21
22
    public array $tubes = [];
23
24
    public static function createFromGlobals(): QueueAgePlugin
25
    {
26
        /** @var \OSInet\Beanstalkd\Munin\QueueAgePlugin $instance */
27
        $instance = parent::createFromGlobals();
28
29
        $tubes = getenv('BEANSTALKD_TUBES') ?: 'default';
30
        $tubesArray = explode(' ', $tubes);
31
32
        foreach ($tubesArray as $tube) {
33
            $instance->tubes[$instance->cleanTube($tube)] = $tube;
34
        }
35
36
        return $instance;
37
    }
38
39
    public static function cleanTube($tube)
40
    {
41
        return str_replace('.', '_', $tube);
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function config(): string
48
    {
49
        $ret = <<<'CONFIG'
50
graph_title Job Age
51
graph_vlabel Max Age
52
graph_category Beanstalk
53
graph_args --lower-limit 0
54
graph_scale no
55
56
CONFIG;
57
58
        foreach (array_keys($this->tubes) as $clean) {
59
            $ret .= sprintf("%s_jobs.label %s\n", $clean, $clean);
60
            $ret .= sprintf("%s_jobs.type GAUGE\n", $clean)
61
              . sprintf("%s_jobs.min 0\n", $clean);
62
        }
63
        return $ret;
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     */
69
    public function data(): string
70
    {
71
        $server = $this->server;
72
        $ret = '';
73
74
        foreach ($this->tubes as $clean => $tube) {
75
            $server->useTube($tube);
76
            try {
77
                $job = $server->peekReady();
78
            } catch (\Exception $exc) {
79
                $job = null;
80
            }
81
82
            $val = isset($job)
83
              ? $server->statsJob($job)['age']
84
              : 0;
85
86
            $ret .= sprintf("%s_jobs.value %d\n", $clean, $val);
87
        }
88
89
        return $ret;
90
    }
91
}
92