network.go 48 KB

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