-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
executable file
·130 lines (109 loc) · 2.57 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
package main
import (
"flag"
"fmt"
"github.com/sepuka/gowatcher/command"
"github.com/sepuka/gowatcher/config"
"github.com/sepuka/gowatcher/definition/logger"
"github.com/sepuka/gowatcher/definition/transport"
"github.com/sepuka/gowatcher/services"
"github.com/sepuka/gowatcher/watchers"
"github.com/sevlyar/go-daemon"
"go.uber.org/zap"
"os"
"syscall"
"time"
)
const (
daemonName = "gowatcher"
)
var (
buildstamp = "buildstamp not present"
githash = "githash not present"
stop = make(chan struct{})
done = make(chan struct{})
watcherResult chan command.Result
log *zap.Logger
signal = flag.String("s", "", "send signal to the daemon\nstop - to stop daemon")
daemonize = flag.Bool("d", false, "Daemonize gowatcher")
testMode = flag.Bool("t", false, "Test mode")
version = flag.Bool("version", false, "Print version info")
cntxt = &daemon.Context{
PidFileName: "pid",
PidFilePerm: 0644,
WorkDir: "./",
Umask: 027,
Args: []string{daemonName},
}
)
func init() {
services.Build(config.AppConfig)
services.Container.Fill(transport.DefTransportChan, &watcherResult)
services.Container.Fill(logger.DefLogger, &log)
}
func main() {
go transmitter()
flag.Parse()
daemon.AddCommand(daemon.StringFlag(signal, "stop"), syscall.SIGTERM, termHandler)
if *testMode {
watcherResult <- watchers.Test()
time.Sleep(time.Second * 3)
return
}
if *version {
fmt.Println("Build time: ", buildstamp)
fmt.Println("Git hash: ", githash)
return
}
if isDaemonFlagsPresent() {
d, err := cntxt.Search()
if err != nil {
log.Fatal("Unable send signal to the daemon", zap.Any("err", err))
}
daemon.SendCommands(d)
return
}
if !daemon.WasReborn() && !*daemonize {
watchers.RunWatchers()
log.Info("Press <Ctrl>+C to exit")
daemonLoop()
return
}
child, err := cntxt.Reborn()
if err != nil {
log.Fatal("Unable to reborn", zap.Any("err", err))
}
if child != nil {
return
} else {
defer cntxt.Release()
}
log.Info("watcher daemon started")
watchers.RunWatchers()
go daemonLoop()
err = daemon.ServeSignals()
if err != nil {
log.Debug("Error of signal serving", zap.Any("err", err))
}
log.Info("daemon terminated.")
}
func isDaemonFlagsPresent() bool {
return len(daemon.ActiveFlags()) > 0
}
func daemonLoop() {
for {
time.Sleep(time.Second)
if _, ok := <-stop; ok {
break
}
}
done <- struct{}{}
}
func termHandler(sig os.Signal) error {
log.Info("terminating...")
stop <- struct{}{}
if sig == syscall.SIGQUIT {
<-done
}
return daemon.ErrStop
}