forked from infinilabs/framework
/
rpc.go
252 lines (205 loc) · 6.45 KB
/
rpc.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
/*
Copyright Medcl (m AT medcl.net)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package rpc
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/pem"
log "github.com/cihub/seelog"
"github.com/dan-drl/framework/core/config"
"github.com/dan-drl/framework/core/util"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
_ "google.golang.org/grpc/encoding/gzip" // Install the gzip compressor
"google.golang.org/grpc/reflection"
"net"
"time"
)
func GetRPCServer() *grpc.Server {
return s
}
//only select local connection
func ObtainLocalConnection() (conn *grpc.ClientConn, err error) {
return ObtainConnection(listenAddress)
}
//func ObtainLeaderConnection() (conn *grpc.ClientConn, err error) {
//// return ObtainConnection(leaderAddr)
////}
//var addr = flag.String("rpc.bind", "localhost:20000", "the rpc address to bind to")
//auto select connection
func ObtainConnection(addr string) (conn *grpc.ClientConn, err error) {
log.Trace("obtain client connection: ", addr)
if rpcConfig.TLSConfig.TLSEnabled {
var creds credentials.TransportCredentials
log.Trace("using tls connection")
cert := rpcConfig.TLSConfig.TLSCertFile
key := rpcConfig.TLSConfig.TLSKeyFile
if cert != "" && key != "" {
log.Trace("use pre-defined cert")
// Create tls based credential.
creds, err = credentials.NewClientTLSFromFile(cert, key)
if err != nil {
log.Errorf("failed to load credentials: %v", err)
}
// Set up a connection to the server.
conn, err = grpc.Dial(addr, grpc.WithTransportCredentials(creds))
if err != nil {
log.Errorf("did not connect: %v", err)
}
// Load the client certificates from disk
certificate, err := tls.LoadX509KeyPair(cert, key)
if err != nil {
panic(err)
}
creds = credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{certificate},
RootCAs: certPool,
InsecureSkipVerify: true,
})
} else {
log.Debug("auto generate server cert")
clientTLSCert, _, _ := util.GetClientCert(rootCert, rootKey)
// Create the TLS credentials
creds = credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{clientTLSCert},
RootCAs: certPool,
InsecureSkipVerify: true,
})
}
dialOption := grpc.WithTransportCredentials(creds)
conn, err = grpc.Dial(addr, dialOption)
if err != nil {
log.Errorf("cannot connect to %s, %v", addr, err)
}
} else {
log.Trace("using insecure tcp connection")
conn, err = grpc.Dial(addr, grpc.WithInsecure())
if err != nil {
log.Errorf("cannot connect to %s, %v", addr, err)
}
}
return conn, err
}
var s *grpc.Server
var rpcConfig *config.RPCConfig
var connected bool
var lastContact *time.Time
var certPool *x509.CertPool
var rootCert *x509.Certificate
var rootKey *rsa.PrivateKey
var rootCertPEM []byte
func Setup(cfg *config.RPCConfig) {
rpcConfig = cfg
var err error
s = grpc.NewServer()
if rpcConfig.TLSConfig.TLSEnabled {
cert := rpcConfig.TLSConfig.TLSCertFile
key := rpcConfig.TLSConfig.TLSKeyFile
log.Trace("using tls connection")
var creds credentials.TransportCredentials
if cert != "" && key != "" {
log.Debug("use pre-defined cert")
creds, err = credentials.NewServerTLSFromFile(cert, key)
if err != nil {
log.Errorf("failed to create credentials: %v", err)
panic(err)
}
} else {
log.Debug("auto generate server cert")
rootCert, rootKey, rootCertPEM = util.GetRootCert()
certPool = x509.NewCertPool()
certPool.AppendCertsFromPEM(rootCertPEM)
//fmt.Printf("ca\n")
//fmt.Printf("%s\n", rootCertPEM)
// create a key-pair for the server
servKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
panic(err)
}
// create a template for the server
servCertTmpl, err := util.GetCertTemplate()
if err != nil {
panic(err)
}
servCertTmpl.KeyUsage = x509.KeyUsageDigitalSignature
servCertTmpl.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}
// create a certificate which wraps the server's public key, sign it with the root private key
_, servCertPEM, err := util.CreateCert(servCertTmpl, rootCert, &servKey.PublicKey, rootKey)
if err != nil {
panic(err)
}
// provide the private key and the cert
servKeyPEM := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(servKey),
})
//fmt.Printf("server_cert\n")
//fmt.Printf("%s\n", servCertPEM)
//fmt.Printf("server_key\n")
//fmt.Printf("%s\n", servKeyPEM)
servTLSCert, err := tls.X509KeyPair(servCertPEM, servKeyPEM)
if err != nil {
log.Errorf("invalid key pair: %v", err)
}
// Create the TLS credentials
creds = credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{servTLSCert},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: certPool,
InsecureSkipVerify: false,
})
if rpcConfig.TLSConfig.TLSInsecureSkipVerify {
// Create the TLS credentials
creds = credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{servTLSCert},
ClientAuth: tls.RequireAnyClientCert,
ClientCAs: certPool,
InsecureSkipVerify: true,
})
}
}
s = grpc.NewServer(grpc.Creds(creds))
} else {
log.Trace("using insecure tcp connection")
s = grpc.NewServer()
}
}
var listener net.Listener
var listenAddress string
func GetListener() net.Listener {
return listener
}
func GetRPCAddress() string {
return listenAddress
}
func StartRPCServer() {
listenAddress = util.AutoGetAddress(rpcConfig.NetworkConfig.GetBindingAddr())
var err error
listener, err = net.Listen("tcp", listenAddress)
if err != nil {
log.Errorf("failed to listen: %v", err)
}
// Register reflection service on gRPC server.
reflection.Register(s)
go func() {
if err := s.Serve(listener); err != nil {
log.Errorf("failed to serve: %v", err)
}
}()
err = util.WaitServerUp(listenAddress, 30*time.Second)
if err != nil {
panic(err)
}
log.Info("rpc server listen at: ", listenAddress)
}