network.go 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240
  1. package libnetwork
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "runtime"
  8. "strings"
  9. "sync"
  10. "time"
  11. "github.com/containerd/containerd/log"
  12. "github.com/docker/docker/libnetwork/config"
  13. "github.com/docker/docker/libnetwork/datastore"
  14. "github.com/docker/docker/libnetwork/driverapi"
  15. "github.com/docker/docker/libnetwork/etchosts"
  16. "github.com/docker/docker/libnetwork/internal/setmatrix"
  17. "github.com/docker/docker/libnetwork/ipamapi"
  18. "github.com/docker/docker/libnetwork/netlabel"
  19. "github.com/docker/docker/libnetwork/netutils"
  20. "github.com/docker/docker/libnetwork/networkdb"
  21. "github.com/docker/docker/libnetwork/options"
  22. "github.com/docker/docker/libnetwork/types"
  23. "github.com/docker/docker/pkg/stringid"
  24. )
  25. // A Network represents a logical connectivity zone that containers may
  26. // join using the Link method. A Network is managed by a specific driver.
  27. type Network interface {
  28. // Name returns a user chosen name for this network.
  29. Name() string
  30. // ID returns a system generated id for this network.
  31. ID() string
  32. // Type returns the type of network, which corresponds to its managing driver.
  33. Type() string
  34. // CreateEndpoint creates a new endpoint to this network symbolically identified by the
  35. // specified unique name. The options parameter carries driver specific options.
  36. CreateEndpoint(name string, options ...EndpointOption) (*Endpoint, error)
  37. // Delete the network.
  38. Delete(options ...NetworkDeleteOption) error
  39. // Endpoints returns the list of Endpoint(s) in this network.
  40. Endpoints() []*Endpoint
  41. // WalkEndpoints uses the provided function to walk the Endpoints.
  42. WalkEndpoints(walker EndpointWalker)
  43. // EndpointByName returns the Endpoint which has the passed name. If not found, the error ErrNoSuchEndpoint is returned.
  44. EndpointByName(name string) (*Endpoint, error)
  45. // EndpointByID returns the Endpoint which has the passed id. If not found, the error ErrNoSuchEndpoint is returned.
  46. EndpointByID(id string) (*Endpoint, error)
  47. // Info returns certain operational data belonging to this network.
  48. Info() NetworkInfo
  49. }
  50. // NetworkInfo returns some configuration and operational information about the network
  51. type NetworkInfo interface {
  52. IpamConfig() (string, map[string]string, []*IpamConf, []*IpamConf)
  53. IpamInfo() ([]*IpamInfo, []*IpamInfo)
  54. DriverOptions() map[string]string
  55. Scope() string
  56. IPv6Enabled() bool
  57. Internal() bool
  58. Attachable() bool
  59. Ingress() bool
  60. ConfigFrom() string
  61. ConfigOnly() bool
  62. Labels() map[string]string
  63. Dynamic() bool
  64. Created() time.Time
  65. // Peers returns a slice of PeerInfo structures which has the information about the peer
  66. // nodes participating in the same overlay network. This is currently the per-network
  67. // gossip cluster. For non-dynamic overlay networks and bridge networks it returns an
  68. // empty slice
  69. Peers() []networkdb.PeerInfo
  70. // Services returns a map of services keyed by the service name with the details
  71. // of all the tasks that belong to the service. Applicable only in swarm mode.
  72. Services() map[string]ServiceInfo
  73. }
  74. // EndpointWalker is a client provided function which will be used to walk the Endpoints.
  75. // When the function returns true, the walk will stop.
  76. type EndpointWalker func(ep *Endpoint) bool
  77. // ipInfo is the reverse mapping from IP to service name to serve the PTR query.
  78. // extResolver is set if an external server resolves a service name to this IP.
  79. // It's an indication to defer PTR queries also to that external server.
  80. type ipInfo struct {
  81. name string
  82. serviceID string
  83. extResolver bool
  84. }
  85. // svcMapEntry is the body of the element into the svcMap
  86. // The ip is a string because the SetMatrix does not accept non hashable values
  87. type svcMapEntry struct {
  88. ip string
  89. serviceID string
  90. }
  91. type svcInfo struct {
  92. svcMap setmatrix.SetMatrix[svcMapEntry]
  93. svcIPv6Map setmatrix.SetMatrix[svcMapEntry]
  94. ipMap setmatrix.SetMatrix[ipInfo]
  95. service map[string][]servicePorts
  96. }
  97. // backing container or host's info
  98. type serviceTarget struct {
  99. name string
  100. ip net.IP
  101. port uint16
  102. }
  103. type servicePorts struct {
  104. portName string
  105. proto string
  106. target []serviceTarget
  107. }
  108. type networkDBTable struct {
  109. name string
  110. objType driverapi.ObjectType
  111. }
  112. // IpamConf contains all the ipam related configurations for a network
  113. type IpamConf struct {
  114. // PreferredPool is the master address pool for containers and network interfaces.
  115. PreferredPool string
  116. // SubPool is a subset of the master pool. If specified,
  117. // this becomes the container pool.
  118. SubPool string
  119. // Gateway is the preferred Network Gateway address (optional).
  120. Gateway string
  121. // AuxAddresses contains auxiliary addresses for network driver. Must be within the master pool.
  122. // libnetwork will reserve them if they fall into the container pool.
  123. AuxAddresses map[string]string
  124. }
  125. // Validate checks whether the configuration is valid
  126. func (c *IpamConf) Validate() error {
  127. if c.Gateway != "" && nil == net.ParseIP(c.Gateway) {
  128. return types.BadRequestErrorf("invalid gateway address %s in Ipam configuration", c.Gateway)
  129. }
  130. return nil
  131. }
  132. // IpamInfo contains all the ipam related operational info for a network
  133. type IpamInfo struct {
  134. PoolID string
  135. Meta map[string]string
  136. driverapi.IPAMData
  137. }
  138. // MarshalJSON encodes IpamInfo into json message
  139. func (i *IpamInfo) MarshalJSON() ([]byte, error) {
  140. m := map[string]interface{}{
  141. "PoolID": i.PoolID,
  142. }
  143. v, err := json.Marshal(&i.IPAMData)
  144. if err != nil {
  145. return nil, err
  146. }
  147. m["IPAMData"] = string(v)
  148. if i.Meta != nil {
  149. m["Meta"] = i.Meta
  150. }
  151. return json.Marshal(m)
  152. }
  153. // UnmarshalJSON decodes json message into PoolData
  154. func (i *IpamInfo) UnmarshalJSON(data []byte) error {
  155. var (
  156. m map[string]interface{}
  157. err error
  158. )
  159. if err = json.Unmarshal(data, &m); err != nil {
  160. return err
  161. }
  162. i.PoolID = m["PoolID"].(string)
  163. if v, ok := m["Meta"]; ok {
  164. b, _ := json.Marshal(v)
  165. if err = json.Unmarshal(b, &i.Meta); err != nil {
  166. return err
  167. }
  168. }
  169. if v, ok := m["IPAMData"]; ok {
  170. if err = json.Unmarshal([]byte(v.(string)), &i.IPAMData); err != nil {
  171. return err
  172. }
  173. }
  174. return nil
  175. }
  176. type network struct {
  177. ctrlr *Controller
  178. name string
  179. networkType string
  180. id string
  181. created time.Time
  182. scope string // network data scope
  183. labels map[string]string
  184. ipamType string
  185. ipamOptions map[string]string
  186. addrSpace string
  187. ipamV4Config []*IpamConf
  188. ipamV6Config []*IpamConf
  189. ipamV4Info []*IpamInfo
  190. ipamV6Info []*IpamInfo
  191. enableIPv6 bool
  192. postIPv6 bool
  193. epCnt *endpointCnt
  194. generic options.Generic
  195. dbIndex uint64
  196. dbExists bool
  197. persist bool
  198. drvOnce *sync.Once
  199. resolverOnce sync.Once //nolint:nolintlint,unused // only used on windows
  200. resolver []*Resolver
  201. internal bool
  202. attachable bool
  203. inDelete bool
  204. ingress bool
  205. driverTables []networkDBTable
  206. dynamic bool
  207. configOnly bool
  208. configFrom string
  209. loadBalancerIP net.IP
  210. loadBalancerMode string
  211. mu sync.Mutex
  212. }
  213. const (
  214. loadBalancerModeNAT = "NAT"
  215. loadBalancerModeDSR = "DSR"
  216. loadBalancerModeDefault = loadBalancerModeNAT
  217. )
  218. func (n *network) Name() string {
  219. n.mu.Lock()
  220. defer n.mu.Unlock()
  221. return n.name
  222. }
  223. func (n *network) ID() string {
  224. n.mu.Lock()
  225. defer n.mu.Unlock()
  226. return n.id
  227. }
  228. func (n *network) Created() time.Time {
  229. n.mu.Lock()
  230. defer n.mu.Unlock()
  231. return n.created
  232. }
  233. func (n *network) Type() string {
  234. n.mu.Lock()
  235. defer n.mu.Unlock()
  236. return n.networkType
  237. }
  238. func (n *network) Key() []string {
  239. n.mu.Lock()
  240. defer n.mu.Unlock()
  241. return []string{datastore.NetworkKeyPrefix, n.id}
  242. }
  243. func (n *network) KeyPrefix() []string {
  244. return []string{datastore.NetworkKeyPrefix}
  245. }
  246. func (n *network) Value() []byte {
  247. n.mu.Lock()
  248. defer n.mu.Unlock()
  249. b, err := json.Marshal(n)
  250. if err != nil {
  251. return nil
  252. }
  253. return b
  254. }
  255. func (n *network) SetValue(value []byte) error {
  256. return json.Unmarshal(value, n)
  257. }
  258. func (n *network) Index() uint64 {
  259. n.mu.Lock()
  260. defer n.mu.Unlock()
  261. return n.dbIndex
  262. }
  263. func (n *network) SetIndex(index uint64) {
  264. n.mu.Lock()
  265. n.dbIndex = index
  266. n.dbExists = true
  267. n.mu.Unlock()
  268. }
  269. func (n *network) Exists() bool {
  270. n.mu.Lock()
  271. defer n.mu.Unlock()
  272. return n.dbExists
  273. }
  274. func (n *network) Skip() bool {
  275. n.mu.Lock()
  276. defer n.mu.Unlock()
  277. return !n.persist
  278. }
  279. func (n *network) New() datastore.KVObject {
  280. n.mu.Lock()
  281. defer n.mu.Unlock()
  282. return &network{
  283. ctrlr: n.ctrlr,
  284. drvOnce: &sync.Once{},
  285. scope: n.scope,
  286. }
  287. }
  288. // CopyTo deep copies to the destination IpamConfig
  289. func (c *IpamConf) CopyTo(dstC *IpamConf) error {
  290. dstC.PreferredPool = c.PreferredPool
  291. dstC.SubPool = c.SubPool
  292. dstC.Gateway = c.Gateway
  293. if c.AuxAddresses != nil {
  294. dstC.AuxAddresses = make(map[string]string, len(c.AuxAddresses))
  295. for k, v := range c.AuxAddresses {
  296. dstC.AuxAddresses[k] = v
  297. }
  298. }
  299. return nil
  300. }
  301. // CopyTo deep copies to the destination IpamInfo
  302. func (i *IpamInfo) CopyTo(dstI *IpamInfo) error {
  303. dstI.PoolID = i.PoolID
  304. if i.Meta != nil {
  305. dstI.Meta = make(map[string]string)
  306. for k, v := range i.Meta {
  307. dstI.Meta[k] = v
  308. }
  309. }
  310. dstI.AddressSpace = i.AddressSpace
  311. dstI.Pool = types.GetIPNetCopy(i.Pool)
  312. dstI.Gateway = types.GetIPNetCopy(i.Gateway)
  313. if i.AuxAddresses != nil {
  314. dstI.AuxAddresses = make(map[string]*net.IPNet)
  315. for k, v := range i.AuxAddresses {
  316. dstI.AuxAddresses[k] = types.GetIPNetCopy(v)
  317. }
  318. }
  319. return nil
  320. }
  321. func (n *network) validateConfiguration() error {
  322. if n.configOnly {
  323. // Only supports network specific configurations.
  324. // Network operator configurations are not supported.
  325. if n.ingress || n.internal || n.attachable || n.scope != "" {
  326. return types.ForbiddenErrorf("configuration network can only contain network " +
  327. "specific fields. Network operator fields like " +
  328. "[ ingress | internal | attachable | scope ] are not supported.")
  329. }
  330. }
  331. if n.configFrom != "" {
  332. if n.configOnly {
  333. return types.ForbiddenErrorf("a configuration network cannot depend on another configuration network")
  334. }
  335. if n.ipamType != "" &&
  336. n.ipamType != defaultIpamForNetworkType(n.networkType) ||
  337. n.enableIPv6 ||
  338. len(n.labels) > 0 || len(n.ipamOptions) > 0 ||
  339. len(n.ipamV4Config) > 0 || len(n.ipamV6Config) > 0 {
  340. return types.ForbiddenErrorf("user specified configurations are not supported if the network depends on a configuration network")
  341. }
  342. if len(n.generic) > 0 {
  343. if data, ok := n.generic[netlabel.GenericData]; ok {
  344. var (
  345. driverOptions map[string]string
  346. opts interface{}
  347. )
  348. switch t := data.(type) {
  349. case map[string]interface{}, map[string]string:
  350. opts = t
  351. }
  352. ba, err := json.Marshal(opts)
  353. if err != nil {
  354. return fmt.Errorf("failed to validate network configuration: %v", err)
  355. }
  356. if err := json.Unmarshal(ba, &driverOptions); err != nil {
  357. return fmt.Errorf("failed to validate network configuration: %v", err)
  358. }
  359. if len(driverOptions) > 0 {
  360. return types.ForbiddenErrorf("network driver options are not supported if the network depends on a configuration network")
  361. }
  362. }
  363. }
  364. }
  365. return nil
  366. }
  367. // applyConfigurationTo applies network specific configurations.
  368. func (n *network) applyConfigurationTo(to *network) error {
  369. to.enableIPv6 = n.enableIPv6
  370. if len(n.labels) > 0 {
  371. to.labels = make(map[string]string, len(n.labels))
  372. for k, v := range n.labels {
  373. if _, ok := to.labels[k]; !ok {
  374. to.labels[k] = v
  375. }
  376. }
  377. }
  378. if len(n.ipamType) != 0 {
  379. to.ipamType = n.ipamType
  380. }
  381. if len(n.ipamOptions) > 0 {
  382. to.ipamOptions = make(map[string]string, len(n.ipamOptions))
  383. for k, v := range n.ipamOptions {
  384. if _, ok := to.ipamOptions[k]; !ok {
  385. to.ipamOptions[k] = v
  386. }
  387. }
  388. }
  389. if len(n.ipamV4Config) > 0 {
  390. to.ipamV4Config = make([]*IpamConf, 0, len(n.ipamV4Config))
  391. to.ipamV4Config = append(to.ipamV4Config, n.ipamV4Config...)
  392. }
  393. if len(n.ipamV6Config) > 0 {
  394. to.ipamV6Config = make([]*IpamConf, 0, len(n.ipamV6Config))
  395. to.ipamV6Config = append(to.ipamV6Config, n.ipamV6Config...)
  396. }
  397. if len(n.generic) > 0 {
  398. to.generic = options.Generic{}
  399. for k, v := range n.generic {
  400. to.generic[k] = v
  401. }
  402. }
  403. return nil
  404. }
  405. func (n *network) CopyTo(o datastore.KVObject) error {
  406. n.mu.Lock()
  407. defer n.mu.Unlock()
  408. dstN := o.(*network)
  409. dstN.name = n.name
  410. dstN.id = n.id
  411. dstN.created = n.created
  412. dstN.networkType = n.networkType
  413. dstN.scope = n.scope
  414. dstN.dynamic = n.dynamic
  415. dstN.ipamType = n.ipamType
  416. dstN.enableIPv6 = n.enableIPv6
  417. dstN.persist = n.persist
  418. dstN.postIPv6 = n.postIPv6
  419. dstN.dbIndex = n.dbIndex
  420. dstN.dbExists = n.dbExists
  421. dstN.drvOnce = n.drvOnce
  422. dstN.internal = n.internal
  423. dstN.attachable = n.attachable
  424. dstN.inDelete = n.inDelete
  425. dstN.ingress = n.ingress
  426. dstN.configOnly = n.configOnly
  427. dstN.configFrom = n.configFrom
  428. dstN.loadBalancerIP = n.loadBalancerIP
  429. dstN.loadBalancerMode = n.loadBalancerMode
  430. // copy labels
  431. if dstN.labels == nil {
  432. dstN.labels = make(map[string]string, len(n.labels))
  433. }
  434. for k, v := range n.labels {
  435. dstN.labels[k] = v
  436. }
  437. if n.ipamOptions != nil {
  438. dstN.ipamOptions = make(map[string]string, len(n.ipamOptions))
  439. for k, v := range n.ipamOptions {
  440. dstN.ipamOptions[k] = v
  441. }
  442. }
  443. for _, v4conf := range n.ipamV4Config {
  444. dstV4Conf := &IpamConf{}
  445. if err := v4conf.CopyTo(dstV4Conf); err != nil {
  446. return err
  447. }
  448. dstN.ipamV4Config = append(dstN.ipamV4Config, dstV4Conf)
  449. }
  450. for _, v4info := range n.ipamV4Info {
  451. dstV4Info := &IpamInfo{}
  452. if err := v4info.CopyTo(dstV4Info); err != nil {
  453. return err
  454. }
  455. dstN.ipamV4Info = append(dstN.ipamV4Info, dstV4Info)
  456. }
  457. for _, v6conf := range n.ipamV6Config {
  458. dstV6Conf := &IpamConf{}
  459. if err := v6conf.CopyTo(dstV6Conf); err != nil {
  460. return err
  461. }
  462. dstN.ipamV6Config = append(dstN.ipamV6Config, dstV6Conf)
  463. }
  464. for _, v6info := range n.ipamV6Info {
  465. dstV6Info := &IpamInfo{}
  466. if err := v6info.CopyTo(dstV6Info); err != nil {
  467. return err
  468. }
  469. dstN.ipamV6Info = append(dstN.ipamV6Info, dstV6Info)
  470. }
  471. dstN.generic = options.Generic{}
  472. for k, v := range n.generic {
  473. dstN.generic[k] = v
  474. }
  475. return nil
  476. }
  477. func (n *network) DataScope() string {
  478. s := n.Scope()
  479. // All swarm scope networks have local datascope
  480. if s == datastore.SwarmScope {
  481. s = datastore.LocalScope
  482. }
  483. return s
  484. }
  485. func (n *network) getEpCnt() *endpointCnt {
  486. n.mu.Lock()
  487. defer n.mu.Unlock()
  488. return n.epCnt
  489. }
  490. // TODO : Can be made much more generic with the help of reflection (but has some golang limitations)
  491. func (n *network) MarshalJSON() ([]byte, error) {
  492. netMap := make(map[string]interface{})
  493. netMap["name"] = n.name
  494. netMap["id"] = n.id
  495. netMap["created"] = n.created
  496. netMap["networkType"] = n.networkType
  497. netMap["scope"] = n.scope
  498. netMap["labels"] = n.labels
  499. netMap["ipamType"] = n.ipamType
  500. netMap["ipamOptions"] = n.ipamOptions
  501. netMap["addrSpace"] = n.addrSpace
  502. netMap["enableIPv6"] = n.enableIPv6
  503. if n.generic != nil {
  504. netMap["generic"] = n.generic
  505. }
  506. netMap["persist"] = n.persist
  507. netMap["postIPv6"] = n.postIPv6
  508. if len(n.ipamV4Config) > 0 {
  509. ics, err := json.Marshal(n.ipamV4Config)
  510. if err != nil {
  511. return nil, err
  512. }
  513. netMap["ipamV4Config"] = string(ics)
  514. }
  515. if len(n.ipamV4Info) > 0 {
  516. iis, err := json.Marshal(n.ipamV4Info)
  517. if err != nil {
  518. return nil, err
  519. }
  520. netMap["ipamV4Info"] = string(iis)
  521. }
  522. if len(n.ipamV6Config) > 0 {
  523. ics, err := json.Marshal(n.ipamV6Config)
  524. if err != nil {
  525. return nil, err
  526. }
  527. netMap["ipamV6Config"] = string(ics)
  528. }
  529. if len(n.ipamV6Info) > 0 {
  530. iis, err := json.Marshal(n.ipamV6Info)
  531. if err != nil {
  532. return nil, err
  533. }
  534. netMap["ipamV6Info"] = string(iis)
  535. }
  536. netMap["internal"] = n.internal
  537. netMap["attachable"] = n.attachable
  538. netMap["inDelete"] = n.inDelete
  539. netMap["ingress"] = n.ingress
  540. netMap["configOnly"] = n.configOnly
  541. netMap["configFrom"] = n.configFrom
  542. netMap["loadBalancerIP"] = n.loadBalancerIP
  543. netMap["loadBalancerMode"] = n.loadBalancerMode
  544. return json.Marshal(netMap)
  545. }
  546. // TODO : Can be made much more generic with the help of reflection (but has some golang limitations)
  547. func (n *network) UnmarshalJSON(b []byte) (err error) {
  548. var netMap map[string]interface{}
  549. if err := json.Unmarshal(b, &netMap); err != nil {
  550. return err
  551. }
  552. n.name = netMap["name"].(string)
  553. n.id = netMap["id"].(string)
  554. // "created" is not available in older versions
  555. if v, ok := netMap["created"]; ok {
  556. // n.created is time.Time but marshalled as string
  557. if err = n.created.UnmarshalText([]byte(v.(string))); err != nil {
  558. log.G(context.TODO()).Warnf("failed to unmarshal creation time %v: %v", v, err)
  559. n.created = time.Time{}
  560. }
  561. }
  562. n.networkType = netMap["networkType"].(string)
  563. n.enableIPv6 = netMap["enableIPv6"].(bool)
  564. // if we weren't unmarshaling to netMap we could simply set n.labels
  565. // unfortunately, we can't because map[string]interface{} != map[string]string
  566. if labels, ok := netMap["labels"].(map[string]interface{}); ok {
  567. n.labels = make(map[string]string, len(labels))
  568. for label, value := range labels {
  569. n.labels[label] = value.(string)
  570. }
  571. }
  572. if v, ok := netMap["ipamOptions"]; ok {
  573. if iOpts, ok := v.(map[string]interface{}); ok {
  574. n.ipamOptions = make(map[string]string, len(iOpts))
  575. for k, v := range iOpts {
  576. n.ipamOptions[k] = v.(string)
  577. }
  578. }
  579. }
  580. if v, ok := netMap["generic"]; ok {
  581. n.generic = v.(map[string]interface{})
  582. // Restore opts in their map[string]string form
  583. if v, ok := n.generic[netlabel.GenericData]; ok {
  584. var lmap map[string]string
  585. ba, err := json.Marshal(v)
  586. if err != nil {
  587. return err
  588. }
  589. if err := json.Unmarshal(ba, &lmap); err != nil {
  590. return err
  591. }
  592. n.generic[netlabel.GenericData] = lmap
  593. }
  594. }
  595. if v, ok := netMap["persist"]; ok {
  596. n.persist = v.(bool)
  597. }
  598. if v, ok := netMap["postIPv6"]; ok {
  599. n.postIPv6 = v.(bool)
  600. }
  601. if v, ok := netMap["ipamType"]; ok {
  602. n.ipamType = v.(string)
  603. } else {
  604. n.ipamType = ipamapi.DefaultIPAM
  605. }
  606. if v, ok := netMap["addrSpace"]; ok {
  607. n.addrSpace = v.(string)
  608. }
  609. if v, ok := netMap["ipamV4Config"]; ok {
  610. if err := json.Unmarshal([]byte(v.(string)), &n.ipamV4Config); err != nil {
  611. return err
  612. }
  613. }
  614. if v, ok := netMap["ipamV4Info"]; ok {
  615. if err := json.Unmarshal([]byte(v.(string)), &n.ipamV4Info); err != nil {
  616. return err
  617. }
  618. }
  619. if v, ok := netMap["ipamV6Config"]; ok {
  620. if err := json.Unmarshal([]byte(v.(string)), &n.ipamV6Config); err != nil {
  621. return err
  622. }
  623. }
  624. if v, ok := netMap["ipamV6Info"]; ok {
  625. if err := json.Unmarshal([]byte(v.(string)), &n.ipamV6Info); err != nil {
  626. return err
  627. }
  628. }
  629. if v, ok := netMap["internal"]; ok {
  630. n.internal = v.(bool)
  631. }
  632. if v, ok := netMap["attachable"]; ok {
  633. n.attachable = v.(bool)
  634. }
  635. if s, ok := netMap["scope"]; ok {
  636. n.scope = s.(string)
  637. }
  638. if v, ok := netMap["inDelete"]; ok {
  639. n.inDelete = v.(bool)
  640. }
  641. if v, ok := netMap["ingress"]; ok {
  642. n.ingress = v.(bool)
  643. }
  644. if v, ok := netMap["configOnly"]; ok {
  645. n.configOnly = v.(bool)
  646. }
  647. if v, ok := netMap["configFrom"]; ok {
  648. n.configFrom = v.(string)
  649. }
  650. if v, ok := netMap["loadBalancerIP"]; ok {
  651. n.loadBalancerIP = net.ParseIP(v.(string))
  652. }
  653. n.loadBalancerMode = loadBalancerModeDefault
  654. if v, ok := netMap["loadBalancerMode"]; ok {
  655. n.loadBalancerMode = v.(string)
  656. }
  657. // Reconcile old networks with the recently added `--ipv6` flag
  658. if !n.enableIPv6 {
  659. n.enableIPv6 = len(n.ipamV6Info) > 0
  660. }
  661. return nil
  662. }
  663. // NetworkOption is an option setter function type used to pass various options to
  664. // NewNetwork method. The various setter functions of type NetworkOption are
  665. // provided by libnetwork, they look like NetworkOptionXXXX(...)
  666. type NetworkOption func(n *network)
  667. // NetworkOptionGeneric function returns an option setter for a Generic option defined
  668. // in a Dictionary of Key-Value pair
  669. func NetworkOptionGeneric(generic map[string]interface{}) NetworkOption {
  670. return func(n *network) {
  671. if n.generic == nil {
  672. n.generic = make(map[string]interface{})
  673. }
  674. if val, ok := generic[netlabel.EnableIPv6]; ok {
  675. n.enableIPv6 = val.(bool)
  676. }
  677. if val, ok := generic[netlabel.Internal]; ok {
  678. n.internal = val.(bool)
  679. }
  680. for k, v := range generic {
  681. n.generic[k] = v
  682. }
  683. }
  684. }
  685. // NetworkOptionIngress returns an option setter to indicate if a network is
  686. // an ingress network.
  687. func NetworkOptionIngress(ingress bool) NetworkOption {
  688. return func(n *network) {
  689. n.ingress = ingress
  690. }
  691. }
  692. // NetworkOptionPersist returns an option setter to set persistence policy for a network
  693. func NetworkOptionPersist(persist bool) NetworkOption {
  694. return func(n *network) {
  695. n.persist = persist
  696. }
  697. }
  698. // NetworkOptionEnableIPv6 returns an option setter to explicitly configure IPv6
  699. func NetworkOptionEnableIPv6(enableIPv6 bool) NetworkOption {
  700. return func(n *network) {
  701. if n.generic == nil {
  702. n.generic = make(map[string]interface{})
  703. }
  704. n.enableIPv6 = enableIPv6
  705. n.generic[netlabel.EnableIPv6] = enableIPv6
  706. }
  707. }
  708. // NetworkOptionInternalNetwork returns an option setter to config the network
  709. // to be internal which disables default gateway service
  710. func NetworkOptionInternalNetwork() NetworkOption {
  711. return func(n *network) {
  712. if n.generic == nil {
  713. n.generic = make(map[string]interface{})
  714. }
  715. n.internal = true
  716. n.generic[netlabel.Internal] = true
  717. }
  718. }
  719. // NetworkOptionAttachable returns an option setter to set attachable for a network
  720. func NetworkOptionAttachable(attachable bool) NetworkOption {
  721. return func(n *network) {
  722. n.attachable = attachable
  723. }
  724. }
  725. // NetworkOptionScope returns an option setter to overwrite the network's scope.
  726. // By default the network's scope is set to the network driver's datascope.
  727. func NetworkOptionScope(scope string) NetworkOption {
  728. return func(n *network) {
  729. n.scope = scope
  730. }
  731. }
  732. // NetworkOptionIpam function returns an option setter for the ipam configuration for this network
  733. func NetworkOptionIpam(ipamDriver string, addrSpace string, ipV4 []*IpamConf, ipV6 []*IpamConf, opts map[string]string) NetworkOption {
  734. return func(n *network) {
  735. if ipamDriver != "" {
  736. n.ipamType = ipamDriver
  737. if ipamDriver == ipamapi.DefaultIPAM {
  738. n.ipamType = defaultIpamForNetworkType(n.Type())
  739. }
  740. }
  741. n.ipamOptions = opts
  742. n.addrSpace = addrSpace
  743. n.ipamV4Config = ipV4
  744. n.ipamV6Config = ipV6
  745. }
  746. }
  747. // NetworkOptionLBEndpoint function returns an option setter for the configuration of the load balancer endpoint for this network
  748. func NetworkOptionLBEndpoint(ip net.IP) NetworkOption {
  749. return func(n *network) {
  750. n.loadBalancerIP = ip
  751. }
  752. }
  753. // NetworkOptionDriverOpts function returns an option setter for any driver parameter described by a map
  754. func NetworkOptionDriverOpts(opts map[string]string) NetworkOption {
  755. return func(n *network) {
  756. if n.generic == nil {
  757. n.generic = make(map[string]interface{})
  758. }
  759. if opts == nil {
  760. opts = make(map[string]string)
  761. }
  762. // Store the options
  763. n.generic[netlabel.GenericData] = opts
  764. }
  765. }
  766. // NetworkOptionLabels function returns an option setter for labels specific to a network
  767. func NetworkOptionLabels(labels map[string]string) NetworkOption {
  768. return func(n *network) {
  769. n.labels = labels
  770. }
  771. }
  772. // NetworkOptionDynamic function returns an option setter for dynamic option for a network
  773. func NetworkOptionDynamic() NetworkOption {
  774. return func(n *network) {
  775. n.dynamic = true
  776. }
  777. }
  778. // NetworkOptionDeferIPv6Alloc instructs the network to defer the IPV6 address allocation until after the endpoint has been created
  779. // It is being provided to support the specific docker daemon flags where user can deterministically assign an IPv6 address
  780. // to a container as combination of fixed-cidr-v6 + mac-address
  781. // TODO: Remove this option setter once we support endpoint ipam options
  782. func NetworkOptionDeferIPv6Alloc(enable bool) NetworkOption {
  783. return func(n *network) {
  784. n.postIPv6 = enable
  785. }
  786. }
  787. // NetworkOptionConfigOnly tells controller this network is
  788. // a configuration only network. It serves as a configuration
  789. // for other networks.
  790. func NetworkOptionConfigOnly() NetworkOption {
  791. return func(n *network) {
  792. n.configOnly = true
  793. }
  794. }
  795. // NetworkOptionConfigFrom tells controller to pick the
  796. // network configuration from a configuration only network
  797. func NetworkOptionConfigFrom(name string) NetworkOption {
  798. return func(n *network) {
  799. n.configFrom = name
  800. }
  801. }
  802. func (n *network) processOptions(options ...NetworkOption) {
  803. for _, opt := range options {
  804. if opt != nil {
  805. opt(n)
  806. }
  807. }
  808. }
  809. type networkDeleteParams struct {
  810. rmLBEndpoint bool
  811. }
  812. // NetworkDeleteOption is a type for optional parameters to pass to the
  813. // network.Delete() function.
  814. type NetworkDeleteOption func(p *networkDeleteParams)
  815. // NetworkDeleteOptionRemoveLB informs a network.Delete() operation that should
  816. // remove the load balancer endpoint for this network. Note that the Delete()
  817. // method will automatically remove a load balancing endpoint for most networks
  818. // when the network is otherwise empty. However, this does not occur for some
  819. // networks. In particular, networks marked as ingress (which are supposed to
  820. // be more permanent than other overlay networks) won't automatically remove
  821. // the LB endpoint on Delete(). This method allows for explicit removal of
  822. // such networks provided there are no other endpoints present in the network.
  823. // If the network still has non-LB endpoints present, Delete() will not
  824. // remove the LB endpoint and will return an error.
  825. func NetworkDeleteOptionRemoveLB(p *networkDeleteParams) {
  826. p.rmLBEndpoint = true
  827. }
  828. func (n *network) resolveDriver(name string, load bool) (driverapi.Driver, driverapi.Capability, error) {
  829. c := n.getController()
  830. // Check if a driver for the specified network type is available
  831. d, cap := c.drvRegistry.Driver(name)
  832. if d == nil {
  833. if load {
  834. err := c.loadDriver(name)
  835. if err != nil {
  836. return nil, driverapi.Capability{}, err
  837. }
  838. d, cap = c.drvRegistry.Driver(name)
  839. if d == nil {
  840. return nil, driverapi.Capability{}, fmt.Errorf("could not resolve driver %s in registry", name)
  841. }
  842. } else {
  843. // don't fail if driver loading is not required
  844. return nil, driverapi.Capability{}, nil
  845. }
  846. }
  847. return d, cap, nil
  848. }
  849. func (n *network) driverIsMultihost() bool {
  850. _, cap, err := n.resolveDriver(n.networkType, true)
  851. if err != nil {
  852. return false
  853. }
  854. return cap.ConnectivityScope == datastore.GlobalScope
  855. }
  856. func (n *network) driver(load bool) (driverapi.Driver, error) {
  857. d, cap, err := n.resolveDriver(n.networkType, load)
  858. if err != nil {
  859. return nil, err
  860. }
  861. n.mu.Lock()
  862. // If load is not required, driver, cap and err may all be nil
  863. if n.scope == "" {
  864. n.scope = cap.DataScope
  865. }
  866. if n.dynamic {
  867. // If the network is dynamic, then it is swarm
  868. // scoped regardless of the backing driver.
  869. n.scope = datastore.SwarmScope
  870. }
  871. n.mu.Unlock()
  872. return d, nil
  873. }
  874. func (n *network) Delete(options ...NetworkDeleteOption) error {
  875. var params networkDeleteParams
  876. for _, opt := range options {
  877. opt(&params)
  878. }
  879. return n.delete(false, params.rmLBEndpoint)
  880. }
  881. // This function gets called in 3 ways:
  882. // - Delete() -- (false, false)
  883. // remove if endpoint count == 0 or endpoint count == 1 and
  884. // there is a load balancer IP
  885. // - Delete(libnetwork.NetworkDeleteOptionRemoveLB) -- (false, true)
  886. // remove load balancer and network if endpoint count == 1
  887. // - controller.networkCleanup() -- (true, true)
  888. // remove the network no matter what
  889. func (n *network) delete(force bool, rmLBEndpoint bool) error {
  890. n.mu.Lock()
  891. c := n.ctrlr
  892. name := n.name
  893. id := n.id
  894. n.mu.Unlock()
  895. c.networkLocker.Lock(id)
  896. defer c.networkLocker.Unlock(id) //nolint:errcheck
  897. n, err := c.getNetworkFromStore(id)
  898. if err != nil {
  899. return &UnknownNetworkError{name: name, id: id}
  900. }
  901. // Only remove ingress on force removal or explicit LB endpoint removal
  902. if n.ingress && !force && !rmLBEndpoint {
  903. return &ActiveEndpointsError{name: n.name, id: n.id}
  904. }
  905. // Check that the network is empty
  906. var emptyCount uint64
  907. if n.hasLoadBalancerEndpoint() {
  908. emptyCount = 1
  909. }
  910. if !force && n.getEpCnt().EndpointCnt() > emptyCount {
  911. if n.configOnly {
  912. return types.ForbiddenErrorf("configuration network %q is in use", n.Name())
  913. }
  914. return &ActiveEndpointsError{name: n.name, id: n.id}
  915. }
  916. if n.hasLoadBalancerEndpoint() {
  917. // If we got to this point, then the following must hold:
  918. // * force is true OR endpoint count == 1
  919. if err := n.deleteLoadBalancerSandbox(); err != nil {
  920. if !force {
  921. return err
  922. }
  923. // continue deletion when force is true even on error
  924. log.G(context.TODO()).Warnf("Error deleting load balancer sandbox: %v", err)
  925. }
  926. // Reload the network from the store to update the epcnt.
  927. n, err = c.getNetworkFromStore(id)
  928. if err != nil {
  929. return &UnknownNetworkError{name: name, id: id}
  930. }
  931. }
  932. // Up to this point, errors that we returned were recoverable.
  933. // From here on, any errors leave us in an inconsistent state.
  934. // This is unfortunate, but there isn't a safe way to
  935. // reconstitute a load-balancer endpoint after removing it.
  936. // Mark the network for deletion
  937. n.inDelete = true
  938. if err = c.updateToStore(n); err != nil {
  939. return fmt.Errorf("error marking network %s (%s) for deletion: %v", n.Name(), n.ID(), err)
  940. }
  941. if n.ConfigFrom() != "" {
  942. if t, err := c.getConfigNetwork(n.ConfigFrom()); err == nil {
  943. if err := t.getEpCnt().DecEndpointCnt(); err != nil {
  944. log.G(context.TODO()).Warnf("Failed to update reference count for configuration network %q on removal of network %q: %v",
  945. t.Name(), n.Name(), err)
  946. }
  947. } else {
  948. log.G(context.TODO()).Warnf("Could not find configuration network %q during removal of network %q", n.configFrom, n.Name())
  949. }
  950. }
  951. if n.configOnly {
  952. goto removeFromStore
  953. }
  954. n.ipamRelease()
  955. // We are about to delete the network. Leave the gossip
  956. // cluster for the network to stop all incoming network
  957. // specific gossip updates before cleaning up all the service
  958. // bindings for the network. But cleanup service binding
  959. // before deleting the network from the store since service
  960. // bindings cleanup requires the network in the store.
  961. n.cancelDriverWatches()
  962. if err = n.leaveCluster(); err != nil {
  963. log.G(context.TODO()).Errorf("Failed leaving network %s from the agent cluster: %v", n.Name(), err)
  964. }
  965. // Cleanup the service discovery for this network
  966. c.cleanupServiceDiscovery(n.ID())
  967. // Cleanup the load balancer. On Windows this call is required
  968. // to remove remote loadbalancers in VFP, and must be performed before
  969. // dataplane network deletion.
  970. if runtime.GOOS == "windows" {
  971. c.cleanupServiceBindings(n.ID())
  972. }
  973. // Delete the network from the dataplane
  974. if err = n.deleteNetwork(); err != nil {
  975. if !force {
  976. return err
  977. }
  978. log.G(context.TODO()).Debugf("driver failed to delete stale network %s (%s): %v", n.Name(), n.ID(), err)
  979. }
  980. removeFromStore:
  981. // deleteFromStore performs an atomic delete operation and the
  982. // network.epCnt will help prevent any possible
  983. // race between endpoint join and network delete
  984. if err = c.deleteFromStore(n.getEpCnt()); err != nil {
  985. if !force {
  986. return fmt.Errorf("error deleting network endpoint count from store: %v", err)
  987. }
  988. log.G(context.TODO()).Debugf("Error deleting endpoint count from store for stale network %s (%s) for deletion: %v", n.Name(), n.ID(), err)
  989. }
  990. if err = c.deleteFromStore(n); err != nil {
  991. return fmt.Errorf("error deleting network from store: %v", err)
  992. }
  993. return nil
  994. }
  995. func (n *network) deleteNetwork() error {
  996. d, err := n.driver(true)
  997. if err != nil {
  998. return fmt.Errorf("failed deleting network: %v", err)
  999. }
  1000. if err := d.DeleteNetwork(n.ID()); err != nil {
  1001. // Forbidden Errors should be honored
  1002. if _, ok := err.(types.ForbiddenError); ok {
  1003. return err
  1004. }
  1005. if _, ok := err.(types.MaskableError); !ok {
  1006. log.G(context.TODO()).Warnf("driver error deleting network %s : %v", n.name, err)
  1007. }
  1008. }
  1009. for _, resolver := range n.resolver {
  1010. resolver.Stop()
  1011. }
  1012. return nil
  1013. }
  1014. func (n *network) addEndpoint(ep *Endpoint) error {
  1015. d, err := n.driver(true)
  1016. if err != nil {
  1017. return fmt.Errorf("failed to add endpoint: %v", err)
  1018. }
  1019. err = d.CreateEndpoint(n.id, ep.id, ep.Interface(), ep.generic)
  1020. if err != nil {
  1021. return types.InternalErrorf("failed to create endpoint %s on network %s: %v",
  1022. ep.Name(), n.Name(), err)
  1023. }
  1024. return nil
  1025. }
  1026. func (n *network) CreateEndpoint(name string, options ...EndpointOption) (*Endpoint, error) {
  1027. var err error
  1028. if !config.IsValidName(name) {
  1029. return nil, ErrInvalidName(name)
  1030. }
  1031. if n.ConfigOnly() {
  1032. return nil, types.ForbiddenErrorf("cannot create endpoint on configuration-only network")
  1033. }
  1034. if _, err = n.EndpointByName(name); err == nil {
  1035. return nil, types.ForbiddenErrorf("endpoint with name %s already exists in network %s", name, n.Name())
  1036. }
  1037. n.ctrlr.networkLocker.Lock(n.id)
  1038. defer n.ctrlr.networkLocker.Unlock(n.id) //nolint:errcheck
  1039. return n.createEndpoint(name, options...)
  1040. }
  1041. func (n *network) createEndpoint(name string, options ...EndpointOption) (*Endpoint, error) {
  1042. var err error
  1043. ep := &Endpoint{name: name, generic: make(map[string]interface{}), iface: &endpointInterface{}}
  1044. ep.id = stringid.GenerateRandomID()
  1045. // Initialize ep.network with a possibly stale copy of n. We need this to get network from
  1046. // store. But once we get it from store we will have the most uptodate copy possibly.
  1047. ep.network = n
  1048. ep.network, err = ep.getNetworkFromStore()
  1049. if err != nil {
  1050. log.G(context.TODO()).Errorf("failed to get network during CreateEndpoint: %v", err)
  1051. return nil, err
  1052. }
  1053. n = ep.network
  1054. ep.processOptions(options...)
  1055. for _, llIPNet := range ep.Iface().LinkLocalAddresses() {
  1056. if !llIPNet.IP.IsLinkLocalUnicast() {
  1057. return nil, types.BadRequestErrorf("invalid link local IP address: %v", llIPNet.IP)
  1058. }
  1059. }
  1060. if opt, ok := ep.generic[netlabel.MacAddress]; ok {
  1061. if mac, ok := opt.(net.HardwareAddr); ok {
  1062. ep.iface.mac = mac
  1063. }
  1064. }
  1065. ipam, capability, err := n.getController().getIPAMDriver(n.ipamType)
  1066. if err != nil {
  1067. return nil, err
  1068. }
  1069. if capability.RequiresMACAddress {
  1070. if ep.iface.mac == nil {
  1071. ep.iface.mac = netutils.GenerateRandomMAC()
  1072. }
  1073. if ep.ipamOptions == nil {
  1074. ep.ipamOptions = make(map[string]string)
  1075. }
  1076. ep.ipamOptions[netlabel.MacAddress] = ep.iface.mac.String()
  1077. }
  1078. if err = ep.assignAddress(ipam, true, n.enableIPv6 && !n.postIPv6); err != nil {
  1079. return nil, err
  1080. }
  1081. defer func() {
  1082. if err != nil {
  1083. ep.releaseAddress()
  1084. }
  1085. }()
  1086. if err = n.addEndpoint(ep); err != nil {
  1087. return nil, err
  1088. }
  1089. defer func() {
  1090. if err != nil {
  1091. if e := ep.deleteEndpoint(false); e != nil {
  1092. log.G(context.TODO()).Warnf("cleaning up endpoint failed %s : %v", name, e)
  1093. }
  1094. }
  1095. }()
  1096. // We should perform updateToStore call right after addEndpoint
  1097. // in order to have iface properly configured
  1098. if err = n.getController().updateToStore(ep); err != nil {
  1099. return nil, err
  1100. }
  1101. defer func() {
  1102. if err != nil {
  1103. if e := n.getController().deleteFromStore(ep); e != nil {
  1104. log.G(context.TODO()).Warnf("error rolling back endpoint %s from store: %v", name, e)
  1105. }
  1106. }
  1107. }()
  1108. if err = ep.assignAddress(ipam, false, n.enableIPv6 && n.postIPv6); err != nil {
  1109. return nil, err
  1110. }
  1111. // Watch for service records
  1112. n.getController().watchSvcRecord(ep)
  1113. defer func() {
  1114. if err != nil {
  1115. n.getController().unWatchSvcRecord(ep)
  1116. }
  1117. }()
  1118. // Increment endpoint count to indicate completion of endpoint addition
  1119. if err = n.getEpCnt().IncEndpointCnt(); err != nil {
  1120. return nil, err
  1121. }
  1122. return ep, nil
  1123. }
  1124. func (n *network) Endpoints() []*Endpoint {
  1125. endpoints, err := n.getEndpointsFromStore()
  1126. if err != nil {
  1127. log.G(context.TODO()).Error(err)
  1128. }
  1129. return endpoints
  1130. }
  1131. func (n *network) WalkEndpoints(walker EndpointWalker) {
  1132. for _, e := range n.Endpoints() {
  1133. if walker(e) {
  1134. return
  1135. }
  1136. }
  1137. }
  1138. func (n *network) EndpointByName(name string) (*Endpoint, error) {
  1139. if name == "" {
  1140. return nil, ErrInvalidName(name)
  1141. }
  1142. var e *Endpoint
  1143. s := func(current *Endpoint) bool {
  1144. if current.Name() == name {
  1145. e = current
  1146. return true
  1147. }
  1148. return false
  1149. }
  1150. n.WalkEndpoints(s)
  1151. if e == nil {
  1152. return nil, ErrNoSuchEndpoint(name)
  1153. }
  1154. return e, nil
  1155. }
  1156. func (n *network) EndpointByID(id string) (*Endpoint, error) {
  1157. if id == "" {
  1158. return nil, ErrInvalidID(id)
  1159. }
  1160. ep, err := n.getEndpointFromStore(id)
  1161. if err != nil {
  1162. return nil, ErrNoSuchEndpoint(id)
  1163. }
  1164. return ep, nil
  1165. }
  1166. func (n *network) updateSvcRecord(ep *Endpoint, localEps []*Endpoint, isAdd bool) {
  1167. var ipv6 net.IP
  1168. epName := ep.Name()
  1169. if iface := ep.Iface(); iface != nil && iface.Address() != nil {
  1170. myAliases := ep.MyAliases()
  1171. if iface.AddressIPv6() != nil {
  1172. ipv6 = iface.AddressIPv6().IP
  1173. }
  1174. serviceID := ep.svcID
  1175. if serviceID == "" {
  1176. serviceID = ep.ID()
  1177. }
  1178. if isAdd {
  1179. // If anonymous endpoint has an alias use the first alias
  1180. // for ip->name mapping. Not having the reverse mapping
  1181. // breaks some apps
  1182. if ep.isAnonymous() {
  1183. if len(myAliases) > 0 {
  1184. n.addSvcRecords(ep.ID(), myAliases[0], serviceID, iface.Address().IP, ipv6, true, "updateSvcRecord")
  1185. }
  1186. } else {
  1187. n.addSvcRecords(ep.ID(), epName, serviceID, iface.Address().IP, ipv6, true, "updateSvcRecord")
  1188. }
  1189. for _, alias := range myAliases {
  1190. n.addSvcRecords(ep.ID(), alias, serviceID, iface.Address().IP, ipv6, false, "updateSvcRecord")
  1191. }
  1192. } else {
  1193. if ep.isAnonymous() {
  1194. if len(myAliases) > 0 {
  1195. n.deleteSvcRecords(ep.ID(), myAliases[0], serviceID, iface.Address().IP, ipv6, true, "updateSvcRecord")
  1196. }
  1197. } else {
  1198. n.deleteSvcRecords(ep.ID(), epName, serviceID, iface.Address().IP, ipv6, true, "updateSvcRecord")
  1199. }
  1200. for _, alias := range myAliases {
  1201. n.deleteSvcRecords(ep.ID(), alias, serviceID, iface.Address().IP, ipv6, false, "updateSvcRecord")
  1202. }
  1203. }
  1204. }
  1205. }
  1206. func addIPToName(ipMap *setmatrix.SetMatrix[ipInfo], name, serviceID string, ip net.IP) {
  1207. reverseIP := netutils.ReverseIP(ip.String())
  1208. ipMap.Insert(reverseIP, ipInfo{
  1209. name: name,
  1210. serviceID: serviceID,
  1211. })
  1212. }
  1213. func delIPToName(ipMap *setmatrix.SetMatrix[ipInfo], name, serviceID string, ip net.IP) {
  1214. reverseIP := netutils.ReverseIP(ip.String())
  1215. ipMap.Remove(reverseIP, ipInfo{
  1216. name: name,
  1217. serviceID: serviceID,
  1218. })
  1219. }
  1220. func addNameToIP(svcMap *setmatrix.SetMatrix[svcMapEntry], name, serviceID string, epIP net.IP) {
  1221. // Since DNS name resolution is case-insensitive, Use the lower-case form
  1222. // of the name as the key into svcMap
  1223. lowerCaseName := strings.ToLower(name)
  1224. svcMap.Insert(lowerCaseName, svcMapEntry{
  1225. ip: epIP.String(),
  1226. serviceID: serviceID,
  1227. })
  1228. }
  1229. func delNameToIP(svcMap *setmatrix.SetMatrix[svcMapEntry], name, serviceID string, epIP net.IP) {
  1230. lowerCaseName := strings.ToLower(name)
  1231. svcMap.Remove(lowerCaseName, svcMapEntry{
  1232. ip: epIP.String(),
  1233. serviceID: serviceID,
  1234. })
  1235. }
  1236. func (n *network) addSvcRecords(eID, name, serviceID string, epIP, epIPv6 net.IP, ipMapUpdate bool, method string) {
  1237. // Do not add service names for ingress network as this is a
  1238. // routing only network
  1239. if n.ingress {
  1240. return
  1241. }
  1242. networkID := n.ID()
  1243. log.G(context.TODO()).Debugf("%s (%.7s).addSvcRecords(%s, %s, %s, %t) %s sid:%s", eID, networkID, name, epIP, epIPv6, ipMapUpdate, method, serviceID)
  1244. c := n.getController()
  1245. c.mu.Lock()
  1246. defer c.mu.Unlock()
  1247. sr, ok := c.svcRecords[networkID]
  1248. if !ok {
  1249. sr = &svcInfo{}
  1250. c.svcRecords[networkID] = sr
  1251. }
  1252. if ipMapUpdate {
  1253. addIPToName(&sr.ipMap, name, serviceID, epIP)
  1254. if epIPv6 != nil {
  1255. addIPToName(&sr.ipMap, name, serviceID, epIPv6)
  1256. }
  1257. }
  1258. addNameToIP(&sr.svcMap, name, serviceID, epIP)
  1259. if epIPv6 != nil {
  1260. addNameToIP(&sr.svcIPv6Map, name, serviceID, epIPv6)
  1261. }
  1262. }
  1263. func (n *network) deleteSvcRecords(eID, name, serviceID string, epIP net.IP, epIPv6 net.IP, ipMapUpdate bool, method string) {
  1264. // Do not delete service names from ingress network as this is a
  1265. // routing only network
  1266. if n.ingress {
  1267. return
  1268. }
  1269. networkID := n.ID()
  1270. log.G(context.TODO()).Debugf("%s (%.7s).deleteSvcRecords(%s, %s, %s, %t) %s sid:%s ", eID, networkID, name, epIP, epIPv6, ipMapUpdate, method, serviceID)
  1271. c := n.getController()
  1272. c.mu.Lock()
  1273. defer c.mu.Unlock()
  1274. sr, ok := c.svcRecords[networkID]
  1275. if !ok {
  1276. return
  1277. }
  1278. if ipMapUpdate {
  1279. delIPToName(&sr.ipMap, name, serviceID, epIP)
  1280. if epIPv6 != nil {
  1281. delIPToName(&sr.ipMap, name, serviceID, epIPv6)
  1282. }
  1283. }
  1284. delNameToIP(&sr.svcMap, name, serviceID, epIP)
  1285. if epIPv6 != nil {
  1286. delNameToIP(&sr.svcIPv6Map, name, serviceID, epIPv6)
  1287. }
  1288. }
  1289. func (n *network) getSvcRecords(ep *Endpoint) []etchosts.Record {
  1290. n.mu.Lock()
  1291. defer n.mu.Unlock()
  1292. if ep == nil {
  1293. return nil
  1294. }
  1295. var recs []etchosts.Record
  1296. epName := ep.Name()
  1297. n.ctrlr.mu.Lock()
  1298. defer n.ctrlr.mu.Unlock()
  1299. sr, ok := n.ctrlr.svcRecords[n.id]
  1300. if !ok {
  1301. return nil
  1302. }
  1303. svcMapKeys := sr.svcMap.Keys()
  1304. // Loop on service names on this network
  1305. for _, k := range svcMapKeys {
  1306. if strings.Split(k, ".")[0] == epName {
  1307. continue
  1308. }
  1309. // Get all the IPs associated to this service
  1310. mapEntryList, ok := sr.svcMap.Get(k)
  1311. if !ok {
  1312. // The key got deleted
  1313. continue
  1314. }
  1315. if len(mapEntryList) == 0 {
  1316. log.G(context.TODO()).Warnf("Found empty list of IP addresses for service %s on network %s (%s)", k, n.name, n.id)
  1317. continue
  1318. }
  1319. recs = append(recs, etchosts.Record{
  1320. Hosts: k,
  1321. IP: mapEntryList[0].ip,
  1322. })
  1323. }
  1324. return recs
  1325. }
  1326. func (n *network) getController() *Controller {
  1327. n.mu.Lock()
  1328. defer n.mu.Unlock()
  1329. return n.ctrlr
  1330. }
  1331. func (n *network) ipamAllocate() error {
  1332. if n.hasSpecialDriver() {
  1333. return nil
  1334. }
  1335. ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
  1336. if err != nil {
  1337. return err
  1338. }
  1339. if n.addrSpace == "" {
  1340. if n.addrSpace, err = n.deriveAddressSpace(); err != nil {
  1341. return err
  1342. }
  1343. }
  1344. err = n.ipamAllocateVersion(4, ipam)
  1345. if err != nil {
  1346. return err
  1347. }
  1348. defer func() {
  1349. if err != nil {
  1350. n.ipamReleaseVersion(4, ipam)
  1351. }
  1352. }()
  1353. if !n.enableIPv6 {
  1354. return nil
  1355. }
  1356. err = n.ipamAllocateVersion(6, ipam)
  1357. return err
  1358. }
  1359. func (n *network) requestPoolHelper(ipam ipamapi.Ipam, addressSpace, preferredPool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error) {
  1360. for {
  1361. poolID, pool, meta, err := ipam.RequestPool(addressSpace, preferredPool, subPool, options, v6)
  1362. if err != nil {
  1363. return "", nil, nil, err
  1364. }
  1365. // If the network belongs to global scope or the pool was
  1366. // explicitly chosen or it is invalid, do not perform the overlap check.
  1367. if n.Scope() == datastore.GlobalScope || preferredPool != "" || !types.IsIPNetValid(pool) {
  1368. return poolID, pool, meta, nil
  1369. }
  1370. // Check for overlap and if none found, we have found the right pool.
  1371. if _, err := netutils.FindAvailableNetwork([]*net.IPNet{pool}); err == nil {
  1372. return poolID, pool, meta, nil
  1373. }
  1374. // Pool obtained in this iteration is
  1375. // overlapping. Hold onto the pool and don't release
  1376. // it yet, because we don't want ipam to give us back
  1377. // the same pool over again. But make sure we still do
  1378. // a deferred release when we have either obtained a
  1379. // non-overlapping pool or ran out of pre-defined
  1380. // pools.
  1381. defer func() {
  1382. if err := ipam.ReleasePool(poolID); err != nil {
  1383. log.G(context.TODO()).Warnf("Failed to release overlapping pool %s while returning from pool request helper for network %s", pool, n.Name())
  1384. }
  1385. }()
  1386. // If this is a preferred pool request and the network
  1387. // is local scope and there is an overlap, we fail the
  1388. // network creation right here. The pool will be
  1389. // released in the defer.
  1390. if preferredPool != "" {
  1391. return "", nil, nil, fmt.Errorf("requested subnet %s overlaps in the host", preferredPool)
  1392. }
  1393. }
  1394. }
  1395. func (n *network) ipamAllocateVersion(ipVer int, ipam ipamapi.Ipam) error {
  1396. var (
  1397. cfgList *[]*IpamConf
  1398. infoList *[]*IpamInfo
  1399. err error
  1400. )
  1401. switch ipVer {
  1402. case 4:
  1403. cfgList = &n.ipamV4Config
  1404. infoList = &n.ipamV4Info
  1405. case 6:
  1406. cfgList = &n.ipamV6Config
  1407. infoList = &n.ipamV6Info
  1408. default:
  1409. return types.InternalErrorf("incorrect ip version passed to ipam allocate: %d", ipVer)
  1410. }
  1411. if len(*cfgList) == 0 {
  1412. *cfgList = []*IpamConf{{}}
  1413. }
  1414. *infoList = make([]*IpamInfo, len(*cfgList))
  1415. log.G(context.TODO()).Debugf("Allocating IPv%d pools for network %s (%s)", ipVer, n.Name(), n.ID())
  1416. for i, cfg := range *cfgList {
  1417. if err = cfg.Validate(); err != nil {
  1418. return err
  1419. }
  1420. d := &IpamInfo{}
  1421. (*infoList)[i] = d
  1422. d.AddressSpace = n.addrSpace
  1423. d.PoolID, d.Pool, d.Meta, err = n.requestPoolHelper(ipam, n.addrSpace, cfg.PreferredPool, cfg.SubPool, n.ipamOptions, ipVer == 6)
  1424. if err != nil {
  1425. return err
  1426. }
  1427. defer func() {
  1428. if err != nil {
  1429. if err := ipam.ReleasePool(d.PoolID); err != nil {
  1430. log.G(context.TODO()).Warnf("Failed to release address pool %s after failure to create network %s (%s)", d.PoolID, n.Name(), n.ID())
  1431. }
  1432. }
  1433. }()
  1434. if gws, ok := d.Meta[netlabel.Gateway]; ok {
  1435. if d.Gateway, err = types.ParseCIDR(gws); err != nil {
  1436. return types.BadRequestErrorf("failed to parse gateway address (%v) returned by ipam driver: %v", gws, err)
  1437. }
  1438. }
  1439. // If user requested a specific gateway, libnetwork will allocate it
  1440. // irrespective of whether ipam driver returned a gateway already.
  1441. // If none of the above is true, libnetwork will allocate one.
  1442. if cfg.Gateway != "" || d.Gateway == nil {
  1443. gatewayOpts := map[string]string{
  1444. ipamapi.RequestAddressType: netlabel.Gateway,
  1445. }
  1446. if d.Gateway, _, err = ipam.RequestAddress(d.PoolID, net.ParseIP(cfg.Gateway), gatewayOpts); err != nil {
  1447. return types.InternalErrorf("failed to allocate gateway (%v): %v", cfg.Gateway, err)
  1448. }
  1449. }
  1450. // Auxiliary addresses must be part of the master address pool
  1451. // If they fall into the container addressable pool, libnetwork will reserve them
  1452. if cfg.AuxAddresses != nil {
  1453. var ip net.IP
  1454. d.IPAMData.AuxAddresses = make(map[string]*net.IPNet, len(cfg.AuxAddresses))
  1455. for k, v := range cfg.AuxAddresses {
  1456. if ip = net.ParseIP(v); ip == nil {
  1457. return types.BadRequestErrorf("non parsable secondary ip address (%s:%s) passed for network %s", k, v, n.Name())
  1458. }
  1459. if !d.Pool.Contains(ip) {
  1460. return types.ForbiddenErrorf("auxiliary address: (%s:%s) must belong to the master pool: %s", k, v, d.Pool)
  1461. }
  1462. // Attempt reservation in the container addressable pool, silent the error if address does not belong to that pool
  1463. if d.IPAMData.AuxAddresses[k], _, err = ipam.RequestAddress(d.PoolID, ip, nil); err != nil && err != ipamapi.ErrIPOutOfRange {
  1464. return types.InternalErrorf("failed to allocate secondary ip address (%s:%s): %v", k, v, err)
  1465. }
  1466. }
  1467. }
  1468. }
  1469. return nil
  1470. }
  1471. func (n *network) ipamRelease() {
  1472. if n.hasSpecialDriver() {
  1473. return
  1474. }
  1475. ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
  1476. if err != nil {
  1477. log.G(context.TODO()).Warnf("Failed to retrieve ipam driver to release address pool(s) on delete of network %s (%s): %v", n.Name(), n.ID(), err)
  1478. return
  1479. }
  1480. n.ipamReleaseVersion(4, ipam)
  1481. n.ipamReleaseVersion(6, ipam)
  1482. }
  1483. func (n *network) ipamReleaseVersion(ipVer int, ipam ipamapi.Ipam) {
  1484. var infoList *[]*IpamInfo
  1485. switch ipVer {
  1486. case 4:
  1487. infoList = &n.ipamV4Info
  1488. case 6:
  1489. infoList = &n.ipamV6Info
  1490. default:
  1491. log.G(context.TODO()).Warnf("incorrect ip version passed to ipam release: %d", ipVer)
  1492. return
  1493. }
  1494. if len(*infoList) == 0 {
  1495. return
  1496. }
  1497. log.G(context.TODO()).Debugf("releasing IPv%d pools from network %s (%s)", ipVer, n.Name(), n.ID())
  1498. for _, d := range *infoList {
  1499. if d.Gateway != nil {
  1500. if err := ipam.ReleaseAddress(d.PoolID, d.Gateway.IP); err != nil {
  1501. log.G(context.TODO()).Warnf("Failed to release gateway ip address %s on delete of network %s (%s): %v", d.Gateway.IP, n.Name(), n.ID(), err)
  1502. }
  1503. }
  1504. if d.IPAMData.AuxAddresses != nil {
  1505. for k, nw := range d.IPAMData.AuxAddresses {
  1506. if d.Pool.Contains(nw.IP) {
  1507. if err := ipam.ReleaseAddress(d.PoolID, nw.IP); err != nil && err != ipamapi.ErrIPOutOfRange {
  1508. log.G(context.TODO()).Warnf("Failed to release secondary ip address %s (%v) on delete of network %s (%s): %v", k, nw.IP, n.Name(), n.ID(), err)
  1509. }
  1510. }
  1511. }
  1512. }
  1513. if err := ipam.ReleasePool(d.PoolID); err != nil {
  1514. log.G(context.TODO()).Warnf("Failed to release address pool %s on delete of network %s (%s): %v", d.PoolID, n.Name(), n.ID(), err)
  1515. }
  1516. }
  1517. *infoList = nil
  1518. }
  1519. func (n *network) getIPInfo(ipVer int) []*IpamInfo {
  1520. var info []*IpamInfo
  1521. switch ipVer {
  1522. case 4:
  1523. info = n.ipamV4Info
  1524. case 6:
  1525. info = n.ipamV6Info
  1526. default:
  1527. return nil
  1528. }
  1529. l := make([]*IpamInfo, 0, len(info))
  1530. n.mu.Lock()
  1531. l = append(l, info...)
  1532. n.mu.Unlock()
  1533. return l
  1534. }
  1535. func (n *network) getIPData(ipVer int) []driverapi.IPAMData {
  1536. var info []*IpamInfo
  1537. switch ipVer {
  1538. case 4:
  1539. info = n.ipamV4Info
  1540. case 6:
  1541. info = n.ipamV6Info
  1542. default:
  1543. return nil
  1544. }
  1545. l := make([]driverapi.IPAMData, 0, len(info))
  1546. n.mu.Lock()
  1547. for _, d := range info {
  1548. l = append(l, d.IPAMData)
  1549. }
  1550. n.mu.Unlock()
  1551. return l
  1552. }
  1553. func (n *network) deriveAddressSpace() (string, error) {
  1554. ipam, _ := n.getController().ipamRegistry.IPAM(n.ipamType)
  1555. if ipam == nil {
  1556. return "", types.NotFoundErrorf("failed to get default address space: unknown ipam type %q", n.ipamType)
  1557. }
  1558. local, global, err := ipam.GetDefaultAddressSpaces()
  1559. if err != nil {
  1560. return "", types.NotFoundErrorf("failed to get default address space: %v", err)
  1561. }
  1562. if n.DataScope() == datastore.GlobalScope {
  1563. return global, nil
  1564. }
  1565. return local, nil
  1566. }
  1567. func (n *network) Info() NetworkInfo {
  1568. return n
  1569. }
  1570. func (n *network) Peers() []networkdb.PeerInfo {
  1571. if !n.Dynamic() {
  1572. return []networkdb.PeerInfo{}
  1573. }
  1574. agent := n.getController().getAgent()
  1575. if agent == nil {
  1576. return []networkdb.PeerInfo{}
  1577. }
  1578. return agent.networkDB.Peers(n.ID())
  1579. }
  1580. func (n *network) DriverOptions() map[string]string {
  1581. n.mu.Lock()
  1582. defer n.mu.Unlock()
  1583. if n.generic != nil {
  1584. if m, ok := n.generic[netlabel.GenericData]; ok {
  1585. return m.(map[string]string)
  1586. }
  1587. }
  1588. return map[string]string{}
  1589. }
  1590. func (n *network) Scope() string {
  1591. n.mu.Lock()
  1592. defer n.mu.Unlock()
  1593. return n.scope
  1594. }
  1595. func (n *network) IpamConfig() (string, map[string]string, []*IpamConf, []*IpamConf) {
  1596. n.mu.Lock()
  1597. defer n.mu.Unlock()
  1598. v4L := make([]*IpamConf, len(n.ipamV4Config))
  1599. v6L := make([]*IpamConf, len(n.ipamV6Config))
  1600. for i, c := range n.ipamV4Config {
  1601. cc := &IpamConf{}
  1602. if err := c.CopyTo(cc); err != nil {
  1603. log.G(context.TODO()).WithError(err).Error("Error copying ipam ipv4 config")
  1604. }
  1605. v4L[i] = cc
  1606. }
  1607. for i, c := range n.ipamV6Config {
  1608. cc := &IpamConf{}
  1609. if err := c.CopyTo(cc); err != nil {
  1610. log.G(context.TODO()).WithError(err).Debug("Error copying ipam ipv6 config")
  1611. }
  1612. v6L[i] = cc
  1613. }
  1614. return n.ipamType, n.ipamOptions, v4L, v6L
  1615. }
  1616. func (n *network) IpamInfo() ([]*IpamInfo, []*IpamInfo) {
  1617. n.mu.Lock()
  1618. defer n.mu.Unlock()
  1619. v4Info := make([]*IpamInfo, len(n.ipamV4Info))
  1620. v6Info := make([]*IpamInfo, len(n.ipamV6Info))
  1621. for i, info := range n.ipamV4Info {
  1622. ic := &IpamInfo{}
  1623. if err := info.CopyTo(ic); err != nil {
  1624. log.G(context.TODO()).WithError(err).Error("Error copying ipv4 ipam config")
  1625. }
  1626. v4Info[i] = ic
  1627. }
  1628. for i, info := range n.ipamV6Info {
  1629. ic := &IpamInfo{}
  1630. if err := info.CopyTo(ic); err != nil {
  1631. log.G(context.TODO()).WithError(err).Error("Error copying ipv6 ipam config")
  1632. }
  1633. v6Info[i] = ic
  1634. }
  1635. return v4Info, v6Info
  1636. }
  1637. func (n *network) Internal() bool {
  1638. n.mu.Lock()
  1639. defer n.mu.Unlock()
  1640. return n.internal
  1641. }
  1642. func (n *network) Attachable() bool {
  1643. n.mu.Lock()
  1644. defer n.mu.Unlock()
  1645. return n.attachable
  1646. }
  1647. func (n *network) Ingress() bool {
  1648. n.mu.Lock()
  1649. defer n.mu.Unlock()
  1650. return n.ingress
  1651. }
  1652. func (n *network) Dynamic() bool {
  1653. n.mu.Lock()
  1654. defer n.mu.Unlock()
  1655. return n.dynamic
  1656. }
  1657. func (n *network) IPv6Enabled() bool {
  1658. n.mu.Lock()
  1659. defer n.mu.Unlock()
  1660. return n.enableIPv6
  1661. }
  1662. func (n *network) ConfigFrom() string {
  1663. n.mu.Lock()
  1664. defer n.mu.Unlock()
  1665. return n.configFrom
  1666. }
  1667. func (n *network) ConfigOnly() bool {
  1668. n.mu.Lock()
  1669. defer n.mu.Unlock()
  1670. return n.configOnly
  1671. }
  1672. func (n *network) Labels() map[string]string {
  1673. n.mu.Lock()
  1674. defer n.mu.Unlock()
  1675. lbls := make(map[string]string, len(n.labels))
  1676. for k, v := range n.labels {
  1677. lbls[k] = v
  1678. }
  1679. return lbls
  1680. }
  1681. func (n *network) TableEventRegister(tableName string, objType driverapi.ObjectType) error {
  1682. if !driverapi.IsValidType(objType) {
  1683. return fmt.Errorf("invalid object type %v in registering table, %s", objType, tableName)
  1684. }
  1685. t := networkDBTable{
  1686. name: tableName,
  1687. objType: objType,
  1688. }
  1689. n.mu.Lock()
  1690. defer n.mu.Unlock()
  1691. n.driverTables = append(n.driverTables, t)
  1692. return nil
  1693. }
  1694. func (n *network) UpdateIpamConfig(ipV4Data []driverapi.IPAMData) {
  1695. ipamV4Config := make([]*IpamConf, len(ipV4Data))
  1696. for i, data := range ipV4Data {
  1697. ic := &IpamConf{}
  1698. ic.PreferredPool = data.Pool.String()
  1699. ic.Gateway = data.Gateway.IP.String()
  1700. ipamV4Config[i] = ic
  1701. }
  1702. n.mu.Lock()
  1703. defer n.mu.Unlock()
  1704. n.ipamV4Config = ipamV4Config
  1705. }
  1706. // Special drivers are ones which do not need to perform any network plumbing
  1707. func (n *network) hasSpecialDriver() bool {
  1708. return n.Type() == "host" || n.Type() == "null"
  1709. }
  1710. func (n *network) hasLoadBalancerEndpoint() bool {
  1711. return len(n.loadBalancerIP) != 0
  1712. }
  1713. func (n *network) ResolveName(req string, ipType int) ([]net.IP, bool) {
  1714. var ipv6Miss bool
  1715. c := n.getController()
  1716. networkID := n.ID()
  1717. c.mu.Lock()
  1718. defer c.mu.Unlock()
  1719. sr, ok := c.svcRecords[networkID]
  1720. if !ok {
  1721. return nil, false
  1722. }
  1723. req = strings.TrimSuffix(req, ".")
  1724. req = strings.ToLower(req)
  1725. ipSet, ok := sr.svcMap.Get(req)
  1726. if ipType == types.IPv6 {
  1727. // If the name resolved to v4 address then its a valid name in
  1728. // the docker network domain. If the network is not v6 enabled
  1729. // set ipv6Miss to filter the DNS query from going to external
  1730. // resolvers.
  1731. if ok && !n.enableIPv6 {
  1732. ipv6Miss = true
  1733. }
  1734. ipSet, ok = sr.svcIPv6Map.Get(req)
  1735. }
  1736. if ok && len(ipSet) > 0 {
  1737. // this map is to avoid IP duplicates, this can happen during a transition period where 2 services are using the same IP
  1738. noDup := make(map[string]bool)
  1739. var ipLocal []net.IP
  1740. for _, ip := range ipSet {
  1741. if _, dup := noDup[ip.ip]; !dup {
  1742. noDup[ip.ip] = true
  1743. ipLocal = append(ipLocal, net.ParseIP(ip.ip))
  1744. }
  1745. }
  1746. return ipLocal, ok
  1747. }
  1748. return nil, ipv6Miss
  1749. }
  1750. func (n *network) HandleQueryResp(name string, ip net.IP) {
  1751. networkID := n.ID()
  1752. c := n.getController()
  1753. c.mu.Lock()
  1754. defer c.mu.Unlock()
  1755. sr, ok := c.svcRecords[networkID]
  1756. if !ok {
  1757. return
  1758. }
  1759. ipStr := netutils.ReverseIP(ip.String())
  1760. // If an object with extResolver == true is already in the set this call will fail
  1761. // but anyway it means that has already been inserted before
  1762. if ok, _ := sr.ipMap.Contains(ipStr, ipInfo{name: name}); ok {
  1763. sr.ipMap.Remove(ipStr, ipInfo{name: name})
  1764. sr.ipMap.Insert(ipStr, ipInfo{name: name, extResolver: true})
  1765. }
  1766. }
  1767. func (n *network) ResolveIP(ip string) string {
  1768. networkID := n.ID()
  1769. c := n.getController()
  1770. c.mu.Lock()
  1771. defer c.mu.Unlock()
  1772. sr, ok := c.svcRecords[networkID]
  1773. if !ok {
  1774. return ""
  1775. }
  1776. nwName := n.Name()
  1777. elemSet, ok := sr.ipMap.Get(ip)
  1778. if !ok || len(elemSet) == 0 {
  1779. return ""
  1780. }
  1781. // NOTE it is possible to have more than one element in the Set, this will happen
  1782. // because of interleave of different events from different sources (local container create vs
  1783. // network db notifications)
  1784. // In such cases the resolution will be based on the first element of the set, and can vary
  1785. // during the system stabilitation
  1786. elem := elemSet[0]
  1787. if elem.extResolver {
  1788. return ""
  1789. }
  1790. return elem.name + "." + nwName
  1791. }
  1792. func (n *network) ResolveService(name string) ([]*net.SRV, []net.IP) {
  1793. c := n.getController()
  1794. srv := []*net.SRV{}
  1795. ip := []net.IP{}
  1796. log.G(context.TODO()).Debugf("Service name To resolve: %v", name)
  1797. // There are DNS implementations that allow SRV queries for names not in
  1798. // the format defined by RFC 2782. Hence specific validations checks are
  1799. // not done
  1800. parts := strings.Split(name, ".")
  1801. if len(parts) < 3 {
  1802. return nil, nil
  1803. }
  1804. portName := parts[0]
  1805. proto := parts[1]
  1806. svcName := strings.Join(parts[2:], ".")
  1807. networkID := n.ID()
  1808. c.mu.Lock()
  1809. defer c.mu.Unlock()
  1810. sr, ok := c.svcRecords[networkID]
  1811. if !ok {
  1812. return nil, nil
  1813. }
  1814. svcs, ok := sr.service[svcName]
  1815. if !ok {
  1816. return nil, nil
  1817. }
  1818. for _, svc := range svcs {
  1819. if svc.portName != portName {
  1820. continue
  1821. }
  1822. if svc.proto != proto {
  1823. continue
  1824. }
  1825. for _, t := range svc.target {
  1826. srv = append(srv,
  1827. &net.SRV{
  1828. Target: t.name,
  1829. Port: t.port,
  1830. })
  1831. ip = append(ip, t.ip)
  1832. }
  1833. }
  1834. return srv, ip
  1835. }
  1836. func (n *network) ExecFunc(f func()) error {
  1837. return types.NotImplementedErrorf("ExecFunc not supported by network")
  1838. }
  1839. func (n *network) NdotsSet() bool {
  1840. return false
  1841. }
  1842. // config-only network is looked up by name
  1843. func (c *Controller) getConfigNetwork(name string) (*network, error) {
  1844. var n Network
  1845. s := func(current Network) bool {
  1846. if current.Info().ConfigOnly() && current.Name() == name {
  1847. n = current
  1848. return true
  1849. }
  1850. return false
  1851. }
  1852. c.WalkNetworks(s)
  1853. if n == nil {
  1854. return nil, types.NotFoundErrorf("configuration network %q not found", name)
  1855. }
  1856. return n.(*network), nil
  1857. }
  1858. func (n *network) lbSandboxName() string {
  1859. name := "lb-" + n.name
  1860. if n.ingress {
  1861. name = n.name + "-sbox"
  1862. }
  1863. return name
  1864. }
  1865. func (n *network) lbEndpointName() string {
  1866. return n.name + "-endpoint"
  1867. }
  1868. func (n *network) createLoadBalancerSandbox() (retErr error) {
  1869. sandboxName := n.lbSandboxName()
  1870. // Mark the sandbox to be a load balancer
  1871. sbOptions := []SandboxOption{OptionLoadBalancer(n.id)}
  1872. if n.ingress {
  1873. sbOptions = append(sbOptions, OptionIngress())
  1874. }
  1875. sb, err := n.ctrlr.NewSandbox(sandboxName, sbOptions...)
  1876. if err != nil {
  1877. return err
  1878. }
  1879. defer func() {
  1880. if retErr != nil {
  1881. if e := n.ctrlr.SandboxDestroy(sandboxName); e != nil {
  1882. log.G(context.TODO()).Warnf("could not delete sandbox %s on failure on failure (%v): %v", sandboxName, retErr, e)
  1883. }
  1884. }
  1885. }()
  1886. endpointName := n.lbEndpointName()
  1887. epOptions := []EndpointOption{
  1888. CreateOptionIpam(n.loadBalancerIP, nil, nil, nil),
  1889. CreateOptionLoadBalancer(),
  1890. }
  1891. if n.hasLoadBalancerEndpoint() && !n.ingress {
  1892. // Mark LB endpoints as anonymous so they don't show up in DNS
  1893. epOptions = append(epOptions, CreateOptionAnonymous())
  1894. }
  1895. ep, err := n.createEndpoint(endpointName, epOptions...)
  1896. if err != nil {
  1897. return err
  1898. }
  1899. defer func() {
  1900. if retErr != nil {
  1901. if e := ep.Delete(true); e != nil {
  1902. log.G(context.TODO()).Warnf("could not delete endpoint %s on failure on failure (%v): %v", endpointName, retErr, e)
  1903. }
  1904. }
  1905. }()
  1906. if err := ep.Join(sb, nil); err != nil {
  1907. return err
  1908. }
  1909. return sb.EnableService()
  1910. }
  1911. func (n *network) deleteLoadBalancerSandbox() error {
  1912. n.mu.Lock()
  1913. c := n.ctrlr
  1914. name := n.name
  1915. n.mu.Unlock()
  1916. sandboxName := n.lbSandboxName()
  1917. endpointName := n.lbEndpointName()
  1918. endpoint, err := n.EndpointByName(endpointName)
  1919. if err != nil {
  1920. log.G(context.TODO()).Warnf("Failed to find load balancer endpoint %s on network %s: %v", endpointName, name, err)
  1921. } else {
  1922. info := endpoint.Info()
  1923. if info != nil {
  1924. sb := info.Sandbox()
  1925. if sb != nil {
  1926. if err := sb.DisableService(); err != nil {
  1927. log.G(context.TODO()).Warnf("Failed to disable service on sandbox %s: %v", sandboxName, err)
  1928. // Ignore error and attempt to delete the load balancer endpoint
  1929. }
  1930. }
  1931. }
  1932. if err := endpoint.Delete(true); err != nil {
  1933. log.G(context.TODO()).Warnf("Failed to delete endpoint %s (%s) in %s: %v", endpoint.Name(), endpoint.ID(), sandboxName, err)
  1934. // Ignore error and attempt to delete the sandbox.
  1935. }
  1936. }
  1937. if err := c.SandboxDestroy(sandboxName); err != nil {
  1938. return fmt.Errorf("Failed to delete %s sandbox: %v", sandboxName, err)
  1939. }
  1940. return nil
  1941. }