cron.php 12 KB

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