ormstopwatch.class.inc.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. <?php
  2. // Copyright (C) 2010-2014 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, $iNow = null)
  304. {
  305. if (!is_null($this->iLastStart))
  306. {
  307. // Already started
  308. return false;
  309. }
  310. if (is_null($iNow))
  311. {
  312. $iNow = time();
  313. }
  314. if (is_null($this->iStarted))
  315. {
  316. $this->iStarted = $iNow;
  317. }
  318. $this->iLastStart = $iNow;
  319. $this->iStopped = null;
  320. return true;
  321. }
  322. /**
  323. * Compute or recompute the goal and threshold deadlines
  324. */
  325. public function ComputeDeadlines($oObject, $oAttDef)
  326. {
  327. if (is_null($this->iLastStart))
  328. {
  329. // Currently stopped - do nothing
  330. return false;
  331. }
  332. $iDurationGoal = $this->ComputeGoal($oObject, $oAttDef);
  333. $iComputationRefTime = time();
  334. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  335. {
  336. if (is_null($iDurationGoal))
  337. {
  338. // No limit: leave null thresholds
  339. $aThresholdData['deadline'] = null;
  340. }
  341. else
  342. {
  343. $iThresholdDuration = round($iPercent * $iDurationGoal / 100);
  344. if (class_exists('WorkingTimeRecorder'))
  345. {
  346. $sClass = get_class($oObject);
  347. $sAttCode = $oAttDef->GetCode();
  348. WorkingTimeRecorder::Start($oObject, $iComputationRefTime, "ormStopWatch-Deadline-$iPercent-$sAttCode", 'Core:ExplainWTC:StopWatch-Deadline', array("Class:$sClass/Attribute:$sAttCode", $iPercent));
  349. }
  350. $aThresholdData['deadline'] = $this->ComputeDeadline($oObject, $oAttDef, $this->iLastStart, $iThresholdDuration - $this->iTimeSpent);
  351. // OR $aThresholdData['deadline'] = $this->ComputeDeadline($oObject, $oAttDef, $this->iStarted, $iThresholdDuration);
  352. if (class_exists('WorkingTimeRecorder'))
  353. {
  354. WorkingTimeRecorder::End();
  355. }
  356. }
  357. if (is_null($aThresholdData['deadline']) || ($aThresholdData['deadline'] > time()))
  358. {
  359. // The threshold is in the future, reset
  360. $aThresholdData['triggered'] = false;
  361. $aThresholdData['overrun'] = null;
  362. }
  363. else
  364. {
  365. // The new threshold is in the past
  366. // Note: the overrun can be wrong, but the correct algorithm to compute
  367. // the overrun of a deadline in the past requires that the ormStopWatch keeps track of all its history!!!
  368. }
  369. }
  370. return true;
  371. }
  372. /**
  373. * Stop counting if not already done
  374. */
  375. public function Stop($oObject, $oAttDef)
  376. {
  377. if (is_null($this->iLastStart))
  378. {
  379. // Already stopped
  380. return false;
  381. }
  382. if (class_exists('WorkingTimeRecorder'))
  383. {
  384. $sClass = get_class($oObject);
  385. $sAttCode = $oAttDef->GetCode();
  386. WorkingTimeRecorder::Start($oObject, time(), "ormStopWatch-TimeSpent-$sAttCode", 'Core:ExplainWTC:StopWatch-TimeSpent', array("Class:$sClass/Attribute:$sAttCode"), true /*cumulative*/);
  387. }
  388. $iElapsed = $this->ComputeDuration($oObject, $oAttDef, $this->iLastStart, time());
  389. $this->iTimeSpent = $this->iTimeSpent + $iElapsed;
  390. if (class_exists('WorkingTimeRecorder'))
  391. {
  392. WorkingTimeRecorder::End();
  393. }
  394. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  395. {
  396. if (!is_null($aThresholdData['deadline']) && (time() > $aThresholdData['deadline']))
  397. {
  398. if ($aThresholdData['overrun'] > 0)
  399. {
  400. // Accumulate from last start
  401. $aThresholdData['overrun'] += $iElapsed;
  402. }
  403. else
  404. {
  405. // First stop after the deadline has been passed
  406. $iOverrun = $this->ComputeDuration($oObject, $oAttDef, $aThresholdData['deadline'], time());
  407. $aThresholdData['overrun'] = $iOverrun;
  408. }
  409. }
  410. $aThresholdData['deadline'] = null;
  411. }
  412. $this->iLastStart = null;
  413. $this->iStopped = time();
  414. return true;
  415. }
  416. }
  417. /**
  418. * CheckStopWatchThresholds
  419. * Implements the automatic actions
  420. *
  421. * @package itopORM
  422. */
  423. class CheckStopWatchThresholds implements iBackgroundProcess
  424. {
  425. public function GetPeriodicity()
  426. {
  427. return 10; // seconds
  428. }
  429. public function Process($iTimeLimit)
  430. {
  431. $aList = array();
  432. foreach (MetaModel::GetClasses() as $sClass)
  433. {
  434. foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  435. {
  436. if ($oAttDef instanceof AttributeStopWatch)
  437. {
  438. foreach ($oAttDef->ListThresholds() as $iThreshold => $aThresholdData)
  439. {
  440. $iPercent = $aThresholdData['percent']; // could be different than the index !
  441. $sNow = date('Y-m-d H:i:s');
  442. $sExpression = "SELECT $sClass WHERE {$sAttCode}_laststart AND {$sAttCode}_{$iThreshold}_triggered = 0 AND {$sAttCode}_{$iThreshold}_deadline < '$sNow'";
  443. $oFilter = DBObjectSearch::FromOQL($sExpression);
  444. $oSet = new DBObjectSet($oFilter);
  445. while ((time() < $iTimeLimit) && ($oObj = $oSet->Fetch()))
  446. {
  447. $sClass = get_class($oObj);
  448. $aList[] = $sClass.'::'.$oObj->GetKey().' '.$sAttCode.' '.$iThreshold;
  449. // Execute planned actions
  450. //
  451. foreach ($aThresholdData['actions'] as $aActionData)
  452. {
  453. $sVerb = $aActionData['verb'];
  454. $aParams = $aActionData['params'];
  455. $aValues = array();
  456. foreach($aParams as $def)
  457. {
  458. if (is_string($def))
  459. {
  460. // Old method (pre-2.1.0) non typed parameters
  461. $aValues[] = $def;
  462. }
  463. else // if(is_array($def))
  464. {
  465. $sParamType = array_key_exists('type', $def) ? $def['type'] : 'string';
  466. switch($sParamType)
  467. {
  468. case 'int':
  469. $value = (int)$def['value'];
  470. break;
  471. case 'float':
  472. $value = (float)$def['value'];
  473. break;
  474. case 'bool':
  475. $value = (bool)$def['value'];
  476. break;
  477. case 'reference':
  478. $value = ${$def['value']};
  479. break;
  480. case 'string':
  481. default:
  482. $value = (string)$def['value'];
  483. }
  484. $aValues[] = $value;
  485. }
  486. }
  487. $aCallSpec = array($oObj, $sVerb);
  488. call_user_func_array($aCallSpec, $aValues);
  489. }
  490. // Mark the threshold as "triggered"
  491. //
  492. $oSW = $oObj->Get($sAttCode);
  493. $oSW->MarkThresholdAsTriggered($iThreshold);
  494. $oObj->Set($sAttCode, $oSW);
  495. if($oObj->IsModified())
  496. {
  497. CMDBObject::SetTrackInfo("Automatic - threshold triggered");
  498. $oMyChange = CMDBObject::GetCurrentChange();
  499. $oObj->DBUpdateTracked($oMyChange, true /*skip security*/);
  500. }
  501. // Activate any existing trigger
  502. //
  503. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  504. $oTriggerSet = new DBObjectSet(
  505. DBObjectSearch::FromOQL("SELECT TriggerOnThresholdReached AS t WHERE t.target_class IN ('$sClassList') AND stop_watch_code=:stop_watch_code AND threshold_index = :threshold_index"),
  506. array(), // order by
  507. array('stop_watch_code' => $sAttCode, 'threshold_index' => $iThreshold)
  508. );
  509. while ($oTrigger = $oTriggerSet->Fetch())
  510. {
  511. $oTrigger->DoActivate($oObj->ToArgs('this'));
  512. }
  513. }
  514. }
  515. }
  516. }
  517. }
  518. $iProcessed = count($aList);
  519. return "Triggered $iProcessed threshold(s):".implode(", ", $aList);
  520. }
  521. }