tripal.jobs.api.inc 16 KB

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