-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibdb.js
More file actions
2404 lines (2096 loc) · 73.3 KB
/
libdb.js
File metadata and controls
2404 lines (2096 loc) · 73.3 KB
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
import Database from 'better-sqlite3';
import fs from 'fs';
import path from 'path';
/**
* Cache class for database query results
* Extends the caching pattern from MapCache with statistics tracking
* and memory management specifically designed for database queries
*/
class DatabaseQueryCache {
/**
* Create a new DatabaseQueryCache instance
* @param {Object} options - Configuration options
* @param {number} options.ttlMs - Time to live in milliseconds (default: 60000)
* @param {number} options.maxSize - Maximum number of cache entries (default: 1000)
* @param {number} options.cleanupIntervalMs - Cleanup interval in ms (default: 300000 = 5 min)
*/
constructor(options = {}) {
this.ttl = options.ttlMs || 60000; // 60 seconds default
this.maxSize = options.maxSize || 1000;
this.cleanupIntervalMs = options.cleanupIntervalMs || 300000; // 5 minutes default
this.cache = new Map();
this.stats = {
hits: 0,
misses: 0,
sets: 0,
invalidations: 0,
cleanups: 0,
evictions: 0
};
// Start periodic cleanup
this.cleanupTimer = null;
this._startCleanupTimer();
}
/**
* Get a cached value by key
* @param {string} key - Cache key
* @returns {*} Cached data or null if not found/expired
*/
get(key) {
const entry = this.cache.get(key);
if (!entry) {
this.stats.misses++;
return null;
}
// Check if entry has expired
if (Date.now() - entry.timestamp > this.ttl) {
this.cache.delete(key);
this.stats.misses++;
return null;
}
this.stats.hits++;
return entry.data;
}
/**
* Set a cached value
* @param {string} key - Cache key
* @param {*} data - Data to cache
*/
set(key, data) {
// Enforce max size by evicting oldest entry if needed
if (this.cache.size >= this.maxSize && !this.cache.has(key)) {
this._evictOldest();
}
this.cache.set(key, {
data,
timestamp: Date.now()
});
this.stats.sets++;
}
/**
* Clear all cache entries
*/
clear() {
const size = this.cache.size;
this.cache.clear();
this.stats.invalidations += size;
}
/**
* Invalidate a specific cache entry
* @param {string} key - Cache key to invalidate
* @returns {boolean} True if entry was found and deleted
*/
invalidate(key) {
const existed = this.cache.has(key);
if (existed) {
this.cache.delete(key);
this.stats.invalidations++;
}
return existed;
}
/**
* Invalidate all entries matching a pattern
* @param {string} pattern - Pattern to match (supports * wildcard at end)
* @returns {number} Number of entries invalidated
*/
invalidatePattern(pattern) {
let count = 0;
const isPrefix = pattern.endsWith('*');
const prefix = isPrefix ? pattern.slice(0, -1) : pattern;
for (const key of this.cache.keys()) {
if (isPrefix ? key.startsWith(prefix) : key === pattern) {
this.cache.delete(key);
this.stats.invalidations++;
count++;
}
}
return count;
}
/**
* Check if a key exists and is not expired
* @param {string} key - Cache key
* @returns {boolean} True if key exists and is valid
*/
has(key) {
const entry = this.cache.get(key);
if (!entry) return false;
if (Date.now() - entry.timestamp > this.ttl) {
this.cache.delete(key);
return false;
}
return true;
}
/**
* Get cache statistics
* @returns {Object} Cache statistics
*/
getStats() {
const total = this.stats.hits + this.stats.misses;
return {
size: this.cache.size,
maxSize: this.maxSize,
ttlMs: this.ttl,
hits: this.stats.hits,
misses: this.stats.misses,
sets: this.stats.sets,
invalidations: this.stats.invalidations,
cleanups: this.stats.cleanups,
evictions: this.stats.evictions,
hitRate: total > 0 ? (this.stats.hits / total * 100).toFixed(2) + '%' : '0%',
memoryEstimateKB: this._estimateMemoryUsage()
};
}
/**
* Reset statistics (useful for monitoring intervals)
*/
resetStats() {
this.stats = {
hits: 0,
misses: 0,
sets: 0,
invalidations: 0,
cleanups: 0,
evictions: 0
};
}
/**
* Get all cache keys (for debugging)
* @returns {string[]} Array of cache keys
*/
keys() {
return Array.from(this.cache.keys());
}
/**
* Clean up expired entries
* @returns {number} Number of entries removed
*/
cleanup() {
const now = Date.now();
let removed = 0;
for (const [key, entry] of this.cache.entries()) {
if (now - entry.timestamp > this.ttl) {
this.cache.delete(key);
removed++;
}
}
if (removed > 0) {
this.stats.cleanups++;
}
return removed;
}
/**
* Stop the cleanup timer (call before disposing)
*/
destroy() {
if (this.cleanupTimer) {
clearInterval(this.cleanupTimer);
this.cleanupTimer = null;
}
this.cache.clear();
}
/**
* Start the periodic cleanup timer
* @private
*/
_startCleanupTimer() {
if (this.cleanupIntervalMs > 0) {
this.cleanupTimer = setInterval(() => {
this.cleanup();
}, this.cleanupIntervalMs);
// Don't prevent process exit
if (this.cleanupTimer.unref) {
this.cleanupTimer.unref();
}
}
}
/**
* Evict the oldest cache entry
* @private
*/
_evictOldest() {
let oldestKey = null;
let oldestTime = Infinity;
for (const [key, entry] of this.cache.entries()) {
if (entry.timestamp < oldestTime) {
oldestTime = entry.timestamp;
oldestKey = key;
}
}
if (oldestKey) {
this.cache.delete(oldestKey);
this.stats.evictions++;
}
}
/**
* Estimate memory usage in KB
* @private
* @returns {number} Estimated memory usage in KB
*/
_estimateMemoryUsage() {
let totalSize = 0;
for (const [key, entry] of this.cache.entries()) {
// Estimate key size
totalSize += key.length * 2; // UTF-16 chars
// Estimate data size (rough approximation)
try {
totalSize += JSON.stringify(entry.data).length * 2;
} catch {
// If can't stringify, estimate based on typeof
totalSize += 1024; // Default 1KB estimate for non-serializable
}
// Timestamp overhead
totalSize += 8;
}
return Math.round(totalSize / 1024);
}
}
/**
* Libreria per gestione database SQLite (stile NeDi)
*/
class NetMapDB {
/**
* Create a new NetMapDB instance
* @param {string} dbPath - Path to the SQLite database file
* @param {Object} cacheOptions - Options for the query cache
* @param {number} cacheOptions.ttlMs - Cache TTL in milliseconds (default: 60000)
* @param {number} cacheOptions.maxSize - Maximum cache entries (default: 100)
*/
constructor(dbPath = './netmap.db', cacheOptions = {}) {
this.dbPath = dbPath;
this.db = null;
// Initialize query cache for expensive operations
this.queryCache = new DatabaseQueryCache({
ttlMs: cacheOptions.ttlMs || 60000, // 60 seconds default
maxSize: cacheOptions.maxSize || 100,
cleanupIntervalMs: cacheOptions.cleanupIntervalMs || 300000
});
this.init();
}
init() {
// Crea directory se non esiste
const dir = path.dirname(this.dbPath);
if (dir && !fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
this.db = new Database(this.dbPath);
this.db.pragma('journal_mode = WAL'); // Write-Ahead Logging per performance
this.createSchema();
}
createSchema() {
// Tabella devices (dispositivi di rete)
this.db.exec(`
CREATE TABLE IF NOT EXISTS devices (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ip TEXT UNIQUE NOT NULL,
sysname TEXT,
sysdesc TEXT,
sysuptime INTEGER,
syslocation TEXT,
vendor TEXT,
model TEXT,
os TEXT,
serial TEXT,
firstseen INTEGER DEFAULT (strftime('%s', 'now')),
lastseen INTEGER DEFAULT (strftime('%s', 'now')),
status TEXT DEFAULT 'active',
snmp_version TEXT DEFAULT '2c',
community TEXT,
notes TEXT,
level INTEGER DEFAULT 0
)
`);
// Tabella interfaces (interfacce di rete)
this.db.exec(`
CREATE TABLE IF NOT EXISTS interfaces (
id INTEGER PRIMARY KEY AUTOINCREMENT,
device_id INTEGER NOT NULL,
ifindex INTEGER,
ifname TEXT,
ifdescr TEXT,
iftype INTEGER,
ifspeed INTEGER,
ifadminstatus INTEGER,
ifoperstatus INTEGER,
ifalias TEXT,
ifphysaddress TEXT,
firstseen INTEGER DEFAULT (strftime('%s', 'now')),
lastseen INTEGER DEFAULT (strftime('%s', 'now')),
FOREIGN KEY (device_id) REFERENCES devices(id) ON DELETE CASCADE,
UNIQUE(device_id, ifindex)
)
`);
// Tabella links (collegamenti LLDP/CDP/FDP/EDP)
this.db.exec(`
CREATE TABLE IF NOT EXISTS links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
device_id INTEGER NOT NULL,
local_ifindex INTEGER,
local_ifname TEXT,
remote_device_id INTEGER,
remote_ip TEXT,
remote_sysname TEXT,
remote_chassisid TEXT,
remote_portid TEXT,
remote_portdesc TEXT,
protocol TEXT, -- LLDP, CDP, FDP, EDP
firstseen INTEGER DEFAULT (strftime('%s', 'now')),
lastseen INTEGER DEFAULT (strftime('%s', 'now')),
FOREIGN KEY (device_id) REFERENCES devices(id) ON DELETE CASCADE,
FOREIGN KEY (remote_device_id) REFERENCES devices(id) ON DELETE SET NULL
)
`);
// Tabella nodes (nodi MAC/IP)
this.db.exec(`
CREATE TABLE IF NOT EXISTS nodes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
mac TEXT NOT NULL,
ip TEXT,
device_id INTEGER,
interface_id INTEGER,
vlan INTEGER,
firstseen INTEGER DEFAULT (strftime('%s', 'now')),
lastseen INTEGER DEFAULT (strftime('%s', 'now')),
source TEXT, -- ARP, FDB, ND
FOREIGN KEY (device_id) REFERENCES devices(id) ON DELETE SET NULL,
FOREIGN KEY (interface_id) REFERENCES interfaces(id) ON DELETE SET NULL
)
`);
// Tabella arp (ARP table)
this.db.exec(`
CREATE TABLE IF NOT EXISTS arp (
id INTEGER PRIMARY KEY AUTOINCREMENT,
device_id INTEGER NOT NULL,
interface_id INTEGER,
ip TEXT NOT NULL,
mac TEXT NOT NULL,
firstseen INTEGER DEFAULT (strftime('%s', 'now')),
lastseen INTEGER DEFAULT (strftime('%s', 'now')),
FOREIGN KEY (device_id) REFERENCES devices(id) ON DELETE CASCADE,
FOREIGN KEY (interface_id) REFERENCES interfaces(id) ON DELETE SET NULL,
UNIQUE(device_id, ip)
)
`);
// Tabella fdb (Forwarding Database / MAC table)
this.db.exec(`
CREATE TABLE IF NOT EXISTS fdb (
id INTEGER PRIMARY KEY AUTOINCREMENT,
device_id INTEGER NOT NULL,
interface_id INTEGER,
mac TEXT NOT NULL,
vlan INTEGER,
firstseen INTEGER DEFAULT (strftime('%s', 'now')),
lastseen INTEGER DEFAULT (strftime('%s', 'now')),
FOREIGN KEY (device_id) REFERENCES devices(id) ON DELETE CASCADE,
FOREIGN KEY (interface_id) REFERENCES interfaces(id) ON DELETE SET NULL,
UNIQUE(device_id, mac, vlan)
)
`);
// Tabella vlans
this.db.exec(`
CREATE TABLE IF NOT EXISTS vlans (
id INTEGER PRIMARY KEY AUTOINCREMENT,
device_id INTEGER NOT NULL,
vlan_id INTEGER NOT NULL,
vlan_name TEXT,
vlan_status TEXT,
firstseen INTEGER DEFAULT (strftime('%s', 'now')),
lastseen INTEGER DEFAULT (strftime('%s', 'now')),
FOREIGN KEY (device_id) REFERENCES devices(id) ON DELETE CASCADE,
UNIQUE(device_id, vlan_id)
)
`);
// Tabella monitoring (stato dispositivi)
this.db.exec(`
CREATE TABLE IF NOT EXISTS monitoring (
id INTEGER PRIMARY KEY AUTOINCREMENT,
device_id INTEGER NOT NULL,
status TEXT DEFAULT 'unknown', -- up, down, warning
latency INTEGER, -- ms
cpu_usage INTEGER, -- %
memory_usage INTEGER, -- %
temperature INTEGER, -- celsius
last_check INTEGER DEFAULT (strftime('%s', 'now')),
FOREIGN KEY (device_id) REFERENCES devices(id) ON DELETE CASCADE,
UNIQUE(device_id)
)
`);
// Tabella events (eventi/incidenti)
this.db.exec(`
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
device_id INTEGER,
type TEXT, -- discovery, alert, change, error
severity TEXT, -- info, warning, error, critical
message TEXT,
timestamp INTEGER DEFAULT (strftime('%s', 'now')),
FOREIGN KEY (device_id) REFERENCES devices(id) ON DELETE SET NULL
)
`);
// Tabella interface_vlans (VLAN membership per porta)
this.db.exec(`
CREATE TABLE IF NOT EXISTS interface_vlans (
id INTEGER PRIMARY KEY AUTOINCREMENT,
interface_id INTEGER NOT NULL,
vlan_id INTEGER NOT NULL,
tagged INTEGER DEFAULT 0, -- 0=untagged/access, 1=tagged/trunk
FOREIGN KEY (interface_id) REFERENCES interfaces(id) ON DELETE CASCADE,
UNIQUE(interface_id, vlan_id)
)
`);
// Tabella stp_ports (STP port states)
this.db.exec(`
CREATE TABLE IF NOT EXISTS stp_ports (
id INTEGER PRIMARY KEY AUTOINCREMENT,
device_id INTEGER NOT NULL,
port_num INTEGER NOT NULL,
state INTEGER, -- 1=disabled, 2=blocking, 3=listening, 4=learning, 5=forwarding, 6=broken
priority INTEGER,
path_cost INTEGER,
designated_root TEXT,
designated_bridge TEXT,
designated_port TEXT,
lastseen INTEGER DEFAULT (strftime('%s', 'now')),
FOREIGN KEY (device_id) REFERENCES devices(id) ON DELETE CASCADE,
UNIQUE(device_id, port_num)
)
`);
// Tabella lag_groups (Link Aggregation Groups)
this.db.exec(`
CREATE TABLE IF NOT EXISTS lag_groups (
id INTEGER PRIMARY KEY AUTOINCREMENT,
device_id INTEGER NOT NULL,
lag_index INTEGER NOT NULL,
lag_name TEXT,
mode TEXT, -- 'lacp', 'static'
lastseen INTEGER DEFAULT (strftime('%s', 'now')),
FOREIGN KEY (device_id) REFERENCES devices(id) ON DELETE CASCADE,
UNIQUE(device_id, lag_index)
)
`);
// Tabella lag_members (membri LAG)
this.db.exec(`
CREATE TABLE IF NOT EXISTS lag_members (
id INTEGER PRIMARY KEY AUTOINCREMENT,
lag_id INTEGER NOT NULL,
interface_id INTEGER NOT NULL,
FOREIGN KEY (lag_id) REFERENCES lag_groups(id) ON DELETE CASCADE,
FOREIGN KEY (interface_id) REFERENCES interfaces(id) ON DELETE CASCADE,
UNIQUE(lag_id, interface_id)
)
`);
// Tabella poe_ports (PoE port info)
this.db.exec(`
CREATE TABLE IF NOT EXISTS poe_ports (
id INTEGER PRIMARY KEY AUTOINCREMENT,
interface_id INTEGER NOT NULL,
admin_enabled INTEGER DEFAULT 1,
detection_status INTEGER, -- 1=disabled, 2=searching, 3=delivering, 4=fault
priority TEXT, -- critical, high, low
power_class INTEGER,
power_used REAL, -- watts
lastseen INTEGER DEFAULT (strftime('%s', 'now')),
FOREIGN KEY (interface_id) REFERENCES interfaces(id) ON DELETE CASCADE,
UNIQUE(interface_id)
)
`);
// Tabella ip_addresses (IP addresses per device/interface)
this.db.exec(`
CREATE TABLE IF NOT EXISTS ip_addresses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
device_id INTEGER NOT NULL,
interface_id INTEGER,
ip_address TEXT NOT NULL,
netmask TEXT,
ip_type TEXT DEFAULT 'ipv4', -- ipv4, ipv6
is_primary INTEGER DEFAULT 0,
firstseen INTEGER DEFAULT (strftime('%s', 'now')),
lastseen INTEGER DEFAULT (strftime('%s', 'now')),
FOREIGN KEY (device_id) REFERENCES devices(id) ON DELETE CASCADE,
FOREIGN KEY (interface_id) REFERENCES interfaces(id) ON DELETE SET NULL,
UNIQUE(device_id, ip_address)
)
`);
// Tabella users (autenticazione)
this.db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
role TEXT DEFAULT 'viewer', -- viewer, operator, admin
email TEXT,
created_at INTEGER DEFAULT (strftime('%s', 'now')),
last_login INTEGER,
active INTEGER DEFAULT 1
)
`);
// Tabella sessions (sessioni utente)
this.db.exec(`
CREATE TABLE IF NOT EXISTS sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
token TEXT UNIQUE NOT NULL,
expires_at INTEGER NOT NULL,
created_at INTEGER DEFAULT (strftime('%s', 'now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
`);
// Tabella sites (definizione siti/tenant)
this.db.exec(`
CREATE TABLE IF NOT EXISTS sites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL,
description TEXT,
created_at INTEGER DEFAULT (strftime('%s', 'now'))
)
`);
// Tabella site_rules (regole matching device -> site)
this.db.exec(`
CREATE TABLE IF NOT EXISTS site_rules (
id INTEGER PRIMARY KEY AUTOINCREMENT,
site_id INTEGER NOT NULL,
rule_type TEXT NOT NULL,
rule_value TEXT NOT NULL,
priority INTEGER DEFAULT 0,
FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
)
`);
// Tabella user_sites (assegnazione utenti a siti)
this.db.exec(`
CREATE TABLE IF NOT EXISTS user_sites (
user_id INTEGER NOT NULL,
site_id INTEGER NOT NULL,
PRIMARY KEY (user_id, site_id),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
)
`);
// Indici per performance
this.db.exec(`
CREATE INDEX IF NOT EXISTS idx_devices_ip ON devices(ip);
CREATE INDEX IF NOT EXISTS idx_devices_sysname ON devices(sysname);
CREATE INDEX IF NOT EXISTS idx_interfaces_device ON interfaces(device_id);
CREATE INDEX IF NOT EXISTS idx_links_device ON links(device_id);
CREATE INDEX IF NOT EXISTS idx_links_remote ON links(remote_device_id);
CREATE INDEX IF NOT EXISTS idx_nodes_mac ON nodes(mac);
CREATE INDEX IF NOT EXISTS idx_nodes_ip ON nodes(ip);
CREATE INDEX IF NOT EXISTS idx_arp_device ON arp(device_id);
CREATE INDEX IF NOT EXISTS idx_fdb_device ON fdb(device_id);
CREATE INDEX IF NOT EXISTS idx_events_device ON events(device_id);
CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp);
CREATE INDEX IF NOT EXISTS idx_interface_vlans_interface ON interface_vlans(interface_id);
CREATE INDEX IF NOT EXISTS idx_stp_ports_device ON stp_ports(device_id);
CREATE INDEX IF NOT EXISTS idx_lag_groups_device ON lag_groups(device_id);
CREATE INDEX IF NOT EXISTS idx_poe_ports_interface ON poe_ports(interface_id);
CREATE INDEX IF NOT EXISTS idx_ip_addresses_device ON ip_addresses(device_id);
CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);
CREATE INDEX IF NOT EXISTS idx_sessions_token ON sessions(token);
CREATE INDEX IF NOT EXISTS idx_sites_name ON sites(name);
CREATE INDEX IF NOT EXISTS idx_site_rules_site ON site_rules(site_id);
CREATE INDEX IF NOT EXISTS idx_site_rules_priority ON site_rules(priority);
CREATE INDEX IF NOT EXISTS idx_user_sites_user ON user_sites(user_id);
CREATE INDEX IF NOT EXISTS idx_user_sites_site ON user_sites(site_id);
`);
// Migration: aggiungi site_id a devices se non esiste
this.migrateSiteId();
}
/**
* Migration per aggiungere site_id alla tabella devices
*/
migrateSiteId() {
try {
// Verifica se la colonna esiste già
const tableInfo = this.db.prepare("PRAGMA table_info(devices)").all();
const hasSiteId = tableInfo.some(col => col.name === 'site_id');
if (!hasSiteId) {
this.db.exec(`ALTER TABLE devices ADD COLUMN site_id INTEGER REFERENCES sites(id)`);
this.db.exec(`CREATE INDEX IF NOT EXISTS idx_devices_site ON devices(site_id)`);
console.log('[DB] Migration: added site_id column to devices');
}
} catch (err) {
console.error('[DB] Migration error:', err.message);
}
}
// ========== DEVICES ==========
/**
* Insert or update a device
* @param {Object} device - Device data
* @param {Object} options - Options for the operation
* @param {boolean} options.skipCacheInvalidation - Skip cache invalidation (for batch operations)
* @returns {Object} Result with lastInsertRowid and changes
*/
upsertDevice(device, options = {}) {
const stmt = this.db.prepare(`
INSERT INTO devices (ip, sysname, sysdesc, sysuptime, syslocation, vendor, model, os, serial, snmp_version, community, status, level)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(ip) DO UPDATE SET
sysname = excluded.sysname,
sysdesc = excluded.sysdesc,
sysuptime = excluded.sysuptime,
syslocation = excluded.syslocation,
vendor = excluded.vendor,
model = excluded.model,
os = excluded.os,
serial = excluded.serial,
level = excluded.level,
lastseen = strftime('%s', 'now'),
status = excluded.status
`);
const result = stmt.run(
device.ip,
device.sysname || null,
device.sysdesc || null,
device.sysuptime || null,
device.syslocation || null,
device.vendor || null,
device.model || null,
device.os || null,
device.serial || null,
device.snmp_version || '2c',
device.community || null,
device.status || 'active',
device.level !== undefined ? device.level : 0
);
// Invalidate device cache unless skipped (for batch operations)
if (!options.skipCacheInvalidation) {
this.queryCache.invalidate('devices:all');
}
// IMPORTANTE: lastInsertRowid funziona solo per INSERT, non per UPDATE
// Se è un UPDATE (changes > 0 ma lastInsertRowid = 0), recupera l'ID dal database
if (result.lastInsertRowid === 0 && result.changes > 0 && device.ip) {
const updatedDevice = this.getDevice(device.ip);
if (updatedDevice) {
// Crea un oggetto result modificato con l'ID corretto
return {
...result,
lastInsertRowid: updatedDevice.id
};
}
}
return result;
}
getDevice(ipOrSysname) {
// Cerca prima per IP
let device = this.db.prepare('SELECT * FROM devices WHERE ip = ?').get(ipOrSysname);
// Se non trovato, cerca per sysname
if (!device) {
device = this.db.prepare('SELECT * FROM devices WHERE sysname = ?').get(ipOrSysname);
}
return device;
}
getAllDevices() {
return this.db.prepare('SELECT * FROM devices ORDER BY lastseen DESC').all();
}
/**
* Get all devices with caching
* Cache key: 'devices:all'
* @returns {Array} Array of device objects
*/
getCachedAllDevices() {
const cacheKey = 'devices:all';
const cached = this.queryCache.get(cacheKey);
if (cached !== null) {
return cached;
}
const result = this.getAllDevices();
this.queryCache.set(cacheKey, result);
return result;
}
/**
* Ottimizzato per large scale: paginazione e filtri
*/
getDevicesPaginated(options = {}) {
const { limit = 100, offset = 0, status = null, level = null } = options;
let query = 'SELECT * FROM devices WHERE 1=1';
const params = [];
if (status) {
query += ' AND status = ?';
params.push(status);
}
if (level !== null) {
query += ' AND level = ?';
params.push(level);
}
query += ' ORDER BY lastseen DESC LIMIT ? OFFSET ?';
params.push(limit, offset);
return this.db.prepare(query).all(...params);
}
/**
* Count totale devices per paginazione
*/
getDevicesCount(options = {}) {
const { status = null, level = null } = options;
let query = 'SELECT COUNT(*) as total FROM devices WHERE 1=1';
const params = [];
if (status) {
query += ' AND status = ?';
params.push(status);
}
if (level !== null) {
query += ' AND level = ?';
params.push(level);
}
return this.db.prepare(query).get(...params).total;
}
/**
* Ottieni device senza link (candidati per discovery LLDP via SSH)
* @param {Object} options - Opzioni filtro
* @param {string} options.vendor - Filtra per vendor (es: 'Huawei')
* @param {number} options.limit - Limite risultati (default: 50)
* @returns {Array} Lista device senza link
*/
getDevicesWithoutLinks(options = {}) {
const { vendor = null, limit = 50 } = options;
// Device senza link: nessuna riga in links con device_id = d.id
let query = `
SELECT d.*
FROM devices d
WHERE d.ip IS NOT NULL
AND d.status NOT IN ('virtual', 'inactive', 'deleted')
AND NOT EXISTS (
SELECT 1 FROM links l WHERE l.device_id = d.id
)
`;
const params = [];
if (vendor) {
query += ' AND d.vendor LIKE ?';
params.push(`%${vendor}%`);
}
query += ' ORDER BY d.lastseen DESC LIMIT ?';
params.push(limit);
return this.db.prepare(query).all(...params);
}
/**
* Trova device che non hanno link nel database
* Utile per identificare device isolati o con problemi di discovery LLDP
* @param {Object} options - Opzioni filtro { vendor: 'Huawei', limit: 100 }
* @returns {Array} Lista device senza link con dati essenziali
*/
getDevicesWithZeroLinks(options = {}) {
const { vendor = null, limit = null } = options;
// Query base: device senza link (non presenti in links.device_id)
let query = `
SELECT d.id, d.ip, d.sysname, d.vendor, d.model, d.syslocation, d.status, d.lastseen
FROM devices d
WHERE d.id NOT IN (SELECT DISTINCT device_id FROM links WHERE device_id IS NOT NULL)
`;
const params = [];
// Escludi device virtuali/inattivi (status = 'virtual' o simili)
query += ` AND d.status NOT IN ('virtual', 'inactive', 'deleted')`;
// Filtro opzionale per vendor (LIKE case-insensitive)
if (vendor) {
query += ' AND d.vendor LIKE ?';
params.push(`%${vendor}%`);
}
// Ordinamento per sysname (NULL ultimi)
query += ' ORDER BY d.sysname COLLATE NOCASE';
// Limite opzionale
if (limit !== null && limit > 0) {
query += ' LIMIT ?';
params.push(limit);
}
return this.db.prepare(query).all(...params);
}
// ========== INTERFACES ==========
/**
* Insert or update an interface
* @param {Object} iface - Interface data
* @param {Object} options - Options for the operation
* @param {boolean} options.skipCacheInvalidation - Skip cache invalidation (for batch operations)
* @returns {Object} Result with lastInsertRowid and changes
*/
upsertInterface(iface, options = {}) {
const stmt = this.db.prepare(`
INSERT INTO interfaces (device_id, ifindex, ifname, ifdescr, iftype, ifspeed, ifadminstatus, ifoperstatus, ifalias, ifphysaddress)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(device_id, ifindex) DO UPDATE SET
ifname = excluded.ifname,
ifdescr = excluded.ifdescr,
iftype = excluded.iftype,
ifspeed = excluded.ifspeed,
ifadminstatus = excluded.ifadminstatus,
ifoperstatus = excluded.ifoperstatus,
ifalias = excluded.ifalias,
ifphysaddress = excluded.ifphysaddress,
lastseen = strftime('%s', 'now')
`);
const result = stmt.run(
iface.device_id,
iface.ifindex,
iface.ifname || null,
iface.ifdescr || null,
iface.iftype || null,
iface.ifspeed || null,
iface.ifadminstatus || null,
iface.ifoperstatus || null,
iface.ifalias || null,
iface.ifphysaddress || null
);
// Invalidate interfaces cache for this device unless skipped (for batch operations)
if (!options.skipCacheInvalidation && iface.device_id) {
this.queryCache.invalidate(`interfaces:device:${iface.device_id}`);
}
return result;
}
getDeviceInterfaces(deviceId) {
return this.db.prepare('SELECT * FROM interfaces WHERE device_id = ? ORDER BY ifindex').all(deviceId);
}
/**
* Get device interfaces with caching
* Cache key: 'interfaces:device:{deviceId}'
* @param {number} deviceId - The device ID
* @returns {Array} Array of interface objects
*/
getCachedDeviceInterfaces(deviceId) {
const cacheKey = `interfaces:device:${deviceId}`;
const cached = this.queryCache.get(cacheKey);
if (cached !== null) {
return cached;
}
const result = this.getDeviceInterfaces(deviceId);
this.queryCache.set(cacheKey, result);
return result;
}
// ========== LINKS ==========
/**
* Insert or update a link
* @param {Object} link - Link data
* @param {Object} options - Options for the operation
* @param {boolean} options.skipCacheInvalidation - Skip cache invalidation (for batch operations)
* @returns {Object} Result with lastInsertRowid and changes
*/
upsertLink(link, options = {}) {
// METODO NEDI: Cerca link esistente con priorità:
// 1. device_id + local_ifindex + remote_device_id (se disponibile)
// 2. device_id + local_ifindex + remote_chassisid + remote_portid (se disponibili)
// 3. device_id + local_ifindex + remote_ip (se disponibile)
// 4. device_id + local_ifindex + remote_sysname (se disponibile)
// 5. device_id + local_ifindex (ultimo caso, per link senza dati remoti)
let existing = null;
// PRIORITÀ 1: remote_device_id (device già matchato)
if (link.remote_device_id) {
existing = this.db.prepare(`
SELECT id FROM links
WHERE device_id = ? AND local_ifindex = ? AND remote_device_id = ?
`).get(
link.device_id,
link.local_ifindex || null,
link.remote_device_id
);
}
// PRIORITÀ 2: chassisid + portid (identificazione univoca LLDP)
if (!existing && link.remote_chassisid && link.remote_portid) {
existing = this.db.prepare(`
SELECT id FROM links
WHERE device_id = ? AND local_ifindex = ? AND remote_chassisid = ? AND remote_portid = ?
`).get(
link.device_id,
link.local_ifindex || null,
link.remote_chassisid,
link.remote_portid
);
}
// PRIORITÀ 3: remote_ip (se disponibile)