ormstopwatch.class.inc.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. $this->iStarted = null;
  239. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  240. {
  241. $aThresholdData['triggered'] = false;
  242. $aThresholdData['overrun'] = null;
  243. }
  244. if (!is_null($this->iLastStart))
  245. {
  246. // Currently running... starting again from now!
  247. $this->iStarted = time();
  248. $this->iLastStart = time();
  249. $this->ComputeDeadlines($oObject, $oAttDef);
  250. }
  251. }
  252. /**
  253. * Start or continue
  254. * It is the responsibility of the caller to compute the deadlines
  255. * (to avoid computing twice for the same result)
  256. */
  257. public function Start($oObject, $oAttDef)
  258. {
  259. if (!is_null($this->iLastStart))
  260. {
  261. // Already started
  262. return false;
  263. }
  264. if (is_null($this->iStarted))
  265. {
  266. $this->iStarted = time();
  267. }
  268. $this->iLastStart = time();
  269. $this->iStopped = null;
  270. return true;
  271. }
  272. /**
  273. * Compute or recompute the goal and threshold deadlines
  274. */
  275. public function ComputeDeadlines($oObject, $oAttDef)
  276. {
  277. if (is_null($this->iLastStart))
  278. {
  279. // Currently stopped - do nothing
  280. return false;
  281. }
  282. $iDurationGoal = $this->ComputeGoal($oObject, $oAttDef);
  283. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  284. {
  285. if (is_null($iDurationGoal))
  286. {
  287. // No limit: leave null thresholds
  288. $aThresholdData['deadline'] = null;
  289. }
  290. else
  291. {
  292. $iThresholdDuration = round($iPercent * $iDurationGoal / 100);
  293. $aThresholdData['deadline'] = $this->ComputeDeadline($oObject, $oAttDef, $this->iLastStart, $iThresholdDuration - $this->iTimeSpent);
  294. // OR $aThresholdData['deadline'] = $this->ComputeDeadline($oObject, $oAttDef, $this->iStarted, $iThresholdDuration);
  295. }
  296. if (is_null($aThresholdData['deadline']) || ($aThresholdData['deadline'] > time()))
  297. {
  298. // The threshold is in the future, reset
  299. $aThresholdData['triggered'] = false;
  300. $aThresholdData['overrun'] = null;
  301. }
  302. else
  303. {
  304. // The new threshold is in the past
  305. // Note: the overrun can be wrong, but the correct algorithm to compute
  306. // the overrun of a deadline in the past requires that the ormStopWatch keeps track of all its history!!!
  307. }
  308. }
  309. return true;
  310. }
  311. /**
  312. * Stop counting if not already done
  313. */
  314. public function Stop($oObject, $oAttDef)
  315. {
  316. if (is_null($this->iLastStart))
  317. {
  318. // Already stopped
  319. return false;
  320. }
  321. $iElapsed = $this->ComputeDuration($oObject, $oAttDef, $this->iLastStart, time());
  322. $this->iTimeSpent = $this->iTimeSpent + $iElapsed;
  323. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  324. {
  325. if (!is_null($aThresholdData['deadline']) && (time() > $aThresholdData['deadline']))
  326. {
  327. if ($aThresholdData['overrun'] > 0)
  328. {
  329. // Accumulate from last start
  330. $aThresholdData['overrun'] += $iElapsed;
  331. }
  332. else
  333. {
  334. // First stop after the deadline has been passed
  335. $iOverrun = $this->ComputeDuration($oObject, $oAttDef, $aThresholdData['deadline'], time());
  336. $aThresholdData['overrun'] = $iOverrun;
  337. }
  338. }
  339. $aThresholdData['deadline'] = null;
  340. }
  341. $this->iLastStart = null;
  342. $this->iStopped = time();
  343. return true;
  344. }
  345. }
  346. /**
  347. * CheckStopWatchThresholds
  348. * Implements the automatic actions
  349. *
  350. * @package itopORM
  351. */
  352. class CheckStopWatchThresholds implements iBackgroundProcess
  353. {
  354. public function GetPeriodicity()
  355. {
  356. return 10; // seconds
  357. }
  358. public function Process($iTimeLimit)
  359. {
  360. $aList = array();
  361. foreach (MetaModel::GetClasses() as $sClass)
  362. {
  363. foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  364. {
  365. if ($oAttDef instanceof AttributeStopWatch)
  366. {
  367. foreach ($oAttDef->ListThresholds() as $iThreshold => $aThresholdData)
  368. {
  369. $iPercent = $aThresholdData['percent']; // could be different than the index !
  370. $sNow = date('Y-m-d H:i:s');
  371. $sExpression = "SELECT $sClass WHERE {$sAttCode}_laststart AND {$sAttCode}_{$iThreshold}_triggered = 0 AND {$sAttCode}_{$iThreshold}_deadline < '$sNow'";
  372. $oFilter = DBObjectSearch::FromOQL($sExpression);
  373. $oSet = new DBObjectSet($oFilter);
  374. while ((time() < $iTimeLimit) && ($oObj = $oSet->Fetch()))
  375. {
  376. $sClass = get_class($oObj);
  377. $aList[] = $sClass.'::'.$oObj->GetKey().' '.$sAttCode.' '.$iThreshold;
  378. // Execute planned actions
  379. //
  380. foreach ($aThresholdData['actions'] as $aActionData)
  381. {
  382. $sVerb = $aActionData['verb'];
  383. $aParams = $aActionData['params'];
  384. $sParams = implode(', ', $aParams);
  385. $aCallSpec = array($oObj, $sVerb);
  386. call_user_func_array($aCallSpec, $aParams);
  387. }
  388. // Mark the threshold as "triggered"
  389. //
  390. $oSW = $oObj->Get($sAttCode);
  391. $oSW->MarkThresholdAsTriggered($iThreshold);
  392. $oObj->Set($sAttCode, $oSW);
  393. if($oObj->IsModified())
  394. {
  395. CMDBObject::SetTrackInfo("Automatic - threshold triggered");
  396. $oMyChange = CMDBObject::GetCurrentChange();
  397. $oObj->DBUpdateTracked($oMyChange, true /*skip security*/);
  398. }
  399. // Activate any existing trigger
  400. //
  401. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  402. $oTriggerSet = new DBObjectSet(
  403. DBObjectSearch::FromOQL("SELECT TriggerOnThresholdReached AS t WHERE t.target_class IN ('$sClassList') AND stop_watch_code=:stop_watch_code AND threshold_index = :threshold_index"),
  404. array(), // order by
  405. array('stop_watch_code' => $sAttCode, 'threshold_index' => $iThreshold)
  406. );
  407. while ($oTrigger = $oTriggerSet->Fetch())
  408. {
  409. $oTrigger->DoActivate($oObj->ToArgs('this'));
  410. }
  411. }
  412. }
  413. }
  414. }
  415. }
  416. $iProcessed = count($aList);
  417. return "Triggered $iProcessed threshold(s):".implode(", ", $aList);
  418. }
  419. }