ormstopwatch.class.inc.php 14 KB

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