Completed
Push — master ( 07e153...ca5d76 )
by Stanislav
02:20
created

InfluxDbClient::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
namespace Popstas\Transmission\Console;
4
5
use GuzzleHttp\Exception\ConnectException;
6
use InfluxDB;
7
use Martial\Transmission\API\Argument\Torrent;
8
use Popstas\Transmission\Console\Helpers\TorrentUtils;
9
use Psr\Log\LoggerInterface;
10
11
class InfluxDbClient
12
{
13
    /**
14
     * @var InfluxDB\Client $influxDb
15
     */
16
    private $influxDb;
17
18
    /**
19
     * @var InfluxDB\Database
20
     */
21
    private $database;
22
23
    /**
24
     * @var LoggerInterface
25
     */
26
    private $logger;
27
28
    private $databaseName;
29
30
    public function __construct(InfluxDB\Client $influxDb, $databaseName)
31
    {
32
33
        $this->influxDb = $influxDb;
34
        $this->databaseName = $databaseName;
35
    }
36
37
    /**
38
     * @return InfluxDB\Database $database
39
     */
40
    private function getDatabase()
41
    {
42
        if (!isset($this->database)) {
43
            $this->database = $this->connectDatabase();
44
        }
45
        return $this->database;
46
    }
47
48
    /**
49
     * @param InfluxDB\Database $database
50
     */
51
    public function setDatabase($database)
52
    {
53
        $this->database = $database;
54
    }
55
56
    /**
57
     * Injects a logger.
58
     *
59
     * @param LoggerInterface $logger
60
     */
61
    public function setLogger(LoggerInterface $logger)
62
    {
63
        $this->logger = $logger;
64
    }
65
66
    /**
67
     * @return InfluxDB\Database
68
     * @throws InfluxDB\Database\Exception
69
     */
70
    public function connectDatabase()
71
    {
72
        if (isset($this->database)) {
73
            $this->database;
74
        }
75
76
        $database = $this->influxDb->selectDB($this->databaseName);
77
78
        try {
79
            $databaseExists = $database->exists();
80
        } catch (ConnectException $e) {
81
            throw new \RuntimeException('InfluxDb connection error: ' . $e->getMessage());
82
        }
83
        if (!$databaseExists) {
84
            $this->logger->info('Database ' . $this->databaseName . ' not exists, creating');
85
            $database->create();
86
        }
87
88
        return $database;
89
    }
90
91
    /**
92
     * @param array $torrent
93
     * @param string $transmissionHost
94
     * @return InfluxDB\Point
95
     */
96
    public function buildPoint(array $torrent, $transmissionHost)
97
    {
98
        $age = TorrentUtils::getTorrentAge($torrent);
99
        $lastPoint = $this->getLastPoint($torrent, $transmissionHost);
100
101
        $tagsData = [
102
            'host'             => $transmissionHost,
103
            'torrent_name'     => $torrent[Torrent\Get::NAME],
104
        ];
105
106
        $uploadedDerivative = count($lastPoint) && $torrent[Torrent\Get::UPLOAD_EVER] - $lastPoint['last'] >= 0 ?
107
            $torrent[Torrent\Get::UPLOAD_EVER] - $lastPoint['last'] : $torrent[Torrent\Get::UPLOAD_EVER];
108
109
        $fieldsData = [
110
            'uploaded_last'       => $uploadedDerivative,
111
            'downloaded'          => $torrent[Torrent\Get::TOTAL_SIZE],
112
            'age'                 => $age,
113
            'uploaded_per_day'    => $age ? intval($torrent[Torrent\Get::UPLOAD_EVER] / $age * 86400) : 0,
114
        ];
115
116
        return new InfluxDB\Point(
117
            'uploaded',
118
            $torrent[Torrent\Get::UPLOAD_EVER],
119
            $tagsData,
120
            $fieldsData,
121
            time()
122
        );
123
    }
124
125
    public function getLastPoint(array $torrent, $transmissionHost)
126
    {
127
        $torrentName = $torrent[Torrent\Get::NAME];
128
        $queryBuilder = $this->getDatabase()->getQueryBuilder();
129
        $results = $queryBuilder
130
            ->last('value')
131
            ->from('uploaded')
132
            ->where([
133
                "host='$transmissionHost'",
134
                "torrent_name='$torrentName'"
135
            ])
136
            ->getResultSet()
137
            ->getPoints();
138
139
        return count($results) ? $results[0] : [];
140
    }
141
    
142
    public function writePoints($points, $precision = InfluxDB\Database::PRECISION_SECONDS)
143
    {
144
        return $this->getDatabase()->writePoints($points, $precision);
145
    }
146
147
    /**
148
     * @param array $torrent
149
     * @param string $fieldName
150
     * @param string $transmissionHost
151
     * @param int $lastDays
152
     * @return int
153
     */
154
    public function getTorrentSum(array $torrent, $fieldName, $transmissionHost = '', $lastDays = 0)
155
    {
156
        $where = [];
157
158
        if (isset($torrent[Torrent\Get::NAME])) {
159
            $where[] = "torrent_name = '" . $torrent[Torrent\Get::NAME] . "'";
160
        }
161
162
        if ($transmissionHost) {
163
            $where[] = "host = '" . $transmissionHost . "'";
164
        }
165
166
        if ($lastDays) {
167
            $fromTimestamp = strtotime('-2 hours');
168
            $fromDate = date('c', $fromTimestamp);
169
            $where[] = "time >= '$fromDate'";
170
        }
171
172
        $results = $this->getDatabase()->getQueryBuilder()
173
            ->from('uploaded')
174
            ->select("sum($fieldName) as $fieldName")
175
            ->where($where)
176
            ->getResultSet()
177
            ->getPoints();
178
        ;
179
180
        $this->logger->debug($this->influxDb->getLastQuery());
181
182
        if (!empty($results)) {
183
            return $results[0][$fieldName];
184
        }
185
        return 0;
186
    }
187
}
188