ormstopwatch.class.inc.php 16 KB

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