-
-
Notifications
You must be signed in to change notification settings - Fork 545
/
api.go
73 lines (60 loc) · 2.28 KB
/
api.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
package ns
import (
"net"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_logrus "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"
grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc"
"github.com/brocaar/chirpstack-api/go/v3/ns"
"github.com/brocaar/chirpstack-network-server/v3/internal/config"
"github.com/brocaar/chirpstack-network-server/v3/internal/logging"
"github.com/brocaar/chirpstack-network-server/v3/internal/tls"
)
func Setup(c config.Config) error {
apiConfig := c.NetworkServer.API
log.WithFields(log.Fields{
"bind": apiConfig.Bind,
"ca-cert": apiConfig.CACert,
"tls-cert": apiConfig.TLSCert,
"tls-key": apiConfig.TLSKey,
}).Info("api: starting network-server api server")
opts := serverOptions()
if apiConfig.CACert != "" || apiConfig.TLSCert != "" || apiConfig.TLSKey != "" {
creds, err := tls.GetTransportCredentials(apiConfig.CACert, apiConfig.TLSCert, apiConfig.TLSKey, true)
if err != nil {
return errors.Wrap(err, "get transport credentials error")
}
opts = append(opts, grpc.Creds(creds))
}
gs := grpc.NewServer(opts...)
nsAPI := NewNetworkServerAPI()
ns.RegisterNetworkServerServiceServer(gs, nsAPI)
ln, err := net.Listen("tcp", apiConfig.Bind)
if err != nil {
return errors.Wrap(err, "start api listener error")
}
go gs.Serve(ln)
return nil
}
func serverOptions() []grpc.ServerOption {
logrusEntry := log.NewEntry(log.StandardLogger())
logrusOpts := []grpc_logrus.Option{
grpc_logrus.WithLevels(grpc_logrus.DefaultCodeToLevel),
}
return []grpc.ServerOption{
grpc_middleware.WithUnaryServerChain(
grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_logrus.UnaryServerInterceptor(logrusEntry, logrusOpts...),
logging.UnaryServerCtxIDInterceptor,
grpc_prometheus.UnaryServerInterceptor,
),
grpc_middleware.WithStreamServerChain(
grpc_ctxtags.StreamServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_logrus.StreamServerInterceptor(logrusEntry, logrusOpts...),
grpc_prometheus.StreamServerInterceptor,
),
}
}