ormstopwatch.class.inc.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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->iStarted = null;
  238. $this->iLastStart = null;
  239. $this->iStopped = null;
  240. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  241. {
  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['triggered'] = false;
  295. $aThresholdData['overrun'] = null;
  296. }
  297. else
  298. {
  299. // The new threshold is in the past
  300. // Note: the overrun can be wrong, but the correct algorithm to compute
  301. // the overrun of a deadline in the past requires that the ormStopWatch keeps track of all its history!!!
  302. }
  303. }
  304. return true;
  305. }
  306. /**
  307. * Stop counting if not already done
  308. */
  309. public function Stop($oObject, $oAttDef)
  310. {
  311. if (is_null($this->iLastStart))
  312. {
  313. // Already stopped
  314. return false;
  315. }
  316. $iElapsed = $this->ComputeDuration($oObject, $oAttDef, $this->iLastStart, time());
  317. $this->iTimeSpent = $this->iTimeSpent + $iElapsed;
  318. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  319. {
  320. if (!is_null($aThresholdData['deadline']) && (time() > $aThresholdData['deadline']))
  321. {
  322. if ($aThresholdData['overrun'] > 0)
  323. {
  324. // Accumulate from last start
  325. $aThresholdData['overrun'] += $iElapsed;
  326. }
  327. else
  328. {
  329. // First stop after the deadline has been passed
  330. $iOverrun = $this->ComputeDuration($oObject, $oAttDef, $aThresholdData['deadline'], time());
  331. $aThresholdData['overrun'] = $iOverrun;
  332. }
  333. }
  334. $aThresholdData['deadline'] = null;
  335. }
  336. $this->iLastStart = null;
  337. $this->iStopped = time();
  338. return true;
  339. }
  340. }
  341. /**
  342. * CheckStopWatchThresholds
  343. * Implements the automatic actions
  344. *
  345. * @package itopORM
  346. */
  347. class CheckStopWatchThresholds implements iBackgroundProcess
  348. {
  349. public function GetPeriodicity()
  350. {
  351. return 10; // seconds
  352. }
  353. public function Process($iTimeLimit)
  354. {
  355. $aList = array();
  356. foreach (MetaModel::GetClasses() as $sClass)
  357. {
  358. foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  359. {
  360. if ($oAttDef instanceof AttributeStopWatch)
  361. {
  362. foreach ($oAttDef->ListThresholds() as $iThreshold => $aThresholdData)
  363. {
  364. $iPercent = $aThresholdData['percent']; // could be different than the index !
  365. $sNow = date('Y-m-d H:i:s');
  366. $sExpression = "SELECT $sClass WHERE {$sAttCode}_laststart AND {$sAttCode}_{$iThreshold}_triggered = 0 AND {$sAttCode}_{$iThreshold}_deadline < '$sNow'";
  367. $oFilter = DBObjectSearch::FromOQL($sExpression);
  368. $oSet = new DBObjectSet($oFilter);
  369. while ((time() < $iTimeLimit) && ($oObj = $oSet->Fetch()))
  370. {
  371. $sClass = get_class($oObj);
  372. $aList[] = $sClass.'::'.$oObj->GetKey().' '.$sAttCode.' '.$iThreshold;
  373. // Execute planned actions
  374. //
  375. foreach ($aThresholdData['actions'] as $aActionData)
  376. {
  377. $sVerb = $aActionData['verb'];
  378. $aParams = $aActionData['params'];
  379. $sParams = implode(', ', $aParams);
  380. $aCallSpec = array($oObj, $sVerb);
  381. call_user_func_array($aCallSpec, $aParams);
  382. }
  383. // Mark the threshold as "triggered"
  384. //
  385. $oSW = $oObj->Get($sAttCode);
  386. $oSW->MarkThresholdAsTriggered($iThreshold);
  387. $oObj->Set($sAttCode, $oSW);
  388. if($oObj->IsModified())
  389. {
  390. CMDBObject::SetTrackInfo("Automatic - threshold triggered");
  391. $oMyChange = CMDBObject::GetCurrentChange();
  392. $oObj->DBUpdateTracked($oMyChange, true /*skip security*/);
  393. }
  394. // Activate any existing trigger
  395. //
  396. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  397. $oTriggerSet = new DBObjectSet(
  398. DBObjectSearch::FromOQL("SELECT TriggerOnThresholdReached AS t WHERE t.target_class IN ('$sClassList') AND stop_watch_code=:stop_watch_code AND threshold_index = :threshold_index"),
  399. array(), // order by
  400. array('stop_watch_code' => $sAttCode, 'threshold_index' => $iThreshold)
  401. );
  402. while ($oTrigger = $oTriggerSet->Fetch())
  403. {
  404. $oTrigger->DoActivate($oObj->ToArgs('this'));
  405. }
  406. }
  407. }
  408. }
  409. }
  410. }
  411. $iProcessed = count($aList);
  412. return "Triggered $iProcessed threshold(s):".implode(", ", $aList);
  413. }
  414. }