2020-06-10 20:36:54 +00:00
|
|
|
//
|
|
|
|
// Copyright 2020 DxOS.org
|
|
|
|
//
|
|
|
|
|
2020-06-10 22:15:07 +00:00
|
|
|
import { spawnSync } from 'child_process';
|
2020-06-10 20:36:54 +00:00
|
|
|
|
|
|
|
class LogCache {
|
2020-06-11 04:47:42 +00:00
|
|
|
constructor (maxLines = 500) {
|
2020-06-10 20:36:54 +00:00
|
|
|
// Sets in JS iterate in insertion order.
|
|
|
|
this.buffer = new Set();
|
|
|
|
this.maxLines = maxLines;
|
|
|
|
}
|
|
|
|
|
2020-06-11 04:47:42 +00:00
|
|
|
append (lines) {
|
2020-06-10 20:36:54 +00:00
|
|
|
const added = [];
|
|
|
|
for (const line of lines) {
|
|
|
|
if (!this.buffer.has(line)) {
|
|
|
|
this.buffer.add(line);
|
|
|
|
added.push(line);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (this.buffer.size > this.maxLines) {
|
|
|
|
this.buffer = new Set(Array.from(this.buffer).slice(parseInt(this.maxLines / 2)));
|
|
|
|
}
|
|
|
|
|
|
|
|
return added;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const _caches = new Map();
|
2020-06-10 22:56:08 +00:00
|
|
|
|
2020-06-10 20:36:54 +00:00
|
|
|
const getLogCache = (name) => {
|
|
|
|
let cache = _caches.get(name);
|
|
|
|
if (!cache) {
|
|
|
|
cache = new LogCache();
|
|
|
|
_caches.set(name, cache);
|
|
|
|
}
|
|
|
|
return cache;
|
2020-06-11 04:47:42 +00:00
|
|
|
};
|
2020-06-10 20:36:54 +00:00
|
|
|
|
2020-06-10 22:56:08 +00:00
|
|
|
const getLogs = async (name, incremental = false, lines = 100) => {
|
2020-06-10 20:36:54 +00:00
|
|
|
const command = 'wire';
|
|
|
|
const args = ['service', 'logs', '--lines', lines, name];
|
|
|
|
|
|
|
|
const child = spawnSync(command, args, { encoding: 'utf8' });
|
|
|
|
const logLines = child.stdout.split(/\n/);
|
|
|
|
const cache = getLogCache(name);
|
2020-06-11 04:47:42 +00:00
|
|
|
const added = cache.append(logLines);
|
2020-06-10 22:56:08 +00:00
|
|
|
|
|
|
|
return incremental ? added : Array.from(cache.buffer);
|
2020-06-10 20:36:54 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export const logResolvers = {
|
|
|
|
Query: {
|
2020-06-11 05:28:19 +00:00
|
|
|
logs: async (_, { service, incremental }) => {
|
|
|
|
const lines = await getLogs(service, incremental);
|
2020-06-10 20:36:54 +00:00
|
|
|
return {
|
|
|
|
timestamp: new Date().toUTCString(),
|
2020-06-11 04:47:42 +00:00
|
|
|
json: JSON.stringify({ incremental, lines })
|
2020-06-10 20:36:54 +00:00
|
|
|
};
|
2020-06-11 21:22:19 +00:00
|
|
|
}
|
2020-06-10 20:36:54 +00:00
|
|
|
}
|
|
|
|
};
|