Repository navigation
Expand file tree
/
Copy pathapi.go
More file actions
444 lines (363 loc) · 11.1 KB
/
Copy pathapi.go
File metadata and controls
444 lines (363 loc) · 11.1 KB
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
package cbmgr
import (
"fmt"
"io/ioutil"
"net/http"
"sync/atomic"
"time"
"unsafe"
"github.com/sirupsen/logrus"
)
// Certificate and key used by TLS client authentication
type TLSClientAuth struct {
// PEM encoded certificate
Cert []byte
// PEM encoded private key
Key []byte
}
// TLS Authentication parameters
type TLSAuth struct {
// PEM encoded CA certificate
CACert []byte
// Optional client authentication
ClientAuth *TLSClientAuth
}
// Client certificate authentication prefixes, used to extract the user name
type ClientCertAuthPrefix struct {
Path string `json:"path"`
Prefix string `json:"prefix"`
Delimiter string `json:"delimiter"`
}
// Client certificate authentication settings
type ClientCertAuth struct {
// Must be 'disable', 'enable', 'mandatory'
State string `json:"state"`
// Maximum of 10
Prefixes []ClientCertAuthPrefix `json:"prefixes"`
}
// UserAgent defines the HTTP User-Agent header string
type UserAgent struct {
// Name is the unique name of the client e.g. couchbase-operator
Name string
// Version is the release version of the client
Version string
// UUID is a unique identifier of the client to differentiate it from
// other clients of the same Name e.g. a FQDN. This field is optional
UUID string
}
// Couchbase is a structure which encapsulates HTTP API access to a
// Couchbase cluster
type Couchbase struct {
// endpoints is a list of URIs to try when performing and operation
endpoints []string
// username is used in basic HTTP authorization
username string
// password is used in basic HTTP authorization
password string
// uuid, when set, is used to verify that endpoints we are connecting
// to are part of the specified cluster and will return reliable
// responses
uuid string
// tls, if set, specifies the client certificate chain and private keys
// for mutual verification. It also contains at least a CA certificate
// to authenticate the server is trustworthy
tls *TLSAuth
// client is a persistent connection pool to be used by all endpoints
// associated with this connection context. It will become invalid
// if any parameters used in the TLS handshake, or HTTP UUID check
// are updated.
client *http.Client
// userAgent is sent to the server for all API requests and allows us
// to uniquely identify the client e.g. differentiates from other go
// tools or even instances of couchbase-operator
userAgent *UserAgent
// the logger for this client
logger *logrus.Logger
}
// New creates a new Couchbase HTTP(S) API client and initializes the
// HTTP connection pool.
func New(username, password string) *Couchbase {
c := &Couchbase{
endpoints: []string{},
username: username,
password: password,
logger: logrus.New(),
}
c.logger.Out = ioutil.Discard
c.makeClient()
return c
}
// SetEndpoints sets the current working set of endpoints to try API requests
// against in the event of failure. The endpoint host and port will be used
// to lookup a persistent connection in the http.Client.
func (c *Couchbase) SetEndpoints(endpoints []string) {
c.endpoints = endpoints
}
// SetUUID updates the cluster UUID to check new connections against. Creates
// a new client object to flush existing persistent connections.
func (c *Couchbase) SetUUID(uuid string) {
c.uuid = uuid
c.makeClient()
}
func (c *Couchbase) SetLogger(logger *logrus.Logger) {
c.logger = logger
}
// SetTLS updates the client TLS settings. Creates a new client object to
// flush existing persistent connections.
func (c *Couchbase) SetTLS(tls *TLSAuth) {
c.tls = tls
c.makeClient()
}
// SetUserAgent sets the User-Agent header to be sent in subsequent HTTP
// requests
func (c *Couchbase) SetUserAgent(userAgent *UserAgent) {
c.userAgent = userAgent
}
type RebalanceProgress struct {
client *Couchbase
cancelled *atomicBool
logger *logrus.Entry
interval time.Duration
}
func (r *RebalanceProgress) Wait() error {
isRunning := true
for isRunning && !r.cancelled.Load() {
tasks, err := r.client.getTasks()
if err != nil {
return err
}
for _, task := range tasks {
if task.Type == "rebalance" {
if task.Status == RebalanceStatusNotRunning || task.Status == RebalanceStatusStale {
isRunning = false
} else if task.Status == RebalanceStatusRunning {
logger := (*logrus.Entry)(atomic.LoadPointer((*unsafe.Pointer)((unsafe.Pointer)(&r.logger))))
if logger != nil {
logger.Infof("Rebalance progress: %f", task.Progress)
}
}
}
}
time.Sleep(r.interval)
}
return nil
}
func (r *RebalanceProgress) SetLogger(logger *logrus.Entry) {
atomic.SwapPointer((*unsafe.Pointer)((unsafe.Pointer)(&r.logger)), unsafe.Pointer(logger))
}
func (r *RebalanceProgress) Cancel() {
r.cancelled.Store(true)
}
func (c *Couchbase) AddNode(hostname, username, password string, services ServiceList) error {
return c.addNode(hostname, username, password, services)
}
func (c *Couchbase) CancelAddNode(hostname string) error {
cluster, err := c.getPoolsDefault()
if err != nil {
return err
}
for _, node := range cluster.Nodes {
if node.HostName == hostname {
return c.cancelAddNode(node.OTPNode)
}
}
return fmt.Errorf("Hostname %s is not part of the cluster", hostname)
}
func (c *Couchbase) CancelAddBackNode(hostname string) error {
cluster, err := c.getPoolsDefault()
if err != nil {
return err
}
for _, node := range cluster.Nodes {
if node.HostName == hostname {
return c.cancelAddBackNode(node.OTPNode)
}
}
return fmt.Errorf("Hostname %s is not part of the cluster", hostname)
}
func (c *Couchbase) ClusterInfo() (*ClusterInfo, error) {
return c.getPoolsDefault()
}
func (c *Couchbase) SetPoolsDefault(defaults *PoolsDefaults) error {
return c.setPoolsDefault(defaults)
}
func (c *Couchbase) ClusterInitialize(username, password string, defaults *PoolsDefaults,
port int, services []ServiceName, mode IndexStorageMode) error {
if err := c.setPoolsDefault(defaults); err != nil {
return err
}
settings, err := c.getIndexSettings()
if err != nil {
return err
}
if err := c.setIndexSettings(mode, settings.Threads, settings.MemSnapInterval,
settings.StableSnapInterval, settings.MaxRollbackPoints, settings.LogLevel); err != nil {
return err
}
if err := c.setServices(services); err != nil {
return err
}
if err := c.setWebSettings(username, password, port); err != nil {
return err
}
return nil
}
func (c *Couchbase) ClusterUUID() (string, error) {
if info, err := c.getPools(); err != nil {
return "", err
} else {
if uuid, ok := info.UUID.(string); ok {
return uuid, nil
}
return "", nil
}
}
func (c *Couchbase) NodeInitialize(hostname, dataPath, indexPath string, analyticsPaths []string) error {
if err := c.setHostname(hostname); err != nil {
return err
}
if err := c.setStoragePaths(dataPath, indexPath, analyticsPaths); err != nil {
return err
}
return nil
}
func (c *Couchbase) Rebalance(nodesToRemove []string) (*RebalanceProgress, error) {
cluster, err := c.getPoolsDefault()
if err != nil {
return nil, err
}
all := []string{}
eject := []string{}
for _, node := range cluster.Nodes {
all = append(all, node.OTPNode)
for _, toRemove := range nodesToRemove {
if node.HostName == toRemove {
eject = append(eject, node.OTPNode)
}
}
}
err = c.rebalance(all, eject)
if err != nil {
return nil, err
}
return &RebalanceProgress{c, newAtomicBool(false), nil, 4 * time.Second}, nil
}
func (c *Couchbase) Failover(nodeToRemove string) error {
cluster, err := c.getPoolsDefault()
if err != nil {
return err
}
for _, node := range cluster.Nodes {
if node.HostName == nodeToRemove {
return c.failover(node.OTPNode)
}
}
return NewErrorClusterNodeNotFound(nodeToRemove)
}
func (c *Couchbase) CreateBucket(bucket *Bucket) error {
return c.createBucket(bucket)
}
func (c *Couchbase) DeleteBucket(name string) error {
return c.deleteBucket(name)
}
func (c *Couchbase) EditBucket(bucket *Bucket) error {
return c.editBucket(bucket)
}
// Determine wether bucket is ready based on status resolving
// to healthy across all nodes
func (c *Couchbase) BucketReady(name string) (bool, error) {
status, err := c.getBucketStatus(name)
if err != nil {
return false, err
}
// check bucket health on all nodes
if len(status.Nodes) == 0 {
return false, NewErrorBucketNotReady(name, "creation pending")
}
for _, node := range status.Nodes {
if node.Status != "healthy" {
return false, NewErrorBucketNotReady(name, node.Status)
}
}
return true, nil
}
func (c *Couchbase) GetBucketStatus(name string) (*BucketStatus, error) {
status, err := c.getBucketStatus(name)
if err != nil {
return nil, err
}
return status, nil
}
func (c *Couchbase) GetBuckets() ([]*Bucket, error) {
return c.getBuckets()
}
func (c *Couchbase) SetAutoFailoverSettings(settings *AutoFailoverSettings) error {
return c.setAutoFailoverSettings(settings)
}
func (c *Couchbase) GetAutoFailoverSettings() (*AutoFailoverSettings, error) {
return c.getAutoFailoverSettings()
}
func (c *Couchbase) ResetFailoverCounter() error {
return c.resetCount()
}
func (c *Couchbase) GetIndexSettings() (*IndexSettings, error) {
return c.getIndexSettings()
}
func (c *Couchbase) SetIndexSettings(settings *IndexSettings) error {
return c.setIndexSettings(settings.StorageMode, settings.Threads, settings.MemSnapInterval,
settings.StableSnapInterval, settings.MaxRollbackPoints, settings.LogLevel)
}
func (c *Couchbase) GetNodeInfo() (*NodeInfo, error) {
return c.getNodeInfo()
}
func (c *Couchbase) UploadClusterCACert(pem []byte) error {
return c.uploadClusterCACert(pem)
}
func (c *Couchbase) ReloadNodeCert() error {
return c.reloadNodeCert()
}
func (c *Couchbase) SetClientCertAuth(settings *ClientCertAuth) error {
return c.setClientCertAuth(settings)
}
func (c *Couchbase) GetUpdatesEnabled() (bool, error) {
return c.getUpdatesEnabled()
}
func (c *Couchbase) SetUpdatesEnabled(enabled bool) error {
return c.setUpdatesEnabled(enabled)
}
func (c *Couchbase) GetAlternateAddressesExternal() (*AlternateAddressesExternal, error) {
return c.getAlternateAddressesExternal()
}
func (c *Couchbase) SetAlternateAddressesExternal(addresses *AlternateAddressesExternal) error {
return c.setAlternateAddressesExternal(addresses)
}
func (c *Couchbase) DeleteAlternateAddressesExternal() error {
return c.deleteAlternateAddressesExternal()
}
func (c *Couchbase) GetLogs() ([]*LogMessage, error) {
return c.getLogs()
}
func (c *Couchbase) LogClientError(msg string) error {
return c.logClientError(msg)
}
func (c *Couchbase) GetServerGroups() (*ServerGroups, error) {
return c.getServerGroups()
}
func (c *Couchbase) CreateServerGroup(name string) error {
return c.createServerGroup(name)
}
func (c *Couchbase) UpdateServerGroups(revision string, groups *ServerGroupsUpdate) error {
return c.updateServerGroups(revision, groups)
}
func (c *Couchbase) SetRecoveryType(hostname string, recoveryType RecoveryType) error {
cluster, err := c.getPoolsDefault()
if err != nil {
return err
}
for _, node := range cluster.Nodes {
if node.HostName == hostname {
return c.setRecoveryType(node.OTPNode, recoveryType)
}
}
return fmt.Errorf("Hostname %s is not part of the cluster", hostname)
}