-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrpc.go
191 lines (162 loc) · 5.17 KB
/
grpc.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
/**
* Copyright (c) 2024 Peking University and Peking University
* Changsha Institute for Computing and Digital Economy
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package cranetoolkit
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/fs"
"net"
"os"
"path/filepath"
"github.com/1daidai1/cranetoolkit/generated/protos"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc"
grpccodes "google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
grpcstatus "google.golang.org/grpc/status"
)
func GetTCPSocket(bindAddr string, config *Config) (net.Listener, error) {
if config.UseTls {
CaCertContent, err := os.ReadFile(config.ServerCertFilePath)
if err != nil {
return nil, err
}
caPool := x509.NewCertPool()
if ok := caPool.AppendCertsFromPEM(CaCertContent); !ok {
return nil, err
}
cert, err := tls.LoadX509KeyPair(config.ServerCertFilePath, config.ServerKeyFilePath)
if err != nil {
return nil, err
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: caPool,
// NextProtos is a list of supported application level protocols, in
// order of preference.
// It MUST be filled. Otherwise, when c++ clients try to connect this
// server, "Cannot check peer: missing selected ALPN property" error
// will occur!!!!
NextProtos: []string{"h2"},
}
listen, err := tls.Listen("tcp", bindAddr, tlsConfig)
if err != nil {
return nil, err
}
return listen, nil
} else {
listen, err := net.Listen("tcp", bindAddr)
if err != nil {
return nil, err
}
return listen, nil
}
}
func GetUnixSocket(path string, mode fs.FileMode) (net.Listener, error) {
dir, err := filepath.Abs(filepath.Dir(path))
if err != nil {
return nil, err
}
err = os.MkdirAll(dir, 0755)
if err != nil {
return nil, err
}
ok := RemoveFileIfExists(path)
if !ok {
return nil, fmt.Errorf("error when removing existing unix socket")
}
socket, err := net.Listen("unix", path)
if err != nil {
return nil, err
}
// 0600 -> only owner can access, no need to use TLS
// 0666 -> everyone can access, insecure
if err = os.Chmod(path, mode); err != nil {
return nil, err
}
return socket, nil
}
// TODO: Refactor this to return ErrCodes instead of exiting.
func GetStubToCtldByConfig(config *Config) protos.CraneCtldClient {
var serverAddr string
var stub protos.CraneCtldClient
if config.UseTls {
serverAddr = fmt.Sprintf("%s.%s:%s",
config.ControlMachine, config.DomainSuffix, config.CraneCtldListenPort)
ServerCertContent, err := os.ReadFile(config.ServerCertFilePath)
if err != nil {
log.Errorln("Read server certificate error: " + err.Error())
os.Exit(ErrorGeneric)
}
ServerKeyContent, err := os.ReadFile(config.ServerKeyFilePath)
if err != nil {
log.Errorln("Read server key error: " + err.Error())
os.Exit(ErrorGeneric)
}
CaCertContent, err := os.ReadFile(config.CaCertFilePath)
if err != nil {
log.Errorln("Read CA certifacate error: " + err.Error())
os.Exit(ErrorGeneric)
}
tlsKeyPair, err := tls.X509KeyPair(ServerCertContent, ServerKeyContent)
if err != nil {
log.Errorln("tlsKeyPair error: " + err.Error())
os.Exit(ErrorGeneric)
}
caPool := x509.NewCertPool()
if ok := caPool.AppendCertsFromPEM(CaCertContent); !ok {
log.Errorln("AppendCertsFromPEM error: " + err.Error())
os.Exit(ErrorGeneric)
}
creds := credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{tlsKeyPair},
RootCAs: caPool,
InsecureSkipVerify: false,
// NextProtos is a list of supported application level protocols, in
// order of preference.
NextProtos: []string{"h2"},
})
conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(creds))
if err != nil {
log.Errorln("Cannot connect to CraneCtld: " + err.Error())
os.Exit(ErrorBackend)
}
stub = protos.NewCraneCtldClient(conn)
} else {
serverAddr = fmt.Sprintf("%s:%s", config.ControlMachine, config.CraneCtldListenPort)
conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Errorf("Cannot connect to CraneCtld %s: %s", serverAddr, err.Error())
os.Exit(ErrorBackend)
}
stub = protos.NewCraneCtldClient(conn)
}
return stub
}
func GrpcErrorPrintf(err error, format string, a ...any) {
s := fmt.Sprintf(format, a...)
if rpcErr, ok := grpcstatus.FromError(err); ok {
if rpcErr.Code() == grpccodes.Unavailable {
log.Errorf("%s: Connection to CraneCtld is broken.", s)
} else {
log.Errorf("%s: gRPC error code %s.", s, rpcErr.String())
}
}
}