ormstopwatch.class.inc.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. if (isset($aThresholdData['overrun']) && ($aThresholdData['overrun'] > 0))
  119. {
  120. $bRet = true;
  121. }
  122. }
  123. return $bRet;
  124. }
  125. public function IsThresholdTriggered($iPercent)
  126. {
  127. if (array_key_exists($iPercent, $this->aThresholds))
  128. {
  129. return $this->aThresholds[$iPercent]['triggered'];
  130. }
  131. else
  132. {
  133. return false;
  134. }
  135. }
  136. public function GetHighlightCode()
  137. {
  138. $sCode = '';
  139. // Process the thresholds in ascending order
  140. $aPercents = array();
  141. foreach($this->aThresholds as $iPercent => $aDefs)
  142. {
  143. $aPercents[] = $iPercent;
  144. }
  145. sort($aPercents, SORT_NUMERIC);
  146. foreach($aPercents as $iPercent)
  147. {
  148. $aDefs = $this->aThresholds[$iPercent];
  149. if (array_key_exists('highlight', $aDefs) && is_array($aDefs['highlight']) && $this->IsThresholdPassed($iPercent))
  150. {
  151. // If persistant or SW running...
  152. if (($aDefs['highlight']['persistent'] == true) || (($aDefs['highlight']['persistent'] == false) && !is_null($this->iLastStart)))
  153. {
  154. $sCode = $aDefs['highlight']['code'];
  155. }
  156. }
  157. }
  158. return $sCode;
  159. }
  160. public function GetAsHTML($oAttDef, $oHostObject = null)
  161. {
  162. $aProperties = array();
  163. $aProperties['States'] = implode(', ', $oAttDef->GetStates());
  164. if (is_null($this->iLastStart))
  165. {
  166. if (is_null($this->iStarted))
  167. {
  168. $aProperties['Elapsed'] = 'never started';
  169. }
  170. else
  171. {
  172. $aProperties['Elapsed'] = $this->iTimeSpent.' s';
  173. }
  174. }
  175. else
  176. {
  177. $aProperties['Elapsed'] = 'running <img src="../images/indicator.gif">';
  178. }
  179. $aProperties['Started'] = $oAttDef->SecondsToDate($this->iStarted);
  180. $aProperties['LastStart'] = $oAttDef->SecondsToDate($this->iLastStart);
  181. $aProperties['Stopped'] = $oAttDef->SecondsToDate($this->iStopped);
  182. foreach ($this->aThresholds as $iPercent => $aThresholdData)
  183. {
  184. $sThresholdDesc = $oAttDef->SecondsToDate($aThresholdData['deadline']);
  185. if ($aThresholdData['triggered'])
  186. {
  187. $sThresholdDesc .= " <b>TRIGGERED</b>";
  188. }
  189. if ($aThresholdData['overrun'])
  190. {
  191. $sThresholdDesc .= " Overrun:".(int) $aThresholdData['overrun']." sec.";
  192. }
  193. $aProperties[$iPercent.'%'] = $sThresholdDesc;
  194. }
  195. $sRes = "<TABLE>";
  196. $sRes .= "<TBODY>";
  197. foreach ($aProperties as $sProperty => $sValue)
  198. {
  199. $sRes .= "<TR>";
  200. $sCell = str_replace("\n", "<br>\n", $sValue);
  201. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  202. $sRes .= "</TR>";
  203. }
  204. $sRes .= "</TBODY>";
  205. $sRes .= "</TABLE>";
  206. return $sRes;
  207. }
  208. protected function ComputeGoal($oObject, $oAttDef)
  209. {
  210. $sMetricComputer = $oAttDef->Get('goal_computing');
  211. $oComputer = new $sMetricComputer();
  212. $aCallSpec = array($oComputer, 'ComputeMetric');
  213. if (!is_callable($aCallSpec))
  214. {
  215. throw new CoreException("Unknown class/verb '$sMetricComputer/ComputeMetric'");
  216. }
  217. $iRet = call_user_func($aCallSpec, $oObject);
  218. return $iRet;
  219. }
  220. protected function ComputeDeadline($oObject, $oAttDef, $iStartTime, $iDurationSec)
  221. {
  222. $sWorkingTimeComputer = $oAttDef->Get('working_time_computing');
  223. if ($sWorkingTimeComputer == '')
  224. {
  225. $sWorkingTimeComputer = class_exists('SLAComputation') ? 'SLAComputation' : 'DefaultWorkingTimeComputer';
  226. }
  227. $aCallSpec = array($sWorkingTimeComputer, '__construct');
  228. if (!is_callable($aCallSpec))
  229. {
  230. //throw new CoreException("Pas de constructeur pour $sWorkingTimeComputer!");
  231. }
  232. $oComputer = new $sWorkingTimeComputer();
  233. $aCallSpec = array($oComputer, 'GetDeadline');
  234. if (!is_callable($aCallSpec))
  235. {
  236. throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetDeadline'");
  237. }
  238. // GetDeadline($oObject, $iDuration, DateTime $oStartDate)
  239. $oStartDate = new DateTime('@'.$iStartTime); // setTimestamp not available in PHP 5.2
  240. $oDeadline = call_user_func($aCallSpec, $oObject, $iDurationSec, $oStartDate);
  241. $iRet = $oDeadline->format('U');
  242. return $iRet;
  243. }
  244. protected function ComputeDuration($oObject, $oAttDef, $iStartTime, $iEndTime)
  245. {
  246. $sWorkingTimeComputer = $oAttDef->Get('working_time_computing');
  247. if ($sWorkingTimeComputer == '')
  248. {
  249. $sWorkingTimeComputer = class_exists('SLAComputation') ? 'SLAComputation' : 'DefaultWorkingTimeComputer';
  250. }
  251. $oComputer = new $sWorkingTimeComputer();
  252. $aCallSpec = array($oComputer, 'GetOpenDuration');
  253. if (!is_callable($aCallSpec))
  254. {
  255. throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetOpenDuration'");
  256. }
  257. // GetOpenDuration($oObject, DateTime $oStartDate, DateTime $oEndDate)
  258. $oStartDate = new DateTime('@'.$iStartTime); // setTimestamp not available in PHP 5.2
  259. $oEndDate = new DateTime('@'.$iEndTime);
  260. $iRet = call_user_func($aCallSpec, $oObject, $oStartDate, $oEndDate);
  261. return $iRet;
  262. }
  263. public function Reset($oObject, $oAttDef)
  264. {
  265. $this->iTimeSpent = 0;
  266. $this->iStopped = null;
  267. $this->iStarted = null;
  268. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  269. {
  270. $aThresholdData['triggered'] = false;
  271. $aThresholdData['overrun'] = null;
  272. }
  273. if (!is_null($this->iLastStart))
  274. {
  275. // Currently running... starting again from now!
  276. $this->iStarted = time();
  277. $this->iLastStart = time();
  278. $this->ComputeDeadlines($oObject, $oAttDef);
  279. }
  280. }
  281. /**
  282. * Start or continue
  283. * It is the responsibility of the caller to compute the deadlines
  284. * (to avoid computing twice for the same result)
  285. */
  286. public function Start($oObject, $oAttDef)
  287. {
  288. if (!is_null($this->iLastStart))
  289. {
  290. // Already started
  291. return false;
  292. }
  293. if (is_null($this->iStarted))
  294. {
  295. $this->iStarted = time();
  296. }
  297. $this->iLastStart = time();
  298. $this->iStopped = null;
  299. return true;
  300. }
  301. /**
  302. * Compute or recompute the goal and threshold deadlines
  303. */
  304. public function ComputeDeadlines($oObject, $oAttDef)
  305. {
  306. if (is_null($this->iLastStart))
  307. {
  308. // Currently stopped - do nothing
  309. return false;
  310. }
  311. $iDurationGoal = $this->ComputeGoal($oObject, $oAttDef);
  312. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  313. {
  314. if (is_null($iDurationGoal))
  315. {
  316. // No limit: leave null thresholds
  317. $aThresholdData['deadline'] = null;
  318. }
  319. else
  320. {
  321. $iThresholdDuration = round($iPercent * $iDurationGoal / 100);
  322. $aThresholdData['deadline'] = $this->ComputeDeadline($oObject, $oAttDef, $this->iLastStart, $iThresholdDuration - $this->iTimeSpent);
  323. // OR $aThresholdData['deadline'] = $this->ComputeDeadline($oObject, $oAttDef, $this->iStarted, $iThresholdDuration);
  324. }
  325. if (is_null($aThresholdData['deadline']) || ($aThresholdData['deadline'] > time()))
  326. {
  327. // The threshold is in the future, reset
  328. $aThresholdData['triggered'] = false;
  329. $aThresholdData['overrun'] = null;
  330. }
  331. else
  332. {
  333. // The new threshold is in the past
  334. // Note: the overrun can be wrong, but the correct algorithm to compute
  335. // the overrun of a deadline in the past requires that the ormStopWatch keeps track of all its history!!!
  336. }
  337. }
  338. return true;
  339. }
  340. /**
  341. * Stop counting if not already done
  342. */
  343. public function Stop($oObject, $oAttDef)
  344. {
  345. if (is_null($this->iLastStart))
  346. {
  347. // Already stopped
  348. return false;
  349. }
  350. $iElapsed = $this->ComputeDuration($oObject, $oAttDef, $this->iLastStart, time());
  351. $this->iTimeSpent = $this->iTimeSpent + $iElapsed;
  352. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  353. {
  354. if (!is_null($aThresholdData['deadline']) && (time() > $aThresholdData['deadline']))
  355. {
  356. if ($aThresholdData['overrun'] > 0)
  357. {
  358. // Accumulate from last start
  359. $aThresholdData['overrun'] += $iElapsed;
  360. }
  361. else
  362. {
  363. // First stop after the deadline has been passed
  364. $iOverrun = $this->ComputeDuration($oObject, $oAttDef, $aThresholdData['deadline'], time());
  365. $aThresholdData['overrun'] = $iOverrun;
  366. }
  367. }
  368. $aThresholdData['deadline'] = null;
  369. }
  370. $this->iLastStart = null;
  371. $this->iStopped = time();
  372. return true;
  373. }
  374. }
  375. /**
  376. * CheckStopWatchThresholds
  377. * Implements the automatic actions
  378. *
  379. * @package itopORM
  380. */
  381. class CheckStopWatchThresholds implements iBackgroundProcess
  382. {
  383. public function GetPeriodicity()
  384. {
  385. return 10; // seconds
  386. }
  387. public function Process($iTimeLimit)
  388. {
  389. $aList = array();
  390. foreach (MetaModel::GetClasses() as $sClass)
  391. {
  392. foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  393. {
  394. if ($oAttDef instanceof AttributeStopWatch)
  395. {
  396. foreach ($oAttDef->ListThresholds() as $iThreshold => $aThresholdData)
  397. {
  398. $iPercent = $aThresholdData['percent']; // could be different than the index !
  399. $sNow = date('Y-m-d H:i:s');
  400. $sExpression = "SELECT $sClass WHERE {$sAttCode}_laststart AND {$sAttCode}_{$iThreshold}_triggered = 0 AND {$sAttCode}_{$iThreshold}_deadline < '$sNow'";
  401. $oFilter = DBObjectSearch::FromOQL($sExpression);
  402. $oSet = new DBObjectSet($oFilter);
  403. while ((time() < $iTimeLimit) && ($oObj = $oSet->Fetch()))
  404. {
  405. $sClass = get_class($oObj);
  406. $aList[] = $sClass.'::'.$oObj->GetKey().' '.$sAttCode.' '.$iThreshold;
  407. // Execute planned actions
  408. //
  409. foreach ($aThresholdData['actions'] as $aActionData)
  410. {
  411. $sVerb = $aActionData['verb'];
  412. $aParams = $aActionData['params'];
  413. $aValues = array();
  414. foreach($aParams as $def)
  415. {
  416. if (is_string($def))
  417. {
  418. // Old method (pre-2.0.4) non typed parameters
  419. $aValues[] = $def;
  420. }
  421. else // if(is_array($def))
  422. {
  423. $sParamType = array_key_exists('type', $def) ? $def['type'] : 'string';
  424. switch($sParamType)
  425. {
  426. case 'int':
  427. $value = (int)$def['value'];
  428. break;
  429. case 'float':
  430. $value = (float)$def['value'];
  431. break;
  432. case 'bool':
  433. $value = (bool)$def['value'];
  434. break;
  435. case 'reference':
  436. $value = ${$def['value']};
  437. break;
  438. case 'string':
  439. default:
  440. $value = (string)$def['value'];
  441. }
  442. $aValues[] = $value;
  443. }
  444. }
  445. $aCallSpec = array($oObj, $sVerb);
  446. call_user_func_array($aCallSpec, $aValues);
  447. }
  448. // Mark the threshold as "triggered"
  449. //
  450. $oSW = $oObj->Get($sAttCode);
  451. $oSW->MarkThresholdAsTriggered($iThreshold);
  452. $oObj->Set($sAttCode, $oSW);
  453. if($oObj->IsModified())
  454. {
  455. CMDBObject::SetTrackInfo("Automatic - threshold triggered");
  456. $oMyChange = CMDBObject::GetCurrentChange();
  457. $oObj->DBUpdateTracked($oMyChange, true /*skip security*/);
  458. }
  459. // Activate any existing trigger
  460. //
  461. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  462. $oTriggerSet = new DBObjectSet(
  463. DBObjectSearch::FromOQL("SELECT TriggerOnThresholdReached AS t WHERE t.target_class IN ('$sClassList') AND stop_watch_code=:stop_watch_code AND threshold_index = :threshold_index"),
  464. array(), // order by
  465. array('stop_watch_code' => $sAttCode, 'threshold_index' => $iThreshold)
  466. );
  467. while ($oTrigger = $oTriggerSet->Fetch())
  468. {
  469. $oTrigger->DoActivate($oObj->ToArgs('this'));
  470. }
  471. }
  472. }
  473. }
  474. }
  475. }
  476. $iProcessed = count($aList);
  477. return "Triggered $iProcessed threshold(s):".implode(", ", $aList);
  478. }
  479. }