cron.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. <?php
  2. // Copyright (C) 2010-2016 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-2016 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. $sConfigFile = APPCONF.ITOP_DEFAULT_ENV.'/'.ITOP_CONFIG_FILE;
  31. if (!file_exists($sConfigFile))
  32. {
  33. echo "iTop is not yet installed. Exiting...\n";
  34. exit(-1);
  35. }
  36. require_once(APPROOT.'/application/startup.inc.php');
  37. $oCtx = new ContextTag('CRON');
  38. function ReadMandatoryParam($oP, $sParam, $sSanitizationFilter = 'parameter')
  39. {
  40. $sValue = utils::ReadParam($sParam, null, true /* Allow CLI */, $sSanitizationFilter);
  41. if (is_null($sValue))
  42. {
  43. $oP->p("ERROR: Missing argument '$sParam'\n");
  44. UsageAndExit($oP);
  45. }
  46. return trim($sValue);
  47. }
  48. function UsageAndExit($oP)
  49. {
  50. $bModeCLI = utils::IsModeCLI();
  51. if ($bModeCLI)
  52. {
  53. $oP->p("USAGE:\n");
  54. $oP->p("php cron.php --auth_user=<login> --auth_pwd=<password> [--param_file=<file>] [--verbose=1] [--debug=1] [--status_only=1]\n");
  55. }
  56. else
  57. {
  58. $oP->p("Optional parameters: verbose, param_file, status_only\n");
  59. }
  60. $oP->output();
  61. exit -2;
  62. }
  63. function RunTask($oProcess, BackgroundTask $oTask, $oStartDate, $iTimeLimit)
  64. {
  65. $oNow = new DateTime();
  66. $fStart = microtime(true);
  67. try
  68. {
  69. $sMessage = $oProcess->Process($iTimeLimit);
  70. }
  71. catch(Exception $e)
  72. {
  73. $sMessage = 'Processing failed with message: '.$e->getMessage();
  74. }
  75. $fDuration = microtime(true) - $fStart;
  76. if ($oTask->Get('total_exec_count') == 0)
  77. {
  78. // First execution
  79. $oTask->Set('first_run_date', $oNow->format('Y-m-d H:i:s'));
  80. }
  81. $oTask->ComputeDurations($fDuration); // does increment the counter and compute statistics
  82. $oTask->Set('latest_run_date', $oNow->format('Y-m-d H:i:s'));
  83. $oRefClass = new ReflectionClass(get_class($oProcess));
  84. if ($oRefClass->implementsInterface('iScheduledProcess'))
  85. {
  86. // Schedules process do repeat at specific moments
  87. $oPlannedStart = $oProcess->GetNextOccurrence();
  88. }
  89. else
  90. {
  91. // Background processes do repeat periodically
  92. $oPlannedStart = new DateTime($oTask->Get('latest_run_date'));
  93. // Let's assume that the task was started exactly when planned so that the schedule does no shift each time
  94. // this allows to schedule a task everyday "around" 11:30PM for example
  95. $oPlannedStart->modify('+'.$oProcess->GetPeriodicity().' seconds');
  96. $oEnd = new DateTime();
  97. if ($oPlannedStart->format('U') < $oEnd->format('U'))
  98. {
  99. // Huh, next planned start is already in the past, shift it of the periodicity !
  100. $oPlannedStart = $oEnd->modify('+'.$oProcess->GetPeriodicity().' seconds');
  101. }
  102. }
  103. $oTask->Set('next_run_date', $oPlannedStart->format('Y-m-d H:i:s'));
  104. $oTask->DBUpdate();
  105. return $sMessage;
  106. }
  107. function CronExec($oP, $aProcesses, $bVerbose)
  108. {
  109. $iStarted = time();
  110. $iMaxDuration = MetaModel::GetConfig()->Get('cron_max_execution_time');
  111. $iTimeLimit = $iStarted + $iMaxDuration;
  112. if ($bVerbose)
  113. {
  114. $oP->p("Planned duration = $iMaxDuration seconds");
  115. }
  116. // Reset the next planned execution to take into account new settings
  117. $oSearch = new DBObjectSearch('BackgroundTask');
  118. $oTasks = new DBObjectSet($oSearch);
  119. while($oTask = $oTasks->Fetch())
  120. {
  121. $sTaskClass = $oTask->Get('class_name');
  122. $oRefClass = new ReflectionClass($sTaskClass);
  123. $oNow = new DateTime();
  124. if($oRefClass->implementsInterface('iScheduledProcess') && (($oTask->Get('status') != 'active') || ($oTask->Get('next_run_date') > $oNow->format('Y-m-d H:i:s'))))
  125. {
  126. if ($bVerbose)
  127. {
  128. $oP->p("Resetting the next run date for $sTaskClass");
  129. }
  130. $oProcess = $aProcesses[$sTaskClass];
  131. $oNextOcc = $oProcess->GetNextOccurrence();
  132. $oTask->Set('next_run_date', $oNextOcc->format('Y-m-d H:i:s'));
  133. $oTask->DBUpdate();
  134. }
  135. }
  136. $iCronSleep = MetaModel::GetConfig()->Get('cron_sleep');
  137. $oSearch = new DBObjectSearch('BackgroundTask');
  138. while (time() < $iTimeLimit)
  139. {
  140. $oTasks = new DBObjectSet($oSearch);
  141. $aTasks = array();
  142. while($oTask = $oTasks->Fetch())
  143. {
  144. $aTasks[$oTask->Get('class_name')] = $oTask;
  145. }
  146. foreach ($aProcesses as $oProcess)
  147. {
  148. $sTaskClass = get_class($oProcess);
  149. $oNow = new DateTime();
  150. if (!array_key_exists($sTaskClass, $aTasks))
  151. {
  152. // New entry, let's create a new BackgroundTask record, and plan the first execution
  153. $oTask = new BackgroundTask();
  154. $oTask->Set('class_name', get_class($oProcess));
  155. $oTask->Set('total_exec_count', 0);
  156. $oTask->Set('min_run_duration', 99999.999);
  157. $oTask->Set('max_run_duration', 0);
  158. $oTask->Set('average_run_duration', 0);
  159. $oRefClass = new ReflectionClass($sTaskClass);
  160. if ($oRefClass->implementsInterface('iScheduledProcess'))
  161. {
  162. $oNextOcc = $oProcess->GetNextOccurrence();
  163. $oTask->Set('next_run_date', $oNextOcc->format('Y-m-d H:i:s'));
  164. }
  165. else
  166. {
  167. // Background processes do start asap, i.e. "now"
  168. $oTask->Set('next_run_date', $oNow->format('Y-m-d H:i:s'));
  169. }
  170. if ($bVerbose)
  171. {
  172. $oP->p('Creating record for: '.$sTaskClass);
  173. $oP->p('First execution planned at: '.$oTask->Get('next_run_date'));
  174. }
  175. $oTask->DBInsert();
  176. $aTasks[$oTask->Get('class_name')] = $oTask;
  177. }
  178. if( ($aTasks[$sTaskClass]->Get('status') == 'active') && ($aTasks[$sTaskClass]->Get('next_run_date') <= $oNow->format('Y-m-d H:i:s')))
  179. {
  180. // Run the task and record its next run time
  181. if ($bVerbose)
  182. {
  183. $oP->p(">> === ".$oNow->format('Y-m-d H:i:s').sprintf(" Starting:%-'=40s", ' '.$sTaskClass.' '));
  184. }
  185. $sMessage = RunTask($oProcess, $aTasks[$sTaskClass], $oNow, $iTimeLimit);
  186. if ($bVerbose)
  187. {
  188. if(!empty($sMessage))
  189. {
  190. $oP->p("$sTaskClass: $sMessage");
  191. }
  192. $oEnd = new DateTime();
  193. $oP->p("<< === ".$oEnd->format('Y-m-d H:i:s').sprintf(" End of: %-'=40s", ' '.$sTaskClass.' '));
  194. }
  195. }
  196. else
  197. {
  198. // will run later
  199. if (($aTasks[$sTaskClass]->Get('status') == 'active') && $bVerbose)
  200. {
  201. $oP->p("Skipping asynchronous task: $sTaskClass until ".$aTasks[$sTaskClass]->Get('next_run_date'));
  202. }
  203. }
  204. }
  205. if ($bVerbose)
  206. {
  207. $oP->p("Sleeping");
  208. }
  209. sleep($iCronSleep);
  210. }
  211. if ($bVerbose)
  212. {
  213. $oP->p("Reached normal execution time limit (exceeded by ".(time()-$iTimeLimit)."s)");
  214. }
  215. }
  216. function DisplayStatus($oP)
  217. {
  218. $oSearch = new DBObjectSearch('BackgroundTask');
  219. $oTasks = new DBObjectSet($oSearch);
  220. $oP->p('+---------------------------+---------+---------------------+---------------------+--------+-----------+');
  221. $oP->p('| Task Class | Status | Last Run | Next Run | Nb Run | Avg. Dur. |');
  222. $oP->p('+---------------------------+---------+---------------------+---------------------+--------+-----------+');
  223. while($oTask = $oTasks->Fetch())
  224. {
  225. $sTaskName = $oTask->Get('class_name');
  226. $sStatus = $oTask->Get('status');
  227. $sLastRunDate = $oTask->Get('latest_run_date');
  228. $sNextRunDate = $oTask->Get('next_run_date');
  229. $iNbRun = (int)$oTask->Get('total_exec_count');
  230. $sAverageRunTime = $oTask->Get('average_run_duration');
  231. $oP->p(sprintf('| %1$-25.25s | %2$-7s | %3$-19s | %4$-19s | %5$6d | %6$7s s |', $sTaskName, $sStatus, $sLastRunDate, $sNextRunDate, $iNbRun, $sAverageRunTime));
  232. }
  233. $oP->p('+---------------------------+---------+---------------------+---------------------+--------+-----------+');
  234. }
  235. ////////////////////////////////////////////////////////////////////////////////
  236. //
  237. // Main
  238. //
  239. set_time_limit(0); // Some background actions may really take long to finish (like backup)
  240. if (utils::IsModeCLI())
  241. {
  242. $oP = new CLIPage("iTop - CRON");
  243. }
  244. else
  245. {
  246. $oP = new WebPage("iTop - CRON");
  247. }
  248. try
  249. {
  250. utils::UseParamFile();
  251. }
  252. catch(Exception $e)
  253. {
  254. $oP->p("Error: ".$e->GetMessage());
  255. $oP->output();
  256. exit -2;
  257. }
  258. if (utils::IsModeCLI())
  259. {
  260. // Next steps:
  261. // specific arguments: 'csvfile'
  262. //
  263. $sAuthUser = ReadMandatoryParam($oP, 'auth_user', 'raw_data');
  264. $sAuthPwd = ReadMandatoryParam($oP, 'auth_pwd', 'raw_data');
  265. if (UserRights::CheckCredentials($sAuthUser, $sAuthPwd))
  266. {
  267. UserRights::Login($sAuthUser); // Login & set the user's language
  268. }
  269. else
  270. {
  271. $oP->p("Access wrong credentials ('$sAuthUser')");
  272. $oP->output();
  273. exit -1;
  274. }
  275. }
  276. else
  277. {
  278. $_SESSION['login_mode'] = 'basic';
  279. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  280. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  281. }
  282. if (!UserRights::IsAdministrator())
  283. {
  284. $oP->p("Access restricted to administrators");
  285. $oP->Output();
  286. exit -1;
  287. }
  288. // Enumerate classes implementing BackgroundProcess
  289. //
  290. $aProcesses = array();
  291. foreach(get_declared_classes() as $sPHPClass)
  292. {
  293. $oRefClass = new ReflectionClass($sPHPClass);
  294. $oExtensionInstance = null;
  295. if ($oRefClass->implementsInterface('iProcess'))
  296. {
  297. if (is_null($oExtensionInstance))
  298. {
  299. $oExecInstance = new $sPHPClass;
  300. }
  301. $aProcesses[$sPHPClass] = $oExecInstance;
  302. }
  303. }
  304. $bVerbose = utils::ReadParam('verbose', false, true /* Allow CLI */);
  305. $bDebug = utils::ReadParam('debug', false, true /* Allow CLI */);
  306. if ($bVerbose)
  307. {
  308. $aDisplayProcesses = array();
  309. foreach ($aProcesses as $oExecInstance)
  310. {
  311. $aDisplayProcesses[] = get_class($oExecInstance);
  312. }
  313. $sDisplayProcesses = implode(', ', $aDisplayProcesses);
  314. $oP->p("Background processes: ".$sDisplayProcesses);
  315. }
  316. if (utils::ReadParam('status_only', false, true /* Allow CLI */))
  317. {
  318. // Display status and exit
  319. DisplayStatus($oP);
  320. exit(0);
  321. }
  322. require_once(APPROOT.'core/mutex.class.inc.php');
  323. $oP->p("Starting: ".time().' ('.date('Y-m-d H:i:s').')');
  324. try
  325. {
  326. $oConfig = utils::GetConfig();
  327. $oMutex = new iTopMutex('cron');
  328. if ($oMutex->TryLock())
  329. {
  330. // Note: testing this now in case some of the background processes forces the read-only mode for a while
  331. // in that case it is better to exit with the check on reentrance (mutex)
  332. if (!MetaModel::DBHasAccess(ACCESS_ADMIN_WRITE))
  333. {
  334. $oP->p("A database maintenance is ongoing (read-only mode even for admins).");
  335. $oP->Output();
  336. exit -1;
  337. }
  338. CronExec($oP, $aProcesses, $bVerbose);
  339. $oMutex->Unlock();
  340. }
  341. else
  342. {
  343. // Exit silently
  344. $oP->p("Already running...");
  345. }
  346. }
  347. catch (Exception $e)
  348. {
  349. $oP->p("ERROR: '".$e->getMessage()."'");
  350. if ($bDebug)
  351. {
  352. // Might contain verb parameters such a password...
  353. $oP->p($e->getTraceAsString());
  354. }
  355. }
  356. $oP->p("Exiting: ".time().' ('.date('Y-m-d H:i:s').')');
  357. $oP->Output();
  358. ?>