network.go 59 KB

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