tripal_core.jobs.api.inc 15 KB

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