-
Notifications
You must be signed in to change notification settings - Fork 310
/
component.go
365 lines (299 loc) · 9.48 KB
/
component.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
357
358
359
360
361
362
363
364
365
// Copyright © 2019 The Things Network Foundation, The Things Industries B.V.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package component contains the methods and structures common to all components.
package component
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"sort"
"strings"
"sync"
"syscall"
"github.com/heptiolabs/healthcheck"
"go.thethings.network/lorawan-stack/v3/pkg/auth/rights"
"go.thethings.network/lorawan-stack/v3/pkg/cluster"
"go.thethings.network/lorawan-stack/v3/pkg/config"
"go.thethings.network/lorawan-stack/v3/pkg/crypto"
"go.thethings.network/lorawan-stack/v3/pkg/fillcontext"
"go.thethings.network/lorawan-stack/v3/pkg/frequencyplans"
"go.thethings.network/lorawan-stack/v3/pkg/interop"
"go.thethings.network/lorawan-stack/v3/pkg/log"
"go.thethings.network/lorawan-stack/v3/pkg/rpcserver"
"go.thethings.network/lorawan-stack/v3/pkg/ttnpb"
"go.thethings.network/lorawan-stack/v3/pkg/web"
"golang.org/x/crypto/acme/autocert"
"google.golang.org/grpc"
)
// Config is the type of configuration for Components
type Config struct {
config.ServiceBase `name:",squash" yaml:",inline"`
}
// Component is a base component for The Things Network cluster
type Component struct {
ctx context.Context
cancelCtx context.CancelFunc
terminationSignals chan os.Signal
config *Config
getBaseConfig func(ctx context.Context) config.ServiceBase
acme *autocert.Manager
logger log.Stack
cluster cluster.Cluster
clusterNew func(ctx context.Context, config *cluster.Config, options ...cluster.Option) (cluster.Cluster, error)
grpc *rpcserver.Server
grpcSubsystems []rpcserver.Registerer
web *web.Server
webSubsystems []web.Registerer
interop *interop.Server
interopSubsystems []interop.Registerer
healthHandler healthcheck.Handler
loopback *grpc.ClientConn
tcpListeners map[string]*listener
tcpListenersMu sync.Mutex
fillers []fillcontext.Filler
FrequencyPlans *frequencyplans.Store
KeyVault crypto.KeyVault
rightsFetcher rights.Fetcher
tasks []task
}
// Option allows extending the component when it is instantiated with New.
type Option func(*Component)
// WithClusterNew returns an option that overrides the component's function for
// setting up the cluster.
// This allows extending the cluster configuration with custom logic based on
// information in the context.
func WithClusterNew(f func(ctx context.Context, config *cluster.Config, options ...cluster.Option) (cluster.Cluster, error)) Option {
return func(c *Component) {
c.clusterNew = f
}
}
// WithBaseConfigGetter returns an option that overrides the component's function
// for getting the base config.
// This allows overriding the configuration with information in the context.
func WithBaseConfigGetter(f func(ctx context.Context) config.ServiceBase) Option {
return func(c *Component) {
c.getBaseConfig = f
}
}
// New returns a new component.
func New(logger log.Stack, config *Config, opts ...Option) (c *Component, err error) {
ctx, cancel := context.WithCancel(context.Background())
defer func() {
if err != nil {
cancel()
}
}()
ctx = log.NewContext(ctx, logger)
keyVault, err := config.KeyVault.KeyVault()
if err != nil {
return nil, err
}
c = &Component{
ctx: ctx,
cancelCtx: cancel,
terminationSignals: make(chan os.Signal),
config: config,
logger: logger,
healthHandler: healthcheck.NewHandler(),
tcpListeners: make(map[string]*listener),
KeyVault: keyVault,
}
for _, opt := range opts {
opt(c)
}
fpsFetcher, err := config.FrequencyPlansFetcher(ctx)
if err != nil {
return nil, err
}
c.FrequencyPlans = frequencyplans.NewStore(fpsFetcher)
if c.clusterNew == nil {
c.clusterNew = cluster.New
}
if err = c.initWeb(); err != nil {
return nil, err
}
if err := c.initACME(); err != nil {
return nil, err
}
config.Interop.SenderClientCA.BlobConfig = config.Blob
c.interop, err = interop.NewServer(c.ctx, c.FillContext, config.Interop)
if err != nil {
return nil, err
}
c.initRights()
c.initGRPC()
return c, nil
}
// MustNew calls New and returns a new component or panics on an error.
// In most cases, you should just use New.
func MustNew(logger log.Stack, config *Config, opts ...Option) *Component {
c, err := New(logger, config, opts...)
if err != nil {
panic(err)
}
return c
}
// Logger returns the logger of the component.
func (c *Component) Logger() log.Stack {
return c.logger
}
// LogDebug returns whether the component should log debug messages.
func (c *Component) LogDebug() bool {
return c.config.Log.Level == log.DebugLevel
}
// Context returns the context of the component.
func (c *Component) Context() context.Context {
return c.ctx
}
// GetBaseConfig gets the base config of the component.
func (c *Component) GetBaseConfig(ctx context.Context) config.ServiceBase {
if c.getBaseConfig != nil {
return c.getBaseConfig(ctx)
}
return c.config.ServiceBase
}
// FillContext fills the context.
// This method should only be used for request contexts.
func (c *Component) FillContext(ctx context.Context) context.Context {
for _, filler := range c.fillers {
ctx = filler(ctx)
}
return ctx
}
// AddContextFiller adds the specified filler.
func (c *Component) AddContextFiller(f fillcontext.Filler) {
c.fillers = append(c.fillers, f)
}
// Start starts the component.
func (c *Component) Start() (err error) {
if c.grpc != nil {
c.logger.Debug("Initializing gRPC server...")
if err = c.setupGRPC(); err != nil {
return err
}
serviceInfo := c.grpc.Server.GetServiceInfo()
services := make([]string, 0, len(serviceInfo))
for service := range serviceInfo {
services = append(services, service)
}
sort.Strings(services)
c.logger.WithFields(log.Fields(
"namespace", "grpc",
"services", services,
)).Debug("Exposed services")
}
c.logger.Debug("Initializing cluster...")
if err := c.initCluster(); err != nil {
return err
}
c.logger.Debug("Initializing web server...")
for _, sub := range c.webSubsystems {
sub.RegisterRoutes(c.web)
}
c.web.RootRouter().PathPrefix("/").Handler(c.web.Router())
c.logger.Debug("Initializing interop server...")
for _, sub := range c.interopSubsystems {
sub.RegisterInterop(c.interop)
}
if c.grpc != nil {
c.logger.Debug("Starting gRPC server...")
if err = c.listenGRPC(); err != nil {
c.logger.WithError(err).Error("Could not start gRPC server")
return err
}
c.web.Prefix(ttnpb.HTTPAPIPrefix + "/").Handler(http.StripPrefix(ttnpb.HTTPAPIPrefix, c.grpc))
c.logger.Debug("Started gRPC server")
}
c.logger.Debug("Starting web server...")
if err = c.listenWeb(); err != nil {
c.logger.WithError(err).Error("Could not start web server")
return err
}
c.logger.Debug("Started web server")
c.logger.Debug("Starting interop server")
if err = c.listenInterop(); err != nil {
c.logger.WithError(err).Error("Could not start interop server")
return err
}
c.logger.Debug("Started interop server")
c.logger.Debug("Joining cluster...")
if err := c.cluster.Join(); err != nil {
c.logger.WithError(err).Error("Could not join cluster")
return err
}
c.logger.Debug("Joined cluster")
c.logger.Debug("Starting tasks")
c.startTasks()
c.logger.Debug("Started tasks")
return nil
}
// Run starts the component, and returns when a stop signal has been received by the process.
func (c *Component) Run() error {
defer c.Close()
if err := c.Start(); err != nil {
return err
}
defer func() {
c.logger.Debug("Leaving cluster...")
if err := c.cluster.Leave(); err != nil {
c.logger.WithError(err).Error("Could not leave cluster")
}
c.logger.Debug("Left cluster")
}()
signal.Notify(c.terminationSignals, os.Interrupt, os.Kill, syscall.SIGTERM)
for {
select {
case sig := <-c.terminationSignals:
fmt.Println()
c.logger.WithField("signal", sig).Info("Received signal, exiting...")
return nil
}
}
}
// Close closes the server.
func (c *Component) Close() {
c.cancelCtx()
c.tcpListenersMu.Lock()
defer c.tcpListenersMu.Unlock()
for _, l := range c.tcpListeners {
err := l.Close()
if err != nil && c.ctx.Err() == nil {
c.logger.WithError(err).Errorf("Error while stopping to listen on %s", l.Addr())
continue
}
c.logger.Debugf("Stopped listening on %s", l.Addr())
}
if c.grpc != nil {
c.logger.Debug("Stopping gRPC server...")
c.grpc.Stop()
c.logger.Debug("Stopped gRPC server")
}
}
// AllowInsecureForCredentials returns `true` if the component was configured to allow transmission of credentials
// over insecure transports.
func (c *Component) AllowInsecureForCredentials() bool {
return c.config.GRPC.AllowInsecureForCredentials
}
// ServeHTTP serves an HTTP request.
// If the Content-Type is application/grpc, the request is routed to gRPC.
// Otherwise, the request is routed to the default web server.
func (c *Component) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
c.grpc.Server.ServeHTTP(w, r)
} else {
c.web.ServeHTTP(w, r)
}
}