ormstopwatch.class.inc.php 16 KB

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