This repository has been archived by the owner on Dec 14, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 279
/
router.go
209 lines (185 loc) · 5.74 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
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
// 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 router
import (
"sync"
"time"
pb_broker "github.com/TheThingsNetwork/api/broker"
"github.com/TheThingsNetwork/api/broker/brokerclient"
pb_discovery "github.com/TheThingsNetwork/api/discovery"
pb_gateway "github.com/TheThingsNetwork/api/gateway"
"github.com/TheThingsNetwork/api/monitor/monitorclient"
pb "github.com/TheThingsNetwork/api/router"
"github.com/TheThingsNetwork/go-utils/grpc/auth"
"github.com/TheThingsNetwork/go-utils/grpc/ttnctx"
"github.com/TheThingsNetwork/ttn/core/component"
"github.com/TheThingsNetwork/ttn/core/router/gateway"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
// Router component
type Router interface {
component.Interface
component.ManagementInterface
// Handle a status message from a gateway
HandleGatewayStatus(gatewayID string, status *pb_gateway.Status) error
// Handle an uplink message from a gateway
HandleUplink(gatewayID string, uplink *pb.UplinkMessage) error
// Handle a downlink message
HandleDownlink(message *pb_broker.DownlinkMessage) error
// Subscribe to downlink messages
SubscribeDownlink(gatewayID string, subscriptionID string) (<-chan *pb.DownlinkMessage, error)
// Unsubscribe from downlink messages
UnsubscribeDownlink(gatewayID string, subscriptionID string) error
// Handle a device activation
HandleActivation(gatewayID string, activation *pb.DeviceActivationRequest) (*pb.DeviceActivationResponse, error)
getGateway(gatewayID string) *gateway.Gateway
}
type broker struct {
conn *grpc.ClientConn
association brokerclient.RouterStream
client pb_broker.BrokerClient
uplink chan *pb_broker.UplinkMessage
downlink chan *pb_broker.DownlinkMessage
}
// NewRouter creates a new Router
func NewRouter() Router {
return &router{
gateways: make(map[string]*gateway.Gateway),
brokers: make(map[string]*broker),
}
}
type router struct {
*component.Component
gateways map[string]*gateway.Gateway
gatewaysLock sync.RWMutex
brokers map[string]*broker
brokersLock sync.RWMutex
status *status
monitorStream monitorclient.Stream
}
func (r *router) tickGateways() {
r.gatewaysLock.RLock()
defer r.gatewaysLock.RUnlock()
for _, gtw := range r.gateways {
gtw.Utilization.Tick()
}
}
func (r *router) Init(c *component.Component) error {
r.Component = c
r.InitStatus()
err := r.Component.UpdateTokenKey()
if err != nil {
return err
}
err = r.Component.Announce()
if err != nil {
return err
}
r.Discovery.GetAll("broker") // Update cache
go func() {
for range time.Tick(5 * time.Second) {
r.tickGateways()
}
}()
r.Component.SetStatus(component.StatusHealthy)
if r.Component.Monitor != nil {
r.monitorStream = r.Component.Monitor.RouterClient(r.Context, grpc.PerRPCCredentials(auth.WithStaticToken(r.AccessToken)))
}
return nil
}
func (r *router) Shutdown() {
r.brokersLock.Lock()
defer r.brokersLock.Unlock()
for _, broker := range r.brokers {
broker.association.Close()
broker.conn.Close()
}
}
// getGateway gets or creates a Gateway
func (r *router) getGateway(id string) *gateway.Gateway {
// We're going to be optimistic and guess that the gateway is already active
r.gatewaysLock.RLock()
gtw, ok := r.gateways[id]
r.gatewaysLock.RUnlock()
if ok {
return gtw
}
// If it doesn't we still have to lock
r.gatewaysLock.Lock()
defer r.gatewaysLock.Unlock()
gtw, ok = r.gateways[id]
if !ok {
gtw = gateway.NewGateway(r.Ctx, id)
ctx := context.Background()
ctx = ttnctx.OutgoingContextWithID(ctx, id)
if r.Identity != nil {
ctx = ttnctx.OutgoingContextWithServiceInfo(ctx, r.Identity.ServiceName, r.Identity.ServiceVersion, r.Identity.NetAddress)
}
gtw.MonitorStream = r.Component.Monitor.GatewayClient(
ctx,
grpc.PerRPCCredentials(auth.WithTokenFunc("id", func(ctxID string) string {
if ctxID != id {
return ""
}
return gtw.Token()
})),
)
r.gateways[id] = gtw
}
return gtw
}
// getBroker gets or creates a broker association and returns the broker
// the first time it also starts a goroutine that receives downlink from the broker
func (r *router) getBroker(brokerAnnouncement *pb_discovery.Announcement) (*broker, error) {
// We're going to be optimistic and guess that the broker is already active
r.brokersLock.RLock()
brk, ok := r.brokers[brokerAnnouncement.ID]
r.brokersLock.RUnlock()
if ok {
return brk, nil
}
// If it doesn't we still have to lock
r.brokersLock.Lock()
defer r.brokersLock.Unlock()
if _, ok := r.brokers[brokerAnnouncement.ID]; !ok {
var err error
brk := &broker{
uplink: make(chan *pb_broker.UplinkMessage),
}
// Connect to the server
brk.conn, err = brokerAnnouncement.Dial(r.Pool)
if err != nil {
return nil, err
}
// Set up the non-streaming client
brk.client = pb_broker.NewBrokerClient(brk.conn)
// Set up the streaming client
config := brokerclient.DefaultClientConfig
config.BackgroundContext = r.Component.Context
cli := brokerclient.NewClient(config)
cli.AddServer(brokerAnnouncement.ID, brk.conn)
brk.association = cli.NewRouterStreams(r.Identity.ID, "")
go func() {
downlinkStream := brk.association.Downlink()
refreshDownlinkStream := time.NewTicker(time.Second)
for {
select {
case message := <-brk.uplink:
brk.association.Uplink(message)
case <-refreshDownlinkStream.C:
downlinkStream = brk.association.Downlink()
case message, ok := <-downlinkStream:
if ok {
go r.HandleDownlink(message)
} else {
r.Ctx.WithField("broker", brokerAnnouncement.ID).Error("Downlink Stream errored")
downlinkStream = nil
}
}
}
}()
r.brokers[brokerAnnouncement.ID] = brk
}
return r.brokers[brokerAnnouncement.ID], nil
}