-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
aedes.js
207 lines (177 loc) · 4.83 KB
/
aedes.js
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
'use strict'
const WebSocket = require('ws')
const tls = require('tls')
const http = require('http')
const net = require('net')
const aedes = require('aedes')
const { readFileSync } = require('fs')
const cluster = require('cluster')
const pMap = require('p-map')
const env = require('./env')
const DB = env[process.env.DB] || env.default
const noCluster = process.env.NO_CLUSTERS === 'true'
const persistence = require(DB.persistence.name)
const mqemitter = require(DB.mqemitter.name)
const servers = []
const isMasterCluster = cluster.isMaster && DB.clusters && !noCluster
process.send = process.send || function () { } // for testing
const ports = {
TLS: 8883,
WS: 4000,
TCP: 1883
}
const args = process.argv.filter(arg => ports[arg])
const options = {
key: readFileSync('./server.key'),
cert: readFileSync('./server.cert'),
rejectUnauthorized: false
}
function listen (server, proto) {
return new Promise((resolve, reject) => {
server.listen(ports[proto], (err) => {
if (err) reject(err)
else {
resolve()
}
})
})
}
function close (server) {
return new Promise((resolve, reject) => {
if (server.listening) {
server.close(function (err) {
if (err) reject(err)
else resolve()
})
} else {
resolve()
}
})
}
async function init () {
var broker = aedes({
id: 'BROKER_' + (cluster.isMaster ? 1 : cluster.worker.id),
persistence: persistence(DB.persistence.options),
mq: mqemitter(DB.mqemitter.options),
concurrency: 1000,
heartbeatInterval: 500
})
broker.authenticate = function (client, username, password, callback) {
var error = null
var success = true
if (username === 'user' && password.toString() === 'notallowed') {
error = new Error('Auth error')
error.returnCode = 4
}
callback(error, success)
}
broker.authorizePublish = function (client, packet, callback) {
if (packet.topic === 'not/allowed/to/publish') {
callback(Error('topic not allowed'))
} else {
callback(null)
}
}
broker.authorizeSubscribe = function (client, sub, callback) {
if (sub.topic === 'not/allowed/to/subscribe') {
callback(null, null) // will negate sub and return granted qos 128
} else {
callback(null, sub)
}
}
if (DB.waitForReady) {
await cleanPersistence(broker)
}
await createServers(broker.handle)
}
function cleanPersistence (broker) {
return new Promise((resolve, reject) => {
broker.persistence.once('ready', function () {
DB.cleanDb(broker.persistence, function (err) {
if (err) {
reject(err)
} else {
resolve()
}
})
})
})
}
async function createServers (aedesHandler) {
var protos = args && args.length > 0 ? args : ['TLS', 'WS', 'TCP']
for (let i = 0; i < protos.length; i++) {
if (protos[i] === 'TLS') {
servers.push(tls.createServer(options, aedesHandler))
} else if (protos[i] === 'WS') {
var server = http.createServer()
servers.push(server)
const ws = new WebSocket.Server({ server: server })
ws.on('connection', function (conn, req) {
const stream = WebSocket.createWebSocketStream(conn)
aedesHandler(stream, req)
})
} else if (protos[i] === 'TCP') {
servers.push(net.createServer(aedesHandler))
} else {
throw Error('Invalid protocol ' + protos[i])
}
}
await pMap(servers, (s, i) => listen(s, protos[i]), { concurrency: 1 })
process.send({ state: 'ready' })
}
process.on('SIGTERM', function () {
function onClose () {
if (cluster.isWorker) {
cluster.worker.kill()
} else {
process.send({ state: 'killed' })
process.exit(0)
}
}
if (isMasterCluster) {
for (const id in cluster.workers) {
cluster.workers[id].kill('SIGTERM')
}
} else {
pMap(servers, s => close(s), { concurrency: 1 })
.then(() => onClose()).catch((err) => {
console.error(err)
onClose()
})
}
})
if (isMasterCluster) {
const numWorkers = require('os').cpus().length
for (let i = 0; i < numWorkers; i++) {
cluster.fork(process.env)
}
cluster.on('message', function (worker, message) {
if (message.state === 'ready') {
cluster.workers[worker.id].isReady = true
var allReady = true
for (const id in cluster.workers) {
if (!cluster.workers[id].isReady) {
allReady = false
break
}
}
if (allReady) {
process.send({ state: 'ready' })
}
}
})
cluster.on('exit', function (worker, code, signal) {
if (Object.keys(cluster.workers).length === 0) {
if (process.connected) {
process.send({ state: 'killed' })
}
}
})
} else {
init()
.catch(error => {
console.log('Unable to start Aedes Broker')
console.error(error)
process.exit(1)
})
}