cron.php 11 KB

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