Developing lightweight computation at the DSG edge

dump-monitor-assign.go 5.18 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
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"os"
	"os/signal"
	"time"
	"uc-monitor-go-test/cnml"
	"uc-monitor-go-test/goclidote"

	"github.com/golang/glog"
)

type JSONDeviceMonitorAssignation struct {
	Device   string   `json:"device"`
	Monitors []string `json:"monitors"`
}

type JSONAllData struct {
	Devices      []string                       `json:"devices"`
	Monitors     []string                       `json:"monitors"`
	Assignations []JSONDeviceMonitorAssignation `json:"assignations"`
}

// Define error levels

// FATAL output code
var FATAL = 1

// ERROR output code
var ERROR = 2

// WARNING output code
var WARNING = 3

// INFO output code
var INFO = 4

// DEFAULTFILEMODE for created files
var DEFAULTFILEMODE os.FileMode = 0755

//Default settings and descriptions

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"

var globalAssignCheckInterval = 5 //60
var globalAssignCheckIntervalHelp = "Interval (in seconds) in which to check for changes in the local devices assignation list"

// Global data structures
var globalAssign []cnml.DeviceMonitorAssignation
var monitorsList []string
var devicesList []string

func main() {
	//Initialize the service (read the configuration flags, etc.)
	initialize()

	// Handle interrupt signals in order to terminate gracefully
	signalChan := make(chan os.Signal, 1)
	cleanupDone := make(chan bool)
	signal.Notify(signalChan, os.Interrupt)
	go func() {
		for _ = range signalChan {
			fmt.Println("\nReceived an interrupt, quitting...")
			cleanupDone <- true
		}
	}()
	<-cleanupDone
	fmt.Println("\nBye!")
}

// The initialize() function manages the execution parameters, sets timers, etc.
func initialize() {

	fmt.Println("Initializing...")

	// Manage command line flags and execution settings
	initializeFlags()

	// Initialize periodic timers
	initializeTimers()

	// The application is now ininitialized; entering the loop
	fmt.Println("Initialization done. Entering infinite loop...")
}

func initializeTimers() {
	// Initialize the local assignation check timer
	startGlobalAssignTimer()
}

// The initializeFlags function initializes the command line flags
func initializeFlags() {

	//Define and parse command line flags
	dbHostPtr := flag.String("db_host", dbHost, dbHostHelp)
	dbPortPtr := flag.Int("db_port", dbPort, dbPortHelp)
	globalAssignCheckIntervalPtr := flag.Int("globalAssignCheckInterval", globalAssignCheckInterval, globalAssignCheckIntervalHelp)

	flag.Parse()

	dbHost = *dbHostPtr
	dbPort = *dbPortPtr
	if *globalAssignCheckIntervalPtr > 0 {
		globalAssignCheckInterval = *globalAssignCheckIntervalPtr
	}
}

func getCnmlDevicesList() []cnml.DeviceIpv4sGraphserver {
	return goclidote.ReadDevicesFromAntidote(dbHost, dbPort)
}

func getGlobalAssignationList() []cnml.DeviceMonitorAssignation {
	var newAssign []cnml.DeviceMonitorAssignation
	for _, v := range getCnmlDevicesList() {
		{
			var newDev cnml.DeviceMonitorAssignation
			newDev.Device.ID = v.ID
			newDev.Device.Addresses = v.Addresses
			newDev.MonitorID = goclidote.AntidoteReadItemsFromSetInBucket(fmt.Sprintf("device-%d", v.ID), "monitors", dbHost, dbPort)
			newAssign = append(newAssign, newDev)
		}
	}
	return newAssign
}

func startGlobalAssignTimer() {
	globalAssignTicker := time.NewTicker(time.Duration(globalAssignCheckInterval) * time.Second)
	go func() {
		for range globalAssignTicker.C {
			fmt.Println("Getting monitors list...")
			monitorsList = getCurrentMonitorsList()
			fmt.Println("The current monitors list contains", len(monitorsList), "monitors")

			fmt.Println("Getting devices list...")
			devicesList = getCurrentDevicesList()
			fmt.Println("The current devices list contains", len(devicesList), "devices")

			fmt.Println("Getting global assignation list...")
			globalAssign = getGlobalAssignationList()
			fmt.Println("The global assignation list contains", len(globalAssign), "devices")

			var dataToExport JSONAllData

			dataToExport.Devices = devicesList
			dataToExport.Monitors = monitorsList
			for _, v := range globalAssign {
				var newAssg JSONDeviceMonitorAssignation
				newAssg.Device = fmt.Sprintf("%d", v.Device.ID)
				newAssg.Monitors = v.MonitorID
				dataToExport.Assignations = append(dataToExport.Assignations, newAssg)
			}

			outFile, _ := os.Create("/tmp/out.json")
			defer outFile.Close()
			jnodes, _ := json.Marshal(dataToExport)

			//fmt.Println(string(jnode))
			//outFile.WriteString(string(jnodes))
			outFile.WriteString(fmt.Sprintf("data = %s", string(jnodes)))

		}
	}()
}

func getCurrentMonitorsList() []string {
	return goclidote.AntidoteReadItemsFromSetInBucket("guifi", "monitors", dbHost, dbPort)
}

func getCurrentDevicesList() []string {
	allDevs := goclidote.ReadDevicesFromAntidote(dbHost, dbPort)
	var devsID []string
	for _, v := range allDevs {
		devsID = append(devsID, fmt.Sprintf("%d", v.ID))
	}
	return devsID
}

func errCheck(e error, level int, message string) {
	if message == "" {
		message = "Unknown error"
	}
	if e != nil {
		switch level {
		case FATAL:
			glog.Fatalln(message, e)
		case ERROR:
			glog.Errorln(message, e)
		case WARNING:
			glog.Warningln(message, e)
		default:
			glog.Infoln(message, e)
		}
	}
}