cron.php 12 KB

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