-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
356 lines (310 loc) · 8.71 KB
/
server.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
// Package server describes all server-side operations.
package server
import (
"encoding/json"
"io"
"log"
"net"
"os"
"os/signal"
"path/filepath"
"syscall"
"github.com/fgahr/tilo/config"
"github.com/fgahr/tilo/msg"
"github.com/fgahr/tilo/server/backend"
_ "github.com/mattn/go-sqlite3"
"github.com/pkg/errors"
)
var operations = make(map[string]Operation)
type Request struct {
Conn net.Conn
Cmd msg.Cmd
}
func (req *Request) Close() error {
return req.Conn.Close()
}
type Operation interface {
// Execute server-side behaviour based on the command
ServerExec(srv *Server, req *Request) error
}
func RegisterOperation(name string, operation Operation) {
operations[name] = operation
}
// A tilo Server. When the configuration is provided, the remaining fields
// are filled by the .init() method.
type Server struct {
shutdownChan chan struct{} // Used to communicate shutdown requests
conf *config.Opts // Configuration parameters for this instance
Backend backend.Backend // The database backend
socketListener net.Listener // Listener on the client request socket
CurrentTask msg.Task // The currently active task, if any
listeners []NotificationListener // Listeners for task change notifications
}
// Start server operation.
// This function will block until server shutdown.
func Run(conf *config.Opts) error {
s := Server{conf: conf}
if err := s.init(); err != nil {
return errors.Wrap(err, "Failed to initialize server")
}
// Ensure clean shutdown if at all possible.
defer s.enforceCleanup()
defer close(s.shutdownChan)
s.main()
return nil
}
// Check whether the server is running.
func IsRunning(conf *config.Opts) (bool, error) {
_, err := os.Stat(conf.Socket.Value)
if os.IsNotExist(err) {
return false, nil
} else if err != nil {
return false, errors.Wrap(err, "Could not determine server status")
}
return true, nil
}
// Check whether the server is currently in shutdown.
func (s *Server) shuttingDown() bool {
select {
case <-s.shutdownChan:
return true
default:
return false
}
}
// Make sure the configuration directory exists, creating it if necessary.
func ensureDirExists(dir string) error {
return os.MkdirAll(dir, 0700)
}
// Start the server, initiating required connections.
func (s *Server) init() error {
if running, err := IsRunning(s.conf); err != nil {
return err
} else if running {
return errors.New("Cannot start server: Already running.")
}
s.shutdownChan = make(chan struct{})
// Create directories if necessary
if err := ensureDirExists(s.conf.ConfigDir()); err != nil {
return err
}
if err := ensureDirExists(s.conf.SocketDir()); err != nil {
return err
}
// Establish database connection.
backend := backend.From(s.conf)
if err := backend.Init(); err != nil {
s.socketListener.Close()
backend.Close()
return err
} else {
s.Backend = backend
}
// Open request socket.
if requestListener, err := net.Listen(s.conf.Protocol.Value, s.conf.Socket.Value); err != nil {
return err
} else {
s.socketListener = requestListener
}
s.CurrentTask = msg.IdleTask()
return nil
}
// Enforce cleanup when the server stops.
func (s *Server) enforceCleanup() {
if r := recover(); r != nil {
s.logWarn("Shutting down.", r)
}
s.shutdown()
}
// Server main loop: process incoming requests.
func (s *Server) main() {
// Signal channel needs to be buffered, see documentation.
sigChan := make(chan os.Signal, 1)
srvChan := make(chan net.Conn)
defer close(srvChan)
// Enable cleanup on receiving SIGTERM.
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
// Enable connection processing.
go s.waitForConnection(s.socketListener, srvChan)
s.logDebug("Starting server main loop.")
MainLoop:
for {
select {
case conn := <-srvChan:
s.serveConnection(conn)
case sig := <-sigChan:
s.logDebug("Received signal: ", sig)
break MainLoop
case <-s.shutdownChan:
break MainLoop
}
}
}
// Wait for a client to connect. Send connections to the given channel.
func (s *Server) waitForConnection(lst net.Listener, srvChan chan<- net.Conn) {
for {
if conn, err := lst.Accept(); err != nil {
if s.shuttingDown() {
// Ignore shutdown-related errors.
break
}
s.logError(errors.Wrap(err, "Error listening for connections"))
} else {
srvChan <- conn
}
}
}
// Serve a notification listener connection, keeping it open.
func (s *Server) serveConnection(conn net.Conn) {
dec := json.NewDecoder(conn)
cmd := msg.Cmd{}
if err := dec.Decode(&cmd); err != nil {
s.logError(errors.Wrap(err, "Failed to decode command"))
}
if err := s.Dispatch(&Request{conn, cmd}); err != nil {
s.logError(errors.Wrap(err, "Unable to execute command"))
}
}
func (s *Server) Dispatch(req *Request) error {
s.logCommand(req.Cmd)
command := req.Cmd.Op
op := operations[command]
if op == nil {
return errors.New("No such operation: " + command)
}
op.ServerExec(s, req)
return nil
}
// Send a notification to all registered listeners.
func (s *Server) notifyListeners() {
ntf := TaskNotification(s.CurrentTask)
s.logDebug("Notifying listeners:", ntf)
if len(s.listeners) > 0 {
remainingListeners := make([]NotificationListener, 0)
for _, lst := range s.listeners {
if err := lst.Notify(ntf); err != nil {
s.logInfo("Could not notify listener, disconnecting:", err)
lst.disconnect()
} else {
remainingListeners = append(remainingListeners, lst)
}
}
s.listeners = remainingListeners
}
}
// Notify all connected listeners of shutdown and disconnect them.
func (s *Server) disconnectAllListeners() {
ntf := shutdownNotification()
for _, lst := range s.listeners {
lst.Notify(ntf)
if err := lst.disconnect(); err != nil {
s.logWarn("Error closing listener connection:", err)
}
}
}
// Initiate shutdown, closing open connections.
func (s *Server) shutdown() {
var err error
s.logInfo("Shutting down server..")
// When the shutdown is initiated by a message, the task is stopped prior.
// If shutdown is in response to a signal, there is nothing else to do here.
s.StopCurrentTask()
if len(s.listeners) > 0 {
s.logInfo("Disconnecting listeners")
s.disconnectAllListeners()
}
s.logInfo("Closing socket..")
err = s.socketListener.Close()
if err != nil {
s.logError(err)
} else {
s.logInfo("OK")
}
// FIXME: Directory should probably not be removed unless in /tmp
s.logInfo("Removing temporary directory..")
err = os.RemoveAll(s.conf.SocketDir())
if err != nil {
s.logError(err)
} else {
s.logInfo("OK")
}
s.logInfo("Shutdown complete.")
}
// TODO: Move to client package?
// Start a server in a background process.
func StartInBackground(conf *config.Opts) (int, error) {
sysProcAttr := syscall.SysProcAttr{}
// Prepare high-level process attributes
confDir := filepath.Dir(conf.ConfFile.Value)
if err := ensureDirExists(confDir); err != nil {
return 0, errors.Wrap(err, "Unable to start server in background")
}
procAttr := os.ProcAttr{
Dir: confDir,
Env: conf.MergeIntoEnv(os.Environ()),
Files: []*os.File{nil, nil, nil}, // stdin, stdout, stderr
Sys: &sysProcAttr,
}
// No need to keep track of the spawned process
executable, err := os.Executable()
if err != nil {
return 0, errors.Wrap(err, "Unable to determine server executable")
}
// NOTE: Due to dependency resolution issues, there is no direct way to tie
// the arguments to the corresponding operation and its arguments. It could
// be done indirectly.
proc, err := os.StartProcess(executable, []string{executable, "server", "run"}, &procAttr)
if err != nil {
return 0, errors.Wrap(err, "Unable to start server process")
}
return proc.Pid, nil
}
// Serialize obj to JSON, add a linebreak, and send it to the writer.
func writeJsonLine(obj interface{}, w io.Writer) error {
data, err := json.Marshal(obj)
if err != nil {
panic(err)
}
// Ending messages with a linebreak makes writing listeners easier.
data = append(data, '\n')
_, err = w.Write(data)
return err
}
func (s *Server) logError(err error) {
if err == nil {
return
}
if s.conf.ShouldLogAny() {
log.Println(err)
}
}
func (s *Server) logWarn(msg ...interface{}) {
if s.conf.ShouldLogWarnings() {
log.Println(msg...)
}
}
func (s *Server) logFmtWarn(format string, v ...interface{}) {
if s.conf.ShouldLogWarnings() {
log.Printf(format, v...)
}
}
func (s *Server) logInfo(msg ...interface{}) {
if s.conf.ShouldLogInfo() {
log.Println(msg...)
}
}
func (s *Server) logFmtInfo(format string, v ...interface{}) {
if s.conf.ShouldLogInfo() {
log.Printf(format, v...)
}
}
func (s *Server) logDebug(msg ...interface{}) {
if s.conf.ShouldLogDebug() {
log.Println(msg...)
}
}
func (s *Server) logFmtDebug(format string, v ...interface{}) {
if s.conf.ShouldLogDebug() {
log.Printf(format, v...)
}
}