Cleaner::checking()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 4
nop 0
dl 0
loc 14
rs 9.9666
c 0
b 0
f 0
1
<?php
2
/**
3
 * Crashed program metrics cleaner
4
 * User: moyo
5
 * Date: 18/03/2018
6
 * Time: 1:08 PM
7
 */
8
9
namespace Carno\Monitor\Collector;
10
11
use Carno\Monitor\Contracts\Metrical;
12
use Carno\Monitor\Daemon;
13
use Carno\Timer\Timer;
14
15
class Cleaner
16
{
17
    // special identify for crash reporting
18
    private const SP_IDENTIFY = 'px0';
19
20
    /**
21
     * @var string
22
     */
23
    private $daemon = null;
24
25
    /**
26
     * @var Daemon
27
     */
28
    private $source = null;
29
30
    /**
31
     * @var int
32
     */
33
    private $patrol = null;
34
35
    /**
36
     * @var int
37
     */
38
    private $expired = null;
39
40
    /**
41
     * @var array
42
     */
43
    private $activity = [];
44
45
    /**
46
     * @var int
47
     */
48
    private $crashed = 0;
49
50
    /**
51
     * Cleaner constructor.
52
     * @param Daemon $daemon
53
     * @param int $patrol
54
     * @param int $expired
55
     */
56
    public function __construct(Daemon $daemon, int $patrol = 5, int $expired = 55)
57
    {
58
        $this->source = $daemon;
59
        $this->patrol = $patrol;
60
        $this->expired = $expired;
61
    }
62
63
    /**
64
     * @return static
65
     */
66
    public function start() : self
67
    {
68
        $this->daemon = Timer::loop($this->patrol * 1000, [$this, 'checking']);
69
        return $this;
70
    }
71
72
    /**
73
     */
74
    public function stop() : void
75
    {
76
        $this->daemon && Timer::clear($this->daemon);
77
    }
78
79
    /**
80
     */
81
    public function checking() : void
82
    {
83
        foreach ($this->source->lived() as $pid => $time) {
84
            if ($pid === self::SP_IDENTIFY) {
85
                continue;
86
            }
87
88
            $last = $this->activity[$pid] ?? $time;
89
            $this->activity[$pid] = $time;
90
91
            if (time() - $last >= $this->expired) {
92
                unset($this->activity[$pid]);
93
                $this->source->forget($pid);
94
                $this->reporting();
95
            }
96
        }
97
    }
98
99
    /**
100
     */
101
    private function reporting() : void
102
    {
103
        $this->source->metrics(
104
            self::SP_IDENTIFY,
105
            Metrical::COUNTER,
106
            'program.crashed',
107
            'system',
108
            '',
109
            [],
110
            ['value' => ++ $this->crashed]
111
        );
112
    }
113
}
114