Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
monitoring.php
1<?php
2namespace Bitrix\Scale;
3
4use \Bitrix\Main\Localization\Loc;
5Loc::loadMessages(__FILE__);
6
12{
13 protected static $rrdPath = "/var/lib/munin";
14 protected static $monitoringCategories = array();
15
20 public static function isDatabaseCreated($hostname)
21 {
22 $dir = new \Bitrix\Main\IO\Directory(static::$rrdPath."/".$hostname);
23 return $dir->isExists();
24 }
25
30 public static function isEnabled()
31 {
32 $result = false;
33 $command = "sudo -u root /opt/webdir/bin/bx-monitor -o json";
34
35 try
36 {
37 $action = new Action("is_monitoring_enabled", array(
38 "START_COMMAND_TEMPLATE" => $command,
39 "LOG_LEVEL" => Logger::LOG_LEVEL_DISABLE
40 ), "", array());
41
42 if(!$action->start())
43 {
44 return false;
45 }
46 }
47 catch(\Exception $e)
48 {
49 return false;
50 }
51
52 $actRes = $action->getResult();
53 if(isset($actRes["is_monitoring_enabled"]["OUTPUT"]["DATA"]["params"]["monitor"]["monitoring_status"]))
54 {
55 $result = ($actRes["is_monitoring_enabled"]["OUTPUT"]["DATA"]["params"]["monitor"]["monitoring_status"] == "enable");
56 }
57 else
58 {
59 $result = false;
60 }
61
62 return $result;
63 }
64
74 public static function getLoadBarValue($hostname, $roleId)
75 {
76 if (!extension_loaded('rrd'))
77 throw new \Exception("Extension rrd not loaded!");
78
79 if($hostname == '')
80 throw new \Bitrix\Main\ArgumentNullException("hostname");
81
82 if($roleId == '')
83 throw new \Bitrix\Main\ArgumentNullException("roleId");
84
85 $role = RolesData::getRole($roleId);
86
87 if(empty($role))
88 throw new \Exception("Role with id = ".$roleId." was not defined.");
89
90 if(!isset($role["LOADBAR_INFO"]) || $role["LOADBAR_INFO"] == '')
91 throw new \Exception("Role ".$roleId." has no correctly defined LOADBAR_INFO param .");
92
93 $rrdFile = str_replace('##HOSTNAME##', $hostname, $role["LOADBAR_INFO"]);
94 $rrdPath = "/var/lib/munin/".$hostname."/".$rrdFile;
95 $file = new \Bitrix\Main\IO\File($rrdPath);
96
97 if(!$file->isExists())
98 throw new \Bitrix\Main\IO\FileNotFoundException($rrdPath);
99
100 $data = \rrd_lastupdate($rrdPath);
101
102 $result = static::extractRrdValue($data);
103
104 return $result;
105 }
106
107 public static function getInfoTableCategory($hostname, $categoryId)
108 {
109 if($hostname == '')
110 throw new \Bitrix\Main\ArgumentNullException("hostname");
111
112 if($categoryId == '')
113 throw new \Bitrix\Main\ArgumentNullException("paramId");
114
115 $categories = self::getInfoTableCategoriesList($hostname);
116 $result = array();
117
118 if(isset($categories[$categoryId]))
119 $result = $categories[$categoryId];
120
121 return $result;
122 }
123
124 public static function getInfoTableCategoriesList($hostname)
125 {
126 $result = array();
127
128 $result["HDD"] = array(
129 "NAME" => Loc::getMessage("SCALE_MONITORING_HDD"),
130 "PARAMS" => static::getHddsParams($hostname)
131 );
132
133 $result["NET"] = array(
134 "NAME" => Loc::getMessage("SCALE_MONITORING_NET"),
135 "PARAMS" => static::getNetParams($hostname)
136 );
137
138 $result["HDDACT"] = array(
139 "NAME" => Helper::nbsp(Loc::getMessage("SCALE_MONITORING_HDDACT")),
140 "PARAMS" => static::getHddsUtilization($hostname)
141 );
142
143 $result["MEMORY"] = array(
144 "NAME" => Loc::getMessage("SCALE_MONITORING_MEMORY"),
145 "PARAMS" => array(
146 array(
147 "NAME" => Loc::getMessage("SCALE_MONITORING_MEMORY_PARAMS"),
148 "TYPE" => "ARRAY",
149 "ITEMS" => array(
150 array(
151 "VALUE_FUNC" => '\Bitrix\Scale\Monitoring::getMemoryUsage',
152 "FUNC_PARAMS" => array($hostname)
153 ),
154 array(
155 "VALUE_FUNC" => '\Bitrix\Scale\Monitoring::getMemoryUsageValue',
156 "FUNC_PARAMS" => array($hostname),
157 "TYPE"=>"LOADBAR"
158 )
159 )
160 )
161 )
162 );
163
164 $result["AVG_LOAD"] = array(
165 "NAME" => Helper::nbsp(Loc::getMessage("SCALE_ITS_AVG_LOAD_NAME")),
166 "PARAMS" => array(
167 "CURR" => array(
168 "NAME" => Loc::getMessage("SCALE_ITS_AVG_LOAD_CURR"),
169 "RRD" => "##HOSTNAME##-load-load-g.rrd",
170 "CF" => "LAST",
171 "FORMAT" => "%2.2lf"
172 ),
173 "MIN" => array(
174 "NAME" => Loc::getMessage("SCALE_ITS_AVG_LOAD_MIN"),
175 "RRD" => "##HOSTNAME##-load-load-g.rrd",
176 "CF" => "MIN",
177 "FORMAT" => "%2.2lf"
178 ),
179 "MAX" => array(
180 "NAME" => Loc::getMessage("SCALE_ITS_AVG_LOAD_MAX"),
181 "RRD" => "##HOSTNAME##-load-load-g.rrd",
182 "CF" => "MAX",
183 "FORMAT" => "%2.2lf"
184 )
185 )
186 );
187
188 return $result;
189 }
190
191 public static function getValue($hostname, $categoryId, $param)
192 {
193 if($hostname == '')
194 throw new \Bitrix\Main\ArgumentNullException("hostname");
195
196 if($categoryId == '')
197 throw new \Bitrix\Main\ArgumentNullException("categoryId");
198
199 if($param == '')
200 throw new \Bitrix\Main\ArgumentNullException("param");
201
202 $arCat = static::getInfoTableCategory($hostname, $categoryId);
203
204 if(!$arCat)
205 throw new \Exception("Monitoring category ".$categoryId." not exist.");
206
207 if(!$arCat["PARAMS"][$param])
208 throw new \Exception("Monitoring param ".$param." in category ".$categoryId." not exist.");
209
210 $monParam = $arCat["PARAMS"][$param];
211
212 if(isset($monParam["TYPE"]) && $monParam["TYPE"] == "ARRAY")
213 {
214 if(!isset($monParam["ITEMS"]) || !is_array($monParam["ITEMS"]))
215 throw new \Exception("Monitoring param ".$param." in category ".$categoryId." hasn't field ITEMS.");
216
217 $result = array();
218 foreach($monParam["ITEMS"] as $item)
219 {
220 $result[] = static::getItemValue($hostname, $categoryId, $item, $param);
221 }
222 }
223 else
224 {
225 $result = static::getItemValue($hostname, $categoryId, $monParam, $param);
226 }
227
228 return $result;
229 }
230
231 protected static function getItemValue($hostname, $categoryId, $item, $param)
232 {
233 if(isset($item["VALUE"]))
234 return $item["VALUE"];
235
236 if(isset($item["VALUE_FUNC"]))
237 {
238 return call_user_func_array($item["VALUE_FUNC"], (isset($item["FUNC_PARAMS"]) ? $item["FUNC_PARAMS"] : array()));
239 }
240
241 if((!$item["RRD"] || !$item["CF"]) && !$item["OPTIONS"])
242 throw new \Exception("Monitoring param item in category ".$categoryId." has no RRD or CF fields.");
243
244 if(isset($item["RRD"]))
245 {
246 $rrdFile = str_replace('##HOSTNAME##', $hostname, $item["RRD"]);
247 $rrdPath = static::$rrdPath."/".$hostname."/".$rrdFile;
248 $file = new \Bitrix\Main\IO\File($rrdPath);
249
250 if(!$file->isExists())
251 throw new \Bitrix\Main\IO\FileNotFoundException($rrdPath);
252
253 $first = \rrd_first($rrdPath);
254 $last = \rrd_last($rrdPath);
255 }
256
257 if(isset($item["OPTIONS"]))
258 {
259 $arOpts = $item["OPTIONS"];
260 $arOpts = str_replace('##HOSTNAME##', $hostname, $arOpts);
261 }
262 else
263 {
264 if($item["CF"] == "MIN")
265 {
266 $agr = "MINIMUM";
267 }
268 elseif($item["CF"] == "MAX")
269 {
270 $agr = "MAXIMUM";
271 }
272 else
273 {
274 $agr = $item["CF"];
275 }
276
277 if($item["CF"] == "LAST")
278 $item["CF"] = "AVERAGE";
279
280 $format = isset($item["FORMAT"]) ? $item["FORMAT"] : "%6.2lf";
281
282 $arOpts = array(
283 "DEF:val=".$rrdPath.":42:".$item["CF"],
284 "VDEF:vval=val,".$agr,
285 "PRINT:vval:".$format);
286 }
287
288 if(isset($item["RRD"]))
289 {
290 $arOpts[] = "--start";
291 $arOpts[] = $first;
292 $arOpts[] = "--end";
293 $arOpts[] = $last;
294 }
295
296 $data = \rrd_graph( "/dev/null", $arOpts);
297
298 if(isset($item["DATA_FUNC"]) && is_callable($item["DATA_FUNC"]))
299 {
300 $result = $item["DATA_FUNC"]($data);
301 }
302 else
303 {
304 if(isset($data["calcpr"]))
305 {
306 $data["data"] = $data["calcpr"];
307 }
308
309 $result = static::extractRrdValue($data);
310 }
311
312 return $result;
313 }
314
315 protected static function extractRrdValue($data)
316 {
317 $result = false;
318
319 if(isset($data["data"]) && is_array($data["data"]))
320 {
321 reset($data["data"]);
322 $result = current($data["data"]);
323 }
324
325 return trim($result);
326 }
327
328 protected static function getAnsibleSetup($hostname)
329 {
330 static $info = array();
331
332 if(!isset($info[$hostname]))
333 {
334 $shellAdapter = new ShellAdapter();
335 $execRes = $shellAdapter->syncExec("sudo -u root /usr/bin/ansible ".$hostname." -m setup");
336 $serversData = $shellAdapter->getLastOutput();
337 $serversData = mb_substr($serversData, mb_strpos($serversData, "{"));
338
339 if($execRes)
340 {
341 $info[$hostname] = json_decode($serversData, true);
342 }
343 else
344 {
345 $info[$hostname] = array();
346 }
347 }
348
349 return $info[$hostname];
350 }
351
352 protected static function getHddsParams($hostname)
353 {
354 $result = array();
355 $arData = static::getAnsibleSetup($hostname);
356
357 if(isset($arData["ansible_facts"]["ansible_mounts"]))
358 {
359 foreach($arData["ansible_facts"]["ansible_mounts"] as $mountId => $mount)
360 {
361 $result[$mountId] = array(
362 "NAME" => $mount["device"]." ".Loc::getMessage("SCALE_MONITORING_HDD_PARAMS"),
363 "TYPE" => "ARRAY",
364 "ITEMS" => array(
365 array(
366 "VALUE_FUNC" => '\Bitrix\Scale\Monitoring::getHddsValues',
367 "FUNC_PARAMS" => array(
368 $hostname,
369 $mountId
370 )
371 ),
372 array(
373 "TYPE" => "LOADBAR",
374 "VALUE_FUNC" => '\Bitrix\Scale\Monitoring::getHddsUsed',
375 "FUNC_PARAMS" => array(
376 $hostname,
377 $mountId
378 )
379
380 )
381 )
382 );
383 }
384 }
385
386 return $result;
387 }
388
389 protected static function getHddsUsed($hostname, $param)
390 {
391 $arData = static::getAnsibleSetup($hostname);
392
393 if(isset($arData["ansible_facts"]["ansible_mounts"][$param]["size_total"]) && isset($arData["ansible_facts"]["ansible_mounts"][$param]["size_available"]))
394 {
395 $mount = $arData["ansible_facts"]["ansible_mounts"][$param];
396 $result = ($mount["size_total"]-$mount["size_available"])/$mount["size_total"]*100;
397 }
398 else
399 {
400 $result = "0";
401 }
402
403 return $result;
404 }
405
406 protected static function getHddsValues($hostname, $param)
407 {
408 $arData = static::getAnsibleSetup($hostname);
409
410 if(isset($arData["ansible_facts"]["ansible_mounts"][$param]["size_total"]) && isset($arData["ansible_facts"]["ansible_mounts"][$param]["size_available"]))
411 {
412 $mount = $arData["ansible_facts"]["ansible_mounts"][$param];
413
414 $result = static::formatSize($mount["size_total"], 2)."&nbsp;/&nbsp;".
415 static::formatSize(($mount["size_total"]-$mount["size_available"]), 2)."&nbsp;/&nbsp;".
416 static::formatSize($mount["size_available"], 2);
417 }
418 else
419 {
420 $result = "0";
421 }
422
423 return $result;
424 }
425
426 protected static function getNetParams($hostname)
427 {
428 $dir = new \Bitrix\Main\IO\Directory(static::$rrdPath."/".$hostname);
429
430 if(!$dir->isExists())
431 return array();
432
433 $arChildren = $dir->getChildren();
434 $result = array();
435
436 foreach ($arChildren as $child)
437 {
438 if(!$child->isFile())
439 continue;
440
441 $name = $child->getName();
442 $pos1 = mb_strpos($name, "-if_");
443 $pos2 = mb_strpos($name, "-up-");
444
445 if($pos1 !== false && $pos2 !== false)
446 {
447 $pos1 += 4;
448 $dev = mb_substr($name, $pos1, $pos2 - $pos1);
449
450 $result[$dev] = array(
451 "NAME" => $dev." ".Loc::getMessage("SCALE_MONITORING_NET_PARAMS"),
452 "RRD" => $hostname."-if_".$dev."-up-d.rrd",
453 "OPTIONS" => array(
454 "DEF:in=".static::$rrdPath."/".$hostname."/".$hostname."-if_".$dev."-up-d.rrd:42:AVERAGE:start=now-600;end=now",
455 "DEF:out=".static::$rrdPath."/".$hostname."/".$hostname."-if_".$dev."-down-d.rrd:42:AVERAGE:start=now-600;end=now",
456 "VDEF:vin=in,TOTAL",
457 "VDEF:vout=out,TOTAL",
458 "PRINT:vin:%1.2lf",
459 "PRINT:vout:%1.2lf"
460 ),
461 "DATA_FUNC" => '\Bitrix\Scale\Monitoring::formatNetParamsValue'
462 );
463 }
464 }
465
466 return $result;
467 }
468
469 protected static function formatNetParamsValue(array $data)
470 {
471 $result = false;
472
473 if(isset($data['calcpr'][0], $data['calcpr'][1]))
474 {
475 $result = static::formatSize((int)$data['calcpr'][0]/600) .
476 '&nbsp;/&nbsp;' .
477 static::formatSize((int)$data['calcpr'][1]/600).'&nbsp;' .
478 Helper::nbsp(Loc::getMessage('SCALE_MONITORING_NET_SEC'));
479 }
480
481 return $result;
482 }
483
484 protected static function getHddsUtilization($hostname)
485 {
486 $dir = new \Bitrix\Main\IO\Directory(static::$rrdPath."/".$hostname);
487
488 if(!$dir->isExists())
489 return array();
490
491 $arChildren = $dir->getChildren();
492 $result = array();
493
494 foreach ($arChildren as $child)
495 {
496 if(!$child->isFile())
497 continue;
498
499 $name = $child->getName();
500 $pos1 = mb_strpos($name, "-diskstats_utilization-");
501 $pos2 = mb_strpos($name, "-util-");
502 if($pos1 !== false && $pos2 !== false)
503 {
504 $pos1 += 23; //strlen("-diskstats_utilization-")
505 $dev = mb_substr($name, $pos1, $pos2 - $pos1);
506
507 $result[$dev] = array(
508 "NAME" => $dev." ".Loc::getMessage("SCALE_MONITORING_HDDACT_PARAMS"),
509 "TYPE" => "ARRAY",
510 "ITEMS" => array(
511 array(
512 "OPTIONS" => array(
513 "DEF:r=".static::$rrdPath."/".$hostname."/".$hostname."-diskstats_throughput-".$dev."-rdbytes-g.rrd:42:AVERAGE:start=now-600;end=now",
514 "DEF:w=".static::$rrdPath."/".$hostname."/".$hostname."-diskstats_throughput-".$dev."-wrbytes-g.rrd:42:AVERAGE:start=now-600;end=now",
515 "VDEF:vr=r,TOTAL",
516 "VDEF:vw=w,TOTAL",
517 "PRINT:vr:%1.2lf",
518 "PRINT:vw:%1.2lf"
519 ),
520 "DATA_FUNC" => '\Bitrix\Scale\Monitoring::formatHddsUtilizationValue'
521 ),
522 array(
523 "RRD" => $hostname."-diskstats_utilization-".$dev."-util-g.rrd",
524 "CF" => "LAST",
525 "FORMAT" => "%2.2lf",
526 "TYPE" => "LOADBAR"
527 ),
528 )
529 );
530 }
531 }
532
533 return $result;
534 }
535
536 protected static function formatHddsUtilizationValue(array $data)
537 {
538 $result = false;
539
540 if(isset($data['calcpr'][0], $data['calcpr'][1]))
541 {
542 $result = static::formatSize((int)$data['calcpr'][0]/600) .
543 '&nbsp;/&nbsp;' .
544 static::formatSize((int)$data['calcpr'][1]/600) .
545 '&nbsp;'.Loc::getMessage('SCALE_MONITORING_NET_SEC');
546 }
547
548 return $result;
549 }
550
556 public static function formatSize($size, $precision = 2)
557 {
558 static $a = array("b", "Kb", "Mb", "Gb", "Tb");
559 $pos = 0;
560 while($size >= 1024 && $pos < 4)
561 {
562 $size /= 1024;
563 $pos++;
564 }
565 return round($size, $precision)."&nbsp;".$a[$pos];
566 }
567
568 protected static function getMemoryUsage($hostname)
569 {
570 $result = "0";
571 $arData = static::getAnsibleSetup($hostname);
572
573 if(isset($arData["ansible_facts"]["ansible_memtotal_mb"]) && isset($arData["ansible_facts"]["ansible_memfree_mb"]))
574 $result = $arData["ansible_facts"]["ansible_memtotal_mb"]." / ".(intval($arData["ansible_facts"]["ansible_memtotal_mb"])-intval($arData["ansible_facts"]["ansible_memfree_mb"]))." / ".$arData["ansible_facts"]["ansible_memfree_mb"]." Mb";
575
576 return $result;
577 }
578
579 protected static function getMemoryUsageValue($hostname)
580 {
581 $result = "0";
582 $arData = static::getAnsibleSetup($hostname);
583
584 if(isset($arData["ansible_facts"]["ansible_memtotal_mb"]) && isset($arData["ansible_facts"]["ansible_memfree_mb"]) && intval($arData["ansible_facts"]["ansible_memtotal_mb"]) != 0)
585 $result = (intval($arData["ansible_facts"]["ansible_memtotal_mb"]) - intval($arData["ansible_facts"]["ansible_memfree_mb"]))/intval($arData["ansible_facts"]["ansible_memtotal_mb"])*100;
586
587 return $result;
588 }
589}
static loadMessages($file)
Definition loc.php:64
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
static nbsp($str)
Definition helper.php:23
const LOG_LEVEL_DISABLE
Definition logger.php:14
static getHddsUtilization($hostname)
static getMemoryUsage($hostname)
static formatHddsUtilizationValue(array $data)
static isDatabaseCreated($hostname)
static getMemoryUsageValue($hostname)
static getHddsValues($hostname, $param)
static getLoadBarValue($hostname, $roleId)
static getHddsUsed($hostname, $param)
static extractRrdValue($data)
static formatNetParamsValue(array $data)
static formatSize($size, $precision=2)
static getItemValue($hostname, $categoryId, $item, $param)
static getHddsParams($hostname)
static getInfoTableCategory($hostname, $categoryId)
static getInfoTableCategoriesList($hostname)
static getAnsibleSetup($hostname)
static getValue($hostname, $categoryId, $param)
static getNetParams($hostname)
static getRole($roleId)
Definition rolesdata.php:16