-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
executable file
·119 lines (99 loc) · 2.49 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
// Copyright (c) 2022 Cisco All Rights Reserved.
package main
import (
"encoding/json"
"flag"
"fmt"
"net/http"
"regexp"
"strings"
"example.com/gocr/src/api"
"example.com/gocr/src/config"
"example.com/gocr/src/events"
"example.com/gocr/src/filewatcher"
"example.com/gocr/src/httpapi"
"example.com/gocr/src/info"
"example.com/gocr/src/process"
)
type ExecArgs struct {
cmds map[string]string
}
func (e *ExecArgs) Set(value string) error {
parts := strings.Split(value, "->")
key, val := strings.TrimSpace(parts[0]), strings.TrimSpace(strings.Join(parts[1:], "->"))
e.cmds[key] = val
return nil
}
func (e *ExecArgs) String() string {
return fmt.Sprintf("%#v", e)
}
var cfg = flag.String("cfgfile", "", "config file")
var port = flag.Int("port", 7357, "listening port")
var configJson = flag.String("cfgjson", "", "config from json arg")
var startup = flag.String("startup", "", "execute command at startup")
var debug = flag.Bool("debug", false, "debug logs")
func main() {
execes := ExecArgs{cmds: make(map[string]string)}
flag.Var(&execes, "exec", "exec command")
flag.Parse()
conf := config.DefaultConfig
if *cfg != "" {
if err := conf.LoadFile(*cfg); err != nil {
info.Printf("no config file found:%v\n", *cfg)
return
}
}
if *configJson != "" {
if err := json.Unmarshal([]byte(*configJson), &conf.Strimap); err != nil {
info.Printf("unable parse config json:%v", err)
return
}
}
if *debug {
info.Printf("%#v\n", conf)
}
filesToWatch := conf.CollectFileEvents()
filewatcher.Start()
defer filewatcher.Stop()
for _, f := range filesToWatch {
filewatcher.Add(f)
}
api := api.New(process.New())
go func() {
for {
event := <-events.DefaultPipe
if *debug {
info.Println(event)
}
actions, err := conf.ActionsForEvent(event.Args())
if err != nil {
if config.IsNotFound(err) {
continue
}
info.Println("event error", err)
}
res := api.RunActions(actions)
for _, r := range res {
if r.Error != nil {
info.Println("error:", r)
}
}
}
}()
httpApi := httpapi.New()
apiRegx := regexp.MustCompile(httpapi.APIRegxPattern)
httpApi.HandleFunc(apiRegx, httpapi.CommandHandler(api, apiRegx))
if *startup != "" {
api.Exec("startup", *startup)
}
for k, c := range execes.cmds {
api.Exec(k, c)
}
events.Add(events.OnStart())
if *port != 0 {
info.Printf("listening on port:%v\n", *port)
info.Println(http.ListenAndServe(fmt.Sprintf(":%v", *port), httpApi))
} else {
info.Printf("listening port disabled\n")
}
}