cron.php 12 KB

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