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 = 0)
  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. if ($aThresholdData['overrun'])
  181. {
  182. $sThresholdDesc .= " <b>TRIGGERED</b>, Overrun:".(int) $aThresholdData['overrun']." seconds";
  183. }
  184. else
  185. {
  186. // Still active, overrun unknown
  187. $sThresholdDesc .= " <b>TRIGGERED</b>";
  188. }
  189. }
  190. $aProperties[$iPercent.'%'] = $sThresholdDesc;
  191. }
  192. $sRes = "<TABLE class=\"listResults\">";
  193. $sRes .= "<TBODY>";
  194. foreach ($aProperties as $sProperty => $sValue)
  195. {
  196. $sRes .= "<TR>";
  197. $sCell = str_replace("\n", "<br>\n", $sValue);
  198. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  199. $sRes .= "</TR>";
  200. }
  201. $sRes .= "</TBODY>";
  202. $sRes .= "</TABLE>";
  203. return $sRes;
  204. }
  205. protected function ComputeGoal($oObject, $oAttDef)
  206. {
  207. $sMetricComputer = $oAttDef->Get('goal_computing');
  208. $oComputer = new $sMetricComputer();
  209. $aCallSpec = array($oComputer, 'ComputeMetric');
  210. if (!is_callable($aCallSpec))
  211. {
  212. throw new CoreException("Unknown class/verb '$sMetricComputer/ComputeMetric'");
  213. }
  214. $iRet = call_user_func($aCallSpec, $oObject);
  215. return $iRet;
  216. }
  217. protected function ComputeDeadline($oObject, $oAttDef, $iStartTime, $iDurationSec)
  218. {
  219. $sWorkingTimeComputer = $oAttDef->Get('working_time_computing');
  220. $aCallSpec = array($sWorkingTimeComputer, '__construct');
  221. if (!is_callable($aCallSpec))
  222. {
  223. //throw new CoreException("Pas de constructeur pour $sWorkingTimeComputer!");
  224. }
  225. $oComputer = new $sWorkingTimeComputer();
  226. $aCallSpec = array($oComputer, 'GetDeadline');
  227. if (!is_callable($aCallSpec))
  228. {
  229. throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetDeadline'");
  230. }
  231. // GetDeadline($oObject, $iDuration, DateTime $oStartDate)
  232. $oStartDate = new DateTime('@'.$iStartTime); // setTimestamp not available in PHP 5.2
  233. $oDeadline = call_user_func($aCallSpec, $oObject, $iDurationSec, $oStartDate);
  234. $iRet = $oDeadline->format('U');
  235. return $iRet;
  236. }
  237. protected function ComputeDuration($oObject, $oAttDef, $iStartTime, $iEndTime)
  238. {
  239. $sWorkingTimeComputer = $oAttDef->Get('working_time_computing');
  240. $oComputer = new $sWorkingTimeComputer();
  241. $aCallSpec = array($oComputer, 'GetOpenDuration');
  242. if (!is_callable($aCallSpec))
  243. {
  244. throw new CoreException("Unknown class/verb '$sWorkingTimeComputer/GetOpenDuration'");
  245. }
  246. // GetOpenDuration($oObject, DateTime $oStartDate, DateTime $oEndDate)
  247. $oStartDate = new DateTime('@'.$iStartTime); // setTimestamp not available in PHP 5.2
  248. $oEndDate = new DateTime('@'.$iEndTime);
  249. $iRet = call_user_func($aCallSpec, $oObject, $oStartDate, $oEndDate);
  250. return $iRet;
  251. }
  252. public function Reset($oObject, $oAttDef)
  253. {
  254. $this->iTimeSpent = 0;
  255. $this->iStarted = null;
  256. $this->iLastStart = null;
  257. $this->iStopped = null;
  258. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  259. {
  260. $aThresholdData['passed'] = false;
  261. $aThresholdData['triggered'] = false;
  262. $aThresholdData['deadline'] = null;
  263. $aThresholdData['overrun'] = null;
  264. }
  265. }
  266. /**
  267. * Start or continue
  268. * It is the responsibility of the caller to compute the deadlines
  269. * (to avoid computing twice for the same result)
  270. */
  271. public function Start($oObject, $oAttDef)
  272. {
  273. if (!is_null($this->iLastStart))
  274. {
  275. // Already started
  276. return false;
  277. }
  278. if (is_null($this->iStarted))
  279. {
  280. $this->iStarted = time();
  281. }
  282. $this->iLastStart = time();
  283. $this->iStopped = null;
  284. return true;
  285. }
  286. /**
  287. * Compute or recompute the goal and threshold deadlines
  288. */
  289. public function ComputeDeadlines($oObject, $oAttDef)
  290. {
  291. if (is_null($this->iLastStart))
  292. {
  293. // Currently stopped - do nothing
  294. return false;
  295. }
  296. $iDurationGoal = $this->ComputeGoal($oObject, $oAttDef);
  297. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  298. {
  299. if (is_null($iDurationGoal))
  300. {
  301. // No limit: leave null thresholds
  302. $aThresholdData['deadline'] = null;
  303. }
  304. else
  305. {
  306. $iThresholdDuration = round($iPercent * $iDurationGoal / 100);
  307. $aThresholdData['deadline'] = $this->ComputeDeadline($oObject, $oAttDef, $this->iLastStart, $iThresholdDuration - $this->iTimeSpent);
  308. // OR $aThresholdData['deadline'] = $this->ComputeDeadline($oObject, $oAttDef, $this->iStarted, $iThresholdDuration);
  309. }
  310. if (is_null($aThresholdData['deadline']) || ($aThresholdData['deadline'] > time()))
  311. {
  312. // The threshold is in the future, reset
  313. $aThresholdData['passed'] = false;
  314. $aThresholdData['triggered'] = false;
  315. }
  316. else
  317. {
  318. // The new threshold is in the past
  319. $aThresholdData['passed'] = true;
  320. }
  321. }
  322. return true;
  323. }
  324. /**
  325. * Stop counting if not already done
  326. */
  327. public function Stop($oObject, $oAttDef)
  328. {
  329. if (is_null($this->iLastStart))
  330. {
  331. // Already stopped
  332. return false;
  333. }
  334. $iElapsed = $this->ComputeDuration($oObject, $oAttDef, $this->iLastStart, time());
  335. $this->iTimeSpent = $this->iTimeSpent + $iElapsed;
  336. foreach ($this->aThresholds as $iPercent => &$aThresholdData)
  337. {
  338. if (!is_null($aThresholdData['deadline']) && (time() > $aThresholdData['deadline']))
  339. {
  340. $aThresholdData['passed'] = true;
  341. if ($aThresholdData['overrun'] > 0)
  342. {
  343. // Accumulate from last start
  344. $aThresholdData['overrun'] += $iElapsed;
  345. }
  346. else
  347. {
  348. // First stop after the deadline has been passed
  349. $iOverrun = $this->ComputeDuration($oObject, $oAttDef, $aThresholdData['deadline'], time());
  350. $aThresholdData['overrun'] = $iOverrun;
  351. }
  352. }
  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. ?>