-
Notifications
You must be signed in to change notification settings - Fork 8
/
grpcserver.go
152 lines (117 loc) · 4.25 KB
/
grpcserver.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package server
import (
"context"
"crypto/tls"
"flag"
"fmt"
"net"
"net/http"
"os"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"github.com/soheilhy/cmux"
"go.uber.org/automaxprocs/maxprocs"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/reflection"
"namespacelabs.dev/foundation/std/go/core"
gogrpc "namespacelabs.dev/foundation/std/go/grpc"
"namespacelabs.dev/foundation/std/go/grpc/interceptors"
"namespacelabs.dev/foundation/std/go/http/middleware"
"namespacelabs.dev/foundation/std/grpc/requestid"
)
var (
listenHostname = flag.String("listen_hostname", "localhost", "Hostname to listen on.")
port = flag.Int("port", 0, "Port to listen on.")
httpPort = flag.Int("http_port", 0, "Port to listen HTTP on.")
)
func ListenPort() int { return *port }
func InitializationDone() {
core.InitializationDone()
}
func Listen(ctx context.Context, registerServices func(Server)) error {
lis, err := net.Listen("tcp", fmt.Sprintf("%s:%d", *listenHostname, *port))
if err != nil {
return err
}
m := cmux.New(lis)
httpL := m.Match(cmux.HTTP1())
anyL := m.Match(cmux.Any())
opts := interceptorsAsOpts()
if gogrpc.ServerCert != nil {
cert, err := tls.X509KeyPair(gogrpc.ServerCert.CertificateBundle, gogrpc.ServerCert.PrivateKey)
if err != nil {
return err
}
config := &tls.Config{
Certificates: []tls.Certificate{cert},
ClientAuth: tls.NoClientCert,
}
transportCreds := credentials.NewTLS(config)
opts = append(opts, grpc.Creds(transportCreds))
}
// XXX serving keys.
grpcServer := grpc.NewServer(opts...)
// Enable tooling to query which gRPC services, etc are exported by this server.
reflection.Register(grpcServer)
httpMux := mux.NewRouter()
httpMux.Use(middleware.Consume()...)
httpMux.Use(proxyHeaders)
httpMux.Use(func(h http.Handler) http.Handler {
return handlers.CombinedLoggingHandler(os.Stdout, h)
})
s := &ServerImpl{srv: grpcServer, httpMux: httpMux}
registerServices(s)
// Export standard metrics.
grpc_prometheus.Register(grpcServer)
// XXX keep track of per-service health.
grpc_health_v1.RegisterHealthServer(grpcServer, health.NewServer())
// XXX configurable logging.
core.Log.Printf("Starting to listen on %v", lis.Addr())
// Set runtime.GOMAXPROCS to respect container limits if the env var GOMAXPROCS is not set or is invalid, preventing CPU throttling.
if _, err := maxprocs.Set(maxprocs.Logger(core.Log.Printf)); err != nil {
core.Log.Printf("Failed to reset GOMAXPROCS: %v", err)
}
debugMux := mux.NewRouter()
core.RegisterDebugEndpoints(debugMux)
debugHTTP := &http.Server{Handler: debugMux}
go func() { checkReturn("http/debug", debugHTTP.Serve(httpL)) }()
go func() { checkReturn("grpc", grpcServer.Serve(anyL)) }()
if *httpPort != 0 {
httpServer := &http.Server{Handler: httpMux}
gwLis, err := net.Listen("tcp", fmt.Sprintf("%s:%d", *listenHostname, *httpPort))
if err != nil {
return err
}
core.Log.Printf("Starting HTTP listen on %v", gwLis.Addr())
go func() { checkReturn("http", httpServer.Serve(gwLis)) }()
}
return m.Serve()
}
func interceptorsAsOpts() []grpc.ServerOption {
unary, streaming := interceptors.ServerInterceptors()
var coreU []grpc.UnaryServerInterceptor
var coreS []grpc.StreamServerInterceptor
// Interceptors are always invoked in order. It's **imperative** that the
// request id handling interceptor shows up first.
coreU = append(coreU, requestid.Interceptor{}.Unary)
coreS = append(coreS, requestid.Interceptor{}.Streaming)
coreU = append(coreU, unary...)
coreS = append(coreS, streaming...)
return []grpc.ServerOption{
grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(coreS...)),
grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(coreU...)),
}
}
func checkReturn(what string, err error) {
if err != nil {
core.Log.Fatalf("%s: serving failed: %v", what, err)
}
}