444 lines
14 KiB
JavaScript
444 lines
14 KiB
JavaScript
const fs = require('fs');
|
|
const fsp = require('fs').promises;
|
|
const { URL } = require('url');
|
|
const http = require('http');
|
|
const https = require('https');
|
|
const crypto = require('crypto');
|
|
const zlib = require('zlib');
|
|
|
|
const ws = require('ws');
|
|
|
|
const EtcTree = require('./etctree.js');
|
|
|
|
class RequestError
|
|
{
|
|
constructor(code, text)
|
|
{
|
|
this.code = code;
|
|
this.message = text;
|
|
}
|
|
}
|
|
|
|
class AntiEtcd
|
|
{
|
|
constructor(cfg)
|
|
{
|
|
this.clients = {};
|
|
this.client_id = 1;
|
|
this.etctree = new EtcTree(true);
|
|
this.cfg = cfg;
|
|
this.stopped = false;
|
|
this.cfg.use_base64 = true;
|
|
}
|
|
|
|
async run()
|
|
{
|
|
if (this.cfg.filename)
|
|
{
|
|
// Load data from disk
|
|
const [ err, stat ] = await new Promise(ok => fs.stat(this.cfg.filename, (err, stat) => ok([ err, stat ])));
|
|
if (!err)
|
|
{
|
|
const data = await fsp.readFile(this.cfg.filename);
|
|
data = JSON.parse(zlib.Gunzip(data));
|
|
this.etctree.load(data);
|
|
}
|
|
else if (err.code != ENOENT)
|
|
{
|
|
throw err;
|
|
}
|
|
// Set exit hook
|
|
const on_stop_cb = () => this.on_stop();
|
|
process.on('SIGINT', on_stop_cb);
|
|
process.on('SIGTERM', on_stop_cb);
|
|
process.on('SIGQUIT', on_stop_cb);
|
|
}
|
|
if (this.cfg.cert)
|
|
{
|
|
this.tls = { key: await fsp.readFile(this.cfg.key), cert: await fsp.readFile(this.cfg.cert) };
|
|
this.server = https.createServer(this.tls, (req, res) => this.handleRequest(req, res));
|
|
}
|
|
else
|
|
{
|
|
this.server = http.createServer((req, res) => this.handleRequest(req, res));
|
|
}
|
|
this.wss = new ws.WebSocketServer({ server: this.server });
|
|
this.wss.on('connection', (conn, req) => this.startWebsocket(conn, req));
|
|
this.server.listen(this.cfg.port || 2379);
|
|
}
|
|
|
|
async on_stop()
|
|
{
|
|
if (this.stopped)
|
|
{
|
|
return;
|
|
}
|
|
this.stopped = true;
|
|
// Wait until all requests complete
|
|
while (this.inflight > 0)
|
|
{
|
|
await new Promise(ok => this.waitInflight.push(ok));
|
|
}
|
|
await this.persist();
|
|
}
|
|
|
|
async persist()
|
|
{
|
|
if (!this.cfg.filename)
|
|
{
|
|
return;
|
|
}
|
|
let dump = this.etctree.dump(true);
|
|
dump = JSON.stringify(dump);
|
|
dump = zlib.Gzip(dump);
|
|
const fd = await fsp.open(this.cfg.filename+'.tmp', 'w');
|
|
await fsp.write(fd, dump);
|
|
await fsp.fsync(fd);
|
|
await fsp.close(fd);
|
|
await fsp.rename(this.cfg.filename+'.tmp', this.cfg.filename);
|
|
}
|
|
|
|
fail(res, code, text)
|
|
{
|
|
res.writeHead(code);
|
|
res.write(text);
|
|
res.end();
|
|
}
|
|
|
|
handleRequest(req, res)
|
|
{
|
|
let data = [];
|
|
req.on('data', (chunk) => data.push(chunk));
|
|
req.on('end', async () =>
|
|
{
|
|
data = Buffer.concat(data);
|
|
let body = '';
|
|
let code = 200;
|
|
let reply;
|
|
try
|
|
{
|
|
if (req.headers['content-type'] != 'application/json')
|
|
{
|
|
throw new RequestError(400, 'content-type should be application/json');
|
|
}
|
|
body = data.toString();
|
|
try
|
|
{
|
|
data = data.length ? JSON.parse(data) : {};
|
|
}
|
|
catch (e)
|
|
{
|
|
throw new RequestError(400, 'body should be valid JSON');
|
|
}
|
|
if (!(data instanceof Object) || data instanceof Array)
|
|
{
|
|
throw new RequestError(400, 'body should be JSON object');
|
|
}
|
|
reply = await this.runHandler(req, data, res);
|
|
reply = JSON.stringify(reply);
|
|
}
|
|
catch (e)
|
|
{
|
|
if (e instanceof RequestError)
|
|
{
|
|
code = e.code;
|
|
reply = e.message;
|
|
}
|
|
else
|
|
{
|
|
console.error(e);
|
|
code = 500;
|
|
reply = 'Internal error: '+e.message;
|
|
}
|
|
}
|
|
try
|
|
{
|
|
// Access log
|
|
console.log(
|
|
new Date().toISOString()+
|
|
' '+(req.headers['x-forwarded-for'] || req.socket.remoteAddress)+
|
|
' '+req.method+' '+req.url+' '+code+'\n '+body.replace(/\n/g, '\\n')+
|
|
'\n '+reply.replace(/\n/g, '\\n')
|
|
);
|
|
// FIXME: Access log :req[X-Forwarded-For] [:date[clf]] pid=:pid ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" - :response-time ms
|
|
reply = Buffer.from(reply);
|
|
res.writeHead(200, {
|
|
'Content-Type': 'application/json',
|
|
'Content-Length': reply.length,
|
|
});
|
|
res.write(reply);
|
|
res.end();
|
|
}
|
|
catch (e)
|
|
{
|
|
console.error(e);
|
|
}
|
|
});
|
|
}
|
|
|
|
startWebsocket(socket, req)
|
|
{
|
|
const client_id = this.client_id++;
|
|
this.clients[client_id] = {
|
|
socket,
|
|
alive: true,
|
|
watches: {},
|
|
};
|
|
socket.on('pong', () => this.clients[client_id].alive = true);
|
|
socket.on('error', console.error);
|
|
const pinger = setInterval(() =>
|
|
{
|
|
if (!this.clients[client_id])
|
|
{
|
|
return;
|
|
}
|
|
if (!this.clients[client_id].alive)
|
|
{
|
|
return socket.terminate();
|
|
}
|
|
this.clients[client_id].alive = false;
|
|
socket.ping(() => {});
|
|
}, 30000);
|
|
socket.on('message', (msg) =>
|
|
{
|
|
try
|
|
{
|
|
msg = JSON.parse(msg);
|
|
}
|
|
catch (e)
|
|
{
|
|
socket.send(JSON.stringify({ error: 'bad-json' }));
|
|
return;
|
|
}
|
|
if (!msg)
|
|
{
|
|
socket.send(JSON.stringify({ error: 'empty-message' }));
|
|
}
|
|
else
|
|
{
|
|
this.handleMessage(client_id, msg, socket);
|
|
}
|
|
});
|
|
socket.on('close', () =>
|
|
{
|
|
this.unsubscribeClient(client_id);
|
|
clearInterval(pinger);
|
|
delete this.clients[client_id];
|
|
socket.terminate();
|
|
});
|
|
}
|
|
|
|
async runHandler(req, data, res)
|
|
{
|
|
// v3/kv/txn
|
|
// v3/kv/range
|
|
// v3/kv/put
|
|
// v3/kv/deleterange
|
|
// v3/lease/grant
|
|
// v3/lease/keepalive
|
|
// v3/lease/revoke O_o
|
|
// v3/kv/lease/revoke O_o
|
|
const requestUrl = new URL(req.url, 'http://'+(req.headers.host || 'localhost'));
|
|
if (requestUrl.pathname.substr(0, 4) == '/v3/')
|
|
{
|
|
const path = requestUrl.pathname.substr(4).replace(/\/+$/, '').replace(/\/+/g, '_');
|
|
const cb = this['handle_'+path];
|
|
if (cb)
|
|
{
|
|
if (req.method != 'POST')
|
|
{
|
|
throw new RequestError(405, 'Please use POST method');
|
|
}
|
|
return cb.call(this, data);
|
|
}
|
|
}
|
|
else if (requestUrl.pathname == '/dump')
|
|
{
|
|
return this.handle_dump(data);
|
|
}
|
|
throw new RequestError(404, 'Supported APIs: /v3/kv/txn, /v3/kv/range, /v3/kv/put, /v3/kv/deleterange, '+
|
|
'/v3/lease/grant, /v3/lease/revoke, /v3/kv/lease/revoke, /v3/lease/keepalive');
|
|
}
|
|
|
|
handle_kv_txn(data)
|
|
{
|
|
if (this.cfg.use_base64)
|
|
{
|
|
for (const item of data.compare||[])
|
|
{
|
|
if (item.key != null)
|
|
item.key = this.de64(item.key);
|
|
}
|
|
for (const items of [ data.success, data.failure ])
|
|
{
|
|
for (const item of items||[])
|
|
{
|
|
const req = item.request_range || item.requestRange ||
|
|
item.request_put || item.requestPut ||
|
|
item.request_delete_range || item.requestDeleteRange;
|
|
if (req.key != null)
|
|
req.key = this.de64(req.key);
|
|
if (req.range_end != null)
|
|
req.range_end = this.de64(req.range_end);
|
|
if (req.value != null)
|
|
req.value = this.de64(req.value);
|
|
}
|
|
}
|
|
}
|
|
const result = this.etctree.api_txn(data);
|
|
if (this.cfg.use_base64)
|
|
{
|
|
for (const item of result.responses||[])
|
|
{
|
|
if (item.response_range)
|
|
{
|
|
for (const kv of item.response_range.kvs)
|
|
{
|
|
if (kv.key != null)
|
|
kv.key = this.b64(kv.key);
|
|
if (kv.value != null)
|
|
kv.value = this.b64(kv.value);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
handle_kv_range(data)
|
|
{
|
|
const r = this.handle_kv_txn({ success: [ { request_range: data } ] });
|
|
return { header: r.header, ...r.responses[0].response_range };
|
|
}
|
|
|
|
handle_kv_put(data)
|
|
{
|
|
const r = this.handle_kv_txn({ success: [ { request_put: data } ] });
|
|
return { header: r.header, ...r.responses[0].response_put };
|
|
}
|
|
|
|
handle_kv_deleterange(data)
|
|
{
|
|
const r = this.handle_kv_txn({ success: [ { request_delete_range: data } ] });
|
|
return { header: r.header, ...r.responses[0].response_delete_range };
|
|
}
|
|
|
|
handle_lease_grant(data)
|
|
{
|
|
return this.etctree.api_grant_lease(data);
|
|
}
|
|
|
|
handle_lease_revoke(data)
|
|
{
|
|
return this.etctree.api_revoke_lease(data);
|
|
}
|
|
|
|
handle_kv_lease_revoke(data)
|
|
{
|
|
return this.etctree.api_revoke_lease(data);
|
|
}
|
|
|
|
handle_lease_keepalive(data)
|
|
{
|
|
return this.etctree.api_keepalive_lease(data);
|
|
}
|
|
|
|
handle_dump(data)
|
|
{
|
|
return this.etctree.dump();
|
|
}
|
|
|
|
handleMessage(client_id, msg, socket)
|
|
{
|
|
if (msg.create_request)
|
|
{
|
|
// FIXME progress_notify, filters, prev_kv
|
|
const create_request = msg.create_request;
|
|
if (!create_request.watch_id || !this.clients[client_id].watches[create_request.watch_id])
|
|
{
|
|
const req = { ...create_request, watch_id: null };
|
|
if (this.cfg.use_base64)
|
|
{
|
|
if (req.key != null)
|
|
req.key = this.de64(req.key);
|
|
if (req.range_end != null)
|
|
req.range_end = this.de64(req.range_end);
|
|
}
|
|
const watch = this.etctree.api_create_watch(req, (msg) => this.sendToSocket(socket, msg));
|
|
if (!watch.created)
|
|
{
|
|
socket.send(JSON.stringify({ result: { header: { revision: this.etctree.mod_revision }, watch_id: create_request.watch_id, ...watch } }));
|
|
}
|
|
else
|
|
{
|
|
create_request.watch_id ||= watch.watch_id;
|
|
this.clients[client_id].watches[create_request.watch_id] = watch.watch_id;
|
|
socket.send(JSON.stringify({ result: { header: { revision: this.etctree.mod_revision }, watch_id: create_request.watch_id, created: true } }));
|
|
}
|
|
}
|
|
}
|
|
else if (msg.cancel_request)
|
|
{
|
|
const mapped_id = this.clients[client_id].watches[msg.cancel_request.watch_id];
|
|
if (mapped_id)
|
|
{
|
|
this.etctree.api_cancel_watch({ watch_id: mapped_id });
|
|
delete this.clients[client_id].watches[msg.cancel_request.watch_id];
|
|
socket.send(JSON.stringify({ result: { header: { revision: this.etctree.mod_revision }, watch_id: msg.cancel_request.watch_id, canceled: true } }));
|
|
}
|
|
}
|
|
else if (msg.progress_request)
|
|
{
|
|
socket.send(JSON.stringify({ result: { header: { revision: this.etctree.mod_revision } } }));
|
|
}
|
|
}
|
|
|
|
sendToSocket(socket, msg)
|
|
{
|
|
if (this.cfg.use_base64 && msg.result && msg.result.events)
|
|
{
|
|
msg = { ...msg, result: { ...msg.result, events: msg.result.events.map(ev =>
|
|
{
|
|
if (ev.kv)
|
|
{
|
|
const kv = { ...ev.kv };
|
|
if (kv.key != null)
|
|
{
|
|
kv.key = this.b64(kv.key);
|
|
}
|
|
if (kv.value != null)
|
|
{
|
|
kv.value = this.b64(kv.value);
|
|
}
|
|
return { ...ev, kv };
|
|
}
|
|
return ev;
|
|
}) } };
|
|
}
|
|
socket.send(JSON.stringify(msg));
|
|
}
|
|
|
|
unsubscribeClient(client_id)
|
|
{
|
|
if (!this.clients[client_id])
|
|
return;
|
|
for (const watch_id in this.clients[client_id].watches)
|
|
{
|
|
const mapped_id = this.clients[client_id].watches[watch_id];
|
|
this.etctree.api_cancel_watch({ watch_id: mapped_id });
|
|
}
|
|
}
|
|
|
|
de64(k)
|
|
{
|
|
return Buffer.from(k, 'base64').toString();
|
|
}
|
|
|
|
b64(k)
|
|
{
|
|
return Buffer.from(k).toString('base64');
|
|
}
|
|
}
|
|
|
|
new AntiEtcd({ port: 12379 }).run().catch(console.error);
|