network.go 58 KB

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