-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
180 lines (138 loc) · 4.87 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
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
package main
import (
"github.com/go-redis/redis/v8"
"github.com/gorilla/handlers"
"github.com/londonhackspace/acnode-dashboard/acnode"
"github.com/londonhackspace/acnode-dashboard/acserver_api"
"github.com/londonhackspace/acnode-dashboard/acserverwatcher"
"github.com/londonhackspace/acnode-dashboard/api"
"github.com/londonhackspace/acnode-dashboard/auth"
"github.com/londonhackspace/acnode-dashboard/config"
"github.com/londonhackspace/acnode-dashboard/usagelogs"
"sync"
"github.com/gorilla/mux"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/prometheus/client_golang/prometheus/promhttp"
"html/template"
"net/http"
"os"
)
func getTemplate(page string) *template.Template {
return template.Must(template.ParseFiles(
"templates/base.gohtml",
"templates/"+page))
}
func checkAuth(w http.ResponseWriter, r *http.Request) bool {
ok, _ := auth.CheckAuthUser(w, r)
if !ok {
http.Redirect(w, r, "/login?next="+r.URL.Path, 302)
}
return ok
}
var error404Template *template.Template = nil
func handle404(w http.ResponseWriter, r *http.Request) {
if error404Template == nil {
error404Template = getTemplate("404.gohtml")
}
error404Template.ExecuteTemplate(w, "404.gohtml", nil)
}
var swaggerTemplate *template.Template = nil
func handleSwagger(w http.ResponseWriter, r *http.Request) {
if swaggerTemplate == nil {
swaggerTemplate = getTemplate("swagger.gohtml")
}
swaggerTemplate.ExecuteTemplate(w, "swagger.gohtml", GetBaseTemplateArgs())
}
func main() {
// setup logging
consoleLogger := zerolog.ConsoleWriter{Out: os.Stderr}
log.Logger = log.Output(consoleLogger)
startupWg := sync.WaitGroup{}
conf := config.GetCombinedConfig("acserverdash.json")
if !conf.Validate() {
log.Fatal().Msg("Invalid configuration")
return
}
if conf.LogJSON {
log.Logger = log.Output(os.Stdout)
}
acserverapi := acserver_api.CreateACServer(&conf)
var usageLogger usagelogs.UsageLogger = nil
var persistence acnode.NodePersistence = nil
if conf.RedisEnable {
redisConn := redis.NewClient(&redis.Options{
Addr: conf.RedisServer,
Password: "",
DB: 0,
})
sessStore := auth.CreateRedisSessionStore(redisConn)
auth.SetSessionStore(sessStore)
userStore := auth.CreateRedisProvider(redisConn)
auth.AddProvider(userStore)
persistence = acnode.GetRedisNodePersistence(redisConn)
usageLogger = usagelogs.CreateRedisUsageLogger(redisConn, &acserverapi)
} else {
persistence = acnode.CreateMemoryNodePersistence()
}
acnodehandler := acnode.CreateACNodeHandler(persistence)
websockerServer := api.CreateWebsockerHandler(&acnodehandler)
if conf.LdapEnable {
ldapauth := auth.GetLDAPAuthenticator(&conf)
auth.AddProvider(&ldapauth)
}
acsw := acserverwatcher.Watcher{acserverapi, &acnodehandler}
apihandler := api.CreateApi(&conf, &acnodehandler, usageLogger)
mqttHandler := CreateMQTTHandler(&conf, &acnodehandler, usageLogger)
// Don't initialise MQTT or ACServer watcher until everything else is running
go func() {
startupWg.Wait()
go acsw.Run()
mqttHandler.Init()
}()
// create a URL router
rtr := mux.NewRouter()
rtr.NotFoundHandler = http.HandlerFunc(handle404)
rtr.PathPrefix("/api/").Handler(http.StripPrefix("/api", apihandler.GetRouter()))
rtr.PathPrefix("/ws").Handler(websockerServer)
// Cache the assets, unless there's no version, in which case
// it's most likely a development version
staticCachePolicy := CachePolicyAlways
if getVersion() == "Unknown" {
staticCachePolicy = CachePolicyNever
}
var fs http.Handler
// if the frontend build exists, serve it from there, otherwise from /static
if _, err := os.Stat("frontend/dist/"); !os.IsNotExist(err) {
fs = http.FileServer(http.Dir("./frontend/dist"))
} else {
// serve our /static
fs = http.FileServer(http.Dir("./static/"))
}
// always serve swagger from /static but without cache
swaggerfs := CreateCacheHeaderInserter(
http.StripPrefix("/static", http.FileServer(http.Dir("./static/"))), CachePolicyNever)
rtr.PathPrefix("/static/swagger/").Handler(swaggerfs)
rtr.Handle("/static/api.yaml", swaggerfs)
// serve our /static via a cache
staticfs := CreateCacheHeaderInserter(fs, staticCachePolicy)
rtr.PathPrefix("/static/").Handler(staticfs)
//favicon and index don't get cache headers so we can change them
rtr.Handle("/favicon.png", fs)
// Add Swagger for API docs
rtr.HandleFunc("/swagger/", handleSwagger)
// Prometheus-format metrics
rtr.Handle("/metrics", promhttp.Handler())
//Default, catch all handler so the client-side router works:
rtr.PathPrefix("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.URL.Path = "/"
fs.ServeHTTP(w, r)
})
listen, ok := os.LookupEnv("LISTEN_ADDR")
if !ok {
listen = "localhost:8080"
}
log.Info().Msg("Listening on " + listen)
handler := CreateCacheHeaderInserter(rtr, CachePolicyNever)
http.ListenAndServe(listen, handlers.ProxyHeaders(LoggingHandler{next: handler}))
}