ondemand.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. const config = require("fourier-common").config;
  2. const db = require("fourier-common").fbconn.database();
  3. const spawn = require("child_process").spawn;
  4. const path = require("path");
  5. const express = require('express');
  6. var working = false;
  7. var queue = {};
  8. var od_ref = db.ref("devices").child(config.device_id).child("ondemand");
  9. var proc;
  10. function process_queue() {
  11. if (working) return;
  12. working = true;
  13. //var key = Object.keys(queue)[0];
  14. //if (!key) return;
  15. //var job = queue[key];
  16. //delete queue[key];
  17. var job = queue.shift();
  18. if(!job) {
  19. console.log("nothing left to do");
  20. working = false;
  21. return;
  22. }
  23. var key = job.key;
  24. if (job.status == "done" || job.status === "no_index") {
  25. setTimeout(() => {
  26. working = false;
  27. process_queue();
  28. }, 1000);
  29. return;
  30. }
  31. od_ref.child(key).update({status: "in_progress"});
  32. var params = [
  33. path.join(config.installDir,"fourier/process_timespan_nodb.py"),
  34. config.device_id,
  35. job.station,
  36. job.fromTime,
  37. job.toTime,
  38. job.ad,
  39. key,
  40. ];
  41. if (job.ads) params.push(job.ads.join(","));
  42. console.log("ondemand: " + params.join(" "));
  43. proc = spawn("python", params);
  44. proc.stdout.on("data", data => {
  45. console.log("ondemand data: " + data);
  46. });
  47. proc.stderr.on("data", data => {
  48. console.log("ondemand error: " + data);
  49. });
  50. proc.on("exit", code => {
  51. working = false;
  52. proc = null;
  53. if (code == 2) {
  54. od_ref.child(key).update({status: "no_index"});
  55. } else {
  56. od_ref.child(key).update({status: "done"});
  57. }
  58. console.log("done", key);
  59. process_queue();
  60. });
  61. }
  62. function addAndProc(key, job) {
  63. //queue[key] = job;
  64. queue.push(job);
  65. job.key = key;
  66. process_queue();
  67. }
  68. function start() {
  69. queue = [];
  70. od_ref.on("child_added", snp => {
  71. console.log("added", snp.key);
  72. addAndProc(snp.key, snp.val());
  73. });
  74. //od_ref.on("child_changed", snp => {
  75. // addAndProc(snp.key, snp.val());
  76. //});
  77. }
  78. endpoint.get('/info', function(request, response) {
  79. response.send(JSON.stringify({
  80. 'version': version,
  81. 'processID': process.id,
  82. 'memoryUsage': process.memoryUsage().rss
  83. }));
  84. });
  85. endpoint.listen(49223);
  86. function stop() {
  87. od_ref.off();
  88. queue = {};
  89. }
  90. module.exports = {
  91. start: start,
  92. stop: stop,
  93. };