ormstopwatch.class.inc.php 15 KB

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