ormstopwatch.class.inc.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. <?php
  2. // Copyright (C) 2010-2012 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. require_once('backgroundprocess.inc.php');
  17. /**
  18. * ormStopWatch
  19. * encapsulate the behavior of a stop watch that will be stored as an attribute of class AttributeStopWatch
  20. *
  21. * @author Erwan Taloc <erwan.taloc@combodo.com>
  22. * @author Romain Quetiez <romain.quetiez@combodo.com>
  23. * @author Denis Flaven <denis.flaven@combodo.com>
  24. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  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. // BUGGY - DOES NOT DETECT A CHANGE IN THE DEADLINE
  51. //
  52. public function HasSameContents($oStopWatch)
  53. {
  54. if ($oStopWatch->iTimeSpent != $this->iTimeSpent) return false;
  55. if ($oStopWatch->iStarted != $this->iStarted) return false;
  56. if ($oStopWatch->iLastStart != $this->iLastStart) return false;
  57. if ($oStopWatch->iStopped != $this->iStopped) return false;
  58. if ($oStopWatch->aThresholds != $this->aThresholds) return false;
  59. // Array comparison is not recursive... let's do it by myself
  60. foreach ($oStopWatch->aThresholds as $iPercent => $aThresholdData)
  61. {
  62. // Assumption: the thresholds will not change dynamically (defined at application design time)
  63. $aThisThresholdData = $this->aThresholds[$iPercent];
  64. if ($aThisThresholdData['deadline'] != $aThresholdData['deadline']) return false;
  65. if ($aThisThresholdData['passed'] != $aThresholdData['passed']) return false;
  66. if ($aThisThresholdData['triggered'] != $aThresholdData['triggered']) return false;
  67. if ($aThisThresholdData['overrun'] != $aThresholdData['overrun']) return false;
  68. }
  69. return false;
  70. return true;
  71. }
  72. /**
  73. * Necessary for the triggers
  74. */
  75. public function __toString()
  76. {
  77. return (string) $this->iTimeSpent;
  78. }
  79. public function DefineThreshold($iPercent, $tDeadline = null, $bPassed = false, $bTriggered = false, $iOverrun = null)
  80. {
  81. $this->aThresholds[$iPercent] = array(
  82. 'deadline' => $tDeadline, // unix time (seconds)
  83. 'passed' => $bPassed,
  84. 'triggered' => $bTriggered,
  85. 'overrun' => $iOverrun
  86. );
  87. }
  88. public function MarkThresholdAsTriggered($iPercent)
  89. {
  90. $this->aThresholds[$iPercent]['triggered'] = true;
  91. }
  92. public function GetTimeSpent()
  93. {
  94. return $this->iTimeSpent;
  95. }
  96. public function GetStartDate()
  97. {
  98. return $this->iStarted;
  99. }
  100. public function GetLastStartDate()
  101. {
  102. return $this->iLastStart;
  103. }
  104. public function GetStopDate()
  105. {
  106. return $this->iStopped;
  107. }
  108. public function GetThresholdDate($iPercent)
  109. {
  110. if (array_key_exists($iPercent, $this->aThresholds))
  111. {
  112. return $this->aThresholds[$iPercent]['deadline'];
  113. }
  114. else
  115. {
  116. return null;
  117. }
  118. }
  119. public function GetOverrun($iPercent)
  120. {
  121. if (array_key_exists($iPercent, $this->aThresholds))
  122. {
  123. return $this->aThresholds[$iPercent]['overrun'];
  124. }
  125. else
  126. {
  127. return null;
  128. }
  129. }
  130. public function IsThresholdPassed($iPercent)
  131. {
  132. if (array_key_exists($iPercent, $this->aThresholds))
  133. {
  134. return $this->aThresholds[$iPercent]['passed'];
  135. }
  136. else
  137. {
  138. return false;
  139. }
  140. }
  141. public function IsThresholdTriggered($iPercent)
  142. {
  143. if (array_key_exists($iPercent, $this->aThresholds))
  144. {
  145. return $this->aThresholds[$iPercent]['triggered'];
  146. }
  147. else
  148. {
  149. return false;
  150. }
  151. }
  152. public function GetAsHTML($oAttDef, $oHostObject = null)
  153. {
  154. $aProperties = array();
  155. $aProperties['States'] = implode(', ', $oAttDef->GetStates());
  156. if (is_null($this->iLastStart))
  157. {
  158. if (is_null($this->iStarted))
  159. {
  160. $aProperties['Elapsed'] = 'never started';
  161. }
  162. else
  163. {
  164. $aProperties['Elapsed'] = $this->iTimeSpent.' s';
  165. }
  166. }
  167. else
  168. {
  169. $iElapsedTemp = $this->ComputeDuration($oHostObject, $oAttDef, $this->iLastStart, time());
  170. $aProperties['Elapsed'] = $this->iTimeSpent.' + '.$iElapsedTemp.' s + <img src="../images/indicator.gif">';
  171. }
  172. $aProperties['Started'] = $oAttDef->SecondsToDate($this->iStarted);
  173. $aProperties['LastStart'] = $oAttDef->SecondsToDate($this->iLastStart);
  174. $aProperties['Stopped'] = $oAttDef->SecondsToDate($this->iStopped);
  175. foreach ($this->aThresholds as $iPercent => $aThresholdData)
  176. {
  177. $sThresholdDesc = $oAttDef->SecondsToDate($aThresholdData['deadline']);
  178. if ($aThresholdData['triggered'])
  179. {
  180. $sThresholdDesc .= " <b>TRIGGERED</b>";
  181. }
  182. if ($aThresholdData['overrun'])
  183. {
  184. $sThresholdDesc .= " Overrun:".(int) $aThresholdData['overrun']." sec.";
  185. }
  186. $aProperties[$iPercent.'%'] = $sThresholdDesc;
  187. }
  188. $sRes = "<TABLE class=\"listResults\">";
  189. $sRes .= "<TBODY>";
  190. foreach ($aProperties as $sProperty => $sValue)
  191. {
  192. $sRes .= "<TR>";
  193. $sCell = str_replace("\n", "<br>\n", $sValue);
  194. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  195. $sRes .= "</TR>";
  196. }
  197. $sRes .= "</TBODY>";
  198. $sRes .= "</TABLE>";
  199. return $sRes;
  200. }
  201. protected function ComputeGoal($oObject, $oAttDef)
  202. {
  203. $sMetricComputer = $oAttDef->Get('goal_computing');
  204. $oComputer = new $sMetricComputer();
  205. $aCallSpec = array($oComputer, 'ComputeMetric');
  206. if (!is_callable($aCallSpec))
  207. {
  208. throw new CoreException("Unknown class/verb '$sMetricComputer/ComputeMetric'");
  209. }
  210. $iRet = call_user_func($aCallSpec, $oObject);
  211. return $iRet;
  212. }
  213. protected function ComputeDeadline($oObject, $oAttDef, $iStartTime, $iDurationSec)
  214. {
  215. $sWorkingTimeComputer = $oAttDef->Get('working_time_computing');
  216. $aCallSpec = array($sWorkingTimeComputer, '__construct');
  217. if (!is_callable($aCallSpec))
  218. {
  219. //throw new CoreException("Pas de constructeur pour $sWorkingTimeComputer!");
  220. }
  221. $oComputer = new $sWorkingTimeComputer();
  222. $aCallSpec = array($oComputer, 'GetDeadline');
  223. if (!is_callable($aCallSpec))
  224. {
  225. throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetDeadline'");
  226. }
  227. // GetDeadline($oObject, $iDuration, DateTime $oStartDate)
  228. $oStartDate = new DateTime('@'.$iStartTime); // setTimestamp not available in PHP 5.2
  229. $oDeadline = call_user_func($aCallSpec, $oObject, $iDurationSec, $oStartDate);
  230. $iRet = $oDeadline->format('U');
  231. return $iRet;
  232. }
  233. protected function ComputeDuration($oObject, $oAttDef, $iStartTime, $iEndTime)
  234. {
  235. $sWorkingTimeComputer = $oAttDef->Get('working_time_computing');
  236. $oComputer = new $sWorkingTimeComputer();
  237. $aCallSpec = array($oComputer, 'GetOpenDuration');
  238. if (!is_callable($aCallSpec))
  239. {
  240. throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetOpenDuration'");
  241. }
  242. // GetOpenDuration($oObject, DateTime $oStartDate, DateTime $oEndDate)
  243. $oStartDate = new DateTime('@'.$iStartTime); // setTimestamp not available in PHP 5.2
  244. $oEndDate = new DateTime('@'.$iEndTime);
  245. $iRet = call_user_func($aCallSpec, $oObject, $oStartDate, $oEndDate);
  246. return $iRet;
  247. }
  248. public function Reset($oObject, $oAttDef)
  249. {
  250. $this->iTimeSpent = 0;
  251. $this->iStarted = null;
  252. $this->iLastStart = null;
  253. $this->iStopped = null;
  254. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  255. {
  256. $aThresholdData['passed'] = false;
  257. $aThresholdData['triggered'] = false;
  258. $aThresholdData['deadline'] = null;
  259. $aThresholdData['overrun'] = null;
  260. }
  261. }
  262. /**
  263. * Start or continue
  264. * It is the responsibility of the caller to compute the deadlines
  265. * (to avoid computing twice for the same result)
  266. */
  267. public function Start($oObject, $oAttDef)
  268. {
  269. if (!is_null($this->iLastStart))
  270. {
  271. // Already started
  272. return false;
  273. }
  274. if (is_null($this->iStarted))
  275. {
  276. $this->iStarted = time();
  277. }
  278. $this->iLastStart = time();
  279. $this->iStopped = null;
  280. return true;
  281. }
  282. /**
  283. * Compute or recompute the goal and threshold deadlines
  284. */
  285. public function ComputeDeadlines($oObject, $oAttDef)
  286. {
  287. if (is_null($this->iLastStart))
  288. {
  289. // Currently stopped - do nothing
  290. return false;
  291. }
  292. $iDurationGoal = $this->ComputeGoal($oObject, $oAttDef);
  293. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  294. {
  295. if (is_null($iDurationGoal))
  296. {
  297. // No limit: leave null thresholds
  298. $aThresholdData['deadline'] = null;
  299. }
  300. else
  301. {
  302. $iThresholdDuration = round($iPercent * $iDurationGoal / 100);
  303. $aThresholdData['deadline'] = $this->ComputeDeadline($oObject, $oAttDef, $this->iLastStart, $iThresholdDuration - $this->iTimeSpent);
  304. // OR $aThresholdData['deadline'] = $this->ComputeDeadline($oObject, $oAttDef, $this->iStarted, $iThresholdDuration);
  305. }
  306. if (is_null($aThresholdData['deadline']) || ($aThresholdData['deadline'] > time()))
  307. {
  308. // The threshold is in the future, reset
  309. $aThresholdData['passed'] = false;
  310. $aThresholdData['triggered'] = false;
  311. $aThresholdData['overrun'] = null;
  312. }
  313. else
  314. {
  315. // The new threshold is in the past
  316. $aThresholdData['passed'] = true;
  317. // Note: the overrun can be wrong, but the correct algorithm to compute
  318. // the overrun of a deadline in the past requires that the ormStopWatch keeps track of all its history!!!
  319. }
  320. }
  321. return true;
  322. }
  323. /**
  324. * Stop counting if not already done
  325. */
  326. public function Stop($oObject, $oAttDef)
  327. {
  328. if (is_null($this->iLastStart))
  329. {
  330. // Already stopped
  331. return false;
  332. }
  333. $iElapsed = $this->ComputeDuration($oObject, $oAttDef, $this->iLastStart, time());
  334. $this->iTimeSpent = $this->iTimeSpent + $iElapsed;
  335. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  336. {
  337. if (!is_null($aThresholdData['deadline']) && (time() > $aThresholdData['deadline']))
  338. {
  339. if ($aThresholdData['overrun'] > 0)
  340. {
  341. // Accumulate from last start
  342. $aThresholdData['overrun'] += $iElapsed;
  343. }
  344. else
  345. {
  346. // First stop after the deadline has been passed
  347. $iOverrun = $this->ComputeDuration($oObject, $oAttDef, $aThresholdData['deadline'], time());
  348. $aThresholdData['overrun'] = $iOverrun;
  349. }
  350. $aThresholdData['passed'] = true;
  351. }
  352. $aThresholdData['deadline'] = null;
  353. }
  354. $this->iLastStart = null;
  355. $this->iStopped = time();
  356. return true;
  357. }
  358. }
  359. /**
  360. * CheckStopWatchThresholds
  361. * Implements the automatic actions
  362. *
  363. * @package itopORM
  364. */
  365. class CheckStopWatchThresholds implements iBackgroundProcess
  366. {
  367. public function GetPeriodicity()
  368. {
  369. return 10; // seconds
  370. }
  371. public function Process($iTimeLimit)
  372. {
  373. foreach (MetaModel::GetClasses() as $sClass)
  374. {
  375. foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  376. {
  377. if ($oAttDef instanceof AttributeStopWatch)
  378. {
  379. foreach ($oAttDef->ListThresholds() as $iThreshold => $aThresholdData)
  380. {
  381. $iPercent = $aThresholdData['percent']; // could be different than the index !
  382. $sExpression = "SELECT $sClass WHERE {$sAttCode}_laststart AND {$sAttCode}_{$iThreshold}_triggered = 0 AND {$sAttCode}_{$iThreshold}_deadline < NOW()";
  383. //echo $sExpression."<br/>\n";
  384. $oFilter = DBObjectSearch::FromOQL($sExpression);
  385. $aList = array();
  386. $oSet = new DBObjectSet($oFilter);
  387. while ((time() < $iTimeLimit) && ($oObj = $oSet->Fetch()))
  388. {
  389. $sClass = get_class($oObj);
  390. $aList[] = $sClass.'::'.$oObj->GetKey().' '.$sAttCode.' '.$iThreshold;
  391. //echo $sClass.'::'.$oObj->GetKey().' '.$sAttCode.' '.$iThreshold."\n";
  392. // Execute planned actions
  393. //
  394. foreach ($aThresholdData['actions'] as $aActionData)
  395. {
  396. $sVerb = $aActionData['verb'];
  397. $aParams = $aActionData['params'];
  398. $sParams = implode(', ', $aParams);
  399. //echo "Calling: $sVerb($sParams)<br/>\n";
  400. $aCallSpec = array($oObj, $sVerb);
  401. call_user_func_array($aCallSpec, $aParams);
  402. }
  403. // Mark the threshold as "triggered"
  404. //
  405. $oSW = $oObj->Get($sAttCode);
  406. $oSW->MarkThresholdAsTriggered($iThreshold);
  407. $oObj->Set($sAttCode, $oSW);
  408. if($oObj->IsModified())
  409. {
  410. // Todo - factorize so that only one single change will be instantiated
  411. $oMyChange = new CMDBChange();
  412. $oMyChange->Set("date", time());
  413. $oMyChange->Set("userinfo", "Automatic - threshold triggered");
  414. $iChangeId = $oMyChange->DBInsertNoReload();
  415. $oObj->DBUpdateTracked($oMyChange, true /*skip security*/);
  416. }
  417. // Activate any existing trigger
  418. //
  419. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  420. $oSet = new DBObjectSet(
  421. DBObjectSearch::FromOQL("SELECT TriggerOnThresholdReached AS t WHERE t.target_class IN ('$sClassList') AND stop_watch_code=:stop_watch_code AND threshold_index = :threshold_index"),
  422. array(), // order by
  423. array('stop_watch_code' => $sAttCode, 'threshold_index' => $iThreshold)
  424. );
  425. while ($oTrigger = $oSet->Fetch())
  426. {
  427. $oTrigger->DoActivate($oObj->ToArgs('this'));
  428. }
  429. }
  430. }
  431. }
  432. }
  433. }
  434. $iProcessed = count($aList);
  435. return "Triggered $iProcessed threshold(s)";
  436. }
  437. }
  438. ?>