-
Notifications
You must be signed in to change notification settings - Fork 163
/
client.go
401 lines (339 loc) · 11 KB
/
client.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
package scyllaclient
import (
"context"
"crypto/tls"
"net"
"net/http"
"runtime"
"sort"
"strings"
"sync"
"time"
api "github.com/go-openapi/runtime/client"
apiMiddleware "github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/strfmt"
"github.com/hailocab/go-hostpool"
"github.com/scylladb/go-log"
"github.com/scylladb/go-set/strset"
"github.com/scylladb/scylla-operator/pkg/auth"
scyllaClient "github.com/scylladb/scylla-operator/pkg/scyllaclient/internal/scylla/client"
scyllaOperations "github.com/scylladb/scylla-operator/pkg/scyllaclient/internal/scylla/client/operations"
"github.com/scylladb/scylla-operator/pkg/util/httpx"
)
type Client struct {
config *Config
logger log.Logger
scyllaOps *scyllaOperations.Client
transport http.RoundTripper
pool hostpool.HostPool
mu sync.RWMutex
dcCache map[string]string
}
func NewClient(config *Config, logger log.Logger) (*Client, error) {
/*if err := config.Validate(); err != nil {
return nil, errors.Wrap(err, "invalid config")
}*/
setOpenAPIGlobals()
hosts := make([]string, len(config.Hosts))
copy(hosts, config.Hosts)
pool := hostpool.NewEpsilonGreedy(hosts, config.PoolDecayDuration, &hostpool.LinearEpsilonValueCalculator{})
if config.Transport == nil {
config.Transport = DefaultTransport()
}
transport := config.Transport
transport = timeout(transport, config.Timeout)
transport = requestLogger(transport, logger)
transport = hostPool(transport, pool, config.Port)
transport = auth.AddToken(transport, config.AuthToken)
transport = fixContentType(transport)
c := &http.Client{Transport: transport}
scyllaRuntime := api.NewWithClient(
scyllaClient.DefaultHost, scyllaClient.DefaultBasePath, []string{config.Scheme}, c,
)
// Debug can be turned on by SWAGGER_DEBUG or DEBUG env variable
scyllaRuntime.Debug = false
scyllaOps := scyllaOperations.New(retryable(scyllaRuntime, config, logger), strfmt.Default)
return &Client{
config: config,
logger: logger,
scyllaOps: scyllaOps,
transport: transport,
pool: pool,
dcCache: make(map[string]string),
}, nil
}
func (c *Client) Close() {
if c.pool != nil {
c.pool.Close()
}
}
// HostDatacenter looks up the datacenter that the given host belongs to.
func (c *Client) HostDatacenter(ctx context.Context, host string) (dc string, err error) {
// Try reading from cache
c.mu.RLock()
dc = c.dcCache[host]
c.mu.RUnlock()
if dc != "" {
return
}
resp, err := c.scyllaOps.SnitchDatacenterGet(&scyllaOperations.SnitchDatacenterGetParams{
Context: ctx,
Host: &host,
})
if err != nil {
return "", err
}
dc = resp.Payload
return
}
func (c *Client) Status(ctx context.Context, host string) (NodeStatusInfoSlice, error) {
if len(host) > 0 {
// Always query same host
ctx = forceHost(ctx, host)
}
// Get all hosts
resp, err := c.scyllaOps.StorageServiceHostIDGet(&scyllaOperations.StorageServiceHostIDGetParams{Context: ctx})
if err != nil {
return nil, err
}
all := make([]NodeStatusInfo, len(resp.Payload))
for i, p := range resp.Payload {
all[i].Addr = p.Key
all[i].HostID = p.Value
}
// Get host datacenter (hopefully cached)
for i := range all {
all[i].Datacenter, err = c.HostDatacenter(ctx, all[i].Addr)
if err != nil {
return nil, err
}
}
// Get live nodes
live, err := c.scyllaOps.GossiperEndpointLiveGet(&scyllaOperations.GossiperEndpointLiveGetParams{Context: ctx})
if err != nil {
return nil, err
}
setNodeStatus(all, NodeStatusUp, live.Payload)
// Get joining nodes
joining, err := c.scyllaOps.StorageServiceNodesJoiningGet(&scyllaOperations.StorageServiceNodesJoiningGetParams{Context: ctx})
if err != nil {
return nil, err
}
setNodeState(all, NodeStateJoining, joining.Payload)
// Get leaving nodes
leaving, err := c.scyllaOps.StorageServiceNodesLeavingGet(&scyllaOperations.StorageServiceNodesLeavingGetParams{Context: ctx})
if err != nil {
return nil, err
}
setNodeState(all, NodeStateLeaving, leaving.Payload)
// Get moving nodes
moving, err := c.scyllaOps.StorageServiceNodesMovingGet(&scyllaOperations.StorageServiceNodesMovingGetParams{Context: ctx})
if err != nil {
return nil, err
}
setNodeState(all, NodeStateMoving, moving.Payload)
// Sort by Datacenter and Address
sort.Slice(all, func(i, j int) bool {
if all[i].Datacenter != all[j].Datacenter {
return all[i].Datacenter < all[j].Datacenter
}
return all[i].Addr < all[j].Addr
})
return all, nil
}
func (c *Client) GetLocalHostId(ctx context.Context, host string, retry bool) (string, error) {
if len(host) > 0 {
ctx = forceHost(ctx, host)
}
if !retry {
ctx = noRetry(ctx)
}
resp, err := c.scyllaOps.StorageServiceHostidLocalGet(&scyllaOperations.StorageServiceHostidLocalGetParams{Context: ctx})
if err != nil {
return "", err
}
return resp.GetPayload(), nil
}
const (
snapshotTimeout = 5 * time.Minute
drainTimeout = 5 * time.Minute
)
// Keyspaces return a list of all the keyspaces.
func (c *Client) Keyspaces(ctx context.Context) ([]string, error) {
resp, err := c.scyllaOps.StorageServiceKeyspacesGet(&scyllaOperations.StorageServiceKeyspacesGetParams{Context: ctx})
if err != nil {
return nil, err
}
return resp.Payload, nil
}
// Snapshots lists available snapshots.
func (c *Client) Snapshots(ctx context.Context, host string) ([]string, error) {
ctx = customTimeout(ctx, snapshotTimeout)
resp, err := c.scyllaOps.StorageServiceSnapshotsGet(&scyllaOperations.StorageServiceSnapshotsGetParams{
Context: forceHost(ctx, host),
})
if err != nil {
return nil, err
}
var tags []string
for _, p := range resp.Payload {
tags = append(tags, p.Key)
}
return tags, nil
}
// TakeSnapshot flushes and takes a snapshot of a keyspace.
// Multiple keyspaces may have the same tag.
func (c *Client) TakeSnapshot(ctx context.Context, host, tag, keyspace string, tables ...string) error {
ctx = customTimeout(ctx, snapshotTimeout)
var cfPtr *string
if len(tables) > 0 {
v := strings.Join(tables, ",")
cfPtr = &v
}
if _, err := c.scyllaOps.StorageServiceKeyspaceFlushByKeyspacePost(&scyllaOperations.StorageServiceKeyspaceFlushByKeyspacePostParams{ // nolint: errcheck
Context: forceHost(ctx, host),
Keyspace: keyspace,
Cf: cfPtr,
}); err != nil {
return err
}
if _, err := c.scyllaOps.StorageServiceSnapshotsPost(&scyllaOperations.StorageServiceSnapshotsPostParams{ // nolint: errcheck
Context: forceHost(ctx, host),
Tag: &tag,
Kn: &keyspace,
Cf: cfPtr,
}); err != nil {
return err
}
return nil
}
// DeleteSnapshot removes a snapshot with a given tag.
func (c *Client) DeleteSnapshot(ctx context.Context, host, tag string) error {
ctx = customTimeout(ctx, snapshotTimeout)
_, err := c.scyllaOps.StorageServiceSnapshotsDelete(&scyllaOperations.StorageServiceSnapshotsDeleteParams{ // nolint: errcheck
Context: forceHost(ctx, host),
Tag: &tag,
})
return err
}
// Drain makes node unavailable for writes, flushes memtables and replays commitlog
func (c *Client) Drain(ctx context.Context, host string) error {
ctx = customTimeout(ctx, drainTimeout)
if _, err := c.scyllaOps.StorageServiceDrainPost(&scyllaOperations.StorageServiceDrainPostParams{ // nolint: errcheck
Context: forceHost(ctx, host),
}); err != nil {
return err
}
return nil
}
func (c *Client) Decommission(ctx context.Context, host string) error {
queryCtx := forceHost(ctx, host)
// On decommission request api server waits till decommission is completed
// Usually decommission takes significant amount of time therefore request is failing by timeout
// As result of the scylla client will retry it and get 500 response that is saying that
// decommission is already in progress.
// To avoid that we pass noRetry to the context
queryCtx = noRetry(queryCtx)
_, err := c.scyllaOps.StorageServiceDecommissionPost(&scyllaOperations.StorageServiceDecommissionPostParams{Context: queryCtx})
if err != nil {
return err
}
return nil
}
func (c *Client) ScyllaVersion(ctx context.Context) (string, error) {
resp, err := c.scyllaOps.StorageServiceScyllaReleaseVersionGet(&scyllaOperations.StorageServiceScyllaReleaseVersionGetParams{Context: ctx})
if err != nil {
return "", err
}
return resp.Payload, nil
}
func (c *Client) OperationMode(ctx context.Context, host string) (OperationalMode, error) {
resp, err := c.scyllaOps.StorageServiceOperationModeGet(&scyllaOperations.StorageServiceOperationModeGetParams{Context: forceHost(ctx, host)})
if err != nil {
return "", err
}
return operationalModeFromString(resp.Payload), nil
}
func (c *Client) IsNativeTransportEnabled(ctx context.Context, host string) (bool, error) {
resp, err := c.scyllaOps.StorageServiceNativeTransportGet(&scyllaOperations.StorageServiceNativeTransportGetParams{Context: forceHost(ctx, host)})
if err != nil {
return false, err
}
return resp.Payload, nil
}
func (c *Client) HasSchemaAgreement(ctx context.Context) (bool, error) {
resp, err := c.scyllaOps.StorageProxySchemaVersionsGet(&scyllaOperations.StorageProxySchemaVersionsGetParams{Context: ctx})
if err != nil {
return false, err
}
versions := map[string]struct{}{}
for _, kv := range resp.Payload {
versions[kv.Key] = struct{}{}
}
return len(versions) == 1, nil
}
func DefaultTransport() *http.Transport {
return &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
}
func setNodeState(all []NodeStatusInfo, state NodeState, addrs []string) {
if len(addrs) == 0 {
return
}
m := strset.New(addrs...)
for i := range all {
if m.Has(all[i].Addr) {
all[i].State = state
}
}
}
func setNodeStatus(all []NodeStatusInfo, status NodeStatus, addrs []string) {
if len(addrs) == 0 {
return
}
m := strset.New(addrs...)
for i := range all {
if m.Has(all[i].Addr) {
all[i].Status = status
}
}
}
var setOpenAPIGlobalsOnce sync.Once
func setOpenAPIGlobals() {
setOpenAPIGlobalsOnce.Do(func() {
// Timeout is defined in http client that we provide in api.NewWithClient.
// If Context is provided to operation, which is always the case here,
// this value has no meaning since OpenAPI runtime ignores it.
api.DefaultTimeout = 0
// Disable debug output to stderr, it could have been enabled by setting
// SWAGGER_DEBUG or DEBUG env variables.
apiMiddleware.Debug = false
})
}
// fixContentType adjusts Scylla REST API response so that it can be consumed
// by Open API.
func fixContentType(next http.RoundTripper) http.RoundTripper {
return httpx.RoundTripperFunc(func(req *http.Request) (resp *http.Response, err error) {
defer func() {
if resp != nil {
// Force JSON, Scylla returns "text/plain" that misleads the
// unmarshaller and breaks processing.
resp.Header.Set("Content-Type", "application/json")
}
}()
return next.RoundTrip(req)
})
}