ormstopwatch.class.inc.php 13 KB

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