network.go 53 KB

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