-
Notifications
You must be signed in to change notification settings - Fork 881
/
controller.go
1397 lines (1197 loc) · 36.7 KB
/
controller.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 libnetwork provides the basic functionality and extension points to
create network namespaces and allocate interfaces for containers to use.
networkType := "bridge"
// Create a new controller instance
driverOptions := options.Generic{}
genericOption := make(map[string]interface{})
genericOption[netlabel.GenericData] = driverOptions
controller, err := libnetwork.New(config.OptionDriverConfig(networkType, genericOption))
if err != nil {
return
}
// Create a network for containers to join.
// NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can make use of
network, err := controller.NewNetwork(networkType, "network1", "")
if err != nil {
return
}
// For each new container: allocate IP and interfaces. The returned network
// settings will be used for container infos (inspect and such), as well as
// iptables rules for port publishing. This info is contained or accessible
// from the returned endpoint.
ep, err := network.CreateEndpoint("Endpoint1")
if err != nil {
return
}
// Create the sandbox for the container.
// NewSandbox accepts Variadic optional arguments which libnetwork can use.
sbx, err := controller.NewSandbox("container1",
libnetwork.OptionHostname("test"),
libnetwork.OptionDomainname("docker.io"))
// A sandbox can join the endpoint via the join api.
err = ep.Join(sbx)
if err != nil {
return
}
*/
package libnetwork
import (
"fmt"
"net"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"github.com/docker/docker/pkg/discovery"
"github.com/docker/docker/pkg/plugingetter"
"github.com/docker/docker/pkg/plugins"
"github.com/docker/docker/pkg/stringid"
"github.com/docker/libnetwork/cluster"
"github.com/docker/libnetwork/config"
"github.com/docker/libnetwork/datastore"
"github.com/docker/libnetwork/diagnostic"
"github.com/docker/libnetwork/discoverapi"
"github.com/docker/libnetwork/driverapi"
"github.com/docker/libnetwork/drvregistry"
"github.com/docker/libnetwork/hostdiscovery"
"github.com/docker/libnetwork/ipamapi"
"github.com/docker/libnetwork/netlabel"
"github.com/docker/libnetwork/options"
"github.com/docker/libnetwork/osl"
"github.com/docker/libnetwork/types"
"github.com/moby/locker"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// NetworkController provides the interface for controller instance which manages
// networks.
type NetworkController interface {
// ID provides a unique identity for the controller
ID() string
// BuiltinDrivers returns list of builtin drivers
BuiltinDrivers() []string
// BuiltinIPAMDrivers returns list of builtin ipam drivers
BuiltinIPAMDrivers() []string
// Config method returns the bootup configuration for the controller
Config() config.Config
// Create a new network. The options parameter carries network specific options.
NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error)
// Networks returns the list of Network(s) managed by this controller.
Networks() []Network
// WalkNetworks uses the provided function to walk the Network(s) managed by this controller.
WalkNetworks(walker NetworkWalker)
// NetworkByName returns the Network which has the passed name. If not found, the error ErrNoSuchNetwork is returned.
NetworkByName(name string) (Network, error)
// NetworkByID returns the Network which has the passed id. If not found, the error ErrNoSuchNetwork is returned.
NetworkByID(id string) (Network, error)
// NewSandbox creates a new network sandbox for the passed container id
NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error)
// Sandboxes returns the list of Sandbox(s) managed by this controller.
Sandboxes() []Sandbox
// WalkSandboxes uses the provided function to walk the Sandbox(s) managed by this controller.
WalkSandboxes(walker SandboxWalker)
// SandboxByID returns the Sandbox which has the passed id. If not found, a types.NotFoundError is returned.
SandboxByID(id string) (Sandbox, error)
// SandboxDestroy destroys a sandbox given a container ID
SandboxDestroy(id string) error
// Stop network controller
Stop()
// ReloadConfiguration updates the controller configuration
ReloadConfiguration(cfgOptions ...config.Option) error
// SetClusterProvider sets cluster provider
SetClusterProvider(provider cluster.Provider)
// Wait for agent initialization complete in libnetwork controller
AgentInitWait()
// Wait for agent to stop if running
AgentStopWait()
// SetKeys configures the encryption key for gossip and overlay data path
SetKeys(keys []*types.EncryptionKey) error
// StartDiagnostic start the network diagnostic mode
StartDiagnostic(port int)
// StopDiagnostic start the network diagnostic mode
StopDiagnostic()
// IsDiagnosticEnabled returns true if the diagnostic is enabled
IsDiagnosticEnabled() bool
}
// NetworkWalker is a client provided function which will be used to walk the Networks.
// When the function returns true, the walk will stop.
type NetworkWalker func(nw Network) bool
// SandboxWalker is a client provided function which will be used to walk the Sandboxes.
// When the function returns true, the walk will stop.
type SandboxWalker func(sb Sandbox) bool
type sandboxTable map[string]*sandbox
type controller struct {
id string
drvRegistry *drvregistry.DrvRegistry
sandboxes sandboxTable
cfg *config.Config
stores []datastore.DataStore
discovery hostdiscovery.HostDiscovery
extKeyListener net.Listener
watchCh chan *endpoint
unWatchCh chan *endpoint
svcRecords map[string]svcInfo
nmap map[string]*netWatch
serviceBindings map[serviceKey]*service
defOsSbox osl.Sandbox
ingressSandbox *sandbox
sboxOnce sync.Once
agent *agent
networkLocker *locker.Locker
agentInitDone chan struct{}
agentStopDone chan struct{}
keys []*types.EncryptionKey
clusterConfigAvailable bool
DiagnosticServer *diagnostic.Server
sync.Mutex
}
type initializer struct {
fn drvregistry.InitFunc
ntype string
}
// New creates a new instance of network controller.
func New(cfgOptions ...config.Option) (NetworkController, error) {
c := &controller{
id: stringid.GenerateRandomID(),
cfg: config.ParseConfigOptions(cfgOptions...),
sandboxes: sandboxTable{},
svcRecords: make(map[string]svcInfo),
serviceBindings: make(map[serviceKey]*service),
agentInitDone: make(chan struct{}),
networkLocker: locker.New(),
DiagnosticServer: diagnostic.New(),
}
c.DiagnosticServer.Init()
if err := c.initStores(); err != nil {
return nil, err
}
drvRegistry, err := drvregistry.New(c.getStore(datastore.LocalScope), c.getStore(datastore.GlobalScope), c.RegisterDriver, nil, c.cfg.PluginGetter)
if err != nil {
return nil, err
}
for _, i := range getInitializers(c.cfg.Daemon.Experimental) {
var dcfg map[string]interface{}
// External plugins don't need config passed through daemon. They can
// bootstrap themselves
if i.ntype != "remote" {
dcfg = c.makeDriverConfig(i.ntype)
}
if err := drvRegistry.AddDriver(i.ntype, i.fn, dcfg); err != nil {
return nil, err
}
}
if err = initIPAMDrivers(drvRegistry, nil, c.getStore(datastore.GlobalScope), c.cfg.Daemon.DefaultAddressPool); err != nil {
return nil, err
}
c.drvRegistry = drvRegistry
if c.cfg != nil && c.cfg.Cluster.Watcher != nil {
if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil {
// Failing to initialize discovery is a bad situation to be in.
// But it cannot fail creating the Controller
logrus.Errorf("Failed to Initialize Discovery : %v", err)
}
}
c.WalkNetworks(populateSpecial)
// Reserve pools first before doing cleanup. Otherwise the
// cleanups of endpoint/network and sandbox below will
// generate many unnecessary warnings
c.reservePools()
// Cleanup resources
c.sandboxCleanup(c.cfg.ActiveSandboxes)
c.cleanupLocalEndpoints()
c.networkCleanup()
if err := c.startExternalKeyListener(); err != nil {
return nil, err
}
setupArrangeUserFilterRule(c)
return c, nil
}
func (c *controller) SetClusterProvider(provider cluster.Provider) {
var sameProvider bool
c.Lock()
// Avoids to spawn multiple goroutine for the same cluster provider
if c.cfg.Daemon.ClusterProvider == provider {
// If the cluster provider is already set, there is already a go routine spawned
// that is listening for events, so nothing to do here
sameProvider = true
} else {
c.cfg.Daemon.ClusterProvider = provider
}
c.Unlock()
if provider == nil || sameProvider {
return
}
// We don't want to spawn a new go routine if the previous one did not exit yet
c.AgentStopWait()
go c.clusterAgentInit()
}
func isValidClusteringIP(addr string) bool {
return addr != "" && !net.ParseIP(addr).IsLoopback() && !net.ParseIP(addr).IsUnspecified()
}
// libnetwork side of agent depends on the keys. On the first receipt of
// keys setup the agent. For subsequent key set handle the key change
func (c *controller) SetKeys(keys []*types.EncryptionKey) error {
subsysKeys := make(map[string]int)
for _, key := range keys {
if key.Subsystem != subsysGossip &&
key.Subsystem != subsysIPSec {
return fmt.Errorf("key received for unrecognized subsystem")
}
subsysKeys[key.Subsystem]++
}
for s, count := range subsysKeys {
if count != keyringSize {
return fmt.Errorf("incorrect number of keys for subsystem %v", s)
}
}
agent := c.getAgent()
if agent == nil {
c.Lock()
c.keys = keys
c.Unlock()
return nil
}
return c.handleKeyChange(keys)
}
func (c *controller) getAgent() *agent {
c.Lock()
defer c.Unlock()
return c.agent
}
func (c *controller) clusterAgentInit() {
clusterProvider := c.cfg.Daemon.ClusterProvider
var keysAvailable bool
for {
eventType := <-clusterProvider.ListenClusterEvents()
// The events: EventSocketChange, EventNodeReady and EventNetworkKeysAvailable are not ordered
// when all the condition for the agent initialization are met then proceed with it
switch eventType {
case cluster.EventNetworkKeysAvailable:
// Validates that the keys are actually available before starting the initialization
// This will handle old spurious messages left on the channel
c.Lock()
keysAvailable = c.keys != nil
c.Unlock()
fallthrough
case cluster.EventSocketChange, cluster.EventNodeReady:
if keysAvailable && !c.isDistributedControl() {
c.agentOperationStart()
if err := c.agentSetup(clusterProvider); err != nil {
c.agentStopComplete()
} else {
c.agentInitComplete()
}
}
case cluster.EventNodeLeave:
c.agentOperationStart()
c.Lock()
c.keys = nil
c.Unlock()
// We are leaving the cluster. Make sure we
// close the gossip so that we stop all
// incoming gossip updates before cleaning up
// any remaining service bindings. But before
// deleting the networks since the networks
// should still be present when cleaning up
// service bindings
c.agentClose()
c.cleanupServiceDiscovery("")
c.cleanupServiceBindings("")
c.agentStopComplete()
return
}
}
}
// AgentInitWait waits for agent initialization to be completed in the controller.
func (c *controller) AgentInitWait() {
c.Lock()
agentInitDone := c.agentInitDone
c.Unlock()
if agentInitDone != nil {
<-agentInitDone
}
}
// AgentStopWait waits for the Agent stop to be completed in the controller
func (c *controller) AgentStopWait() {
c.Lock()
agentStopDone := c.agentStopDone
c.Unlock()
if agentStopDone != nil {
<-agentStopDone
}
}
// agentOperationStart marks the start of an Agent Init or Agent Stop
func (c *controller) agentOperationStart() {
c.Lock()
if c.agentInitDone == nil {
c.agentInitDone = make(chan struct{})
}
if c.agentStopDone == nil {
c.agentStopDone = make(chan struct{})
}
c.Unlock()
}
// agentInitComplete notifies the successful completion of the Agent initialization
func (c *controller) agentInitComplete() {
c.Lock()
if c.agentInitDone != nil {
close(c.agentInitDone)
c.agentInitDone = nil
}
c.Unlock()
}
// agentStopComplete notifies the successful completion of the Agent stop
func (c *controller) agentStopComplete() {
c.Lock()
if c.agentStopDone != nil {
close(c.agentStopDone)
c.agentStopDone = nil
}
c.Unlock()
}
func (c *controller) makeDriverConfig(ntype string) map[string]interface{} {
if c.cfg == nil {
return nil
}
config := make(map[string]interface{})
for _, label := range c.cfg.Daemon.Labels {
if !strings.HasPrefix(netlabel.Key(label), netlabel.DriverPrefix+"."+ntype) {
continue
}
config[netlabel.Key(label)] = netlabel.Value(label)
}
drvCfg, ok := c.cfg.Daemon.DriverCfg[ntype]
if ok {
for k, v := range drvCfg.(map[string]interface{}) {
config[k] = v
}
}
for k, v := range c.cfg.Scopes {
if !v.IsValid() {
continue
}
config[netlabel.MakeKVClient(k)] = discoverapi.DatastoreConfigData{
Scope: k,
Provider: v.Client.Provider,
Address: v.Client.Address,
Config: v.Client.Config,
}
}
return config
}
var procReloadConfig = make(chan (bool), 1)
func (c *controller) ReloadConfiguration(cfgOptions ...config.Option) error {
procReloadConfig <- true
defer func() { <-procReloadConfig }()
// For now we accept the configuration reload only as a mean to provide a global store config after boot.
// Refuse the configuration if it alters an existing datastore client configuration.
update := false
cfg := config.ParseConfigOptions(cfgOptions...)
for s := range c.cfg.Scopes {
if _, ok := cfg.Scopes[s]; !ok {
return types.ForbiddenErrorf("cannot accept new configuration because it removes an existing datastore client")
}
}
for s, nSCfg := range cfg.Scopes {
if eSCfg, ok := c.cfg.Scopes[s]; ok {
if eSCfg.Client.Provider != nSCfg.Client.Provider ||
eSCfg.Client.Address != nSCfg.Client.Address {
return types.ForbiddenErrorf("cannot accept new configuration because it modifies an existing datastore client")
}
} else {
if err := c.initScopedStore(s, nSCfg); err != nil {
return err
}
update = true
}
}
if !update {
return nil
}
c.Lock()
c.cfg = cfg
c.Unlock()
var dsConfig *discoverapi.DatastoreConfigData
for scope, sCfg := range cfg.Scopes {
if scope == datastore.LocalScope || !sCfg.IsValid() {
continue
}
dsConfig = &discoverapi.DatastoreConfigData{
Scope: scope,
Provider: sCfg.Client.Provider,
Address: sCfg.Client.Address,
Config: sCfg.Client.Config,
}
break
}
if dsConfig == nil {
return nil
}
c.drvRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool {
err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
if err != nil {
logrus.Errorf("Failed to set datastore in driver %s: %v", name, err)
}
return false
})
c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
if err != nil {
logrus.Errorf("Failed to set datastore in driver %s: %v", name, err)
}
return false
})
if c.discovery == nil && c.cfg.Cluster.Watcher != nil {
if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil {
logrus.Errorf("Failed to Initialize Discovery after configuration update: %v", err)
}
}
return nil
}
func (c *controller) ID() string {
return c.id
}
func (c *controller) BuiltinDrivers() []string {
drivers := []string{}
c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
if driver.IsBuiltIn() {
drivers = append(drivers, name)
}
return false
})
return drivers
}
func (c *controller) BuiltinIPAMDrivers() []string {
drivers := []string{}
c.drvRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool {
if driver.IsBuiltIn() {
drivers = append(drivers, name)
}
return false
})
return drivers
}
func (c *controller) validateHostDiscoveryConfig() bool {
if c.cfg == nil || c.cfg.Cluster.Discovery == "" || c.cfg.Cluster.Address == "" {
return false
}
return true
}
func (c *controller) clusterHostID() string {
c.Lock()
defer c.Unlock()
if c.cfg == nil || c.cfg.Cluster.Address == "" {
return ""
}
addr := strings.Split(c.cfg.Cluster.Address, ":")
return addr[0]
}
func (c *controller) isNodeAlive(node string) bool {
if c.discovery == nil {
return false
}
nodes := c.discovery.Fetch()
for _, n := range nodes {
if n.String() == node {
return true
}
}
return false
}
func (c *controller) initDiscovery(watcher discovery.Watcher) error {
if c.cfg == nil {
return fmt.Errorf("discovery initialization requires a valid configuration")
}
c.discovery = hostdiscovery.NewHostDiscovery(watcher)
return c.discovery.Watch(c.activeCallback, c.hostJoinCallback, c.hostLeaveCallback)
}
func (c *controller) activeCallback() {
ds := c.getStore(datastore.GlobalScope)
if ds != nil && !ds.Active() {
ds.RestartWatch()
}
}
func (c *controller) hostJoinCallback(nodes []net.IP) {
c.processNodeDiscovery(nodes, true)
}
func (c *controller) hostLeaveCallback(nodes []net.IP) {
c.processNodeDiscovery(nodes, false)
}
func (c *controller) processNodeDiscovery(nodes []net.IP, add bool) {
c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
c.pushNodeDiscovery(driver, capability, nodes, add)
return false
})
}
func (c *controller) pushNodeDiscovery(d driverapi.Driver, cap driverapi.Capability, nodes []net.IP, add bool) {
var self net.IP
if c.cfg != nil {
addr := strings.Split(c.cfg.Cluster.Address, ":")
self = net.ParseIP(addr[0])
// if external kvstore is not configured, try swarm-mode config
if self == nil {
if agent := c.getAgent(); agent != nil {
self = net.ParseIP(agent.advertiseAddr)
}
}
}
if d == nil || cap.ConnectivityScope != datastore.GlobalScope || nodes == nil {
return
}
for _, node := range nodes {
nodeData := discoverapi.NodeDiscoveryData{Address: node.String(), Self: node.Equal(self)}
var err error
if add {
err = d.DiscoverNew(discoverapi.NodeDiscovery, nodeData)
} else {
err = d.DiscoverDelete(discoverapi.NodeDiscovery, nodeData)
}
if err != nil {
logrus.Debugf("discovery notification error: %v", err)
}
}
}
func (c *controller) Config() config.Config {
c.Lock()
defer c.Unlock()
if c.cfg == nil {
return config.Config{}
}
return *c.cfg
}
func (c *controller) isManager() bool {
c.Lock()
defer c.Unlock()
if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
return false
}
return c.cfg.Daemon.ClusterProvider.IsManager()
}
func (c *controller) isAgent() bool {
c.Lock()
defer c.Unlock()
if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
return false
}
return c.cfg.Daemon.ClusterProvider.IsAgent()
}
func (c *controller) isDistributedControl() bool {
return !c.isManager() && !c.isAgent()
}
func (c *controller) GetPluginGetter() plugingetter.PluginGetter {
return c.drvRegistry.GetPluginGetter()
}
func (c *controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error {
c.Lock()
hd := c.discovery
c.Unlock()
if hd != nil {
c.pushNodeDiscovery(driver, capability, hd.Fetch(), true)
}
c.agentDriverNotify(driver)
return nil
}
// XXX This should be made driver agnostic. See comment below.
const overlayDSROptionString = "dsr"
// NewNetwork creates a new network of the specified network type. The options
// are network specific and modeled in a generic way.
func (c *controller) NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error) {
var (
cap *driverapi.Capability
err error
t *network
skipCfgEpCount bool
)
if id != "" {
c.networkLocker.Lock(id)
defer c.networkLocker.Unlock(id)
if _, err = c.NetworkByID(id); err == nil {
return nil, NetworkNameError(id)
}
}
if !config.IsValidName(name) {
return nil, ErrInvalidName(name)
}
if id == "" {
id = stringid.GenerateRandomID()
}
defaultIpam := defaultIpamForNetworkType(networkType)
// Construct the network object
network := &network{
name: name,
networkType: networkType,
generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)},
ipamType: defaultIpam,
id: id,
created: time.Now(),
ctrlr: c,
persist: true,
drvOnce: &sync.Once{},
loadBalancerMode: loadBalancerModeDefault,
}
network.processOptions(options...)
if err = network.validateConfiguration(); err != nil {
return nil, err
}
// Reset network types, force local scope and skip allocation and
// plumbing for configuration networks. Reset of the config-only
// network drivers is needed so that this special network is not
// usable by old engine versions.
if network.configOnly {
network.scope = datastore.LocalScope
network.networkType = "null"
goto addToStore
}
_, cap, err = network.resolveDriver(network.networkType, true)
if err != nil {
return nil, err
}
if network.scope == datastore.LocalScope && cap.DataScope == datastore.GlobalScope {
return nil, types.ForbiddenErrorf("cannot downgrade network scope for %s networks", networkType)
}
if network.ingress && cap.DataScope != datastore.GlobalScope {
return nil, types.ForbiddenErrorf("Ingress network can only be global scope network")
}
// At this point the network scope is still unknown if not set by user
if (cap.DataScope == datastore.GlobalScope || network.scope == datastore.SwarmScope) &&
!c.isDistributedControl() && !network.dynamic {
if c.isManager() {
// For non-distributed controlled environment, globalscoped non-dynamic networks are redirected to Manager
return nil, ManagerRedirectError(name)
}
return nil, types.ForbiddenErrorf("Cannot create a multi-host network from a worker node. Please create the network from a manager node.")
}
if network.scope == datastore.SwarmScope && c.isDistributedControl() {
return nil, types.ForbiddenErrorf("cannot create a swarm scoped network when swarm is not active")
}
// Make sure we have a driver available for this network type
// before we allocate anything.
if _, err := network.driver(true); err != nil {
return nil, err
}
// From this point on, we need the network specific configuration,
// which may come from a configuration-only network
if network.configFrom != "" {
t, err = c.getConfigNetwork(network.configFrom)
if err != nil {
return nil, types.NotFoundErrorf("configuration network %q does not exist", network.configFrom)
}
if err = t.applyConfigurationTo(network); err != nil {
return nil, types.InternalErrorf("Failed to apply configuration: %v", err)
}
network.generic[netlabel.Internal] = network.internal
defer func() {
if err == nil && !skipCfgEpCount {
if err := t.getEpCnt().IncEndpointCnt(); err != nil {
logrus.Warnf("Failed to update reference count for configuration network %q on creation of network %q: %v",
t.Name(), network.Name(), err)
}
}
}()
}
err = network.ipamAllocate()
if err != nil {
return nil, err
}
defer func() {
if err != nil {
network.ipamRelease()
}
}()
err = c.addNetwork(network)
if err != nil {
if _, ok := err.(types.MaskableError); ok {
// This error can be ignored and set this boolean
// value to skip a refcount increment for configOnly networks
skipCfgEpCount = true
} else {
return nil, err
}
}
defer func() {
if err != nil {
if e := network.deleteNetwork(); e != nil {
logrus.Warnf("couldn't roll back driver network on network %s creation failure: %v", network.name, err)
}
}
}()
// XXX If the driver type is "overlay" check the options for DSR
// being set. If so, set the network's load balancing mode to DSR.
// This should really be done in a network option, but due to
// time pressure to get this in without adding changes to moby,
// swarm and CLI, it is being implemented as a driver-specific
// option. Unfortunately, drivers can't influence the core
// "libnetwork.network" data type. Hence we need this hack code
// to implement in this manner.
if gval, ok := network.generic[netlabel.GenericData]; ok && network.networkType == "overlay" {
optMap := gval.(map[string]string)
if _, ok := optMap[overlayDSROptionString]; ok {
network.loadBalancerMode = loadBalancerModeDSR
}
}
addToStore:
// First store the endpoint count, then the network. To avoid to
// end up with a datastore containing a network and not an epCnt,
// in case of an ungraceful shutdown during this function call.
epCnt := &endpointCnt{n: network}
if err = c.updateToStore(epCnt); err != nil {
return nil, err
}
defer func() {
if err != nil {
if e := c.deleteFromStore(epCnt); e != nil {
logrus.Warnf("could not rollback from store, epCnt %v on failure (%v): %v", epCnt, err, e)
}
}
}()
network.epCnt = epCnt
if err = c.updateToStore(network); err != nil {
return nil, err
}
defer func() {
if err != nil {
if e := c.deleteFromStore(network); e != nil {
logrus.Warnf("could not rollback from store, network %v on failure (%v): %v", network, err, e)
}
}
}()
if network.configOnly {
return network, nil
}
joinCluster(network)
defer func() {
if err != nil {
network.cancelDriverWatches()
if e := network.leaveCluster(); e != nil {
logrus.Warnf("Failed to leave agent cluster on network %s on failure (%v): %v", network.name, err, e)
}
}
}()
if network.hasLoadBalancerEndpoint() {
if err = network.createLoadBalancerSandbox(); err != nil {
return nil, err
}
}
if !c.isDistributedControl() {
c.Lock()
arrangeIngressFilterRule()
c.Unlock()
}
arrangeUserFilterRule()
return network, nil
}
var joinCluster NetworkWalker = func(nw Network) bool {
n := nw.(*network)
if n.configOnly {
return false
}
if err := n.joinCluster(); err != nil {
logrus.Errorf("Failed to join network %s (%s) into agent cluster: %v", n.Name(), n.ID(), err)
}
n.addDriverWatches()
return false
}
func (c *controller) reservePools() {
networks, err := c.getNetworksForScope(datastore.LocalScope)
if err != nil {
logrus.Warnf("Could not retrieve networks from local store during ipam allocation for existing networks: %v", err)
return
}
for _, n := range networks {
if n.configOnly {
continue
}
if !doReplayPoolReserve(n) {
continue
}
// Construct pseudo configs for the auto IP case
autoIPv4 := (len(n.ipamV4Config) == 0 || (len(n.ipamV4Config) == 1 && n.ipamV4Config[0].PreferredPool == "")) && len(n.ipamV4Info) > 0
autoIPv6 := (len(n.ipamV6Config) == 0 || (len(n.ipamV6Config) == 1 && n.ipamV6Config[0].PreferredPool == "")) && len(n.ipamV6Info) > 0
if autoIPv4 {
n.ipamV4Config = []*IpamConf{{PreferredPool: n.ipamV4Info[0].Pool.String()}}
}
if n.enableIPv6 && autoIPv6 {
n.ipamV6Config = []*IpamConf{{PreferredPool: n.ipamV6Info[0].Pool.String()}}
}
// Account current network gateways
for i, c := range n.ipamV4Config {
if c.Gateway == "" && n.ipamV4Info[i].Gateway != nil {
c.Gateway = n.ipamV4Info[i].Gateway.IP.String()
}
}
if n.enableIPv6 {
for i, c := range n.ipamV6Config {
if c.Gateway == "" && n.ipamV6Info[i].Gateway != nil {
c.Gateway = n.ipamV6Info[i].Gateway.IP.String()
}
}
}
// Reserve pools
if err := n.ipamAllocate(); err != nil {
logrus.Warnf("Failed to allocate ipam pool(s) for network %q (%s): %v", n.Name(), n.ID(), err)
}
// Reserve existing endpoints' addresses
ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
if err != nil {
logrus.Warnf("Failed to retrieve ipam driver for network %q (%s) during address reservation", n.Name(), n.ID())
continue
}
epl, err := n.getEndpointsFromStore()
if err != nil {
logrus.Warnf("Failed to retrieve list of current endpoints on network %q (%s)", n.Name(), n.ID())
continue
}
for _, ep := range epl {
if ep.Iface() == nil {
logrus.Warnf("endpoint interface is empty for %q (%s)", ep.Name(), ep.ID())
continue
}
if err := ep.assignAddress(ipam, true, ep.Iface().AddressIPv6() != nil); err != nil {
logrus.Warnf("Failed to reserve current address for endpoint %q (%s) on network %q (%s)",
ep.Name(), ep.ID(), n.Name(), n.ID())
}
}
}
}
func doReplayPoolReserve(n *network) bool {
_, caps, err := n.getController().getIPAMDriver(n.ipamType)
if err != nil {
logrus.Warnf("Failed to retrieve ipam driver for network %q (%s): %v", n.Name(), n.ID(), err)
return false
}