tripal_core.jobs.api.inc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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. foreach ($includes as $include) {
  86. require_once($include);
  87. }
  88. if (!function_exists($callback)) {
  89. watchdog('tripal', "Must provide a valid callback function to the tripal_add_job() function.", 'error');
  90. return FALSE;
  91. }
  92. if (!is_numeric($uid)) {
  93. watchdog('tripal', "Must provide a numeric \$uid argument to the tripal_add_job() function.", 'error');
  94. return FALSE;
  95. }
  96. if (!$priority or !is_numeric($priority) or $priority < 1 or $priority > 10) {
  97. watchdog('tripal', "Must provide a numeric \$priority argument between 1 and 10 to the tripal_add_job() function.", 'error');
  98. return FALSE;
  99. }
  100. if (!is_array($arguments)) {
  101. watchdog('tripal', "Must provide an array as the \$arguments argument to the tripal_add_job() function.", 'error');
  102. return FALSE;
  103. }
  104. $user = user_load($uid);
  105. // convert the arguments into a string for storage in the database
  106. $args = array();
  107. if (is_array($arguments)) {
  108. $args = serialize($arguments);
  109. }
  110. $job_id = db_insert('tripal_jobs')
  111. ->fields(array(
  112. 'job_name' => $job_name,
  113. 'modulename' => $modulename,
  114. 'callback' => $callback,
  115. 'status' => 'Waiting',
  116. 'submit_date' => REQUEST_TIME,
  117. 'uid' => $uid,
  118. # The lower the number the higher the priority.
  119. 'priority' => $priority,
  120. 'arguments' => $args,
  121. ))
  122. ->execute();
  123. if ($job_id) {
  124. drupal_set_message(t("Job '%job_name' submitted.", array('%job_name' => $job_name)));
  125. if (user_access('administer tripal')) {
  126. $jobs_url = url("admin/tripal/tripal_jobs");
  127. drupal_set_message(t("Check the <a href='!jobs_url'>jobs page</a> for status.",
  128. array('!jobs_url' => $jobs_url)));
  129. drupal_set_message(t("You can execute the job queue manually on the command line " .
  130. "using the following Drush command: <br>drush trp-run-jobs --username=%uname --root=%base_path",
  131. array('%base_path' => DRUPAL_ROOT, '%uname' => $user->name)));
  132. }
  133. }
  134. else {
  135. drupal_set_message(t("Failed to add job: %job_name.", array('%job_name' => $job_name)), 'error');
  136. }
  137. return $job_id;
  138. }
  139. /**
  140. * Retrieve information regarding a tripal job
  141. *
  142. * @param $job_id
  143. * The unique identifier of the job
  144. *
  145. * @return
  146. * An object describing the job if a job is found or FALSE on failure.
  147. *
  148. * @ingroup tripal_jobs_api
  149. */
  150. function tripal_get_job($job_id) {
  151. if (!$job_id or !is_numeric($job_id)) {
  152. watchdog('tripal', "Must provide a numeric \$job_id to the tripal_cancel_job() function.");
  153. return FALSE;
  154. }
  155. $job = db_query('SELECT j.* FROM {tripal_jobs} j WHERE j.job_id=:job_id', array(':job_id' => $job_id))
  156. ->fetchObject();
  157. $job->submit_date_string = format_date($job->submit_date);
  158. $job->start_time_string = format_date($job->start_time);
  159. $job->end_time_string = format_date($job->end_time);
  160. return $job;
  161. }
  162. /**
  163. * Indicates if any jobs are running.
  164. *
  165. * This function will check the system to see if a job has a process ID
  166. * and if that process ID is still running. It will update the job status
  167. * accordingly before returning.
  168. *
  169. * @return
  170. * Returns TRUE if any job is running or FALSE otherwise.
  171. *
  172. * @ingroup tripal_jobs_api
  173. */
  174. function tripal_is_job_running() {
  175. // iterate through each job that has not ended
  176. // and see if it is still running. If it is not
  177. // running but does not have an end_time then
  178. // set the end time and set the status to 'Error'
  179. $sql = "SELECT * FROM {tripal_jobs} TJ " .
  180. "WHERE TJ.end_time IS NULL and NOT TJ.start_time IS NULL ";
  181. $jobs = db_query($sql);
  182. foreach ($jobs as $job) {
  183. $status = shell_exec('ps -p ' . escapeshellarg($job->pid) . ' -o pid=');
  184. if ($job->pid && $status) {
  185. // the job is still running so let it go
  186. // we return 1 to indicate that a job is running
  187. return TRUE;
  188. }
  189. else {
  190. // the job is not running so terminate it
  191. $record = new stdClass();
  192. $record->job_id = $job->job_id;
  193. $record->end_time = REQUEST_TIME;
  194. $record->status = 'Error';
  195. $record->error_msg = 'Job has terminated unexpectedly.';
  196. drupal_write_record('tripal_jobs', $record, 'job_id');
  197. }
  198. }
  199. // return 1 to indicate that no jobs are currently running.
  200. return FALSE;
  201. }
  202. /**
  203. * Returns the start time for a given job
  204. *
  205. * @param $job
  206. * An object describing the job
  207. *
  208. * @return
  209. * The start time of the job if it was already run and either "Cancelled" or "Not Yet Started" otherwise
  210. *
  211. * @ingroup tripal_jobs_api
  212. */
  213. function tripal_get_job_start($job) {
  214. if ($job->start_time > 0) {
  215. $start = format_date($job->start_time);
  216. }
  217. else {
  218. if (strcmp($job->job_status, 'Cancelled')==0) {
  219. $start = 'Cancelled';
  220. }
  221. else {
  222. $start = 'Not Yet Started';
  223. }
  224. }
  225. return $start;
  226. }
  227. /**
  228. * Returns the end time for a given job
  229. *
  230. * @param $job
  231. * An object describing the job
  232. *
  233. * @return
  234. * The end time of the job if it was already run and empty otherwise
  235. *
  236. * @ingroup tripal_jobs_api
  237. */
  238. function tripal_get_job_end($job) {
  239. if ($job->end_time > 0) {
  240. $end = format_date($job->end_time);
  241. }
  242. else {
  243. $end = '';
  244. }
  245. return $end;
  246. }
  247. /**
  248. * Set a job to be re-ran (ie: add it back into the job queue)
  249. *
  250. * @param $job_id
  251. * The job_id of the job to be re-ran
  252. * @param $goto_jobs_page
  253. * If set to TRUE then after the re run job is added Drupal will redirect to the jobs page
  254. *
  255. * @ingroup tripal_jobs_api
  256. */
  257. function tripal_rerun_job($job_id, $goto_jobs_page = TRUE) {
  258. global $user;
  259. $user_id = $user->uid;
  260. $sql = "SELECT * FROM {tripal_jobs} WHERE job_id = :job_id";
  261. $results = db_query($sql, array(':job_id' => $job_id));
  262. $job = $results->fetchObject();
  263. // arguments for jobs used to be stored as plain string with a double colon
  264. // separating them. But as of Tripal v2.0 the arguments are stored as
  265. // a serialized array. To be backwards compatible, we should check for serialization
  266. // and if not then we will use the old style
  267. $args = unserialize($job->arguments);
  268. if (!$args) {
  269. $args = explode("::", $job->arguments);
  270. }
  271. $job_id = tripal_add_job($job->job_name, $job->modulename, $job->callback, $args, $user_id, $job->priority);
  272. if ($goto_jobs_page) {
  273. drupal_goto("admin/tripal/tripal_jobs");
  274. }
  275. return $job_id;
  276. }
  277. /**
  278. * Cancel a Tripal Job currently waiting in the job queue
  279. *
  280. * @param $job_id
  281. * The job_id of the job to be cancelled
  282. *
  283. * @return
  284. * FALSE if the an error occured or the job could not be canceled, TRUE
  285. * otherwise.
  286. *
  287. * @ingroup tripal_jobs_api
  288. */
  289. function tripal_cancel_job($job_id, $redirect = TRUE) {
  290. if (!$job_id or !is_numeric($job_id)) {
  291. watchdog('tripal', "Must provide a numeric \$job_id to the tripal_cancel_job() function.");
  292. return FALSE;
  293. }
  294. $sql = "SELECT * FROM {tripal_jobs} WHERE job_id = :job_id";
  295. $results = db_query($sql, array(':job_id' => $job_id));
  296. $job = $results->fetchObject();
  297. // set the end time for this job
  298. if ($job->start_time == 0) {
  299. $record = new stdClass();
  300. $record->job_id = $job->job_id;
  301. $record->end_time = REQUEST_TIME;
  302. $record->status = 'Cancelled';
  303. $record->progress = '0';
  304. drupal_write_record('tripal_jobs', $record, 'job_id');
  305. drupal_set_message(t("Job #%job_id cancelled", array('%job_id' => $job_id)));
  306. }
  307. else {
  308. drupal_set_message(t("Job %job_id cannot be cancelled. It is in progress or has finished.", array('%job_id' => $job_id)));
  309. }
  310. if ($redirect) {
  311. drupal_goto("admin/tripal/tripal_jobs");
  312. }
  313. }
  314. /**
  315. * Execute a specific Tripal Job.
  316. *
  317. * @param $job_id
  318. * The job id to be exeuted
  319. * @param bool $redirect [optional]
  320. * Whether to redirect to the job page or not
  321. */
  322. function tripal_execute_job($job_id, $redirect = TRUE) {
  323. $sql = "SELECT * FROM {tripal_jobs} WHERE job_id = :job_id";
  324. $results = db_query($sql, array(':job_id' => $job_id));
  325. $job = $results->fetchObject();
  326. // set the end time for this job
  327. if ($job->start_time == 0 and $job->end_time == 0) {
  328. tripal_launch_job(1, $job_id);
  329. drupal_set_message(t("Job %job_id has finished executing. See below for more information.", array('%job_id' => $job_id)));
  330. }
  331. else {
  332. drupal_set_message(t("Job %job_id cannot be executed. It has already finished.", array('%job_id' => $job_id)));
  333. }
  334. if ($redirect) {
  335. drupal_goto("admin/tripal/tripal_jobs/view/$job_id");
  336. }
  337. }
  338. /**
  339. * A function used to manually launch all queued tripal jobs
  340. *
  341. * @param $do_parallel
  342. * A boolean indicating whether jobs should be attempted to run in parallel
  343. *
  344. * @param $job_id
  345. * To launch a specific job provide the job id. This option should be
  346. * used sparingly as the jobs queue managment system should launch jobs
  347. * based on order and priority. However there are times when a specific
  348. * job needs to be launched and this argument will allow it. Only jobs
  349. * which have not been run previously will run.
  350. *
  351. * @ingroup tripal_jobs_api
  352. */
  353. function tripal_launch_job($do_parallel = 0, $job_id = NULL) {
  354. // first check if any jobs are currently running
  355. // if they are, don't continue, we don't want to have
  356. // more than one job script running at a time
  357. if (!$do_parallel and tripal_is_job_running()) {
  358. print "Jobs are still running. Use the --parallel=1 option with the Drush command to run jobs in parallel.";
  359. return;
  360. }
  361. // get all jobs that have not started and order them such that
  362. // they are processed in a FIFO manner.
  363. if ($job_id) {
  364. $sql = "SELECT * FROM {tripal_jobs} TJ " .
  365. "WHERE TJ.start_time IS NULL and TJ.end_time IS NULL and TJ.job_id = :job_id " .
  366. "ORDER BY priority ASC,job_id ASC";
  367. $job_res = db_query($sql, array(':job_id' => $job_id));
  368. }
  369. else {
  370. $sql = "SELECT * FROM {tripal_jobs} TJ " .
  371. "WHERE TJ.start_time IS NULL and TJ.end_time IS NULL " .
  372. "ORDER BY priority ASC,job_id ASC";
  373. $job_res = db_query($sql);
  374. }
  375. foreach ($job_res as $job) {
  376. // set the start time for this job
  377. $record = new stdClass();
  378. $record->job_id = $job->job_id;
  379. $record->start_time = REQUEST_TIME;
  380. $record->status = 'Running';
  381. $record->pid = getmypid();
  382. drupal_write_record('tripal_jobs', $record, 'job_id');
  383. // call the function provided in the callback column.
  384. // Add the job_id as the last item in the list of arguments. All
  385. // callback functions should support this argument.
  386. $callback = $job->callback;
  387. // arguments for jobs used to be stored as plain string with a double colon
  388. // separating them. But as of Tripal v2.0 the arguments are stored as
  389. // a serialized array. To be backwards compatible, we should check for serialization
  390. // and if not then we will use the old style
  391. $args = unserialize($job->arguments);
  392. if (!$args) {
  393. $args = explode("::", $job->arguments);
  394. }
  395. $args[] = $job->job_id;
  396. // We need to do some additional processing for printing since the switch
  397. // to serialized arrays now allows nested arrays which cause errors when
  398. // printed using implode alone.
  399. $string_args = array();
  400. foreach ($args as $k => $a) {
  401. if (is_array($a)) {
  402. $string_args[$k] = 'Array';
  403. }
  404. elseif (is_object($a)) {
  405. $string_args[$k] = 'Object';
  406. }
  407. else {
  408. $string_args[$k] = $a;
  409. }
  410. }
  411. print "Calling: $callback(" . implode(", ", $string_args) . ")\n";
  412. call_user_func_array($callback, $args);
  413. // set the end time for this job
  414. $record->end_time = REQUEST_TIME;
  415. $record->status = 'Completed';
  416. $record->progress = '100';
  417. drupal_write_record('tripal_jobs', $record, 'job_id');
  418. // send an email to the user advising that the job has finished
  419. }
  420. }
  421. /**
  422. * An internal function for setting the progress for a current job
  423. *
  424. * @param $job_id
  425. * The job_id to set the progress for
  426. * @param $percentage
  427. * The progress to set the job to
  428. *
  429. * @return
  430. * True on success and False otherwise
  431. *
  432. * @ingroup tripal_core
  433. */
  434. function tripal_set_job_progress($job_id, $percentage) {
  435. if (preg_match("/^(\d+|100)$/", $percentage)) {
  436. $record = new stdClass();
  437. $record->job_id = $job_id;
  438. $record->progress = $percentage;
  439. if (drupal_write_record('tripal_jobs', $record, 'job_id')) {
  440. return TRUE;
  441. }
  442. }
  443. return FALSE;
  444. }
  445. /**
  446. * Returns a list of jobs that are active.
  447. *
  448. * @param $modulename
  449. * Limit the list returned to those that were added by a specific module. If
  450. * no module name is provided then all active jobs are returned.
  451. *
  452. * @return
  453. * An array of objects where each object describes a tripal job. If no
  454. * jobs were found then an empty array is returned. Each object will have
  455. * the following members:
  456. * - job_id: The unique ID number for the job.
  457. * - uid: The ID of the user that submitted the job.
  458. * - job_name: The human-readable name of the job.
  459. * - modulename: The name of the module that submitted the job.
  460. * - callback: The callback function to be called when the job is run.
  461. * - arguments: An array of arguments to be passed to the callback function.
  462. * - progress: The percent progress of completion if the job is running.
  463. * - status: The status of the job: Waiting, Completed, Running or Cancelled.
  464. * - submit_date: The UNIX timestamp when the job was submitted.
  465. * - start_time: The UNIX timestamp for when the job started running.
  466. * - end_time: The UNIX timestampe when the job completed running.
  467. * - error_msg: Any error message that occured during execution of the job.
  468. * - prirotiy: The execution priority of the job (value between 1 and 10)
  469. *
  470. * @ingroup tripal_jobs_api
  471. */
  472. function tripal_get_active_jobs($modulename = NULL) {
  473. $query = db_select('tripal_jobs', 'TJ')
  474. ->fields('TJ', array('job_id', 'uid', 'job_name', 'modulename', 'callback',
  475. 'arguments', 'progress', 'status', 'submit_date', 'start_time',
  476. 'end_time', 'error_msg', 'priority'));
  477. if ($modulename) {
  478. $query->where(
  479. "TJ.modulename = :modulename and NOT (TJ.status = 'Completed' or TJ.status = 'Cancelled')",
  480. array(':modulename' => $modulename)
  481. );
  482. }
  483. $results = $query->execute();
  484. $jobs = array();
  485. while($job = $results->fetchobject()) {
  486. $jobs->arguments = unserialize($job->arguments);
  487. $jobs[] = $job;
  488. }
  489. return $jobs;
  490. }
  491. /**
  492. * Returns the date the job was added to the queue
  493. *
  494. * @param $job
  495. * An object describing the job
  496. *
  497. * @return
  498. * The date teh job was submitted
  499. *
  500. * @ingroup tripal_jobs_api
  501. */
  502. function tripal_get_job_submit_date($job) {
  503. return format_date($job->submit_date);
  504. }