ormstopwatch.class.inc.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. /**
  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. $iElapsedTemp = $this->ComputeDuration($oHostObject, $oAttDef, $this->iLastStart, time());
  148. $aProperties['Elapsed'] = $this->iTimeSpent.' + '.$iElapsedTemp.' s + <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 class=\"listResults\">";
  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. $aCallSpec = array($sWorkingTimeComputer, '__construct');
  195. if (!is_callable($aCallSpec))
  196. {
  197. //throw new CoreException("Pas de constructeur pour $sWorkingTimeComputer!");
  198. }
  199. $oComputer = new $sWorkingTimeComputer();
  200. $aCallSpec = array($oComputer, 'GetDeadline');
  201. if (!is_callable($aCallSpec))
  202. {
  203. throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetDeadline'");
  204. }
  205. // GetDeadline($oObject, $iDuration, DateTime $oStartDate)
  206. $oStartDate = new DateTime('@'.$iStartTime); // setTimestamp not available in PHP 5.2
  207. $oDeadline = call_user_func($aCallSpec, $oObject, $iDurationSec, $oStartDate);
  208. $iRet = $oDeadline->format('U');
  209. return $iRet;
  210. }
  211. protected function ComputeDuration($oObject, $oAttDef, $iStartTime, $iEndTime)
  212. {
  213. $sWorkingTimeComputer = $oAttDef->Get('working_time_computing');
  214. $oComputer = new $sWorkingTimeComputer();
  215. $aCallSpec = array($oComputer, 'GetOpenDuration');
  216. if (!is_callable($aCallSpec))
  217. {
  218. throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetOpenDuration'");
  219. }
  220. // GetOpenDuration($oObject, DateTime $oStartDate, DateTime $oEndDate)
  221. $oStartDate = new DateTime('@'.$iStartTime); // setTimestamp not available in PHP 5.2
  222. $oEndDate = new DateTime('@'.$iEndTime);
  223. $iRet = call_user_func($aCallSpec, $oObject, $oStartDate, $oEndDate);
  224. return $iRet;
  225. }
  226. public function Reset($oObject, $oAttDef)
  227. {
  228. $this->iTimeSpent = 0;
  229. $this->iStarted = null;
  230. $this->iLastStart = null;
  231. $this->iStopped = null;
  232. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  233. {
  234. $aThresholdData['passed'] = false;
  235. $aThresholdData['triggered'] = false;
  236. $aThresholdData['deadline'] = null;
  237. $aThresholdData['overrun'] = null;
  238. }
  239. }
  240. /**
  241. * Start or continue
  242. * It is the responsibility of the caller to compute the deadlines
  243. * (to avoid computing twice for the same result)
  244. */
  245. public function Start($oObject, $oAttDef)
  246. {
  247. if (!is_null($this->iLastStart))
  248. {
  249. // Already started
  250. return false;
  251. }
  252. if (is_null($this->iStarted))
  253. {
  254. $this->iStarted = time();
  255. }
  256. $this->iLastStart = time();
  257. $this->iStopped = null;
  258. return true;
  259. }
  260. /**
  261. * Compute or recompute the goal and threshold deadlines
  262. */
  263. public function ComputeDeadlines($oObject, $oAttDef)
  264. {
  265. if (is_null($this->iLastStart))
  266. {
  267. // Currently stopped - do nothing
  268. return false;
  269. }
  270. $iDurationGoal = $this->ComputeGoal($oObject, $oAttDef);
  271. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  272. {
  273. if (is_null($iDurationGoal))
  274. {
  275. // No limit: leave null thresholds
  276. $aThresholdData['deadline'] = null;
  277. }
  278. else
  279. {
  280. $iThresholdDuration = round($iPercent * $iDurationGoal / 100);
  281. $aThresholdData['deadline'] = $this->ComputeDeadline($oObject, $oAttDef, $this->iLastStart, $iThresholdDuration - $this->iTimeSpent);
  282. // OR $aThresholdData['deadline'] = $this->ComputeDeadline($oObject, $oAttDef, $this->iStarted, $iThresholdDuration);
  283. }
  284. if (is_null($aThresholdData['deadline']) || ($aThresholdData['deadline'] > time()))
  285. {
  286. // The threshold is in the future, reset
  287. $aThresholdData['passed'] = false;
  288. $aThresholdData['triggered'] = false;
  289. $aThresholdData['overrun'] = null;
  290. }
  291. else
  292. {
  293. // The new threshold is in the past
  294. $aThresholdData['passed'] = true;
  295. // Note: the overrun can be wrong, but the correct algorithm to compute
  296. // the overrun of a deadline in the past requires that the ormStopWatch keeps track of all its history!!!
  297. }
  298. }
  299. return true;
  300. }
  301. /**
  302. * Stop counting if not already done
  303. */
  304. public function Stop($oObject, $oAttDef)
  305. {
  306. if (is_null($this->iLastStart))
  307. {
  308. // Already stopped
  309. return false;
  310. }
  311. $iElapsed = $this->ComputeDuration($oObject, $oAttDef, $this->iLastStart, time());
  312. $this->iTimeSpent = $this->iTimeSpent + $iElapsed;
  313. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  314. {
  315. if (!is_null($aThresholdData['deadline']) && (time() > $aThresholdData['deadline']))
  316. {
  317. if ($aThresholdData['overrun'] > 0)
  318. {
  319. // Accumulate from last start
  320. $aThresholdData['overrun'] += $iElapsed;
  321. }
  322. else
  323. {
  324. // First stop after the deadline has been passed
  325. $iOverrun = $this->ComputeDuration($oObject, $oAttDef, $aThresholdData['deadline'], time());
  326. $aThresholdData['overrun'] = $iOverrun;
  327. }
  328. $aThresholdData['passed'] = true;
  329. }
  330. $aThresholdData['deadline'] = null;
  331. }
  332. $this->iLastStart = null;
  333. $this->iStopped = time();
  334. return true;
  335. }
  336. }
  337. /**
  338. * CheckStopWatchThresholds
  339. * Implements the automatic actions
  340. *
  341. * @package itopORM
  342. */
  343. class CheckStopWatchThresholds implements iBackgroundProcess
  344. {
  345. public function GetPeriodicity()
  346. {
  347. return 10; // seconds
  348. }
  349. public function Process($iTimeLimit)
  350. {
  351. foreach (MetaModel::GetClasses() as $sClass)
  352. {
  353. foreach (MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  354. {
  355. if ($oAttDef instanceof AttributeStopWatch)
  356. {
  357. foreach ($oAttDef->ListThresholds() as $iThreshold => $aThresholdData)
  358. {
  359. $iPercent = $aThresholdData['percent']; // could be different than the index !
  360. $sExpression = "SELECT $sClass WHERE {$sAttCode}_laststart AND {$sAttCode}_{$iThreshold}_triggered = 0 AND {$sAttCode}_{$iThreshold}_deadline < NOW()";
  361. //echo $sExpression."<br/>\n";
  362. $oFilter = DBObjectSearch::FromOQL($sExpression);
  363. $aList = array();
  364. $oSet = new DBObjectSet($oFilter);
  365. while ((time() < $iTimeLimit) && ($oObj = $oSet->Fetch()))
  366. {
  367. $sClass = get_class($oObj);
  368. $aList[] = $sClass.'::'.$oObj->GetKey().' '.$sAttCode.' '.$iThreshold;
  369. //echo $sClass.'::'.$oObj->GetKey().' '.$sAttCode.' '.$iThreshold."\n";
  370. // Execute planned actions
  371. //
  372. foreach ($aThresholdData['actions'] as $aActionData)
  373. {
  374. $sVerb = $aActionData['verb'];
  375. $aParams = $aActionData['params'];
  376. $sParams = implode(', ', $aParams);
  377. //echo "Calling: $sVerb($sParams)<br/>\n";
  378. $aCallSpec = array($oObj, $sVerb);
  379. call_user_func_array($aCallSpec, $aParams);
  380. }
  381. // Mark the threshold as "triggered"
  382. //
  383. $oSW = $oObj->Get($sAttCode);
  384. $oSW->MarkThresholdAsTriggered($iThreshold);
  385. $oObj->Set($sAttCode, $oSW);
  386. if($oObj->IsModified())
  387. {
  388. // Todo - factorize so that only one single change will be instantiated
  389. $oMyChange = new CMDBChange();
  390. $oMyChange->Set("date", time());
  391. $oMyChange->Set("userinfo", "Automatic - threshold triggered");
  392. $iChangeId = $oMyChange->DBInsertNoReload();
  393. $oObj->DBUpdateTracked($oMyChange, true /*skip security*/);
  394. }
  395. // Activate any existing trigger
  396. //
  397. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  398. $oSet = new DBObjectSet(
  399. DBObjectSearch::FromOQL("SELECT TriggerOnThresholdReached AS t WHERE t.target_class IN ('$sClassList') AND stop_watch_code=:stop_watch_code AND threshold_index = :threshold_index"),
  400. array(), // order by
  401. array('stop_watch_code' => $sAttCode, 'threshold_index' => $iThreshold)
  402. );
  403. while ($oTrigger = $oSet->Fetch())
  404. {
  405. $oTrigger->DoActivate($oObj->ToArgs('this'));
  406. }
  407. }
  408. }
  409. }
  410. }
  411. }
  412. $iProcessed = count($aList);
  413. return "Triggered $iProcessed threshold(s)";
  414. }
  415. }
  416. ?>