-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmystique.go
282 lines (245 loc) · 7.45 KB
/
mystique.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
// Copyright © 2018 The Things Industries, distributed under the MIT license (see LICENSE file)
// Package mystique implements an MQTT server.
// See the cmd package for the main executables.
package mystique
import (
"context"
"crypto/sha1"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/TheThingsIndustries/mystique/pkg/apex"
"github.com/TheThingsIndustries/mystique/pkg/inspect"
"github.com/TheThingsIndustries/mystique/pkg/log"
mqttnet "github.com/TheThingsIndustries/mystique/pkg/net"
"github.com/TheThingsIndustries/mystique/pkg/server"
"github.com/fsnotify/fsnotify"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
var (
ctx = context.Background()
logger = apex.Log
configured = false
s server.Server
)
// Context returns the global context
func Context() context.Context {
if !configured {
panic("mystique.Configure() was not called")
}
return ctx
}
// Configure the binary
func Configure(binaryName string) {
pflag.BoolP("debug", "d", false, "Print debug logs")
pflag.String("listen.tcp", ":1883", "TCP address for MQTT server to listen on")
pflag.String("listen.tls", ":8883", "TLS address for MQTT server to listen on")
pflag.String("listen.http", ":1880", "TCP address for HTTP+websocket server to listen on")
pflag.String("listen.https", ":1443", "TLS address for HTTP+websocket server to listen on")
pflag.String("websocket.pattern", "/mqtt", "URL pattern for websocket server to be registered on")
pflag.String("listen.status", ":9383", "Address for status server to listen on")
pflag.String("tls.cert", "", "Location of the TLS certificate")
pflag.String("tls.key", "", "Location of the TLS key")
pflag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s [options]\n", binaryName)
fmt.Fprintln(os.Stderr, "Options:")
pflag.PrintDefaults()
}
pflag.Parse()
viper.BindPFlags(pflag.CommandLine)
viper.AutomaticEnv()
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
if viper.GetBool("debug") {
apex.SetLevelFromString("debug")
}
ctx = log.NewContext(ctx, logger)
configured = true
}
var certificateExpiry = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "tls",
Name: "certificate_expiry_seconds",
Help: "Expiry date of the TLS certificate.",
}, []string{"fingerprint"})
func init() {
prometheus.MustRegister(certificateExpiry)
}
func TLSConfig(certFile, keyFile string) (tlsConfig *tls.Config) {
var (
cert *tls.Certificate
certMu sync.RWMutex
)
readCert := func() error {
newCert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return fmt.Errorf("Could not load X509 keypair: %s", err)
}
newCert.Leaf, err = x509.ParseCertificate(newCert.Certificate[0])
if err != nil {
logger.WithError(err).Warn("Could not parse leaf certificate")
}
sum := sha1.Sum(newCert.Leaf.Raw)
certMu.Lock()
cert = &newCert
certificateExpiry.Reset()
certificateExpiry.WithLabelValues(hex.EncodeToString(sum[:])).Set(float64(newCert.Leaf.NotAfter.Unix()))
certMu.Unlock()
return nil
}
if err := readCert(); err != nil {
logger.WithError(err).Fatal("Could not set up TLS")
}
if watcher, err := fsnotify.NewWatcher(); err == nil {
if watcher.Add(certFile) == nil && watcher.Add(keyFile) == nil {
update := make(chan bool, 1)
go func() {
for {
select {
case event := <-watcher.Events:
if event.Op&fsnotify.Write == fsnotify.Write {
select {
case update <- true:
logger.Info("Detected certificate change. Scheduling update...")
time.AfterFunc(5*time.Second, func() {
logger.Info("Updating TLS certificate...")
if err := readCert(); err != nil {
logger.WithError(err).Error("Could not update TLS certificate")
} else {
logger.Info("Updated TLS certificate")
}
<-update
})
default:
// Debounce
}
}
case err := <-watcher.Errors:
logger.WithError(err).Warn("Error watching file")
}
}
}()
}
}
return &tls.Config{
GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
certMu.RLock()
currentCert := cert
certMu.RUnlock()
return currentCert, nil
},
}
}
// RunServer the server
func RunServer(s server.Server) {
wss := mqttnet.Websocket(s.Handle)
var tlsConfig *tls.Config
certFile, keyFile := viper.GetString("tls.cert"), viper.GetString("tls.key")
if certFile != "" && keyFile != "" {
tlsConfig = TLSConfig(certFile, keyFile)
}
if listen := viper.GetString("listen.status"); listen != "" {
http.Handle("/mqtt", wss)
http.Handle("/metrics", promhttp.Handler())
if s.Sessions() != nil {
http.Handle("/debug/sessions", inspect.Sessions(s.Sessions()))
}
logger.WithField("address", listen).Info("Starting status+debug+metrics server")
go func() {
err := http.ListenAndServe(listen, nil)
if err != nil {
logger.WithError(err).Fatal("Could not start status+debug+metrics server")
}
}()
}
if listen := viper.GetString("listen.tcp"); listen != "" {
logger.WithField("address", listen).Info("Starting MQTT server")
lis, err := mqttnet.Listen("tcp", listen)
if err != nil {
logger.WithError(err).Fatal("Could not start MQTT server")
}
defer lis.Close()
go func() {
for {
conn, err := lis.Accept()
if err != nil {
logger.WithError(err).Error("Could not accept connection")
return
}
go s.Handle(conn)
}
}()
}
if listen := viper.GetString("listen.tls"); listen != "" {
if tlsConfig != nil {
logger.WithField("address", listen).Info("Starting MQTT+TLS server")
tlsLis, err := tls.Listen("tcp", listen, tlsConfig)
if err != nil {
logger.WithError(err).Fatal("Could not start MQTT+TLS server")
}
defer tlsLis.Close()
lis := mqttnet.NewListener(tlsLis, "tls")
go func() {
for {
conn, err := lis.Accept()
if err != nil {
logger.WithError(err).Error("Could not accept connection")
return
}
go s.Handle(conn)
}
}()
}
}
mux := http.NewServeMux()
mux.Handle(viper.GetString("websocket.pattern"), wss)
if _, err := os.Stat("example/websocket_client.html"); err == nil {
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "example/websocket_client.html")
})
}
if listen := viper.GetString("listen.http"); listen != "" {
logger.WithField("address", listen).Info("Starting HTTP+ws server")
lis, err := net.Listen("tcp", listen)
if err != nil {
logger.WithError(err).Fatal("Could not start HTTP+ws server")
}
defer lis.Close()
go func() {
err := http.Serve(lis, mux)
if err != nil {
logger.WithError(err).Error("Could not serve HTTP+ws")
}
}()
}
if listen := viper.GetString("listen.https"); listen != "" {
if tlsConfig != nil {
logger.WithField("address", listen).Info("Starting HTTPS+wss server")
tlsLis, err := tls.Listen("tcp", listen, tlsConfig)
if err != nil {
logger.WithError(err).Fatal("Could not start HTTPS+wss server")
}
defer tlsLis.Close()
go func() {
err := http.Serve(tlsLis, mux)
if err != nil {
logger.WithError(err).Error("Could not serve HTTPS+wss")
}
}()
}
}
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
signal := (<-sigChan).String()
logger.WithField("signal", signal).Info("Signal received")
}