forked from gravitational/teleport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.go
354 lines (323 loc) · 9.79 KB
/
test.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
/*
Copyright 2022 Gravitational, Inc.
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 cassandra
import (
"bytes"
"context"
"crypto/tls"
"net"
"strings"
"time"
"github.com/datastax/go-cassandra-native-protocol/client"
"github.com/datastax/go-cassandra-native-protocol/datatype"
"github.com/datastax/go-cassandra-native-protocol/frame"
"github.com/datastax/go-cassandra-native-protocol/message"
"github.com/datastax/go-cassandra-native-protocol/primitive"
"github.com/gocql/gocql"
"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
"github.com/zmb3/teleport/lib/defaults"
"github.com/zmb3/teleport/lib/srv/db/common"
)
// Session alias for easier use.
type Session = gocql.Session
// ClientOptionsParams is a struct for client configuration options.
type ClientOptionsParams struct {
Username string
}
// ClientOptions allows setting test client options.
type ClientOptions func(*ClientOptionsParams)
// WithCassandraUsername set the username used during cassandra login.
func WithCassandraUsername(username string) ClientOptions {
return func(params *ClientOptionsParams) {
params.Username = username
}
}
// MakeTestClient returns Cassandra client connection according to the provided
// parameters.
func MakeTestClient(_ context.Context, config common.TestClientConfig, opts ...ClientOptions) (*Session, error) {
tlsConfig, err := common.MakeTestClientTLSConfig(config)
if err != nil {
return nil, trace.Wrap(err)
}
clientOptions := &ClientOptionsParams{}
for _, opt := range opts {
opt(clientOptions)
}
cluster := gocql.NewCluster(config.Address)
cluster.SslOpts = &gocql.SslOptions{
Config: tlsConfig,
}
cluster.DisableInitialHostLookup = true
cluster.ConnectTimeout = 5 * time.Second
cluster.Timeout = 5 * time.Second
cluster.ProtoVersion = 4
cluster.Authenticator = gocql.PasswordAuthenticator{
Username: "cassandra",
Password: "cassandra",
}
session, err := cluster.CreateSession()
if err != nil {
return nil, trace.Wrap(err)
}
return session, nil
}
// TestServerOption allows setting test server options.
type TestServerOption func(*TestServer)
type TestServer struct {
cfg common.TestServerConfig
port string
tlsConfig *tls.Config
log logrus.FieldLogger
server *client.CqlServer
}
// NewTestServer returns a new instance of a test Snowflake server.
func NewTestServer(config common.TestServerConfig, opts ...TestServerOption) (*TestServer, error) {
address := "localhost:0"
tlsConfig, err := common.MakeTestServerTLSConfig(config)
if err != nil {
return nil, trace.Wrap(err)
}
server := client.NewCqlServer(address, &client.AuthCredentials{
Password: "cassandra",
Username: "cassandra",
})
if config.Listener != nil {
server.Listener = tls.NewListener(config.Listener, tlsConfig)
}
server.RequestHandlers = []client.RequestHandler{
client.HandshakeHandler,
handleMessageOption,
handleMessageQuery,
handleMessagePrepare,
handleMessageExecute,
handleMessageBatch,
handleMessageRegister,
}
server.TLSConfig = tlsConfig
if err := server.Start(context.Background()); err != nil {
return nil, trace.Wrap(err)
}
_, port, err := net.SplitHostPort(server.Listener.Addr().String())
if err != nil {
return nil, trace.Wrap(err)
}
testServer := &TestServer{
cfg: config,
port: port,
tlsConfig: tlsConfig,
server: server,
log: logrus.WithFields(logrus.Fields{
trace.Component: defaults.ProtocolCassandra,
"name": config.Name,
}),
}
for _, opt := range opts {
opt(testServer)
}
return testServer, nil
}
// Serve starts serving client connections.
func (s *TestServer) Serve() error {
return s.server.Start(context.Background())
}
// Close closes the server.
func (s *TestServer) Close() error {
return s.server.Close()
}
func (s *TestServer) Port() string {
return s.port
}
func handleMessageQuery(request *frame.Frame, conn *client.CqlServerConnection, ctx client.RequestHandlerContext) *frame.Frame {
switch msg := request.Body.Message.(type) {
case *message.Query:
lQuery := strings.TrimSpace(strings.ToLower(msg.Query))
switch lQuery {
case "select * from system.local where key='local'":
return frame.NewFrame(
request.Header.Version,
request.Header.StreamId,
&message.RowsResult{
Metadata: &message.RowsMetadata{
ColumnCount: 7,
Columns: []*message.ColumnMetadata{
{Keyspace: "system", Table: "local", Name: "key", Index: 0, Type: datatype.Varchar},
{Keyspace: "system", Table: "local", Name: "bootstrapped", Index: 0, Type: datatype.Varchar},
{Keyspace: "system", Table: "local", Name: "broadcast_address", Index: 0, Type: datatype.Inet},
{Keyspace: "system", Table: "local", Name: "broadcast_port", Index: 0, Type: datatype.Inet},
{Keyspace: "system", Table: "local", Name: "cluster_name", Index: 0, Type: datatype.Varchar},
{Keyspace: "system", Table: "local", Name: "cql_version", Index: 0, Type: datatype.Varchar},
{Keyspace: "system", Table: "local", Name: "data_center", Index: 0, Type: datatype.Varchar},
},
},
Data: message.RowSet{
{
[]byte("local"),
[]byte("COMPLETED"),
[]byte{192, 168, 0, 185},
[]byte{0, 0, 27, 88},
[]byte("Test Cluster"),
[]byte("3.4.5"),
[]byte("datacenter1"),
},
},
},
)
}
}
return nil
}
func handleMessagePrepare(request *frame.Frame, conn *client.CqlServerConnection, ctx client.RequestHandlerContext) *frame.Frame {
switch msg := request.Body.Message.(type) {
case *message.Prepare:
lQuery := strings.TrimSpace(strings.ToLower(msg.Query))
switch lQuery {
case "select * from system_schema.keyspaces":
return frame.NewFrame(
request.Header.Version,
request.Header.StreamId,
&message.PreparedResult{
PreparedQueryId: []byte{211, 78, 99, 137, 52, 114, 28, 59, 205, 105, 147, 63, 153, 42, 0, 203},
ResultMetadata: &message.RowsMetadata{
ColumnCount: 3,
},
})
case "select cluster_name from system.local":
return frame.NewFrame(
request.Header.Version,
request.Header.StreamId,
&message.PreparedResult{
PreparedQueryId: []byte{48, 60, 203, 12, 80, 82, 198, 204, 96, 125, 128, 97, 211, 209, 122, 35},
ResultMetadata: &message.RowsMetadata{
ColumnCount: 1,
Columns: []*message.ColumnMetadata{
{
Keyspace: "system",
Table: "local",
Name: "cluster_name",
Index: 0,
Type: datatype.Varchar,
},
},
},
})
}
}
return nil
}
func handleMessageExecute(request *frame.Frame, conn *client.CqlServerConnection, ctx client.RequestHandlerContext) *frame.Frame {
switch msg := request.Body.Message.(type) {
case *message.Execute:
switch {
case bytes.Equal(msg.QueryId, []byte{211, 78, 99, 137, 52, 114, 28, 59, 205, 105, 147, 63, 153, 42, 0, 203}):
return frame.NewFrame(
request.Header.Version,
request.Header.StreamId,
&message.RowsResult{
Metadata: &message.RowsMetadata{
ColumnCount: 3,
},
Data: message.RowSet{
{
[]byte("system_auth"),
[]byte("org.apache.cassandra.locator.SimpleStrategy"),
[]byte("1"),
},
{
[]byte("system_schema"),
[]byte("org.apache.cassandra.locator.LocalStrategy"),
[]byte("1"),
},
{
[]byte("system_distributed"),
[]byte("org.apache.cassandra.locator.SimpleStrategy"),
[]byte("3"),
},
{
[]byte("system"),
[]byte("org.apache.cassandra.locator.LocalStrategy"),
[]byte("1"),
},
{
[]byte("system_traces"),
[]byte("org.apache.cassandra.locator.SimpleStrategy"),
[]byte("2"),
},
},
},
)
case bytes.Equal(msg.QueryId, []byte{48, 60, 203, 12, 80, 82, 198, 204, 96, 125, 128, 97, 211, 209, 122, 35}):
return frame.NewFrame(
request.Header.Version,
request.Header.StreamId,
&message.RowsResult{
Metadata: &message.RowsMetadata{
ColumnCount: 1,
},
Data: message.RowSet{
{
[]byte("Test Cluster"),
},
},
},
)
}
}
return nil
}
func handleMessageRegister(request *frame.Frame, conn *client.CqlServerConnection, ctx client.RequestHandlerContext) *frame.Frame {
switch request.Body.Message.(type) {
case *message.Register:
return frame.NewFrame(
request.Header.Version,
request.Header.StreamId,
&message.Ready{},
)
default:
return nil
}
}
func handleMessageBatch(request *frame.Frame, conn *client.CqlServerConnection, ctx client.RequestHandlerContext) *frame.Frame {
codec := frame.NewRawCodec()
switch request.Body.Message.(type) {
case *message.Batch:
resp := &frame.RawFrame{
Header: &frame.Header{
IsResponse: true,
Version: request.Header.Version,
StreamId: request.Header.StreamId,
OpCode: primitive.OpCodeResult,
BodyLength: 4,
},
Body: []byte{0, 0, 0, 1},
}
responseFrame, err := codec.ConvertFromRawFrame(resp)
if err != nil {
logrus.Errorf("Error converting raw frame to frame: %v", err)
return nil
}
return responseFrame
default:
return nil
}
}
func handleMessageOption(request *frame.Frame, conn *client.CqlServerConnection, ctx client.RequestHandlerContext) *frame.Frame {
if _, ok := request.Body.Message.(*message.Options); ok {
return frame.NewFrame(
request.Header.Version,
request.Header.StreamId,
&message.Supported{},
)
}
return nil
}