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