-
Notifications
You must be signed in to change notification settings - Fork 23
/
hostspool_mgr.go
775 lines (689 loc) · 22.8 KB
/
hostspool_mgr.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
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
// Copyright 2018 Bull S.A.S. Atos Technologies - Bull, Rue Jean Jaures, B.P.68, 78340, Les Clayes-sous-Bois, France.
//
// 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 hostspool
import (
"context"
"fmt"
"path"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/hashicorp/consul/api"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
"github.com/ystia/yorc/helper/consulutil"
"github.com/ystia/yorc/helper/labelsutil"
"github.com/ystia/yorc/helper/sshutil"
)
const (
// CheckpointError is an error of checkpoint between the current Hosts Pool
// and an apply change request
CheckpointError = "Checkpoint for Hosts Pool error"
// maxWaitTimeSeconds is the max time to wait for a lock on write operations
maxWaitTimeSeconds = 120
// maxNbTransactionOps is the maximum number of operations within a transaction
// supported by Consul (limit hard-coded in Consul implementation)
maxNbTransactionOps = 64
)
// A Manager is in charge of creating/updating/deleting hosts from the pool
type Manager interface {
Add(hostname string, connection Connection, labels map[string]string) error
Apply(pool []Host, checkpoint *uint64) error
Remove(hostname string) error
UpdateResourcesLabels(hostname string, diff map[string]string, operation func(a int64, b int64) int64, update func(orig map[string]string, diff map[string]string, operation func(a int64, b int64) int64) (map[string]string, error)) error
AddLabels(hostname string, labels map[string]string) error
RemoveLabels(hostname string, labels []string) error
UpdateConnection(hostname string, connection Connection) error
List(filters ...labelsutil.Filter) ([]string, []labelsutil.Warning, uint64, error)
GetHost(hostname string) (Host, error)
Allocate(allocation *Allocation, filters ...labelsutil.Filter) (string, []labelsutil.Warning, error)
Release(hostname string, allocation *Allocation) error
}
// SSHClientFactory is a that could be called to customize the client used to check the connection.
//
// Currently this is used for testing purpose to mock the ssh connection.
type SSHClientFactory func(config *ssh.ClientConfig, conn Connection) sshutil.Client
// NewManager creates a Manager backed to Consul
func NewManager(cc *api.Client) Manager {
return NewManagerWithSSHFactory(cc, func(config *ssh.ClientConfig, conn Connection) sshutil.Client {
return &sshutil.SSHClient{
Config: config,
Host: conn.Host,
Port: int(conn.Port),
}
})
}
// NewManagerWithSSHFactory creates a Manager with a given ssh factory
//
// Currently this is used for testing purpose to mock the ssh connection.
func NewManagerWithSSHFactory(cc *api.Client, sshClientFactory SSHClientFactory) Manager {
return &consulManager{cc: cc, getSSHClient: sshClientFactory}
}
// Lock key is not under HostsPoolPrefix so that taking the lock and releasing
// without any change to the Hosts Pool will not update the last index of the
// Hosts Pool list
const kvLockKey = consulutil.YorcManagementPrefix + "/hosts_pool/lock"
type consulManager struct {
cc *api.Client
getSSHClient SSHClientFactory
}
func (cm *consulManager) Add(hostname string, conn Connection, labels map[string]string) error {
return cm.addWait(hostname, conn, labels, maxWaitTimeSeconds*time.Second)
}
func (cm *consulManager) addWait(hostname string, conn Connection, labels map[string]string, maxWaitTime time.Duration) error {
ops, err := cm.getAddOperations(hostname, conn, labels, HostStatusFree, "", nil)
if err != nil {
return err
}
_, cleanupFn, err := cm.lockKey(hostname, "creation", maxWaitTime)
if err != nil {
return err
}
defer cleanupFn()
ok, response, _, err := cm.cc.KV().Txn(ops, nil)
if err != nil {
return errors.Wrap(err, consulutil.ConsulGenericErrMsg)
}
if !ok {
// Check the response
errs := make([]string, 0)
for _, e := range response.Errors {
if e.OpIndex == 0 {
return errors.WithStack(hostAlreadyExistError{})
}
errs = append(errs, e.What)
}
return errors.Errorf("Failed to register host %q: %s", hostname, strings.Join(errs, ", "))
}
err = cm.checkConnection(hostname)
if err != nil {
cm.setHostStatusWithMessage(hostname, HostStatusError, "can't connect to host")
}
return err
}
func (cm *consulManager) getAddOperations(
hostname string,
conn Connection,
labels map[string]string,
status HostStatus,
message string,
allocations []Allocation) (api.KVTxnOps, error) {
if hostname == "" {
return nil, errors.WithStack(badRequestError{`"hostname" missing`})
}
if conn.Password == "" && conn.PrivateKey == "" {
return nil, errors.WithStack(badRequestError{`at least "password" or "private_key" is required for a host pool connection`})
}
user := conn.User
if user == "" {
user = "root"
}
port := conn.Port
if port == 0 {
port = 22
}
host := conn.Host
if host == "" {
host = hostname
}
hostKVPrefix := path.Join(consulutil.HostsPoolPrefix, hostname)
addOps := api.KVTxnOps{
&api.KVTxnOp{
Verb: api.KVCheckNotExists,
Key: path.Join(hostKVPrefix, "status"),
},
&api.KVTxnOp{
Verb: api.KVSet,
Key: path.Join(hostKVPrefix, "status"),
Value: []byte(status.String()),
},
&api.KVTxnOp{
Verb: api.KVSet,
Key: path.Join(hostKVPrefix, "connection", "host"),
Value: []byte(host),
},
&api.KVTxnOp{
Verb: api.KVSet,
Key: path.Join(hostKVPrefix, "connection", "user"),
Value: []byte(user),
},
&api.KVTxnOp{
Verb: api.KVSet,
Key: path.Join(hostKVPrefix, "connection", "password"),
Value: []byte(conn.Password),
},
&api.KVTxnOp{
Verb: api.KVSet,
Key: path.Join(hostKVPrefix, "connection", "private_key"),
Value: []byte(conn.PrivateKey),
},
&api.KVTxnOp{
Verb: api.KVSet,
Key: path.Join(hostKVPrefix, "connection", "port"),
Value: []byte(strconv.FormatUint(port, 10)),
},
}
if message != "" {
addOps = append(addOps, &api.KVTxnOp{
Verb: api.KVSet,
Key: path.Join(hostKVPrefix, "message"),
Value: []byte(message),
})
}
var allocsOps api.KVTxnOps
var err error
if allocsOps, err = getAddAllocationsOperation(hostname, allocations); err != nil {
return nil, err
} else if len(allocsOps) > 0 {
addOps = append(addOps, allocsOps...)
}
labelOps, err := cm.getAddUpdatedLabelsOperations(hostname, labels)
if err != nil {
return nil, err
}
addOps = append(addOps, labelOps...)
return addOps, nil
}
func (cm *consulManager) Remove(hostname string) error {
return cm.removeWait(hostname, maxWaitTimeSeconds*time.Second)
}
func (cm *consulManager) removeWait(hostname string, maxWaitTime time.Duration) error {
ops, err := cm.getRemoveOperations(hostname, true)
if err != nil {
return err
}
lockCh, cleanupFn, err := cm.lockKey(hostname, "deletion", maxWaitTime)
if err != nil {
return err
}
defer cleanupFn()
select {
case <-lockCh:
return errors.Errorf("admin lock lost on hosts pool for host %q deletion", hostname)
default:
}
ok, response, _, err := cm.cc.KV().Txn(ops, nil)
if err != nil {
return errors.Wrapf(err, "failed to delete host %q", hostname)
}
if !ok {
// Check the response
errs := make([]string, 0)
for _, e := range response.Errors {
errs = append(errs, e.What)
}
return errors.Errorf("Failed to delete host %q: %s", hostname, strings.Join(errs, ", "))
}
return nil
}
func (cm *consulManager) getRemoveOperations(hostname string, checkStatus bool) (api.KVTxnOps, error) {
if hostname == "" {
return nil, errors.WithStack(badRequestError{`"hostname" missing`})
}
hostKVPrefix := path.Join(consulutil.HostsPoolPrefix, hostname)
if checkStatus {
status, err := cm.GetHostStatus(hostname)
if err != nil {
return nil, err
}
switch status {
case HostStatusFree, HostStatusError:
// Ok go ahead
default:
return nil, errors.WithStack(badRequestError{fmt.Sprintf("can't delete host %q with status %q", hostname, status.String())})
}
}
rmOps := api.KVTxnOps{
&api.KVTxnOp{
Verb: api.KVDeleteTree,
Key: hostKVPrefix,
},
}
return rmOps, nil
}
func (cm *consulManager) lockKey(hostname, opType string, lockWaitTime time.Duration) (lockCh <-chan struct{}, cleanupFn func(), err error) {
var sessionName string
if hostname != "" {
sessionName = fmt.Sprintf("%q %s", hostname, opType)
} else {
sessionName = opType
}
lock, err := cm.cc.LockOpts(&api.LockOptions{
Key: kvLockKey,
Value: []byte(fmt.Sprintf("locked for %s", sessionName)),
MonitorRetries: 2,
LockWaitTime: lockWaitTime,
// Not setting LockTryOnce to true to workaround this Consul issue:
// https://github.com/hashicorp/consul/issues/4003
// LockTryOnce: true,
SessionName: sessionName,
SessionTTL: lockWaitTime.String(),
SessionOpts: &api.SessionEntry{
Behavior: api.SessionBehaviorDelete,
},
})
if err != nil {
err = errors.Wrap(err, consulutil.ConsulGenericErrMsg)
return
}
// To workaround Consul issue https://github.com/hashicorp/consul/issues/4003
// LockTryOnce is false (default value) which means lock.Lock() will be
// blocking.
// Now to avoid being blocked forever attempting to get the lock, arming a
// timer and closing a stopChannel if this timer expires to go out of the
// call to lock.Lock(stopChannel) below
stopChannel := make(chan struct{})
timerWaitLock := time.NewTimer(lockWaitTime)
go func() {
<-timerWaitLock.C
// Timer expired, closing stop channel to stop the blocking lock below
if lockCh == nil {
close(stopChannel)
}
}()
lockCh, err = lock.Lock(stopChannel)
timerWaitLock.Stop()
if err != nil {
err = errors.Wrapf(err, "failed to acquire admin lock on hosts pool for %s", sessionName)
return
}
if lockCh == nil {
err = errors.Errorf("failed to acquire admin lock on Hosts Pool for %s", sessionName)
return
}
select {
case <-lockCh:
err = errors.Errorf("admin lock lost on hosts pool for %s", sessionName)
return
default:
}
cleanupFn = func() {
lock.Unlock()
lock.Destroy()
}
return
}
func (cm *consulManager) List(filters ...labelsutil.Filter) ([]string, []labelsutil.Warning, uint64, error) {
hosts, metadata, err := cm.cc.KV().Keys(consulutil.HostsPoolPrefix+"/", "/", nil)
if err != nil {
return nil, nil, 0, errors.Wrap(err, consulutil.ConsulGenericErrMsg)
}
warnings := make([]labelsutil.Warning, 0)
results := hosts[:0]
for _, host := range hosts {
host = path.Base(host)
labels, err := cm.GetHostLabels(host)
if err != nil {
return nil, nil, 0, err
}
ok, warn := labelsutil.MatchesAll(labels, filters...)
if warn != nil {
warnings = append(warnings, errors.Wrapf(warn, "host: %q", host))
} else if ok {
results = append(results, host)
}
}
return results, warnings, metadata.LastIndex, nil
}
func (cm *consulManager) backupHostStatus(hostname string) error {
status, err := cm.GetHostStatus(hostname)
if err != nil {
return err
}
message, err := cm.GetHostMessage(hostname)
if err != nil {
return err
}
hostPath := path.Join(consulutil.HostsPoolPrefix, hostname)
_, errGrp, store := consulutil.WithContext(context.Background())
store.StoreConsulKeyAsString(path.Join(hostPath, ".statusBackup"), status.String())
store.StoreConsulKeyAsString(path.Join(hostPath, ".messageBackup"), message)
return errGrp.Wait()
}
func (cm *consulManager) restoreHostStatus(hostname string) error {
hostPath := path.Join(consulutil.HostsPoolPrefix, hostname)
kvp, _, err := cm.cc.KV().Get(path.Join(hostPath, ".statusBackup"), nil)
if err != nil {
return errors.Wrap(err, consulutil.ConsulGenericErrMsg)
}
if kvp == nil || len(kvp.Value) == 0 {
return errors.Errorf("missing backup status for host %q", hostname)
}
status, err := ParseHostStatus(string(kvp.Value))
if err != nil {
return errors.Wrapf(err, "invalid backup status for host %q", hostname)
}
err = cm.setHostStatus(hostname, status)
if err != nil {
return err
}
_, err = cm.cc.KV().Delete(path.Join(hostPath, ".statusBackup"), nil)
if err != nil {
return errors.Wrap(err, consulutil.ConsulGenericErrMsg)
}
kvp, _, err = cm.cc.KV().Get(path.Join(hostPath, ".messageBackup"), nil)
if err != nil {
return errors.Wrap(err, consulutil.ConsulGenericErrMsg)
}
var msg string
if kvp != nil {
msg = string(kvp.Value)
}
err = cm.setHostMessage(hostname, msg)
if err != nil {
return err
}
_, err = cm.cc.KV().Delete(path.Join(hostPath, ".messageBackup"), nil)
return errors.Wrap(err, consulutil.ConsulGenericErrMsg)
}
func (cm *consulManager) setHostStatus(hostname string, status HostStatus) error {
return cm.setHostStatusWithMessage(hostname, status, "")
}
func (cm *consulManager) setHostStatusWithMessage(hostname string, status HostStatus, message string) error {
_, err := cm.GetHostStatus(hostname)
if err != nil {
return err
}
err = consulutil.StoreConsulKeyAsString(path.Join(consulutil.HostsPoolPrefix, hostname, "status"), status.String())
if err != nil {
return err
}
return cm.setHostMessage(hostname, message)
}
func (cm *consulManager) GetHostStatus(hostname string) (HostStatus, error) {
return cm.getStatus(hostname, false)
}
func (cm *consulManager) getStatus(hostname string, backup bool) (HostStatus, error) {
if hostname == "" {
return HostStatus(0), errors.WithStack(badRequestError{`"hostname" missing`})
}
keyname := "status"
if backup {
keyname = ".statusBackup"
}
kvp, _, err := cm.cc.KV().Get(path.Join(consulutil.HostsPoolPrefix, hostname, keyname), nil)
if err != nil {
return HostStatus(0), errors.Wrap(err, consulutil.ConsulGenericErrMsg)
}
if kvp == nil || len(kvp.Value) == 0 {
return HostStatus(0), errors.WithStack(hostNotFoundError{})
}
status, err := ParseHostStatus(string(kvp.Value))
if err != nil {
return HostStatus(0), errors.Wrapf(err, "failed to retrieve %s for host %q", keyname, hostname)
}
return status, nil
}
func (cm *consulManager) GetHostMessage(hostname string) (string, error) {
return cm.getMessage(hostname, false)
}
func (cm *consulManager) getMessage(hostname string, backup bool) (string, error) {
if hostname == "" {
return "", errors.WithStack(badRequestError{`"hostname" missing`})
}
// check if host exists
_, err := cm.GetHostStatus(hostname)
if err != nil {
return "", err
}
keyname := "message"
if backup {
keyname = ".messageBackup"
}
kvp, _, err := cm.cc.KV().Get(path.Join(consulutil.HostsPoolPrefix, hostname, keyname), nil)
if err != nil {
return "", errors.Wrap(err, consulutil.ConsulGenericErrMsg)
}
if kvp == nil || len(kvp.Value) == 0 {
return "", nil
}
return string(kvp.Value), nil
}
func (cm *consulManager) setHostMessage(hostname, message string) error {
if hostname == "" {
return errors.WithStack(badRequestError{`"hostname" missing`})
}
// check if host exists
_, err := cm.GetHostStatus(hostname)
if err != nil {
return err
}
return consulutil.StoreConsulKeyAsString(path.Join(consulutil.HostsPoolPrefix, hostname, "message"), message)
}
func (cm *consulManager) GetHost(hostname string) (Host, error) {
host := Host{Name: hostname}
if hostname == "" {
return host, errors.WithStack(badRequestError{`"hostname" missing`})
}
var err error
host.Status, err = cm.GetHostStatus(hostname)
if err != nil {
return host, err
}
host.Message, err = cm.GetHostMessage(hostname)
if err != nil {
return host, err
}
host.Connection, err = cm.GetHostConnection(hostname)
if err != nil {
return host, err
}
host.Allocations, err = cm.GetAllocations(hostname)
if err != nil {
return host, err
}
host.Labels, err = cm.GetHostLabels(hostname)
return host, err
}
func getSSHConfig(conn Connection) (*ssh.ClientConfig, error) {
conf := &ssh.ClientConfig{
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
User: conn.User,
}
if conn.PrivateKey != "" {
keyAuth, err := sshutil.ReadPrivateKey(conn.PrivateKey)
if err != nil {
return nil, err
}
conf.Auth = append(conf.Auth, keyAuth)
}
if conn.Password != "" {
conf.Auth = append(conf.Auth, ssh.Password(conn.Password))
}
return conf, nil
}
// Apply a Hosts Pool configuration.
// If checkpoint is not nil, it should point to a value returned by a previous
// call to the List() function described above. A checkpoint verification will
// be done to ensure that the Hosts Pool was not changed between the call to
// List() and the current call to Apply(). Once the Hosts Pool configuration
// has been applied, checkpoint will point to the new Hosts Pool checkpoint
// value.
// If checkpoint is nil, the Hosts Pool configuration will be applied without
// checkpoint verification.
func (cm *consulManager) Apply(pool []Host, checkpoint *uint64) error {
return cm.applyWait(pool, checkpoint, maxWaitTimeSeconds*time.Second)
}
func (cm *consulManager) applyWait(
pool []Host,
checkpoint *uint64,
maxWaitTime time.Duration) error {
// First, checking the pool definition to verify there is no host with an
// empty name or a duplicate name, or wrong connection definition, and
// provide an error message referencing indexes in the definition to help
// the user identify which definition is erroneous
hostIndexDefinition := make(map[string]int)
for i, host := range pool {
if host.Name == "" {
return errors.WithStack(badRequestError{
fmt.Sprintf("A non-empty Name should be provided for Host number %d, defined with connection %q",
i+1, host.Connection)})
}
// Check if the name has already been used. It must me unique in the Hosts Pool
if index, ok := hostIndexDefinition[host.Name]; ok {
return errors.WithStack(badRequestError{
fmt.Sprintf("Name value %q must be unique but is re-used in host number %d when first used in host number %d",
host.Name, i+1, index+1)})
}
hostIndexDefinition[host.Name] = i
}
// Take the lock to have a consistent view while computing needed
// configuration changes
lockCh, cleanupFn, err := cm.lockKey("", "apply", maxWaitTime)
if err != nil {
return err
}
defer cleanupFn()
// Get all hosts currently registered to find which ones will have to be
// unregistered or updated.
// Attempting to unregister a host that is still allocated is illegal
registeredHosts, _, runtimeCheckpoint, err := cm.List()
if err != nil {
return errors.Wrapf(err, "Failed to get list of registered hosts")
}
// Verify checkpoint, no change done if the checkpoint in argument is
// lower than the current checkpoint, as it means that another Hosts Pool
// change happened since
if checkpoint != nil &&
((*checkpoint == 0 && len(registeredHosts) > 0) ||
(*checkpoint > 0 && *checkpoint < runtimeCheckpoint)) {
return errors.WithStack(badRequestError{
fmt.Sprintf("%s: value provided %d lower than expected checkpoint %d",
CheckpointError, *checkpoint, runtimeCheckpoint)})
}
hostsToUnregisterCheckAllocatedStatus := make(map[string]bool)
for _, registeredHost := range registeredHosts {
hostsToUnregisterCheckAllocatedStatus[registeredHost] = true
}
// Compare new hosts pool definition to the runtime to compute changes
var hostChanged []string
var addOps api.KVTxnOps
for _, host := range pool {
found := hostsToUnregisterCheckAllocatedStatus[host.Name]
if found {
// Host already in pool, check if an update is needed
oldHost, _ := cm.GetHost(host.Name)
if oldHost.Connection == host.Connection &&
reflect.DeepEqual(oldHost.Labels, host.Labels) {
// No config change, no update needed, ignoring this host
delete(hostsToUnregisterCheckAllocatedStatus, host.Name)
continue
}
// A config change is request for this already known host.
hostChanged = append(hostChanged, host.Name)
// This host will be unregistered then registered again.
// No need to check the status of this host at unregistration time,
// it will be recreated with the same status
hostsToUnregisterCheckAllocatedStatus[host.Name] = false
status, err := cm.GetHostStatus(host.Name)
if err != nil {
return err
}
message, err := cm.GetHostMessage(host.Name)
if err != nil {
return err
}
allocations, err := cm.GetAllocations(host.Name)
if err != nil {
return err
}
// Backup status and message if defined are restored at re-creation,
// the connection check will be performed afterwards
if status == HostStatusError {
backupStatus, err := cm.getStatus(host.Name, true)
if err == nil {
status = backupStatus
message, _ = cm.getMessage(host.Name, true)
}
}
ops, err := cm.getAddOperations(host.Name, host.Connection, host.Labels,
status, message, allocations)
if err != nil {
return err
}
addOps = append(addOps, ops...)
} else {
// Host is new, creating it
hostChanged = append(hostChanged, host.Name)
ops, err := cm.getAddOperations(host.Name, host.Connection, host.Labels,
HostStatusFree, "", nil)
if err != nil {
return err
}
addOps = append(addOps, ops...)
}
}
// Now manage hosts to delete
var ops api.KVTxnOps
for host, checkStatus := range hostsToUnregisterCheckAllocatedStatus {
removeOps, err := cm.getRemoveOperations(host, checkStatus)
if err != nil {
return err
}
ops = append(ops, removeOps...)
}
ops = append(ops, addOps...)
// Execute operations in a transaction
select {
case <-lockCh:
return errors.Errorf("admin lock lost on hosts pool for apply operation")
default:
}
// Need to split the transaction if there are more than the max number of
// operations in a transaction supported by Consul
opsLength := len(ops)
for begin := 0; begin < opsLength; begin += maxNbTransactionOps {
end := begin + maxNbTransactionOps
if end > opsLength {
end = opsLength
}
ok, response, _, err := cm.cc.KV().Txn(ops[begin:end], nil)
if err != nil {
return errors.Wrap(err, "Failed to apply new Hosts Pool configuration")
}
if !ok {
// Check the response
var errs []string
for _, e := range response.Errors {
errs = append(errs, e.What)
}
err = errors.Errorf("Failed to apply new Hosts Pool configuration: %s", strings.Join(errs, ", "))
}
}
// Update the connection status for each updated/created host
var waitGroup sync.WaitGroup
for _, name := range hostChanged {
waitGroup.Add(1)
go cm.updateConnectionStatus(name, &waitGroup)
}
waitGroup.Wait()
// Updating the checkpoint value
// Not using querymeta.LastIndex from KV().Txn() as it doesn't work the same
// way as in KV().Keys used in cm.List().
if checkpoint != nil {
_, _, newCheckpoint, errCkpt := cm.List()
if errCkpt != nil {
// If the apply didn't fail, return this error, else the apply error
// takes precedence
if err == nil {
err = errors.Wrapf(errCkpt, "Failed to get list of registered hosts")
}
} else {
*checkpoint = newCheckpoint
}
}
return err
}