hello_world.agi 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. Hello World - the launcher
  3. Run this script (for example with the Serverless tool, or from Code
  4. Studio). It sends hello_world.job.agi to every usable node of the
  5. cluster, pinning one copy to each node with the "nodes" option, waits
  6. for the replies and returns them as one JSON document:
  7. {
  8. "cluster": "Home Lab",
  9. "replies": [ {message, node: {...}, health: {...}}, ... ],
  10. "skipped": [ {node, reason}, ... ]
  11. }
  12. Keep hello_world.job.agi in the same folder as this file; the script
  13. path below is relative to this launcher.
  14. */
  15. requirelib("cluster");
  16. //How long to wait for each node before giving up on it, in seconds
  17. var WAIT_SECONDS = 60;
  18. function main() {
  19. if (!cluster.inCluster()) {
  20. return { error: "This node is not part of a cluster. Create or join one in System Settings > Cluster Settings." };
  21. }
  22. var submitted = [];
  23. var skipped = [];
  24. //Send one job to each node that can take work right now
  25. var nodes = cluster.nodes();
  26. for (var i = 0; i < nodes.length; i++) {
  27. var n = nodes[i];
  28. if (n.state !== "ONLINE" && n.state !== "DEGRADED") {
  29. skipped.push({ node: n.name, reason: "node is " + n.state.toLowerCase() });
  30. continue;
  31. }
  32. try {
  33. var id = cluster.jobs.submit({
  34. name: "Hello World on " + n.name,
  35. script: "hello_world.job.agi",
  36. nodes: [n.id], //run on this node and nowhere else
  37. timeout: WAIT_SECONDS
  38. });
  39. submitted.push({ node: n.name, id: id });
  40. } catch (e) {
  41. skipped.push({ node: n.name, reason: String(e) });
  42. }
  43. }
  44. //The jobs run in parallel; collect the answers one by one
  45. var replies = [];
  46. for (var j = 0; j < submitted.length; j++) {
  47. var rec;
  48. try {
  49. rec = cluster.jobs.wait(submitted[j].id, WAIT_SECONDS);
  50. } catch (e) {
  51. //wait() throws when the job is still not finished
  52. rec = cluster.jobs.status(submitted[j].id);
  53. }
  54. if (rec.state.status === "succeeded") {
  55. replies.push(rec.state.output);
  56. } else {
  57. skipped.push({
  58. node: submitted[j].node,
  59. reason: "job " + rec.state.status + (rec.state.error ? ": " + rec.state.error : (rec.state.reason ? ": " + rec.state.reason : ""))
  60. });
  61. }
  62. }
  63. return {
  64. cluster: cluster.status().cluster.name,
  65. replies: replies,
  66. skipped: skipped
  67. };
  68. }
  69. sendJSONResp(JSON.stringify(main()));