network.go 58 KB

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