query-runner.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2021 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. 'use strict';
  5. const child_process = require('child_process');
  6. const fs = require('fs');
  7. const os = require('os');
  8. const path = require('path');
  9. // QueryRunner uses the swarming binary to retrieve data from the swarming
  10. // servers.
  11. class QueryRunner {
  12. constructor(server) {
  13. this.swarming_server_ = server;
  14. this.bin_ = './tools/luci-go/swarming';
  15. }
  16. // Retrieves the list of tasks matching `tag`.
  17. retrieveTasks(tag, fields = [
  18. 'task_id', 'run_id', 'failure', 'state', 'tags'
  19. ]) {
  20. const cmds = [
  21. this.bin_, 'tasks', '-S', this.swarming_server_,
  22. `-field="items(${fields.join(',')})"`, `-tag="${tag}"`
  23. ];
  24. const output = child_process.execSync(cmds.join(' '));
  25. return JSON.parse(output.toString());
  26. }
  27. // Returns a promoise for a parsed JSON object from the contents in `filename`
  28. // for the specified `task_id`.
  29. retrieveJSONFile(task_id, filename) {
  30. // This is going to create some temp directory. So put this in a try/finally
  31. // block so that the temp directory gets cleaned up correctly.
  32. let temp_dir = undefined;
  33. try {
  34. temp_dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cr-fetch'));
  35. return this.retrieveFile_(task_id, filename, temp_dir);
  36. } catch (e) {
  37. console.error(e);
  38. } finally {
  39. if (temp_dir) {
  40. try {
  41. fs.rmdirSync(temp_dir, {recursive: true, force: false});
  42. } catch (e) {
  43. console.error(`Failed to cleanup temp directory at ${temp_dir}.`);
  44. console.error(e);
  45. }
  46. }
  47. }
  48. }
  49. retrieveFile_(task_id, filename, temp_dir) {
  50. return new Promise((resolve, reject) => {
  51. const cmds = [
  52. this.bin_, 'collect', '-S', this.swarming_server_,
  53. `-output-dir="${temp_dir}"`, task_id
  54. ];
  55. const output = child_process.exec(cmds.join(' '), () => {
  56. const filepath = path.join(temp_dir, task_id, filename);
  57. resolve(JSON.parse(fs.readFileSync(filepath).toString()));
  58. });
  59. });
  60. }
  61. };
  62. module.exports = {
  63. QueryRunner,
  64. };