-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.js
1605 lines (1357 loc) · 50.5 KB
/
main.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';
/*
* Created with @iobroker/create-adapter v1.24.2
*/
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
const utils = require('@iobroker/adapter-core');
// Load your modules here, e.g.:
const NodeSSH = require('node-ssh').NodeSSH;
const csvToJson = require('csvtojson');
const words = require('./admin/words.js');
const ping = require('ping');
const { exception } = require('console');
let language = 'en';
let _ = null;
var requestInterval;
var requestIntervalUserCommand;
this.isAdapterStart = false;
class LinuxControl extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: 'linux-control',
});
this.on('ready', this.onReady.bind(this));
this.on('objectChange', this.onObjectChange.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
// this.on('message', this.onMessage.bind(this));
this.on('unload', this.onUnload.bind(this));
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
try {
// Initialize your adapter here
await this.prepareTranslation();
await this.setSelectableHosts()
this.isAdapterStart = true;
await Promise.allSettled(this.config.hosts.map((host) => this.refreshHost(host)));
this.isAdapterStart = false;
} catch (err) {
this.errorHandling(err, '[onReady]');
}
}
/**
* @param {object} host
*/
async refreshHost(host) {
if (host.enabled) {
this.log.info(`getting data from ${host.name} (${host.ip}:${host.port}${this.isAdapterStart ? ', Adapter start' : ''})`);
await this.createObjectButton(`${host.name}.refresh`, _('refreshHost'));
this.subscribeStates(`${host.name}.refresh`);
let connection = await this.getConnection(host);
await this.getInfos(connection, host);
if (connection) {
await this.createControls(host);
await this.distributionInfo(connection, host);
await this.updateInfos(connection, host);
await this.servicesInfo(connection, host);
await this.needrestart(connection, host);
await this.folderSizes(connection, host);
await this.userCommand(connection, host);
connection.dispose();
if (await this.getObjectAsync(`${host.name}.info.lastRefresh`)) {
await this.setStateAsync(`${host.name}.info.lastRefresh`, new Date().getTime(), true);
}
this.log.info(`successful received data from ${host.name} (${host.ip}:${host.port})`);
}
if (this.isAdapterStart) {
let objList = await this.getForeignObjectsAsync(`${this.namespace}.${host.name}.*`);
for (const id in objList) {
let obj = objList[id];
if (obj && obj.common && obj.common.role === 'button' && obj.common.type === 'boolean') {
this.subscribeStates(id);
this.debugHandling(`[refreshHost] ${host.name} (${host.ip}:${host.port}): button '${id}' subscribed`);
}
}
}
// interval using timeout
if (requestInterval) requestInterval = null;
if (host.interval && host.interval > 0) {
requestInterval = setTimeout(() => {
this.refreshHost(host);
}, host.interval * 60000);
} else {
this.log.info(`polling interval is deactivated for ${host.name} (${host.ip}:${host.port})`);
}
} else {
this.debugHandling(`getting data from ${host.name} (${host.ip}:${host.port}) -> not enabled!`);
}
}
/**
* @param {NodeSSH | undefined} connection
* @param {object} host
*/
async getInfos(connection, host) {
let logPrefix = `[getInfos] ${host.name} (${host.ip}:${host.port}):`;
const objects = require('./admin/lib/info.json');
if (this.config.whitelist && this.config.whitelist["info"] && this.config.whitelist["info"].length > 0 && !this.config.blacklistDatapoints[host.name].includes('info.all')) {
for (const propObj of objects) {
if (this.config.whitelist["info"].includes(propObj.id) && !this.config.blacklistDatapoints[host.name].includes(`info.${propObj.id}`)) {
let id = `${host.name.replace(' ', '_')}.info.${propObj.id}`;
if (propObj.id === "is_online") {
if (connection) {
await this.createObjectBoolean(id, propObj.name);
await this.setStateAsync(id, true, true);
} else {
await this.createObjectBoolean(id, propObj.name);
await this.setStateAsync(id, false, true);
}
} else if (propObj.id === "ip") {
await this.createObjectString(id, propObj.name);
await this.setStateAsync(id, host.ip, true);
} else {
if (propObj.type === 'number') {
await this.createObjectNumber(id, propObj.name);
}
}
} else {
await this.delMyObject(`${host.name.replace(' ', '_')}.info.${propObj.id}`, logPrefix);
}
}
} else {
if (this.isAdapterStart) {
this.debugHandling(`${logPrefix} no datapoints selected -> removing existing datapoints`);
for (const propObj of objects) {
await this.delMyObject(`${host.name.replace(' ', '_')}.info.${propObj.id}`);
}
}
}
}
//#region Command Functions
/**
* @param {NodeSSH | undefined} connection
* @param {object} host
*/
async userCommand(connection, host) {
let logPrefix = `[userCommand] ${host.name} (${host.ip}:${host.port}):`;
try {
/** @type {any[]} */
let commandsList = this.config.commands;
if (commandsList.length > 0) {
let commands = commandsList.filter(x => {
return x.host === host.name;
});
for (const cmd of commands) {
if (cmd.enabled) {
try {
if ((!cmd.interval || cmd.interval === 0) && cmd.type !== 'button') {
await this.userCommandExecute(connection, host, cmd);
} else {
if (this.isAdapterStart) {
// adapter first run -> execute userCommands with diffrent polling interval
if (cmd.type !== 'button') {
this.debugHandling(`${logPrefix} datapoint-id: ${cmd.name}, description: ${cmd.description}: first start of adapter -> run also command with diffrent polling interval configured`);
} else {
this.debugHandling(`${logPrefix} datapoint-id: ${cmd.name}, description: ${cmd.description}: create button`);
}
await this.userCommandExecute(connection, host, cmd);
} else {
if (cmd.type !== 'button') {
this.debugHandling(`${logPrefix} datapoint-id: ${cmd.name}, description: ${cmd.description}: diffrent polling interval configured`);
}
}
}
} catch (err) {
this.log.error(`${logPrefix} datapoint-id: ${cmd.name}, description: ${cmd.description}`);
// No Sentry error report for user commands
this.errorHandling(err, logPrefix);
}
} else {
this.debugHandling(`${logPrefix} datapoint-id: '${cmd.name}', description: '${cmd.description}' -> is not enabled!`);
}
}
}
} catch (err) {
this.errorHandling(err, logPrefix);
}
}
/**
* @param {NodeSSH | undefined} connection
* @param {object} host
* @param {object} cmd
*/
async userCommandExecute(connection, host, cmd) {
let logPrefix = `[userCommandExecute] ${host.name} (${host.ip}:${host.port}):`;
let establishedNewConnection = false;
try {
if (connection === undefined && cmd.interval && cmd.interval > 0 && cmd.type !== 'button') {
establishedNewConnection = true;
this.debugHandling(`[userCommandExecute] ${host.name} (${host.ip}:${host.port}, id: ${cmd.name}, description: ${cmd.description}): diffrent polling interval -> create connection`);
connection = await this.getConnection(host);
}
if (connection) {
let id = `${host.name.replace(' ', '_')}.${cmd.name}`;
if (cmd.type !== 'button') {
let response = await this.sendCommand(connection, host, `${cmd.command}`, `[userCommandExecute] ${host.name} (${host.ip}:${host.port}, id: ${cmd.name}, description: ${cmd.description}):`);
if (response) {
if (cmd.type === 'string') {
await this.createObjectString(id, cmd.description);
await this.setStateAsync(id, response, true);
} else if (cmd.type === 'number') {
await this.createObjectNumber(id, cmd.description, cmd.unit);
await this.setStateAsync(id, parseFloat(response), true);
} else if (cmd.type === 'boolean') {
await this.createObjectBoolean(id, cmd.description);
await this.setStateAsync(id, (response === 'true' || parseInt(response) === 1) ? true : false, true);
} else if (cmd.type === 'array') {
await this.createObjectArray(id, cmd.description);
await this.setStateAsync(id, JSON.parse(response), true);
}
} else {
if (await this.getObjectAsync(id)) {
if (cmd.type === 'string') {
await this.setStateAsync(id, "", true);
} else if (cmd.type === 'number') {
await this.setStateAsync(id, 0, true);
} else if (cmd.type === 'boolean') {
await this.setStateAsync(id, false, true);
} else if (cmd.type === 'array') {
await this.setStateAsync(id, null, true);
}
} else {
if (cmd.type === 'string') {
await this.createObjectString(id, cmd.description);
await this.setStateAsync(id, "", true);
} else if (cmd.type === 'number') {
await this.createObjectNumber(id, cmd.description, cmd.unit);
await this.setStateAsync(id, 0, true);
} else if (cmd.type === 'boolean') {
await this.createObjectBoolean(id, cmd.description);
await this.setStateAsync(id, false, true);
} else if (cmd.type === 'array') {
await this.createObjectArray(id, cmd.description);
await this.setStateAsync(id, null, true);
}
}
}
} else {
await this.createObjectButton(id, cmd.description);
this.subscribeStates(id);
}
if (establishedNewConnection) {
this.debugHandling(`[userCommandExecute] ${host.name} (${host.ip}:${host.port}, id: ${cmd.name}, description: ${cmd.description}): diffrent polling interval -> close connection`);
connection.dispose();
}
}
if (cmd.interval && cmd.interval > 0 && cmd.type !== 'button') {
// interval using timeout
if (requestIntervalUserCommand) requestIntervalUserCommand = null;
if (cmd.interval && cmd.interval > 0) {
requestIntervalUserCommand = setTimeout(() => {
this.userCommandExecute(undefined, host, cmd);
}, cmd.interval * 1000);
}
}
} catch (err) {
this.log.error(`${logPrefix} datapoint-id: ${cmd.name}, description: ${cmd.description}`);
// No Sentry error report for user commands
this.errorHandling(err, logPrefix);
}
}
/**
* @param {NodeSSH | undefined} connection
* @param {object} host
*/
async folderSizes(connection, host) {
let logPrefix = `[folderSizes] ${host.name} (${host.ip}:${host.port}):`;
try {
if (connection) {
// @ts-ignore
let folderList = this.config.folders;
if (folderList.length > 0) {
let hostFolders = folderList.filter(x => {
return x.host === host.name;
})
for (const folder of hostFolders) {
if (folder.enabled) {
let unitFaktor = "/1024"
if (folder.unit === 'GB') {
unitFaktor = "/1024/1024"
} else if (folder.unit === 'TB') {
unitFaktor = "/1024/1024/1024"
}
let response = undefined;
if (folder.fileNamePattern) {
response = await this.sendCommand(connection, host, `${host.useSudo ? 'sudo -S ' : ''}find ${folder.path} -name "${folder.fileNamePattern}" -exec du -c {} + | tail -1 | awk '{printf $1${unitFaktor}}'`, logPrefix, undefined, false);
} else {
response = await this.sendCommand(connection, host, `${host.useSudo ? 'sudo -S ' : ''}du -sk ${folder.path} | awk '{ print $1 ${unitFaktor} }'`, logPrefix, undefined, false);
}
if (response) {
let id = `${host.name.replace(' ', '_')}.folders.${folder.name}.size`;
await this.createObjectNumber(id, _('folderSize'), folder.unit);
let result = parseFloat(response).toFixed(parseInt(folder.digits) || 0);
this.debugHandling(`${logPrefix} ${id}: ${parseFloat(result)} ${folder.unit}`);
await this.setStateAsync(id, parseFloat(result), true);
if (folder.countFiles) {
response = await this.sendCommand(connection, host, `${host.useSudo ? 'sudo -S ' : ''}find ${folder.path} -name "${folder.fileNamePattern ? folder.fileNamePattern : '*'}" | wc -l`, logPrefix, undefined, false);
if (response) {
let id = `${host.name.replace(' ', '_')}.folders.${folder.name}.files`;
await this.createObjectNumber(id, _('countFilesInFolder'), _('files'));
this.debugHandling(`${logPrefix} ${id}: ${parseInt(response)} ${_('files')}`);
await this.setStateAsync(id, parseInt(response), true);
}
}
if (folder.lastChange) {
response = await this.sendCommand(connection, host, `tmp=$(${host.useSudo ? 'sudo -S ' : ''}find ${folder.path} -name "${folder.fileNamePattern ? folder.fileNamePattern : '*'}" -type f -exec stat -c "%Y %n" -- {} \\; | sort -nr | head -n1 | awk '{print $2}') && date +%s -r $tmp`, logPrefix, undefined, false);
if (response) {
let id = `${host.name.replace(' ', '_')}.folders.${folder.name}.lastChange`;
let timestamp = parseInt(response) * 1000;
await this.createObjectNumber(id, _('last change'));
this.debugHandling(`${logPrefix} ${id}: ${timestamp} -> ${this.formatDate(timestamp, 'DD.MM.YYYY hh:mm')}`);
await this.setStateAsync(id, timestamp, true);
}
}
}
} else {
this.debugHandling(`${logPrefix} getting size for '${host.name.replace(' ', '_')}.folders.${folder.name}' -> is not enabled!`);
}
}
}
}
} catch (err) {
this.errorHandling(err, logPrefix);
}
}
/**
* @param {NodeSSH | undefined} connection
* @param {object} host
*/
async needrestart(connection, host) {
let logPrefix = `[needrestart] ${host.name} (${host.ip}:${host.port}):`;
const objects = require('./admin/lib/needrestart.json');
try {
// @ts-ignore
if (this.config.whitelist && this.config.whitelist["needrestart"] && this.config.whitelist["needrestart"].length > 0 && !this.config.blacklistDatapoints[host.name].includes('needrestart.all')) {
if (connection) {
if (await this.cmdPackageExist(connection, host, 'needrestart')) {
let response = await this.sendCommand(connection, host, `(tmp=$(${host.useSudo ? 'sudo -S ' : ''}/usr/sbin/needrestart -p -l | head -1) && echo "$tmp" | awk '{print $1}' && echo ", $tmp" | sed 's/.*Services=\\([0-9]*\\);.*/\\1/' && echo "$tmp" | sed 's/.*Containers=\\([0-9]*\\);.*/\\1/' && echo "$tmp" | sed 's/.*Sessions=\\([0-9]*\\);.*/\\1/') | awk '{printf "%s" (NR%4==0?RS:FS),$1}'`, logPrefix, undefined, false);
if (response) {
/** @type {object} */
let parsed = await csvToJson({
noheader: true,
headers: ['needrestart', 'services', 'containers', 'sessions'],
delimiter: [" "]
}).fromString(response);
this.debugHandling(`${logPrefix} csvToJson result: ${JSON.stringify(parsed)}`);
for (const obj of objects) {
// @ts-ignore
if (this.config.whitelist["needrestart"].includes(obj.id) && !this.config.blacklistDatapoints[host.name].includes(`needrestart.${obj.id}`)) {
if (parsed && parsed[0] && parsed[0][obj.id]) {
let id = `${host.name.replace(' ', '_')}.needrestart.${obj.id}`;
if (obj.id === 'needrestart') {
this.debugHandling(`${logPrefix} ${id}: ${parsed[0][obj.id] === 'OK' ? false : true}`);
await this.createObjectBoolean(id, _(obj.name));
await this.setStateAsync(id, parsed[0][obj.id] === 'OK' ? false : true, true);
}
if (obj.type === 'number') {
this.debugHandling(`${logPrefix} ${id}: ${parseInt(parsed[0][obj.id])}`);
await this.createObjectNumber(id, _(obj.name));
await this.setStateAsync(id, parseInt(parsed[0][obj.id]), true);
}
}
} else {
await this.delMyObject(`${host.name.replace(' ', '_')}.needrestart.${obj.id}`, logPrefix);
}
}
}
} else {
this.log.warn(`${logPrefix} package 'needrestart' not installed. You must install 'needrestart' to use this functions or deactivate the datapoints!`);
let needRestartStates = await this.getStatesAsync(`${this.namespace}.${host.name.replace(' ', '_')}.needrestart.*`);
for (const id of Object.keys(needRestartStates)) {
await this.delMyObject(id);
}
}
}
} else {
if (this.isAdapterStart) {
this.debugHandling(`${logPrefix} no datapoints selected -> removing existing datapoints`);
let needRestartStates = await this.getStatesAsync(`${this.namespace}.${host.name.replace(' ', '_')}.needrestart.*`);
for (const id of Object.keys(needRestartStates)) {
await this.delMyObject(id);
}
}
}
} catch (err) {
this.errorHandling(err, logPrefix);
}
}
/**
* @param {NodeSSH | undefined} connection
* @param {object} host
* @param {string | undefined} serviceName
*/
async servicesInfo(connection, host, serviceName = undefined) {
let logPrefix = `[servicesInfo] ${host.name} (${host.ip}:${host.port}):`;
const objects = require('./admin/lib/services.json');
try {
// @ts-ignore
if (this.config.whitelist && this.config.whitelist["services"] && this.config.whitelist["services"].length > 0 && !this.config.blacklistDatapoints[host.name].includes('services.all')) {
if (connection) {
let response = await this.sendCommand(connection, host, `systemctl list-units --type service --all --no-legend | awk '{out=""; for(i=5;i<=NF;i++){out=out" "$i}; print $1","$2","$3","$4","out}'${serviceName ? ` | grep ${serviceName}` : ''}`, logPrefix, undefined, false);
if (response) {
response = response.replace(/\t/g, ',')
/** @type {object} */
let parsed = await csvToJson({
noheader: true,
headers: ['id', 'load', 'active', 'running', 'description'],
delimiter: [","]
}).fromString(response);
this.debugHandling(`${logPrefix} csvToJson result: ${JSON.stringify(parsed)}`);
// TODO: whitelist für services implementieren
for (const result of parsed) {
let idPrefix = `${host.name.replace(' ', '_')}.services.${result.id.replace('.service', '')}`;
for (const obj of objects) {
let id = `${idPrefix}.${obj.id}`;
// @ts-ignore
if (this.config.whitelist["services"].includes(obj.id) && !this.config.blacklistDatapoints[host.name].includes(`services.${obj.id}`) && (this.config.serviceWhiteList[host.name].includes(result.id.replace('.service', '')) || this.config.serviceWhiteList[host.name].length === 0)) {
if (obj.type === 'string') {
await this.createObjectString(id, obj.name);
await this.setStateAsync(id, result[obj.id], true);
} else if (obj.type === 'boolean') {
await this.createObjectBoolean(id, obj.name);
await this.setStateAsync(id, result[obj.id] === 'running' ? true : false, true);
} else if (obj.type === 'button') {
await this.createObjectButton(id, obj.name);
this.subscribeStates(id);
}
} else {
await this.delMyObject(id, logPrefix);
}
}
}
}
}
} else {
if (this.isAdapterStart) {
this.debugHandling(`${logPrefix} no datapoints selected -> removing existing datapoints`);
let servicesStates = await this.getStatesAsync(`${this.namespace}.${host.name.replace(' ', '_')}.services.*`);
for (const id of Object.keys(servicesStates)) {
await this.delMyObject(id);
}
}
}
} catch (err) {
this.errorHandling(err, logPrefix);
}
}
/**
* @param {NodeSSH | undefined} connection
* @param {object} host
*/
async distributionInfo(connection, host) {
let logPrefix = `[distributionInfo] ${host.name} (${host.ip}:${host.port}):`;
const objects = require('./admin/lib/distribution.json');
try {
// @ts-ignore
if (this.config.whitelist && this.config.whitelist["distribution"] && this.config.whitelist["distribution"].length > 0 && !this.config.blacklistDatapoints[host.name].includes('distribution.all')) {
if (connection) {
let response = await this.sendCommand(connection, host, "cat /etc/os-release", logPrefix, undefined, false);
if (response) {
/** @type {object} */
let parsed = await csvToJson({
noheader: true,
headers: ['prop', 'val'],
delimiter: ["="]
}).fromString(response);
this.debugHandling(`${logPrefix} csvToJson result: ${JSON.stringify(parsed)}`);
for (const propObj of objects) {
let obj = parsed.find(x => x.prop === propObj.propName);
// @ts-ignore
if (this.config.whitelist["distribution"].includes(propObj.id) && !this.config.blacklistDatapoints[host.name].includes(`distribution.${propObj.id}`)) {
if (obj && obj.prop && obj.val) {
let id = `${host.name.replace(' ', '_')}.distribution.${propObj.id}`;
await this.createObjectString(id, propObj.name);
await this.setStateAsync(id, obj.val, true);
} else {
this.log.warn(`${logPrefix} property '${propObj.propName}' not exist in result!`);
}
} else {
await this.delMyObject(`${host.name.replace(' ', '_')}.distribution.${propObj.id}`, logPrefix);
}
}
}
}
} else {
if (this.isAdapterStart) {
this.debugHandling(`${logPrefix} no datapoints selected -> removing existing datapoints`);
for (const propObj of objects) {
await this.delMyObject(`${host.name.replace(' ', '_')}.distribution.${propObj.id}`);
}
}
}
} catch (err) {
this.errorHandling(err, logPrefix);
}
}
/**
* @param {NodeSSH | undefined} connection
* @param {object} host
*/
async updateInfos(connection, host) {
let logPrefix = `[updateInfos] ${host.name} (${host.ip}:${host.port}):`;
try {
if (connection) {
if (this.isAdapterStart) {
await this.cmdAptUpdate(connection, host);
} else {
if (this.config.aptUpdateInterval === 0) {
// apt update should run on every host refresh interval
await this.cmdAptUpdate(connection, host);
this.debugHandling(`${logPrefix}: no diffrent interval for updates configured by user`);
} else {
// user defined a diffrent update interval for apt update
let lastUpdate = await this.getStateAsync(`${this.namespace}.${host.name}.updates.upgradable`);
if (lastUpdate) {
let now = new Date().getTime();
let diff = (now - lastUpdate.ts) / 1000 / 60;
if (diff > this.config.aptUpdateInterval) {
await this.cmdAptUpdate(connection, host);
} else {
this.debugHandling(`${logPrefix}: receving last updates info before ${diff.toFixed(0)} Min. -> no data refresh needed`);
}
}
}
}
}
} catch (err) {
this.errorHandling(err, logPrefix);
return undefined;
}
}
/**
* @param {NodeSSH | undefined} connection
* @param {object} host
* @param {Boolean} restart
* @param {string | undefined} responseId
*/
async cmdShutdown(connection, host, restart = false, responseId = undefined) {
let logPrefix = `[cmdShutdown] ${host.name} (${host.ip}:${host.port}):`;
try {
if (connection) {
let cmd = `${host.useSudo ? 'sudo -S ' : ''}shutdown 0`
if (restart) {
cmd = `${host.useSudo ? 'sudo -S ' : ''}shutdown -r 0`
}
await this.sendCommand(connection, host, cmd, logPrefix, responseId);
}
} catch (err) {
this.errorHandling(err, logPrefix);
}
}
/**
* @param {NodeSSH | undefined} connection
* @param {object} host
* @param {string} responseId
*/
async cmdAptUpgrade(connection, host, responseId) {
let logPrefix = `[cmdAptUpgrade] ${host.name} (${host.ip}:${host.port}):`;
try {
if (connection) {
let response = await this.sendCommand(connection, host, `${host.useSudo ? 'sudo -S ' : ''}DEBIAN_FRONTEND=noninteractive apt-get upgrade -y`, logPrefix, responseId);
if (response) {
await this.setStateAsync(responseId, response, true);
await this.cmdAptUpdate(connection, host);
}
}
} catch (err) {
this.errorHandling(err, logPrefix);
}
}
/**
* @param {NodeSSH | undefined} connection
* @param {object} host
* @param {string} packageName
* @returns {Promise<boolean>}
*/
async cmdPackageExist(connection, host, packageName) {
let logPrefix = `[cmdPackageExist] ${host.name} (${host.ip}:${host.port}):`;
try {
if (connection) {
let response = await this.sendCommand(connection, host, `dpkg-query --list | grep -i ${packageName}`, logPrefix);
if (response) {
return true;
} else {
return false;
}
}
} catch (err) {
this.errorHandling(err, logPrefix);
}
return false;
}
/**
* @param {NodeSSH | undefined} connection
* @param {object} host
* @param {string | undefined} responseId
*/
async cmdAptUpdate(connection, host, responseId = undefined) {
let logPrefix = `[cmdAptUpdate] ${host.name} (${host.ip}:${host.port}):`;
const objects = require('./admin/lib/updates.json');
try {
// @ts-ignore
if (this.config.whitelist && this.config.whitelist["updates"] && this.config.whitelist["updates"].length > 0 && !this.config.blacklistDatapoints[host.name].includes('updates.all')) {
if (connection) {
// run apt update
let response = await this.sendCommand(connection, host, `${host.useSudo ? 'sudo -S ' : ''}apt-get update`, logPrefix, responseId, false);
if (response) {
response = await this.sendCommand(connection, host, `apt-get --just-print upgrade 2>&1 | perl -ne 'if (/Inst\\s([\\w,\\-,\\d,\\.,~,:,\\+]+)\\s\\[([\\w,\\-,\\d,\\.,~,:,\\+]+)\\]\\s\\(([\\w,\\-,\\d,\\.,~,:,\\+]+)\\)? /i) {print \"$1,$2,$3\\n\"}' \| column -s \" \" -t`, logPrefix, undefined, false);
let parsed = [];
let newPackages = 0;
if (response) {
parsed = await csvToJson({
noheader: true,
headers: ['name', 'installedVersion', 'availableVersion'],
delimiter: [","]
// @ts-ignore
}).fromString(response);
newPackages = parsed.length;
}
// Number of new Packages
let id = `${host.name.replace(' ', '_')}.updates.newPackages`;
// @ts-ignore
if (this.config.whitelist["updates"].includes("newPackages") && !this.config.blacklistDatapoints[host.name].includes(`updates.newPackages`)) {
this.debugHandling(`${logPrefix} ${id}: ${newPackages}`);
await this.createObjectNumber(id, `newPackages`, `packages`);
await this.setStateAsync(id, newPackages, true);
} else {
await this.delMyObject(id, logPrefix);
}
// is upgradable
id = `${host.name.replace(' ', '_')}.updates.upgradable`;
// @ts-ignore
if (this.config.whitelist["updates"].includes("upgradable") && !this.config.blacklistDatapoints[host.name].includes(`updates.upgradable`)) {
this.debugHandling(`${logPrefix} ${id}: ${newPackages > 0 ? true : false}`);
await this.createObjectBoolean(id, `upgradable`);
await this.setStateAsync(id, newPackages > 0 ? true : false, true);
} else {
await this.delMyObject(id, logPrefix);
}
// list of new packages
id = `${host.name.replace(' ', '_')}.updates.newPackagesList`;
// @ts-ignore
if (this.config.whitelist["updates"].includes("newPackagesList") && !this.config.blacklistDatapoints[host.name].includes(`updates.newPackagesList`)) {
if (newPackages > 0) {
this.debugHandling(`${logPrefix} ${id}: ${JSON.stringify(parsed)}`);
await this.createObjectString(id, `newPackagesList`);
await this.setStateAsync(id, JSON.stringify(parsed), true);
} else {
await this.createObjectString(id, `newPackagesList`);
await this.setStateAsync(id, '', true);
}
} else {
await this.delMyObject(id, logPrefix);
}
}
// last update
let id = `${host.name.replace(' ', '_')}.updates.lastUpdate`;
// @ts-ignore
if (this.config.whitelist["updates"].includes("lastUpdate") && !this.config.blacklistDatapoints[host.name].includes(`updates.lastUpdate`)) {
response = await this.sendCommand(connection, host, "dpkg-query -f '${db-fsys:Last-Modified}\n' -W | sort -nr | head -1", logPrefix, responseId, false);
if (response) {
let timestamp = parseInt(response) * 1000;
this.debugHandling(`${logPrefix} ${id}: ${timestamp} -> ${this.formatDate(timestamp, 'DD.MM.YYYY hh:mm')}`);
await this.createObjectNumber(id, `lastUpdate`);
await this.setStateAsync(id, timestamp, true);
} else {
// Fallback method
response = await this.sendCommand(connection, host, "grep installed /var/log/dpkg.log | tail -1 | cut -c1-19", logPrefix, responseId, false);
if (response) {
let timestamp = Date.parse(response);
this.debugHandling(`${logPrefix} ${id}: Fallback method: ${timestamp} -> ${this.formatDate(timestamp, 'DD.MM.YYYY hh:mm')}`);
await this.createObjectNumber(id, `lastUpdate`);
await this.setStateAsync(id, timestamp, true);
}
}
} else {
await this.delMyObject(id, logPrefix);
}
}
} else {
if (this.isAdapterStart) {
this.debugHandling(`${logPrefix} no datapoints selected -> removing existing datapoints`);
for (const propObj of objects) {
await this.delMyObject(`${host.name.replace(' ', '_')}.updates.${propObj.id}`);
}
}
}
} catch (err) {
this.errorHandling(err, logPrefix);
}
}
/**
* @param {NodeSSH | undefined} connection
* @param {string} cmd
* @param {string} logPrefix
* @param {string | undefined} responseId
* @param {boolean | undefined} responseErrorSendToSentry
* @returns {Promise<string | undefined>}
*/
async sendCommand(connection, host, cmd, logPrefix, responseId = undefined, responseErrorSendToSentry = false) {
try {
if (connection) {
this.debugHandling(`${logPrefix} send command: '${cmd}'`);
let response = undefined;
if (host.useSudo && cmd.includes('sudo -S ')) {
// using sudo
let password = await this.getPassword(host);
response = await connection.execCommand(cmd, { execOptions: { pty: true }, stdin: `${password}\n` });
if (!response.stderr) {
response.stdout = response.stdout.replace(password, "")
}
} else if (cmd.includes('sudo ') && !cmd.includes('sudo -S ')) {
this.errorHandling(new ResponseError(`${logPrefix} you must use 'sudo -S' instead of 'sudo' only!`), logPrefix, responseErrorSendToSentry);
return undefined;
} else {
response = await connection.execCommand(cmd);
}
if (!response.stderr) {
this.debugHandling(`${logPrefix} response stdout: ${response.stdout}`);
await this.reportResponse(responseId, 'successful');
// remove system stdout
if (!response.stderr) {
response.stdout = response.stdout
.replace(/^.*\[sudo\] password for.*$/mg, "")
.replace(/^.*\[sudo\] Passwort für.*$/mg, "")
.replace(/^.*sudo\: setrlimit\(RLIMIT_CORE\)\: Operation not permitted.*$/mg, "")
.replace(/^\s*$(?:\r\n?|\n)/gm, ""); // remove all empty lines
// .replace(`[sudo] password for ${host.user}: \r`, "")
// .replace('sudo: setrlimit(RLIMIT_CORE): Operation not permitted', "").replace("\n\n", "")
// .replace('[sudo] Passwort für pi: \r', "")
// .replace('[sudo] Passwort für pi: \n', "");
}
// catch errors that have no .stderr
let errorResponse = ['is not in the sudoers file', 'nicht in der sudoers-Datei']
if (errorResponse.some(word => response.stdout.includes(word))) {
this.errorHandling(new ResponseError(`${logPrefix} ${response.stdout}`), logPrefix, responseErrorSendToSentry);
return undefined;
}
return response.stdout;
} else {
if (response.stderr.includes('Shutdown scheduled for')) {
if (cmd.includes('-r')) {
this.log.info(`${logPrefix} restart`);
} else {
this.log.info(`${logPrefix} shutdown`);
}
await this.reportResponse(responseId, 'successful');
} else {
this.errorHandling(new ResponseError(`${logPrefix} ${response.stderr}`), logPrefix, responseErrorSendToSentry);
await this.reportResponse(responseId, response.stderr);
}
return undefined;
}
}
} catch (err) {
this.errorHandling(err, logPrefix);
await this.reportResponse(responseId, err.message);
return undefined;
}
}
//#endregion
//#region Functions
/**
* @param {string | undefined} responseId
* @param {string } msg
*/
async reportResponse(responseId, msg) {
if (responseId) {
await this.setStateAsync(responseId, msg, true);
}
}
/**
* @param {object} host
* @returns {Promise<NodeSSH | undefined>}
*/
async getConnection(host) {
try {
let pingResult = await ping.promise.probe(host.ip, { timeout: parseInt(host.timeout) || 5 });
if (pingResult.alive) {
let password = await this.getPassword(host);
let ssh = new NodeSSH();
let options = {
host: host.ip,
port: host.port,
username: host.user,
password: password,
readyTimeout: parseInt(host.timeout) * 1000 || 5000
}
if (host.rsakey && host.rsakey.length > 0) {
this.debugHandling(`[getConnection] Host '${host.name}' (${host.ip}:${host.port}): using rsa key for authentification`);
options.passphrase = password;
options.privateKey = host.rsakey;
} else if (host.useSudo) {
this.debugHandling(`[getConnection] Host '${host.name}' (${host.ip}:${host.port}): using sudo for authentification`);
}
return await ssh.connect(options);
} else {
this.log.info(`[getConnection] Host '${host.name}' (${host.ip}:${host.port}) seems not to be online`);
this.debugHandling(`[getConnection] Host '${host.name}' (${host.ip}:${host.port}) ping result: ${JSON.stringify(pingResult)}`)
return undefined;
}
} catch (err) {
this.log.error(`[getConnection] Could not establish a connection to '${host.name}' (${host.ip}:${host.port})!`);
this.errorHandling(err, '[getConnection]', false);
return undefined;
}
}
async getPassword(host) {
let obj = await this.getForeignObjectAsync('system.config');
if (obj && obj.native && obj.native.secret) {
//noinspection JSUnresolvedVariable
return this.decryptPassword(obj.native.secret, host.password);
} else {
//noinspection JSUnresolvedVariable
return this.decryptPassword("Zgfr56gFe87jJOM", host.password);
}
}
async setSelectableHosts() {
let hostObj = await this.getObjectAsync(`command.host`);
if (hostObj && hostObj.common) {
let hostStates = {};
// @ts-ignore
for (const host of this.config.hosts) {
if (host) {
// @ts-ignore
hostStates[host.name] = host.name;
}
}
hostObj.common.states = hostStates;