ormstopwatch.class.inc.php 13 KB

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