-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.go
149 lines (134 loc) · 4.28 KB
/
init.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
package main
import (
"context"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"time"
"github.com/sirupsen/logrus"
"github.com/smarthome-go/smarthome/core"
"github.com/smarthome-go/smarthome/core/automation"
"github.com/smarthome-go/smarthome/core/database"
"github.com/smarthome-go/smarthome/core/device/driver"
"github.com/smarthome-go/smarthome/core/event"
"github.com/smarthome-go/smarthome/core/homescript/dispatcher"
"github.com/smarthome-go/smarthome/core/scheduler"
"github.com/smarthome-go/smarthome/core/user/notify"
"github.com/smarthome-go/smarthome/core/utils"
"github.com/smarthome-go/smarthome/server/api"
"github.com/smarthome-go/smarthome/server/middleware"
"github.com/smarthome-go/smarthome/server/routes"
"github.com/smarthome-go/smarthome/server/templates"
"github.com/smarthome-go/smarthome/services/camera"
"github.com/smarthome-go/smarthome/services/reminder"
)
// Initializes logging configuration
func initLoggers() {
logLevel := logrus.TraceLevel
if newLogLevel, newLogLevelOk := os.LookupEnv("SMARTHOME_LOG_LEVEL"); newLogLevelOk {
switch newLogLevel {
case "TRACE":
logLevel = logrus.TraceLevel
case "DEBUG":
logLevel = logrus.DebugLevel
case "INFO":
logLevel = logrus.InfoLevel
case "WARN":
logLevel = logrus.WarnLevel
case "ERROR":
logLevel = logrus.ErrorLevel
case "FATAL":
logLevel = logrus.FatalLevel
default:
fmt.Printf("Invalid log level from environment variable: '%s'. Using TRACE\n", newLogLevel)
}
}
logTemp := utils.NewLogger(logLevel)
// Initialize module loggers
log = logTemp
core.InitLoggers(log)
dispatcher.InitLogger(log)
automation.InitLogger(log)
scheduler.InitLogger(log)
notify.InitLogger(log)
camera.InitLogger(log)
middleware.InitLogger(log)
api.InitLogger(log)
routes.InitLogger(log)
templates.InitLogger(log)
reminder.InitLogger(log)
driver.InitLogger(log)
}
const httpRootPath = "/"
func runWebServer(configStruct core.Config, serverConfig database.ServerConfig) {
// Server, middleware and routes
r := routes.NewRouter()
if !configStruct.Server.Production {
log.Warn("Using default session encryption. This is a security risk and must only be used during development.\nHint: this message should disappear when using `production` mode")
middleware.InitWithManualKey("")
} else {
if configStruct.Server.SessionKey == "" {
log.Debug("Manual session key is empty, generating random key...")
middleware.InitWithRandomKey()
} else {
middleware.InitWithManualKey(configStruct.Server.SessionKey)
}
}
if err := templates.LoadTemplates("./web/dist/html/*.html"); err != nil {
log.Error("Failed to load HTML templates: ", err.Error())
os.Exit(1)
}
http.Handle(httpRootPath, r)
// Finish startup and launch web server
event.Info("System Started", fmt.Sprintf("The Smarthome server completed startup at %s", time.Now().Format(time.ANSIC)))
operatingMode := "development"
if configStruct.Server.Production {
operatingMode = "production"
}
///// Start the server /////
errCh := make(chan error)
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt)
// Register a shutdown handler
ctx := context.Background()
shutdownCtx, cancel := context.WithCancel(context.Background())
ctx = context.WithValue(ctx, ShutdownContextKey, shutdownCtx)
server := http.Server{
Addr: fmt.Sprintf(":%d", port),
BaseContext: func(l net.Listener) context.Context { return ctx },
}
server.RegisterOnShutdown(cancel)
log.Info(fmt.Sprintf("Smarthome v%s is listening on http://localhost:%d using %s mode", utils.Version, port, operatingMode))
go func() { errCh <- server.ListenAndServe() }()
go core.RunBootAutomations(serverConfig)
// Main loop
mainLoop:
for {
select {
case s := <-sigCh:
if s == os.Interrupt {
break mainLoop
}
case err := <-errCh:
log.Error("Web server failed: ", err.Error())
break
}
}
// Shutdown
{
signal.Reset(os.Interrupt)
// Shutdown the webserver
server.SetKeepAlivesEnabled(false)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
if err := server.Shutdown(ctx); err != nil {
log.Error(fmt.Sprintf("Shutdown error: `%s`", err.Error()))
}
cancel()
// Wait for any other tasks
if err := core.Shutdown(false); err != nil {
log.Fatal(fmt.Sprintf("Graceful shutdown failed: `%s`", err.Error()))
}
}
}