forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc_server.go
68 lines (55 loc) · 1.71 KB
/
grpc_server.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
// Copyright 2015, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package servenv
import (
"flag"
"fmt"
"net"
"google.golang.org/grpc"
log "github.com/golang/glog"
)
// This file handles gRPC server, on its own port.
// Clients register servers, based on service map:
//
// servenv.RegisterGRPCFlags()
// servenv.OnRun(func() {
// if servenv.GRPCCheckServiceMap("XXX") {
// pb.RegisterXXX(servenv.GRPCServer, XXX)
// }
// }
var (
// GRPCPort is the port to listen on for gRPC. If not set or zero, don't listen.
GRPCPort *int
// GRPCServer is the global server to serve gRPC.
GRPCServer = grpc.NewServer()
)
func serveGRPC() {
// skip if not registered
if GRPCPort == nil || *GRPCPort == 0 {
return
}
// listen on the port
log.Infof("Listening for gRPC calls on port %v", *GRPCPort)
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", *GRPCPort))
if err != nil {
log.Fatalf("Cannot listen on port %v for gRPC: %v", *GRPCPort, err)
}
// and serve on it
go GRPCServer.Serve(listener)
}
// RegisterGRPCFlags registers the right command line flag to enable gRPC
func RegisterGRPCFlags() {
GRPCPort = flag.Int("grpc_port", 0, "Port to listen on for gRPC calls")
}
// GRPCCheckServiceMap returns if we should register a gRPC service
// (and also logs how to enable / disable it)
func GRPCCheckServiceMap(name string) bool {
// Silently fail individual services if gRPC is not enabled in
// the first place (either on a grpc port or on the socket file)
if (GRPCPort == nil || *GRPCPort == 0) && (SocketFile == nil || *SocketFile == "") {
return false
}
// then check ServiceMap
return CheckServiceMap("grpc", name)
}