-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmain.go
311 lines (259 loc) · 7.83 KB
/
main.go
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
package main
import (
"github.com/cretz/bine/tor"
"github.com/jessevdk/go-flags"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/the-lightning-land/sweetd/dispenser"
"github.com/the-lightning-land/sweetd/machine"
"github.com/the-lightning-land/sweetd/network"
"github.com/the-lightning-land/sweetd/nodeman"
"github.com/the-lightning-land/sweetd/pairing"
"github.com/the-lightning-land/sweetd/sweetdb"
"github.com/the-lightning-land/sweetd/sweetlog"
"github.com/the-lightning-land/sweetd/updater"
"net/http"
"os"
"os/signal"
"path/filepath"
// Blank import to set up profiling HTTP handlers.
_ "net/http/pprof"
)
var (
// commit stores the current commit hash of this build. This should be set using -ldflags during compilation.
Commit string
// version stores the version string of this build. This should be set using -ldflags during compilation.
Version string
// date stores the date of this build. This should be set using -ldflags during compilation.
Date string
)
// sweetdMain is the true entry point for sweetd. This is required since defers
// created in the top-level scope of a main method aren't executed if os.Exit() is called.
func sweetdMain() error {
sweetLog := sweetlog.New()
log.SetOutput(os.Stdout)
log.SetLevel(log.InfoLevel)
log.AddHook(sweetLog)
// load cli configuration and defaults
cfg, err := loadConfig()
if e, ok := err.(*flags.Error); ok && e.Type == flags.ErrHelp {
return nil
} else if err != nil {
return errors.Errorf("Failed parsing arguments: %v", err)
}
// set logger into debug mode if called with --debug
if cfg.Debug {
log.SetLevel(log.DebugLevel)
log.Info("Setting debug mode.")
}
log.Debug("Loaded config.")
// print version of the daemon
log.Infof("Version %s (commit %s)", Version, Commit)
log.Infof("Built on %s", Date)
if cfg.ShowVersion {
// return without error if only the version string was requested
return nil
}
if cfg.Profiling != nil && cfg.Profiling.Listen != "" {
go func() {
log.Infof("Starting profiling server on %v", cfg.Profiling.Listen)
// redirect the root path
http.Handle("/", http.RedirectHandler("/debug/pprof", http.StatusSeeOther))
// All other handlers are registered on DefaultServeMux through the import of pprof
err := http.ListenAndServe(cfg.Profiling.Listen, nil)
if err != nil {
log.Errorf("Could not run profiler: %v", err)
}
}()
}
// sweet.db persistently stores all dispenser configurations and settings
sweetDB, err := sweetdb.Open(cfg.DataDir)
if err != nil {
return errors.Errorf("Could not open sweet.db: %v", err)
}
log.Infof("Opened sweet.db")
defer func() {
err := sweetDB.Close()
if err != nil {
log.Errorf("Could not close sweet.db: %v", err)
} else {
log.Info("Closed sweet.db.")
}
}()
// network, which acts as the core connectivity
// provider for all other components
var net network.Network
if cfg.Net.Interface != "" {
net = network.NewWpaNetwork(&network.Config{
Interface: cfg.Net.Interface,
Logger: log.WithField("system", "network"),
})
log.Info("Created network.")
} else {
net = network.NewMockNetwork()
log.Info("Created mock network.")
}
err = net.Start()
if err != nil {
return errors.Errorf("Could not start network: %v", err)
}
defer func() {
err = net.Stop()
if err != nil {
log.Errorf("Could not properly shut down network: %v", err)
} else {
log.Info("Stopped network.")
}
}()
// updater which takes care of system updates
var u updater.Updater
switch cfg.Updater {
case "none":
u = updater.NewNoopUpdater()
log.Info("Created noop updater.")
case "mender":
u = updater.NewMenderUpdater(&updater.MenderUpdaterConfig{
Logger: log.WithField("system", "updater"),
DB: sweetDB,
})
log.Info("Created Mender updater.")
default:
return errors.Errorf("Unknown updater type %v", cfg.Updater)
}
err = u.Setup()
if err != nil {
return errors.Errorf("unable to set up updater: %v", err)
}
// hardware machine controller
var m machine.Machine
switch cfg.Machine {
case "raspberry":
m = machine.NewDispenserMachine(&machine.DispenserMachineConfig{
TouchPin: cfg.Raspberry.TouchPin,
MotorPin: cfg.Raspberry.MotorPin,
BuzzerPin: cfg.Raspberry.BuzzerPin,
})
log.Infof("Created Raspberry Pi machine on touch pin %v, motor pin %v and buzzer pin %v.",
cfg.Raspberry.TouchPin, cfg.Raspberry.MotorPin, cfg.Raspberry.BuzzerPin)
case "mock":
m = machine.NewMockMachine(cfg.Mock.Listen)
log.Info("Created a mock machine.")
default:
return errors.Errorf("Unknown machine type %v", cfg.Machine)
}
if err := m.Start(); err != nil {
return errors.Errorf("Could not start machine: %v", err)
}
defer func() {
err := m.Stop()
if err != nil {
log.Errorf("Could not properly stop machine: %v", err)
} else {
log.Infof("Stopped machine.")
}
}()
// start Tor node
t, err := tor.Start(nil, &tor.StartConf{
ExePath: cfg.Tor.Path,
TempDataDirBase: os.TempDir(),
RetainTempDataDir: false,
DebugWriter: log.WithField("system", "tor").WriterLevel(log.DebugLevel),
})
if err != nil {
return errors.Errorf("Could not start tor: %v", err)
}
log.Infof("Started Tor.")
defer func() {
t.StopProcessOnClose = true
t.DeleteDataDirOnClose = true
err := t.Close()
if err != nil {
log.Errorf("Could not properly stop Tor: %v", err)
} else {
log.Infof("Stopped Tor.")
}
}()
nodeman := nodeman.New(&nodeman.Config{
NodesDataDir: filepath.Join(cfg.DataDir, "nodes"),
DB: sweetDB,
Tor: t,
LogCreator: func(node string) nodeman.Logger {
logger := log.WithField("system", "nodeman")
if node != "" {
logger = logger.WithField("node", node)
}
return logger
},
})
// pairingAdapter adapts the dispenser API to one compatible
// with the pairing controller
pairingAdapter := &dispenser.PairingAdapter{}
if cfg.Pairing.Interface != "" {
pairingAdapter.Pairing, err = pairing.NewController(&pairing.BLEControllerConfig{
Logger: log.WithField("system", "pairing"),
AdapterId: cfg.Pairing.Interface,
Dispenser: pairingAdapter,
})
if err != nil {
return errors.Errorf("unable to create BLE pairing controller: %v", err)
}
log.Infof("created BLE pairing controller")
} else {
pairingAdapter.Pairing = pairing.NewNoopController()
log.Info("created no-op pairing controller as no interface was specified")
}
// central controller for everything the dispenser does
dispenser := dispenser.NewDispenser(&dispenser.Config{
Nodeman: nodeman,
Machine: m,
DB: sweetDB,
Updater: u,
SweetLog: sweetLog,
Logger: log.WithField("system", "dispenser"),
Tor: t,
Network: net,
Pairing: pairingAdapter.Pairing,
})
pairingAdapter.Dispenser = dispenser
log.Infof("created dispenser")
err = pairingAdapter.Pairing.Start()
if err != nil {
return errors.Errorf("unable to start pairing controller: %v", err)
}
log.Info("started pairing controller")
defer func() {
err := pairingAdapter.Pairing.Stop()
if err != nil {
log.Errorf("unable to stop pairing controller: %v", err)
} else {
log.Info("stopped pairing controller")
}
}()
// Handle interrupt signals correctly
go func() {
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
sig := <-signals
log.Info(sig)
log.Info("Received an interrupt, stopping dispenser...")
dispenser.Stop()
}()
// blocks until the dispenser is stopped
err = dispenser.RunAndWait()
if err != nil {
return errors.Errorf("unable to run: %v", err)
}
// finish without error
return nil
}
func main() {
// Call the "real" main in a nested manner so the defers will properly
// be executed in the case of a graceful shutdown.
if err := sweetdMain(); err != nil {
if e, ok := err.(*flags.Error); ok && e.Type == flags.ErrHelp {
} else {
log.WithError(err).Println("Failed running sweetd.")
}
os.Exit(1)
}
}