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 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
|
<?php
/*
** Zabbix
** Copyright (C) 2001-2019 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 services.
*/
class CService extends CApiService {
protected $tableName = 'services';
protected $tableAlias = 's';
protected $sortColumns = ['sortorder', 'name'];
public function __construct() {
parent::__construct();
$this->getOptions = array_merge($this->getOptions, [
'parentids' => null,
'childids' => null,
'countOutput' => false,
'selectParent' => null,
'selectDependencies' => null,
'selectParentDependencies' => null,
'selectTimes' => null,
'selectAlarms' => null,
'selectTrigger' => null,
'sortfield' => '',
'sortorder' => ''
]);
}
/**
* Get services.
*
* Allowed options:
* - parentids - fetch the services that are hardlinked to the given parent services;
* - childids - fetch the services that are hardlinked to the given child services;
* - countOutput - return the number of the results as an integer;
* - selectParent - include the parent service in the result;
* - selectDependencies - include service child dependencies in the result;
* - selectParentDependencies - include service parent dependencies in the result;
* - selectTimes - include service times in the result;
* - selectAlarms - include alarms generated by the service;
* - selectTrigger - include the linked trigger;
* - sortfield - name of columns to sort by;
* - sortorder - sort order.
*
* @param array $options
*
* @return array
*/
public function get(array $options) {
$options = zbx_array_merge($this->getOptions, $options);
// build and execute query
$sql = $this->createSelectQuery($this->tableName(), $options);
$res = DBselect($sql, $options['limit']);
// fetch results
$result = [];
while ($row = DBfetch($res)) {
// a count query, return a single result
if ($options['countOutput']) {
$result = $row['rowscount'];
}
// a normal select query
else {
$result[$row[$this->pk()]] = $row;
}
}
if ($options['countOutput']) {
return $result;
}
if ($result) {
$result = $this->addRelatedObjects($options, $result);
$result = $this->unsetExtraFields($result, ['triggerid'], $options['output']);
}
if (!$options['preservekeys']) {
$result = zbx_cleanHashes($result);
}
return $result;
}
/**
* Validates the input parameters for the create() method.
*
* @throws APIException if the input is invalid
*
* @param array $services
*/
protected function validateCreate(array $services) {
foreach ($services as $service) {
$this->checkName($service);
$this->checkAlgorithm($service);
$this->checkShowSla($service);
$this->checkGoodSla($service);
$this->checkSortOrder($service);
$this->checkTriggerId($service);
$this->checkStatus($service);
$this->checkParentId($service);
$error = _s('Wrong fields for service "%1$s".', $service['name']);
$this->checkUnsupportedFields($this->tableName(), $service, $error, [
'parentid', 'dependencies', 'times'
]);
}
$this->checkTriggerPermissions($services);
}
/**
* Creates the given services.
*
* @param array $services
*
* @return array
*/
public function create(array $services) {
$services = zbx_toArray($services);
$this->validateCreate($services);
// save the services
$serviceIds = DB::insert($this->tableName(), $services);
$dependencies = [];
$serviceTimes = [];
foreach ($services as $key => $service) {
$serviceId = $serviceIds[$key];
// save dependencies
if (!empty($service['dependencies'])) {
foreach ($service['dependencies'] as $dependency) {
$dependency['serviceid'] = $serviceId;
$dependencies[] = $dependency;
}
}
// save parent service
if (!empty($service['parentid'])) {
$dependencies[] = [
'serviceid' => $service['parentid'],
'dependsOnServiceid' => $serviceId,
'soft' => 0
];
}
// save service times
if (isset($service['times'])) {
foreach ($service['times'] as $serviceTime) {
$serviceTime['serviceid'] = $serviceId;
$serviceTimes[] = $serviceTime;
}
}
}
if ($dependencies) {
$this->addDependencies($dependencies);
}
if ($serviceTimes) {
$this->addTimes($serviceTimes);
}
updateItServices();
return ['serviceids' => $serviceIds];
}
/**
* Validates the input parameters for the update() method.
*
* @throws APIException if the input is invalid
*
* @param array $services
*/
public function validateUpdate(array $services) {
foreach ($services as $service) {
if (empty($service['serviceid'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Invalid method parameters.'));
}
}
$this->checkServicePermissions(zbx_objectValues($services, 'serviceid'));
$services = $this->extendObjects($this->tableName(), $services, ['name']);
foreach ($services as $service) {
$this->checkName($service);
if (isset($service['algorithm'])) {
$this->checkAlgorithm($service);
}
if (isset($service['showsla'])) {
$this->checkShowSla($service);
}
if (isset($service['goodsla'])) {
$this->checkGoodSla($service);
}
if (isset($service['sortorder'])) {
$this->checkSortOrder($service);
}
if (isset($service['triggerid'])) {
$this->checkTriggerId($service);
}
if (isset($service['status'])) {
$this->checkStatus($service);
}
if (isset($service['parentid'])) {
$this->checkParentId($service);
}
$error = _s('Wrong fields for service "%1$s".', $service['name']);
$this->checkUnsupportedFields($this->tableName(), $service, $error, [
'parentid', 'dependencies', 'times'
]);
}
$this->checkTriggerPermissions($services);
}
/**
* Updates the given services.
*
* @param array $services
*
* @return array
*/
public function update(array $services) {
$services = zbx_toArray($services);
$this->validateUpdate($services);
// save the services
foreach ($services as $service) {
DB::updateByPk($this->tableName(), $service['serviceid'], $service);
}
// update dependencies
$dependencies = [];
$parentDependencies = [];
$serviceTimes = [];
$deleteParentsForServiceIds = [];
$deleteDependenciesForServiceIds = [];
$deleteTimesForServiceIds = [];
foreach ($services as $service) {
if (isset($service['dependencies'])) {
$deleteDependenciesForServiceIds[] = $service['serviceid'];
if ($service['dependencies']) {
foreach ($service['dependencies'] as $dependency) {
$dependency['serviceid'] = $service['serviceid'];
$dependencies[] = $dependency;
}
}
}
// update parent
if (isset($service['parentid'])) {
$deleteParentsForServiceIds[] = $service['serviceid'];
if ($service['parentid']) {
$parentDependencies[] = [
'serviceid' => $service['parentid'],
'dependsOnServiceid' => $service['serviceid'],
'soft' => 0
];
}
}
// save service times
if (isset($service['times'])) {
$deleteTimesForServiceIds[] = $service['serviceid'];
foreach ($service['times'] as $serviceTime) {
$serviceTime['serviceid'] = $service['serviceid'];
$serviceTimes[] = $serviceTime;
}
}
}
// replace dependencies
if ($deleteParentsForServiceIds) {
$this->deleteParentDependencies(zbx_objectValues($services, 'serviceid'));
}
if ($deleteDependenciesForServiceIds) {
$this->deleteDependencies(array_unique($deleteDependenciesForServiceIds));
}
if ($parentDependencies || $dependencies) {
$this->addDependencies(array_merge($parentDependencies, $dependencies));
}
// replace service times
if ($deleteTimesForServiceIds) {
$this->deleteTimes($deleteTimesForServiceIds);
}
if ($serviceTimes) {
$this->addTimes($serviceTimes);
}
updateItServices();
return ['serviceids' => zbx_objectValues($services, 'serviceid')];
}
/**
* Validates the input parameters for the delete() method.
*
* @throws APIException if the input is invalid
*
* @param array $serviceIds
*/
public function validateDelete($serviceIds) {
if (!$serviceIds) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.'));
}
$this->checkServicePermissions($serviceIds);
$this->checkThatServicesDontHaveChildren($serviceIds);
}
/**
* Delete services.
*
* @param array $serviceIds
*
* @return array
*/
public function delete(array $serviceIds) {
$this->validateDelete($serviceIds);
DB::delete($this->tableName(), ['serviceid' => $serviceIds]);
updateItServices();
return ['serviceids' => $serviceIds];
}
/**
* Validates the input parameters for the addDependencies() method.
*
* @throws APIException if the input is invalid
*
* @param array $dependencies
*/
protected function validateAddDependencies(array $dependencies) {
if (!$dependencies) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.'));
}
foreach ($dependencies as $dependency) {
if (empty($dependency['serviceid']) || empty($dependency['dependsOnServiceid'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Invalid method parameters.'));
}
}
$serviceIds = array_merge(
zbx_objectValues($dependencies, 'serviceid'),
zbx_objectValues($dependencies, 'dependsOnServiceid')
);
$serviceIds = array_unique($serviceIds);
$this->checkServicePermissions($serviceIds);
foreach ($dependencies as $dependency) {
$this->checkDependency($dependency);
$this->checkUnsupportedFields('services_links', $dependency,
_s('Wrong fields for dependency for service "%1$s".', $dependency['serviceid']),
['dependsOnServiceid', 'serviceid']
);
}
$this->checkForHardlinkedDependencies($dependencies);
$this->checkThatParentsDontHaveTriggers($dependencies);
$this->checkForCircularityInDependencies($dependencies);
}
/**
* Add the given service dependencies.
*
* @param array $dependencies an array of service dependencies, each pair in the form of
* array('serviceid' => 1, 'dependsOnServiceid' => 2, 'soft' => 0)
*
* @return array
*/
public function addDependencies(array $dependencies) {
$dependencies = zbx_toArray($dependencies);
$this->validateAddDependencies($dependencies);
$data = [];
foreach ($dependencies as $dependency) {
$data[] = [
'serviceupid' => $dependency['serviceid'],
'servicedownid' => $dependency['dependsOnServiceid'],
'soft' => $dependency['soft']
];
}
DB::insert('services_links', $data);
return ['serviceids' => zbx_objectValues($dependencies, 'serviceid')];
}
/**
* Validates the input for the deleteDependencies() method.
*
* @throws APIException if the given input is invalid
*
* @param array $serviceIds
*/
protected function validateDeleteDependencies(array $serviceIds) {
if (!$serviceIds) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.'));
}
$this->checkServicePermissions($serviceIds);
}
/**
* Deletes all dependencies for the given services.
*
* @param array $serviceIds
*
* @return boolean
*/
public function deleteDependencies($serviceIds) {
$serviceIds = zbx_toArray($serviceIds);
$this->validateDeleteDependencies($serviceIds);
DB::delete('services_links', [
'serviceupid' => $serviceIds
]);
return ['serviceids' => $serviceIds];
}
/**
* Validates the input for the addTimes() method.
*
* @throws APIException if the given input is invalid
*
* @param array $serviceTimes
*/
public function validateAddTimes(array $serviceTimes) {
foreach ($serviceTimes as $serviceTime) {
$this->checkTime($serviceTime);
$this->checkUnsupportedFields('services_times', $serviceTime,
_s('Wrong fields for time for service "%1$s".', $serviceTime['serviceid'])
);
}
$this->checkServicePermissions(array_unique(zbx_objectValues($serviceTimes, 'serviceid')));
}
/**
* Adds the given service times.
*
* @param array $serviceTimes an array of service times
*
* @return array
*/
public function addTimes(array $serviceTimes) {
$serviceTimes = zbx_toArray($serviceTimes);
$this->validateAddTimes($serviceTimes);
DB::insert('services_times', $serviceTimes);
return ['serviceids' => zbx_objectValues($serviceTimes, 'serviceid')];
}
/**
* Validates the input for the deleteTimes() method.
*
* @throws APIException if the given input is invalid
*
* @param array $serviceIds
*/
protected function validateDeleteTimes(array $serviceIds) {
if (!$serviceIds) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.'));
}
$this->checkServicePermissions($serviceIds);
}
/**
* Returns availability-related information about the given services during the given time intervals.
*
* Available options:
* - serviceids - a single service ID or an array of service IDs;
* - intervals - a single time interval or an array of time intervals, each containing:
* - from - the beginning of the interval, timestamp;
* - to - the end of the interval, timestamp.
*
* Returns the following availability information for each service:
* - status - the current status of the service;
* - problems - an array of triggers that are currently in problem state and belong to the given service
* or it's descendants;
* - sla - an array of requested intervals with SLA information:
* - from - the beginning of the interval;
* - to - the end of the interval;
* - okTime - the time the service was in OK state, in seconds;
* - problemTime - the time the service was in problem state, in seconds;
* - downtimeTime - the time the service was down, in seconds.
*
* If the service calculation algorithm is set to SERVICE_ALGORITHM_NONE, the method will return an empty 'problems'
* array and null for all of the calculated values.
*
* @param array $options
*
* @return array as array(serviceId2 => data1, serviceId2 => data2, ...)
*/
public function getSla(array $options) {
$serviceIds = (isset($options['serviceids'])) ? zbx_toArray($options['serviceids']) : null;
$intervals = (isset($options['intervals'])) ? zbx_toArray($options['intervals']) : [];
// fetch services
$services = $this->get([
'output' => ['serviceid', 'name', 'status', 'algorithm'],
'selectTimes' => API_OUTPUT_EXTEND,
'selectParentDependencies' => ['serviceupid'],
'serviceids' => $serviceIds,
'preservekeys' => true
]);
$rs = [];
if ($services) {
$usedSeviceIds = [];
$problemServiceIds = [];
foreach ($services as &$service) {
$service['alarms'] = [];
// don't calculate SLA for services with disabled status calculation
if ($this->isStatusEnabled($service)) {
$usedSeviceIds[$service['serviceid']] = $service['serviceid'];
if ($service['status'] > 0) {
$problemServiceIds[] = $service['serviceid'];
}
}
}
unset($service);
// initial data
foreach ($services as $service) {
$rs[$service['serviceid']] = [
'status' => ($this->isStatusEnabled($service)) ? $service['status'] : null,
'problems' => [],
'sla' => []
];
}
if ($usedSeviceIds) {
// add service alarms
if ($intervals) {
$intervalConditions = [];
foreach ($intervals as $interval) {
$intervalConditions[] = 'sa.clock BETWEEN '.zbx_dbstr($interval['from']).' AND '.zbx_dbstr($interval['to']);
}
$query = DBselect(
'SELECT *'.
' FROM service_alarms sa'.
' WHERE '.dbConditionInt('sa.serviceid', $usedSeviceIds).
' AND ('.implode(' OR ', $intervalConditions).')'.
' ORDER BY sa.servicealarmid'
);
while ($data = DBfetch($query)) {
$services[$data['serviceid']]['alarms'][] = $data;
}
}
// add problem triggers
if ($problemServiceIds) {
$problemTriggers = $this->fetchProblemTriggers($problemServiceIds);
$rs = $this->escalateProblems($services, $problemTriggers, $rs);
}
$slaCalculator = new CServicesSlaCalculator();
// calculate SLAs
foreach ($intervals as $interval) {
$latestValues = $this->fetchLatestValues($usedSeviceIds, $interval['from']);
foreach ($services as $service) {
$serviceId = $service['serviceid'];
// only calculate the sla for services which require it
if (isset($usedSeviceIds[$serviceId])) {
$latestValue = (isset($latestValues[$serviceId])) ? $latestValues[$serviceId] : 0;
$intervalSla = $slaCalculator->calculateSla($service['alarms'], $service['times'],
$interval['from'], $interval['to'], $latestValue
);
}
else {
$intervalSla = [
'ok' => null,
'okTime' => null,
'problemTime' => null,
'downtimeTime' => null
];
}
$rs[$service['serviceid']]['sla'][] = [
'from' => $interval['from'],
'to' => $interval['to'],
'sla' => $intervalSla['ok'],
'okTime' => $intervalSla['okTime'],
'problemTime' => $intervalSla['problemTime'],
'downtimeTime' => $intervalSla['downtimeTime']
];
}
}
}
}
return $rs;
}
/**
* Deletes all service times for the given services.
*
* @param array $serviceIds
*
* @return boolean
*/
public function deleteTimes($serviceIds) {
$serviceIds = zbx_toArray($serviceIds);
$this->validateDeleteTimes($serviceIds);
DB::delete('services_times', [
'serviceid' => $serviceIds
]);
return ['serviceids' => $serviceIds];
}
/**
* Deletes the dependencies of the parent services on the given services.
*
* @param $serviceIds
*/
protected function deleteParentDependencies($serviceIds) {
DB::delete('services_links', [
'servicedownid' => $serviceIds,
'soft' => 0
]);
}
/**
* Returns an array of triggers which are in a problem state and are linked to the given services.
*
* @param array $serviceIds
*
* @return array in the form of array(serviceId1 => array(triggerId => trigger), ...)
*/
protected function fetchProblemTriggers(array $serviceIds) {
$sql = 'SELECT s.serviceid,t.triggerid'.
' FROM services s,triggers t'.
' WHERE s.status>0'.
' AND t.triggerid=s.triggerid'.
' AND '.dbConditionInt('s.serviceid', $serviceIds).
' ORDER BY s.status DESC,t.description';
// get service reason
$triggers = DBfetchArray(DBSelect($sql));
$rs = [];
foreach ($triggers as $trigger) {
$serviceId = $trigger['serviceid'];
unset($trigger['serviceid']);
$rs[$serviceId] = [$trigger['triggerid'] => $trigger];
}
return $rs;
}
/**
* Escalates the problem triggers from the child services to their parents and adds them to $slaData.
* The escalation will stop if a service has status calculation disabled or is in OK state.
*
* @param array $services
* @param array $serviceProblems an array of service triggers defines as
* array(serviceId1 => array(triggerId => trigger), ...)
* @param array $slaData
*
* @return array
*/
protected function escalateProblems(array $services, array $serviceProblems, array $slaData) {
$parentProblems = [];
foreach ($serviceProblems as $serviceId => $problemTriggers) {
$service = $services[$serviceId];
// add the problem trigger of the current service to the data
$slaData[$serviceId]['problems'] = zbx_array_merge($slaData[$serviceId]['problems'], $problemTriggers);
// add the same trigger to the parent services
foreach ($service['parentDependencies'] as $dependency) {
$parentServiceId = $dependency['serviceupid'];
if (isset($services[$parentServiceId])) {
$parentService = $services[$parentServiceId];
// escalate only if status calculation is enabled for the parent service and it's in problem state
if ($this->isStatusEnabled($parentService) && $parentService['status']) {
if (!isset($parentProblems[$parentServiceId])) {
$parentProblems[$parentServiceId] = [];
}
$parentProblems[$parentServiceId] = zbx_array_merge($parentProblems[$parentServiceId], $problemTriggers);
}
}
}
}
// propagate the problems to the parents
if ($parentProblems) {
$slaData = $this->escalateProblems($services, $parentProblems, $slaData);
}
return $slaData;
}
/**
* Returns the value of the latest service alarm before the given time.
*
* @param array $serviceIds
* @param int $beforeTime
*
* @return array
*/
protected function fetchLatestValues(array $serviceIds, $beforeTime) {
// The query will return the alarms with the latest servicealarmid for each service, before $beforeTime.
$query = DBSelect(
'SELECT sa.serviceid,sa.value'.
' FROM (SELECT sa2.serviceid,MAX(sa2.servicealarmid) AS servicealarmid'.
' FROM service_alarms sa2'.
' WHERE sa2.clock<'.zbx_dbstr($beforeTime).
' AND '.dbConditionInt('sa2.serviceid', $serviceIds).
'GROUP BY sa2.serviceid) ss2 '.
' JOIN service_alarms sa ON sa.servicealarmid = ss2.servicealarmid'
);
$rs = [];
while ($alarm = DBfetch($query)) {
$rs[$alarm['serviceid']] = $alarm['value'];
}
return $rs;
}
/**
* Returns an array of dependencies that are children of the given services. Performs permission checks.
*
* @param array $parentServiceIds
* @param $output
*
* @return array an array of service links sorted by "sortorder" in ascending order
*/
protected function fetchChildDependencies(array $parentServiceIds, $output) {
$sqlParts = API::getApiService()->createSelectQueryParts('services_links', 'sl', [
'output' => $output,
'filter' => ['serviceupid' => $parentServiceIds]
]);
// sort by sortorder
$sqlParts['from'][] = $this->tableName().' '.$this->tableAlias();
$sqlParts['where'][] = 'sl.servicedownid='.$this->fieldId('serviceid');
$sqlParts = $this->addQueryOrder($this->fieldId('sortorder'), $sqlParts);
$sqlParts = $this->addQueryOrder($this->fieldId('serviceid'), $sqlParts);
// add permission filter
if (self::$userData['type'] != USER_TYPE_SUPER_ADMIN) {
$sqlParts = $this->addPermissionFilter($sqlParts);
}
$sql = $this->createSelectQueryFromParts($sqlParts);
return DBfetchArray(DBselect($sql));
}
/**
* Returns an array of dependencies from the parent services to the given services.
* Performs permission checks.
*
* @param array $childServiceIds
* @param $output
* @param boolean $soft if set to true, will return only soft-linked dependencies
*
* @return array an array of service links sorted by "sortorder" in ascending order
*/
protected function fetchParentDependencies(array $childServiceIds, $output, $soft = null) {
$sqlParts = API::getApiService()->createSelectQueryParts('services_links', 'sl', [
'output' => $output,
'filter' => ['servicedownid' => $childServiceIds]
]);
$sqlParts['from'][] = $this->tableName().' '.$this->tableAlias();
$sqlParts['where'][] = 'sl.serviceupid='.$this->fieldId('serviceid');
if ($soft !== null) {
$sqlParts['where'][] = 'sl.soft='.($soft ? 1 : 0);
}
$sqlParts = $this->addQueryOrder($this->fieldId('sortorder'), $sqlParts);
$sqlParts = $this->addQueryOrder($this->fieldId('serviceid'), $sqlParts);
// add permission filter
if (self::$userData['type'] != USER_TYPE_SUPER_ADMIN) {
$sqlParts = $this->addPermissionFilter($sqlParts);
}
$sql = $this->createSelectQueryFromParts($sqlParts);
return DBfetchArray(DBselect($sql));
}
/**
* Returns true if status calculation is enabled for the given service.
*
* @param array $service
*
* @return bool
*/
protected function isStatusEnabled(array $service) {
return ($service['algorithm'] != SERVICE_ALGORITHM_NONE);
}
/**
* Validates the "name" field.
*
* @throws APIException if the name is missing
*
* @param array $service
*/
protected function checkName(array $service) {
if (!isset($service['name']) || zbx_empty($service['name'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty name.'));
}
}
/**
* Validates the "algorithm" field. Assumes the "name" field is valid.
*
* @throws APIException if the name is missing or invalid
*
* @param array $service
*/
protected function checkAlgorithm(array $service) {
if (!isset($service['algorithm']) || !serviceAlgorithm($service['algorithm'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect algorithm for service "%1$s".', $service['name']));
}
}
/**
* Validates the "showsla" field. Assumes the "name" field is valid.
*
* @throws APIException if the name is missing or is not a boolean value
*
* @param array $service
*/
protected function checkShowSla(array $service) {
$showSlaValues = [
SERVICE_SHOW_SLA_OFF => true,
SERVICE_SHOW_SLA_ON => true
];
if (!isset($service['showsla']) || !isset($showSlaValues[$service['showsla']])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect calculate SLA value for service "%1$s".', $service['name']));
}
}
/**
* Validates the "showsla" field. Assumes the "name" field is valid.
*
* @throws APIException if the value is missing, or is out of bounds
*
* @param array $service
*/
protected function checkGoodSla(array $service) {
if ((!empty($service['showsla']) && empty($service['goodsla']))
|| (isset($service['goodsla'])
&& (!is_numeric($service['goodsla']) || $service['goodsla'] < 0 || $service['goodsla'] > 100))) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect acceptable SLA for service "%1$s".', $service['name']));
}
}
/**
* Validates the "sortorder" field. Assumes the "name" field is valid.
*
* @throws APIException if the value is missing, or is out of bounds
*
* @param array $service
*/
protected function checkSortOrder(array $service) {
if (!isset($service['sortorder']) || !zbx_is_int($service['sortorder'])
|| $service['sortorder'] < 0 || $service['sortorder'] > 999) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect sort order for service "%1$s".', $service['name']));
}
}
/**
* Validates the "triggerid" field. Assumes the "name" field is valid.
*
* @throws APIException if the value is incorrect
*
* @param array $service
*/
protected function checkTriggerId(array $service) {
if (!empty($service['triggerid']) && !zbx_is_int($service['triggerid'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect trigger ID for service "%1$s".', $service['name']));
}
}
/**
* Validates the "parentid" field. Assumes the "name" field is valid.
*
* @throws APIException if the value is incorrect
*
* @param array $service
*/
protected function checkParentId(array $service) {
if (!empty($service['parentid']) && !zbx_is_int($service['parentid'])) {
if (isset($service['name'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect parent for service "%1$s".', $service['name']));
}
else {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect parent service.'));
}
}
if (isset($service['serviceid']) && idcmp($service['serviceid'], $service['parentid'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Service cannot be parent and child at the same time.'));
}
}
/**
* Validates the "status" field. Assumes the "name" field is valid.
*
* @throws APIException if the value is incorrect
*
* @param array $service
*/
protected function checkStatus(array $service) {
if (!empty($service['status']) && !zbx_is_int($service['status'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect status for service "%1$s".', $service['name']));
}
}
/**
* Checks that the user has read access to the given triggers.
*
* @throws APIException if the user doesn't have permission to access any of the triggers
*
* @param array $services
*/
protected function checkTriggerPermissions(array $services) {
$triggerids = [];
foreach ($services as $service) {
if (!empty($service['triggerid'])) {
$triggerids[$service['triggerid']] = true;
}
}
if ($triggerids) {
$count = API::Trigger()->get([
'countOutput' => true,
'triggerids' => array_keys($triggerids)
]);
if ($count != count($triggerids)) {
self::exception(ZBX_API_ERROR_PERMISSIONS,
_('No permissions to referred object or it does not exist!')
);
}
}
}
/**
* Checks that all of the given services are readable.
*
* @throws APIException if at least one of the services doesn't exist
*
* @param array $serviceids
*/
protected function checkServicePermissions(array $serviceids) {
if ($serviceids) {
$serviceids = array_unique($serviceids);
$count = $this->get([
'countOutput' => true,
'serviceids' => $serviceids
]);
if ($count != count($serviceids)) {
self::exception(ZBX_API_ERROR_PERMISSIONS,
_('No permissions to referred object or it does not exist!')
);
}
}
}
/**
* Checks that none of the given services have any children.
*
* @throws APIException if at least one of the services has a child service
*
* @param array $serviceIds
*/
protected function checkThatServicesDontHaveChildren(array $serviceIds) {
$child = API::getApiService()->select('services_links', [
'output' => ['serviceupid'],
'filter' => [
'serviceupid' => $serviceIds,
'soft' => 0
],
'limit' => 1
]);
$child = reset($child);
if ($child) {
$service = API::getApiService()->select($this->tableName(), [
'output' => ['name'],
'serviceids' => $child['serviceupid'],
'limit' => 1
]);
$service = reset($service);
self::exception(ZBX_API_ERROR_PERMISSIONS,
_s('Service "%1$s" cannot be deleted, because it is dependent on another service.', $service['name'])
);
}
}
/**
* Checks that the given dependency is valid.
*
* @throws APIException if the dependency is invalid
*
* @param array $dependency
*/
protected function checkDependency(array $dependency) {
if (idcmp($dependency['serviceid'], $dependency['dependsOnServiceid'])) {
$service = API::getApiService()->select($this->tableName(), [
'output' => ['name'],
'serviceids' => $dependency['serviceid']
]);
$service = reset($service);
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Service "%1$s" cannot be dependent on itself.', $service['name']));
}
// check 'soft' field value
if (!isset($dependency['soft']) || !in_array((int) $dependency['soft'], [0, 1], true)) {
$service = API::getApiService()->select($this->tableName(), [
'output' => ['name'],
'serviceids' => $dependency['serviceid']
]);
$service = reset($service);
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect "soft" field value for dependency for service "%1$s".', $service['name'])
);
}
}
/**
* Checks that that none of the given services are hard linked to a different service.
* Assumes the dependencies are valid.
*
* @throws APIException if at a least one service is hard linked to another service
*
* @param array $dependencies
*/
protected function checkForHardlinkedDependencies(array $dependencies) {
// only check hard dependencies
$hardDepServiceIds = [];
foreach ($dependencies as $dependency) {
if (!$dependency['soft']) {
$hardDepServiceIds[] = $dependency['dependsOnServiceid'];
}
}
if ($hardDepServiceIds) {
// look for at least one hardlinked service among the given
$hardDepServiceIds = array_unique($hardDepServiceIds);
$dep = API::getApiService()->select('services_links', [
'output' => ['servicedownid'],
'filter' => [
'soft' => 0,
'servicedownid' => $hardDepServiceIds
],
'limit' => 1
]);
if ($dep) {
$dep = reset($dep);
$service = API::getApiService()->select($this->tableName(), [
'output' => ['name'],
'serviceids' => $dep['servicedownid']
]);
$service = reset($service);
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Service "%1$s" is already hardlinked to a different service.', $service['name'])
);
}
}
}
/**
* Checks that none of the parent services are linked to a trigger. Assumes the dependencies are valid.
*
* @throws APIException if at least one of the parent services is linked to a trigger
*
* @param array $dependencies
*/
protected function checkThatParentsDontHaveTriggers(array $dependencies) {
$parentServiceIds = array_unique(zbx_objectValues($dependencies, 'serviceid'));
if ($parentServiceIds) {
$query = DBselect(
'SELECT s.triggerid,s.name'.
' FROM services s '.
' WHERE '.dbConditionInt('s.serviceid', $parentServiceIds).
' AND s.triggerid IS NOT NULL', 1);
if ($parentService = DBfetch($query)) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Service "%1$s" cannot be linked to a trigger and have children at the same time.', $parentService['name']));
}
}
}
/**
* Checks that dependencies will not create cycles in service dependencies.
*
* @throws APIException if at least one cycle is possible
*
* @param array $depsToValid dependency list to be validated
*/
protected function checkForCircularityInDependencies($depsToValid) {
$dbDeps = API::getApiService()->select('services_links', [
'output' => ['serviceupid', 'servicedownid']
]);
// create existing dependency acyclic graph
$arr = [];
foreach ($dbDeps as $dbDep) {
if (!isset($arr[$dbDep['serviceupid']])) {
$arr[$dbDep['serviceupid']] = [];
}
$arr[$dbDep['serviceupid']][$dbDep['servicedownid']] = $dbDep['servicedownid'];
}
// check for circularity and add dependencies to the graph
foreach ($depsToValid as $dep) {
$this->DFCircularitySearch($dep['serviceid'], $dep['dependsOnServiceid'], $arr);
$arr[$dep['serviceid']][$dep['dependsOnServiceid']] = $dep['dependsOnServiceid'];
}
}
/**
* Depth First Search recursive function to find circularity and rise exception.
*
* @throws APIException if cycle is possible
*
* @param int $id dependency from id
* @param int $depId dependency to id
* @param ref $arr reference to graph structure. Structure is associative array with keys as "from id"
* and values as arrays with keys and values as "to id".
*/
protected function dfCircularitySearch($id, $depId, &$arr) {
if ($id == $depId) {
// cycle found
self::exception(ZBX_API_ERROR_PARAMETERS, _('Services form a circular dependency.'));
}
if (isset($arr[$depId])) {
foreach ($arr[$depId] as $dep) {
$this->DFCircularitySearch($id, $dep, $arr);
}
}
}
/**
* Checks that the given service time is valid.
*
* @throws APIException if the service time is invalid
*
* @param array $serviceTime
*/
protected function checkTime(array $serviceTime) {
if (empty($serviceTime['serviceid'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Invalid method parameters.'));
}
checkServiceTime($serviceTime);
}
protected function applyQueryFilterOptions($tableName, $tableAlias, array $options, array $sqlParts) {
if (self::$userData['type'] != USER_TYPE_SUPER_ADMIN) {
// if services with specific trigger IDs were requested, return only the ones accessible to the current user.
if ($options['filter']['triggerid']) {
$accessibleTriggers = API::Trigger()->get([
'output' => ['triggerid'],
'triggerids' => $options['filter']['triggerid']
]);
$options['filter']['triggerid'] = zbx_objectValues($accessibleTriggers, 'triggerid');
}
// otherwise return services with either no triggers, or any trigger accessible to the current user
else {
$sqlParts = $this->addPermissionFilter($sqlParts);
}
}
$sqlParts = parent::applyQueryFilterOptions($tableName, $tableAlias, $options, $sqlParts);
// parentids
if ($options['parentids'] !== null) {
$sqlParts['from'][] = 'services_links slp';
$sqlParts['where'][] = $this->fieldId('serviceid').'=slp.servicedownid AND slp.soft=0';
$sqlParts['where'][] = dbConditionInt('slp.serviceupid', (array) $options['parentids']);
}
// childids
if ($options['childids'] !== null) {
$sqlParts['from'][] = 'services_links slc';
$sqlParts['where'][] = $this->fieldId('serviceid').'=slc.serviceupid AND slc.soft=0';
$sqlParts['where'][] = dbConditionInt('slc.servicedownid', (array) $options['childids']);
}
return $sqlParts;
}
protected function addRelatedObjects(array $options, array $result) {
$result = parent::addRelatedObjects($options, $result);
$serviceIds = array_keys($result);
// selectDependencies
if ($options['selectDependencies'] !== null && $options['selectDependencies'] != API_OUTPUT_COUNT) {
$dependencies = $this->fetchChildDependencies($serviceIds,
$this->outputExtend($options['selectDependencies'], ['serviceupid', 'linkid'])
);
$dependencies = zbx_toHash($dependencies, 'linkid');
$relationMap = $this->createRelationMap($dependencies, 'serviceupid', 'linkid');
$dependencies = $this->unsetExtraFields($dependencies, ['serviceupid', 'linkid'], $options['selectDependencies']);
$result = $relationMap->mapMany($result, $dependencies, 'dependencies');
}
// selectParentDependencies
if ($options['selectParentDependencies'] !== null && $options['selectParentDependencies'] != API_OUTPUT_COUNT) {
$dependencies = $this->fetchParentDependencies($serviceIds,
$this->outputExtend($options['selectParentDependencies'], ['servicedownid', 'linkid'])
);
$dependencies = zbx_toHash($dependencies, 'linkid');
$relationMap = $this->createRelationMap($dependencies, 'servicedownid', 'linkid');
$dependencies = $this->unsetExtraFields($dependencies, ['servicedownid', 'linkid'],
$options['selectParentDependencies']
);
$result = $relationMap->mapMany($result, $dependencies, 'parentDependencies');
}
// selectParent
if ($options['selectParent'] !== null && $options['selectParent'] != API_OUTPUT_COUNT) {
$dependencies = $this->fetchParentDependencies($serviceIds, ['servicedownid', 'serviceupid'], false);
$relationMap = $this->createRelationMap($dependencies, 'servicedownid', 'serviceupid');
$parents = $this->get([
'output' => $options['selectParent'],
'serviceids' => $relationMap->getRelatedIds(),
'preservekeys' => true
]);
$result = $relationMap->mapOne($result, $parents, 'parent');
}
// selectTimes
if ($options['selectTimes'] !== null && $options['selectTimes'] != API_OUTPUT_COUNT) {
$serviceTimes = API::getApiService()->select('services_times', [
'output' => $this->outputExtend($options['selectTimes'], ['serviceid', 'timeid']),
'filter' => ['serviceid' => $serviceIds],
'preservekeys' => true
]);
$relationMap = $this->createRelationMap($serviceTimes, 'serviceid', 'timeid');
$serviceTimes = $this->unsetExtraFields($serviceTimes, ['serviceid', 'timeid'], $options['selectTimes']);
$result = $relationMap->mapMany($result, $serviceTimes, 'times');
}
// selectAlarms
if ($options['selectAlarms'] !== null && $options['selectAlarms'] != API_OUTPUT_COUNT) {
$serviceAlarms = API::getApiService()->select('service_alarms', [
'output' => $this->outputExtend($options['selectAlarms'], ['serviceid', 'servicealarmid']),
'filter' => ['serviceid' => $serviceIds],
'preservekeys' => true
]);
$relationMap = $this->createRelationMap($serviceAlarms, 'serviceid', 'servicealarmid');
$serviceAlarms = $this->unsetExtraFields($serviceAlarms, ['serviceid', 'servicealarmid'],
$options['selectAlarms']
);
$result = $relationMap->mapMany($result, $serviceAlarms, 'alarms');
}
// selectTrigger
if ($options['selectTrigger'] !== null && $options['selectTrigger'] != API_OUTPUT_COUNT) {
$relationMap = $this->createRelationMap($result, 'serviceid', 'triggerid');
$triggers = API::getApiService()->select('triggers', [
'output' => $options['selectTrigger'],
'triggerids' => $relationMap->getRelatedIds(),
'preservekeys' => true
]);
$result = $relationMap->mapOne($result, $triggers, 'trigger');
}
return $result;
}
protected function applyQueryOutputOptions($tableName, $tableAlias, array $options, array $sqlParts) {
$sqlParts = parent::applyQueryOutputOptions($tableName, $tableAlias, $options, $sqlParts);
if (!$options['countOutput']) {
if ($options['selectTrigger'] !== null) {
$sqlParts = $this->addQuerySelect($this->fieldId('triggerid'), $sqlParts);
}
}
return $sqlParts;
}
/**
* Add permission filter SQL query part
*
* @param array $sqlParts
*
* @return string
*/
protected function addPermissionFilter($sqlParts) {
$userGroups = getUserGroupsByUserId(self::$userData['userid']);
$sqlParts['where'][] = '(EXISTS ('.
'SELECT NULL'.
' FROM functions f,items i,hosts_groups hgg'.
' JOIN rights r'.
' ON r.id=hgg.groupid'.
' AND '.dbConditionInt('r.groupid', $userGroups).
' WHERE s.triggerid=f.triggerid'.
' AND f.itemid=i.itemid'.
' AND i.hostid=hgg.hostid'.
' GROUP BY f.triggerid'.
' HAVING MIN(r.permission)>'.PERM_DENY.
')'.
' OR s.triggerid IS NULL)';
return $sqlParts;
}
}
|