-
Notifications
You must be signed in to change notification settings - Fork 8
/
example.go
222 lines (180 loc) · 4.86 KB
/
example.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
package main
import (
"context"
"fmt"
"github.com/One-com/gone/daemon"
"github.com/One-com/gone/daemon/ctrl"
gonehttp "github.com/One-com/gone/http"
"github.com/One-com/gone/log"
"github.com/One-com/gone/log/syslog"
"github.com/One-com/gone/sd"
"github.com/One-com/gone/signals"
"io"
stdlog "log"
"net/http"
"os"
"strconv"
"syscall"
"time"
)
//----------------- The actual server ----------------------
func myHandlerFunc(cfg string, revision int) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, fmt.Sprintf("I'm here. cfg: %s, rev: %d, pid %d\n", cfg, revision, os.Getpid()))
})
}
func newHTTPServer(handler http.HandlerFunc) (s *gonehttp.Server) {
gonelog := log.NewStdlibAdapter(log.Default(), syslog.LOG_CRIT)
errorlog := stdlog.New(gonelog, "", stdlog.LstdFlags)
// basic HTTP server
s1 := &http.Server{
//Addr: ":4321",
Handler: handler,
ErrorLog: errorlog,
}
s3 := &gonehttp.Server{
Name: "Example",
Server: s1,
Listeners: daemon.ListenerGroup{daemon.ListenerSpec{Addr: ":4321"}},
}
return s3
}
type trivialServer struct{}
func (t *trivialServer) Serve(ctx context.Context) error {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
LOOP:
for {
select {
case <-ticker.C:
log.Println("trivial tick")
case <-ctx.Done():
break LOOP
}
}
return nil
}
func (t *trivialServer) Description() string {
return "Trivial"
}
func loadConfig(cfg string) daemon.ConfigFunc {
var revision int
cf := daemon.ConfigFunc(
func() (s []daemon.Server, c []daemon.CleanupFunc, err error) {
revision++
log.Printf("Loading config. rev: %d", revision)
s = make([]daemon.Server, 2)
c = make([]daemon.CleanupFunc, 1)
s[0] = newHTTPServer(http.HandlerFunc(myHandlerFunc(cfg, revision)))
s[1] = &trivialServer{}
localRevision := revision
c[0] = func() error {
log.Printf("Ran cleanup, rev: %d", localRevision)
return nil
}
return
})
return cf
}
//----------------- Signal handling ----------------------
func onSignalExit() {
log.Println("Signal Exit")
daemon.Exit(false)
}
func onSignalExitGraceful() {
log.Println("Signal Exit - graceful")
sd.Notify(0, "STOPPING=1")
daemon.Exit(true)
}
func onSignalReload() {
log.Println("Signal Reload")
sd.Notify(0, "RELOADING=1")
daemon.Reload()
}
func onSignalRespawn() {
log.Println("Signal Respawn")
daemon.ReplaceProcess(syscall.SIGTERM)
}
func onSignalIncLogLevel() {
log.IncLevel()
log.ALERT(fmt.Sprintf("Log level: %d", log.Level()))
}
func onSignalDecLogLevel() {
log.DecLevel()
log.ALERT(fmt.Sprintf("Log level: %d\n", log.Level()))
}
func serverLogFunc(level int, message string) {
log.Log(syslog.Priority(level), message)
}
var procControl = &procCommand{}
func init() {
/* Setup signalling */
handledSignals := signals.Mappings{
syscall.SIGINT: onSignalExit,
syscall.SIGTERM: onSignalExitGraceful,
syscall.SIGHUP: onSignalReload,
syscall.SIGUSR2: onSignalRespawn,
syscall.SIGTTIN: onSignalIncLogLevel,
syscall.SIGTTOU: onSignalDecLogLevel,
}
log.SetLevel(syslog.LOG_DEBUG)
daemon.SetLogger(serverLogFunc)
ctrl.RegisterCommand("daemon", procControl)
signals.RunSignalHandler(handledSignals)
}
//---------------------------------------------------------------------------
func main() {
configureFunc := loadConfig("myconf")
log.Println("Starting server", "PID", os.Getpid())
runoptions := []daemon.RunOption{
daemon.Configurator(configureFunc),
daemon.ControlSocket("", "ctrl.sock"),
daemon.ShutdownTimeout(time.Duration(4 * time.Second)),
daemon.SdNotifyOnReady(true, "Ready and serving"),
daemon.SignalParentOnReady(),
}
err := daemon.Run(runoptions...)
if err != nil {
log.Println(err)
}
sd.Notify(sd.NotifyUnsetEnv, "STATUS=Terminated")
log.Println("Halted")
}
// ---------------------------------------------------------------
// A simple control socket command controlling the daemon process
type procCommand struct{}
func (p *procCommand) ShortUsage() (syntax, comment string) {
syntax = "[reload|respawn|kill|stop <timeout seconds>]"
comment = "control the daemon process"
return
}
func (p *procCommand) Usage(cmd string, w io.Writer) {
fmt.Fprintln(w, cmd, "control the process")
}
func (p *procCommand) Invoke(ctx context.Context, w io.Writer, cmd string, args []string) (async func(), persistent string, err error) {
cmd = args[0]
switch cmd {
case "reload":
onSignalReload()
case "kill":
onSignalExit()
case "stop":
var timeout time.Duration
if len(args) > 1 && args[1] != "" {
var to int
to, err = strconv.Atoi(args[1])
if err != nil {
return
}
timeout = time.Second * time.Duration(to)
}
log.Printf("Signal Exit - graceful: %s", timeout.String())
sd.Notify(0, "STOPPING=1")
daemon.ExitGracefulWithTimeout(timeout)
case "respawn":
onSignalRespawn()
default:
fmt.Fprintln(w, "Unknown action")
}
return
}