creeperxtsread.js 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* eslint-disable strict */
  2. const _ = require('lodash');
  3. const moment = require('moment');
  4. const { CrudService } = require('naf-framework-mongoose/lib/service');
  5. class CreeperxtsreadService extends CrudService {
  6. async creeper() {
  7. // 链接linux服务器
  8. console.log('进入读取取回的文本文件');
  9. // await this.sshcon();
  10. await this.top();
  11. await this.qnodes();
  12. console.log('读取取回的文本文件结束');
  13. }
  14. async top() {
  15. const redis = this.app.redis;
  16. const text = await redis.get('top');
  17. const arr = text.split('\\r\\n');
  18. for (const rl of arr) {
  19. const strsplit = rl.split(' ');
  20. const strs = _.pull(strsplit, '');
  21. if (_.isNaN(parseInt(strs[0]))) continue;
  22. const newdata = {};
  23. newdata.pid = strs[0];
  24. newdata.user = strs[1];
  25. newdata.pr = strs[2];
  26. newdata.ni = strs[3];
  27. newdata.virt = strs[4];
  28. newdata.res = strs[5];
  29. newdata.shr = strs[6];
  30. newdata.s = strs[7];
  31. newdata.cpu = strs[8];
  32. newdata.mem = strs[9];
  33. newdata.time = strs[10];
  34. newdata.command = strs[11];
  35. if (newdata.pid && newdata.pid !== '0' && newdata.user && newdata.user !== '0') {
  36. await this.ctx.model.Top.create(newdata);
  37. }
  38. }
  39. }
  40. async qnodes() {
  41. const nowdate = moment().format('YYYY-MM-DD');
  42. const redis = this.app.redis;
  43. const text = await redis.get('qnodes');
  44. let lineList = text.split('\\r\\n');
  45. // res,去掉前两行和最后一行
  46. lineList = _.drop(lineList, 2);
  47. lineList = _.dropRight(lineList, 1);
  48. const arr = [];
  49. if (_.isArray(lineList)) {
  50. const match = /^(gpu|cu)(\d+)$/i;
  51. // 规律,当line符合 cuxx(数字)或gpuxx(数字) 时,之后的行数就是集群属性,直到 line === ''时截止,再扫到条件1的时候又是开始
  52. let obj = {};
  53. for (let line of lineList) {
  54. if (line.match(match)) {
  55. // 找到开始
  56. obj.node = _.trim(line);
  57. } else if (line === '') {
  58. // 找到结束,推进去,重置
  59. obj.time = nowdate;
  60. arr.push(_.cloneDeep(obj));
  61. obj = {};
  62. } else {
  63. line = _.trim(line);
  64. const arr = line.split(',');
  65. for (const i of arr) {
  66. const iarr = i.split('=');
  67. if (iarr && iarr.length >= 2) {
  68. obj[_.trim(iarr[0])] = _.trim(iarr[1]);
  69. }
  70. }
  71. }
  72. }
  73. }
  74. await this.ctx.model.Qnodes.insertMany(arr);
  75. await this.toMq(arr);
  76. }
  77. async toMq(data) {
  78. if (this.ctx.mq) {
  79. const exchange = 'service_count';
  80. const routerKey = 'nodes';
  81. const parm = { durable: true };
  82. await this.ctx.mq.fanout(exchange, routerKey, JSON.stringify(data), parm);
  83. }
  84. }
  85. }
  86. module.exports = CreeperxtsreadService;