network.go 59 KB

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