network.go 58 KB

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