network.go 58 KB

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