jobs.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. <?php
  2. /**
  3. * @file
  4. * Contains functions related to the Tripal Jobs API
  5. *
  6. * @defgroup tripal_jobs_api Core Module Jobs API
  7. * @{
  8. * Tripal offers a job management subsystem for managing tasks that may require an extended period of time for
  9. * completion. Drupal uses a UNIX-based cron job to handle tasks such as checking the availability of updates,
  10. * indexing new nodes for searching, etc. Drupal's cron uses the web interface for launching these tasks, however,
  11. * Tripal provides several administrative tasks that may time out and not complete due to limitations of the web
  12. * server. Examples including syncing of a large number of features between chado and Drupal. To circumvent this,
  13. * as well as provide more fine-grained control and monitoring, Tripal uses a jobs management sub-system built into
  14. * the Tripal Core module. It is anticipated that this functionality will be used for managing analysis jobs provided by
  15. * future tools, with eventual support for distributed computing.
  16. *
  17. * The Tripal jobs management system allows administrators to submit tasks to be performed which can then be
  18. * launched through a UNIX command-line PHP script or cron job. This command-line script can be added to a cron
  19. * entry along-side the Drupal cron entry for automatic, regular launching of Tripal jobs. The order of execution of
  20. * waiting jobs is determined first by priority and second by the order the jobs were entered.
  21. *
  22. * The API functions described below provide a programmatic interface for adding, checking and viewing jobs.
  23. * @}
  24. * @ingroup tripal_api
  25. */
  26. /**
  27. * Adds a job to the Tripal Jbo queue
  28. *
  29. * @param $job_name
  30. * The human readable name for the job
  31. * @param $modulename
  32. * The name of the module adding the job
  33. * @param $callback
  34. * The name of a function to be called when the job is executed
  35. * @param $arguments
  36. * An array of arguements to be passed on to the callback
  37. * @param $uid
  38. * The uid of the user adding the job
  39. * @param $priority
  40. * The priority at which to run the job where the highest priority is 10 and the lowest priority
  41. * is 1. The default priority is 10.
  42. *
  43. * @return
  44. * The job_id of the registered job
  45. *
  46. * Example usage:
  47. * @code
  48. * $args = array($dfile, $organism_id, $type, $library_id, $re_name, $re_uname,
  49. * $re_accession, $db_id, $rel_type, $re_subject, $parent_type, $method,
  50. * $user->uid, $analysis_id, $match_type);
  51. *
  52. * tripal_add_job("Import FASTA file: $dfile", 'tripal_feature',
  53. * 'tripal_feature_load_fasta', $args, $user->uid);
  54. * @endcode
  55. * The code above is copied from the tripal_feature/fasta_loader.php file. The
  56. * snipped first builds an array of arguments that will then be passed to the
  57. * tripal_add_job function. The number of arguments provided in the $arguments
  58. * variable should match the argument set for the callback function provided
  59. * as the third argument.
  60. *
  61. * @ingroup tripal_jobs_api
  62. */
  63. function tripal_add_job($job_name, $modulename, $callback, $arguments, $uid, $priority = 10) {
  64. // convert the arguments into a string for storage in the database
  65. $args = implode("::", $arguments);
  66. $record = new stdClass();
  67. $record->job_name = $job_name;
  68. $record->modulename = $modulename;
  69. $record->callback = $callback;
  70. $record->status = 'Waiting';
  71. $record->submit_date = time();
  72. $record->uid = $uid;
  73. $record->priority = $priority; # the lower the number the higher the priority
  74. if ($args) {
  75. $record->arguments = $args;
  76. }
  77. if (drupal_write_record('tripal_jobs', $record)) {
  78. $jobs_url = url("admin/tripal/tripal_jobs");
  79. drupal_set_message(t("Job '%job_name' submitted. Check the %jobs_link for status", array('%job_name' => $job_name, '%jobs_link' => l($jobs_url, 'jobs page'))));
  80. }
  81. else {
  82. drupal_set_message(t("Failed to add job %job_name.", array('%job_name' => $job_name)), 'error');
  83. }
  84. return $record->job_id;
  85. }
  86. /**
  87. * An internal function for setting the progress for a current job
  88. *
  89. * @param $job_id
  90. * The job_id to set the progress for
  91. * @param $percentage
  92. * The progress to set the job to
  93. *
  94. * @return
  95. * True on success and False otherwise
  96. *
  97. * @ingroup tripal_core
  98. */
  99. function tripal_job_set_progress($job_id, $percentage) {
  100. if (preg_match("/^(\d+|100)$/", $percentage)) {
  101. $record = new stdClass();
  102. $record->job_id = $job_id;
  103. $record->progress = $percentage;
  104. if (drupal_write_record('tripal_jobs', $record, 'job_id')) {
  105. return TRUE;
  106. }
  107. }
  108. return FALSE;
  109. }
  110. /**
  111. * Returns a list of jobs associated with the given module
  112. *
  113. * @param $modulename
  114. * The module to return a list of jobs for
  115. *
  116. * @return
  117. * An array of objects where each object describes a tripal job
  118. *
  119. * @ingroup tripal_jobs_api
  120. */
  121. function tripal_get_module_active_jobs($modulename) {
  122. $sql = "SELECT * FROM {tripal_jobs} TJ ".
  123. "WHERE TJ.end_time IS NULL and TJ.modulename = '%s' ";
  124. return db_fetch_object(db_query($sql, $modulename));
  125. }
  126. /**
  127. * Returns the Tripal Job Report
  128. *
  129. * @return
  130. * The HTML to be rendered which describes the job report
  131. *
  132. * @ingroup tripal_core
  133. */
  134. function tripal_jobs_report() {
  135. //$jobs = db_query("SELECT * FROM {tripal_jobs} ORDER BY job_id DESC");
  136. $jobs = pager_query(
  137. "SELECT TJ.job_id,TJ.uid,TJ.job_name,TJ.modulename,TJ.progress,
  138. TJ.status as job_status, TJ,submit_date,TJ.start_time,
  139. TJ.end_time,TJ.priority,U.name as username
  140. FROM {tripal_jobs} TJ
  141. INNER JOIN {users} U on TJ.uid = U.uid
  142. ORDER BY job_id DESC", 10, 0, "SELECT count(*) FROM {tripal_jobs}");
  143. // create a table with each row containig stats for
  144. // an individual job in the results set.
  145. $output .= "Waiting jobs are executed first by priority level (the lower the ".
  146. "number the higher the priority) and second by the order they ".
  147. "were entered";
  148. $output .= "<table class=\"tripal-table tripal-table-horz\">".
  149. " <tr>".
  150. " <th>Job ID</th>".
  151. " <th>User</th>".
  152. " <th>Job Name</th>".
  153. " <th nowrap>Dates</th>".
  154. " <th>Priority</th>".
  155. " <th>Progress</th>".
  156. " <th>Status</th>".
  157. " <th>Actions</th>".
  158. " </tr>";
  159. $i = 0;
  160. while ($job = db_fetch_object($jobs)) {
  161. $class = 'tripal-table-odd-row';
  162. if ($i % 2 == 0 ) {
  163. $class = 'tripal-table-even-row';
  164. }
  165. $submit = tripal_jobs_get_submit_date($job);
  166. $start = tripal_jobs_get_start_time($job);
  167. $end = tripal_jobs_get_end_time($job);
  168. $cancel_link = '';
  169. if ($job->start_time == 0 and $job->end_time == 0) {
  170. $cancel_link = "<a href=\"" . url("admin/tripal/tripal_jobs/cancel/" . $job->job_id) . "\">Cancel</a><br />";
  171. }
  172. $rerun_link = "<a href=\"" . url("admin/tripal/tripal_jobs/rerun/" . $job->job_id) . "\">Re-run</a><br />";
  173. $view_link ="<a href=\"" . url("admin/tripal/tripal_jobs/view/" . $job->job_id) . "\">View</a>";
  174. $output .= " <tr class=\"$class\">";
  175. $output .= " <td>$job->job_id</td>".
  176. " <td>$job->username</td>".
  177. " <td>$job->job_name</td>".
  178. " <td nowrap>Submit Date: $submit".
  179. " <br />Start Time: $start".
  180. " <br />End Time: $end</td>".
  181. " <td>$job->priority</td>".
  182. " <td>$job->progress%</td>".
  183. " <td>$job->job_status</td>".
  184. " <td>$cancel_link $rerun_link $view_link</td>".
  185. " </tr>";
  186. $i++;
  187. }
  188. $output .= "</table>";
  189. $output .= theme_pager();
  190. return $output;
  191. }
  192. /**
  193. * Returns the start time for a given job
  194. *
  195. * @param $job
  196. * An object describing the job
  197. *
  198. * @return
  199. * The start time of the job if it was already run and either "Cancelled" or "Not Yet Started" otherwise
  200. *
  201. * @ingroup tripal_jobs_api
  202. */
  203. function tripal_jobs_get_start_time($job) {
  204. if ($job->start_time > 0) {
  205. $start = format_date($job->start_time);
  206. }
  207. else {
  208. if (strcmp($job->job_status, 'Cancelled')==0) {
  209. $start = 'Cancelled';
  210. }
  211. else {
  212. $start = 'Not Yet Started';
  213. }
  214. }
  215. return $start;
  216. }
  217. /**
  218. * Returns the end time for a given job
  219. *
  220. * @param $job
  221. * An object describing the job
  222. *
  223. * @return
  224. * The end time of the job if it was already run and empty otherwise
  225. *
  226. * @ingroup tripal_jobs_api
  227. */
  228. function tripal_jobs_get_end_time($job) {
  229. if ($job->end_time > 0) {
  230. $end = format_date($job->end_time);
  231. }
  232. else {
  233. $end = '';
  234. }
  235. return $end;
  236. }
  237. /**
  238. * Returns the date the job was added to the queue
  239. *
  240. * @param $job
  241. * An object describing the job
  242. *
  243. * @return
  244. * The date teh job was submitted
  245. *
  246. * @ingroup tripal_jobs_api
  247. */
  248. function tripal_jobs_get_submit_date($job) {
  249. return format_date($job->submit_date);
  250. }
  251. /**
  252. * A function used to manually launch all queued tripal jobs
  253. *
  254. * @param $do_parallel
  255. * A boolean indicating whether jobs should be attempted to run in parallel
  256. *
  257. * @ingroup tripal_jobs_api
  258. */
  259. function tripal_jobs_launch($do_parallel = 0) {
  260. // first check if any jobs are currently running
  261. // if they are, don't continue, we don't want to have
  262. // more than one job script running at a time
  263. if (!$do_parallel and tripal_jobs_check_running()) {
  264. return;
  265. }
  266. // get all jobs that have not started and order them such that
  267. // they are processed in a FIFO manner.
  268. $sql = "SELECT * FROM {tripal_jobs} TJ ".
  269. "WHERE TJ.start_time IS NULL and TJ.end_time IS NULL ".
  270. "ORDER BY priority ASC,job_id ASC";
  271. $job_res = db_query($sql);
  272. while ($job = db_fetch_object($job_res)) {
  273. // set the start time for this job
  274. $record = new stdClass();
  275. $record->job_id = $job->job_id;
  276. $record->start_time = time();
  277. $record->status = 'Running';
  278. $record->pid = getmypid();
  279. drupal_write_record('tripal_jobs', $record, 'job_id');
  280. // call the function provided in the callback column.
  281. // Add the job_id as the last item in the list of arguments. All
  282. // callback functions should support this argument.
  283. $callback = $job->callback;
  284. $args = split("::", $job->arguments);
  285. $args[] = $job->job_id;
  286. print "Calling: $callback(" . implode(", ", $args) . ")\n";
  287. call_user_func_array($callback, $args);
  288. // set the end time for this job
  289. $record->end_time = time();
  290. $record->status = 'Completed';
  291. $record->progress = '100';
  292. drupal_write_record('tripal_jobs', $record, 'job_id');
  293. // send an email to the user advising that the job has finished
  294. }
  295. }
  296. /**
  297. * Returns a list of running tripal jobs
  298. *
  299. * @return
  300. * and array of objects where each object describes a running job or FALSE if no jobs are running
  301. *
  302. * @ingroup tripal_jobs_api
  303. */
  304. function tripal_jobs_check_running() {
  305. // iterate through each job that has not ended
  306. // and see if it is still running. If it is not
  307. // running but does not have an end_time then
  308. // set the end time and set the status to 'Error'
  309. $sql = "SELECT * FROM {tripal_jobs} TJ ".
  310. "WHERE TJ.end_time IS NULL and NOT TJ.start_time IS NULL ";
  311. $jobs = db_query($sql);
  312. while ($job = db_fetch_object($jobs)) {
  313. $status = `ps --pid=$job->pid --no-header`;
  314. if ($job->pid && $status) {
  315. // the job is still running so let it go
  316. // we return 1 to indicate that a job is running
  317. print "Job is still running (pid $job->pid)\n";
  318. return TRUE;
  319. }
  320. else {
  321. // the job is not running so terminate it
  322. $record = new stdClass();
  323. $record->job_id = $job->job_id;
  324. $record->end_time = time();
  325. $record->status = 'Error';
  326. $record->error_msg = 'Job has terminated unexpectedly.';
  327. drupal_write_record('tripal_jobs', $record, 'job_id');
  328. }
  329. }
  330. // return 1 to indicate that no jobs are currently running.
  331. return FALSE;
  332. }
  333. /**
  334. * Returns the HTML code to display a given job
  335. *
  336. * @param $job_id
  337. * The job_id of the job to display
  338. *
  339. * @return
  340. * The HTML describing the indicated job
  341. * @ingroup tripal_core
  342. */
  343. function tripal_jobs_view($job_id) {
  344. return theme('tripal_core_job_view', $job_id);
  345. }
  346. /**
  347. * Registers variables for the tripal_core_job_view themeing function
  348. *
  349. * @param $variables
  350. * An array containing all variables supplied to this template
  351. *
  352. * @ingroup tripal_core
  353. */
  354. function tripal_core_preprocess_tripal_core_job_view(&$variables) {
  355. // get the job record
  356. $job_id = $variables['job_id'];
  357. $sql =
  358. "SELECT TJ.job_id,TJ.uid,TJ.job_name,TJ.modulename,TJ.progress,
  359. TJ.status as job_status, TJ,submit_date,TJ.start_time,
  360. TJ.end_time,TJ.priority,U.name as username,TJ.arguments,
  361. TJ.callback,TJ.error_msg,TJ.pid
  362. FROM {tripal_jobs} TJ
  363. INNER JOIN users U on TJ.uid = U.uid
  364. WHERE TJ.job_id = %d";
  365. $job = db_fetch_object(db_query($sql, $job_id));
  366. // we do not know what the arguments are for and we want to provide a
  367. // meaningful description to the end-user. So we use a callback function
  368. // deinfed in the module that created the job to describe in an array
  369. // the arguments provided. If the callback fails then just use the
  370. // arguments as they are
  371. $args = preg_split("/::/", $job->arguments);
  372. $arg_hook = $job->modulename . "_job_describe_args";
  373. if (is_callable($arg_hook)) {
  374. $new_args = call_user_func_array($arg_hook, array($job->callback, $args));
  375. if (is_array($new_args) and count($new_args)) {
  376. $job->arguments = $new_args;
  377. }
  378. else {
  379. $job->arguments = $args;
  380. }
  381. }
  382. else {
  383. $job->arguments = $args;
  384. }
  385. // make our start and end times more legible
  386. $job->submit_date = tripal_jobs_get_submit_date($job);
  387. $job->start_time = tripal_jobs_get_start_time($job);
  388. $job->end_time = tripal_jobs_get_end_time($job);
  389. // add the job to the variables that get exported to the template
  390. $variables['job'] = $job;
  391. }
  392. /**
  393. * Set a job to be re-ran (ie: add it back into the job queue)
  394. *
  395. * @param $job_id
  396. * The job_id of the job to be re-ran
  397. *
  398. * @ingroup tripal_jobs_api
  399. */
  400. function tripal_jobs_rerun($job_id) {
  401. global $user;
  402. $sql = "SELECT * FROM {tripal_jobs} WHERE job_id = %d";
  403. $job = db_fetch_object(db_query($sql, $job_id));
  404. $args = explode("::", $job->arguments);
  405. tripal_add_job($job->job_name, $job->modulename, $job->callback, $args, $user->uid,
  406. $job->priority);
  407. drupal_goto("admin/tripal/tripal_jobs");
  408. }
  409. /**
  410. * Cancel a Tripal Job currently waiting in the job queue
  411. *
  412. * @param $job_id
  413. * The job_id of the job to be cancelled
  414. *
  415. * @ingroup tripal_jobs_api
  416. */
  417. function tripal_jobs_cancel($job_id) {
  418. $sql = "SELECT * FROM {tripal_jobs} WHERE job_id = %d";
  419. $job = db_fetch_object(db_query($sql, $job_id));
  420. // set the end time for this job
  421. if ($job->start_time == 0) {
  422. $record = new stdClass();
  423. $record->job_id = $job->job_id;
  424. $record->end_time = time();
  425. $record->status = 'Cancelled';
  426. $record->progress = '0';
  427. drupal_write_record('tripal_jobs', $record, 'job_id');
  428. drupal_set_message(t("Job #%job_id cancelled", array('%job_id' => $job_id)));
  429. }
  430. else {
  431. drupal_set_message(t("Job %job_id cannot be cancelled. It is in progress or has finished.", array('%job_id' => $job_id)));
  432. }
  433. drupal_goto("admin/tripal/tripal_jobs");
  434. }