-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathconnection.go
363 lines (331 loc) · 10.9 KB
/
connection.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package private_maprdb_go_client
import (
"context"
"crypto/tls"
b64 "encoding/base64"
"errors"
"fmt"
"github.com/grpc-ecosystem/go-grpc-middleware"
"github.com/grpc-ecosystem/go-grpc-middleware/retry"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
"net/url"
"strconv"
"strings"
"time"
)
type Connection struct {
stub MapRDbServerClient
umd userMetadata
channel *grpc.ClientConn
opts *ConnectionOptions
}
// ConnectionOptions apply to all calls for the connections
// MaxAttempt attempt count
// WaitBetweenSeconds delay between attempts in seconds
// CallTimeoutSeconds maximum call timeout
type ConnectionOptions struct {
MaxAttempt int
WaitBetweenSeconds int
CallTimeoutSeconds int
}
var prefix = "ojai:mapr@"
// Default connection options
// MaxAttempt 9
// WaitBetweenSeconds 12
// CallTimeoutSeconds 60
var defaultConnectionOpts = &ConnectionOptions{MaxAttempt: 9, WaitBetweenSeconds: 12, CallTimeoutSeconds: 60}
// Method creates channel for secure or insecure connection according to input parameters in connection string.
func createChannel(encodedUMD *string, connectionUrl *string,
ssl *bool,
sslValidate *bool,
sslCA *string,
sslTargetNameOverride *string,
conOpts *ConnectionOptions) (*Connection, error) {
var opts []grpc.DialOption
if !*ssl {
opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
} else if *sslValidate {
transportCredentials, err := credentials.NewClientTLSFromFile(*sslCA, *sslTargetNameOverride)
if err != nil {
return nil, err
}
opts = append(opts, grpc.WithTransportCredentials(transportCredentials))
} else {
var tlsConf tls.Config
tlsConf.InsecureSkipVerify = true
var creds = credentials.NewTLS(&tlsConf)
opts = append(opts, grpc.WithTransportCredentials(creds))
}
conn := &Connection{umd: userMetadata{*encodedUMD, ""}}
if conOpts == nil || conOpts.MaxAttempt < 1 || conOpts.WaitBetweenSeconds < 1 || conOpts.CallTimeoutSeconds < 1 {
conn.opts = defaultConnectionOpts
} else {
conn.opts = conOpts
}
retryOpts := []grpc_retry.CallOption{
grpc_retry.WithBackoff(grpc_retry.BackoffLinear(time.Duration(conn.opts.WaitBetweenSeconds) * time.Second)),
grpc_retry.WithCodes(
codes.NotFound,
codes.Unavailable),
grpc_retry.WithPerRetryTimeout(time.Duration(conn.opts.WaitBetweenSeconds) * time.Second),
grpc_retry.WithMax(uint(conn.opts.MaxAttempt)),
}
opts = append(
opts,
grpc.WithUnaryInterceptor(
grpc_middleware.ChainUnaryClient(
UnaryClientAuthInterceptor(&conn.umd),
UnaryClientTokenInterceptor(&conn.umd),
grpc_retry.UnaryClientInterceptor(retryOpts...),
)),
grpc.WithStreamInterceptor(
grpc_middleware.ChainStreamClient(
StreamClientAuthInterceptor(&conn.umd),
StreamClientTokenInterceptor(&conn.umd),
grpc_retry.StreamClientInterceptor(retryOpts...),
)),
)
channel, err := grpc.Dial(*connectionUrl, opts...)
if err != nil {
return nil, err
}
conn.channel = channel
return conn, nil
}
// Method pings gRPC server for ensure that connection is established
func pingRequest(connection *Connection) error {
header := make(metadata.MD)
trailer := make(metadata.MD)
ctx, cancel := context.WithTimeout(context.Background(),
time.Duration(connection.opts.CallTimeoutSeconds)*time.Second)
defer cancel()
_, err := connection.stub.Ping(ctx,
&PingRequest{},
grpc.Header(&header),
grpc.Trailer(&trailer),
)
if err != nil {
return err
}
connection.umd.UpdateToken(header, trailer)
return nil
}
// Method executes IsStoreExists method for ensure that store with given
// name is exists and return new DocumentStore if result is positive.
func (connection *Connection) GetStore(storeName string) (*DocumentStore, error) {
res, err := connection.IsStoreExists(storeName)
if err != nil {
return nil, err
}
if res {
return &DocumentStore{connection: connection, storeName: storeName}, nil
} else {
return nil, errors.New(fmt.Sprintf("store %v not found", storeName))
}
}
// Method executes TableExists RPC request with given store name and return true if table is exists or false if not.
func (connection *Connection) IsStoreExists(storeName string) (bool, error) {
header := make(metadata.MD)
trailer := make(metadata.MD)
ctx, cancel := context.WithTimeout(context.Background(),
time.Duration(connection.opts.CallTimeoutSeconds)*time.Second)
defer cancel()
response, err := connection.stub.TableExists(ctx,
&TableExistsRequest{TablePath: storeName},
grpc.Header(&header),
grpc.Trailer(&trailer))
if err != nil {
return false, errors.New(fmt.Sprintf("couldn't execute request: %v", err))
}
connection.umd.UpdateToken(header, trailer)
return checkExistsErrorCode(response.GetError())
}
// Method executes DeleteTable RPC request with given store name.
func (connection *Connection) DeleteStore(storeName string) error {
header := make(metadata.MD)
trailer := make(metadata.MD)
ctx, cancel := context.WithTimeout(context.Background(),
time.Duration(connection.opts.CallTimeoutSeconds)*time.Second)
defer cancel()
response, err := connection.stub.DeleteTable(ctx,
&DeleteTableRequest{TablePath: storeName},
grpc.Header(&header),
grpc.Trailer(&trailer))
if err != nil {
return err
}
err = checkResponseErrorCode(response.GetError())
if err != nil {
return err
}
connection.umd.UpdateToken(header, trailer)
return nil
}
// Creates and returns a new instance of an OJAI Document.
func (connection *Connection) CreateDocumentFromString(jsonString string) (*Document, error) {
return MakeDocumentFromJson(jsonString)
}
// Creates and returns a new, empty instance of an OJAI Document.
func (connection *Connection) CreateEmptyDocument() (*Document, error) {
return MakeDocument()
}
// Creates and returns a new instance of an OJAI Document.
func (connection *Connection) CreateDocumentFromMap(documentMap map[string]interface{}) *Document {
return MakeDocumentFromMap(documentMap)
}
// Method executes CreateTable RPC request with given store name and return new DocumentStore.
func (connection *Connection) CreateStore(storeName string) (*DocumentStore, error) {
header := make(metadata.MD)
trailer := make(metadata.MD)
ctx, cancel := context.WithTimeout(context.Background(),
time.Duration(connection.opts.CallTimeoutSeconds)*time.Second)
defer cancel()
response, err := connection.stub.CreateTable(ctx,
&CreateTableRequest{TablePath: storeName},
grpc.Header(&header),
grpc.Trailer(&trailer))
if err != nil {
return nil, errors.New(fmt.Sprintf("couldn't execute request: %v", err))
}
err = checkResponseErrorCode(response.GetError())
if err != nil {
return nil, err
}
connection.umd.UpdateToken(header, trailer)
return connection.GetStore(storeName)
}
// Method checks response error code.
func checkResponseErrorCode(rpcError *RpcError) error {
switch rpcError.ErrCode {
case ErrorCode_NO_ERROR:
return nil
default:
return errors.New(fmt.Sprintf("unexpected error code recieved from server.\n error: %v.\n"+
" error message : %v.\n java stacktrace: %v.\n",
rpcError.ErrCode.String(),
rpcError.ErrorMessage,
rpcError.JavaStackTrace))
}
}
// Method checks IsTableExists response error code and return true
// if error code is 0 (NO ERROR), false if error code 2(TABLE NOT FOUND) otherwise error.
func checkExistsErrorCode(rpcError *RpcError) (bool, error) {
switch rpcError.ErrCode {
case ErrorCode_NO_ERROR:
return true, nil
case ErrorCode_TABLE_NOT_FOUND:
return false, nil
default:
return false, errors.New(fmt.Sprintf("unexpected error code recieved from server.\n error: %v.\n"+
" error message : %v.\n java stacktrace: %v.\n",
rpcError.ErrCode.String(),
rpcError.ErrorMessage,
rpcError.JavaStackTrace))
}
}
// Method parses input connection string and returns argument or default values.
func parseConnectionString(connectionString string) (
connectionUrl string,
auth string,
encodedMetadata string,
ssl bool,
sslValidate bool,
sslCA string,
sslTargetNameOverride string,
err error) {
u, err := url.Parse(connectionString)
if err != nil {
connectionString = prefix + connectionString
u, err = url.Parse(connectionString)
if err != nil {
return
}
}
mapValues := parseQuery(u.RawQuery)
connectionUrl = findHost(fmt.Sprintf("%v:%v", u.Scheme, u.Opaque))
auth = getValueOrDefault(mapValues, "auth", "basic")
user := getValueOrDefault(mapValues, "user", "")
password := getValueOrDefault(mapValues, "password", "")
encodedMetadata = b64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%v:%v", user, password)))
sslDecoded := getValueOrDefault(mapValues, "ssl", "false")
ssl, err = strconv.ParseBool(sslDecoded)
if err != nil {
return
}
sslValidateDecoded := getValueOrDefault(mapValues, "sslValidate", "true")
sslValidate, err = strconv.ParseBool(sslValidateDecoded)
if err != nil {
return
}
sslCA = getValueOrDefault(mapValues, "sslCA", "")
sslTargetNameOverride = getValueOrDefault(mapValues, "sslTargetNameOverride", "")
//TODO add value validation before return
return
}
// find host or host:port in connection string opaque value
func findHost(unparsedString string) string {
parsedString := strings.Split(unparsedString, "@")
return parsedString[len(parsedString)-1]
}
func parseQuery(unparsedString string) url.Values {
items := strings.Split(unparsedString, ";")
// create and fill the map
valuesMap := make(url.Values)
for _, item := range items {
value := strings.Split(item, "=")
valuesMap[value[0]] = append(valuesMap[value[0]], value[1])
}
return valuesMap
}
// method fetches value from url.Values or returns default value
func getValueOrDefault(content url.Values, key string, defaultValue string) string {
if val, ok := content[key]; ok {
decodedValue, _ := url.QueryUnescape(val[0])
return decodedValue
} else {
return defaultValue
}
}
// Function initialize connection and returns new Connection struct
func MakeConnection(connectionString string) (*Connection, error) {
return MakeConnectionWithRetryOptions(connectionString, nil)
}
// Function initialize connection with specific retry options and returns new Connection struct
func MakeConnectionWithRetryOptions(
connectionString string,
connectionOptions *ConnectionOptions,
) (*Connection, error) {
connectionUrl, auth, encodedMetadata,
ssl, sslValidate, sslCA, sslTargetNameOverride, err := parseConnectionString(connectionString)
if err != nil {
return nil, err
}
if auth != "basic" {
return nil, errors.New("currently server supports only 'basic' authentication")
}
connection, err := createChannel(
&encodedMetadata,
&connectionUrl,
&ssl,
&sslValidate,
&sslCA,
&sslTargetNameOverride,
connectionOptions)
if err != nil {
return nil, err
}
connection.stub = NewMapRDbServerClient(connection.channel)
err = pingRequest(connection)
if err != nil {
return nil, err
}
return connection, nil
}
// Method Close closes gRPC channel.
func (connection *Connection) Close() {
defer connection.channel.Close()
}