Welcome to mirror list, hosted at ThFree Co, Russian Federation.

CHistory.php « services « api « classes « include « ui - github.com/zabbix/zabbix.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b9d429b163826de2844dd60ed2b2887aeab113c6 (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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
<?php
/*
** Zabbix
** Copyright (C) 2001-2021 Zabbix SIA
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/


/**
 * Class containing methods for operations with histories.
 */
class CHistory extends CApiService {

	public const ACCESS_RULES = [
		'get' => ['min_user_type' => USER_TYPE_ZABBIX_USER]
	];

	protected $tableName;
	protected $tableAlias = 'h';
	protected $sortColumns = ['itemid', 'clock'];

	public function __construct() {
		// considering the quirky nature of the history API,
		// the parent::__construct() method should not be called.
	}

	/**
	 * Get history data.
	 *
	 * @param array  $options
	 * @param int    $options['history']                       History object type to return.
	 * @param array  $options['hostids']                       Return only history from the given hosts.
	 * @param array  $options['itemids']                       Return only history from the given items.
	 * @param int    $options['time_from']                     Return only values that have been received after or at
	 *                                                         the given time.
	 * @param int    $options['time_till']                     Return only values that have been received before or at
	 *                                                         the given time.
	 * @param array  $options['filter']                        Return only those results that exactly match the given
	 *                                                         filter.
	 * @param int    $options['filter']['itemid']
	 * @param int    $options['filter']['clock']
	 * @param mixed  $options['filter']['value']
	 * @param int    $options['filter']['ns']
	 * @param array  $options['search']                        Return results that match the given wildcard search
	 *                                                         (case-insensitive).
	 * @param string $options['search']['value']
	 * @param bool   $options['searchByAny']                   If set to true return results that match any of the
	 *                                                         criteria given in the filter or search parameter instead
	 *                                                         of all of them.
	 * @param bool   $options['startSearch']                   Return results that match the given wildcard search
	 *                                                         (case-insensitive).
	 * @param bool   $options['excludeSearch']                 Return results that do not match the criteria given in
	 *                                                         the search parameter.
	 * @param bool   $options['searchWildcardsEnabled']        If set to true enables the use of "*" as a wildcard
	 *                                                         character in the search parameter.
	 * @param array  $options['output']                        Object properties to be returned.
	 * @param bool   $options['countOutput']                   Return the number of records in the result instead of the
	 *                                                         actual data.
	 * @param array  $options['sortfield']                     Sort the result by the given properties. Refer to a
	 *                                                         specific API get method description for a list of
	 *                                                         properties that can be used for sorting. Macros are not
	 *                                                         expanded before sorting.
	 * @param array  $options['sortorder']                     Order of sorting. If an array is passed, each value will
	 *                                                         be matched to the corresponding property given in the
	 *                                                         sortfield parameter.
	 * @param int    $options['limit']                         Limit the number of records returned.
	 * @param bool   $options['editable']                      If set to true return only objects that the user has
	 *                                                         write permissions to.
	 *
	 * @throws Exception
	 * @return array|int    Data array or number of rows.
	 */
	public function get($options = []) {
		$value_types = [ITEM_VALUE_TYPE_FLOAT, ITEM_VALUE_TYPE_STR, ITEM_VALUE_TYPE_LOG, ITEM_VALUE_TYPE_UINT64,
			ITEM_VALUE_TYPE_TEXT
		];
		$common_value_types = [ITEM_VALUE_TYPE_FLOAT, ITEM_VALUE_TYPE_STR, ITEM_VALUE_TYPE_UINT64,
			ITEM_VALUE_TYPE_TEXT
		];

		$api_input_rules = ['type' => API_OBJECT, 'fields' => [
			// filter
			'history' =>				['type' => API_INT32, 'in' => implode(',', $value_types), 'default' => ITEM_VALUE_TYPE_UINT64],
			'hostids' =>				['type' => API_IDS, 'flags' => API_ALLOW_NULL | API_NORMALIZE, 'default' => null],
			'itemids' =>				['type' => API_IDS, 'flags' => API_ALLOW_NULL | API_NORMALIZE, 'default' => null],
			'time_from' =>				['type' => API_INT32, 'flags' => API_ALLOW_NULL, 'default' => null],
			'time_till' =>				['type' => API_INT32, 'flags' => API_ALLOW_NULL, 'default' => null],
			'filter' =>					['type' => API_MULTIPLE, 'default' => null, 'rules' => [
											['if' => ['field' => 'history', 'in' => implode(',', [ITEM_VALUE_TYPE_LOG])], 'type' => API_OBJECT, 'flags' => API_ALLOW_NULL, 'fields' => [
					'itemid' =>					['type' => API_IDS, 'flags' => API_ALLOW_NULL | API_NORMALIZE],
					'clock' =>					['type' => API_INTS32, 'flags' => API_ALLOW_NULL | API_NORMALIZE],
					'timestamp' =>				['type' => API_INTS32, 'flags' => API_ALLOW_NULL | API_NORMALIZE],
					'source' =>					['type' => API_STRINGS_UTF8, 'flags' => API_ALLOW_NULL | API_NORMALIZE],
					'severity' =>				['type' => API_INTS32, 'flags' => API_ALLOW_NULL | API_NORMALIZE],
					'logeventid' =>				['type' => API_INTS32, 'flags' => API_ALLOW_NULL | API_NORMALIZE],
					'ns' =>						['type' => API_INTS32, 'flags' => API_ALLOW_NULL | API_NORMALIZE]
				]],
											['if' => ['field' => 'history', 'in' => implode(',', [ITEM_VALUE_TYPE_STR, ITEM_VALUE_TYPE_TEXT])], 'type' => API_OBJECT, 'flags' => API_ALLOW_NULL, 'fields' => [
					'itemid' =>					['type' => API_IDS, 'flags' => API_ALLOW_NULL | API_NORMALIZE],
					'clock' =>					['type' => API_INTS32, 'flags' => API_ALLOW_NULL | API_NORMALIZE],
					'ns' =>						['type' => API_INTS32, 'flags' => API_ALLOW_NULL | API_NORMALIZE]
				]],
											['if' => ['field' => 'history', 'in' => implode(',', [ITEM_VALUE_TYPE_UINT64])], 'type' => API_OBJECT, 'flags' => API_ALLOW_NULL, 'fields' => [
					'itemid' =>					['type' => API_IDS, 'flags' => API_ALLOW_NULL | API_NORMALIZE],
					'clock' =>					['type' => API_INTS32, 'flags' => API_ALLOW_NULL | API_NORMALIZE],
					'ns' =>						['type' => API_INTS32, 'flags' => API_ALLOW_NULL | API_NORMALIZE],
					'value' =>					['type' => API_UINTS64, 'flags' => API_ALLOW_NULL | API_NORMALIZE]
				]],
											['if' => ['field' => 'history', 'in' => implode(',', [ITEM_VALUE_TYPE_FLOAT])], 'type' => API_OBJECT, 'flags' => API_ALLOW_NULL, 'fields' => [
					'itemid' =>					['type' => API_IDS, 'flags' => API_ALLOW_NULL | API_NORMALIZE],
					'clock' =>					['type' => API_INTS32, 'flags' => API_ALLOW_NULL | API_NORMALIZE],
					'ns' =>						['type' => API_INTS32, 'flags' => API_ALLOW_NULL | API_NORMALIZE],
					'value' =>					['type' => API_FLOATS, 'flags' => API_ALLOW_NULL | API_NORMALIZE]
				]]
			]],
			'search' =>					['type' => API_MULTIPLE, 'default' => null, 'rules' => [
											['if' => ['field' => 'history', 'in' => implode(',', [ITEM_VALUE_TYPE_LOG])], 'type' => API_OBJECT, 'flags' => API_ALLOW_NULL, 'fields' => [
					'source' =>					['type' => API_STRINGS_UTF8, 'flags' => API_ALLOW_NULL | API_NORMALIZE],
					'value' =>					['type' => API_STRINGS_UTF8, 'flags' => API_ALLOW_NULL | API_NORMALIZE]
				]],
											['if' => ['field' => 'history', 'in' => implode(',', [ITEM_VALUE_TYPE_STR, ITEM_VALUE_TYPE_TEXT])], 'type' => API_OBJECT, 'flags' => API_ALLOW_NULL, 'fields' => [
					'value' =>					['type' => API_STRINGS_UTF8, 'flags' => API_ALLOW_NULL | API_NORMALIZE]
				]],
											['if' => ['field' => 'history', 'in' => implode(',', [ITEM_VALUE_TYPE_FLOAT, ITEM_VALUE_TYPE_UINT64])], 'type' => API_OBJECT, 'flags' => API_ALLOW_NULL, 'fields' => []]
			]],
			'searchByAny' =>			['type' => API_BOOLEAN, 'default' => false],
			'startSearch' =>			['type' => API_FLAG, 'default' => false],
			'excludeSearch' =>			['type' => API_FLAG, 'default' => false],
			'searchWildcardsEnabled' =>	['type' => API_BOOLEAN, 'default' => false],
			// output
			'output' =>					['type' => API_MULTIPLE, 'default' => API_OUTPUT_EXTEND, 'rules' => [
											['if' => ['field' => 'history', 'in' => implode(',', [ITEM_VALUE_TYPE_LOG])], 'type' => API_OUTPUT, 'in' => implode(',', ['itemid', 'clock', 'timestamp', 'source', 'severity', 'value', 'logeventid', 'ns'])],
											['if' => ['field' => 'history', 'in' => implode(',', $common_value_types)], 'type' => API_OUTPUT, 'in' => implode(',', ['itemid', 'clock', 'value', 'ns'])]
			]],
			'countOutput' =>			['type' => API_FLAG, 'default' => false],
			// sort and limit
			'sortfield' =>				['type' => API_STRINGS_UTF8, 'flags' => API_NORMALIZE, 'in' => implode(',', $this->sortColumns), 'uniq' => true, 'default' => []],
			'sortorder' =>				['type' => API_SORTORDER, 'default' => []],
			'limit' =>					['type' => API_INT32, 'flags' => API_ALLOW_NULL, 'in' => '1:'.ZBX_MAX_INT32, 'default' => null],
			// flags
			'editable' =>				['type' => API_BOOLEAN, 'default' => false]
		]];

		if (!CApiInputValidator::validate($api_input_rules, $options, '/', $error)) {
			self::exception(ZBX_API_ERROR_PARAMETERS, $error);
		}

		if (self::$userData['type'] != USER_TYPE_SUPER_ADMIN || $options['hostids'] !== null) {
			$items = API::Item()->get([
				'output' => ['itemid'],
				'itemids' => $options['itemids'],
				'hostids' => $options['hostids'],
				'editable' => $options['editable'],
				'webitems' => true,
				'preservekeys' => true
			]);
			$options['itemids'] = array_keys($items);
		}

		$this->tableName = CHistoryManager::getTableName($options['history']);

		switch (CHistoryManager::getDataSourceType($options['history'])) {
			case ZBX_HISTORY_SOURCE_ELASTIC:
				return $this->getFromElasticsearch($options);

			default:
				return $this->getFromSql($options);
		}
	}

	/**
	 * SQL specific implementation of get.
	 *
	 * @see CHistory::get
	 */
	private function getFromSql($options) {
		$result = [];
		$sql_parts = [
			'select'	=> ['history' => 'h.itemid'],
			'from'		=> [
				'history' => $this->tableName.' h'
			],
			'where'		=> [],
			'group'		=> [],
			'order'		=> []
		];

		// itemids
		if ($options['itemids'] !== null) {
			$sql_parts['where']['itemid'] = dbConditionInt('h.itemid', $options['itemids']);
		}

		// time_from
		if ($options['time_from'] !== null) {
			$sql_parts['where']['clock_from'] = 'h.clock>='.$options['time_from'];
		}

		// time_till
		if ($options['time_till'] !== null) {
			$sql_parts['where']['clock_till'] = 'h.clock<='.$options['time_till'];
		}

		// filter
		if ($options['filter'] !== null) {
			$this->dbFilter($sql_parts['from']['history'], $options, $sql_parts);
		}

		// search
		if ($options['search'] !== null) {
			zbx_db_search($sql_parts['from']['history'], $options, $sql_parts);
		}

		$sql_parts = $this->applyQueryOutputOptions($this->tableName(), $this->tableAlias(), $options, $sql_parts);
		$sql_parts = $this->applyQuerySortOptions($this->tableName, $this->tableAlias(), $options, $sql_parts);

		$db_res = DBselect(self::createSelectQueryFromParts($sql_parts), $options['limit']);

		while ($data = DBfetch($db_res)) {
			if ($options['countOutput']) {
				$result = $data['rowscount'];
			}
			else {
				$result[] = $data;
			}
		}

		return $result;
	}

	/**
	 * Elasticsearch specific implementation of get.
	 *
	 * @see CHistory::get
	 */
	private function getFromElasticsearch($options) {
		$query = [];
		$schema = DB::getSchema($this->tableName);

		// itemids
		if ($options['itemids'] !== null) {
			$query['query']['bool']['must'][] = [
				'terms' => [
					'itemid' => $options['itemids']
				]
			];
		}

		// time_from
		if ($options['time_from'] !== null) {
			$query['query']['bool']['must'][] = [
				'range' => [
					'clock' => [
						'gte' => $options['time_from']
					]
				]
			];
		}

		// time_till
		if ($options['time_till'] !== null) {
			$query['query']['bool']['must'][] = [
				'range' => [
					'clock' => [
						'lte' => $options['time_till']
					]
				]
			];
		}

		// filter
		if ($options['filter'] !== null) {
			$query = CElasticsearchHelper::addFilter(DB::getSchema($this->tableName), $query, $options);
		}

		// search
		if ($options['search'] !== null) {
			$query = CElasticsearchHelper::addSearch($schema, $query, $options);
		}

		// output
		if ($options['countOutput'] === false && $options['output'] !== API_OUTPUT_EXTEND) {
			$query['_source'] = $options['output'];
		}

		// sorting
		if ($options['sortfield']) {
			$query = CElasticsearchHelper::addSort($query, $options);
		}

		// limit
		if ($options['limit'] !== null) {
			$query['size'] = $options['limit'];
		}

		$endpoints = CHistoryManager::getElasticsearchEndpoints($options['history']);
		if ($endpoints) {
			return CElasticsearchHelper::query('POST', reset($endpoints), $query);
		}

		return null;
	}
}