File: C52TriggerExpressionConverter.php

package info (click to toggle)
zabbix 1%3A6.0.14%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 283,384 kB
  • sloc: sql: 868,673; ansic: 322,351; php: 235,311; javascript: 62,116; sh: 5,555; makefile: 2,257; java: 1,397; cpp: 662; xml: 49; perl: 41
file content (556 lines) | stat: -rw-r--r-- 16,989 bytes parent folder | download
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
<?php declare(strict_types = 0);
/*
** Zabbix
** Copyright (C) 2001-2023 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.
**/


/**
 * A converter to convert trigger expression syntax from 5.2 to 5.4.
 */
class C52TriggerExpressionConverter extends CConverter {

	/**
	 * Functions which are not related to item.
	 *
	 * @var array
	 */
	protected $standalone_functions;

	/**
	 * State of each host reference being present in some non-standalone function.
	 *
	 * @var array
	 */
	protected $hanged_refs = [];

	/**
	 * Host for simplified functions.
	 *
	 * @var string|null
	 */
	protected $host;

	/**
	 * Item for simplified functions.
	 *
	 * @var string|null
	 */
	protected $item;

	/**
	 * Old trigger expression syntax parser.
	 *
	 * @var C10TriggerExpression
	 */
	protected $parser;

	public function __construct() {
		$this->parser = new C10TriggerExpression(['allow_func_only' => true]);
		$this->standalone_functions = getStandaloneFunctions();
	}

	/**
	 * Converts trigger expression to new syntax.
	 *
	 * @param array  $trigger_data
	 * @param string $trigger_data['expression']
	 * @param string $trigger_data['host']                 (optional)
	 * @param string $trigger_data['item']                 (optional)
	 *
	 * @return string
	 */
	public function convert($trigger_data) {
		$this->item = (array_key_exists('item', $trigger_data) && $trigger_data['item']) ? $trigger_data['item'] : '';
		$this->host = (array_key_exists('host', $trigger_data) && $this->item) ? $trigger_data['host'] : '';

		if ($this->parser->parse($trigger_data['expression']) !== false) {
			$functions = $this->parser->result->getTokensByType(C10TriggerExprParserResult::TOKEN_TYPE_FUNCTION_MACRO);
			$this->hanged_refs = $this->checkHangedFunctionsPerHost($functions);

			$extra_expressions = [];

			for ($i = count($functions) - 1; $i >= 0; $i--) {
				[$new_expr, $extra_expr] = $this->convertFunction($functions[$i]['data'], $this->host, $this->item);

				$trigger_data['expression'] = substr_replace($trigger_data['expression'], $new_expr,
					$functions[$i]['pos'], $functions[$i]['length']
				);

				if ($extra_expr !== null) {
					$extra_expressions[] = $extra_expr;
				}
			}

			if ($extra_expressions) {
				$extra_expressions = array_keys(array_flip($extra_expressions));

				$trigger_data['expression'] = '('.$trigger_data['expression'].')';

				$extra_expressions = array_reverse($extra_expressions);
				$trigger_data['expression'] .= ' or '.implode(' or ', $extra_expressions);
			}
		}

		return $trigger_data['expression'];
	}

	/**
	 * Convert function to new syntax.
	 *
	 * @param array $fn          Function to convert.
	 * @param string $host_name  Host name.
	 * @param string $item_key   Item key.
	 *
	 * @return array
	 */
	protected function convertFunction(array $fn, string $host_name, string $item_key): array {
		if ($fn['item'] === '' && $fn['host'] === '') {
			$query = sprintf('/%s/%s', $host_name, $item_key);
			$has_hanged_functions = $this->hanged_refs[''];
		}
		else {
			$query = sprintf('/%s/%s', $fn['host'], $fn['item']);
			$has_hanged_functions = array_key_exists($fn['host'], $this->hanged_refs)
				? $this->hanged_refs[$fn['host']]
				: false;
		}

		$extra_expr = null;

		$parameters = [
			'unquotable' => array_filter($fn['functionParamsRaw']['parameters'], function ($param) {
				return ($param['type'] == C10FunctionParser::PARAM_UNQUOTED && $param['raw'] === '');
			}),
			'indicated' => array_filter($fn['functionParamsRaw']['parameters'], function ($param) {
				return ($param['type'] == C10FunctionParser::PARAM_QUOTED || $param['raw'] !== '');
			})
		];

		switch ($fn['functionName']) {
			case 'abschange':
				$new_expression = sprintf('abs(change(%1$s))', $query);
				break;

			case 'band':
				$params = self::convertParameters($fn['functionParams'], $parameters, $fn['functionName']);
				$timeshift = self::paramsToString([$params[0]]);
				$mask = self::paramsToString([$params[1]]);
				$new_expression = sprintf('bitand(last(%1$s%2$s)%3$s)', $query, $timeshift, $mask);
				break;

			case 'change':
				$new_expression = sprintf('change(%1$s)', $query);
				break;

			case 'delta':
				$params = self::convertParameters($fn['functionParams'], $parameters, $fn['functionName']);
				$params = self::paramsToString($params);
				$new_expression = sprintf('(max(%1$s%2$s)-min(%1$s%2$s))', $query, $params);
				break;

			case 'diff':
				$new_expression = sprintf('(last(%1$s,#1)<>last(%1$s,#2))', $query);
				break;

			case 'prev':
				$new_expression = sprintf('last(%1$s,#2)', $query);
				break;

			case 'trenddelta':
				$params = self::convertParameters($fn['functionParams'], $parameters, $fn['functionName']);
				$params = self::paramsToString($params);
				$new_expression = sprintf('(trendmax(%1$s%2$s)-trendmin(%1$s%2$s))', $query, $params);
				break;

			case 'iregexp':
			case 'regexp':
			case 'str':
				$params = self::convertParameters($fn['functionParams'], $parameters, $fn['functionName']);
				$params = self::paramsToString($params);
				$new_expression = sprintf('find(%1$s%2$s)', $query, $params);
				break;

			case 'strlen':
				$params = self::convertParameters($fn['functionParams'], $parameters, $fn['functionName']);
				$params = self::paramsToString($params);
				$new_expression = sprintf('length(last(%1$s%2$s))', $query, $params);
				break;

			case 'date':
			case 'dayofmonth':
			case 'dayofweek':
			case 'time':
			case 'now':
				$new_expression = $fn['functionName'].'()';
				if (!$has_hanged_functions) {
					$extra_expr = sprintf('(last(%1$s)<>last(%1$s))', $query);
				}
				break;

			case 'logseverity':
				$new_expression = sprintf('logseverity(%1$s)', $query);
				break;

			default:
				$new_expression = sprintf('%s(%s%s)', $fn['functionName'], $query,
					self::paramsToString(self::convertParameters($fn['functionParams'], $parameters,
						$fn['functionName']
					))
				);
				break;
		}

		return [$new_expression, $extra_expr];
	}

	/**
	 * Convert function parameters to new syntax.
	 *
	 * @param array $parameters                List of parameters according to the previous syntax.
	 * @param array $param_dets
	 * @param array $param_dets['unquotable']  List of numeric indexes for parameters that don't need to be quoted.
	 * @param array $param_dets['indicated']   List of numeric indexes for parameters that are especially indicated and
	 *                                         must be kept.
	 * @param string $fn_name                  Function name.
	 *
	 * @return array
	 */
	private static function convertParameters(array $parameters, array $param_dets, string $fn_name): array {
		switch ($fn_name) {
			// (sec|#num,<time_shift>)
			case 'delta':
			case 'avg':
			case 'max':
			case 'min':
			case 'sum':
			// (sec|#num,<time_shift>,percentage)
			case 'percentile':
				$parameters += ['', ''];
				$parameters[0] = self::convertParamSec($parameters[0]);
				$parameters[1] = self::convertTimeshift($parameters[1]);
				$parameters[0] = ((string) $parameters[0] === '0') ? '#1' : $parameters[0];
				if ($parameters[1] !== '') {
					$parameters[0] .= ':'.$parameters[1];
				}
				unset($parameters[1], $param_dets['unquotable'][1], $param_dets['indicated'][1]);
				break;

			// (sec|#num,<time_shift>,threshold,<fit>)
			case 'timeleft':
				$parameters += ['', '', '', ''];
				$parameters[0] = self::convertParamSec($parameters[0]);
				$parameters[1] = self::convertTimeshift($parameters[1]);
				$parameters[0] = ((string) $parameters[0] === '0') ? '#1' : $parameters[0];
				if ($parameters[1] !== '') {
					$parameters[0] .= ':'.$parameters[1];
				}
				unset($parameters[1], $param_dets['unquotable'][1], $param_dets['indicated'][1]);

				if ($parameters[3] === '') {
					// Don't quote unspecified <fit>.
					$param_dets['unquotable'][3] = true;
				}
				break;

			// (<#num>,<time_shift>)
			case 'strlen':
			case 'last':
				$parameters += ['', ''];
				if (!self::isMacro($parameters[0])
						&& (substr($parameters[0], 0, 1) !== '#'
							|| !ctype_digit(substr($parameters[0], 1))
							|| (int) substr($parameters[0], 1) === 0)) {
					$parameters[0] = '';
				}

				$parameters[1] = self::convertTimeshift($parameters[1]);
				if ($parameters[1] !== '') {
					$parameters[0] = ($parameters[0] === '') ? '#1' : $parameters[0];
					$parameters[0] .= ':'.$parameters[1];
				}
				unset($parameters[1], $param_dets['unquotable'][1], $param_dets['indicated'][1]);
				break;

			// (sec|#num,<time_shift>,time,<fit>,<mode>)
			case 'forecast':
				$parameters += ['', '', '', '', ''];
				$parameters[0] = self::convertParamSec($parameters[0]);
				$parameters[1] = self::convertTimeshift($parameters[1]);
				$parameters[0] = ((string) $parameters[0] === '0') ? '#1' : $parameters[0];
				if ($parameters[1] !== '') {
					$parameters[0] .= ':'.$parameters[1];
				}
				unset($parameters[1], $param_dets['unquotable'][1], $param_dets['indicated'][1]);
				$parameters[2] = self::convertParamSec($parameters[2]);

				if ($parameters[3] === '') {
					// Don't quote unspecified <fit>.
					$param_dets['unquotable'][3] = true;
				}
				if ($parameters[4] === '') {
					// Don't quote unspecified <mode>.
					$param_dets['unquotable'][4] = true;
				}
				break;

			// (<sec|#num>,mask,<time_shift>)
			case 'band':
				$parameters += ['', '', ''];
				if (!self::isMacro($parameters[0])
						&& (substr($parameters[0], 0, 1) !== '#'
							|| !ctype_digit(substr($parameters[0], 1))
							|| (int) substr($parameters[0], 1) === 0)) {
					$parameters[0] = '';
				}

				$parameters[2] = self::convertTimeshift($parameters[2]);
				if ($parameters[2] !== '') {
					$parameters[0] = ($parameters[0] === '') ? '#1' : $parameters[0];
					$parameters[0] .= ':'.$parameters[2];
				}
				unset($parameters[2], $param_dets['unquotable'][2], $param_dets['indicated'][2]);
				break;

			// (sec|#num,<pattern>,<operator>,<time_shift>)
			case 'count':
				$parameters += ['', '', '', ''];
				$parameters[0] = self::convertParamSec($parameters[0]);
				$parameters[3] = self::convertTimeshift($parameters[3]);
				$parameters[0] = ((string) $parameters[0] === '0') ? '#1' : $parameters[0];
				if ($parameters[3] !== '') {
					$parameters[0] .= ':'.$parameters[3];
				}
				if ($parameters[2] === 'band') {
					$parameters[2] = 'bitand';
				}
				elseif ($parameters[2] === '') {
					// Don't quote unspecified <operator>.
					$param_dets['unquotable'][2] = true;
				}

				$parameters[3] = $parameters[1];
				unset($param_dets['unquotable'][3], $param_dets['indicated'][3], $parameters[1]);
				if (array_key_exists(1, $param_dets['unquotable'])) {
					$param_dets['unquotable'][3] = true;
					unset($param_dets['unquotable'][1]);
				}
				if (array_key_exists(1, $param_dets['indicated'])) {
					$param_dets['indicated'][3] = true;
					unset($param_dets['indicated'][1]);
				}
				break;

			// (sec,<mode>)
			case 'nodata':
				$parameters += ['', ''];
				$parameters[0] = self::convertParamSec($parameters[0]);
				if ($parameters[1] === '') {
					// Don't quote unspecified <mode>.
					$param_dets['unquotable'][1] = true;
				}
				break;

			// (sec)
			case 'fuzzytime':
				$parameters += [''];
				$parameters[0] = self::convertParamSec($parameters[0]);
				break;

			// (<pattern>,<sec|#num>)
			case 'iregexp':
			case 'regexp':
			case 'str':
				$parameters += ['', ''];
				$parameters = [
					self::convertParamSec($parameters[1]),
					($fn_name === 'str') ? 'like' : $fn_name,
					$parameters[0]
				];
				unset($param_dets['unquotable'][1]);
				if (array_key_exists(0, $param_dets['indicated'])) {
					$param_dets['indicated'][2] = true;
					unset($param_dets['indicated'][0]);
				}

				break;

			// (period,period_shift)
			case 'trendavg':
			case 'trendcount':
			case 'trenddelta':
			case 'trendmax':
			case 'trendmin':
			case 'trendsum':
				$parameters += ['', ''];
				$parameters[0] = self::convertParamPeriod($parameters[0]);
				if ($parameters[1] !== '') {
					$parameters[0] .= ':'.$parameters[1];
				}
				unset($parameters[1], $param_dets['unquotable'][1], $param_dets['indicated'][1]);
				break;

			case 'logeventid':
			case 'logsource':
				array_unshift($parameters, '');
				if (array_key_exists(0, $param_dets['indicated'])) {
					$param_dets['indicated'][1] = true;
					unset($param_dets['indicated'][0]);
				}
				break;
		}

		// Keys in $parameters array to skip from quoting.
		$param_dets['unquotable'] = array_keys($param_dets['unquotable']);
		$param_dets['indicated'] = array_keys($param_dets['indicated']);
		$functions_with_period_parameter = ['delta', 'avg', 'max', 'min', 'sum', 'last', 'strlen', 'percentile',
			'timeleft', 'forecast', 'band', 'count', 'fuzzytime', 'nodata', 'iregexp', 'regexp', 'str', 'trendavg',
			'trendcount', 'trenddelta', 'trendmax', 'trendmin', 'trendsum', 'logeventid', 'logsource'
		];
		if (in_array($fn_name, $functions_with_period_parameter)) {
			$param_dets['unquotable'][] = 0;
		}

		if (in_array($fn_name, ['forecast', 'timeleft', 'percentile'])) {
			// Time parameter don't need to be quoted for forecast() function.
			$param_dets['unquotable'][] = 2;
		}
		elseif ($fn_name === 'band') {
			// Mask parameter don't need to be quoted for bitand() function.
			$param_dets['unquotable'][] = 1;
		}

		array_walk($parameters, function (&$param, $i) use ($param_dets) {
			if (in_array($i, $param_dets['unquotable'])) {
				return;
			}

			$param = CHistFunctionParser::quoteParam($param);
		});

		// Remove empty parameters from the end of the parameters array.
		foreach (array_reverse(array_keys($parameters)) as $i) {
			if (in_array($i, $param_dets['indicated'])) {
				break;
			}

			if ($parameters[$i] !== '""' && $parameters[$i] !== '') {
				break;
			}

			unset($parameters[$i]);
		}

		return array_values($parameters);
	}

	/**
	 * Convert seconds.
	 *
	 * @param string $param  Parameter to convert.
	 *
	 * @return string
	 */
	private static function convertParamSec(string $param): string {
		return (preg_match('/^(?<num>\d+)(?<suffix>['.ZBX_TIME_SUFFIXES.']{0,1})$/', $param, $m) && $m['num'] > 0)
			? $m['num'].($m['suffix'] !== '' ? $m['suffix'] : 's')
			: $param;
	}

	/**
	 * Convert period.
	 *
	 * @param string $param  Parameter to convert.
	 *
	 * @return string
	 */
	private static function convertParamPeriod(string $param): string {
		return (preg_match('/^(?<num>\d+)(?<suffix>[hdwMy]{0,1})$/', $param, $m) && $m['num'] > 0)
			? $m['num'].($m['suffix'] !== '' ? $m['suffix'] : 's')
			: $param;
	}

	/**
	 * Convert time shift.
	 *
	 * @param string $param  Parameter to convert.
	 *
	 * @return string
	 */
	private static function convertTimeshift(string $param): string {
		$param = (preg_match('/^(?<num>\d+)(?<suffix>['.ZBX_TIME_SUFFIXES.']{0,1})$/', $param, $m) && $m['num'] > 0)
			? $m['num'].($m['suffix'] !== '' ? $m['suffix'] : 's')
			: $param;

		return ($param !== '') ? 'now-'.$param : '';
	}

	/**
	 * Concatenate parameters into comma separated string.
	 *
	 * @param array $parameters  Parameter to concatenate.
	 *
	 * @return string
	 */
	private static function paramsToString(array $parameters): string {
		$parameters = rtrim(implode(',', $parameters), ',');

		return ($parameters === '') ? '' : ','.$parameters;
	}

	/**
	 * Check if each particular host reference would be linked through at least one functions according to the new
	 * trigger expression syntax.
	 *
	 * @param array $tokens
	 *
	 * @return array
	 */
	protected function checkHangedFunctionsPerHost(array $tokens): array {
		$hanged_refs = [];

		foreach ($tokens as $token) {
			$fn = $token['data'];

			if (!array_key_exists($fn['host'], $hanged_refs)) {
				$hanged_refs[$fn['host']] = false;
			}
			if (!in_array($fn['functionName'], $this->standalone_functions)) {
				$hanged_refs[$fn['host']] = true;
			}
		}

		return $hanged_refs;
	}

	/**
	 * Check if given string is valid user or lld macro.
	 *
	 * @param string $param
	 *
	 * @return bool
	 */
	private static function isMacro(string $param): bool {
		foreach ([new CUserMacroParser(), new CLLDMacroParser(), new CLLDMacroFunctionParser()] as $parser) {
			if ($parser->parse($param) == CParser::PARSE_SUCCESS) {
				return true;
			}
		}

		return false;
	}
}