summaryrefslogtreecommitdiff
path: root/vendor/liuggio/statsd-php-client/src/Liuggio/StatsdClient/StatsdClient.php
blob: c5c16fed4f0d4be7313234f1e55e4201cf784d1c (plain)
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
<?php

namespace Liuggio\StatsdClient;

use Liuggio\StatsdClient\Sender\SenderInterface;
use Liuggio\StatsdClient\Entity\StatsdDataInterface;
use Liuggio\StatsdClient\Exception\InvalidArgumentException;

class StatsdClient implements StatsdClientInterface
{
    /**
     * @var boolean
     */
    private $failSilently;

    /**
     * @var \Liuggio\StatsdClient\Sender\SenderInterface
     */
    private $sender;

    /**
     * @var boolean
     */
    private $reducePacket;

    /**
     * Constructor.
     *
     * @param \Liuggio\StatsdClient\Sender\SenderInterface $sender
     * @param Boolean                                      $reducePacket
     * @param Boolean                                      $fail_silently
     */
    public function __construct(SenderInterface $sender, $reducePacket = true, $fail_silently = true)
    {
        $this->sender       = $sender;
        $this->reducePacket = $reducePacket;
        $this->failSilently = $fail_silently;
    }

    /**
     * Throws an exc only if failSilently if  getFailSilently is false.
     *
     * @param \Exception $exception
     *
     * @throws \Exception
     */
    private function throwException(\Exception $exception)
    {
        if (!$this->getFailSilently()) {
            throw $exception;
        }
    }

    /**
     * This function reduces the number of packets,the reduced has the maximum dimension of self::MAX_UDP_SIZE_STR
     * Reference:
     * https://github.com/etsy/statsd/blob/master/README.md
     * All metrics can also be batch send in a single UDP packet, separated by a newline character.
     *
     * @param array $reducedMetrics
     * @param array $metric
     *
     * @return array
     */
    private static function doReduce($reducedMetrics, $metric)
    {
        $metricLength = strlen($metric);
        $lastReducedMetric = count($reducedMetrics) > 0 ? end($reducedMetrics) : null;

        if ($metricLength >= self::MAX_UDP_SIZE_STR
            || null === $lastReducedMetric
            || strlen($newMetric = $lastReducedMetric . "\n" . $metric) > self::MAX_UDP_SIZE_STR
        ) {
            $reducedMetrics[] = $metric;
        } else {
            array_pop($reducedMetrics);
            $reducedMetrics[] = $newMetric;
        }

        return $reducedMetrics;
    }


    /**
     * this function reduce the amount of data that should be send
     *
     * @param mixed $arrayData
     *
     * @return mixed $arrayData
     */
    public function reduceCount($arrayData)
    {
        if (is_array($arrayData)) {
            $arrayData = array_reduce($arrayData, "self::doReduce", array());
        }

        return $arrayData;
    }

    /**
     *  Reference: https://github.com/etsy/statsd/blob/master/README.md
     *  Sampling 0.1
     *  Tells StatsD that this counter is being sent sampled every 1/10th of the time.
     *
     * @param mixed $data
     * @param int   $sampleRate
     *
     * @return mixed $data
     */
    public function appendSampleRate($data, $sampleRate = 1)
    {
        if ($sampleRate < 1) {
            array_walk($data, function(&$message, $key) use ($sampleRate) {
                $message = sprintf('%s|@%s', $message, $sampleRate);
            });
        }

        return $data;
    }

    /*
     * Send the metrics over UDP
     *
     * {@inheritDoc}
     */
    public function send($data, $sampleRate = 1)
    {
        // check format
        if ($data instanceof StatsdDataInterface || is_string($data)) {
            $data = array($data);
        }
        if (!is_array($data) || empty($data)) {
            return;
        }
        // add sampling
        if ($sampleRate < 1) {
            $data = $this->appendSampleRate($data, $sampleRate);
        }
        // reduce number of packets
        if ($this->getReducePacket()) {
            $data = $this->reduceCount($data);
        }
        //failures in any of this should be silently ignored if ..
        try {
            $fp = $this->getSender()->open();
            if (!$fp) {
                return;
            }
            $written = 0;
            foreach ($data as $key => $message) {
                $written += $this->getSender()->write($fp, $message);
            }
            $this->getSender()->close($fp);
        } catch (\Exception $e) {
            $this->throwException($e);
        }

        return $written;
    }

    /**
     * @param boolean $failSilently
     */
    public function setFailSilently($failSilently)
    {
        $this->failSilently = $failSilently;
    }

    /**
     * @return boolean
     */
    public function getFailSilently()
    {
        return $this->failSilently;
    }

    /**
     * @param \Liuggio\StatsdClient\Sender\SenderInterface $sender
     */
    public function setSender(SenderInterface $sender)
    {
        $this->sender = $sender;
    }

    /**
     * @return \Liuggio\StatsdClient\Sender\SenderInterface
     */
    public function getSender()
    {
        return $this->sender;
    }

    /**
     * @param boolean $reducePacket
     */
    public function setReducePacket($reducePacket)
    {
        $this->reducePacket = $reducePacket;
    }

    /**
     * @return boolean
     */
    public function getReducePacket()
    {
        return $this->reducePacket;
    }

}