-
Notifications
You must be signed in to change notification settings - Fork 16
/
serve.go
103 lines (91 loc) · 2.57 KB
/
serve.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
package main
import (
"fmt"
"github.com/eywa/configs"
"github.com/eywa/connections"
. "github.com/eywa/loggers"
"github.com/eywa/models"
"github.com/eywa/pubsub"
"github.com/zenazn/goji/graceful"
"io/ioutil"
"log"
"os"
"strconv"
)
func serve() {
cert := configs.Config().Security.SSL.CertFile
key := configs.Config().Security.SSL.KeyFile
if len(cert) > 0 {
if _, err := os.Stat(cert); os.IsNotExist(err) {
log.Fatalln(fmt.Sprintf("cert file doesn't exist at: %s\n", cert))
}
}
if len(key) > 0 {
if _, err := os.Stat(key); os.IsNotExist(err) {
log.Fatalln(fmt.Sprintf("key file doesn't exist at: %s\n", key))
}
}
go func() {
if len(cert) > 0 && len(key) > 0 {
Logger.Info(fmt.Sprintf("Eywa started listening to port %d with SSL", configs.Config().Service.ApiPort))
graceful.ListenAndServeTLS(
":"+strconv.Itoa(configs.Config().Service.ApiPort),
cert,
key,
HttpRouter(),
)
} else {
Logger.Info(fmt.Sprintf("Eywa started listening to port %d", configs.Config().Service.ApiPort))
graceful.ListenAndServe(
":"+strconv.Itoa(configs.Config().Service.ApiPort),
HttpRouter(),
)
}
}()
go func() {
if len(cert) > 0 && len(key) > 0 {
Logger.Info(fmt.Sprintf("Connection Manager started listening to port %d with SSL", configs.Config().Service.DevicePort))
graceful.ListenAndServeTLS(
":"+strconv.Itoa(configs.Config().Service.DevicePort),
cert,
key,
DeviceRouter(),
)
} else {
Logger.Info(fmt.Sprintf("Connection Manager started listening to port %d", configs.Config().Service.DevicePort))
graceful.ListenAndServe(
":"+strconv.Itoa(configs.Config().Service.DevicePort),
DeviceRouter(),
)
}
}()
graceful.HandleSignals()
graceful.PreHook(func() {
Logger.Info("Eywa received signal, gracefully stopping...")
})
graceful.PreHook(func() {
close(connections.HttpCloseChan)
})
graceful.PostHook(func() {
Logger.Info("Waiting for websockets to drain...")
connections.CloseCMs()
Logger.Info("Connection Manager closed.")
})
graceful.PostHook(func() { models.CloseDB() })
graceful.PostHook(func() { models.CloseIndexClient() })
graceful.PostHook(func() {
Logger.Info("Eywa stopped")
})
graceful.PostHook(func() { CloseLogger() })
graceful.PostHook(func() { pubsub.Close() })
graceful.PostHook(func() { removePidFile() })
createPidFile()
graceful.Wait()
}
func createPidFile() error {
pid := os.Getpid()
return ioutil.WriteFile(configs.Config().Service.PidFile, []byte(strconv.Itoa(pid)), 0644)
}
func removePidFile() error {
return os.Remove(configs.Config().Service.PidFile)
}