-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmain.go
83 lines (70 loc) · 1.67 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
package main
import (
"flag"
"log"
"os"
"os/signal"
"time"
)
func main() {
//Load the config file
var configFile string
var conf *config
flag.StringVar(&configFile, "configfile", "", "config file to use")
flag.Parse()
if configFile != "" {
var err error
conf, err = loadConfig(configFile)
if err != nil {
log.Fatal("failed to parse config file: ", err)
}
} else {
log.Println("defaulting to immediate shutdown and 1 second polling interval")
conf = &config{Shutdown: true, PollInterval: 1000, ShutdownTimeout: 10000}
}
initialDevices, err := enumerateDevices()
if err != nil {
log.Fatal(err)
}
deviceMap := map[device]int64{}
if len(initialDevices) > 0 {
now := time.Now().UnixNano()
for _, d := range initialDevices {
deviceMap[d] = now
}
} else {
log.Fatal("No devices found")
}
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt)
check := time.NewTicker(time.Duration(conf.PollInterval) * time.Millisecond)
log.Println("deadman started (press ctrl-c to exit)")
for {
select {
case <-check.C:
now := time.Now().UnixNano()
devices, err := enumerateDevices()
if err != nil {
log.Fatal(err)
}
// Look to see if there are any new devicies
for _, d := range devices {
if _, ok := deviceMap[d]; !ok {
log.Printf("New device: %s [%s]\n", d.Name, d.ID)
shutdownSequence(conf)
}
deviceMap[d] = now
}
// Look to see if any devices have been removed
for d, t := range deviceMap {
if t != now {
log.Printf("Device %s [%s] has been removed\n", d.Name, d.ID)
shutdownSequence(conf)
}
}
case <-sigint:
log.Println("SIGINT received")
os.Exit(0)
}
}
}