systemquery/src/lib/agent/Agent.mjs

65 lines
1.7 KiB
JavaScript
Raw Normal View History

"use strict";
import fs from 'fs';
import os from 'os';
import path from 'path';
2022-01-09 16:30:42 +00:00
import log from '../io/NamespacedLog.mjs'; const l = log("agent");
2022-01-08 21:37:03 +00:00
import settings from '../../settings.mjs';
import PeerServer from './PeerServer.mjs';
import parse_peer_name from '../parse/peer_name.mjs';
2022-01-08 21:55:18 +00:00
import hostuuid from '../io/hostuuid.mjs';
class Agent {
constructor(config) {
this.config = config;
}
async find_secret() {
if(this.config.secret_join_filepath !== "CHANGE_ME") {
let filepath = path.resolve(
path.dirname(settings.cli.config),
this.config.secret_join_filepath
);
if(fs.existsSync(filepath))
return await fs.promises.readFile(filepath, "utf-8");
}
if(this.config.secret_join !== "CHANGE_ME")
return this.config.secret_join;
throw new Error(`Error: Failed to find join secret.`);
}
async init() {
/** Our peer id - calculated automatically from the system's uuid */
2022-01-09 00:57:06 +00:00
this.peer_id = await hostuuid(this.config.net.port);
this.peer_name = os.hostname();
this.server = new PeerServer(
this.peer_id,
await this.find_secret()
);
this.server.retries = this.config.net.peer_retries;
2022-01-09 16:30:42 +00:00
l.log(`Starting peer listener....`);
await this.server.listen(
this.config.net.port,
this.config.net.bind_address
);
2022-01-09 16:30:42 +00:00
l.log(`Listening on ${this.config.net.bind_address}:${this.config.net.port}`);
await this.server.add_peers(...this.config.peers.map(
peer => parse_peer_name(peer)
));
2022-01-09 17:02:26 +00:00
l.log(`Added ${this.server.peers().length} / ${this.config.peers.length} initial peers`);
if(this.config.peers.length < 1)
l.warn(`No initial peers were specified! It's recommended that you specify at least 1 on every host.`);
}
}
export default Agent;