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

CDataHelper.php « helpers « include « tests « ui - github.com/zabbix/zabbix.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0202c8cf031cf980413c49e40231473b19808d76 (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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
<?php

/*
** Zabbix
** Copyright (C) 2001-2022 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.
**/

require_once 'vendor/autoload.php';

require_once dirname(__FILE__).'/../../../include/defines.inc.php';
require_once dirname(__FILE__).'/../../../include/hosts.inc.php';
require_once dirname(__FILE__).'/../../../include/db.inc.php';

class CDataHelper extends CAPIHelper {

	protected static $data = null;
	protected static $request = [];
	protected static $response = [];

	/**
	 * Prepare request for API call and make API call (@see callRaw).
	 *
	 * @param string $method    API method to be called.
	 * @param mixed $params     API call params.
	 *
	 * @return array
	 *
	 * @throws Exception on API error
	 */
	public static function call($method, $params) {
		global $URL;
		if (!$URL) {
			$URL = PHPUNIT_URL.'api_jsonrpc.php';
		}

		static::$request = [];
		static::$response = [];

		if (CAPIHelper::getSessionId() === null) {
			CAPIHelper::createSessionId();
		}

		$response = CAPIHelper::call($method, $params);

		if (array_key_exists('error', $response)) {
			throw new Exception('API call failed: '.json_encode($response['error'], JSON_PRETTY_PRINT));
		}

		if (!array_key_exists('result', $response)) {
			throw new Exception('API call failed: result is not present');
		}

		static::$request = (CTestArrayHelper::isAssociative($params)) ? [$params] : $params;
		static::$response = $response['result'];

		return static::$response;
	}

	/**
	 * Prepare request for API call and make API call (@see callRaw).
	 *
	 * @param string $method    API method to be called.
	 * @param mixed $params     API call params.
	 *
	 * @return array
	 *
	 * @throws Exception on API error
	 */
	public static function getIds($field) {
		$ids = [];
		$result = reset(static::$response);
		if (count(static::$request) !== count($result)) {
			throw new Exception('Failed to get ids: record counts don\'t match');
		}

		foreach (static::$request as $i => $object) {
			if (!array_key_exists($field, $object)) {
				throw new Exception('Failed to get ids: field "'.$field.'" is not present in request.');
			}

			if (!array_key_exists($i, $result)) {
				throw new Exception('Failed to get ids: element ('.$i.') is not present in result.');
			}

			if (array_key_exists($object[$field], $ids)) {
				throw new Exception('Failed to get ids: field "'.$field.'" is not unique.');
			}

			$ids[$object[$field]] = $result[$i];
		}

		return $ids;
	}

	/**
	 * Create host with items and discovery rules.
	 *
	 * @param mixed $params    API call params.
	 *                         In addition to the default host.create params, "items" and "discoveryrules" can be set
	 *			               for any of the host in order to create host items and discovery rules.
	 *
	 * @return array
	 */
	public static function createHosts($params) {
		return static::createHostTemplate($params, 'host');
	}

	/**
	 * Create template with items and discovery rules.
	 *
	 * @param mixed $params    API call params
	 *
	 * @return array
	 */
	public static function createTemplates($params) {
		return static::createHostTemplate($params, 'template');
	}

	/**
	 * Execute creation of host or template.
	 *
	 * @param mixed $params    API call params
	 * @param string $object   host or template object
	 *
	 * @return array
	 */
	public static function createHostTemplate($params, $object) {
		$items = [];
		$discoveryrules = [];
		foreach ($params as &$param) {
			if (array_key_exists('items', $param)) {
				$items[$param['host']] = $param['items'];
				unset($param['items']);
			}
			if (array_key_exists('discoveryrules', $param)) {
				$discoveryrules[$param['host']] = $param['discoveryrules'];
				unset($param['discoveryrules']);
			}
		}
		unset($param);

		static::call($object.'.create', $params);
		$objectids = static::getIds('host');

		$result = [
			$object.'ids' => $objectids
		];

		if ($items) {
			$result['itemids'] = static::createItems('item', $items, $objectids, $object);
		}

		if ($discoveryrules) {
			$result['discoveryruleids'] = static::createItems('discoveryrule', $discoveryrules, $objectids, $object);
		}

		return $result;
	}

	/**
	 * Get host interfaces.
	 *
	 * @param array $hostids	host ids
	 *
	 * @return array
	 */
	public static function getInterfaces($hostids) {
		$hosts = static::call('host.get', [
			'output' => ['host'],
			'hostids' => array_values($hostids),
			'selectInterfaces' => ['interfaceid', 'useip', 'ip', 'type', 'dns', 'port', 'main']
		]);

		$result['default_interfaces'] = [];
		$result['ids'] = [];
		foreach ($hosts as $host) {
			foreach ($host['interfaces'] as $interface) {
				if ($interface['main'] == INTERFACE_PRIMARY) {
					$result['default_interfaces'][$host['host']][$interface['type']] = $interface['interfaceid'];
				}

				$address = ($interface['useip'] == 1) ? $interface['ip'] : $interface['dns'];
				$result['ids'][$host['host']][$address.':'.$interface['port']] = $interface['interfaceid'];
			}
		}

		return $result;
	}

	/**
	 * Create items or discovery rule for host and template.
	 *
	 * @param string $type			item or discoveryrule type
	 * @param mixed $items			API call items or discovery params
	 * @param array $objectids		host or template ids
	 * @param string $object		host or template
	 *
	 * @return array
	 *
	 * @throws Exception on API error
	 */
	public static function createItems($type, $items, $objectids, $object = 'host') {
		$request = [];
		foreach ($items as $host => $host_items) {
			foreach ($host_items as $item) {
				$item['hostid'] = $objectids[$host];

				if ($object === 'host') {

					$interfaces = static::getInterfaces($objectids);

					if (array_key_exists($host, $interfaces['default_interfaces'])) {
						$interface_type = null;
						switch (CTestArrayHelper::get($item, 'type')) {
							case ITEM_TYPE_ZABBIX:
							case ITEM_TYPE_ZABBIX_ACTIVE:
								$interface_type = 1;
								break;

							case ITEM_TYPE_SNMP:
							case ITEM_TYPE_SNMPTRAP:
								$interface_type = 2;
								break;

							case ITEM_TYPE_IPMI:
								$interface_type = 3;
								break;

							case ITEM_TYPE_JMX:
								$interface_type = 4;
								break;
						}

						if ($interface_type !== null && array_key_exists($interface_type, $interfaces['default_interfaces'][$host])) {
							$item['interfaceid'] = $interfaces['default_interfaces'][$host][$interface_type];
						}
					}

					if (array_key_exists($host, $interfaces['ids'])) {
						$interface = CTestArrayHelper::get($item, 'interface');
						unset($item['interface']);
						if ($interface !== null && array_key_exists($$interfaces['ids'][$host], $interface)) {
							$item['interfaceid'] = $interfaces['ids'][$host][$interface];
						}
					}
				}

				$request[] = $item;
			}
		}

		// Create items or discovery rules.
		$response = static::call($type.'.create', $request);
		$i = 0;

		$result = [];
		foreach ($items as $host => $host_items) {
			foreach ($host_items as $item) {
				if (!array_key_exists($i, $response['itemids'])) {
					throw new Exception('Failed to get ids: element ('.$i.') is not present in result.');
				}

				$result[$host.':'.$item['key_']] = $response['itemids'][$i++];
			}
		}

		return $result;
	}

	/**
	 * Load the data source data from the file cache.
	 */
	protected static function preload() {
		if (static::$data === null) {
			static::$data = [];

			if (!defined('PHPUNIT_DATA_DIR')) {
				return;
			}

			foreach (new DirectoryIterator(PHPUNIT_DATA_DIR) as $file) {
				if ($file->isDot() || $file->isDir() || strtolower($file->getExtension()) !== 'json') {
					continue;
				}

				$name = $file->getBasename('.'.$file->getExtension());
				static::$data[$name] = json_decode(file_get_contents($file->getPathname()), true);
			}
		}
	}

	/**
	 * Get data from the data sources.
	 *
	 * @param mixed $path       data path to look for
	 * @param mixed $default    default value to be returned if data doesn't exist
	 *
	 * @return mixed
	 */
	public static function get($path, $default = null) {
		return CTestArrayHelper::get(static::$data, $path, $default);
	}

	/**
	 * Load specific data source data.
	 *
	 * @param mixed $source    name of the data source(s)
	 *
	 * @return boolean
	 *
	 * @throws \Exception
	 */
	public static function load($source) {
		if (is_array($source)) {
			$result = true;
			foreach ($source as $name) {
				if (!static::load($name)) {
					$result = false;
				}
			}

			return $result;
		}

		static::preload();

		if (array_key_exists($source, static::$data)) {
			return true;
		}

		try {
			$path = PHPUNIT_DATA_SOURCES_DIR.$source.'.php';
			if (!file_exists($path)) {
				throw new \Exception('File "'.$path.'" doesn\'t exist.');
			}

			require_once $path;
			static::$data[$source] = forward_static_call([$source, 'load']);

			if (defined('PHPUNIT_DATA_DIR')) {
				$data = json_encode(static::get($source));
				file_put_contents(PHPUNIT_DATA_DIR.$source.'.json', $data);
			}
		}
		catch (\Exception $e) {
			echo 'Failed to load data from data source "'.$source.'".'."\n\n".$e->getMessage()."\n".$e->getTraceAsString();

			return false;
		}

		return true;
	}

	/**
	 *  Add data to item.
	 *
	 * @param string $itemid		item id
	 * @param array $values			value that should be sent to item
	 * @param mixed $time			time when value was received
	 */
	public static function addItemData($itemid, $values, $time = null) {
		if (!is_array($values)) {
			$values = [$values];
		}

		if ($time === null) {
			$time = time();
		}
		elseif (is_array($time)) {
			if (count($time) !== count($values)) {
				throw new Exception('Value count should match the time record count.');
			}

			$time = array_values($time);
		}

		// Check item value type to set correct history table where to insert data.
		$value_type = CDBHelper::getValue('SELECT value_type FROM items where itemid='.zbx_dbstr($itemid));
		$suffixes = ['', '_str', '_log', '_uint', '_text'];

		if (!array_key_exists($value_type, $suffixes)) {
			throw new Exception('Unsupported item value type: '.$value_type);
		}

		$history_table = 'history'.$suffixes[$value_type];

		foreach (array_values($values) as $key => $value) {
			$clock = is_array($time) ? $time[$key] : $time;
			DBexecute('INSERT INTO '.$history_table.' (itemid, clock, value) VALUES ('.zbx_dbstr($itemid).', '
					.zbx_dbstr($clock).', '.zbx_dbstr($value).')');
		}
	}
}