forked from postalsys/emailengine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
1232 lines (1038 loc) · 39.1 KB
/
server.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
require('dotenv').config();
try {
process.chdir(__dirname);
} catch (err) {
// ignore
}
process.title = 'emailengine';
const os = require('os');
process.env.UV_THREADPOOL_SIZE =
process.env.UV_THREADPOOL_SIZE && !isNaN(process.env.UV_THREADPOOL_SIZE) ? Number(process.env.UV_THREADPOOL_SIZE) : Math.max(os.cpus().length, 4);
// cache before wild-config
const argv = process.argv.slice(2);
const logger = require('./lib/logger');
const packageData = require('./package.json');
const pathlib = require('path');
const { Worker, SHARE_ENV } = require('worker_threads');
const { redis, queueConf } = require('./lib/db');
const promClient = require('prom-client');
const fs = require('fs').promises;
const crypto = require('crypto');
const Joi = require('joi');
const { settingsSchema } = require('./lib/schemas');
const settings = require('./lib/settings');
const tokens = require('./lib/tokens');
const { QueueScheduler } = require('bullmq');
const config = require('wild-config');
const getSecret = require('./lib/get-secret');
const { getDuration, getByteSize, getBoolean, getWorkerCount, selectRendezvousNode, checkLicense, checkForUpgrade, setLicense } = require('./lib/tools');
const { MAX_DAYS_STATS, MESSAGE_NEW_NOTIFY, MESSAGE_DELETED_NOTIFY, CONNECT_ERROR_NOTIFY, REDIS_PREFIX } = require('./lib/consts');
const msgpack = require('msgpack5')();
config.service = config.service || {};
config.workers = config.workers || {
imap: 4,
webhooks: 1,
submit: 1
};
config.dbs = config.dbs || {
redis: 'redis://127.0.0.1:6379/8'
};
config.log = config.log || {
level: 'trace'
};
config.api = config.api || {
port: 3000,
host: '127.0.0.1'
};
config.smtp = config.smtp || {
enabled: false,
port: 2525,
host: '127.0.0.1',
secret: '',
proxy: false
};
const DEFAULT_EENGINE_TIMEOUT = 10 * 1000;
const EENGINE_TIMEOUT = getDuration(process.env.EENGINE_TIMEOUT || config.service.commandTimeout) || DEFAULT_EENGINE_TIMEOUT;
const DEFAULT_MAX_ATTACHMENT_SIZE = 5 * 1024 * 1024;
config.api.maxSize = getByteSize(process.env.EENGINE_MAX_SIZE || config.api.maxSize) || DEFAULT_MAX_ATTACHMENT_SIZE;
config.dbs.redis = process.env.EENGINE_REDIS || process.env.REDIS_URL || config.dbs.redis;
config.workers.imap = getWorkerCount(process.env.EENGINE_WORKERS || config.workers.imap) || 4;
config.workers.webhooks = Number(process.env.EENGINE_WORKERS_WEBHOOKS) || config.workers.webhooks || 1;
config.workers.submit = Number(process.env.EENGINE_WORKERS_SUBMIT) || config.workers.submit || 1;
config.api.port = (process.env.EENGINE_PORT && Number(process.env.EENGINE_PORT)) || (process.env.PORT && Number(process.env.PORT)) || config.api.port;
config.api.host = process.env.EENGINE_HOST || config.api.host;
config.log.level = process.env.EENGINE_LOG_LEVEL || config.log.level;
// legacy options, will be removed in the future
const SMTP_ENABLED = 'EENGINE_SMTP_ENABLED' in process.env ? getBoolean(process.env.EENGINE_SMTP_ENABLED) : getBoolean(config.smtp.enabled);
const SMTP_SECRET = process.env.EENGINE_SMTP_SECRET || config.smtp.secret;
const SMTP_PORT = (process.env.EENGINE_SMTP_PORT && Number(process.env.EENGINE_SMTP_PORT)) || Number(config.smtp.port) || 2525;
const SMTP_HOST = process.env.EENGINE_SMTP_HOST || config.smtp.host || '127.0.0.1';
const SMTP_PROXY = 'EENGINE_SMTP_PROXY' in process.env ? getBoolean(process.env.EENGINE_SMTP_PROXY) : getBoolean(config.smtp.proxy);
const API_PROXY = 'EENGINE_API_PROXY' in process.env ? getBoolean(process.env.EENGINE_API_PROXY) : getBoolean(config.api.proxy);
logger.info({
msg: 'Starting EmailEngine',
version: packageData.version,
node: process.versions.node,
uvThreadpoolSize: Number(process.env.UV_THREADPOOL_SIZE),
workersImap: config.workers.imap,
workersWebhooks: config.workers.webhooks,
workersSubmission: config.workers.submit
});
const NO_ACTIVE_HANDLER_RESP = {
error: 'No active handler for requested account. Try again later.',
statusCode: 503
};
// check for upgrades once in 8 hours
const CHECK_UPGRADE_TIMEOUT = 8 * 3600 * 1000;
const LICENSE_CHECK_TIMEOUT = 15 * 60 * 1000;
const licenseInfo = {
active: false,
details: false,
type: packageData.license
};
let notifyScheduler;
let submitScheduler;
let preparedSettings = false;
const preparedSettingsString = process.env.EENGINE_SETTINGS || config.settings;
if (preparedSettingsString) {
// received a configuration block
try {
const { error, value } = Joi.object(settingsSchema).validate(JSON.parse(preparedSettingsString), {
abortEarly: false,
stripUnknown: true,
convert: true
});
if (error) {
throw error;
}
preparedSettings = value;
} catch (err) {
logger.error({ msg: 'Received invalid settings string', input: preparedSettingsString, err });
process.exit(1);
}
}
let preparedToken = false;
const preparedTokenString = process.env.EENGINE_PREPARED_TOKEN || config.preparedToken;
if (preparedTokenString) {
try {
preparedToken = msgpack.decode(Buffer.from(preparedTokenString, 'base64url'));
if (!preparedToken || !/^[0-9a-f]{64}$/i.test(preparedToken.id)) {
throw new Error('Invalid token format');
}
} catch (err) {
logger.error({ msg: 'Received invalid token string', input: preparedTokenString, err });
process.exit(1);
}
}
let preparedPassword = false;
const preparedPasswordString = process.env.EENGINE_PREPARED_PASSWORD || config.preparedPassword;
if (preparedPasswordString) {
try {
preparedPassword = Buffer.from(preparedPasswordString, 'base64url').toString();
if (!preparedPassword || preparedPassword.indexOf('$pbkdf2') !== 0) {
throw new Error('Invalid password format');
}
} catch (err) {
logger.error({ msg: 'Received invalid password string', input: preparedPasswordString, err });
process.exit(1);
}
}
const metrics = {
threadStarts: new promClient.Counter({
name: 'thread_starts',
help: 'Number of started threads'
}),
threadStops: new promClient.Counter({
name: 'thread_stops',
help: 'Number of stopped threads'
}),
apiCall: new promClient.Counter({
name: 'api_call',
help: 'Number of API calls',
labelNames: ['method', 'statusCode', 'route']
}),
imapConnections: new promClient.Gauge({
name: 'imap_connections',
help: 'Current IMAP connection state',
labelNames: ['status']
}),
webhooks: new promClient.Counter({
name: 'webhooks',
help: 'Webhooks sent',
labelNames: ['status', 'event']
}),
events: new promClient.Counter({
name: 'events',
help: 'Events fired',
labelNames: ['event']
}),
webhook_req: new promClient.Histogram({
name: 'webhook_req',
help: 'Duration of webhook requests',
buckets: [100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000, 60 * 1000]
}),
queues: new promClient.Gauge({
name: 'queue_size',
help: 'Queue size',
labelNames: ['queue']
})
};
let callQueue = new Map();
let mids = 0;
let closing = false;
let assigning = false;
let unassigned = false;
let assigned = new Map();
let unassignCounter = new Map();
let workerAssigned = new WeakMap();
let onlineWorkers = new WeakSet();
let workers = new Map();
let availableIMAPWorkers = new Set();
let suspendedWorkerTypes = new Set();
const postMessage = (worker, payload, ignoreOffline, transferList) => {
if (!onlineWorkers.has(worker)) {
if (ignoreOffline) {
return false;
}
throw new Error('Requested worker thread not available');
}
return worker.postMessage(payload, transferList);
};
const countUnassignment = async account => {
if (!unassignCounter.has(account)) {
unassignCounter.set(account, []);
}
let arr = unassignCounter.get(account);
arr.push(Date.now());
if (arr.length > 10) {
arr = arr.slice(-10);
unassignCounter.set(account, arr);
}
let delay = 0;
if (arr.length === 1) {
delay = 0;
} else {
let lastDelay = arr[arr.length - 1] - arr[arr.length - 2];
// if last delay was longer than a minute, then reset
if (lastDelay >= 60 * 1000) {
delay = 0;
} else {
delay = Math.min(Math.ceil(lastDelay * 1.5), 60 * 1000);
}
}
await redis.hset(`${REDIS_PREFIX}iad:${account}`, 'state', 'disconnected');
for (let worker of workers.get('api')) {
let callPayload = {
cmd: 'change',
account,
type: 'state',
key: 'disconnected',
payload: null
};
try {
postMessage(worker, callPayload, true);
} catch (err) {
logger.error({ msg: 'Failed to post state change to child', worker: worker.threadId, callPayload, err });
}
}
if (delay) {
await new Promise(resolve => setTimeout(resolve, delay));
return true;
} else {
return false;
}
};
let clearUnassignmentCounter = account => {
unassignCounter.delete(account);
};
let updateSmtpServerState = async (state, payload) => {
await redis.hset(`${REDIS_PREFIX}smtp`, 'state', state);
if (payload) {
await redis.hset(`${REDIS_PREFIX}smtp`, 'payload', JSON.stringify(payload));
}
if (workers.has('api')) {
for (let worker of workers.get('api')) {
let callPayload = {
cmd: 'change',
type: 'smtpServerState',
key: state,
payload: payload || null
};
try {
postMessage(worker, callPayload, true);
} catch (err) {
logger.error({ msg: 'Failed to post state change to child', worker: worker.threadId, callPayload, err });
}
}
}
};
let spawnWorker = async type => {
if (closing) {
return;
}
if (!workers.has(type)) {
workers.set(type, new Set());
}
if (suspendedWorkerTypes.has(type)) {
if (type === 'smtp') {
await updateSmtpServerState('suspended', {});
}
return;
}
if (type === 'smtp') {
let smtpEnabled = await settings.get('smtpServerEnabled');
if (!smtpEnabled) {
await updateSmtpServerState('disabled', {});
return;
}
await updateSmtpServerState('spawning');
}
let worker = new Worker(pathlib.join(__dirname, 'workers', `${type}.js`), {
argv,
env: SHARE_ENV,
trackUnmanagedFds: true
});
metrics.threadStarts.inc();
workers.get(type).add(worker);
worker.on('online', () => {
if (type === 'smtp') {
updateSmtpServerState('initializing').catch(err => logger.error({ msg: 'Failed to update smtp server state', err }));
}
onlineWorkers.add(worker);
});
let exitHandler = async exitCode => {
onlineWorkers.delete(worker);
metrics.threadStops.inc();
workers.get(type).delete(worker);
if (type === 'smtp') {
updateSmtpServerState(suspendedWorkerTypes.has(type) ? 'suspended' : 'exited');
}
if (type === 'imap') {
availableIMAPWorkers.delete(worker);
if (workerAssigned.has(worker)) {
let accountList = workerAssigned.get(worker);
workerAssigned.delete(worker);
accountList.forEach(account => {
assigned.delete(account);
let shouldReassign = false;
// graceful reconnect
countUnassignment(account)
.then(sr => {
shouldReassign = sr;
})
.catch(() => {
shouldReassign = true;
})
.finally(() => {
unassigned.add(account);
if (shouldReassign) {
assignAccounts().catch(err => logger.error(err));
}
});
});
}
}
if (closing) {
return;
}
// spawning a new worker trigger reassign
if (suspendedWorkerTypes.has(type)) {
logger.info({ msg: 'Worker thread closed', exitCode, type });
} else {
logger.error({ msg: 'Worker exited', exitCode, type });
}
// trigger new spawn
await new Promise(r => setTimeout(r, 1000));
await spawnWorker(type);
};
worker.on('exit', exitCode => {
exitHandler(exitCode).catch(err => {
logger.error({ msg: 'Failed to handle worker exit', exitCode, worker: worker.threadId, err });
});
});
worker.on('message', message => {
if (!message) {
return;
}
if (message.cmd === 'resp' && message.mid && callQueue.has(message.mid)) {
let { resolve, reject, timer } = callQueue.get(message.mid);
clearTimeout(timer);
callQueue.delete(message.mid);
if (message.error) {
let err = new Error(message.error);
if (message.code) {
err.code = message.code;
}
if (message.statusCode) {
err.statusCode = message.statusCode;
}
return reject(err);
} else {
return resolve(message.response);
}
}
if (message.cmd === 'call' && message.mid) {
return onCommand(worker, message.message)
.then(response => {
let callPayload = {
cmd: 'resp',
mid: message.mid,
response
};
try {
postMessage(worker, callPayload);
} catch (err) {
logger.error({ msg: 'Failed to post state change to child', worker: worker.threadId, callPayload, err });
}
})
.catch(err => {
let callPayload = {
cmd: 'resp',
mid: message.mid,
error: err.message,
code: err.code,
statusCode: err.statusCode
};
try {
postMessage(worker, callPayload);
} catch (err) {
logger.error({ msg: 'Failed to post state change to child', worker: worker.threadId, callPayload, err });
}
});
}
switch (message.cmd) {
case 'metrics': {
let statUpdateKey = false;
switch (message.key) {
// gather for dashboard counter
case 'webhooks': {
let { status } = message.args[0] || {};
statUpdateKey = `${message.key}:${status}`;
break;
}
case 'webhook_req': {
break;
}
case 'events': {
let { event } = message.args[0] || {};
switch (event) {
case MESSAGE_NEW_NOTIFY:
case MESSAGE_DELETED_NOTIFY:
case CONNECT_ERROR_NOTIFY:
statUpdateKey = `${message.key}:${event}`;
break;
}
break;
}
case 'apiCall': {
let { statusCode } = message.args[0] || {};
let success = statusCode >= 200 && statusCode < 300;
statUpdateKey = `${message.key}:${success ? 'success' : 'fail'}`;
break;
}
}
if (statUpdateKey) {
// increment counter in redis
let now = new Date();
// we keep a separate hash value for each ISO day
let dateStr = `${now
.toISOString()
.substr(0, 10)
.replace(/[^0-9]+/g, '')}`;
// hash key for bucket
let timeStr = `${now
.toISOString()
// bucket includes 1 minute
.substr(0, 16)
.replace(/[^0-9]+/g, '')}`;
let hkey = `${REDIS_PREFIX}stats:${statUpdateKey}:${dateStr}`;
redis
.multi()
.hincrby(hkey, timeStr, 1)
.sadd(`${REDIS_PREFIX}stats:keys`, statUpdateKey)
// keep alive at most 2 days
.expire(hkey, MAX_DAYS_STATS + 1 * 24 * 3600)
.exec()
.catch(() => false);
}
if (message.key && metrics[message.key] && typeof metrics[message.key][message.method] === 'function') {
metrics[message.key][message.method](...message.args);
}
return;
}
case 'settings':
availableIMAPWorkers.forEach(worker => {
try {
postMessage(worker, message);
} catch (err) {
logger.error({ msg: 'Failed to post command to child', worker: worker.threadId, callPayload: message, err });
}
});
return;
case 'change':
switch (message.type) {
case 'smtpServerState':
updateSmtpServerState(message.key, message.payload).catch(err => logger.error({ msg: 'Failed to update smtp server state', err }));
break;
default:
// forward all state changes to the API worker
for (let worker of workers.get('api')) {
try {
postMessage(worker, message, true);
} catch (err) {
logger.error({ msg: 'Failed to post state change to child', worker: worker.threadId, callPayload: message, err });
}
}
}
break;
}
switch (type) {
case 'imap':
return processImapWorkerMessage(worker, message);
}
});
};
function processImapWorkerMessage(worker, message) {
if (!message || !message.cmd) {
logger.debug({ msg: 'Unexpected message', type: 'imap', message });
return;
}
switch (message.cmd) {
case 'ready':
availableIMAPWorkers.add(worker);
// assign pending accounts
assignAccounts().catch(err => logger.error(err));
break;
}
}
async function call(worker, message, transferList) {
return new Promise((resolve, reject) => {
let mid = `${Date.now()}:${++mids}`;
let timer = setTimeout(() => {
let err = new Error('Timeout waiting for command response [T1]');
err.statusCode = 504;
err.code = 'Timeout';
err.payload = message;
reject(err);
}, message.timeout || EENGINE_TIMEOUT);
callQueue.set(mid, { resolve, reject, timer });
try {
postMessage(
worker,
{
cmd: 'call',
mid,
message
},
false,
transferList
);
} catch (err) {
callQueue.delete(mid);
return reject(err);
}
});
}
async function assignAccounts() {
if (assigning) {
return false;
}
assigning = true;
try {
if (!unassigned) {
// first run
// list all available accounts and assign to worker threads
let accounts = await redis.smembers(`${REDIS_PREFIX}ia:accounts`);
unassigned = new Set(accounts);
}
if (!availableIMAPWorkers.size || !unassigned.size) {
// nothing to do here
return;
}
for (let account of unassigned) {
if (!availableIMAPWorkers.size) {
// out of workers
break;
}
let worker = selectRendezvousNode(account, Array.from(availableIMAPWorkers));
if (!workerAssigned.has(worker)) {
workerAssigned.set(worker, new Set());
}
workerAssigned.get(worker).add(account);
assigned.set(account, worker);
unassigned.delete(account);
await call(worker, {
cmd: 'assign',
account
});
}
} finally {
assigning = false;
}
}
let licenseCheckTimer = false;
let licenseCheckHandler = async () => {
if (licenseInfo.active && licenseInfo.details && licenseInfo.details.expires && new Date(licenseInfo.details.expires).getTime() < Date.now()) {
// clear expired license
logger.info({ msg: 'License expired', license: licenseInfo.details });
licenseInfo.active = false;
licenseInfo.details = false;
}
if (!licenseInfo.active && !suspendedWorkerTypes.size) {
logger.info({ msg: 'No active license, shutting down workers after 15 minutes of activity' });
for (let type of ['imap', 'submit', 'smtp', 'webhooks']) {
suspendedWorkerTypes.add(type);
if (workers.has(type)) {
for (let worker of workers.get(type).values()) {
worker.terminate();
}
}
}
} else {
if (licenseInfo.active && suspendedWorkerTypes.size) {
// re-enable missing workers
for (let type of suspendedWorkerTypes) {
suspendedWorkerTypes.delete(type);
switch (type) {
case 'smtp':
if (SMTP_ENABLED) {
// single SMTP interface worker
await spawnWorker('smtp');
}
break;
default:
if (config.workers && config.workers[type]) {
for (let i = 0; i < config.workers[type]; i++) {
await spawnWorker(type);
}
}
}
}
}
licenseCheckTimer = setTimeout(checkActiveLicense, LICENSE_CHECK_TIMEOUT);
licenseCheckTimer.unref();
}
};
function checkActiveLicense() {
clearTimeout(licenseCheckTimer);
licenseCheckHandler().catch(err => {
logger.error('Failed to process license checker', err);
});
}
let processCheckUpgrade = async () => {
try {
let updateInfo = await checkForUpgrade();
if (updateInfo.canUpgrade) {
logger.info({ msg: 'Found an upgrade for EmailEngine', updateInfo });
updateInfo.checked = Date.now();
await redis.hset(`${REDIS_PREFIX}settings`, 'upgrade', JSON.stringify(updateInfo));
} else {
await redis.hdel(`${REDIS_PREFIX}settings`, 'upgrade');
}
} catch (err) {
logger.error({ msg: 'Failed to check updates', err });
}
};
let upgradeCheckTimer = false;
let upgradeCheckHandler = async () => {
let upgradeInfoExists = await redis.hexists(`${REDIS_PREFIX}settings`, 'upgrade');
if (!upgradeInfoExists) {
// nothing to do here
return;
}
await processCheckUpgrade();
upgradeCheckTimer = setTimeout(checkUpgrade, CHECK_UPGRADE_TIMEOUT);
licenseCheckTimer.unref();
};
function checkUpgrade() {
clearTimeout(upgradeCheckTimer);
upgradeCheckHandler().catch(err => {
logger.error('Failed to process upgrade check', err);
});
}
async function updateQueueCounters() {
for (let queue of ['notify', 'submit']) {
const [resActive, resDelayed] = await redis.multi().llen(`${REDIS_PREFIX}bull:${queue}:active`).zcard(`${REDIS_PREFIX}bull:${queue}:delayed`).exec();
if (resActive[0] || resDelayed[0]) {
// counting failed
logger.error({ msg: 'Failed to count queue length', queue, active: resActive, delayed: resDelayed });
return false;
}
metrics.queues.set({ queue: `${queue}_active` }, Number(resActive[1]) || 0);
metrics.queues.set({ queue: `${queue}_delayed` }, Number(resDelayed[1]) || 0);
}
}
async function onCommand(worker, message) {
switch (message.cmd) {
case 'metrics':
await updateQueueCounters();
return promClient.register.metrics();
case 'structuredMetrics': {
let connections = {};
for (let key of Object.keys(metrics.imapConnections.hashMap)) {
if (key.indexOf('status:') === 0) {
let metric = metrics.imapConnections.hashMap[key];
connections[metric.labels.status] = metric.value;
}
}
return { connections };
}
case 'license':
if (!licenseInfo.active && suspendedWorkerTypes.size) {
return Object.assign({}, licenseInfo, { suspended: true });
}
return licenseInfo;
case 'updateLicense': {
try {
const licenseFile = message.license;
let licenseData = await checkLicense(licenseFile);
if (!licenseData) {
throw new Error('Failed to verify provided license');
}
logger.info({ msg: 'Loaded license', license: licenseData, source: 'API' });
await setLicense(licenseData, licenseFile);
licenseInfo.active = true;
licenseInfo.details = licenseData;
licenseInfo.type = 'EmailEngine License';
// re-enable workers
checkActiveLicense();
return licenseInfo;
} catch (err) {
logger.fatal({ msg: 'Failed to verify provided license', source: 'API', err });
return false;
}
}
case 'removeLicense': {
try {
await redis.hdel(`${REDIS_PREFIX}settings`, 'license');
licenseInfo.active = false;
licenseInfo.details = false;
licenseInfo.type = packageData.license;
return licenseInfo;
} catch (err) {
logger.fatal({ msg: 'Failed to remove existing license', err });
return false;
}
}
case 'new':
unassigned.add(message.account);
assignAccounts().catch(err => logger.error(err));
return;
case 'delete':
unassigned.delete(message.account); // if set
clearUnassignmentCounter(message.account);
if (assigned.has(message.account)) {
let assignedWorker = assigned.get(message.account);
if (workerAssigned.has(assignedWorker)) {
workerAssigned.get(assignedWorker).delete(message.account);
if (!workerAssigned.get(assignedWorker).size) {
// last item in the worker accounts
workerAssigned.delete(assignedWorker);
}
}
call(assignedWorker, message)
.then(() => logger.debug('worker processed'))
.catch(err => logger.error(err));
}
return;
case 'update':
if (assigned.has(message.account)) {
let assignedWorker = assigned.get(message.account);
call(assignedWorker, message)
.then(() => logger.debug('worker processed'))
.catch(err => logger.error(err));
}
return;
case 'smtpReload':
{
let hasWorkers = workers.has('smtp') && workers.get('smtp').size;
// reload (or kill) SMTP submission worker
if (hasWorkers) {
for (let worker of workers.get('smtp').values()) {
worker.terminate();
}
} else {
let smtpEnabled = await settings.get('smtpServerEnabled');
if (smtpEnabled) {
// spawn a new worker
await spawnWorker('smtp');
}
}
}
break;
case 'listMessages':
case 'buildContacts':
case 'getRawMessage':
case 'getText':
case 'getMessage':
case 'updateMessage':
case 'moveMessage':
case 'deleteMessage':
case 'createMailbox':
case 'deleteMailbox':
case 'submitMessage':
case 'queueMessage':
case 'uploadMessage':
case 'getAttachment': {
if (!assigned.has(message.account)) {
return NO_ACTIVE_HANDLER_RESP;
}
let assignedWorker = assigned.get(message.account);
let transferList = [];
if (['getRawMessage', 'getAttachment'].includes(message.cmd) && message.port) {
transferList.push(message.port);
}
if (['submitMessage', 'queueMessage'].includes(message.cmd) && typeof message.raw === 'object') {
transferList.push(message.raw);
}
return await call(assignedWorker, message, transferList);
}
}
return 999;
}
let metricsResult = {};
async function collectMetrics() {
// reset all counters
Object.keys(metricsResult || {}).forEach(key => {
metricsResult[key] = 0;
});
if (workers.has('imap')) {
let imapWorkers = workers.get('imap');
for (let imapWorker of imapWorkers) {
if (!availableIMAPWorkers.has(imapWorker)) {
// worker not available yet
continue;
}
try {
let workerStats = await call(imapWorker, { cmd: 'countConnections' });
Object.keys(workerStats || {}).forEach(status => {
if (!metricsResult[status]) {
metricsResult[status] = 0;
}
metricsResult[status] += Number(workerStats[status]) || 0;
});
} catch (err) {
logger.error(err);
}
}
}
Object.keys(metricsResult).forEach(status => {
metrics.imapConnections.set({ status }, metricsResult[status]);
});
}
const closeQueues = cb => {
let proms = [];
if (notifyScheduler) {
proms.push(notifyScheduler.close());
}
if (submitScheduler) {
proms.push(submitScheduler.close());
}
if (!proms.length) {
return setImmediate(() => cb());
}
let returned;
let closeTimeout = setTimeout(() => {
clearTimeout(closeTimeout);
if (returned) {
return;
}
returned = true;
cb();