cron.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. <?php
  2. // Copyright (C) 2010-2013 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Heart beat of the application (process asynchron tasks such as broadcasting email)
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. if (!defined('__DIR__')) define('__DIR__', dirname(__FILE__));
  25. require_once(__DIR__.'/../approot.inc.php');
  26. require_once(APPROOT.'/application/application.inc.php');
  27. require_once(APPROOT.'/application/nicewebpage.class.inc.php');
  28. require_once(APPROOT.'/application/webpage.class.inc.php');
  29. require_once(APPROOT.'/application/clipage.class.inc.php');
  30. require_once(APPROOT.'/application/startup.inc.php');
  31. function ReadMandatoryParam($oP, $sParam, $sSanitizationFilter = 'parameter')
  32. {
  33. $sValue = utils::ReadParam($sParam, null, true /* Allow CLI */, $sSanitizationFilter);
  34. if (is_null($sValue))
  35. {
  36. $oP->p("ERROR: Missing argument '$sParam'\n");
  37. UsageAndExit($oP);
  38. }
  39. return trim($sValue);
  40. }
  41. function UsageAndExit($oP)
  42. {
  43. $bModeCLI = utils::IsModeCLI();
  44. if ($bModeCLI)
  45. {
  46. $oP->p("USAGE:\n");
  47. $oP->p("php cron.php --auth_user=<login> --auth_pwd=<password> [--param_file=<file>] [--verbose=1] [--status_only=1]\n");
  48. }
  49. else
  50. {
  51. $oP->p("Optional parameters: verbose, param_file, status_only\n");
  52. }
  53. $oP->output();
  54. exit -2;
  55. }
  56. function RunTask($oBackgroundProcess, BackgroundTask $oTask, $oStartDate, $iTimeLimit)
  57. {
  58. $oNow = new DateTime();
  59. $fStart = microtime(true);
  60. $sMessage = $oBackgroundProcess->Process($iTimeLimit);
  61. $fDuration = microtime(true) - $fStart;
  62. $oTask->ComputeDurations($fDuration);
  63. $oTask->Set('latest_run_date', $oNow->format('Y-m-d H:i:s'));
  64. $oPlannedStart = new DateTime($oTask->Get('latest_run_date'));
  65. // Let's assume that the task was started exactly when planned so that the schedule does no shift each time
  66. // this allows to schedule a task everyday "around" 11:30PM for example
  67. $oPlannedStart->modify('+'.$oBackgroundProcess->GetPeriodicity().' seconds');
  68. $oEnd = new DateTime();
  69. if ($oPlannedStart->format('U') < $oEnd->format('U'))
  70. {
  71. // Huh, next planned start is already in the past, shift it of the periodicity !
  72. $oPlannedStart = $oEnd->modify('+'.$oBackgroundProcess->GetPeriodicity().' seconds');
  73. }
  74. $oTask->Set('next_run_date', $oPlannedStart->format('Y-m-d H:i:s'));
  75. $oTask->DBUpdate();
  76. return $sMessage;
  77. }
  78. // Known limitation - the background process periodicity is NOT taken into account
  79. function CronExec($oP, $aBackgroundProcesses, $bVerbose)
  80. {
  81. $iStarted = time();
  82. $iMaxDuration = MetaModel::GetConfig()->Get('cron_max_execution_time');
  83. $iTimeLimit = $iStarted + $iMaxDuration;
  84. if ($bVerbose)
  85. {
  86. $oP->p("Planned duration = $iMaxDuration seconds");
  87. }
  88. $iCronSleep = MetaModel::GetConfig()->Get('cron_sleep');
  89. $oSearch = new DBObjectSearch('BackgroundTask');
  90. while (time() < $iTimeLimit)
  91. {
  92. $oTasks = new DBObjectSet($oSearch);
  93. $aTasks = array();
  94. while($oTask = $oTasks->Fetch())
  95. {
  96. $aTasks[$oTask->Get('class_name')] = $oTask;
  97. }
  98. foreach ($aBackgroundProcesses as $oBackgroundProcess)
  99. {
  100. $sTaskClass = get_class($oBackgroundProcess);
  101. $oNow = new DateTime();
  102. if (!array_key_exists($sTaskClass, $aTasks))
  103. {
  104. // New entry, let's create a new BackgroundTask record and run the task immediately
  105. $oTask = new BackgroundTask();
  106. $oTask->Set('class_name', get_class($oBackgroundProcess));
  107. $oTask->Set('first_run_date', $oNow->format('Y-m-d H:i:s'));
  108. $oTask->Set('total_exec_count', 0);
  109. $oTask->Set('min_run_duration', 99999.999);
  110. $oTask->Set('max_run_duration', 0);
  111. $oTask->Set('average_run_duration', 0);
  112. $oTask->Set('next_run_date', $oNow->format('Y-m-d H:i:s')); // in case of crash...
  113. $oTask->DBInsert();
  114. if ($bVerbose)
  115. {
  116. $oP->p(">> === ".$oNow->format('Y-m-d H:i:s').sprintf(" Starting:%-'=40s", ' '.$sTaskClass.' (first run) '));
  117. }
  118. $sMessage = RunTask($oBackgroundProcess, $oTask, $oNow, $iTimeLimit);
  119. if ($bVerbose)
  120. {
  121. if(!empty($sMessage))
  122. {
  123. $oP->p("$sTaskClass: $sMessage");
  124. }
  125. $oEnd = new DateTime();
  126. $oP->p("<< === ".$oEnd->format('Y-m-d H:i:s').sprintf(" End of: %-'=40s", ' '.$sTaskClass.' '));
  127. }
  128. }
  129. else if( ($aTasks[$sTaskClass]->Get('status') == 'active') && ($aTasks[$sTaskClass]->Get('next_run_date') <= $oNow->format('Y-m-d H:i:s')))
  130. {
  131. $oTask = $aTasks[$sTaskClass];
  132. // Run the task and record its next run time
  133. if ($bVerbose)
  134. {
  135. $oP->p(">> === ".$oNow->format('Y-m-d H:i:s').sprintf(" Starting:%-'=40s", ' '.$sTaskClass.' '));
  136. }
  137. $sMessage = RunTask($oBackgroundProcess, $aTasks[$sTaskClass], $oNow, $iTimeLimit);
  138. if ($bVerbose)
  139. {
  140. if(!empty($sMessage))
  141. {
  142. $oP->p("$sTaskClass: $sMessage");
  143. }
  144. $oEnd = new DateTime();
  145. $oP->p("<< === ".$oEnd->format('Y-m-d H:i:s').sprintf(" End of: %-'=40s", ' '.$sTaskClass.' '));
  146. }
  147. }
  148. else
  149. {
  150. // will run later
  151. if (($aTasks[$sTaskClass]->Get('status') == 'active') && $bVerbose)
  152. {
  153. $oP->p("Skipping asynchronous task: $sTaskClass until ".$aTasks[$sTaskClass]->Get('next_run_date'));
  154. }
  155. }
  156. }
  157. if ($bVerbose)
  158. {
  159. $oP->p("Sleeping");
  160. }
  161. sleep($iCronSleep);
  162. }
  163. if ($bVerbose)
  164. {
  165. $oP->p("Reached normal execution time limit (exceeded by ".(time()-$iTimeLimit)."s)");
  166. }
  167. }
  168. function DisplayStatus($oP)
  169. {
  170. $oSearch = new DBObjectSearch('BackgroundTask');
  171. $oTasks = new DBObjectSet($oSearch);
  172. $oP->p('+---------------------------+---------+---------------------+---------------------+--------+-----------+');
  173. $oP->p('| Task Class | Status | Last Run | Next Run | Nb Run | Avg. Dur. |');
  174. $oP->p('+---------------------------+---------+---------------------+---------------------+--------+-----------+');
  175. while($oTask = $oTasks->Fetch())
  176. {
  177. $sTaskName = $oTask->Get('class_name');
  178. $sStatus = $oTask->Get('status');
  179. $sLastRunDate = $oTask->Get('latest_run_date');
  180. $sNextRunDate = $oTask->Get('next_run_date');
  181. $iNbRun = (int)$oTask->Get('total_exec_count');
  182. $sAverageRunTime = $oTask->Get('average_run_duration');
  183. $oP->p(sprintf('| %1$-25.25s | %2$-7s | %3$-19s | %4$-19s | %5$6d | %6$7s s |', $sTaskName, $sStatus, $sLastRunDate, $sNextRunDate, $iNbRun, $sAverageRunTime));
  184. }
  185. $oP->p('+---------------------------+---------+---------------------+---------------------+--------+-----------+');
  186. }
  187. ////////////////////////////////////////////////////////////////////////////////
  188. //
  189. // Main
  190. //
  191. if (utils::IsModeCLI())
  192. {
  193. $oP = new CLIPage("iTop - CRON");
  194. }
  195. else
  196. {
  197. $oP = new WebPage("iTop - CRON");
  198. }
  199. try
  200. {
  201. utils::UseParamFile();
  202. }
  203. catch(Exception $e)
  204. {
  205. $oP->p("Error: ".$e->GetMessage());
  206. $oP->output();
  207. exit -2;
  208. }
  209. if (utils::IsModeCLI())
  210. {
  211. // Next steps:
  212. // specific arguments: 'csvfile'
  213. //
  214. $sAuthUser = ReadMandatoryParam($oP, 'auth_user', 'raw_data');
  215. $sAuthPwd = ReadMandatoryParam($oP, 'auth_pwd', 'raw_data');
  216. if (UserRights::CheckCredentials($sAuthUser, $sAuthPwd))
  217. {
  218. UserRights::Login($sAuthUser); // Login & set the user's language
  219. }
  220. else
  221. {
  222. $oP->p("Access wrong credentials ('$sAuthUser')");
  223. $oP->output();
  224. exit -1;
  225. }
  226. }
  227. else
  228. {
  229. $_SESSION['login_mode'] = 'basic';
  230. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  231. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  232. }
  233. if (!UserRights::IsAdministrator())
  234. {
  235. $oP->p("Access restricted to administrators");
  236. $oP->Output();
  237. exit -1;
  238. }
  239. // Enumerate classes implementing BackgroundProcess
  240. //
  241. $aBackgroundProcesses = array();
  242. foreach(get_declared_classes() as $sPHPClass)
  243. {
  244. $oRefClass = new ReflectionClass($sPHPClass);
  245. $oExtensionInstance = null;
  246. if ($oRefClass->implementsInterface('iBackgroundProcess'))
  247. {
  248. if (is_null($oExtensionInstance))
  249. {
  250. $oExecInstance = new $sPHPClass;
  251. }
  252. $aBackgroundProcesses[$sPHPClass] = $oExecInstance;
  253. }
  254. }
  255. $bVerbose = utils::ReadParam('verbose', false, true /* Allow CLI */);
  256. if ($bVerbose)
  257. {
  258. $aDisplayProcesses = array();
  259. foreach ($aBackgroundProcesses as $oExecInstance)
  260. {
  261. $aDisplayProcesses[] = get_class($oExecInstance);
  262. }
  263. $sDisplayProcesses = implode(', ', $aDisplayProcesses);
  264. $oP->p("Background processes: ".$sDisplayProcesses);
  265. }
  266. if (utils::ReadParam('status_only', false, true /* Allow CLI */))
  267. {
  268. // Display status and exit
  269. DisplayStatus($oP);
  270. exit(0);
  271. }
  272. $sLockName = 'itop.cron.php';
  273. $oP->p("Starting: ".time().' ('.date('Y-m-d H:i:s').')');
  274. $res = CMDBSource::QueryToScalar("SELECT GET_LOCK('$sLockName', 1)");// timeout = 1 second (see also IS_FREE_LOCK)
  275. if (is_null($res))
  276. {
  277. // TODO - Log ?
  278. $oP->p("ERROR: Failed to acquire the lock '$sLockName'");
  279. }
  280. elseif ($res === '1')
  281. {
  282. // The current session holds the lock
  283. try
  284. {
  285. CronExec($oP, $aBackgroundProcesses, $bVerbose);
  286. }
  287. catch(Exception $e)
  288. {
  289. // TODO - Log ?
  290. $oP->p("ERROR:".$e->getMessage());
  291. $oP->p($e->getTraceAsString());
  292. }
  293. $res = CMDBSource::QueryToScalar("SELECT RELEASE_LOCK('$sLockName')");
  294. }
  295. else
  296. {
  297. // Lock already held by another session
  298. // Exit silently
  299. $oP->p("Already running...");
  300. }
  301. $oP->p("Exiting: ".time().' ('.date('Y-m-d H:i:s').')');
  302. $oP->Output();
  303. ?>