ormstopwatch.class.inc.php 12 KB

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