Developing lightweight computation at the DSG edge

monitor-fetch-and-upload.go 26.6 KB
Newer Older
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
package main

import (
	"crypto/sha256"
	"encoding/json"
	"encoding/xml"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"sort"
	"strconv"
	"strings"

	"uc-monitor-go-test/cnml"
	"uc-monitor-go-test/goclidote"
)

//Default settings and descriptions
var cnmlFile = "../assets/cnml/upc.xml"
var cnmlFileHelp = "Filename of the XML file containing the CNML information of a zone"
var outDir = "/tmp/gmonitor2"
var outDirHelp = "Directory name where the output files will be saved"
var nodesFile = "nodes.json"
var nodesFileHelp = "Filename where the nodes list in JSON format will be saved"
var devicesFile = "devices.json"
var devicesFileHelp = "Filename where the devices list in JSON format will be saved"
var dbHost = "localhost"
var dbHostHelp = "The hostname or IP address where AntidoteDB is running"
var dbPort = 8087
var dbPortHelp = "The TCP port on which AntidoteDB is listening"

func initialize() {

	//Define and parse command line flags
	cnmlFilePtr := flag.String("cnml_file", cnmlFile, cnmlFileHelp)
	outDirPtr := flag.String("out_dir", outDir, outDirHelp)
	nodesFilePtr := flag.String("nodes_file", nodesFile, nodesFileHelp)
	devicesFilePtr := flag.String("devices_file", devicesFile, devicesFileHelp)
	dbHostPtr := flag.String("db_host", dbHost, dbHostHelp)
	dbPortPtr := flag.Int("db_port", dbPort, dbPortHelp)

	flag.Parse()

	cnmlFile = *cnmlFilePtr
	outDir = *outDirPtr
	nodesFile = *nodesFilePtr
	devicesFile = *devicesFilePtr
	dbHost = *dbHostPtr
	dbPort = *dbPortPtr

	// Add a trailing slash to outDir, if missing
	if outDir[len(outDir)-1:] != "/" {
		outDir = strings.Join([]string{outDir, "/"}, "")
	}

	// Add path to filenames
	nodesFile = strings.Join([]string{outDir, nodesFile}, "")
	devicesFile = strings.Join([]string{outDir, devicesFile}, "")

}

func main() {

	initialize()

	// Open the CNML file to be parsed
	xmlFile, err := os.Open(cnmlFile)
	errCheck(err, fmt.Sprintf("Error opening file %s:", cnmlFile))
	defer xmlFile.Close()

	//Read the whole CNML file and save it to readFile
	readFile, err := ioutil.ReadAll(xmlFile)
	errCheck(err, fmt.Sprintf("Error reading file %s:", cnmlFile))

	// Unmarshal the read CNML file to a CNML data structure
	var GuifiCnml cnml.Cnml
	err = xml.Unmarshal(readFile, &GuifiCnml)
	errCheck(err, fmt.Sprintf("Error parsing XML data in file %s:", cnmlFile))

	// Propagate graph servers top-down to those nodes and devices that don't
	// have a specific server assigned (i.e., that inheir their parents' one)
	GuifiCnml.Network.Zone = propagateGraphServerInZone(GuifiCnml.Network.Zone)

	// Get an array with all the nodes in the CNML
	var allNodes = getNodesInZone(GuifiCnml.Network.Zone)
	// Get an array with all the devices in the CNML
	var allDevices = getDevicesInZone(GuifiCnml.Network.Zone)

	fmt.Println(len(allNodes), "nodes read from", xmlFile.Name())
	fmt.Println(len(allDevices), "devices read from", xmlFile.Name())

	// Create the output directory
	err = os.MkdirAll(outDir, 0755)
	errCheck(err, fmt.Sprintf("Error creating working dir %s:", outDir))

	// Create the nodes JSON output file
	// TODO: Check if really needed
	nJFile, err := os.Create(nodesFile)
	errCheck(err, fmt.Sprintf("Error creating working dir %s:", outDir))
	defer nJFile.Close()

	// Create the devices JSON output file
	dJFile, err := os.Create(devicesFile)
	errCheck(err, "")
	defer dJFile.Close()

	// TODO: Check if really needed
	dafile, err := os.Create("/tmp/gmonitor2/devs_old.json")
	errCheck(err, "")
	defer dafile.Close()

	dasfile, err := os.Create("/tmp/gmonitor2/devs.json")
	errCheck(err, "")
	defer dasfile.Close()

	daChecksumFile, err := os.Create("/tmp/gmonitor2/devs_old.checksum")
	errCheck(err, "")
	defer daChecksumFile.Close()

	dasChecksumFile, err := os.Create("/tmp/gmonitor2/devs.checksum")
	errCheck(err, "")
	defer dasChecksumFile.Close()

	// Save the whole nodes information to a JSON file
	for _, v := range allNodes {
		jnodes, err := json.Marshal(v)
		errCheck(err, "")

		//fmt.Println(string(jnode))
		nJFile.WriteString(string(jnodes))
	}

	// Save the whole devices information to a JSON file
	for _, v := range allDevices {
		jdevices, err := json.Marshal(v)
		errCheck(err, "")

		//fmt.Println(string(jdevices))
		dJFile.WriteString(string(jdevices))
	}

	// cnmlDevsIpv4sGraphs will hold the valid devices from the CNML
	var cnmlDevsIpv4sGraphs []cnml.DeviceIpv4sGraphserver

	// Export only the bare minimum information needed for the monitoring code
	for _, v := range allDevices {
		var devadd cnml.DeviceIpv4Adddresses
		var devaddsrv cnml.DeviceIpv4sGraphserver

		devadd.ID = v.ID
		devaddsrv.ID = v.ID

		devadd.Addresses = getIpv4AddressesInDevice(v)
		devaddsrv.Addresses = getIpv4AddressesInDevice(v)

		devaddsrv.GraphServer = v.GraphServer
		devaddsrv.SNMPNames = getSNMPNamesInDevice(v)

		// This method was previously used but was very inefficient
		// devaddserver.GraphServer = getGraphServerOfDeviceInZone(v, GuifiCnml.Network.Zone)

		// Save only those devices which are addressable (i.e. have an IPv4
		// address) and are either in working or in testing mode
		if len(devadd.Addresses) > 0 && (v.Status == "Working" || v.Status == "Testing") {
			// devsadds = append(devsadds, devadd)
			cnmlDevsIpv4sGraphs = append(cnmlDevsIpv4sGraphs, devaddsrv)

			jdevadd, err := json.Marshal(devadd)
			errCheck(err, "")

			jdevaddsrv, err := json.Marshal(devaddsrv)
			errCheck(err, "")

			//	fmt.Println(string(jdevadd))
			dafile.WriteString(string(jdevadd))
			dafile.WriteString("\n")
			dasfile.WriteString(string(jdevaddsrv))
			dasfile.WriteString("\n")
		}
	}

	// Generate the SHA256 checksum of the cnmlDevsIpv4sGraphs data structure printout
	cnmlDevsIpv4sGraphsChecksum := fmt.Sprintf("%x\n", sha256.Sum256([]byte(fmt.Sprintf("%+v", cnmlDevsIpv4sGraphs))))

	dasChecksumFile.WriteString(cnmlDevsIpv4sGraphsChecksum)

	fmt.Println(len(cnmlDevsIpv4sGraphs), "devices exported to", dasfile.Name())

	// Read current AntidoteDB devices
	antidoteDevices := goclidote.ReadDevicesFromAntidote(dbHost, dbPort)

	// oldAntidoteDevices will hold devices to remove from AntidoteDB
	var oldAntidoteDevices []cnml.DeviceIpv4sGraphserver

	// keepAntidoteDevices will hold devices to keep in AntidoteDB
	var keepAntidoteDevices []cnml.DeviceIpv4sGraphserver

	// Export devices and their addresses to AntidoteDB
	antidoteAddDeviceSuccess := 0
	antidoteAddDeviceFail := 0
	antidoteAddAddressSuccess := 0
	antidoteAddAddressFail := 0
	antidoteAddSNMPNameSuccess := 0
	antidoteAddSNMPNameFail := 0
	antidoteAddGraphserverSuccess := 0
	antidoteAddGraphserverFail := 0
	antidoteDeleteDeviceSuccess := 0
	antidoteDeleteDeviceFail := 0
	antidoteDeleteAddressSuccess := 0
	antidoteDeleteAddressFail := 0
	antidoteDeleteSNMPNameSuccess := 0
	antidoteDeleteSNMPNameFail := 0
	antidoteDeleteGraphserverSuccess := 0
	antidoteDeleteGraphserverFail := 0

	// Check AntidoteDB for old devices not in the current CNML file anymore
	for _, v := range antidoteDevices {
		if !isDeviceIpv4sGraphserverInArray(v, cnmlDevsIpv4sGraphs) {
			// Save old devices to later remove them
			oldAntidoteDevices = append(oldAntidoteDevices, v)

		} else {
			// Save devices to keep to later check if any changes have appeared
			keepAntidoteDevices = append(keepAntidoteDevices, v)
		}
	}

	fmt.Println("")

	// Remove old devices from AntidoteDB not in the CNML file anymore
	removedAntidoteDevices := goclidote.RemoveDevicesFromAntidote(oldAntidoteDevices, dbHost, dbPort)

	for k, v := range oldAntidoteDevices {
		devFound := false
		for _, w := range removedAntidoteDevices {

			if v.ID == w.ID {
				devFound = true
240
				break
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
			}
		}

		if devFound {
			// Removed the device's graphserver from AntidoteDB
			antidoteDeleteGraphserverSuccess++
			// Removed the device's IPv4 addresses from AntidoteDB
			for _ = range v.Addresses {
				antidoteDeleteAddressSuccess++
			}
			// Removed the device's SNMP names from AntidoteDB
			for _ = range v.SNMPNames {
				antidoteDeleteSNMPNameSuccess++
			}
			// Removed the device from AntidoteDB
			antidoteDeleteDeviceSuccess++
		} else {
			// Failed to remove the device's graphserver from AntidoteDB
			antidoteDeleteGraphserverFail++
			// Failed to remove the device's IPv4 addresses from AntidoteDB
			for _ = range v.Addresses {
				antidoteDeleteAddressFail++
			}
			// Failed to remove the device's SNMP names from AntidoteDB
			for _ = range v.SNMPNames {
				antidoteDeleteSNMPNameFail++
			}
			// Failed to remove the device from AntidoteDB
			antidoteDeleteDeviceFail++
		}

		if k == 0 {
			fmt.Printf("%d devices removed from AntidoteDB (%d success, %d fail)\n", antidoteDeleteDeviceSuccess+antidoteDeleteDeviceFail, antidoteDeleteDeviceSuccess, antidoteDeleteDeviceFail)
			fmt.Printf("%d graphservers removed from AntidoteDB (%d success, %d fail)\n", antidoteDeleteGraphserverSuccess+antidoteDeleteGraphserverFail, antidoteDeleteGraphserverSuccess, antidoteDeleteGraphserverFail)
			fmt.Printf("%d IPv4 addresses removed from AntidoteDB (%d success, %d fail)\n", antidoteDeleteAddressSuccess+antidoteDeleteAddressFail, antidoteDeleteAddressSuccess, antidoteDeleteAddressFail)
			fmt.Printf("%d SNMP names removed from AntidoteDB (%d success, %d fail)\n", antidoteDeleteSNMPNameSuccess+antidoteDeleteSNMPNameFail, antidoteDeleteSNMPNameSuccess, antidoteDeleteSNMPNameFail)
		} else {
			fmt.Printf("\033[4A\r%d devices removed from AntidoteDB (%d success, %d fail)\n", antidoteDeleteDeviceSuccess+antidoteDeleteDeviceFail, antidoteDeleteDeviceSuccess, antidoteDeleteDeviceFail)
			fmt.Printf("\r%d graphservers removed from AntidoteDB (%d success, %d fail)\n", antidoteDeleteGraphserverSuccess+antidoteDeleteGraphserverFail, antidoteDeleteGraphserverSuccess, antidoteDeleteGraphserverFail)
			fmt.Printf("\r%d IPv4 addresses removed from AntidoteDB (%d success, %d fail)\n", antidoteDeleteAddressSuccess+antidoteDeleteAddressFail, antidoteDeleteAddressSuccess, antidoteDeleteAddressFail)
			fmt.Printf("\r%d SNMP names removed from AntidoteDB (%d success, %d fail)\n", antidoteDeleteSNMPNameSuccess+antidoteDeleteSNMPNameFail, antidoteDeleteSNMPNameSuccess, antidoteDeleteSNMPNameFail)
		}
	}

	if len(oldAntidoteDevices) > 0 {
		fmt.Printf("\033[4A\r%d devices removed from AntidoteDB (%d success, %d fail)\n", antidoteDeleteDeviceSuccess+antidoteDeleteDeviceFail, antidoteDeleteDeviceSuccess, antidoteDeleteDeviceFail)
	} else {
		fmt.Printf("\r%d devices removed from AntidoteDB (%d success, %d fail)\n", antidoteDeleteDeviceSuccess+antidoteDeleteDeviceFail, antidoteDeleteDeviceSuccess, antidoteDeleteDeviceFail)
	}
	fmt.Printf("\r%d graphservers removed from AntidoteDB (%d success, %d fail)\n", antidoteDeleteGraphserverSuccess+antidoteDeleteGraphserverFail, antidoteDeleteGraphserverSuccess, antidoteDeleteGraphserverFail)
	fmt.Printf("\r%d IPv4 addresses removed from AntidoteDB (%d success, %d fail)\n", antidoteDeleteAddressSuccess+antidoteDeleteAddressFail, antidoteDeleteAddressSuccess, antidoteDeleteAddressFail)
	fmt.Printf("\r%d SNMP names removed from AntidoteDB (%d success, %d fail)\n", antidoteDeleteSNMPNameSuccess+antidoteDeleteSNMPNameFail, antidoteDeleteSNMPNameSuccess, antidoteDeleteSNMPNameFail)

	fmt.Println("")

	// Add or update those devices that are in the CNML file
297
298
299
300
	var newDevs []cnml.DeviceIpv4sGraphserver
	var curDevs []cnml.DeviceIpv4sGraphserver

	for _, v := range cnmlDevsIpv4sGraphs {
301
302
		// Check if the device is in Antidote already and add it if missing
		if !isDeviceIpv4sGraphserverInArray(v, keepAntidoteDevices) && len(v.Addresses) > 0 {
303
304
305
306
307
			newDevs = append(newDevs, v)
		} else {
			curDevs = append(curDevs, v)
		}
	}
308

309
	addDevs := goclidote.AddDevicesToAntidote(newDevs, dbHost, dbPort)
310

311
312
313
	for k, v := range newDevs {
		devFound := false
		for _, w := range addDevs {
314

315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
			if v.ID == w.ID {
				devFound = true
				break
			}
		}

		if devFound {
			// Added the device to AntidoteDB
			antidoteAddDeviceSuccess++
			// Added the device's graphserver to AntidoteDB
			antidoteAddGraphserverSuccess++
			// Added the device's IPv4 addresses from AntidoteDB
			for _ = range v.Addresses {
				antidoteAddAddressSuccess++
			}
			// Removed the device's SNMP names from AntidoteDB
			for _ = range v.SNMPNames {
				antidoteAddSNMPNameSuccess++
333
334
			}
		} else {
335
336
337
338
339
340
341
342
343
344
345
			// Failed to add the device to AntidoteDB
			antidoteAddDeviceFail++
			// Failed to add the device's graphserver to AntidoteDB
			antidoteAddGraphserverFail++
			// Failed to add the device's IPv4 addresses to AntidoteDB
			for _ = range v.Addresses {
				antidoteAddAddressFail++
			}
			// Failed to add the device's SNMP names to AntidoteDB
			for _ = range v.SNMPNames {
				antidoteAddSNMPNameFail++
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
		if k == 0 {
			fmt.Printf("%d devices added to AntidoteDB (%d success, %d fail)\n", antidoteAddDeviceSuccess+antidoteAddDeviceFail, antidoteAddDeviceSuccess, antidoteAddDeviceFail)
			fmt.Printf("%d graphservers added or updated to AntidoteDB (%d success, %d fail)\n", antidoteAddGraphserverSuccess+antidoteAddGraphserverFail, antidoteAddGraphserverSuccess, antidoteAddGraphserverFail)
			fmt.Printf("%d IPv4 addresses added or updated to AntidoteDB (%d success, %d fail)\n", antidoteAddAddressSuccess+antidoteAddAddressFail, antidoteAddAddressSuccess, antidoteAddAddressFail)
			fmt.Printf("%d SNMP names added or updated to AntidoteDB (%d success, %d fail)\n", antidoteAddSNMPNameSuccess+antidoteAddSNMPNameFail, antidoteAddSNMPNameSuccess, antidoteAddSNMPNameFail)
		} else {
			fmt.Printf("\033[4A\r%d devices added to AntidoteDB (%d success, %d fail)\n", antidoteAddDeviceSuccess+antidoteAddDeviceFail, antidoteAddDeviceSuccess, antidoteAddDeviceFail)
			fmt.Printf("\r%d graphservers added or updated to AntidoteDB (%d success, %d fail)\n", antidoteAddGraphserverSuccess+antidoteAddGraphserverFail, antidoteAddGraphserverSuccess, antidoteAddGraphserverFail)
			fmt.Printf("\r%d IPv4 addresses added or updated to AntidoteDB (%d success, %d fail)\n", antidoteAddAddressSuccess+antidoteAddAddressFail, antidoteAddAddressSuccess, antidoteAddAddressFail)
			fmt.Printf("\r%d SNMP names added or updated to AntidoteDB (%d success, %d fail)\n", antidoteAddSNMPNameSuccess+antidoteAddSNMPNameFail, antidoteAddSNMPNameSuccess, antidoteAddSNMPNameFail)
		}
	}

	for k, v := range curDevs {
		// The device is in AntidoteDB; check if it has changed
		if v.GraphServer != keepAntidoteDevices[posDeviceInSlice(v, keepAntidoteDevices)].GraphServer {
			// Save the new default graph server
			if saveGraphserverToDeviceIpv4sGraphserverToAntidote(v) {
				antidoteAddGraphserverSuccess++
			} else {
				antidoteAddGraphserverFail++
			}
		}

		ips1 := v.Addresses
		ips2 := keepAntidoteDevices[posDeviceInSlice(v, keepAntidoteDevices)].Addresses
375

376
377
		sort.Strings(ips1)
		sort.Strings(ips2)
378

379
380
381
382
383
384
		if !compareStringArrays(ips1, ips2) {
			for _, w := range keepAntidoteDevices[posDeviceInSlice(v, keepAntidoteDevices)].Addresses {
				if removeIpv4addressFromDeviceIpv4sGraphserver(v, w) {
					antidoteDeleteAddressSuccess++
				} else {
					antidoteDeleteAddressFail++
385
				}
386
387
388
389
390
391
392
			}
			// Iterate through all the device's addresses and add them if new
			for _, w := range v.Addresses {
				if saveIpv4addressToDeviceIpv4sGraphserverToAntidote(v, w) {
					antidoteAddAddressSuccess++
				} else {
					antidoteAddAddressFail++
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
				}
			}
		}

		if k == 0 {
			fmt.Printf("%d devices added to AntidoteDB (%d success, %d fail)\n", antidoteAddDeviceSuccess+antidoteAddDeviceFail, antidoteAddDeviceSuccess, antidoteAddDeviceFail)
			fmt.Printf("%d graphservers added or updated to AntidoteDB (%d success, %d fail)\n", antidoteAddGraphserverSuccess+antidoteAddGraphserverFail, antidoteAddGraphserverSuccess, antidoteAddGraphserverFail)
			fmt.Printf("%d IPv4 addresses added or updated to AntidoteDB (%d success, %d fail)\n", antidoteAddAddressSuccess+antidoteAddAddressFail, antidoteAddAddressSuccess, antidoteAddAddressFail)
			fmt.Printf("%d SNMP names added or updated to AntidoteDB (%d success, %d fail)\n", antidoteAddSNMPNameSuccess+antidoteAddSNMPNameFail, antidoteAddSNMPNameSuccess, antidoteAddSNMPNameFail)
		} else {
			fmt.Printf("\033[4A\r%d devices added to AntidoteDB (%d success, %d fail)\n", antidoteAddDeviceSuccess+antidoteAddDeviceFail, antidoteAddDeviceSuccess, antidoteAddDeviceFail)
			fmt.Printf("\r%d graphservers added or updated to AntidoteDB (%d success, %d fail)\n", antidoteAddGraphserverSuccess+antidoteAddGraphserverFail, antidoteAddGraphserverSuccess, antidoteAddGraphserverFail)
			fmt.Printf("\r%d IPv4 addresses added or updated to AntidoteDB (%d success, %d fail)\n", antidoteAddAddressSuccess+antidoteAddAddressFail, antidoteAddAddressSuccess, antidoteAddAddressFail)
			fmt.Printf("\r%d SNMP names added or updated to AntidoteDB (%d success, %d fail)\n", antidoteAddSNMPNameSuccess+antidoteAddSNMPNameFail, antidoteAddSNMPNameSuccess, antidoteAddSNMPNameFail)
		}
	}
}

// Get an array with all the nodes in a zone and its subzones, recursively
func getNodesInZone(zone cnml.Zone) []cnml.Node {

	var nodes []cnml.Node

	//Add the nodes directly placed in the zone
	nodes = zone.Nodes
	//Iterate all the subzones in the zone by recursively calling this function
	for _, w := range zone.Zones {
		for _, x := range getNodesInZone(w) {
			nodes = append(nodes, x)
		}
	}

	return nodes
}

// Return an ints array containing, first, the node ID, then the zones ID path
func getNodeZonesPath(node cnml.Node, zone cnml.Zone) []int {

	var path []int

	for _, v := range zone.Nodes {
		if node.ID == v.ID {
			return append(path, v.ID)
		}
	}

	for _, w := range zone.Zones {
		zpath := getNodeZonesPath(node, w)
		if len(zpath) > 0 {
			path = append(path, zpath...)
			path = append(path, w.ID)
		}
	}

	return path
}

// Return the ID of the graph server the a device is assigned to, either
// directly or by inheritance in the node or in the zone
func getGraphServerOfDeviceInZone(device cnml.Device, zone cnml.Zone) int {

	//Check if the device has a graph server directly assigned
	if device.GraphServer > 0 {
		return device.GraphServer
	}

	//Iterate through all the nodes in the zone
	for _, v := range getNodesInZone(zone) {
		for _, w := range v.Devices {
			if device.ID == w.ID {
				//Get the graph server from the node
				return getGraphServerOfNodeInZone(v, zone)
			}
		}
	}

	return -1
}

// Return the ID of the graph server a node is assigned to, either directly
// or by inheritance in the zone
func getGraphServerOfNodeInZone(node cnml.Node, zone cnml.Zone) int {

	if node.GraphServer > 0 {
		return node.GraphServer
	}

	//Iterate through all the nodes in the zone
	for _, v := range getZonesInZoneInc(zone) {
		for _, w := range v.Nodes {
			if node.ID == w.ID {
				if v.GraphServer > 0 {
					return v.GraphServer
				}

				return getGraphServerOfZoneInZone(v, zone)
			}
		}

	}
	return -1

}

// Return the ID of the graph server a zone is assigned to, either directly
// or by inheritance in the zone
func getGraphServerOfZoneInZone(thiszone cnml.Zone, zone cnml.Zone) int {

	if thiszone.GraphServer > 0 {
		return thiszone.GraphServer
	}
	//Iterate through all the zones in the zones to get the parent zone
	for _, v := range getZonesInZoneExc(zone) {
		for _, w := range v.Zones {
			if thiszone.ID == w.ID {
				if v.GraphServer > 0 {
					return v.GraphServer
				}
				return getGraphServerOfZoneInZone(v, zone)
			}
		}
	}
	return -1

}

// Get an array with all the SNMP interfaces name in a device
func getSNMPNamesInDevice(device cnml.Device) []string {

	var SNMPNames []string

	//Iterate all the radios of the device in search of SNMP names
	for _, v := range device.Radios {
		if v.SnmpName != "" {
			SNMPNames = append(SNMPNames, v.SnmpName)
		}
	}

	return SNMPNames
}

// Get an array with all the IPv4 addresses assigned to a device, being the
// first one its main IPv4 address
func getIpv4AddressesInDevice(device cnml.Device) []string {

	var ipv4Addresses []string

	//Add the primary IPv4 address of the devices, if its not an empty string
	if device.MainIpv4 != "" {
		ipv4Addresses = append(ipv4Addresses, device.MainIpv4)
	}

	//Iterate all the interfaces of the device in search of more IPv4 addresses
	for _, v := range device.Interfaces {
		if v.Ipv4 != "" && v.Ipv4 != device.MainIpv4 {
			ipv4Addresses = append(ipv4Addresses, v.Ipv4)
		}
	}

	return ipv4Addresses
}

// Get an array with all the devices in a zone (i.e. in all the zone's nodes)
func getDevicesInZone(zone cnml.Zone) []cnml.Device {

	var devices []cnml.Device

	for _, v := range getNodesInZone(zone) {
		for _, w := range v.Devices {
			devices = append(devices, w)
		}
	}

	return devices
}

// Propagate the zone's graph server to the zones and subzones inside the zone,
// recursively, and to the nodes in the zone, in case they don't have a graph
// server assigned
func propagateGraphServerInZone(zone cnml.Zone) cnml.Zone {

	//First, propagate the zone's graph server to the nodes in the zone
	for k, v := range zone.Nodes {
		if !(v.GraphServer > 0) {
			zone.Nodes[k].GraphServer = zone.GraphServer
		}
		zone.Nodes[k] = propagateGraphServerInNode(zone.Nodes[k])
	}

	//Second, propagate the zone graph server to the zones inside, recursively
	for l, w := range zone.Zones {
		if !(w.GraphServer > 0) {
			zone.Zones[l].GraphServer = zone.GraphServer
		}
		zone.Zones[l] = propagateGraphServerInZone(zone.Zones[l])
	}

	return zone
}

// Propagate the node's graph server to the devices of the node in case they
// don't have a graph_server assigned
func propagateGraphServerInNode(node cnml.Node) cnml.Node {
	for k, v := range node.Devices {
		if !(v.GraphServer > 0) {
			node.Devices[k].GraphServer = node.GraphServer
		}
	}
	return node
}

// Get an array with all the zones and subzones inside a zone, by scanning it
// recursively, including the zone itself
func getZonesInZoneInc(zone cnml.Zone) []cnml.Zone {

	var zones []cnml.Zone
	zones = append(zones, zone)

	zones = append(zones, getZonesInZoneExc(zone)...)

	return zones
}

// Get an array with all the zones and subzones inside a zone, by scanning it
// recursively, not including the zone itself
func getZonesInZoneExc(zone cnml.Zone) []cnml.Zone {

	var zones []cnml.Zone

	for _, v := range zone.Zones {
		zones = append(zones, getZonesInZoneInc(v)...)
	}

	return zones
}

// Remove a device by its ID from Antidote using João's REST server
func removeDeviceFromAntidote(ID int) bool {
	return goclidote.AntidoteRemoveItemFromSetInBucket("guifi", "devices", strconv.Itoa(ID), dbHost, dbPort)
}

// Read all the devices from Antidote using João's REST server
func readDeviceIpv4AddressesFromAntidote(device cnml.DeviceIpv4Adddresses) cnml.DeviceIpv4Adddresses {

	for _, v := range goclidote.AntidoteReadItemsFromSetInBucket("guifi", fmt.Sprintf("device-%d", device.ID), dbHost, dbPort) {
		device.Addresses = append(device.Addresses, v)
	}

	return device
}

// Read all the devices from Antidote using João's REST server
func readDeviceIpv4sGraphserverFromAntidote(device cnml.DeviceIpv4sGraphserver) cnml.DeviceIpv4sGraphserver {

	for _, v := range goclidote.AntidoteReadItemsFromSetInBucket("guifi", fmt.Sprintf("device-%d", device.ID), dbHost, dbPort) {
		device.Addresses = append(device.Addresses, v)
	}

	return device
}

// Save a device ID to Antidote using João's REST server
func saveDeviceToAntidote(device cnml.DeviceIpv4Adddresses) bool {
	return goclidote.AntidoteAddItemToSetInBucket("guifi", "devices", fmt.Sprintf("%d", device.ID), dbHost, dbPort)
}

// Save a device ID to Antidote using João's REST server
func saveDeviceIpv4sGraphserverToAntidote(device cnml.DeviceIpv4sGraphserver) bool {
	return goclidote.AntidoteAddItemToSetInBucket("guifi", "devices", fmt.Sprintf("%d", device.ID), dbHost, dbPort)
}

// Save an IPv4 address to a device
func saveIpv4addresToDeviceToAntidote(device cnml.DeviceIpv4Adddresses, address string) bool {
	return goclidote.AntidoteAddItemToSetInBucket("guifi", fmt.Sprintf("device-%d", device.ID), address, dbHost, dbPort)
}

// Save an IPv4 address to a device
func saveIpv4addressToDeviceIpv4sGraphserverToAntidote(device cnml.DeviceIpv4sGraphserver, address string) bool {
	return goclidote.AntidoteAddItemToSetInBucket(fmt.Sprintf("device-%d", device.ID), "ipv4s", address, dbHost, dbPort)
}

// Save an SNMP name to a device in AntidoteDB
func saveSNMPNameToDeviceIpv4sGraphserverToAntidote(device cnml.DeviceIpv4sGraphserver, SNMPName string) bool {
	return goclidote.AntidoteAddItemToSetInBucket(fmt.Sprintf("device-%d", device.ID), "snmpnames", SNMPName, dbHost, dbPort)
}

// Save the GraphServer to a device
func saveGraphserverToDeviceIpv4sGraphserverToAntidote(device cnml.DeviceIpv4sGraphserver) bool {
	return goclidote.AntidoteSetRegisterInBucket(fmt.Sprintf("device-%d", device.ID), "graphserver", strconv.Itoa(device.GraphServer), dbHost, dbPort)
}

func removeGraphserverFromDeviceIpv4sGraphserver(device cnml.DeviceIpv4sGraphserver) bool {
	return goclidote.AntidoteRemoveRegisterInBucket(fmt.Sprintf("device-%d", device.ID), "graphserver", dbHost, dbPort)
}

func removeIpv4addressFromDeviceIpv4Adddresses(device cnml.DeviceIpv4Adddresses, address string) bool {
	return goclidote.AntidoteRemoveItemFromSetInBucket(fmt.Sprintf("device-%d", device.ID), "ipv4s", address, dbHost, dbPort)
}

// Remove an IPv4 address from a device
func removeIpv4addressFromDeviceIpv4sGraphserver(device cnml.DeviceIpv4sGraphserver, address string) bool {
	return goclidote.AntidoteRemoveItemFromSetInBucket(fmt.Sprintf("device-%d", device.ID), "ipv4s", address, dbHost, dbPort)
}

// Remove an SNMP name from a device
func removeSNMPNameFromDeviceIpv4sGraphserver(device cnml.DeviceIpv4sGraphserver, SNMPName string) bool {
	return goclidote.AntidoteRemoveItemFromSetInBucket(fmt.Sprintf("device-%d", device.ID), "snmpnames", SNMPName, dbHost, dbPort)
}

// Compare two arrays of strings
func compareStringArrays(array1 []string, array2 []string) bool {
	if len(array1) == len(array2) {
		for k := range array1 {
			if array1[k] != array2[k] {
				return false
			}
		}
		return true
	}
	return false
}

// Check if an int item is in an ints array
func isDeviceIPv4AddressesInArray(device cnml.DeviceIpv4Adddresses, devices []cnml.DeviceIpv4Adddresses) bool {
	for _, v := range devices {
		if v.ID == device.ID {
			return true
		}
	}
	return false
}

// Check if an int item is in an ints array
func isDeviceIpv4sGraphserverInArray(device cnml.DeviceIpv4sGraphserver, devices []cnml.DeviceIpv4sGraphserver) bool {
	for _, v := range devices {
		if v.ID == device.ID {
			return true
		}
	}
	return false
}

func isIPv4addressInDevicesArray(device cnml.DeviceIpv4Adddresses, address string) bool {
	for _, v := range device.Addresses {
		if v == address {
			return true
		}
	}
	return false
}

func isIPv4addressInDeviceIpv4sGraphserversArray(device cnml.DeviceIpv4sGraphserver, address string) bool {
	for _, v := range device.Addresses {
		if v == address {
			return true
		}
	}
	return false
}

func posDeviceInSlice(device cnml.DeviceIpv4sGraphserver, slice []cnml.DeviceIpv4sGraphserver) int {
	for k, v := range slice {
		if device.ID == v.ID {
			return k
		}
	}
	return -1
}

// Panic on error
func errCheck(err error, message string) {
	if err != nil {
		fmt.Println(message)
		panic(err)
	}
}