tripal_core.jobs.api.inc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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' => REQUEST_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 = REQUEST_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. * Set a job to be re-ran (ie: add it back into the job queue)
  246. *
  247. * @param $job_id
  248. * The job_id of the job to be re-ran
  249. * @param $goto_jobs_page
  250. * If set to TRUE then after the re run job is added Drupal will redirect to the jobs page
  251. *
  252. * @ingroup tripal_jobs_api
  253. */
  254. function tripal_rerun_job($job_id, $goto_jobs_page = TRUE) {
  255. global $user;
  256. $user_id = $user->uid;
  257. $sql = "SELECT * FROM {tripal_jobs} WHERE job_id = :job_id";
  258. $results = db_query($sql, array(':job_id' => $job_id));
  259. $job = $results->fetchObject();
  260. // arguments for jobs used to be stored as plain string with a double colon
  261. // separating them. But as of Tripal v2.0 the arguments are stored as
  262. // a serialized array. To be backwards compatible, we should check for serialization
  263. // and if not then we will use the old style
  264. $args = unserialize($job->arguments);
  265. if (!$args) {
  266. $args = explode("::", $job->arguments);
  267. }
  268. $job_id = tripal_add_job($job->job_name, $job->modulename, $job->callback, $args, $user_id, $job->priority);
  269. if ($goto_jobs_page) {
  270. drupal_goto("admin/tripal/tripal_jobs");
  271. }
  272. return $job_id;
  273. }
  274. /**
  275. * Cancel a Tripal Job currently waiting in the job queue
  276. *
  277. * @param $job_id
  278. * The job_id of the job to be cancelled
  279. *
  280. * @return
  281. * FALSE if the an error occured or the job could not be canceled, TRUE
  282. * otherwise.
  283. *
  284. * @ingroup tripal_jobs_api
  285. */
  286. function tripal_cancel_job($job_id, $redirect = TRUE) {
  287. if (!$job_id or !is_numeric($job_id)) {
  288. watchdog('tripal', "Must provide a numeric \$job_id to the tripal_cancel_job() function.");
  289. return FALSE;
  290. }
  291. $sql = "SELECT * FROM {tripal_jobs} WHERE job_id = :job_id";
  292. $results = db_query($sql, array(':job_id' => $job_id));
  293. $job = $results->fetchObject();
  294. // set the end time for this job
  295. if ($job->start_time == 0) {
  296. $record = new stdClass();
  297. $record->job_id = $job->job_id;
  298. $record->end_time = REQUEST_TIME;
  299. $record->status = 'Cancelled';
  300. $record->progress = '0';
  301. drupal_write_record('tripal_jobs', $record, 'job_id');
  302. drupal_set_message(t("Job #%job_id cancelled", array('%job_id' => $job_id)));
  303. }
  304. else {
  305. drupal_set_message(t("Job %job_id cannot be cancelled. It is in progress or has finished.", array('%job_id' => $job_id)));
  306. }
  307. if ($redirect) {
  308. drupal_goto("admin/tripal/tripal_jobs");
  309. }
  310. }
  311. /**
  312. * Execute a specific Tripal Job.
  313. *
  314. * @param $job_id
  315. * The job id to be exeuted
  316. * @param bool $redirect [optional]
  317. * Whether to redirect to the job page or not
  318. */
  319. function tripal_execute_job($job_id, $redirect = TRUE) {
  320. $sql = "SELECT * FROM {tripal_jobs} WHERE job_id = :job_id";
  321. $results = db_query($sql, array(':job_id' => $job_id));
  322. $job = $results->fetchObject();
  323. // set the end time for this job
  324. if ($job->start_time == 0 and $job->end_time == 0) {
  325. tripal_launch_job(1, $job_id);
  326. drupal_set_message(t("Job %job_id has finished executing. See below for more information.", array('%job_id' => $job_id)));
  327. }
  328. else {
  329. drupal_set_message(t("Job %job_id cannot be executed. It has already finished.", array('%job_id' => $job_id)));
  330. }
  331. if ($redirect) {
  332. drupal_goto("admin/tripal/tripal_jobs/view/$job_id");
  333. }
  334. }
  335. /**
  336. * A function used to manually launch all queued tripal jobs
  337. *
  338. * @param $do_parallel
  339. * A boolean indicating whether jobs should be attempted to run in parallel
  340. *
  341. * @param $job_id
  342. * To launch a specific job provide the job id. This option should be
  343. * used sparingly as the jobs queue managment system should launch jobs
  344. * based on order and priority. However there are times when a specific
  345. * job needs to be launched and this argument will allow it. Only jobs
  346. * which have not been run previously will run.
  347. *
  348. * @ingroup tripal_jobs_api
  349. */
  350. function tripal_launch_job($do_parallel = 0, $job_id = NULL) {
  351. // first check if any jobs are currently running
  352. // if they are, don't continue, we don't want to have
  353. // more than one job script running at a time
  354. if (!$do_parallel and tripal_is_job_running()) {
  355. print "Jobs are still running. Use the --parallel=1 option with the Drush command to run jobs in parallel.";
  356. return;
  357. }
  358. // get all jobs that have not started and order them such that
  359. // they are processed in a FIFO manner.
  360. if ($job_id) {
  361. $sql = "SELECT * FROM {tripal_jobs} TJ " .
  362. "WHERE TJ.start_time IS NULL and TJ.end_time IS NULL and TJ.job_id = :job_id " .
  363. "ORDER BY priority ASC,job_id ASC";
  364. $job_res = db_query($sql, array(':job_id' => $job_id));
  365. }
  366. else {
  367. $sql = "SELECT * FROM {tripal_jobs} TJ " .
  368. "WHERE TJ.start_time IS NULL and TJ.end_time IS NULL " .
  369. "ORDER BY priority ASC,job_id ASC";
  370. $job_res = db_query($sql);
  371. }
  372. foreach ($job_res as $job) {
  373. // set the start time for this job
  374. $record = new stdClass();
  375. $record->job_id = $job->job_id;
  376. $record->start_time = REQUEST_TIME;
  377. $record->status = 'Running';
  378. $record->pid = getmypid();
  379. drupal_write_record('tripal_jobs', $record, 'job_id');
  380. // call the function provided in the callback column.
  381. // Add the job_id as the last item in the list of arguments. All
  382. // callback functions should support this argument.
  383. $callback = $job->callback;
  384. // arguments for jobs used to be stored as plain string with a double colon
  385. // separating them. But as of Tripal v2.0 the arguments are stored as
  386. // a serialized array. To be backwards compatible, we should check for serialization
  387. // and if not then we will use the old style
  388. $args = unserialize($job->arguments);
  389. if (!$args) {
  390. $args = explode("::", $job->arguments);
  391. }
  392. $args[] = $job->job_id;
  393. // We need to do some additional processing for printing since the switch
  394. // to serialized arrays now allows nested arrays which cause errors when
  395. // printed using implode alone.
  396. $string_args = array();
  397. foreach ($args as $k => $a) {
  398. if (is_array($a)) {
  399. $string_args[$k] = 'Array';
  400. }
  401. elseif (is_object($a)) {
  402. $string_args[$k] = 'Object';
  403. }
  404. else {
  405. $string_args[$k] = $a;
  406. }
  407. }
  408. print "Calling: $callback(" . implode(", ", $string_args) . ")\n";
  409. call_user_func_array($callback, $args);
  410. // set the end time for this job
  411. $record->end_time = REQUEST_TIME;
  412. $record->status = 'Completed';
  413. $record->progress = '100';
  414. drupal_write_record('tripal_jobs', $record, 'job_id');
  415. // send an email to the user advising that the job has finished
  416. }
  417. }
  418. /**
  419. * An internal function for setting the progress for a current job
  420. *
  421. * @param $job_id
  422. * The job_id to set the progress for
  423. * @param $percentage
  424. * The progress to set the job to
  425. *
  426. * @return
  427. * True on success and False otherwise
  428. *
  429. * @ingroup tripal_core
  430. */
  431. function tripal_set_job_progress($job_id, $percentage) {
  432. if (preg_match("/^(\d+|100)$/", $percentage)) {
  433. $record = new stdClass();
  434. $record->job_id = $job_id;
  435. $record->progress = $percentage;
  436. if (drupal_write_record('tripal_jobs', $record, 'job_id')) {
  437. return TRUE;
  438. }
  439. }
  440. return FALSE;
  441. }
  442. /**
  443. * Returns a list of jobs that are active.
  444. *
  445. * @param $modulename
  446. * Limit the list returned to those that were added by a specific module. If
  447. * no module name is provided then all active jobs are returned.
  448. *
  449. * @return
  450. * An array of objects where each object describes a tripal job. If no
  451. * jobs were found then an empty array is returned. Each object will have
  452. * the following members:
  453. * - job_id: The unique ID number for the job.
  454. * - uid: The ID of the user that submitted the job.
  455. * - job_name: The human-readable name of the job.
  456. * - modulename: The name of the module that submitted the job.
  457. * - callback: The callback function to be called when the job is run.
  458. * - arguments: An array of arguments to be passed to the callback function.
  459. * - progress: The percent progress of completion if the job is running.
  460. * - status: The status of the job: Waiting, Completed, Running or Cancelled.
  461. * - submit_date: The UNIX timestamp when the job was submitted.
  462. * - start_time: The UNIX timestamp for when the job started running.
  463. * - end_time: The UNIX timestampe when the job completed running.
  464. * - error_msg: Any error message that occured during execution of the job.
  465. * - prirotiy: The execution priority of the job (value between 1 and 10)
  466. *
  467. * @ingroup tripal_jobs_api
  468. */
  469. function tripal_get_active_jobs($modulename = NULL) {
  470. $query = db_select('tripal_jobs', 'TJ')
  471. ->fields('TJ', array('job_id', 'uid', 'job_name', 'modulename', 'callback',
  472. 'arguments', 'progress', 'status', 'submit_date', 'start_time',
  473. 'end_time', 'error_msg', 'priority'));
  474. if ($modulename) {
  475. $query->where(
  476. "TJ.modulename = :modulename and NOT (TJ.status = 'Completed' or TJ.status = 'Cancelled')",
  477. array(':modulename' => $modulename)
  478. );
  479. }
  480. $results = $query->execute();
  481. $jobs = array();
  482. while($job = $results->fetchobject()) {
  483. $jobs->arguments = unserialize($job->arguments);
  484. $jobs[] = $job;
  485. }
  486. return $jobs;
  487. }
  488. /**
  489. * Returns the date the job was added to the queue
  490. *
  491. * @param $job
  492. * An object describing the job
  493. *
  494. * @return
  495. * The date teh job was submitted
  496. *
  497. * @ingroup tripal_jobs_api
  498. */
  499. function tripal_get_job_submit_date($job) {
  500. return format_date($job->submit_date);
  501. }