sandbox.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  1. package libnetwork
  2. import (
  3. "container/heap"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "strings"
  8. "sync"
  9. "time"
  10. log "github.com/Sirupsen/logrus"
  11. "github.com/docker/libnetwork/etchosts"
  12. "github.com/docker/libnetwork/netlabel"
  13. "github.com/docker/libnetwork/netutils"
  14. "github.com/docker/libnetwork/osl"
  15. "github.com/docker/libnetwork/types"
  16. )
  17. // Sandbox provides the control over the network container entity. It is a one to one mapping with the container.
  18. type Sandbox interface {
  19. // ID returns the ID of the sandbox
  20. ID() string
  21. // Key returns the sandbox's key
  22. Key() string
  23. // ContainerID returns the container id associated to this sandbox
  24. ContainerID() string
  25. // Labels returns the sandbox's labels
  26. Labels() map[string]interface{}
  27. // Statistics retrieves the interfaces' statistics for the sandbox
  28. Statistics() (map[string]*types.InterfaceStatistics, error)
  29. // Refresh leaves all the endpoints, resets and re-apply the options,
  30. // re-joins all the endpoints without destroying the osl sandbox
  31. Refresh(options ...SandboxOption) error
  32. // SetKey updates the Sandbox Key
  33. SetKey(key string) error
  34. // Rename changes the name of all attached Endpoints
  35. Rename(name string) error
  36. // Delete destroys this container after detaching it from all connected endpoints.
  37. Delete() error
  38. // ResolveName resolves a service name to an IPv4 or IPv6 address by searching
  39. // the networks the sandbox is connected to. For IPv6 queries, second return
  40. // value will be true if the name exists in docker domain but doesn't have an
  41. // IPv6 address. Such queries shouldn't be forwarded to external nameservers.
  42. ResolveName(name string, iplen int) ([]net.IP, bool)
  43. // ResolveIP returns the service name for the passed in IP. IP is in reverse dotted
  44. // notation; the format used for DNS PTR records
  45. ResolveIP(name string) string
  46. // Endpoints returns all the endpoints connected to the sandbox
  47. Endpoints() []Endpoint
  48. }
  49. // SandboxOption is an option setter function type used to pass various options to
  50. // NewNetContainer method. The various setter functions of type SandboxOption are
  51. // provided by libnetwork, they look like ContainerOptionXXXX(...)
  52. type SandboxOption func(sb *sandbox)
  53. func (sb *sandbox) processOptions(options ...SandboxOption) {
  54. for _, opt := range options {
  55. if opt != nil {
  56. opt(sb)
  57. }
  58. }
  59. }
  60. type epHeap []*endpoint
  61. type sandbox struct {
  62. id string
  63. containerID string
  64. config containerConfig
  65. extDNS []string
  66. osSbox osl.Sandbox
  67. controller *controller
  68. resolver Resolver
  69. resolverOnce sync.Once
  70. refCnt int
  71. endpoints epHeap
  72. epPriority map[string]int
  73. joinLeaveDone chan struct{}
  74. dbIndex uint64
  75. dbExists bool
  76. isStub bool
  77. inDelete bool
  78. sync.Mutex
  79. }
  80. // These are the container configs used to customize container /etc/hosts file.
  81. type hostsPathConfig struct {
  82. hostName string
  83. domainName string
  84. hostsPath string
  85. originHostsPath string
  86. extraHosts []extraHost
  87. parentUpdates []parentUpdate
  88. }
  89. type parentUpdate struct {
  90. cid string
  91. name string
  92. ip string
  93. }
  94. type extraHost struct {
  95. name string
  96. IP string
  97. }
  98. // These are the container configs used to customize container /etc/resolv.conf file.
  99. type resolvConfPathConfig struct {
  100. resolvConfPath string
  101. originResolvConfPath string
  102. resolvConfHashFile string
  103. dnsList []string
  104. dnsSearchList []string
  105. dnsOptionsList []string
  106. }
  107. type containerConfig struct {
  108. hostsPathConfig
  109. resolvConfPathConfig
  110. generic map[string]interface{}
  111. useDefaultSandBox bool
  112. useExternalKey bool
  113. prio int // higher the value, more the priority
  114. exposedPorts []types.TransportPort
  115. }
  116. func (sb *sandbox) ID() string {
  117. return sb.id
  118. }
  119. func (sb *sandbox) ContainerID() string {
  120. return sb.containerID
  121. }
  122. func (sb *sandbox) Key() string {
  123. if sb.config.useDefaultSandBox {
  124. return osl.GenerateKey("default")
  125. }
  126. return osl.GenerateKey(sb.id)
  127. }
  128. func (sb *sandbox) Labels() map[string]interface{} {
  129. sb.Lock()
  130. sb.Unlock()
  131. opts := make(map[string]interface{}, len(sb.config.generic))
  132. for k, v := range sb.config.generic {
  133. opts[k] = v
  134. }
  135. return opts
  136. }
  137. func (sb *sandbox) Statistics() (map[string]*types.InterfaceStatistics, error) {
  138. m := make(map[string]*types.InterfaceStatistics)
  139. sb.Lock()
  140. osb := sb.osSbox
  141. sb.Unlock()
  142. if osb == nil {
  143. return m, nil
  144. }
  145. var err error
  146. for _, i := range osb.Info().Interfaces() {
  147. if m[i.DstName()], err = i.Statistics(); err != nil {
  148. return m, err
  149. }
  150. }
  151. return m, nil
  152. }
  153. func (sb *sandbox) Delete() error {
  154. return sb.delete(false)
  155. }
  156. func (sb *sandbox) delete(force bool) error {
  157. sb.Lock()
  158. if sb.inDelete {
  159. sb.Unlock()
  160. return types.ForbiddenErrorf("another sandbox delete in progress")
  161. }
  162. // Set the inDelete flag. This will ensure that we don't
  163. // update the store until we have completed all the endpoint
  164. // leaves and deletes. And when endpoint leaves and deletes
  165. // are completed then we can finally delete the sandbox object
  166. // altogether from the data store. If the daemon exits
  167. // ungracefully in the middle of a sandbox delete this way we
  168. // will have all the references to the endpoints in the
  169. // sandbox so that we can clean them up when we restart
  170. sb.inDelete = true
  171. sb.Unlock()
  172. c := sb.controller
  173. // Detach from all endpoints
  174. retain := false
  175. for _, ep := range sb.getConnectedEndpoints() {
  176. // gw network endpoint detach and removal are automatic
  177. if ep.endpointInGWNetwork() {
  178. continue
  179. }
  180. // Retain the sanbdox if we can't obtain the network from store.
  181. if _, err := c.getNetworkFromStore(ep.getNetwork().ID()); err != nil {
  182. retain = true
  183. log.Warnf("Failed getting network for ep %s during sandbox %s delete: %v", ep.ID(), sb.ID(), err)
  184. continue
  185. }
  186. if !force {
  187. if err := ep.Leave(sb); err != nil {
  188. log.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  189. }
  190. }
  191. if err := ep.Delete(force); err != nil {
  192. log.Warnf("Failed deleting endpoint %s: %v\n", ep.ID(), err)
  193. }
  194. }
  195. if retain {
  196. sb.Lock()
  197. sb.inDelete = false
  198. sb.Unlock()
  199. return fmt.Errorf("could not cleanup all the endpoints in container %s / sandbox %s", sb.containerID, sb.id)
  200. }
  201. // Container is going away. Path cache in etchosts is most
  202. // likely not required any more. Drop it.
  203. etchosts.Drop(sb.config.hostsPath)
  204. if sb.resolver != nil {
  205. sb.resolver.Stop()
  206. }
  207. if sb.osSbox != nil && !sb.config.useDefaultSandBox {
  208. sb.osSbox.Destroy()
  209. }
  210. if err := sb.storeDelete(); err != nil {
  211. log.Warnf("Failed to delete sandbox %s from store: %v", sb.ID(), err)
  212. }
  213. c.Lock()
  214. delete(c.sandboxes, sb.ID())
  215. c.Unlock()
  216. return nil
  217. }
  218. func (sb *sandbox) Rename(name string) error {
  219. var err error
  220. for _, ep := range sb.getConnectedEndpoints() {
  221. if ep.endpointInGWNetwork() {
  222. continue
  223. }
  224. oldName := ep.Name()
  225. lEp := ep
  226. if err = ep.rename(name); err != nil {
  227. break
  228. }
  229. defer func() {
  230. if err != nil {
  231. lEp.rename(oldName)
  232. }
  233. }()
  234. }
  235. return err
  236. }
  237. func (sb *sandbox) Refresh(options ...SandboxOption) error {
  238. // Store connected endpoints
  239. epList := sb.getConnectedEndpoints()
  240. // Detach from all endpoints
  241. for _, ep := range epList {
  242. if err := ep.Leave(sb); err != nil {
  243. log.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  244. }
  245. }
  246. // Re-apply options
  247. sb.config = containerConfig{}
  248. sb.processOptions(options...)
  249. // Setup discovery files
  250. if err := sb.setupResolutionFiles(); err != nil {
  251. return err
  252. }
  253. // Re -connect to all endpoints
  254. for _, ep := range epList {
  255. if err := ep.Join(sb); err != nil {
  256. log.Warnf("Failed attach sandbox %s to endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  257. }
  258. }
  259. return nil
  260. }
  261. func (sb *sandbox) MarshalJSON() ([]byte, error) {
  262. sb.Lock()
  263. defer sb.Unlock()
  264. // We are just interested in the container ID. This can be expanded to include all of containerInfo if there is a need
  265. return json.Marshal(sb.id)
  266. }
  267. func (sb *sandbox) UnmarshalJSON(b []byte) (err error) {
  268. sb.Lock()
  269. defer sb.Unlock()
  270. var id string
  271. if err := json.Unmarshal(b, &id); err != nil {
  272. return err
  273. }
  274. sb.id = id
  275. return nil
  276. }
  277. func (sb *sandbox) Endpoints() []Endpoint {
  278. sb.Lock()
  279. defer sb.Unlock()
  280. endpoints := make([]Endpoint, len(sb.endpoints))
  281. for i, ep := range sb.endpoints {
  282. endpoints[i] = ep
  283. }
  284. return endpoints
  285. }
  286. func (sb *sandbox) getConnectedEndpoints() []*endpoint {
  287. sb.Lock()
  288. defer sb.Unlock()
  289. eps := make([]*endpoint, len(sb.endpoints))
  290. for i, ep := range sb.endpoints {
  291. eps[i] = ep
  292. }
  293. return eps
  294. }
  295. func (sb *sandbox) removeEndpoint(ep *endpoint) {
  296. sb.Lock()
  297. defer sb.Unlock()
  298. for i, e := range sb.endpoints {
  299. if e == ep {
  300. heap.Remove(&sb.endpoints, i)
  301. return
  302. }
  303. }
  304. }
  305. func (sb *sandbox) getEndpoint(id string) *endpoint {
  306. sb.Lock()
  307. defer sb.Unlock()
  308. for _, ep := range sb.endpoints {
  309. if ep.id == id {
  310. return ep
  311. }
  312. }
  313. return nil
  314. }
  315. func (sb *sandbox) updateGateway(ep *endpoint) error {
  316. sb.Lock()
  317. osSbox := sb.osSbox
  318. sb.Unlock()
  319. if osSbox == nil {
  320. return nil
  321. }
  322. osSbox.UnsetGateway()
  323. osSbox.UnsetGatewayIPv6()
  324. if ep == nil {
  325. return nil
  326. }
  327. ep.Lock()
  328. joinInfo := ep.joinInfo
  329. ep.Unlock()
  330. if err := osSbox.SetGateway(joinInfo.gw); err != nil {
  331. return fmt.Errorf("failed to set gateway while updating gateway: %v", err)
  332. }
  333. if err := osSbox.SetGatewayIPv6(joinInfo.gw6); err != nil {
  334. return fmt.Errorf("failed to set IPv6 gateway while updating gateway: %v", err)
  335. }
  336. return nil
  337. }
  338. func (sb *sandbox) ResolveIP(ip string) string {
  339. var svc string
  340. log.Debugf("IP To resolve %v", ip)
  341. for _, ep := range sb.getConnectedEndpoints() {
  342. n := ep.getNetwork()
  343. sr, ok := n.getController().svcDb[n.ID()]
  344. if !ok {
  345. continue
  346. }
  347. nwName := n.Name()
  348. n.Lock()
  349. svc, ok = sr.ipMap[ip]
  350. n.Unlock()
  351. if ok {
  352. return svc + "." + nwName
  353. }
  354. }
  355. return svc
  356. }
  357. func (sb *sandbox) execFunc(f func()) {
  358. sb.osSbox.InvokeFunc(f)
  359. }
  360. func (sb *sandbox) ResolveName(name string, ipType int) ([]net.IP, bool) {
  361. // Embedded server owns the docker network domain. Resolution should work
  362. // for both container_name and container_name.network_name
  363. // We allow '.' in service name and network name. For a name a.b.c.d the
  364. // following have to tried;
  365. // {a.b.c.d in the networks container is connected to}
  366. // {a.b.c in network d},
  367. // {a.b in network c.d},
  368. // {a in network b.c.d},
  369. name = strings.TrimSuffix(name, ".")
  370. reqName := []string{name}
  371. networkName := []string{""}
  372. if strings.Contains(name, ".") {
  373. var i int
  374. dup := name
  375. for {
  376. if i = strings.LastIndex(dup, "."); i == -1 {
  377. break
  378. }
  379. networkName = append(networkName, name[i+1:])
  380. reqName = append(reqName, name[:i])
  381. dup = dup[:i]
  382. }
  383. }
  384. epList := sb.getConnectedEndpoints()
  385. for i := 0; i < len(reqName); i++ {
  386. log.Debugf("To resolve: %v in %v", reqName[i], networkName[i])
  387. // First check for local container alias
  388. ip, ipv6Miss := sb.resolveName(reqName[i], networkName[i], epList, true, ipType)
  389. if ip != nil {
  390. return ip, false
  391. }
  392. if ipv6Miss {
  393. return ip, ipv6Miss
  394. }
  395. // Resolve the actual container name
  396. ip, ipv6Miss = sb.resolveName(reqName[i], networkName[i], epList, false, ipType)
  397. if ip != nil {
  398. return ip, false
  399. }
  400. if ipv6Miss {
  401. return ip, ipv6Miss
  402. }
  403. }
  404. return nil, false
  405. }
  406. func (sb *sandbox) resolveName(req string, networkName string, epList []*endpoint, alias bool, ipType int) ([]net.IP, bool) {
  407. var ipv6Miss bool
  408. for _, ep := range epList {
  409. name := req
  410. n := ep.getNetwork()
  411. if networkName != "" && networkName != n.Name() {
  412. continue
  413. }
  414. if alias {
  415. if ep.aliases == nil {
  416. continue
  417. }
  418. var ok bool
  419. ep.Lock()
  420. name, ok = ep.aliases[req]
  421. ep.Unlock()
  422. if !ok {
  423. continue
  424. }
  425. } else {
  426. // If it is a regular lookup and if the requested name is an alias
  427. // don't perform a svc lookup for this endpoint.
  428. ep.Lock()
  429. if _, ok := ep.aliases[req]; ok {
  430. ep.Unlock()
  431. continue
  432. }
  433. ep.Unlock()
  434. }
  435. sr, ok := n.getController().svcDb[n.ID()]
  436. if !ok {
  437. continue
  438. }
  439. var ip []net.IP
  440. n.Lock()
  441. ip, ok = sr.svcMap[name]
  442. if ipType == netutils.IPv6 {
  443. // If the name resolved to v4 address then its a valid name in
  444. // the docker network domain. If the network is not v6 enabled
  445. // set ipv6Miss to filter the DNS query from going to external
  446. // resolvers.
  447. if ok && n.enableIPv6 == false {
  448. ipv6Miss = true
  449. }
  450. ip = sr.svcIPv6Map[name]
  451. }
  452. n.Unlock()
  453. if ip != nil {
  454. return ip, false
  455. }
  456. }
  457. return nil, ipv6Miss
  458. }
  459. func (sb *sandbox) SetKey(basePath string) error {
  460. start := time.Now()
  461. defer func() {
  462. log.Debugf("sandbox set key processing took %s for container %s", time.Now().Sub(start), sb.ContainerID())
  463. }()
  464. if basePath == "" {
  465. return types.BadRequestErrorf("invalid sandbox key")
  466. }
  467. sb.Lock()
  468. oldosSbox := sb.osSbox
  469. sb.Unlock()
  470. if oldosSbox != nil {
  471. // If we already have an OS sandbox, release the network resources from that
  472. // and destroy the OS snab. We are moving into a new home further down. Note that none
  473. // of the network resources gets destroyed during the move.
  474. sb.releaseOSSbox()
  475. }
  476. osSbox, err := osl.GetSandboxForExternalKey(basePath, sb.Key())
  477. if err != nil {
  478. return err
  479. }
  480. sb.Lock()
  481. sb.osSbox = osSbox
  482. sb.Unlock()
  483. defer func() {
  484. if err != nil {
  485. sb.Lock()
  486. sb.osSbox = nil
  487. sb.Unlock()
  488. }
  489. }()
  490. // If the resolver was setup before stop it and set it up in the
  491. // new osl sandbox.
  492. if oldosSbox != nil && sb.resolver != nil {
  493. sb.resolver.Stop()
  494. sb.osSbox.InvokeFunc(sb.resolver.SetupFunc())
  495. if err := sb.resolver.Start(); err != nil {
  496. log.Errorf("Resolver Setup/Start failed for container %s, %q", sb.ContainerID(), err)
  497. }
  498. }
  499. for _, ep := range sb.getConnectedEndpoints() {
  500. if err = sb.populateNetworkResources(ep); err != nil {
  501. return err
  502. }
  503. }
  504. return nil
  505. }
  506. func releaseOSSboxResources(osSbox osl.Sandbox, ep *endpoint) {
  507. for _, i := range osSbox.Info().Interfaces() {
  508. // Only remove the interfaces owned by this endpoint from the sandbox.
  509. if ep.hasInterface(i.SrcName()) {
  510. if err := i.Remove(); err != nil {
  511. log.Debugf("Remove interface %s failed: %v", i.SrcName(), err)
  512. }
  513. }
  514. }
  515. ep.Lock()
  516. joinInfo := ep.joinInfo
  517. ep.Unlock()
  518. if joinInfo == nil {
  519. return
  520. }
  521. // Remove non-interface routes.
  522. for _, r := range joinInfo.StaticRoutes {
  523. if err := osSbox.RemoveStaticRoute(r); err != nil {
  524. log.Debugf("Remove route failed: %v", err)
  525. }
  526. }
  527. }
  528. func (sb *sandbox) releaseOSSbox() {
  529. sb.Lock()
  530. osSbox := sb.osSbox
  531. sb.osSbox = nil
  532. sb.Unlock()
  533. if osSbox == nil {
  534. return
  535. }
  536. for _, ep := range sb.getConnectedEndpoints() {
  537. releaseOSSboxResources(osSbox, ep)
  538. }
  539. osSbox.Destroy()
  540. }
  541. func (sb *sandbox) populateNetworkResources(ep *endpoint) error {
  542. sb.Lock()
  543. if sb.osSbox == nil {
  544. sb.Unlock()
  545. return nil
  546. }
  547. inDelete := sb.inDelete
  548. sb.Unlock()
  549. ep.Lock()
  550. joinInfo := ep.joinInfo
  551. i := ep.iface
  552. ep.Unlock()
  553. if ep.needResolver() {
  554. sb.startResolver()
  555. }
  556. if i != nil && i.srcName != "" {
  557. var ifaceOptions []osl.IfaceOption
  558. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes))
  559. if i.addrv6 != nil && i.addrv6.IP.To16() != nil {
  560. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(i.addrv6))
  561. }
  562. if i.mac != nil {
  563. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().MacAddress(i.mac))
  564. }
  565. if err := sb.osSbox.AddInterface(i.srcName, i.dstPrefix, ifaceOptions...); err != nil {
  566. return fmt.Errorf("failed to add interface %s to sandbox: %v", i.srcName, err)
  567. }
  568. }
  569. if joinInfo != nil {
  570. // Set up non-interface routes.
  571. for _, r := range joinInfo.StaticRoutes {
  572. if err := sb.osSbox.AddStaticRoute(r); err != nil {
  573. return fmt.Errorf("failed to add static route %s: %v", r.Destination.String(), err)
  574. }
  575. }
  576. }
  577. if ep == sb.getGatewayEndpoint() {
  578. if err := sb.updateGateway(ep); err != nil {
  579. return err
  580. }
  581. }
  582. // Only update the store if we did not come here as part of
  583. // sandbox delete. If we came here as part of delete then do
  584. // not bother updating the store. The sandbox object will be
  585. // deleted anyway
  586. if !inDelete {
  587. return sb.storeUpdate()
  588. }
  589. return nil
  590. }
  591. func (sb *sandbox) clearNetworkResources(origEp *endpoint) error {
  592. ep := sb.getEndpoint(origEp.id)
  593. if ep == nil {
  594. return fmt.Errorf("could not find the sandbox endpoint data for endpoint %s",
  595. origEp.id)
  596. }
  597. sb.Lock()
  598. osSbox := sb.osSbox
  599. inDelete := sb.inDelete
  600. sb.Unlock()
  601. if osSbox != nil {
  602. releaseOSSboxResources(osSbox, ep)
  603. }
  604. sb.Lock()
  605. if len(sb.endpoints) == 0 {
  606. // sb.endpoints should never be empty and this is unexpected error condition
  607. // We log an error message to note this down for debugging purposes.
  608. log.Errorf("No endpoints in sandbox while trying to remove endpoint %s", ep.Name())
  609. sb.Unlock()
  610. return nil
  611. }
  612. var (
  613. gwepBefore, gwepAfter *endpoint
  614. index = -1
  615. )
  616. for i, e := range sb.endpoints {
  617. if e == ep {
  618. index = i
  619. }
  620. if len(e.Gateway()) > 0 && gwepBefore == nil {
  621. gwepBefore = e
  622. }
  623. if index != -1 && gwepBefore != nil {
  624. break
  625. }
  626. }
  627. heap.Remove(&sb.endpoints, index)
  628. for _, e := range sb.endpoints {
  629. if len(e.Gateway()) > 0 {
  630. gwepAfter = e
  631. break
  632. }
  633. }
  634. delete(sb.epPriority, ep.ID())
  635. sb.Unlock()
  636. if gwepAfter != nil && gwepBefore != gwepAfter {
  637. sb.updateGateway(gwepAfter)
  638. }
  639. // Only update the store if we did not come here as part of
  640. // sandbox delete. If we came here as part of delete then do
  641. // not bother updating the store. The sandbox object will be
  642. // deleted anyway
  643. if !inDelete {
  644. return sb.storeUpdate()
  645. }
  646. return nil
  647. }
  648. // joinLeaveStart waits to ensure there are no joins or leaves in progress and
  649. // marks this join/leave in progress without race
  650. func (sb *sandbox) joinLeaveStart() {
  651. sb.Lock()
  652. defer sb.Unlock()
  653. for sb.joinLeaveDone != nil {
  654. joinLeaveDone := sb.joinLeaveDone
  655. sb.Unlock()
  656. select {
  657. case <-joinLeaveDone:
  658. }
  659. sb.Lock()
  660. }
  661. sb.joinLeaveDone = make(chan struct{})
  662. }
  663. // joinLeaveEnd marks the end of this join/leave operation and
  664. // signals the same without race to other join and leave waiters
  665. func (sb *sandbox) joinLeaveEnd() {
  666. sb.Lock()
  667. defer sb.Unlock()
  668. if sb.joinLeaveDone != nil {
  669. close(sb.joinLeaveDone)
  670. sb.joinLeaveDone = nil
  671. }
  672. }
  673. func (sb *sandbox) hasPortConfigs() bool {
  674. opts := sb.Labels()
  675. _, hasExpPorts := opts[netlabel.ExposedPorts]
  676. _, hasPortMaps := opts[netlabel.PortMap]
  677. return hasExpPorts || hasPortMaps
  678. }
  679. // OptionHostname function returns an option setter for hostname option to
  680. // be passed to NewSandbox method.
  681. func OptionHostname(name string) SandboxOption {
  682. return func(sb *sandbox) {
  683. sb.config.hostName = name
  684. }
  685. }
  686. // OptionDomainname function returns an option setter for domainname option to
  687. // be passed to NewSandbox method.
  688. func OptionDomainname(name string) SandboxOption {
  689. return func(sb *sandbox) {
  690. sb.config.domainName = name
  691. }
  692. }
  693. // OptionHostsPath function returns an option setter for hostspath option to
  694. // be passed to NewSandbox method.
  695. func OptionHostsPath(path string) SandboxOption {
  696. return func(sb *sandbox) {
  697. sb.config.hostsPath = path
  698. }
  699. }
  700. // OptionOriginHostsPath function returns an option setter for origin hosts file path
  701. // tbeo passed to NewSandbox method.
  702. func OptionOriginHostsPath(path string) SandboxOption {
  703. return func(sb *sandbox) {
  704. sb.config.originHostsPath = path
  705. }
  706. }
  707. // OptionExtraHost function returns an option setter for extra /etc/hosts options
  708. // which is a name and IP as strings.
  709. func OptionExtraHost(name string, IP string) SandboxOption {
  710. return func(sb *sandbox) {
  711. sb.config.extraHosts = append(sb.config.extraHosts, extraHost{name: name, IP: IP})
  712. }
  713. }
  714. // OptionParentUpdate function returns an option setter for parent container
  715. // which needs to update the IP address for the linked container.
  716. func OptionParentUpdate(cid string, name, ip string) SandboxOption {
  717. return func(sb *sandbox) {
  718. sb.config.parentUpdates = append(sb.config.parentUpdates, parentUpdate{cid: cid, name: name, ip: ip})
  719. }
  720. }
  721. // OptionResolvConfPath function returns an option setter for resolvconfpath option to
  722. // be passed to net container methods.
  723. func OptionResolvConfPath(path string) SandboxOption {
  724. return func(sb *sandbox) {
  725. sb.config.resolvConfPath = path
  726. }
  727. }
  728. // OptionOriginResolvConfPath function returns an option setter to set the path to the
  729. // origin resolv.conf file to be passed to net container methods.
  730. func OptionOriginResolvConfPath(path string) SandboxOption {
  731. return func(sb *sandbox) {
  732. sb.config.originResolvConfPath = path
  733. }
  734. }
  735. // OptionDNS function returns an option setter for dns entry option to
  736. // be passed to container Create method.
  737. func OptionDNS(dns string) SandboxOption {
  738. return func(sb *sandbox) {
  739. sb.config.dnsList = append(sb.config.dnsList, dns)
  740. }
  741. }
  742. // OptionDNSSearch function returns an option setter for dns search entry option to
  743. // be passed to container Create method.
  744. func OptionDNSSearch(search string) SandboxOption {
  745. return func(sb *sandbox) {
  746. sb.config.dnsSearchList = append(sb.config.dnsSearchList, search)
  747. }
  748. }
  749. // OptionDNSOptions function returns an option setter for dns options entry option to
  750. // be passed to container Create method.
  751. func OptionDNSOptions(options string) SandboxOption {
  752. return func(sb *sandbox) {
  753. sb.config.dnsOptionsList = append(sb.config.dnsOptionsList, options)
  754. }
  755. }
  756. // OptionUseDefaultSandbox function returns an option setter for using default sandbox to
  757. // be passed to container Create method.
  758. func OptionUseDefaultSandbox() SandboxOption {
  759. return func(sb *sandbox) {
  760. sb.config.useDefaultSandBox = true
  761. }
  762. }
  763. // OptionUseExternalKey function returns an option setter for using provided namespace
  764. // instead of creating one.
  765. func OptionUseExternalKey() SandboxOption {
  766. return func(sb *sandbox) {
  767. sb.config.useExternalKey = true
  768. }
  769. }
  770. // OptionGeneric function returns an option setter for Generic configuration
  771. // that is not managed by libNetwork but can be used by the Drivers during the call to
  772. // net container creation method. Container Labels are a good example.
  773. func OptionGeneric(generic map[string]interface{}) SandboxOption {
  774. return func(sb *sandbox) {
  775. if sb.config.generic == nil {
  776. sb.config.generic = make(map[string]interface{}, len(generic))
  777. }
  778. for k, v := range generic {
  779. sb.config.generic[k] = v
  780. }
  781. }
  782. }
  783. // OptionExposedPorts function returns an option setter for the container exposed
  784. // ports option to be passed to container Create method.
  785. func OptionExposedPorts(exposedPorts []types.TransportPort) SandboxOption {
  786. return func(sb *sandbox) {
  787. if sb.config.generic == nil {
  788. sb.config.generic = make(map[string]interface{})
  789. }
  790. // Defensive copy
  791. eps := make([]types.TransportPort, len(exposedPorts))
  792. copy(eps, exposedPorts)
  793. // Store endpoint label and in generic because driver needs it
  794. sb.config.exposedPorts = eps
  795. sb.config.generic[netlabel.ExposedPorts] = eps
  796. }
  797. }
  798. // OptionPortMapping function returns an option setter for the mapping
  799. // ports option to be passed to container Create method.
  800. func OptionPortMapping(portBindings []types.PortBinding) SandboxOption {
  801. return func(sb *sandbox) {
  802. if sb.config.generic == nil {
  803. sb.config.generic = make(map[string]interface{})
  804. }
  805. // Store a copy of the bindings as generic data to pass to the driver
  806. pbs := make([]types.PortBinding, len(portBindings))
  807. copy(pbs, portBindings)
  808. sb.config.generic[netlabel.PortMap] = pbs
  809. }
  810. }
  811. func (eh epHeap) Len() int { return len(eh) }
  812. func (eh epHeap) Less(i, j int) bool {
  813. var (
  814. cip, cjp int
  815. ok bool
  816. )
  817. ci, _ := eh[i].getSandbox()
  818. cj, _ := eh[j].getSandbox()
  819. epi := eh[i]
  820. epj := eh[j]
  821. if epi.endpointInGWNetwork() {
  822. return false
  823. }
  824. if epj.endpointInGWNetwork() {
  825. return true
  826. }
  827. if ci != nil {
  828. cip, ok = ci.epPriority[eh[i].ID()]
  829. if !ok {
  830. cip = 0
  831. }
  832. }
  833. if cj != nil {
  834. cjp, ok = cj.epPriority[eh[j].ID()]
  835. if !ok {
  836. cjp = 0
  837. }
  838. }
  839. if cip == cjp {
  840. return eh[i].network.Name() < eh[j].network.Name()
  841. }
  842. return cip > cjp
  843. }
  844. func (eh epHeap) Swap(i, j int) { eh[i], eh[j] = eh[j], eh[i] }
  845. func (eh *epHeap) Push(x interface{}) {
  846. *eh = append(*eh, x.(*endpoint))
  847. }
  848. func (eh *epHeap) Pop() interface{} {
  849. old := *eh
  850. n := len(old)
  851. x := old[n-1]
  852. *eh = old[0 : n-1]
  853. return x
  854. }