forked from docker-archive/classicswarm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathengine.go
1537 lines (1336 loc) · 43 KB
/
engine.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
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cluster
import (
"bufio"
"crypto/tls"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"math/rand"
"net"
"net/http"
"net/url"
"strings"
"sync"
"time"
"golang.org/x/net/context"
log "github.com/Sirupsen/logrus"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/events"
"github.com/docker/docker/api/types/filters"
networktypes "github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/versions"
"github.com/docker/docker/api/types/volume"
engineapi "github.com/docker/docker/client"
engineapinop "github.com/docker/swarm/api/nopclient"
"github.com/docker/swarm/swarmclient"
"github.com/samalba/dockerclient"
"github.com/samalba/dockerclient/nopclient"
)
const (
// Timeout for requests sent out to the engine.
requestTimeout = 10 * time.Second
// Threshold of delta duration between swarm manager and engine's systime
thresholdTime = 2 * time.Second
// Minimum docker engine version supported by swarm.
minSupportedVersion = "1.8.0"
)
type engineState int
const (
// pending means an engine added to cluster has not been validated
statePending engineState = iota
// unhealthy means an engine is unreachable
stateUnhealthy
// healthy means an engine is reachable
stateHealthy
// disconnected means engine is removed from discovery
stateDisconnected
// TODO: add maintenance state. Proposal #1486
// maintenance means an engine is under maintenance.
// There is no action to migrate a node into maintenance state yet.
//stateMaintenance
)
var stateText = map[engineState]string{
statePending: "Pending",
stateUnhealthy: "Unhealthy",
stateHealthy: "Healthy",
stateDisconnected: "Disconnected",
//stateMaintenance: "Maintenance",
}
// delayer offers a simple API to random delay within a given time range.
type delayer struct {
rangeMin time.Duration
rangeMax time.Duration
r *rand.Rand
l sync.Mutex
}
func newDelayer(rangeMin, rangeMax time.Duration) *delayer {
return &delayer{
rangeMin: rangeMin,
rangeMax: rangeMax,
r: rand.New(rand.NewSource(time.Now().UTC().UnixNano())),
}
}
// Wait returns timeout event after fixed + randomized time duration
func (d *delayer) Wait(backoffFactor int) <-chan time.Time {
d.l.Lock()
defer d.l.Unlock()
waitPeriod := int64(d.rangeMin) * int64(1+backoffFactor)
if delta := int64(d.rangeMax) - int64(d.rangeMin); delta > 0 {
// Int63n panics if the parameter is 0
waitPeriod += d.r.Int63n(delta)
}
return time.After(time.Duration(waitPeriod))
}
// EngineOpts represents the options for an engine
type EngineOpts struct {
RefreshMinInterval time.Duration
RefreshMaxInterval time.Duration
FailureRetry int
}
// Engine represents a docker engine
type Engine struct {
sync.RWMutex
ID string
IP string
Addr string
Name string
Cpus int64
Memory int64
Labels map[string]string
Version string
stopCh chan struct{}
refreshDelayer *delayer
containers map[string]*Container
images []*Image
networks map[string]*Network
volumes map[string]*Volume
httpClient *http.Client
url *url.URL
client dockerclient.Client
apiClient swarmclient.SwarmAPIClient
eventHandler EventHandler
state engineState
lastError string
updatedAt time.Time
failureCount int
overcommitRatio int64
opts *EngineOpts
eventsMonitor *EventsMonitor
DeltaDuration time.Duration // swarm's systime - engine's systime
}
// NewEngine is exported
func NewEngine(addr string, overcommitRatio float64, opts *EngineOpts) *Engine {
e := &Engine{
Addr: addr,
client: nopclient.NewNopClient(),
apiClient: engineapinop.NewNopClient(),
refreshDelayer: newDelayer(opts.RefreshMinInterval, opts.RefreshMaxInterval),
Labels: make(map[string]string),
stopCh: make(chan struct{}),
containers: make(map[string]*Container),
networks: make(map[string]*Network),
volumes: make(map[string]*Volume),
state: statePending,
updatedAt: time.Now(),
overcommitRatio: int64(overcommitRatio * 100),
opts: opts,
}
return e
}
// HTTPClientAndScheme returns the underlying HTTPClient and the scheme used by the engine
func (e *Engine) HTTPClientAndScheme() (*http.Client, string, error) {
// TODO(nishanttotla): return the proper client after checking connection
if _, ok := e.apiClient.(*engineapi.Client); ok {
return e.httpClient, e.url.Scheme, nil
}
return nil, "", fmt.Errorf("Possibly lost connection to Engine (name: %s, ID: %s) ", e.Name, e.ID)
}
// Connect will initialize a connection to the Docker daemon running on the
// host, gather machine specs (memory, cpu, ...) and monitor state changes.
func (e *Engine) Connect(config *tls.Config) error {
host, _, err := net.SplitHostPort(e.Addr)
if err != nil {
return err
}
addr, err := net.ResolveIPAddr("ip", host)
if err != nil {
return err
}
e.IP = addr.IP.String()
// create the HTTP Client and URL
httpClient, url, err := NewHTTPClientTimeout("tcp://"+e.Addr, config, time.Duration(requestTimeout), nil)
if err != nil {
return err
}
e.httpClient = httpClient
e.url = url
// Use HTTP Client created above to create a dockerclient client
c, err := dockerclient.NewDockerClient(url.String(), config)
if err != nil {
return err
}
// Use HTTP Client used by dockerclient to create docker/api client
apiClient, err := engineapi.NewClient("tcp://"+e.Addr, "", c.HTTPClient, nil)
if err != nil {
return err
}
return e.ConnectWithClient(c, apiClient)
}
// StartMonitorEvents monitors events from the engine
func (e *Engine) StartMonitorEvents() {
log.WithFields(log.Fields{"name": e.Name, "id": e.ID}).Debug("Start monitoring events")
ec := make(chan error)
go func() {
if err := <-ec; err != nil {
log.WithFields(log.Fields{"name": e.Name, "id": e.ID}).WithError(err).Error("error monitoring events, will restart")
// failing node reconnect should use back-off strategy to avoid frequent reconnect
retryInterval := e.getFailureCount() + 1
// maximum retry interval of 10 seconds
if retryInterval > 10 {
retryInterval = 10
}
<-time.After(time.Duration(retryInterval) * time.Second)
e.StartMonitorEvents()
}
close(ec)
}()
e.eventsMonitor.Start(ec)
}
// ConnectWithClient is exported
func (e *Engine) ConnectWithClient(client dockerclient.Client, apiClient swarmclient.SwarmAPIClient) error {
e.client = client
e.apiClient = apiClient
e.eventsMonitor = NewEventsMonitor(e.apiClient, e.handler)
// Fetch the engine labels.
if err := e.updateSpecs(); err != nil {
return err
}
e.StartMonitorEvents()
// Force a state update before returning.
if err := e.RefreshContainers(true); err != nil {
return err
}
if err := e.RefreshImages(); err != nil {
return err
}
// Do not check error as older daemon doesn't support this call.
e.RefreshVolumes()
e.RefreshNetworks()
e.emitEvent("engine_connect")
return nil
}
// Disconnect will stop all monitoring of the engine.
// The Engine object cannot be further used without reconnecting it first.
func (e *Engine) Disconnect() {
e.Lock()
defer e.Unlock()
// Resource clean up should be done only once
if e.state == stateDisconnected {
return
}
// close the chan
close(e.stopCh)
e.eventsMonitor.Stop()
// close idle connections
if dc, ok := e.client.(*dockerclient.DockerClient); ok {
closeIdleConnections(dc.HTTPClient)
}
e.client = nopclient.NewNopClient()
e.apiClient = engineapinop.NewNopClient()
e.state = stateDisconnected
e.emitEvent("engine_disconnect")
}
func closeIdleConnections(client *http.Client) {
if tr, ok := client.Transport.(*http.Transport); ok {
tr.CloseIdleConnections()
}
}
// isConnected returns true if the engine is connected to a remote docker API
// note that it's not the same as stateDisconnected. Engine isConnected is also true
// when it is first created but not yet 'Connect' to a remote docker API.
func (e *Engine) isConnected() bool {
_, ok := e.client.(*nopclient.NopClient)
_, okAPIClient := e.apiClient.(*engineapinop.NopClient)
return (!ok && !okAPIClient)
}
// IsHealthy returns true if the engine is healthy
func (e *Engine) IsHealthy() bool {
e.RLock()
defer e.RUnlock()
return e.state == stateHealthy
}
// HealthIndicator returns degree of healthiness between 0 and 100.
// 0 means node is not healthy (unhealthy, pending), 100 means last connectivity was successful
// other values indicate recent failures but haven't moved engine out of healthy state
func (e *Engine) HealthIndicator() int64 {
e.RLock()
defer e.RUnlock()
if e.state != stateHealthy || e.failureCount >= e.opts.FailureRetry {
return 0
}
return int64(100 - e.failureCount*100/e.opts.FailureRetry)
}
// setState sets engine state
func (e *Engine) setState(state engineState) {
e.Lock()
defer e.Unlock()
e.state = state
}
// TimeToValidate returns true if a pending node is up for validation
func (e *Engine) TimeToValidate() bool {
const validationLimit time.Duration = 4 * time.Hour
const minFailureBackoff time.Duration = 30 * time.Second
e.Lock()
defer e.Unlock()
if e.state != statePending {
return false
}
sinceLastUpdate := time.Since(e.updatedAt)
// Increase check interval for a pending engine according to failureCount and cap it at a limit
// it's exponential backoff = 2 ^ failureCount + minFailureBackoff. A minimum backoff is
// needed because e.failureCount could be 0 at first join, or the engine has a duplicate ID
if sinceLastUpdate > validationLimit ||
sinceLastUpdate > (1<<uint(e.failureCount))*time.Second+minFailureBackoff {
return true
}
return false
}
// ValidationComplete transitions engine state from statePending to stateHealthy
func (e *Engine) ValidationComplete() {
e.Lock()
defer e.Unlock()
if e.state != statePending {
return
}
e.state = stateHealthy
e.failureCount = 0
go e.refreshLoop()
}
// setErrMsg sets error message for the engine
func (e *Engine) setErrMsg(errMsg string) {
e.Lock()
defer e.Unlock()
e.lastError = strings.TrimSpace(errMsg)
e.updatedAt = time.Now()
}
// ErrMsg returns error message for the engine
func (e *Engine) ErrMsg() string {
e.RLock()
defer e.RUnlock()
return e.lastError
}
// HandleIDConflict handles ID duplicate with existing engine
func (e *Engine) HandleIDConflict(otherAddr string) {
e.setErrMsg(fmt.Sprintf("ID duplicated. %s shared by this node %s and another node %s", e.ID, e.Addr, otherAddr))
}
// Status returns the health status of the Engine: Healthy or Unhealthy
func (e *Engine) Status() string {
e.RLock()
defer e.RUnlock()
return stateText[e.state]
}
// incFailureCount increases engine's failure count, and sets engine as unhealthy if threshold is crossed
func (e *Engine) incFailureCount() {
e.Lock()
defer e.Unlock()
e.failureCount++
if e.state == stateHealthy && e.failureCount >= e.opts.FailureRetry {
e.state = stateUnhealthy
log.WithFields(log.Fields{"name": e.Name, "id": e.ID}).Errorf("Flagging engine as unhealthy. Connect failed %d times", e.failureCount)
e.emitEvent("engine_disconnect")
}
}
// getFailureCount returns a copy on the getFailureCount, thread-safe
func (e *Engine) getFailureCount() int {
e.RLock()
defer e.RUnlock()
return e.failureCount
}
// UpdatedAt returns the previous updatedAt time
func (e *Engine) UpdatedAt() time.Time {
e.RLock()
defer e.RUnlock()
return e.updatedAt
}
func (e *Engine) resetFailureCount() {
e.Lock()
defer e.Unlock()
e.failureCount = 0
}
// CheckConnectionErr checks error from client response and adjusts engine healthy indicators
func (e *Engine) CheckConnectionErr(err error) {
if err == nil {
e.setErrMsg("")
// If current state is unhealthy, change it to healthy
if e.state == stateUnhealthy {
log.WithFields(log.Fields{"name": e.Name, "id": e.ID}).Infof("Engine came back to life after %d retries. Hooray!", e.getFailureCount())
e.emitEvent("engine_reconnect")
e.setState(stateHealthy)
}
e.resetFailureCount()
return
}
if IsConnectionError(err) {
// each connection refused instance may increase failure count so
// engine can fail fast. Short engine freeze or network failure may result
// in engine marked as unhealthy. If this causes unnecessary failure, engine
// can track last error time. Only increase failure count if last error is
// not too recent, e.g., last error is at least 1 seconds ago.
e.incFailureCount()
// update engine error message
e.setErrMsg(err.Error())
return
}
// other errors may be ambiguous.
}
// EngineToContainerNode constructs types.ContainerNode from engine
func (e *Engine) EngineToContainerNode() *types.ContainerNode {
return &types.ContainerNode{
ID: e.ID,
IPAddress: e.IP,
Addr: e.Addr,
Name: e.Name,
Cpus: int(e.Cpus),
Memory: int64(e.Memory),
Labels: e.Labels,
}
}
// Update API Version in apiClient
func (e *Engine) updateClientVersionFromServer(serverVersion string) {
// v will be >= 1.8, since this is checked earlier
switch {
case versions.LessThan(serverVersion, "1.9"):
e.apiClient.UpdateClientVersion("1.20")
case versions.LessThan(serverVersion, "1.10"):
e.apiClient.UpdateClientVersion("1.21")
case versions.LessThan(serverVersion, "1.11"):
e.apiClient.UpdateClientVersion("1.22")
case versions.LessThan(serverVersion, "1.12"):
e.apiClient.UpdateClientVersion("1.23")
case versions.LessThan(serverVersion, "1.13"):
e.apiClient.UpdateClientVersion("1.24")
default:
e.apiClient.UpdateClientVersion("1.25")
}
}
// Gather engine specs (CPU, memory, constraints, ...).
func (e *Engine) updateSpecs() error {
info, err := e.apiClient.Info(context.Background())
e.CheckConnectionErr(err)
if err != nil {
return err
}
if info.NCPU == 0 || info.MemTotal == 0 {
return fmt.Errorf("cannot get resources for this engine, make sure %s is a Docker Engine, not a Swarm manager", e.Addr)
}
v, err := e.apiClient.ServerVersion(context.Background())
e.CheckConnectionErr(err)
if err != nil {
return err
}
// Older versions of Docker don't expose the ID field, Labels and are not supported
// by Swarm. Catch the error ASAP and refuse to connect.
if versions.LessThan(v.Version, minSupportedVersion) {
err = fmt.Errorf("engine %s is running an unsupported version of Docker Engine. Please upgrade to at least %s", e.Addr, minSupportedVersion)
return err
}
// update server version
e.Version = v.Version
// update client version. docker/api handles backward compatibility where needed
e.updateClientVersionFromServer(v.Version)
e.Lock()
defer e.Unlock()
// Swarm/docker identifies engine by ID. Updating ID but not updating cluster
// index will put the cluster into inconsistent state. If this happens, the
// engine should be put to pending state for re-validation.
// We concatenate the engine ID and the address because sometimes engine
// IDs can be duplicated on different nodes (e.g. if a user has
// accidentally copied their /etc/docker/daemon.json file onto another
// node).
infoID := info.ID + "|" + e.Addr
if e.ID == "" {
e.ID = infoID
} else if e.ID != infoID {
e.state = statePending
message := fmt.Sprintf("Engine (ID: %s, Addr: %s) shows up with another ID:%s. Please remove it from cluster, it can be added back.", e.ID, e.Addr, infoID)
e.lastError = message
return errors.New(message)
}
// delta is an estimation of time difference between manager and engine
// with adjustment of delays (Engine response delay + network delay + manager process delay).
var delta time.Duration
if info.SystemTime != "" {
engineTime, _ := time.Parse(time.RFC3339Nano, info.SystemTime)
delta = time.Now().UTC().Sub(engineTime)
} else {
// if no SystemTime in info response, we treat delta as 0.
delta = time.Duration(0)
}
// If the servers are sync up on time, this delta might be the source of error
// we set a threshold that to ignore this case.
absDelta := delta
if delta.Seconds() < 0 {
absDelta = time.Duration(-1*delta.Seconds()) * time.Second
}
if absDelta < thresholdTime {
e.DeltaDuration = 0
} else {
log.Warnf("Engine (ID: %s, Addr: %s) has unsynchronized systime with swarm, please synchronize it.", e.ID, e.Addr)
e.DeltaDuration = delta
}
e.Name = info.Name
e.Cpus = int64(info.NCPU)
e.Memory = info.MemTotal
e.Labels = map[string]string{}
if info.Driver != "" {
e.Labels["storagedriver"] = info.Driver
}
if info.KernelVersion != "" {
e.Labels["kernelversion"] = info.KernelVersion
}
if info.OperatingSystem != "" {
e.Labels["operatingsystem"] = info.OperatingSystem
}
if info.OSType != "" {
e.Labels["ostype"] = info.OSType
}
for _, label := range info.Labels {
kv := strings.SplitN(label, "=", 2)
if len(kv) != 2 {
message := fmt.Sprintf("Engine (ID: %s, Addr: %s) contains an invalid label (%s) not formatted as \"key=value\".", e.ID, e.Addr, label)
return errors.New(message)
}
// If an engine managed by Swarm contains a label with key "node",
// such as node=node1
// `docker run -e constraint:node==node1 -d nginx` will not work,
// since "node" in constraint will match node.Name instead of label.
// Log warn message in this case.
if kv[0] == "node" {
log.Warnf("Engine (ID: %s, Addr: %s) contains a label (%s) with key of \"node\" which cannot be used in Swarm.", e.ID, e.Addr, label)
continue
}
if value, exist := e.Labels[kv[0]]; exist {
log.Warnf("Node (ID: %s, Addr: %s) already contains a label (%s) with key (%s), and Engine's label (%s) cannot override it.", e.ID, e.Addr, value, kv[0], kv[1])
} else {
e.Labels[kv[0]] = kv[1]
}
}
return nil
}
// RemoveImage deletes an image from the engine.
func (e *Engine) RemoveImage(name string, force bool) ([]types.ImageDelete, error) {
rmOpts := types.ImageRemoveOptions{
Force: force,
PruneChildren: true,
}
dels, err := e.apiClient.ImageRemove(context.Background(), name, rmOpts)
e.CheckConnectionErr(err)
// ImageRemove is not atomic. Engine may have deleted some layers and still failed.
// Swarm should still refresh images before returning an error
e.RefreshImages()
return dels, err
}
// RemoveNetwork removes a network from the engine.
func (e *Engine) RemoveNetwork(network *Network) error {
err := e.apiClient.NetworkRemove(context.Background(), network.ID)
e.CheckConnectionErr(err)
if err != nil {
return err
}
// Remove the container from the state. Eventually, the state refresh loop
// will rewrite this.
e.DeleteNetwork(network)
return nil
}
// DeleteNetwork deletes a network from the internal engine state.
func (e *Engine) DeleteNetwork(network *Network) {
e.Lock()
delete(e.networks, network.ID)
e.Unlock()
}
// AddNetwork adds a network to the internal engine state.
func (e *Engine) AddNetwork(network *Network) {
e.Lock()
e.networks[network.ID] = &Network{
NetworkResource: network.NetworkResource,
Engine: e,
}
e.Unlock()
}
// RemoveVolume deletes a volume from the engine.
func (e *Engine) RemoveVolume(name string) error {
err := e.apiClient.VolumeRemove(context.Background(), name, false)
e.CheckConnectionErr(err)
if err != nil {
return err
}
// Remove the container from the state. Eventually, the state refresh loop
// will rewrite this.
e.Lock()
defer e.Unlock()
delete(e.volumes, name)
return nil
}
// RefreshImages refreshes the list of images on the engine.
func (e *Engine) RefreshImages() error {
imgLstOpts := types.ImageListOptions{All: true}
images, err := e.apiClient.ImageList(context.Background(), imgLstOpts)
e.CheckConnectionErr(err)
if err != nil {
return err
}
e.Lock()
e.images = nil
for _, image := range images {
e.images = append(e.images, &Image{ImageSummary: image, Engine: e})
}
e.Unlock()
return nil
}
// refreshNetwork refreshes single network on the engine.
func (e *Engine) refreshNetwork(ID string) error {
network, err := e.apiClient.NetworkInspect(context.Background(), ID)
e.CheckConnectionErr(err)
if err != nil {
if strings.Contains(err.Error(), "No such network") {
e.Lock()
delete(e.networks, ID)
e.Unlock()
return nil
}
return err
}
e.Lock()
e.networks[ID] = &Network{NetworkResource: network, Engine: e}
e.Unlock()
return nil
}
// RefreshNetworks refreshes the list of networks on the engine.
func (e *Engine) RefreshNetworks() error {
netLsOpts := types.NetworkListOptions{Filters: filters.NewArgs()}
networks, err := e.apiClient.NetworkList(context.Background(), netLsOpts)
e.CheckConnectionErr(err)
if err != nil {
return err
}
e.Lock()
e.networks = make(map[string]*Network)
for _, network := range networks {
e.networks[network.ID] = &Network{NetworkResource: network, Engine: e}
}
e.Unlock()
return nil
}
// RefreshVolumes refreshes the list of volumes on the engine.
func (e *Engine) RefreshVolumes() error {
volumesLsRsp, err := e.apiClient.VolumeList(context.Background(), filters.NewArgs())
e.CheckConnectionErr(err)
if err != nil {
return err
}
e.Lock()
e.volumes = make(map[string]*Volume)
for _, volume := range volumesLsRsp.Volumes {
e.volumes[volume.Name] = &Volume{Volume: *volume, Engine: e}
}
e.Unlock()
return nil
}
// refreshVolume refreshes single volume on the engine.
func (e *Engine) refreshVolume(IDOrName string) error {
volume, err := e.apiClient.VolumeInspect(context.Background(), IDOrName)
e.CheckConnectionErr(err)
if err != nil {
if strings.Contains(err.Error(), "No such volume") {
e.Lock()
delete(e.volumes, IDOrName)
e.Unlock()
return nil
}
return err
}
e.Lock()
e.volumes[volume.Name] = &Volume{Volume: volume, Engine: e}
e.Unlock()
return nil
}
// RefreshContainers will refresh the list and status of containers running on the engine. If `full` is
// true, each container will be inspected.
// FIXME: unexport this method after mesos scheduler stops using it directly
func (e *Engine) RefreshContainers(full bool) error {
opts := types.ContainerListOptions{
All: true,
Size: false,
}
containers, err := e.apiClient.ContainerList(context.Background(), opts)
e.CheckConnectionErr(err)
if err != nil {
return err
}
merged := make(map[string]*Container)
for _, c := range containers {
mergedUpdate, err := e.updateContainer(c, merged, full)
if err != nil {
log.WithFields(log.Fields{"name": e.Name, "id": e.ID}).Errorf("Unable to update state of container %q: %v", c.ID, err)
} else {
merged = mergedUpdate
}
}
e.Lock()
defer e.Unlock()
e.containers = merged
return nil
}
// Refresh the status of a container running on the engine. If `full` is true,
// the container will be inspected.
func (e *Engine) refreshContainer(ID string, full bool) (*Container, error) {
filterArgs := filters.NewArgs()
filterArgs.Add("id", ID)
opts := types.ContainerListOptions{
All: true,
Size: false,
Filters: filterArgs,
}
containers, err := e.apiClient.ContainerList(context.Background(), opts)
e.CheckConnectionErr(err)
if err != nil {
return nil, err
}
if len(containers) > 1 {
// We expect one container, if we get more than one, trigger a full refresh.
err = e.RefreshContainers(full)
return nil, err
}
if len(containers) == 0 {
// The container doesn't exist on the engine, remove it.
e.Lock()
delete(e.containers, ID)
e.Unlock()
return nil, nil
}
_, err = e.updateContainer(containers[0], e.containers, full)
e.RLock()
container := e.containers[containers[0].ID]
e.RUnlock()
return container, err
}
func (e *Engine) updateContainer(c types.Container, containers map[string]*Container, full bool) (map[string]*Container, error) {
var container *Container
e.RLock()
if current, exists := e.containers[c.ID]; exists {
// The container is already known.
container = current
// Restarting is a transit state. Unfortunately Docker doesn't always emit
// events when it gets out of Restarting state. Force an inspect to update.
if container.Info.State != nil && container.Info.State.Restarting {
full = true
}
} else {
// This is a brand new container. We need to do a full refresh.
container = &Container{
Engine: e,
}
full = true
}
// Release the lock here as the next step is slow.
// Trade-off: If updateContainer() is called concurrently for the same
// container, we will end up doing a full refresh twice and the original
// container (containers[container.Id]) will get replaced.
e.RUnlock()
c.Created = time.Unix(c.Created, 0).Add(e.DeltaDuration).Unix()
// Update ContainerInfo.
if full {
info, err := e.apiClient.ContainerInspect(context.Background(), c.ID)
e.CheckConnectionErr(err)
if err != nil {
return nil, err
}
// Convert the ContainerConfig from inspect into our own
// cluster.ContainerConfig.
// info.HostConfig.CPUShares = info.HostConfig.CPUShares * int64(e.Cpus) / 1024.0
networkingConfig := networktypes.NetworkingConfig{
EndpointsConfig: info.NetworkSettings.Networks,
}
container.Config = BuildContainerConfig(*info.Config, *info.HostConfig, networkingConfig)
// FIXME remove "duplicate" line and move this to cluster/config.go
container.Config.HostConfig.CPUShares = container.Config.HostConfig.CPUShares * e.Cpus / 1024.0
// consider the delta duration between swarm and docker engine
startedAt, _ := time.Parse(time.RFC3339Nano, info.State.StartedAt)
finishedAt, _ := time.Parse(time.RFC3339Nano, info.State.FinishedAt)
info.State.StartedAt = startedAt.Add(e.DeltaDuration).Format(time.RFC3339Nano)
info.State.FinishedAt = finishedAt.Add(e.DeltaDuration).Format(time.RFC3339Nano)
// Save the entire inspect back into the container.
container.Info = info
}
// Update its internal state.
e.Lock()
container.Container = c
containers[container.ID] = container
e.Unlock()
return containers, nil
}
// refreshLoop periodically triggers engine refresh.
func (e *Engine) refreshLoop() {
const maxBackoffFactor int = 1000
// engine can hot-plug CPU/Mem or update labels. but there is no events
// from engine to trigger spec update.
// add an update interval and refresh spec for healthy nodes.
const specUpdateInterval = 5 * time.Minute
lastSpecUpdatedAt := time.Now()
for {
var err error
// Engines keep failing should backoff
// e.failureCount and e.opts.FailureRetry are type of int
backoffFactor := e.getFailureCount() - e.opts.FailureRetry
if backoffFactor < 0 {
backoffFactor = 0
} else if backoffFactor > maxBackoffFactor {
backoffFactor = maxBackoffFactor
}
// Wait for the delayer or quit if we get stopped.
select {
case <-e.refreshDelayer.Wait(backoffFactor):
case <-e.stopCh:
return
}
healthy := e.IsHealthy()
if !healthy || time.Since(lastSpecUpdatedAt) > specUpdateInterval {
if err = e.updateSpecs(); err != nil {
log.WithFields(log.Fields{"name": e.Name, "id": e.ID}).Errorf("Update engine specs failed: %v", err)
continue
}
lastSpecUpdatedAt = time.Now()
}
err = e.RefreshContainers(false)
if err == nil {
// Do not check error as older daemon doesn't support this call
e.RefreshVolumes()
e.RefreshNetworks()
e.RefreshImages()
log.WithFields(log.Fields{"id": e.ID, "name": e.Name}).Debugf("Engine update succeeded")
} else {
log.WithFields(log.Fields{"id": e.ID, "name": e.Name}).Debugf("Engine refresh failed")
}
}
}
func (e *Engine) emitEvent(event string) {
// If there is no event handler registered, abort right now.
if e.eventHandler == nil {
return
}
ev := &Event{
Message: events.Message{
Status: event,
From: "swarm",
Type: "swarm",
Action: event,
Actor: events.Actor{
Attributes: make(map[string]string),
},
Time: time.Now().Unix(),
TimeNano: time.Now().UnixNano(),
},
Engine: e,
}
e.eventHandler.Handle(ev)
}
// UsedMemory returns the sum of memory reserved by containers.
func (e *Engine) UsedMemory() int64 {
var r int64
e.RLock()
for _, c := range e.containers {
r += c.Config.HostConfig.Memory
}
e.RUnlock()
return r
}
// UsedCpus returns the sum of CPUs reserved by containers.
func (e *Engine) UsedCpus() int64 {
var r int64
e.RLock()
for _, c := range e.containers {
r += c.Config.HostConfig.CPUShares
}
e.RUnlock()
return r
}
// TotalMemory returns the total memory + overcommit
func (e *Engine) TotalMemory() int64 {
return e.Memory + (e.Memory * e.overcommitRatio / 100)
}
// TotalCpus returns the total cpus + overcommit
func (e *Engine) TotalCpus() int64 {
return e.Cpus + (e.Cpus * e.overcommitRatio / 100)
}
// CreateContainer creates a new container
func (e *Engine) CreateContainer(config *ContainerConfig, name string, pullImage bool, authConfig *types.AuthConfig) (*Container, error) {
var (
err error
createResp container.ContainerCreateCreatedBody
)
// Convert our internal ContainerConfig into something Docker will
// understand. Start by making a copy of the internal ContainerConfig as
// we don't want to mess with the original.
dockerConfig := *config