tripal_core.jobs.api.inc

Tripal offers a job management subsystem for managing tasks that may require an extended period of time for completion.

File

tripal_core/api/tripal_core.jobs.api.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Tripal offers a job management subsystem for managing tasks that may require
  5. * an extended period of time for completion.
  6. */
  7. /**
  8. * @defgroup tripal_jobs_api Tripal Jobs API
  9. * @ingroup tripal_core_api
  10. * @{
  11. * Tripal offers a job management subsystem for managing tasks that may require
  12. * an extended period of time for completion. Drupal uses a UNIX-based cron
  13. * job to handle tasks such as checking the availability of updates, indexing
  14. * new nodes for searching, etc. Drupal's cron uses the web interface for
  15. * launching these tasks, however, Tripal provides several administrative tasks
  16. * that may time out and not complete due to limitations of the web server.
  17. * Examples including syncing of a large number of features between chado and
  18. * Drupal. To circumvent this, as well as provide more fine-grained control
  19. * and monitoring, Tripal uses a jobs management sub-system built into the
  20. * Tripal Core module. It is anticipated that this functionality will be used
  21. * for managing analysis jobs provided by future tools, with eventual support
  22. * for distributed computing.
  23. *
  24. * The Tripal jobs management system allows administrators to submit tasks to
  25. * be performed which can then be launched through a UNIX command-line PHP
  26. * script or cron job. This command-line script can be added to a cron entry
  27. * along-side the Drupal cron entry for automatic, regular launching of Tripal
  28. * jobs. The order of execution of waiting jobs is determined first by
  29. * priority and second by the order the jobs were entered.
  30. *
  31. * The API functions described below provide a programmatic interface for
  32. * adding, checking and viewing jobs.
  33. * @}
  34. */
  35. /**
  36. * Adds a job to the Tripal Jbo queue
  37. *
  38. * @param $job_name
  39. * The human readable name for the job
  40. * @param $modulename
  41. * The name of the module adding the job
  42. * @param $callback
  43. * The name of a function to be called when the job is executed
  44. * @param $arguments
  45. * An array of arguments to be passed on to the callback
  46. * @param $uid
  47. * The uid of the user adding the job
  48. * @param $priority
  49. * The priority at which to run the job where the highest priority is 10 and the lowest priority
  50. * is 1. The default priority is 10.
  51. *
  52. * @return
  53. * The job_id of the registered job
  54. *
  55. * Example usage:
  56. * @code
  57. * $args = array($dfile, $organism_id, $type, $library_id, $re_name, $re_uname,
  58. * $re_accession, $db_id, $rel_type, $re_subject, $parent_type, $method,
  59. * $user->uid, $analysis_id, $match_type);
  60. *
  61. * tripal_add_job("Import FASTA file: $dfile", 'tripal_feature',
  62. * 'tripal_feature_load_fasta', $args, $user->uid);
  63. * @endcode
  64. * The code above is copied from the tripal_feature/fasta_loader.php file. The
  65. * snipped first builds an array of arguments that will then be passed to the
  66. * tripal_add_job function. The number of arguments provided in the $arguments
  67. * variable should match the argument set for the callback function provided
  68. * as the third argument.
  69. *
  70. * @ingroup tripal_jobs_api
  71. */
  72. function tripal_add_job($job_name, $modulename, $callback, $arguments, $uid, $priority = 10) {
  73. if (!$job_name) {
  74. watchdog('tripal', "Must provide a \$job_name argument to the tripal_add_job() function.", 'error');
  75. return FALSE;
  76. }
  77. if (!$modulename) {
  78. watchdog('tripal', "Must provide a \$modulename argument to the tripal_add_job() function.", 'error');
  79. return FALSE;
  80. }
  81. if (!$callback) {
  82. watchdog('tripal', "Must provide a \$callback argument to the tripal_add_job() function.", 'error');
  83. return FALSE;
  84. }
  85. if (!function_exists($callback)) {
  86. watchdog('tripal', "Must provide a valid callback function to the tripal_add_job() function.", 'error');
  87. return FALSE;
  88. }
  89. if (!is_numeric($uid)) {
  90. watchdog('tripal', "Must provide a numeric \$uid argument to the tripal_add_job() function.", 'error');
  91. return FALSE;
  92. }
  93. if (!$priority or !is_numeric($priority) or $priority < 1 or $priority > 10) {
  94. watchdog('tripal', "Must provide a numeric \$priority argument between 1 and 10 to the tripal_add_job() function.", 'error');
  95. return FALSE;
  96. }
  97. if (!is_array($arguments)) {
  98. watchdog('tripal', "Must provide an array as the \$arguments argument to the tripal_add_job() function.", 'error');
  99. return FALSE;
  100. }
  101. $user = user_load($uid);
  102. // convert the arguments into a string for storage in the database
  103. $args = array();
  104. if (is_array($arguments)) {
  105. $args = serialize($arguments);
  106. }
  107. $job_id = db_insert('tripal_jobs')
  108. ->fields(array(
  109. 'job_name' => $job_name,
  110. 'modulename' => $modulename,
  111. 'callback' => $callback,
  112. 'status' => 'Waiting',
  113. 'submit_date' => time(),
  114. 'uid' => $uid,
  115. # The lower the number the higher the priority.
  116. 'priority' => $priority,
  117. 'arguments' => $args,
  118. ))
  119. ->execute();
  120. if ($job_id) {
  121. drupal_set_message(t("Job '%job_name' submitted.", array('%job_name' => $job_name)));
  122. if (user_access('administer tripal')) {
  123. $jobs_url = url("admin/tripal/tripal_jobs");
  124. drupal_set_message(t("Check the <a href='!jobs_url'>jobs page</a> for status.",
  125. array('!jobs_url' => $jobs_url)));
  126. drupal_set_message(t("You can execute the job queue manually on the command line " .
  127. "using the following Drush command: <br>drush trp-run-jobs --username=%uname --root=%base_path",
  128. array('%base_path' => DRUPAL_ROOT, '%uname' => $user->name)));
  129. }
  130. }
  131. else {
  132. drupal_set_message(t("Failed to add job: %job_name.", array('%job_name' => $job_name)), 'error');
  133. }
  134. return $job_id;
  135. }
  136. /**
  137. * Retrieve information regarding a tripal job
  138. *
  139. * @param $job_id
  140. * The unique identifier of the job
  141. *
  142. * @return
  143. * An object describing the job if a job is found or FALSE on failure.
  144. *
  145. * @ingroup tripal_jobs_api
  146. */
  147. function tripal_get_job($job_id) {
  148. if (!$job_id or !is_numeric($job_id)) {
  149. watchdog('tripal', "Must provide a numeric \$job_id to the tripal_cancel_job() function.");
  150. return FALSE;
  151. }
  152. $job = db_query('SELECT j.* FROM {tripal_jobs} j WHERE j.job_id=:job_id', array(':job_id' => $job_id))
  153. ->fetchObject();
  154. $job->submit_date_string = format_date($job->submit_date);
  155. $job->start_time_string = format_date($job->start_time);
  156. $job->end_time_string = format_date($job->end_time);
  157. return $job;
  158. }
  159. /**
  160. * Indicates if any jobs are running.
  161. *
  162. * This function will check the system to see if a job has a process ID
  163. * and if that process ID is still running. It will update the job status
  164. * accordingly before returning.
  165. *
  166. * @return
  167. * Returns TRUE if any job is running or FALSE otherwise.
  168. *
  169. * @ingroup tripal_jobs_api
  170. */
  171. function tripal_is_job_running() {
  172. // Iterate through each job that has not ended
  173. // and see if it is still running. If it is not
  174. // running but does not have an end_time then
  175. // set the end time and set the status to 'Error'
  176. $sql = "SELECT * FROM {tripal_jobs} TJ " .
  177. "WHERE TJ.end_time IS NULL and NOT TJ.start_time IS NULL ";
  178. $jobs = db_query($sql);
  179. foreach ($jobs as $job) {
  180. $status = shell_exec('ps -p ' . escapeshellarg($job->pid) . ' -o pid=');
  181. if ($job->pid && $status) {
  182. // the job is still running so let it go
  183. // we return 1 to indicate that a job is running
  184. return TRUE;
  185. }
  186. else {
  187. // the job is not running so terminate it
  188. $record = new stdClass();
  189. $record->job_id = $job->job_id;
  190. $record->end_time = time();
  191. $record->status = 'Error';
  192. $record->error_msg = 'Job has terminated unexpectedly.';
  193. drupal_write_record('tripal_jobs', $record, 'job_id');
  194. }
  195. }
  196. // return 1 to indicate that no jobs are currently running.
  197. return FALSE;
  198. }
  199. /**
  200. * Returns the start time for a given job
  201. *
  202. * @param $job
  203. * An object describing the job
  204. *
  205. * @return
  206. * The start time of the job if it was already run and either "Cancelled" or "Not Yet Started" otherwise
  207. *
  208. * @ingroup tripal_jobs_api
  209. */
  210. function tripal_get_job_start($job) {
  211. if ($job->start_time > 0) {
  212. $start = format_date($job->start_time);
  213. }
  214. else {
  215. if (strcmp($job->job_status, 'Cancelled')==0) {
  216. $start = 'Cancelled';
  217. }
  218. else {
  219. $start = 'Not Yet Started';
  220. }
  221. }
  222. return $start;
  223. }
  224. /**
  225. * Returns the end time for a given job
  226. *
  227. * @param $job
  228. * An object describing the job
  229. *
  230. * @return
  231. * The end time of the job if it was already run and empty otherwise
  232. *
  233. * @ingroup tripal_jobs_api
  234. */
  235. function tripal_get_job_end($job) {
  236. if ($job->end_time > 0) {
  237. $end = format_date($job->end_time);
  238. }
  239. else {
  240. $end = '';
  241. }
  242. return $end;
  243. }
  244. /**
  245. * Check for too many concurrent jobs
  246. *
  247. * @param $max_jobs
  248. * The maximum number of concurrent jobs to allow; -1 = no limit
  249. *
  250. * @ingroup tripal_jobs_api
  251. */
  252. function tripal_max_jobs_exceeded($max_jobs) {
  253. if ($max_jobs < 0) {
  254. // No limit on concurrent jobs
  255. return FALSE;
  256. }
  257. $num_jobs_running = 0;
  258. // Iterate through each job that has not ended and see if it is still running.
  259. // If it is not running but does not have an end_time then set the end time
  260. // and set the status to 'Error'
  261. $sql = "SELECT * FROM {tripal_jobs} TJ " .
  262. "WHERE TJ.end_time IS NULL and NOT TJ.start_time IS NULL ";
  263. $jobs = db_query($sql);
  264. foreach ($jobs as $job) {
  265. $status = shell_exec('ps -p ' . escapeshellarg($job->pid) . ' -o pid=');
  266. if ($job->pid && $status) {
  267. // the job is still running
  268. $num_jobs_running++;
  269. }
  270. else {
  271. // the job is not running so terminate it
  272. $record = new stdClass();
  273. $record->job_id = $job->job_id;
  274. $record->end_time = time();
  275. $record->status = 'Error';
  276. $record->error_msg = 'Job has terminated unexpectedly.';
  277. drupal_write_record('tripal_jobs', $record, 'job_id');
  278. }
  279. }
  280. return ($num_jobs_running >= $max_jobs);
  281. }
  282. /**
  283. * Set a job to be re-ran (ie: add it back into the job queue)
  284. *
  285. * @param $job_id
  286. * The job_id of the job to be re-ran
  287. * @param $goto_jobs_page
  288. * If set to TRUE then after the re run job is added Drupal will redirect to the jobs page
  289. *
  290. * @ingroup tripal_jobs_api
  291. */
  292. function tripal_rerun_job($job_id, $goto_jobs_page = TRUE) {
  293. global $user;
  294. $user_id = $user->uid;
  295. $sql = "SELECT * FROM {tripal_jobs} WHERE job_id = :job_id";
  296. $results = db_query($sql, array(':job_id' => $job_id));
  297. $job = $results->fetchObject();
  298. // arguments for jobs used to be stored as plain string with a double colon
  299. // separating them. But as of Tripal v2.0 the arguments are stored as
  300. // a serialized array. To be backwards compatible, we should check for serialization
  301. // and if not then we will use the old style
  302. $args = unserialize($job->arguments);
  303. if (!$args) {
  304. $args = explode("::", $job->arguments);
  305. }
  306. $job_id = tripal_add_job($job->job_name, $job->modulename, $job->callback, $args, $user_id, $job->priority);
  307. if ($goto_jobs_page) {
  308. drupal_goto("admin/tripal/tripal_jobs");
  309. }
  310. return $job_id;
  311. }
  312. /**
  313. * Cancel a Tripal Job currently waiting in the job queue
  314. *
  315. * @param $job_id
  316. * The job_id of the job to be cancelled
  317. *
  318. * @return
  319. * FALSE if the an error occured or the job could not be canceled, TRUE
  320. * otherwise.
  321. *
  322. * @ingroup tripal_jobs_api
  323. */
  324. function tripal_cancel_job($job_id, $redirect = TRUE) {
  325. if (!$job_id or !is_numeric($job_id)) {
  326. watchdog('tripal', "Must provide a numeric \$job_id to the tripal_cancel_job() function.");
  327. return FALSE;
  328. }
  329. $sql = "SELECT * FROM {tripal_jobs} WHERE job_id = :job_id";
  330. $results = db_query($sql, array(':job_id' => $job_id));
  331. $job = $results->fetchObject();
  332. // set the end time for this job
  333. if ($job->start_time == 0) {
  334. $record = new stdClass();
  335. $record->job_id = $job->job_id;
  336. $record->end_time = time();
  337. $record->status = 'Cancelled';
  338. $record->progress = '0';
  339. drupal_write_record('tripal_jobs', $record, 'job_id');
  340. drupal_set_message(t("Job #%job_id cancelled", array('%job_id' => $job_id)));
  341. }
  342. else {
  343. drupal_set_message(t("Job %job_id cannot be cancelled. It is in progress or has finished.", array('%job_id' => $job_id)));
  344. }
  345. if ($redirect) {
  346. drupal_goto("admin/tripal/tripal_jobs");
  347. }
  348. }
  349. /**
  350. * Execute a specific Tripal Job.
  351. *
  352. * @param $job_id
  353. * The job id to be exeuted
  354. * @param bool $redirect [optional]
  355. * Whether to redirect to the job page or not
  356. */
  357. function tripal_execute_job($job_id, $redirect = TRUE) {
  358. $sql = "SELECT * FROM {tripal_jobs} WHERE job_id = :job_id";
  359. $results = db_query($sql, array(':job_id' => $job_id));
  360. $job = $results->fetchObject();
  361. // set the end time for this job
  362. if ($job->start_time == 0 and $job->end_time == 0) {
  363. tripal_launch_job(1, $job_id);
  364. drupal_set_message(t("Job %job_id has finished executing. See below for more information.", array('%job_id' => $job_id)));
  365. }
  366. else {
  367. drupal_set_message(t("Job %job_id cannot be executed. It has already finished.", array('%job_id' => $job_id)));
  368. }
  369. if ($redirect) {
  370. drupal_goto("admin/tripal/tripal_jobs/view/$job_id");
  371. }
  372. }
  373. /**
  374. * A function used to manually launch all queued tripal jobs
  375. *
  376. * @param $do_parallel
  377. * A boolean indicating whether jobs should be attempted to run in parallel
  378. *
  379. * @param $job_id
  380. * To launch a specific job provide the job id. This option should be
  381. * used sparingly as the jobs queue managment system should launch jobs
  382. * based on order and priority. However there are times when a specific
  383. * job needs to be launched and this argument will allow it. Only jobs
  384. * which have not been run previously will run.
  385. * @param $max_jobs
  386. * The maximum number of jobs that should be run concurrently. If -1 then unlimited.
  387. * @param $single
  388. * Ensures only a single job is run rather then the entire queue.
  389. * @ingroup tripal_jobs_api
  390. */
  391. function tripal_launch_job($do_parallel = 0, $job_id = NULL, $max_jobs = -1, $single = 0) {
  392. // first check if any jobs are currently running
  393. // if they are, don't continue, we don't want to have
  394. // more than one job script running at a time
  395. if (!$do_parallel and tripal_is_job_running()) {
  396. print "Jobs are still running. Use the --parallel=1 option with the Drush command to run jobs in parallel.\n";
  397. return;
  398. }
  399. if ($do_parallel && tripal_max_jobs_exceeded($max_jobs)) {
  400. print "At least $max_jobs jobs are still running. At least one of these jobs much complete before a new job can start.\n";
  401. return;
  402. }
  403. // get all jobs that have not started and order them such that
  404. // they are processed in a FIFO manner.
  405. if ($job_id) {
  406. $sql = "SELECT * FROM {tripal_jobs} TJ " .
  407. "WHERE TJ.start_time IS NULL and TJ.end_time IS NULL and TJ.job_id = :job_id " .
  408. "ORDER BY priority ASC,job_id ASC";
  409. $job_res = db_query($sql, array(':job_id' => $job_id));
  410. }
  411. else {
  412. $sql = "SELECT * FROM {tripal_jobs} TJ " .
  413. "WHERE TJ.start_time IS NULL and TJ.end_time IS NULL " .
  414. "ORDER BY priority ASC,job_id ASC";
  415. $job_res = db_query($sql);
  416. }
  417. print "There are " . $job_res->rowCount() . " jobs queued.\n";
  418. foreach ($job_res as $job) {
  419. // set the start time for this job
  420. $record = new stdClass();
  421. $record->job_id = $job->job_id;
  422. $record->start_time = time();
  423. $record->status = 'Running';
  424. $record->pid = getmypid();
  425. drupal_write_record('tripal_jobs', $record, 'job_id');
  426. // call the function provided in the callback column.
  427. // Add the job_id as the last item in the list of arguments. All
  428. // callback functions should support this argument.
  429. $callback = $job->callback;
  430. // arguments for jobs used to be stored as plain string with a double colon
  431. // separating them. But as of Tripal v2.0 the arguments are stored as
  432. // a serialized array. To be backwards compatible, we should check for serialization
  433. // and if not then we will use the old style
  434. $args = unserialize($job->arguments);
  435. if (!$args) {
  436. $args = explode("::", $job->arguments);
  437. }
  438. $args[] = $job->job_id;
  439. // We need to do some additional processing for printing since the switch
  440. // to serialized arrays now allows nested arrays which cause errors when
  441. // printed using implode alone.
  442. $string_args = array();
  443. foreach ($args as $k => $a) {
  444. if (is_array($a)) {
  445. $string_args[$k] = 'Array';
  446. }
  447. elseif (is_object($a)) {
  448. $string_args[$k] = 'Object';
  449. }
  450. else {
  451. $string_args[$k] = $a;
  452. }
  453. }
  454. print "Calling: $callback(" . implode(", ", $string_args) . ")\n";
  455. call_user_func_array($callback, $args);
  456. // set the end time for this job
  457. $record->end_time = time();
  458. $record->status = 'Completed';
  459. $record->progress = '100';
  460. drupal_write_record('tripal_jobs', $record, 'job_id');
  461. if ($single) {
  462. // Don't start any more jobs
  463. break;
  464. }
  465. if (tripal_max_jobs_exceeded($max_jobs)) {
  466. break;
  467. }
  468. // send an email to the user advising that the job has finished
  469. }
  470. }
  471. /**
  472. * An internal function for setting the progress for a current job
  473. *
  474. * @param $job_id
  475. * The job_id to set the progress for
  476. * @param $percentage
  477. * The progress to set the job to
  478. *
  479. * @return
  480. * True on success and False otherwise
  481. *
  482. * @ingroup tripal_core
  483. */
  484. function tripal_set_job_progress($job_id, $percentage) {
  485. if (preg_match("/^(\d+|100)$/", $percentage)) {
  486. $record = new stdClass();
  487. $record->job_id = $job_id;
  488. $record->progress = $percentage;
  489. if (drupal_write_record('tripal_jobs', $record, 'job_id')) {
  490. return TRUE;
  491. }
  492. }
  493. return FALSE;
  494. }
  495. /**
  496. * Returns a list of jobs that are active.
  497. *
  498. * @param $modulename
  499. * Limit the list returned to those that were added by a specific module. If
  500. * no module name is provided then all active jobs are returned.
  501. *
  502. * @return
  503. * An array of objects where each object describes a tripal job. If no
  504. * jobs were found then an empty array is returned. Each object will have
  505. * the following members:
  506. * - job_id: The unique ID number for the job.
  507. * - uid: The ID of the user that submitted the job.
  508. * - job_name: The human-readable name of the job.
  509. * - modulename: The name of the module that submitted the job.
  510. * - callback: The callback function to be called when the job is run.
  511. * - arguments: An array of arguments to be passed to the callback function.
  512. * - progress: The percent progress of completion if the job is running.
  513. * - status: The status of the job: Waiting, Completed, Running or Cancelled.
  514. * - submit_date: The UNIX timestamp when the job was submitted.
  515. * - start_time: The UNIX timestamp for when the job started running.
  516. * - end_time: The UNIX timestampe when the job completed running.
  517. * - error_msg: Any error message that occured during execution of the job.
  518. * - prirotiy: The execution priority of the job (value between 1 and 10)
  519. *
  520. * @ingroup tripal_jobs_api
  521. */
  522. function tripal_get_active_jobs($modulename = NULL) {
  523. $query = db_select('tripal_jobs', 'TJ')
  524. ->fields('TJ', array('job_id', 'uid', 'job_name', 'modulename', 'callback',
  525. 'arguments', 'progress', 'status', 'submit_date', 'start_time',
  526. 'end_time', 'error_msg', 'priority'));
  527. if ($modulename) {
  528. $query->where(
  529. "TJ.modulename = :modulename and NOT (TJ.status = 'Completed' or TJ.status = 'Cancelled')",
  530. array(':modulename' => $modulename)
  531. );
  532. }
  533. $results = $query->execute();
  534. $jobs = array();
  535. while($job = $results->fetchobject()) {
  536. $jobs->arguments = unserialize($job->arguments);
  537. $jobs[] = $job;
  538. }
  539. return $jobs;
  540. }
  541. /**
  542. * Returns the date the job was added to the queue
  543. *
  544. * @param $job
  545. * An object describing the job
  546. *
  547. * @return
  548. * The date teh job was submitted
  549. *
  550. * @ingroup tripal_jobs_api
  551. */
  552. function tripal_get_job_submit_date($job) {
  553. return format_date($job->submit_date);
  554. }