-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cluster.service.ts
136 lines (120 loc) · 3.92 KB
/
cluster.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import {
Injectable,
Logger,
OnApplicationBootstrap,
OnApplicationShutdown
} from '@nestjs/common';
import Democracy, { Node } from 'democracy';
import { Advertisement, Browser, Service } from 'mdns';
import _ from 'lodash';
import * as os from 'os';
import { NetworkInterfaceInfo } from 'os';
import { ConfigService } from '../config/config.service';
import { ClusterConfig } from './cluster.config';
let mdns;
try {
mdns = require('mdns');
} catch (e) {
mdns = undefined;
}
@Injectable()
export class ClusterService extends Democracy
implements OnApplicationBootstrap, OnApplicationShutdown {
private readonly configService: ConfigService;
private readonly config: ClusterConfig;
private readonly logger: Logger;
private advertisement: Advertisement;
private browser: Browser;
private networkInterfaces: NetworkInterfaceInfo[];
constructor(configService: ConfigService) {
const config = configService.get('cluster');
const networkInterfaces = _.flatMap<NetworkInterfaceInfo>(
config.networkInterface
? os.networkInterfaces()[config.networkInterface]
: os.networkInterfaces()
);
const ip = networkInterfaces.find(
address => address.internal === false && address.family === 'IPv4'
).address;
super({
source: `${ip}:${config.port}`,
peers: Array.from(config.peerAddresses),
timeout: config.timeout * 1000,
weight: config.weight
});
this.networkInterfaces = networkInterfaces;
this.configService = configService;
this.config = config;
this.logger = new Logger(ClusterService.name);
}
onApplicationBootstrap(): any {
if (this.config.autoDiscovery) {
if (mdns !== undefined) {
this.startBonjourDiscovery();
} else {
this.logger.warn(
'Dependency "mdns" was not found, automatic discovery has been disabled. You will have to provide the addresses of other room-assistant nodes manually in the config.'
);
}
}
this.on('added', this.handleNodeAdded);
this.on('removed', this.handleNodeRemoved);
this.on('elected', this.handleNodeElected);
}
onApplicationShutdown(): any {
this.advertisement?.stop();
this.browser?.stop();
}
protected startBonjourDiscovery(): void {
this.advertisement = mdns.createAdvertisement(
mdns.udp('room-assistant'),
this.config.port,
{
networkInterface: this.config.networkInterface
}
);
const sequence = [
mdns.rst.DNSServiceResolve(),
'DNSServiceGetAddrInfo' in mdns.dns_sd
? mdns.rst.DNSServiceGetAddrInfo()
: mdns.rst.getaddrinfo({ families: [0] }),
mdns.rst.makeAddressesUnique()
];
this.browser = mdns.createBrowser(mdns.udp('room-assistant'), {
resolverSequence: sequence
});
this.browser.on('serviceUp', this.handleNodeDiscovery.bind(this));
this.browser.on('error', e => {
this.logger.error(e.message, e.trace);
});
this.logger.log('Starting mDNS advertisements and discovery');
this.advertisement.start();
this.browser.start();
}
private handleNodeDiscovery(service: Service): void {
const ownIps = this.networkInterfaces.map(info => info.address);
if (
_.some(service.addresses, address => ownIps.includes(address)) ||
_.some(this.options.peers, peer =>
service.addresses.some(
address => peer[0] === address && peer[1] === service.port.toString()
)
)
) {
return;
}
this.options.peers.push([service.addresses[0], service.port.toString()]);
this.hello();
}
private handleNodeAdded(node: Node): void {
this.logger.log(`Added ${node.source} to the cluster with id ${node.id}`);
}
private handleNodeRemoved(node: Node): void {
this.logger.log(
`Removed ${node.source} from the cluster with id ${node.id}`
);
}
private handleNodeElected(node: Node): void {
this.logger.log(`${node.id} has been elected as leader`);
}
}