cron.php 10 KB

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