ormstopwatch.class.inc.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. <?php
  2. // Copyright (C) 2010-2013 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. require_once('backgroundprocess.inc.php');
  19. /**
  20. * ormStopWatch
  21. * encapsulate the behavior of a stop watch that will be stored as an attribute of class AttributeStopWatch
  22. *
  23. * @copyright Copyright (C) 2010-2012 Combodo SARL
  24. * @license http://opensource.org/licenses/AGPL-3.0
  25. */
  26. /**
  27. * ormStopWatch
  28. * encapsulate the behavior of a stop watch that will be stored as an attribute of class AttributeStopWatch
  29. *
  30. * @package itopORM
  31. */
  32. class ormStopWatch
  33. {
  34. protected $iTimeSpent; // seconds
  35. protected $iStarted; // unix time (seconds)
  36. protected $iLastStart; // unix time (seconds)
  37. protected $iStopped; // unix time (seconds)
  38. protected $aThresholds;
  39. /**
  40. * Constructor
  41. */
  42. public function __construct($iTimeSpent = 0, $iStarted = null, $iLastStart = null, $iStopped = null)
  43. {
  44. $this->iTimeSpent = (int) $iTimeSpent;
  45. $this->iStarted = $iStarted;
  46. $this->iLastStart = $iLastStart;
  47. $this->iStopped = $iStopped;
  48. $this->aThresholds = array();
  49. }
  50. /**
  51. * Necessary for the triggers
  52. */
  53. public function __toString()
  54. {
  55. return (string) $this->iTimeSpent;
  56. }
  57. public function DefineThreshold($iPercent, $tDeadline = null, $bPassed = false, $bTriggered = false, $iOverrun = null, $aHighlightDef = null)
  58. {
  59. $this->aThresholds[$iPercent] = array(
  60. 'deadline' => $tDeadline, // unix time (seconds)
  61. 'triggered' => $bTriggered,
  62. 'overrun' => $iOverrun,
  63. 'highlight' => $aHighlightDef, // array('code' => string, 'persistent' => boolean)
  64. );
  65. }
  66. public function MarkThresholdAsTriggered($iPercent)
  67. {
  68. $this->aThresholds[$iPercent]['triggered'] = true;
  69. }
  70. public function GetTimeSpent()
  71. {
  72. return $this->iTimeSpent;
  73. }
  74. public function GetStartDate()
  75. {
  76. return $this->iStarted;
  77. }
  78. public function GetLastStartDate()
  79. {
  80. return $this->iLastStart;
  81. }
  82. public function GetStopDate()
  83. {
  84. return $this->iStopped;
  85. }
  86. public function GetThresholdDate($iPercent)
  87. {
  88. if (array_key_exists($iPercent, $this->aThresholds))
  89. {
  90. return $this->aThresholds[$iPercent]['deadline'];
  91. }
  92. else
  93. {
  94. return null;
  95. }
  96. }
  97. public function GetOverrun($iPercent)
  98. {
  99. if (array_key_exists($iPercent, $this->aThresholds))
  100. {
  101. return $this->aThresholds[$iPercent]['overrun'];
  102. }
  103. else
  104. {
  105. return null;
  106. }
  107. }
  108. public function IsThresholdPassed($iPercent)
  109. {
  110. $bRet = false;
  111. if (array_key_exists($iPercent, $this->aThresholds))
  112. {
  113. $aThresholdData = $this->aThresholds[$iPercent];
  114. if (!is_null($aThresholdData['deadline']) && ($aThresholdData['deadline'] <= time()))
  115. {
  116. $bRet = true;
  117. }
  118. }
  119. return $bRet;
  120. }
  121. public function IsThresholdTriggered($iPercent)
  122. {
  123. if (array_key_exists($iPercent, $this->aThresholds))
  124. {
  125. return $this->aThresholds[$iPercent]['triggered'];
  126. }
  127. else
  128. {
  129. return false;
  130. }
  131. }
  132. public function GetHighlightCode()
  133. {
  134. $sCode = '';
  135. // Process the thresholds in ascending order
  136. $aPercents = array();
  137. foreach($this->aThresholds as $iPercent => $aDefs)
  138. {
  139. $aPercents[] = $iPercent;
  140. }
  141. sort($aPercents, SORT_NUMERIC);
  142. foreach($aPercents as $iPercent)
  143. {
  144. $aDefs = $this->aThresholds[$iPercent];
  145. if (array_key_exists('highlight', $aDefs) && is_array($aDefs['highlight']) && $this->IsThresholdPassed($iPercent))
  146. {
  147. if (($aDefs['highlight']['persistent'] == true) || (($aDefs['highlight']['persistent'] == false) && !is_null($this->iLastStart)))
  148. {
  149. $sCode = $aDefs['highlight']['code'];
  150. }
  151. }
  152. }
  153. return $sCode;
  154. }
  155. public function GetAsHTML($oAttDef, $oHostObject = null)
  156. {
  157. $aProperties = array();
  158. $aProperties['States'] = implode(', ', $oAttDef->GetStates());
  159. if (is_null($this->iLastStart))
  160. {
  161. if (is_null($this->iStarted))
  162. {
  163. $aProperties['Elapsed'] = 'never started';
  164. }
  165. else
  166. {
  167. $aProperties['Elapsed'] = $this->iTimeSpent.' s';
  168. }
  169. }
  170. else
  171. {
  172. $aProperties['Elapsed'] = 'running <img src="../images/indicator.gif">';
  173. }
  174. $aProperties['Started'] = $oAttDef->SecondsToDate($this->iStarted);
  175. $aProperties['LastStart'] = $oAttDef->SecondsToDate($this->iLastStart);
  176. $aProperties['Stopped'] = $oAttDef->SecondsToDate($this->iStopped);
  177. foreach ($this->aThresholds as $iPercent => $aThresholdData)
  178. {
  179. $sThresholdDesc = $oAttDef->SecondsToDate($aThresholdData['deadline']);
  180. if ($aThresholdData['triggered'])
  181. {
  182. $sThresholdDesc .= " <b>TRIGGERED</b>";
  183. }
  184. if ($aThresholdData['overrun'])
  185. {
  186. $sThresholdDesc .= " Overrun:".(int) $aThresholdData['overrun']." sec.";
  187. }
  188. $aProperties[$iPercent.'%'] = $sThresholdDesc;
  189. }
  190. $sRes = "<TABLE>";
  191. $sRes .= "<TBODY>";
  192. foreach ($aProperties as $sProperty => $sValue)
  193. {
  194. $sRes .= "<TR>";
  195. $sCell = str_replace("\n", "<br>\n", $sValue);
  196. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  197. $sRes .= "</TR>";
  198. }
  199. $sRes .= "</TBODY>";
  200. $sRes .= "</TABLE>";
  201. return $sRes;
  202. }
  203. protected function ComputeGoal($oObject, $oAttDef)
  204. {
  205. $sMetricComputer = $oAttDef->Get('goal_computing');
  206. $oComputer = new $sMetricComputer();
  207. $aCallSpec = array($oComputer, 'ComputeMetric');
  208. if (!is_callable($aCallSpec))
  209. {
  210. throw new CoreException("Unknown class/verb '$sMetricComputer/ComputeMetric'");
  211. }
  212. $iRet = call_user_func($aCallSpec, $oObject);
  213. return $iRet;
  214. }
  215. protected function ComputeDeadline($oObject, $oAttDef, $iStartTime, $iDurationSec)
  216. {
  217. $sWorkingTimeComputer = $oAttDef->Get('working_time_computing');
  218. if ($sWorkingTimeComputer == '')
  219. {
  220. $sWorkingTimeComputer = class_exists('SLAComputation') ? 'SLAComputation' : 'DefaultWorkingTimeComputer';
  221. }
  222. $aCallSpec = array($sWorkingTimeComputer, '__construct');
  223. if (!is_callable($aCallSpec))
  224. {
  225. //throw new CoreException("Pas de constructeur pour $sWorkingTimeComputer!");
  226. }
  227. $oComputer = new $sWorkingTimeComputer();
  228. $aCallSpec = array($oComputer, 'GetDeadline');
  229. if (!is_callable($aCallSpec))
  230. {
  231. throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetDeadline'");
  232. }
  233. // GetDeadline($oObject, $iDuration, DateTime $oStartDate)
  234. $oStartDate = new DateTime('@'.$iStartTime); // setTimestamp not available in PHP 5.2
  235. $oDeadline = call_user_func($aCallSpec, $oObject, $iDurationSec, $oStartDate);
  236. $iRet = $oDeadline->format('U');
  237. return $iRet;
  238. }
  239. protected function ComputeDuration($oObject, $oAttDef, $iStartTime, $iEndTime)
  240. {
  241. $sWorkingTimeComputer = $oAttDef->Get('working_time_computing');
  242. if ($sWorkingTimeComputer == '')
  243. {
  244. $sWorkingTimeComputer = class_exists('SLAComputation') ? 'SLAComputation' : 'DefaultWorkingTimeComputer';
  245. }
  246. $oComputer = new $sWorkingTimeComputer();
  247. $aCallSpec = array($oComputer, 'GetOpenDuration');
  248. if (!is_callable($aCallSpec))
  249. {
  250. throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetOpenDuration'");
  251. }
  252. // GetOpenDuration($oObject, DateTime $oStartDate, DateTime $oEndDate)
  253. $oStartDate = new DateTime('@'.$iStartTime); // setTimestamp not available in PHP 5.2
  254. $oEndDate = new DateTime('@'.$iEndTime);
  255. $iRet = call_user_func($aCallSpec, $oObject, $oStartDate, $oEndDate);
  256. return $iRet;
  257. }
  258. public function Reset($oObject, $oAttDef)
  259. {
  260. $this->iTimeSpent = 0;
  261. $this->iStopped = null;
  262. $this->iStarted = null;
  263. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  264. {
  265. $aThresholdData['triggered'] = false;
  266. $aThresholdData['overrun'] = null;
  267. }
  268. if (!is_null($this->iLastStart))
  269. {
  270. // Currently running... starting again from now!
  271. $this->iStarted = time();
  272. $this->iLastStart = time();
  273. $this->ComputeDeadlines($oObject, $oAttDef);
  274. }
  275. }
  276. /**
  277. * Start or continue
  278. * It is the responsibility of the caller to compute the deadlines
  279. * (to avoid computing twice for the same result)
  280. */
  281. public function Start($oObject, $oAttDef)
  282. {
  283. if (!is_null($this->iLastStart))
  284. {
  285. // Already started
  286. return false;
  287. }
  288. if (is_null($this->iStarted))
  289. {
  290. $this->iStarted = time();
  291. }
  292. $this->iLastStart = time();
  293. $this->iStopped = null;
  294. return true;
  295. }
  296. /**
  297. * Compute or recompute the goal and threshold deadlines
  298. */
  299. public function ComputeDeadlines($oObject, $oAttDef)
  300. {
  301. if (is_null($this->iLastStart))
  302. {
  303. // Currently stopped - do nothing
  304. return false;
  305. }
  306. $iDurationGoal = $this->ComputeGoal($oObject, $oAttDef);
  307. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  308. {
  309. if (is_null($iDurationGoal))
  310. {
  311. // No limit: leave null thresholds
  312. $aThresholdData['deadline'] = null;
  313. }
  314. else
  315. {
  316. $iThresholdDuration = round($iPercent * $iDurationGoal / 100);
  317. $aThresholdData['deadline'] = $this->ComputeDeadline($oObject, $oAttDef, $this->iLastStart, $iThresholdDuration - $this->iTimeSpent);
  318. // OR $aThresholdData['deadline'] = $this->ComputeDeadline($oObject, $oAttDef, $this->iStarted, $iThresholdDuration);
  319. }
  320. if (is_null($aThresholdData['deadline']) || ($aThresholdData['deadline'] > time()))
  321. {
  322. // The threshold is in the future, reset
  323. $aThresholdData['triggered'] = false;
  324. $aThresholdData['overrun'] = null;
  325. }
  326. else
  327. {
  328. // The new threshold is in the past
  329. // Note: the overrun can be wrong, but the correct algorithm to compute
  330. // the overrun of a deadline in the past requires that the ormStopWatch keeps track of all its history!!!
  331. }
  332. }
  333. return true;
  334. }
  335. /**
  336. * Stop counting if not already done
  337. */
  338. public function Stop($oObject, $oAttDef)
  339. {
  340. if (is_null($this->iLastStart))
  341. {
  342. // Already stopped
  343. return false;
  344. }
  345. $iElapsed = $this->ComputeDuration($oObject, $oAttDef, $this->iLastStart, time());
  346. $this->iTimeSpent = $this->iTimeSpent + $iElapsed;
  347. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  348. {
  349. if (!is_null($aThresholdData['deadline']) && (time() > $aThresholdData['deadline']))
  350. {
  351. if ($aThresholdData['overrun'] > 0)
  352. {
  353. // Accumulate from last start
  354. $aThresholdData['overrun'] += $iElapsed;
  355. }
  356. else
  357. {
  358. // First stop after the deadline has been passed
  359. $iOverrun = $this->ComputeDuration($oObject, $oAttDef, $aThresholdData['deadline'], time());
  360. $aThresholdData['overrun'] = $iOverrun;
  361. }
  362. }
  363. $aThresholdData['deadline'] = null;
  364. }
  365. $this->iLastStart = null;
  366. $this->iStopped = time();
  367. return true;
  368. }
  369. }
  370. /**
  371. * CheckStopWatchThresholds
  372. * Implements the automatic actions
  373. *
  374. * @package itopORM
  375. */
  376. class CheckStopWatchThresholds implements iBackgroundProcess
  377. {
  378. public function GetPeriodicity()
  379. {
  380. return 10; // seconds
  381. }
  382. public function Process($iTimeLimit)
  383. {
  384. $aList = array();
  385. foreach (MetaModel::GetClasses() as $sClass)
  386. {
  387. foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  388. {
  389. if ($oAttDef instanceof AttributeStopWatch)
  390. {
  391. foreach ($oAttDef->ListThresholds() as $iThreshold => $aThresholdData)
  392. {
  393. $iPercent = $aThresholdData['percent']; // could be different than the index !
  394. $sNow = date('Y-m-d H:i:s');
  395. $sExpression = "SELECT $sClass WHERE {$sAttCode}_laststart AND {$sAttCode}_{$iThreshold}_triggered = 0 AND {$sAttCode}_{$iThreshold}_deadline < '$sNow'";
  396. $oFilter = DBObjectSearch::FromOQL($sExpression);
  397. $oSet = new DBObjectSet($oFilter);
  398. while ((time() < $iTimeLimit) && ($oObj = $oSet->Fetch()))
  399. {
  400. $sClass = get_class($oObj);
  401. $aList[] = $sClass.'::'.$oObj->GetKey().' '.$sAttCode.' '.$iThreshold;
  402. // Execute planned actions
  403. //
  404. foreach ($aThresholdData['actions'] as $aActionData)
  405. {
  406. $sVerb = $aActionData['verb'];
  407. $aParams = $aActionData['params'];
  408. $aValues = array();
  409. foreach($aParams as $def)
  410. {
  411. if (is_string($def))
  412. {
  413. // Old method (pre-2.0.4) non typed parameters
  414. $aValues[] = $def;
  415. }
  416. else // if(is_array($def))
  417. {
  418. $sParamType = array_key_exists('type', $def) ? $def['type'] : 'string';
  419. switch($sParamType)
  420. {
  421. case 'int':
  422. $value = (int)$def['value'];
  423. break;
  424. case 'float':
  425. $value = (float)$def['value'];
  426. break;
  427. case 'bool':
  428. $value = (bool)$def['value'];
  429. break;
  430. case 'reference':
  431. $value = ${$def['value']};
  432. break;
  433. case 'string':
  434. default:
  435. $value = (string)$def['value'];
  436. }
  437. $aValues[] = $value;
  438. }
  439. }
  440. $aCallSpec = array($oObj, $sVerb);
  441. call_user_func_array($aCallSpec, $aValues);
  442. }
  443. // Mark the threshold as "triggered"
  444. //
  445. $oSW = $oObj->Get($sAttCode);
  446. $oSW->MarkThresholdAsTriggered($iThreshold);
  447. $oObj->Set($sAttCode, $oSW);
  448. if($oObj->IsModified())
  449. {
  450. CMDBObject::SetTrackInfo("Automatic - threshold triggered");
  451. $oMyChange = CMDBObject::GetCurrentChange();
  452. $oObj->DBUpdateTracked($oMyChange, true /*skip security*/);
  453. }
  454. // Activate any existing trigger
  455. //
  456. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  457. $oTriggerSet = new DBObjectSet(
  458. DBObjectSearch::FromOQL("SELECT TriggerOnThresholdReached AS t WHERE t.target_class IN ('$sClassList') AND stop_watch_code=:stop_watch_code AND threshold_index = :threshold_index"),
  459. array(), // order by
  460. array('stop_watch_code' => $sAttCode, 'threshold_index' => $iThreshold)
  461. );
  462. while ($oTrigger = $oTriggerSet->Fetch())
  463. {
  464. $oTrigger->DoActivate($oObj->ToArgs('this'));
  465. }
  466. }
  467. }
  468. }
  469. }
  470. }
  471. $iProcessed = count($aList);
  472. return "Triggered $iProcessed threshold(s):".implode(", ", $aList);
  473. }
  474. }