/
router.go
80 lines (69 loc) · 2.75 KB
/
router.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
// Copyright © 2017 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
package cmd
import (
"fmt"
"net"
"os"
"os/signal"
"syscall"
"github.com/TheThingsNetwork/ttn/core/component"
"github.com/TheThingsNetwork/ttn/core/router"
"github.com/apex/log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"google.golang.org/grpc"
)
// routerCmd represents the router command
var routerCmd = &cobra.Command{
Use: "router",
Short: "The Things Network router",
Long: ``,
PreRun: func(cmd *cobra.Command, args []string) {
ctx.WithFields(log.Fields{
"Server": fmt.Sprintf("%s:%d", viper.GetString("router.server-address"), viper.GetInt("router.server-port")),
"Announce": fmt.Sprintf("%s:%d", viper.GetString("router.server-address-announce"), viper.GetInt("router.server-port")),
}).Info("Initializing Router")
},
Run: func(cmd *cobra.Command, args []string) {
ctx.Info("Starting")
// Component
component, err := component.New(ctx, "router", fmt.Sprintf("%s:%d", viper.GetString("router.server-address-announce"), viper.GetInt("router.server-port")))
if err != nil {
ctx.WithError(err).Fatal("Could not initialize component")
}
// Router
router := router.NewRouter()
err = router.Init(component)
if err != nil {
ctx.WithError(err).Fatal("Could not initialize router")
}
// gRPC Server
lis, err := net.Listen("tcp", fmt.Sprintf("%s:%d", viper.GetString("router.server-address"), viper.GetInt("router.server-port")))
if err != nil {
ctx.WithError(err).Fatal("Could not start gRPC server")
}
grpc := grpc.NewServer(component.ServerOptions()...)
// Register and Listen
component.RegisterHealthServer(grpc)
router.RegisterRPC(grpc)
router.RegisterManager(grpc)
go grpc.Serve(lis)
sigChan := make(chan os.Signal)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
ctx.WithField("signal", <-sigChan).Info("signal received")
grpc.Stop()
router.Shutdown()
},
}
func init() {
RootCmd.AddCommand(routerCmd)
routerCmd.Flags().String("server-address", "0.0.0.0", "The IP address to listen for communication")
routerCmd.Flags().String("server-address-announce", "localhost", "The public IP address to announce")
routerCmd.Flags().Int("server-port", 1901, "The port for communication")
routerCmd.Flags().Bool("skip-verify-gateway-token", false, "Skip verification of the gateway token")
viper.BindPFlag("router.server-address", routerCmd.Flags().Lookup("server-address"))
viper.BindPFlag("router.server-address-announce", routerCmd.Flags().Lookup("server-address-announce"))
viper.BindPFlag("router.server-port", routerCmd.Flags().Lookup("server-port"))
viper.BindPFlag("router.skip-verify-gateway-token", routerCmd.Flags().Lookup("skip-verify-gateway-token"))
}