-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
187 lines (170 loc) · 4.28 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
package main
import (
"context"
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"path/filepath"
"sort"
"strings"
"syscall"
"time"
udev "github.com/jochenvg/go-udev"
)
// ---------------------------------------------------------------------
// Workers to run triggers
var Workers = 3
// Workers delay running scripts slightly to give OS time to register device
var WorkerDelay = 200 * time.Millisecond
// abstract the *Device type so I can create test entries
type device interface {
Action() string
Properties() map[string]string
PropertyValue(string) string
}
// ---------------------------------------------------------------------
func main() {
flagParse()
conf := getConfig(configfile, override_subsystems)
switch {
case list_devs:
displayDeviceList(conf)
case monit:
devchan := deviceChan(conf)
printerChan(devchan)
default:
devchan := deviceChan(conf)
matchchan := commandRunners(conf)
watchLoop(devchan, matchchan, conf)
}
}
// display the list of devices
func displayDeviceList(conf *Config) {
u := udev.Udev{}
e := u.NewEnumerate()
e.AddMatchTag("seat")
for _, sub := range conf.subsystems {
e.AddMatchSubsystem(sub)
}
e.AddMatchIsInitialized()
udev_devices, err := e.Devices()
if err != nil {
log.Fatal(err)
}
for _, d := range udev_devices {
log.Println(devString(d))
}
}
// Returns the channel of device events
func deviceChan(conf *Config) <-chan device {
u := udev.Udev{}
m := u.NewMonitorFromNetlink("udev")
m.FilterAddMatchTag("seat")
for _, sub := range conf.subsystems {
m.FilterAddMatchSubsystem(sub)
}
ctx, cancel := context.WithCancel(context.Background())
devchan := make(chan device)
ch, err := m.DeviceChan(ctx)
if err != nil {
log.Fatal(err)
}
go func() {
<-sighalt()
cancel()
}()
// wrap udev's chan in one that I can control the type
go func() {
for d := range ch {
devchan <- d
}
close(devchan)
}()
return devchan
}
// watch for signals to quit
func sighalt() <-chan os.Signal {
interrupts := make(chan os.Signal, 1)
signal.Notify(interrupts, os.Interrupt, syscall.SIGQUIT, syscall.SIGTERM)
return interrupts
}
// Print device stream
func printerChan(devchan <-chan device) {
for d := range devchan {
log.Println(devString(d))
}
}
// Run the commands for matching rules
// use a small pool in case a script is slow
func commandRunners(conf *Config) chan<- rule {
matchchan := make(chan rule, Workers*3)
for i := 0; i < Workers; i++ {
go func() {
for r := range matchchan {
time.Sleep(WorkerDelay)
log.Println("************************ rule fired: ", r.Command)
cmd := r.Command
if !filepath.IsAbs(cmd) {
cmd = filepath.Join(os.ExpandEnv(conf.ScriptPath),
r.Command)
}
out, err := exec.Command(cmd, r.Args...).CombinedOutput()
if err != nil {
log.Println(err)
}
if len(out) > 0 {
log.Printf("%s\n", out)
}
}
}()
}
return matchchan
}
// main loop
// monitors udev events, looks for matches and runs commands
func watchLoop(devchan <-chan device, matchchan chan<- rule, conf *Config) {
rate_limiter := map[string]struct{}{}
watched_actions := map[string]bool{}
for _, rule := range conf.Rules {
watched_actions[rule.Action] = true
}
for d := range devchan {
if watched_actions[d.Action()] {
for _, rule := range conf.Rules {
pval := strings.TrimSpace(d.PropertyValue(rule.PropName))
prop_test := strings.HasSuffix(pval, rule.PropValue)
action_test := rule.Action == d.Action()
if prop_test && action_test {
if _, ok := rate_limiter[rule.Command]; !ok {
rate_limiter[rule.Command] = struct{}{}
go func() {
time.Sleep(time.Second)
delete(rate_limiter, rule.Command)
}()
matchchan <- rule
}
}
}
}
}
close(matchchan)
}
// returns list of connected devices and properties
func devString(dev device) string {
properties := dev.Properties()
ordered_keys := make([]string, 0, len(properties))
result := make([]string, 0, len(properties)+1)
result = append(result, fmt.Sprintf("%s\n\n", strings.Repeat("-", 3)))
for k := range properties {
ordered_keys = append(ordered_keys, k)
}
sort.Sort(sort.StringSlice(ordered_keys))
for _, k := range ordered_keys {
v := properties[k]
result = append(result,
fmt.Sprintf("%s = \"%s\"\n", k, strings.TrimSpace(v)))
}
return strings.Join(result, "")
}