network.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  1. package libnetwork
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net"
  6. "strings"
  7. "sync"
  8. log "github.com/Sirupsen/logrus"
  9. "github.com/docker/docker/pkg/stringid"
  10. "github.com/docker/libnetwork/config"
  11. "github.com/docker/libnetwork/datastore"
  12. "github.com/docker/libnetwork/driverapi"
  13. "github.com/docker/libnetwork/etchosts"
  14. "github.com/docker/libnetwork/ipamapi"
  15. "github.com/docker/libnetwork/netlabel"
  16. "github.com/docker/libnetwork/netutils"
  17. "github.com/docker/libnetwork/options"
  18. "github.com/docker/libnetwork/types"
  19. )
  20. // A Network represents a logical connectivity zone that containers may
  21. // join using the Link method. A Network is managed by a specific driver.
  22. type Network interface {
  23. // A user chosen name for this network.
  24. Name() string
  25. // A system generated id for this network.
  26. ID() string
  27. // The type of network, which corresponds to its managing driver.
  28. Type() string
  29. // Create a new endpoint to this network symbolically identified by the
  30. // specified unique name. The options parameter carry driver specific options.
  31. CreateEndpoint(name string, options ...EndpointOption) (Endpoint, error)
  32. // Delete the network.
  33. Delete() error
  34. // Endpoints returns the list of Endpoint(s) in this network.
  35. Endpoints() []Endpoint
  36. // WalkEndpoints uses the provided function to walk the Endpoints
  37. WalkEndpoints(walker EndpointWalker)
  38. // EndpointByName returns the Endpoint which has the passed name. If not found, the error ErrNoSuchEndpoint is returned.
  39. EndpointByName(name string) (Endpoint, error)
  40. // EndpointByID returns the Endpoint which has the passed id. If not found, the error ErrNoSuchEndpoint is returned.
  41. EndpointByID(id string) (Endpoint, error)
  42. // Return certain operational data belonging to this network
  43. Info() NetworkInfo
  44. }
  45. // NetworkInfo returns some configuration and operational information about the network
  46. type NetworkInfo interface {
  47. IpamConfig() (string, map[string]string, []*IpamConf, []*IpamConf)
  48. IpamInfo() ([]*IpamInfo, []*IpamInfo)
  49. DriverOptions() map[string]string
  50. Scope() string
  51. IPv6Enabled() bool
  52. Internal() bool
  53. }
  54. // EndpointWalker is a client provided function which will be used to walk the Endpoints.
  55. // When the function returns true, the walk will stop.
  56. type EndpointWalker func(ep Endpoint) bool
  57. type svcInfo struct {
  58. svcMap map[string][]net.IP
  59. ipMap map[string]string
  60. }
  61. // IpamConf contains all the ipam related configurations for a network
  62. type IpamConf struct {
  63. // The master address pool for containers and network interfaces
  64. PreferredPool string
  65. // A subset of the master pool. If specified,
  66. // this becomes the container pool
  67. SubPool string
  68. // Preferred Network Gateway address (optional)
  69. Gateway string
  70. // Auxiliary addresses for network driver. Must be within the master pool.
  71. // libnetwork will reserve them if they fall into the container pool
  72. AuxAddresses map[string]string
  73. }
  74. // Validate checks whether the configuration is valid
  75. func (c *IpamConf) Validate() error {
  76. if c.Gateway != "" && nil == net.ParseIP(c.Gateway) {
  77. return types.BadRequestErrorf("invalid gateway address %s in Ipam configuration", c.Gateway)
  78. }
  79. return nil
  80. }
  81. // IpamInfo contains all the ipam related operational info for a network
  82. type IpamInfo struct {
  83. PoolID string
  84. Meta map[string]string
  85. driverapi.IPAMData
  86. }
  87. // MarshalJSON encodes IpamInfo into json message
  88. func (i *IpamInfo) MarshalJSON() ([]byte, error) {
  89. m := map[string]interface{}{
  90. "PoolID": i.PoolID,
  91. }
  92. v, err := json.Marshal(&i.IPAMData)
  93. if err != nil {
  94. return nil, err
  95. }
  96. m["IPAMData"] = string(v)
  97. if i.Meta != nil {
  98. m["Meta"] = i.Meta
  99. }
  100. return json.Marshal(m)
  101. }
  102. // UnmarshalJSON decodes json message into PoolData
  103. func (i *IpamInfo) UnmarshalJSON(data []byte) error {
  104. var (
  105. m map[string]interface{}
  106. err error
  107. )
  108. if err = json.Unmarshal(data, &m); err != nil {
  109. return err
  110. }
  111. i.PoolID = m["PoolID"].(string)
  112. if v, ok := m["Meta"]; ok {
  113. b, _ := json.Marshal(v)
  114. if err = json.Unmarshal(b, &i.Meta); err != nil {
  115. return err
  116. }
  117. }
  118. if v, ok := m["IPAMData"]; ok {
  119. if err = json.Unmarshal([]byte(v.(string)), &i.IPAMData); err != nil {
  120. return err
  121. }
  122. }
  123. return nil
  124. }
  125. type network struct {
  126. ctrlr *controller
  127. name string
  128. networkType string
  129. id string
  130. scope string
  131. ipamType string
  132. ipamOptions map[string]string
  133. addrSpace string
  134. ipamV4Config []*IpamConf
  135. ipamV6Config []*IpamConf
  136. ipamV4Info []*IpamInfo
  137. ipamV6Info []*IpamInfo
  138. enableIPv6 bool
  139. postIPv6 bool
  140. epCnt *endpointCnt
  141. generic options.Generic
  142. dbIndex uint64
  143. dbExists bool
  144. persist bool
  145. stopWatchCh chan struct{}
  146. drvOnce *sync.Once
  147. internal bool
  148. sync.Mutex
  149. }
  150. func (n *network) Name() string {
  151. n.Lock()
  152. defer n.Unlock()
  153. return n.name
  154. }
  155. func (n *network) ID() string {
  156. n.Lock()
  157. defer n.Unlock()
  158. return n.id
  159. }
  160. func (n *network) Type() string {
  161. n.Lock()
  162. defer n.Unlock()
  163. return n.networkType
  164. }
  165. func (n *network) Key() []string {
  166. n.Lock()
  167. defer n.Unlock()
  168. return []string{datastore.NetworkKeyPrefix, n.id}
  169. }
  170. func (n *network) KeyPrefix() []string {
  171. return []string{datastore.NetworkKeyPrefix}
  172. }
  173. func (n *network) Value() []byte {
  174. n.Lock()
  175. defer n.Unlock()
  176. b, err := json.Marshal(n)
  177. if err != nil {
  178. return nil
  179. }
  180. return b
  181. }
  182. func (n *network) SetValue(value []byte) error {
  183. return json.Unmarshal(value, n)
  184. }
  185. func (n *network) Index() uint64 {
  186. n.Lock()
  187. defer n.Unlock()
  188. return n.dbIndex
  189. }
  190. func (n *network) SetIndex(index uint64) {
  191. n.Lock()
  192. n.dbIndex = index
  193. n.dbExists = true
  194. n.Unlock()
  195. }
  196. func (n *network) Exists() bool {
  197. n.Lock()
  198. defer n.Unlock()
  199. return n.dbExists
  200. }
  201. func (n *network) Skip() bool {
  202. n.Lock()
  203. defer n.Unlock()
  204. return !n.persist
  205. }
  206. func (n *network) New() datastore.KVObject {
  207. n.Lock()
  208. defer n.Unlock()
  209. return &network{
  210. ctrlr: n.ctrlr,
  211. drvOnce: &sync.Once{},
  212. scope: n.scope,
  213. }
  214. }
  215. // CopyTo deep copies to the destination IpamConfig
  216. func (c *IpamConf) CopyTo(dstC *IpamConf) error {
  217. dstC.PreferredPool = c.PreferredPool
  218. dstC.SubPool = c.SubPool
  219. dstC.Gateway = c.Gateway
  220. if c.AuxAddresses != nil {
  221. dstC.AuxAddresses = make(map[string]string, len(c.AuxAddresses))
  222. for k, v := range c.AuxAddresses {
  223. dstC.AuxAddresses[k] = v
  224. }
  225. }
  226. return nil
  227. }
  228. // CopyTo deep copies to the destination IpamInfo
  229. func (i *IpamInfo) CopyTo(dstI *IpamInfo) error {
  230. dstI.PoolID = i.PoolID
  231. if i.Meta != nil {
  232. dstI.Meta = make(map[string]string)
  233. for k, v := range i.Meta {
  234. dstI.Meta[k] = v
  235. }
  236. }
  237. dstI.AddressSpace = i.AddressSpace
  238. dstI.Pool = types.GetIPNetCopy(i.Pool)
  239. dstI.Gateway = types.GetIPNetCopy(i.Gateway)
  240. if i.AuxAddresses != nil {
  241. dstI.AuxAddresses = make(map[string]*net.IPNet)
  242. for k, v := range i.AuxAddresses {
  243. dstI.AuxAddresses[k] = types.GetIPNetCopy(v)
  244. }
  245. }
  246. return nil
  247. }
  248. func (n *network) CopyTo(o datastore.KVObject) error {
  249. n.Lock()
  250. defer n.Unlock()
  251. dstN := o.(*network)
  252. dstN.name = n.name
  253. dstN.id = n.id
  254. dstN.networkType = n.networkType
  255. dstN.scope = n.scope
  256. dstN.ipamType = n.ipamType
  257. dstN.enableIPv6 = n.enableIPv6
  258. dstN.persist = n.persist
  259. dstN.postIPv6 = n.postIPv6
  260. dstN.dbIndex = n.dbIndex
  261. dstN.dbExists = n.dbExists
  262. dstN.drvOnce = n.drvOnce
  263. dstN.internal = n.internal
  264. for _, v4conf := range n.ipamV4Config {
  265. dstV4Conf := &IpamConf{}
  266. v4conf.CopyTo(dstV4Conf)
  267. dstN.ipamV4Config = append(dstN.ipamV4Config, dstV4Conf)
  268. }
  269. for _, v4info := range n.ipamV4Info {
  270. dstV4Info := &IpamInfo{}
  271. v4info.CopyTo(dstV4Info)
  272. dstN.ipamV4Info = append(dstN.ipamV4Info, dstV4Info)
  273. }
  274. for _, v6conf := range n.ipamV6Config {
  275. dstV6Conf := &IpamConf{}
  276. v6conf.CopyTo(dstV6Conf)
  277. dstN.ipamV6Config = append(dstN.ipamV6Config, dstV6Conf)
  278. }
  279. for _, v6info := range n.ipamV6Info {
  280. dstV6Info := &IpamInfo{}
  281. v6info.CopyTo(dstV6Info)
  282. dstN.ipamV6Info = append(dstN.ipamV6Info, dstV6Info)
  283. }
  284. dstN.generic = options.Generic{}
  285. for k, v := range n.generic {
  286. dstN.generic[k] = v
  287. }
  288. return nil
  289. }
  290. func (n *network) DataScope() string {
  291. return n.Scope()
  292. }
  293. func (n *network) getEpCnt() *endpointCnt {
  294. n.Lock()
  295. defer n.Unlock()
  296. return n.epCnt
  297. }
  298. // TODO : Can be made much more generic with the help of reflection (but has some golang limitations)
  299. func (n *network) MarshalJSON() ([]byte, error) {
  300. netMap := make(map[string]interface{})
  301. netMap["name"] = n.name
  302. netMap["id"] = n.id
  303. netMap["networkType"] = n.networkType
  304. netMap["scope"] = n.scope
  305. netMap["ipamType"] = n.ipamType
  306. netMap["addrSpace"] = n.addrSpace
  307. netMap["enableIPv6"] = n.enableIPv6
  308. if n.generic != nil {
  309. netMap["generic"] = n.generic
  310. }
  311. netMap["persist"] = n.persist
  312. netMap["postIPv6"] = n.postIPv6
  313. if len(n.ipamV4Config) > 0 {
  314. ics, err := json.Marshal(n.ipamV4Config)
  315. if err != nil {
  316. return nil, err
  317. }
  318. netMap["ipamV4Config"] = string(ics)
  319. }
  320. if len(n.ipamV4Info) > 0 {
  321. iis, err := json.Marshal(n.ipamV4Info)
  322. if err != nil {
  323. return nil, err
  324. }
  325. netMap["ipamV4Info"] = string(iis)
  326. }
  327. if len(n.ipamV6Config) > 0 {
  328. ics, err := json.Marshal(n.ipamV6Config)
  329. if err != nil {
  330. return nil, err
  331. }
  332. netMap["ipamV6Config"] = string(ics)
  333. }
  334. if len(n.ipamV6Info) > 0 {
  335. iis, err := json.Marshal(n.ipamV6Info)
  336. if err != nil {
  337. return nil, err
  338. }
  339. netMap["ipamV6Info"] = string(iis)
  340. }
  341. netMap["internal"] = n.internal
  342. return json.Marshal(netMap)
  343. }
  344. // TODO : Can be made much more generic with the help of reflection (but has some golang limitations)
  345. func (n *network) UnmarshalJSON(b []byte) (err error) {
  346. var netMap map[string]interface{}
  347. if err := json.Unmarshal(b, &netMap); err != nil {
  348. return err
  349. }
  350. n.name = netMap["name"].(string)
  351. n.id = netMap["id"].(string)
  352. n.networkType = netMap["networkType"].(string)
  353. n.enableIPv6 = netMap["enableIPv6"].(bool)
  354. if v, ok := netMap["generic"]; ok {
  355. n.generic = v.(map[string]interface{})
  356. // Restore opts in their map[string]string form
  357. if v, ok := n.generic[netlabel.GenericData]; ok {
  358. var lmap map[string]string
  359. ba, err := json.Marshal(v)
  360. if err != nil {
  361. return err
  362. }
  363. if err := json.Unmarshal(ba, &lmap); err != nil {
  364. return err
  365. }
  366. n.generic[netlabel.GenericData] = lmap
  367. }
  368. }
  369. if v, ok := netMap["persist"]; ok {
  370. n.persist = v.(bool)
  371. }
  372. if v, ok := netMap["postIPv6"]; ok {
  373. n.postIPv6 = v.(bool)
  374. }
  375. if v, ok := netMap["ipamType"]; ok {
  376. n.ipamType = v.(string)
  377. } else {
  378. n.ipamType = ipamapi.DefaultIPAM
  379. }
  380. if v, ok := netMap["addrSpace"]; ok {
  381. n.addrSpace = v.(string)
  382. }
  383. if v, ok := netMap["ipamV4Config"]; ok {
  384. if err := json.Unmarshal([]byte(v.(string)), &n.ipamV4Config); err != nil {
  385. return err
  386. }
  387. }
  388. if v, ok := netMap["ipamV4Info"]; ok {
  389. if err := json.Unmarshal([]byte(v.(string)), &n.ipamV4Info); err != nil {
  390. return err
  391. }
  392. }
  393. if v, ok := netMap["ipamV6Config"]; ok {
  394. if err := json.Unmarshal([]byte(v.(string)), &n.ipamV6Config); err != nil {
  395. return err
  396. }
  397. }
  398. if v, ok := netMap["ipamV6Info"]; ok {
  399. if err := json.Unmarshal([]byte(v.(string)), &n.ipamV6Info); err != nil {
  400. return err
  401. }
  402. }
  403. if v, ok := netMap["internal"]; ok {
  404. n.internal = v.(bool)
  405. }
  406. if s, ok := netMap["scope"]; ok {
  407. n.scope = s.(string)
  408. }
  409. return nil
  410. }
  411. // NetworkOption is an option setter function type used to pass various options to
  412. // NewNetwork method. The various setter functions of type NetworkOption are
  413. // provided by libnetwork, they look like NetworkOptionXXXX(...)
  414. type NetworkOption func(n *network)
  415. // NetworkOptionGeneric function returns an option setter for a Generic option defined
  416. // in a Dictionary of Key-Value pair
  417. func NetworkOptionGeneric(generic map[string]interface{}) NetworkOption {
  418. return func(n *network) {
  419. if n.generic == nil {
  420. n.generic = make(map[string]interface{})
  421. }
  422. if val, ok := generic[netlabel.EnableIPv6]; ok {
  423. n.enableIPv6 = val.(bool)
  424. }
  425. if val, ok := generic[netlabel.Internal]; ok {
  426. n.internal = val.(bool)
  427. }
  428. for k, v := range generic {
  429. n.generic[k] = v
  430. }
  431. }
  432. }
  433. // NetworkOptionPersist returns an option setter to set persistence policy for a network
  434. func NetworkOptionPersist(persist bool) NetworkOption {
  435. return func(n *network) {
  436. n.persist = persist
  437. }
  438. }
  439. // NetworkOptionEnableIPv6 returns an option setter to explicitly configure IPv6
  440. func NetworkOptionEnableIPv6(enableIPv6 bool) NetworkOption {
  441. return func(n *network) {
  442. if n.generic == nil {
  443. n.generic = make(map[string]interface{})
  444. }
  445. n.enableIPv6 = enableIPv6
  446. n.generic[netlabel.EnableIPv6] = enableIPv6
  447. }
  448. }
  449. // NetworkOptionInternalNetwork returns an option setter to config the network
  450. // to be internal which disables default gateway service
  451. func NetworkOptionInternalNetwork() NetworkOption {
  452. return func(n *network) {
  453. if n.generic == nil {
  454. n.generic = make(map[string]interface{})
  455. }
  456. n.internal = true
  457. n.generic[netlabel.Internal] = true
  458. }
  459. }
  460. // NetworkOptionIpam function returns an option setter for the ipam configuration for this network
  461. func NetworkOptionIpam(ipamDriver string, addrSpace string, ipV4 []*IpamConf, ipV6 []*IpamConf, opts map[string]string) NetworkOption {
  462. return func(n *network) {
  463. if ipamDriver != "" {
  464. n.ipamType = ipamDriver
  465. }
  466. n.ipamOptions = opts
  467. n.addrSpace = addrSpace
  468. n.ipamV4Config = ipV4
  469. n.ipamV6Config = ipV6
  470. }
  471. }
  472. // NetworkOptionDriverOpts function returns an option setter for any parameter described by a map
  473. func NetworkOptionDriverOpts(opts map[string]string) NetworkOption {
  474. return func(n *network) {
  475. if n.generic == nil {
  476. n.generic = make(map[string]interface{})
  477. }
  478. if opts == nil {
  479. opts = make(map[string]string)
  480. }
  481. // Store the options
  482. n.generic[netlabel.GenericData] = opts
  483. }
  484. }
  485. // NetworkOptionDeferIPv6Alloc instructs the network to defer the IPV6 address allocation until after the endpoint has been created
  486. // It is being provided to support the specific docker daemon flags where user can deterministically assign an IPv6 address
  487. // to a container as combination of fixed-cidr-v6 + mac-address
  488. // TODO: Remove this option setter once we support endpoint ipam options
  489. func NetworkOptionDeferIPv6Alloc(enable bool) NetworkOption {
  490. return func(n *network) {
  491. n.postIPv6 = enable
  492. }
  493. }
  494. func (n *network) processOptions(options ...NetworkOption) {
  495. for _, opt := range options {
  496. if opt != nil {
  497. opt(n)
  498. }
  499. }
  500. }
  501. func (n *network) driverScope() string {
  502. c := n.getController()
  503. c.Lock()
  504. // Check if a driver for the specified network type is available
  505. dd, ok := c.drivers[n.networkType]
  506. c.Unlock()
  507. if !ok {
  508. var err error
  509. dd, err = c.loadDriver(n.networkType)
  510. if err != nil {
  511. // If driver could not be resolved simply return an empty string
  512. return ""
  513. }
  514. }
  515. return dd.capability.DataScope
  516. }
  517. func (n *network) driver(load bool) (driverapi.Driver, error) {
  518. c := n.getController()
  519. c.Lock()
  520. // Check if a driver for the specified network type is available
  521. dd, ok := c.drivers[n.networkType]
  522. c.Unlock()
  523. if !ok && load {
  524. var err error
  525. dd, err = c.loadDriver(n.networkType)
  526. if err != nil {
  527. return nil, err
  528. }
  529. } else if !ok {
  530. // don't fail if driver loading is not required
  531. return nil, nil
  532. }
  533. n.Lock()
  534. n.scope = dd.capability.DataScope
  535. n.Unlock()
  536. return dd.driver, nil
  537. }
  538. func (n *network) Delete() error {
  539. n.Lock()
  540. c := n.ctrlr
  541. name := n.name
  542. id := n.id
  543. n.Unlock()
  544. n, err := c.getNetworkFromStore(id)
  545. if err != nil {
  546. return &UnknownNetworkError{name: name, id: id}
  547. }
  548. numEps := n.getEpCnt().EndpointCnt()
  549. if numEps != 0 {
  550. return &ActiveEndpointsError{name: n.name, id: n.id}
  551. }
  552. if err = n.deleteNetwork(); err != nil {
  553. return err
  554. }
  555. defer func() {
  556. if err != nil {
  557. if e := c.addNetwork(n); e != nil {
  558. log.Warnf("failed to rollback deleteNetwork for network %s: %v",
  559. n.Name(), err)
  560. }
  561. }
  562. }()
  563. // deleteFromStore performs an atomic delete operation and the
  564. // network.epCnt will help prevent any possible
  565. // race between endpoint join and network delete
  566. if err = n.getController().deleteFromStore(n.getEpCnt()); err != nil {
  567. return fmt.Errorf("error deleting network endpoint count from store: %v", err)
  568. }
  569. n.ipamRelease()
  570. if err = n.getController().deleteFromStore(n); err != nil {
  571. return fmt.Errorf("error deleting network from store: %v", err)
  572. }
  573. return nil
  574. }
  575. func (n *network) deleteNetwork() error {
  576. d, err := n.driver(true)
  577. if err != nil {
  578. return fmt.Errorf("failed deleting network: %v", err)
  579. }
  580. if err := d.DeleteNetwork(n.ID()); err != nil {
  581. // Forbidden Errors should be honored
  582. if _, ok := err.(types.ForbiddenError); ok {
  583. return err
  584. }
  585. if _, ok := err.(types.MaskableError); !ok {
  586. log.Warnf("driver error deleting network %s : %v", n.name, err)
  587. }
  588. }
  589. return nil
  590. }
  591. func (n *network) addEndpoint(ep *endpoint) error {
  592. d, err := n.driver(true)
  593. if err != nil {
  594. return fmt.Errorf("failed to add endpoint: %v", err)
  595. }
  596. err = d.CreateEndpoint(n.id, ep.id, ep.Interface(), ep.generic)
  597. if err != nil {
  598. return types.InternalErrorf("failed to create endpoint %s on network %s: %v",
  599. ep.Name(), n.Name(), err)
  600. }
  601. return nil
  602. }
  603. func (n *network) CreateEndpoint(name string, options ...EndpointOption) (Endpoint, error) {
  604. var err error
  605. if !config.IsValidName(name) {
  606. return nil, ErrInvalidName(name)
  607. }
  608. if _, err = n.EndpointByName(name); err == nil {
  609. return nil, types.ForbiddenErrorf("service endpoint with name %s already exists", name)
  610. }
  611. ep := &endpoint{name: name, generic: make(map[string]interface{}), iface: &endpointInterface{}}
  612. ep.id = stringid.GenerateRandomID()
  613. // Initialize ep.network with a possibly stale copy of n. We need this to get network from
  614. // store. But once we get it from store we will have the most uptodate copy possibly.
  615. ep.network = n
  616. ep.locator = n.getController().clusterHostID()
  617. ep.network, err = ep.getNetworkFromStore()
  618. if err != nil {
  619. return nil, fmt.Errorf("failed to get network during CreateEndpoint: %v", err)
  620. }
  621. n = ep.network
  622. ep.processOptions(options...)
  623. if opt, ok := ep.generic[netlabel.MacAddress]; ok {
  624. if mac, ok := opt.(net.HardwareAddr); ok {
  625. ep.iface.mac = mac
  626. }
  627. }
  628. ipam, err := n.getController().getIPAM(n.ipamType)
  629. if err != nil {
  630. return nil, err
  631. }
  632. if ipam.capability.RequiresMACAddress {
  633. if ep.iface.mac == nil {
  634. ep.iface.mac = netutils.GenerateRandomMAC()
  635. }
  636. if ep.ipamOptions == nil {
  637. ep.ipamOptions = make(map[string]string)
  638. }
  639. ep.ipamOptions[netlabel.MacAddress] = ep.iface.mac.String()
  640. }
  641. if err = ep.assignAddress(ipam.driver, true, !n.postIPv6); err != nil {
  642. return nil, err
  643. }
  644. defer func() {
  645. if err != nil {
  646. ep.releaseAddress()
  647. }
  648. }()
  649. if err = n.addEndpoint(ep); err != nil {
  650. return nil, err
  651. }
  652. defer func() {
  653. if err != nil {
  654. if e := ep.deleteEndpoint(false); e != nil {
  655. log.Warnf("cleaning up endpoint failed %s : %v", name, e)
  656. }
  657. }
  658. }()
  659. if err = ep.assignAddress(ipam.driver, false, n.postIPv6); err != nil {
  660. return nil, err
  661. }
  662. if err = n.getController().updateToStore(ep); err != nil {
  663. return nil, err
  664. }
  665. defer func() {
  666. if err != nil {
  667. if e := n.getController().deleteFromStore(ep); e != nil {
  668. log.Warnf("error rolling back endpoint %s from store: %v", name, e)
  669. }
  670. }
  671. }()
  672. // Watch for service records
  673. n.getController().watchSvcRecord(ep)
  674. defer func() {
  675. if err != nil {
  676. n.getController().unWatchSvcRecord(ep)
  677. }
  678. }()
  679. // Increment endpoint count to indicate completion of endpoint addition
  680. if err = n.getEpCnt().IncEndpointCnt(); err != nil {
  681. return nil, err
  682. }
  683. return ep, nil
  684. }
  685. func (n *network) Endpoints() []Endpoint {
  686. var list []Endpoint
  687. endpoints, err := n.getEndpointsFromStore()
  688. if err != nil {
  689. log.Error(err)
  690. }
  691. for _, ep := range endpoints {
  692. list = append(list, ep)
  693. }
  694. return list
  695. }
  696. func (n *network) WalkEndpoints(walker EndpointWalker) {
  697. for _, e := range n.Endpoints() {
  698. if walker(e) {
  699. return
  700. }
  701. }
  702. }
  703. func (n *network) EndpointByName(name string) (Endpoint, error) {
  704. if name == "" {
  705. return nil, ErrInvalidName(name)
  706. }
  707. var e Endpoint
  708. s := func(current Endpoint) bool {
  709. if current.Name() == name {
  710. e = current
  711. return true
  712. }
  713. return false
  714. }
  715. n.WalkEndpoints(s)
  716. if e == nil {
  717. return nil, ErrNoSuchEndpoint(name)
  718. }
  719. return e, nil
  720. }
  721. func (n *network) EndpointByID(id string) (Endpoint, error) {
  722. if id == "" {
  723. return nil, ErrInvalidID(id)
  724. }
  725. ep, err := n.getEndpointFromStore(id)
  726. if err != nil {
  727. return nil, ErrNoSuchEndpoint(id)
  728. }
  729. return ep, nil
  730. }
  731. func (n *network) updateSvcRecord(ep *endpoint, localEps []*endpoint, isAdd bool) {
  732. epName := ep.Name()
  733. if iface := ep.Iface(); iface.Address() != nil {
  734. myAliases := ep.MyAliases()
  735. if isAdd {
  736. // If anonymous endpoint has an alias use the first alias
  737. // for ip->name mapping. Not having the reverse mapping
  738. // breaks some apps
  739. if ep.isAnonymous() {
  740. if len(myAliases) > 0 {
  741. n.addSvcRecords(myAliases[0], iface.Address().IP, true)
  742. }
  743. } else {
  744. n.addSvcRecords(epName, iface.Address().IP, true)
  745. }
  746. for _, alias := range myAliases {
  747. n.addSvcRecords(alias, iface.Address().IP, false)
  748. }
  749. } else {
  750. if ep.isAnonymous() {
  751. if len(myAliases) > 0 {
  752. n.deleteSvcRecords(myAliases[0], iface.Address().IP, true)
  753. }
  754. } else {
  755. n.deleteSvcRecords(epName, iface.Address().IP, true)
  756. }
  757. for _, alias := range myAliases {
  758. n.deleteSvcRecords(alias, iface.Address().IP, false)
  759. }
  760. }
  761. }
  762. }
  763. func (n *network) addSvcRecords(name string, epIP net.IP, ipMapUpdate bool) {
  764. c := n.getController()
  765. c.Lock()
  766. defer c.Unlock()
  767. sr, ok := c.svcDb[n.ID()]
  768. if !ok {
  769. sr = svcInfo{
  770. svcMap: make(map[string][]net.IP),
  771. ipMap: make(map[string]string),
  772. }
  773. c.svcDb[n.ID()] = sr
  774. }
  775. if ipMapUpdate {
  776. reverseIP := netutils.ReverseIP(epIP.String())
  777. if _, ok := sr.ipMap[reverseIP]; !ok {
  778. sr.ipMap[reverseIP] = name
  779. }
  780. }
  781. ipList := sr.svcMap[name]
  782. for _, ip := range ipList {
  783. if ip.Equal(epIP) {
  784. return
  785. }
  786. }
  787. sr.svcMap[name] = append(sr.svcMap[name], epIP)
  788. }
  789. func (n *network) deleteSvcRecords(name string, epIP net.IP, ipMapUpdate bool) {
  790. c := n.getController()
  791. c.Lock()
  792. defer c.Unlock()
  793. sr, ok := c.svcDb[n.ID()]
  794. if !ok {
  795. return
  796. }
  797. if ipMapUpdate {
  798. delete(sr.ipMap, netutils.ReverseIP(epIP.String()))
  799. }
  800. ipList := sr.svcMap[name]
  801. for i, ip := range ipList {
  802. if ip.Equal(epIP) {
  803. ipList = append(ipList[:i], ipList[i+1:]...)
  804. break
  805. }
  806. }
  807. sr.svcMap[name] = ipList
  808. if len(ipList) == 0 {
  809. delete(sr.svcMap, name)
  810. }
  811. }
  812. func (n *network) getSvcRecords(ep *endpoint) []etchosts.Record {
  813. n.Lock()
  814. defer n.Unlock()
  815. var recs []etchosts.Record
  816. sr, _ := n.ctrlr.svcDb[n.id]
  817. for h, ip := range sr.svcMap {
  818. if ep != nil && strings.Split(h, ".")[0] == ep.Name() {
  819. continue
  820. }
  821. recs = append(recs, etchosts.Record{
  822. Hosts: h,
  823. IP: ip[0].String(),
  824. })
  825. }
  826. return recs
  827. }
  828. func (n *network) getController() *controller {
  829. n.Lock()
  830. defer n.Unlock()
  831. return n.ctrlr
  832. }
  833. func (n *network) ipamAllocate() error {
  834. // For now also exclude bridge from using new ipam
  835. if n.Type() == "host" || n.Type() == "null" {
  836. return nil
  837. }
  838. ipam, err := n.getController().getIpamDriver(n.ipamType)
  839. if err != nil {
  840. return err
  841. }
  842. if n.addrSpace == "" {
  843. if n.addrSpace, err = n.deriveAddressSpace(); err != nil {
  844. return err
  845. }
  846. }
  847. err = n.ipamAllocateVersion(4, ipam)
  848. if err != nil {
  849. return err
  850. }
  851. defer func() {
  852. if err != nil {
  853. n.ipamReleaseVersion(4, ipam)
  854. }
  855. }()
  856. return n.ipamAllocateVersion(6, ipam)
  857. }
  858. func (n *network) ipamAllocateVersion(ipVer int, ipam ipamapi.Ipam) error {
  859. var (
  860. cfgList *[]*IpamConf
  861. infoList *[]*IpamInfo
  862. err error
  863. )
  864. switch ipVer {
  865. case 4:
  866. cfgList = &n.ipamV4Config
  867. infoList = &n.ipamV4Info
  868. case 6:
  869. cfgList = &n.ipamV6Config
  870. infoList = &n.ipamV6Info
  871. default:
  872. return types.InternalErrorf("incorrect ip version passed to ipam allocate: %d", ipVer)
  873. }
  874. if len(*cfgList) == 0 {
  875. if ipVer == 6 {
  876. return nil
  877. }
  878. *cfgList = []*IpamConf{{}}
  879. }
  880. *infoList = make([]*IpamInfo, len(*cfgList))
  881. log.Debugf("Allocating IPv%d pools for network %s (%s)", ipVer, n.Name(), n.ID())
  882. for i, cfg := range *cfgList {
  883. if err = cfg.Validate(); err != nil {
  884. return err
  885. }
  886. d := &IpamInfo{}
  887. (*infoList)[i] = d
  888. d.PoolID, d.Pool, d.Meta, err = ipam.RequestPool(n.addrSpace, cfg.PreferredPool, cfg.SubPool, n.ipamOptions, ipVer == 6)
  889. if err != nil {
  890. return err
  891. }
  892. defer func() {
  893. if err != nil {
  894. if err := ipam.ReleasePool(d.PoolID); err != nil {
  895. log.Warnf("Failed to release address pool %s after failure to create network %s (%s)", d.PoolID, n.Name(), n.ID())
  896. }
  897. }
  898. }()
  899. if gws, ok := d.Meta[netlabel.Gateway]; ok {
  900. if d.Gateway, err = types.ParseCIDR(gws); err != nil {
  901. return types.BadRequestErrorf("failed to parse gateway address (%v) returned by ipam driver: %v", gws, err)
  902. }
  903. }
  904. // If user requested a specific gateway, libnetwork will allocate it
  905. // irrespective of whether ipam driver returned a gateway already.
  906. // If none of the above is true, libnetwork will allocate one.
  907. if cfg.Gateway != "" || d.Gateway == nil {
  908. var gatewayOpts = map[string]string{
  909. ipamapi.RequestAddressType: netlabel.Gateway,
  910. }
  911. if d.Gateway, _, err = ipam.RequestAddress(d.PoolID, net.ParseIP(cfg.Gateway), gatewayOpts); err != nil {
  912. return types.InternalErrorf("failed to allocate gateway (%v): %v", cfg.Gateway, err)
  913. }
  914. }
  915. // Auxiliary addresses must be part of the master address pool
  916. // If they fall into the container addressable pool, libnetwork will reserve them
  917. if cfg.AuxAddresses != nil {
  918. var ip net.IP
  919. d.IPAMData.AuxAddresses = make(map[string]*net.IPNet, len(cfg.AuxAddresses))
  920. for k, v := range cfg.AuxAddresses {
  921. if ip = net.ParseIP(v); ip == nil {
  922. return types.BadRequestErrorf("non parsable secondary ip address (%s:%s) passed for network %s", k, v, n.Name())
  923. }
  924. if !d.Pool.Contains(ip) {
  925. return types.ForbiddenErrorf("auxilairy address: (%s:%s) must belong to the master pool: %s", k, v, d.Pool)
  926. }
  927. // Attempt reservation in the container addressable pool, silent the error if address does not belong to that pool
  928. if d.IPAMData.AuxAddresses[k], _, err = ipam.RequestAddress(d.PoolID, ip, nil); err != nil && err != ipamapi.ErrIPOutOfRange {
  929. return types.InternalErrorf("failed to allocate secondary ip address (%s:%s): %v", k, v, err)
  930. }
  931. }
  932. }
  933. }
  934. return nil
  935. }
  936. func (n *network) ipamRelease() {
  937. // For now exclude host and null
  938. if n.Type() == "host" || n.Type() == "null" {
  939. return
  940. }
  941. ipam, err := n.getController().getIpamDriver(n.ipamType)
  942. if err != nil {
  943. log.Warnf("Failed to retrieve ipam driver to release address pool(s) on delete of network %s (%s): %v", n.Name(), n.ID(), err)
  944. return
  945. }
  946. n.ipamReleaseVersion(4, ipam)
  947. n.ipamReleaseVersion(6, ipam)
  948. }
  949. func (n *network) ipamReleaseVersion(ipVer int, ipam ipamapi.Ipam) {
  950. var infoList []*IpamInfo
  951. switch ipVer {
  952. case 4:
  953. infoList = n.ipamV4Info
  954. case 6:
  955. infoList = n.ipamV6Info
  956. default:
  957. log.Warnf("incorrect ip version passed to ipam release: %d", ipVer)
  958. return
  959. }
  960. if infoList == nil {
  961. return
  962. }
  963. log.Debugf("releasing IPv%d pools from network %s (%s)", ipVer, n.Name(), n.ID())
  964. for _, d := range infoList {
  965. if d.Gateway != nil {
  966. if err := ipam.ReleaseAddress(d.PoolID, d.Gateway.IP); err != nil {
  967. log.Warnf("Failed to release gateway ip address %s on delete of network %s (%s): %v", d.Gateway.IP, n.Name(), n.ID(), err)
  968. }
  969. }
  970. if d.IPAMData.AuxAddresses != nil {
  971. for k, nw := range d.IPAMData.AuxAddresses {
  972. if d.Pool.Contains(nw.IP) {
  973. if err := ipam.ReleaseAddress(d.PoolID, nw.IP); err != nil && err != ipamapi.ErrIPOutOfRange {
  974. log.Warnf("Failed to release secondary ip address %s (%v) on delete of network %s (%s): %v", k, nw.IP, n.Name(), n.ID(), err)
  975. }
  976. }
  977. }
  978. }
  979. if err := ipam.ReleasePool(d.PoolID); err != nil {
  980. log.Warnf("Failed to release address pool %s on delete of network %s (%s): %v", d.PoolID, n.Name(), n.ID(), err)
  981. }
  982. }
  983. }
  984. func (n *network) getIPInfo(ipVer int) []*IpamInfo {
  985. var info []*IpamInfo
  986. switch ipVer {
  987. case 4:
  988. info = n.ipamV4Info
  989. case 6:
  990. info = n.ipamV6Info
  991. default:
  992. return nil
  993. }
  994. l := make([]*IpamInfo, 0, len(info))
  995. n.Lock()
  996. for _, d := range info {
  997. l = append(l, d)
  998. }
  999. n.Unlock()
  1000. return l
  1001. }
  1002. func (n *network) getIPData(ipVer int) []driverapi.IPAMData {
  1003. var info []*IpamInfo
  1004. switch ipVer {
  1005. case 4:
  1006. info = n.ipamV4Info
  1007. case 6:
  1008. info = n.ipamV6Info
  1009. default:
  1010. return nil
  1011. }
  1012. l := make([]driverapi.IPAMData, 0, len(info))
  1013. n.Lock()
  1014. for _, d := range info {
  1015. l = append(l, d.IPAMData)
  1016. }
  1017. n.Unlock()
  1018. return l
  1019. }
  1020. func (n *network) deriveAddressSpace() (string, error) {
  1021. c := n.getController()
  1022. c.Lock()
  1023. ipd, ok := c.ipamDrivers[n.ipamType]
  1024. c.Unlock()
  1025. if !ok {
  1026. return "", types.NotFoundErrorf("could not find ipam driver %s to get default address space", n.ipamType)
  1027. }
  1028. if n.DataScope() == datastore.GlobalScope {
  1029. return ipd.defaultGlobalAddressSpace, nil
  1030. }
  1031. return ipd.defaultLocalAddressSpace, nil
  1032. }
  1033. func (n *network) Info() NetworkInfo {
  1034. return n
  1035. }
  1036. func (n *network) DriverOptions() map[string]string {
  1037. n.Lock()
  1038. defer n.Unlock()
  1039. if n.generic != nil {
  1040. if m, ok := n.generic[netlabel.GenericData]; ok {
  1041. return m.(map[string]string)
  1042. }
  1043. }
  1044. return map[string]string{}
  1045. }
  1046. func (n *network) Scope() string {
  1047. n.Lock()
  1048. defer n.Unlock()
  1049. return n.scope
  1050. }
  1051. func (n *network) IpamConfig() (string, map[string]string, []*IpamConf, []*IpamConf) {
  1052. n.Lock()
  1053. defer n.Unlock()
  1054. v4L := make([]*IpamConf, len(n.ipamV4Config))
  1055. v6L := make([]*IpamConf, len(n.ipamV6Config))
  1056. for i, c := range n.ipamV4Config {
  1057. cc := &IpamConf{}
  1058. c.CopyTo(cc)
  1059. v4L[i] = cc
  1060. }
  1061. for i, c := range n.ipamV6Config {
  1062. cc := &IpamConf{}
  1063. c.CopyTo(cc)
  1064. v6L[i] = cc
  1065. }
  1066. return n.ipamType, n.ipamOptions, v4L, v6L
  1067. }
  1068. func (n *network) IpamInfo() ([]*IpamInfo, []*IpamInfo) {
  1069. n.Lock()
  1070. defer n.Unlock()
  1071. v4Info := make([]*IpamInfo, len(n.ipamV4Info))
  1072. v6Info := make([]*IpamInfo, len(n.ipamV6Info))
  1073. for i, info := range n.ipamV4Info {
  1074. ic := &IpamInfo{}
  1075. info.CopyTo(ic)
  1076. v4Info[i] = ic
  1077. }
  1078. for i, info := range n.ipamV6Info {
  1079. ic := &IpamInfo{}
  1080. info.CopyTo(ic)
  1081. v6Info[i] = ic
  1082. }
  1083. return v4Info, v6Info
  1084. }
  1085. func (n *network) Internal() bool {
  1086. n.Lock()
  1087. defer n.Unlock()
  1088. return n.internal
  1089. }
  1090. func (n *network) IPv6Enabled() bool {
  1091. n.Lock()
  1092. defer n.Unlock()
  1093. return n.enableIPv6
  1094. }