sandbox.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. package libnetwork
  2. import (
  3. "container/heap"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/Sirupsen/logrus"
  11. "github.com/docker/libnetwork/etchosts"
  12. "github.com/docker/libnetwork/netlabel"
  13. "github.com/docker/libnetwork/osl"
  14. "github.com/docker/libnetwork/types"
  15. )
  16. // Sandbox provides the control over the network container entity. It is a one to one mapping with the container.
  17. type Sandbox interface {
  18. // ID returns the ID of the sandbox
  19. ID() string
  20. // Key returns the sandbox's key
  21. Key() string
  22. // ContainerID returns the container id associated to this sandbox
  23. ContainerID() string
  24. // Labels returns the sandbox's labels
  25. Labels() map[string]interface{}
  26. // Statistics retrieves the interfaces' statistics for the sandbox
  27. Statistics() (map[string]*types.InterfaceStatistics, error)
  28. // Refresh leaves all the endpoints, resets and re-applies the options,
  29. // re-joins all the endpoints without destroying the osl sandbox
  30. Refresh(options ...SandboxOption) error
  31. // SetKey updates the Sandbox Key
  32. SetKey(key string) error
  33. // Rename changes the name of all attached Endpoints
  34. Rename(name string) error
  35. // Delete destroys this container after detaching it from all connected endpoints.
  36. Delete() error
  37. // Endpoints returns all the endpoints connected to the sandbox
  38. Endpoints() []Endpoint
  39. // ResolveService returns all the backend details about the containers or hosts
  40. // backing a service. Its purpose is to satisfy an SRV query
  41. ResolveService(name string) ([]*net.SRV, []net.IP)
  42. // EnableService makes a managed container's service available by adding the
  43. // endpoint to the service load balancer and service discovery
  44. EnableService() error
  45. // DisableService removes a managed container's endpoints from the load balancer
  46. // and service discovery
  47. DisableService() error
  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 []extDNSEntry
  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. populatedEndpoints map[string]struct{}
  74. joinLeaveDone chan struct{}
  75. dbIndex uint64
  76. dbExists bool
  77. isStub bool
  78. inDelete bool
  79. ingress bool
  80. ndotsSet bool
  81. sync.Mutex
  82. }
  83. // These are the container configs used to customize container /etc/hosts file.
  84. type hostsPathConfig struct {
  85. hostName string
  86. domainName string
  87. hostsPath string
  88. originHostsPath string
  89. extraHosts []extraHost
  90. parentUpdates []parentUpdate
  91. }
  92. type parentUpdate struct {
  93. cid string
  94. name string
  95. ip string
  96. }
  97. type extraHost struct {
  98. name string
  99. IP string
  100. }
  101. // These are the container configs used to customize container /etc/resolv.conf file.
  102. type resolvConfPathConfig struct {
  103. resolvConfPath string
  104. originResolvConfPath string
  105. resolvConfHashFile string
  106. dnsList []string
  107. dnsSearchList []string
  108. dnsOptionsList []string
  109. }
  110. type containerConfig struct {
  111. hostsPathConfig
  112. resolvConfPathConfig
  113. generic map[string]interface{}
  114. useDefaultSandBox bool
  115. useExternalKey bool
  116. prio int // higher the value, more the priority
  117. exposedPorts []types.TransportPort
  118. }
  119. const (
  120. resolverIPSandbox = "127.0.0.11"
  121. )
  122. func (sb *sandbox) ID() string {
  123. return sb.id
  124. }
  125. func (sb *sandbox) ContainerID() string {
  126. return sb.containerID
  127. }
  128. func (sb *sandbox) Key() string {
  129. if sb.config.useDefaultSandBox {
  130. return osl.GenerateKey("default")
  131. }
  132. return osl.GenerateKey(sb.id)
  133. }
  134. func (sb *sandbox) Labels() map[string]interface{} {
  135. sb.Lock()
  136. defer sb.Unlock()
  137. opts := make(map[string]interface{}, len(sb.config.generic))
  138. for k, v := range sb.config.generic {
  139. opts[k] = v
  140. }
  141. return opts
  142. }
  143. func (sb *sandbox) Statistics() (map[string]*types.InterfaceStatistics, error) {
  144. m := make(map[string]*types.InterfaceStatistics)
  145. sb.Lock()
  146. osb := sb.osSbox
  147. sb.Unlock()
  148. if osb == nil {
  149. return m, nil
  150. }
  151. var err error
  152. for _, i := range osb.Info().Interfaces() {
  153. if m[i.DstName()], err = i.Statistics(); err != nil {
  154. return m, err
  155. }
  156. }
  157. return m, nil
  158. }
  159. func (sb *sandbox) Delete() error {
  160. return sb.delete(false)
  161. }
  162. func (sb *sandbox) delete(force bool) error {
  163. sb.Lock()
  164. if sb.inDelete {
  165. sb.Unlock()
  166. return types.ForbiddenErrorf("another sandbox delete in progress")
  167. }
  168. // Set the inDelete flag. This will ensure that we don't
  169. // update the store until we have completed all the endpoint
  170. // leaves and deletes. And when endpoint leaves and deletes
  171. // are completed then we can finally delete the sandbox object
  172. // altogether from the data store. If the daemon exits
  173. // ungracefully in the middle of a sandbox delete this way we
  174. // will have all the references to the endpoints in the
  175. // sandbox so that we can clean them up when we restart
  176. sb.inDelete = true
  177. sb.Unlock()
  178. c := sb.controller
  179. // Detach from all endpoints
  180. retain := false
  181. for _, ep := range sb.getConnectedEndpoints() {
  182. // gw network endpoint detach and removal are automatic
  183. if ep.endpointInGWNetwork() && !force {
  184. continue
  185. }
  186. // Retain the sanbdox if we can't obtain the network from store.
  187. if _, err := c.getNetworkFromStore(ep.getNetwork().ID()); err != nil {
  188. if c.isDistributedControl() {
  189. retain = true
  190. }
  191. logrus.Warnf("Failed getting network for ep %s during sandbox %s delete: %v", ep.ID(), sb.ID(), err)
  192. continue
  193. }
  194. if !force {
  195. if err := ep.Leave(sb); err != nil {
  196. logrus.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  197. }
  198. }
  199. if err := ep.Delete(force); err != nil {
  200. logrus.Warnf("Failed deleting endpoint %s: %v\n", ep.ID(), err)
  201. }
  202. }
  203. if retain {
  204. sb.Lock()
  205. sb.inDelete = false
  206. sb.Unlock()
  207. return fmt.Errorf("could not cleanup all the endpoints in container %s / sandbox %s", sb.containerID, sb.id)
  208. }
  209. // Container is going away. Path cache in etchosts is most
  210. // likely not required any more. Drop it.
  211. etchosts.Drop(sb.config.hostsPath)
  212. if sb.resolver != nil {
  213. sb.resolver.Stop()
  214. }
  215. if sb.osSbox != nil && !sb.config.useDefaultSandBox {
  216. sb.osSbox.Destroy()
  217. }
  218. if err := sb.storeDelete(); err != nil {
  219. logrus.Warnf("Failed to delete sandbox %s from store: %v", sb.ID(), err)
  220. }
  221. c.Lock()
  222. if sb.ingress {
  223. c.ingressSandbox = nil
  224. }
  225. delete(c.sandboxes, sb.ID())
  226. c.Unlock()
  227. return nil
  228. }
  229. func (sb *sandbox) Rename(name string) error {
  230. var err error
  231. for _, ep := range sb.getConnectedEndpoints() {
  232. if ep.endpointInGWNetwork() {
  233. continue
  234. }
  235. oldName := ep.Name()
  236. lEp := ep
  237. if err = ep.rename(name); err != nil {
  238. break
  239. }
  240. defer func() {
  241. if err != nil {
  242. lEp.rename(oldName)
  243. }
  244. }()
  245. }
  246. return err
  247. }
  248. func (sb *sandbox) Refresh(options ...SandboxOption) error {
  249. // Store connected endpoints
  250. epList := sb.getConnectedEndpoints()
  251. // Detach from all endpoints
  252. for _, ep := range epList {
  253. if err := ep.Leave(sb); err != nil {
  254. logrus.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  255. }
  256. }
  257. // Re-apply options
  258. sb.config = containerConfig{}
  259. sb.processOptions(options...)
  260. // Setup discovery files
  261. if err := sb.setupResolutionFiles(); err != nil {
  262. return err
  263. }
  264. // Re-connect to all endpoints
  265. for _, ep := range epList {
  266. if err := ep.Join(sb); err != nil {
  267. logrus.Warnf("Failed attach sandbox %s to endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  268. }
  269. }
  270. return nil
  271. }
  272. func (sb *sandbox) MarshalJSON() ([]byte, error) {
  273. sb.Lock()
  274. defer sb.Unlock()
  275. // We are just interested in the container ID. This can be expanded to include all of containerInfo if there is a need
  276. return json.Marshal(sb.id)
  277. }
  278. func (sb *sandbox) UnmarshalJSON(b []byte) (err error) {
  279. sb.Lock()
  280. defer sb.Unlock()
  281. var id string
  282. if err := json.Unmarshal(b, &id); err != nil {
  283. return err
  284. }
  285. sb.id = id
  286. return nil
  287. }
  288. func (sb *sandbox) Endpoints() []Endpoint {
  289. sb.Lock()
  290. defer sb.Unlock()
  291. endpoints := make([]Endpoint, len(sb.endpoints))
  292. for i, ep := range sb.endpoints {
  293. endpoints[i] = ep
  294. }
  295. return endpoints
  296. }
  297. func (sb *sandbox) getConnectedEndpoints() []*endpoint {
  298. sb.Lock()
  299. defer sb.Unlock()
  300. eps := make([]*endpoint, len(sb.endpoints))
  301. for i, ep := range sb.endpoints {
  302. eps[i] = ep
  303. }
  304. return eps
  305. }
  306. func (sb *sandbox) removeEndpoint(ep *endpoint) {
  307. sb.Lock()
  308. defer sb.Unlock()
  309. for i, e := range sb.endpoints {
  310. if e == ep {
  311. heap.Remove(&sb.endpoints, i)
  312. return
  313. }
  314. }
  315. }
  316. func (sb *sandbox) getEndpoint(id string) *endpoint {
  317. sb.Lock()
  318. defer sb.Unlock()
  319. for _, ep := range sb.endpoints {
  320. if ep.id == id {
  321. return ep
  322. }
  323. }
  324. return nil
  325. }
  326. func (sb *sandbox) updateGateway(ep *endpoint) error {
  327. sb.Lock()
  328. osSbox := sb.osSbox
  329. sb.Unlock()
  330. if osSbox == nil {
  331. return nil
  332. }
  333. osSbox.UnsetGateway()
  334. osSbox.UnsetGatewayIPv6()
  335. if ep == nil {
  336. return nil
  337. }
  338. ep.Lock()
  339. joinInfo := ep.joinInfo
  340. ep.Unlock()
  341. if err := osSbox.SetGateway(joinInfo.gw); err != nil {
  342. return fmt.Errorf("failed to set gateway while updating gateway: %v", err)
  343. }
  344. if err := osSbox.SetGatewayIPv6(joinInfo.gw6); err != nil {
  345. return fmt.Errorf("failed to set IPv6 gateway while updating gateway: %v", err)
  346. }
  347. return nil
  348. }
  349. func (sb *sandbox) HandleQueryResp(name string, ip net.IP) {
  350. for _, ep := range sb.getConnectedEndpoints() {
  351. n := ep.getNetwork()
  352. n.HandleQueryResp(name, ip)
  353. }
  354. }
  355. func (sb *sandbox) ResolveIP(ip string) string {
  356. var svc string
  357. logrus.Debugf("IP To resolve %v", ip)
  358. for _, ep := range sb.getConnectedEndpoints() {
  359. n := ep.getNetwork()
  360. svc = n.ResolveIP(ip)
  361. if len(svc) != 0 {
  362. return svc
  363. }
  364. }
  365. return svc
  366. }
  367. func (sb *sandbox) ExecFunc(f func()) error {
  368. sb.Lock()
  369. osSbox := sb.osSbox
  370. sb.Unlock()
  371. if osSbox != nil {
  372. return osSbox.InvokeFunc(f)
  373. }
  374. return fmt.Errorf("osl sandbox unavailable in ExecFunc for %v", sb.ContainerID())
  375. }
  376. func (sb *sandbox) ResolveService(name string) ([]*net.SRV, []net.IP) {
  377. srv := []*net.SRV{}
  378. ip := []net.IP{}
  379. logrus.Debugf("Service name To resolve: %v", name)
  380. // There are DNS implementaions that allow SRV queries for names not in
  381. // the format defined by RFC 2782. Hence specific validations checks are
  382. // not done
  383. parts := strings.Split(name, ".")
  384. if len(parts) < 3 {
  385. return nil, nil
  386. }
  387. for _, ep := range sb.getConnectedEndpoints() {
  388. n := ep.getNetwork()
  389. srv, ip = n.ResolveService(name)
  390. if len(srv) > 0 {
  391. break
  392. }
  393. }
  394. return srv, ip
  395. }
  396. func getDynamicNwEndpoints(epList []*endpoint) []*endpoint {
  397. eps := []*endpoint{}
  398. for _, ep := range epList {
  399. n := ep.getNetwork()
  400. if n.dynamic && !n.ingress {
  401. eps = append(eps, ep)
  402. }
  403. }
  404. return eps
  405. }
  406. func getIngressNwEndpoint(epList []*endpoint) *endpoint {
  407. for _, ep := range epList {
  408. n := ep.getNetwork()
  409. if n.ingress {
  410. return ep
  411. }
  412. }
  413. return nil
  414. }
  415. func getLocalNwEndpoints(epList []*endpoint) []*endpoint {
  416. eps := []*endpoint{}
  417. for _, ep := range epList {
  418. n := ep.getNetwork()
  419. if !n.dynamic && !n.ingress {
  420. eps = append(eps, ep)
  421. }
  422. }
  423. return eps
  424. }
  425. func (sb *sandbox) ResolveName(name string, ipType int) ([]net.IP, bool) {
  426. // Embedded server owns the docker network domain. Resolution should work
  427. // for both container_name and container_name.network_name
  428. // We allow '.' in service name and network name. For a name a.b.c.d the
  429. // following have to tried;
  430. // {a.b.c.d in the networks container is connected to}
  431. // {a.b.c in network d},
  432. // {a.b in network c.d},
  433. // {a in network b.c.d},
  434. logrus.Debugf("Name To resolve: %v", name)
  435. name = strings.TrimSuffix(name, ".")
  436. reqName := []string{name}
  437. networkName := []string{""}
  438. if strings.Contains(name, ".") {
  439. var i int
  440. dup := name
  441. for {
  442. if i = strings.LastIndex(dup, "."); i == -1 {
  443. break
  444. }
  445. networkName = append(networkName, name[i+1:])
  446. reqName = append(reqName, name[:i])
  447. dup = dup[:i]
  448. }
  449. }
  450. epList := sb.getConnectedEndpoints()
  451. // In swarm mode services with exposed ports are connected to user overlay
  452. // network, ingress network and docker_gwbridge network. Name resolution
  453. // should prioritize returning the VIP/IPs on user overlay network.
  454. newList := []*endpoint{}
  455. if !sb.controller.isDistributedControl() {
  456. newList = append(newList, getDynamicNwEndpoints(epList)...)
  457. ingressEP := getIngressNwEndpoint(epList)
  458. if ingressEP != nil {
  459. newList = append(newList, ingressEP)
  460. }
  461. newList = append(newList, getLocalNwEndpoints(epList)...)
  462. epList = newList
  463. }
  464. for i := 0; i < len(reqName); i++ {
  465. // First check for local container alias
  466. ip, ipv6Miss := sb.resolveName(reqName[i], networkName[i], epList, true, ipType)
  467. if ip != nil {
  468. return ip, false
  469. }
  470. if ipv6Miss {
  471. return ip, ipv6Miss
  472. }
  473. // Resolve the actual container name
  474. ip, ipv6Miss = sb.resolveName(reqName[i], networkName[i], epList, false, ipType)
  475. if ip != nil {
  476. return ip, false
  477. }
  478. if ipv6Miss {
  479. return ip, ipv6Miss
  480. }
  481. }
  482. return nil, false
  483. }
  484. func (sb *sandbox) resolveName(req string, networkName string, epList []*endpoint, alias bool, ipType int) ([]net.IP, bool) {
  485. var ipv6Miss bool
  486. for _, ep := range epList {
  487. name := req
  488. n := ep.getNetwork()
  489. if networkName != "" && networkName != n.Name() {
  490. continue
  491. }
  492. if alias {
  493. if ep.aliases == nil {
  494. continue
  495. }
  496. var ok bool
  497. ep.Lock()
  498. name, ok = ep.aliases[req]
  499. ep.Unlock()
  500. if !ok {
  501. continue
  502. }
  503. } else {
  504. // If it is a regular lookup and if the requested name is an alias
  505. // don't perform a svc lookup for this endpoint.
  506. ep.Lock()
  507. if _, ok := ep.aliases[req]; ok {
  508. ep.Unlock()
  509. continue
  510. }
  511. ep.Unlock()
  512. }
  513. ip, miss := n.ResolveName(name, ipType)
  514. if ip != nil {
  515. return ip, false
  516. }
  517. if miss {
  518. ipv6Miss = miss
  519. }
  520. }
  521. return nil, ipv6Miss
  522. }
  523. func (sb *sandbox) SetKey(basePath string) error {
  524. start := time.Now()
  525. defer func() {
  526. logrus.Debugf("sandbox set key processing took %s for container %s", time.Now().Sub(start), sb.ContainerID())
  527. }()
  528. if basePath == "" {
  529. return types.BadRequestErrorf("invalid sandbox key")
  530. }
  531. sb.Lock()
  532. oldosSbox := sb.osSbox
  533. sb.Unlock()
  534. if oldosSbox != nil {
  535. // If we already have an OS sandbox, release the network resources from that
  536. // and destroy the OS snab. We are moving into a new home further down. Note that none
  537. // of the network resources gets destroyed during the move.
  538. sb.releaseOSSbox()
  539. }
  540. osSbox, err := osl.GetSandboxForExternalKey(basePath, sb.Key())
  541. if err != nil {
  542. return err
  543. }
  544. sb.Lock()
  545. sb.osSbox = osSbox
  546. sb.Unlock()
  547. defer func() {
  548. if err != nil {
  549. sb.Lock()
  550. sb.osSbox = nil
  551. sb.Unlock()
  552. }
  553. }()
  554. // If the resolver was setup before stop it and set it up in the
  555. // new osl sandbox.
  556. if oldosSbox != nil && sb.resolver != nil {
  557. sb.resolver.Stop()
  558. if err := sb.osSbox.InvokeFunc(sb.resolver.SetupFunc(0)); err == nil {
  559. if err := sb.resolver.Start(); err != nil {
  560. logrus.Errorf("Resolver Start failed for container %s, %q", sb.ContainerID(), err)
  561. }
  562. } else {
  563. logrus.Errorf("Resolver Setup Function failed for container %s, %q", sb.ContainerID(), err)
  564. }
  565. }
  566. for _, ep := range sb.getConnectedEndpoints() {
  567. if err = sb.populateNetworkResources(ep); err != nil {
  568. return err
  569. }
  570. }
  571. return nil
  572. }
  573. func (sb *sandbox) EnableService() error {
  574. for _, ep := range sb.getConnectedEndpoints() {
  575. if ep.enableService(true) {
  576. if err := ep.addServiceInfoToCluster(); err != nil {
  577. ep.enableService(false)
  578. return fmt.Errorf("could not update state for endpoint %s into cluster: %v", ep.Name(), err)
  579. }
  580. }
  581. }
  582. return nil
  583. }
  584. func (sb *sandbox) DisableService() error {
  585. for _, ep := range sb.getConnectedEndpoints() {
  586. if ep.enableService(false) {
  587. if err := ep.deleteServiceInfoFromCluster(); err != nil {
  588. ep.enableService(true)
  589. return fmt.Errorf("could not delete state for endpoint %s from cluster: %v", ep.Name(), err)
  590. }
  591. }
  592. }
  593. return nil
  594. }
  595. func releaseOSSboxResources(osSbox osl.Sandbox, ep *endpoint) {
  596. for _, i := range osSbox.Info().Interfaces() {
  597. // Only remove the interfaces owned by this endpoint from the sandbox.
  598. if ep.hasInterface(i.SrcName()) {
  599. if err := i.Remove(); err != nil {
  600. logrus.Debugf("Remove interface %s failed: %v", i.SrcName(), err)
  601. }
  602. }
  603. }
  604. ep.Lock()
  605. joinInfo := ep.joinInfo
  606. ep.Unlock()
  607. if joinInfo == nil {
  608. return
  609. }
  610. // Remove non-interface routes.
  611. for _, r := range joinInfo.StaticRoutes {
  612. if err := osSbox.RemoveStaticRoute(r); err != nil {
  613. logrus.Debugf("Remove route failed: %v", err)
  614. }
  615. }
  616. }
  617. func (sb *sandbox) releaseOSSbox() {
  618. sb.Lock()
  619. osSbox := sb.osSbox
  620. sb.osSbox = nil
  621. sb.Unlock()
  622. if osSbox == nil {
  623. return
  624. }
  625. for _, ep := range sb.getConnectedEndpoints() {
  626. releaseOSSboxResources(osSbox, ep)
  627. }
  628. osSbox.Destroy()
  629. }
  630. func (sb *sandbox) restoreOslSandbox() error {
  631. var routes []*types.StaticRoute
  632. // restore osl sandbox
  633. Ifaces := make(map[string][]osl.IfaceOption)
  634. for _, ep := range sb.endpoints {
  635. var ifaceOptions []osl.IfaceOption
  636. ep.Lock()
  637. joinInfo := ep.joinInfo
  638. i := ep.iface
  639. ep.Unlock()
  640. if i == nil {
  641. logrus.Errorf("error restoring endpoint %s for container %s", ep.Name(), sb.ContainerID())
  642. continue
  643. }
  644. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes))
  645. if i.addrv6 != nil && i.addrv6.IP.To16() != nil {
  646. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(i.addrv6))
  647. }
  648. if i.mac != nil {
  649. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().MacAddress(i.mac))
  650. }
  651. if len(i.llAddrs) != 0 {
  652. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().LinkLocalAddresses(i.llAddrs))
  653. }
  654. if len(ep.virtualIP) != 0 {
  655. vipAlias := &net.IPNet{IP: ep.virtualIP, Mask: net.CIDRMask(32, 32)}
  656. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().IPAliases([]*net.IPNet{vipAlias}))
  657. }
  658. Ifaces[fmt.Sprintf("%s+%s", i.srcName, i.dstPrefix)] = ifaceOptions
  659. if joinInfo != nil {
  660. for _, r := range joinInfo.StaticRoutes {
  661. routes = append(routes, r)
  662. }
  663. }
  664. if ep.needResolver() {
  665. sb.startResolver(true)
  666. }
  667. }
  668. gwep := sb.getGatewayEndpoint()
  669. if gwep == nil {
  670. return nil
  671. }
  672. // restore osl sandbox
  673. err := sb.osSbox.Restore(Ifaces, routes, gwep.joinInfo.gw, gwep.joinInfo.gw6)
  674. if err != nil {
  675. return err
  676. }
  677. return nil
  678. }
  679. func (sb *sandbox) populateNetworkResources(ep *endpoint) error {
  680. sb.Lock()
  681. if sb.osSbox == nil {
  682. sb.Unlock()
  683. return nil
  684. }
  685. inDelete := sb.inDelete
  686. sb.Unlock()
  687. ep.Lock()
  688. joinInfo := ep.joinInfo
  689. i := ep.iface
  690. ep.Unlock()
  691. if ep.needResolver() {
  692. sb.startResolver(false)
  693. }
  694. if i != nil && i.srcName != "" {
  695. var ifaceOptions []osl.IfaceOption
  696. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes))
  697. if i.addrv6 != nil && i.addrv6.IP.To16() != nil {
  698. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(i.addrv6))
  699. }
  700. if len(i.llAddrs) != 0 {
  701. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().LinkLocalAddresses(i.llAddrs))
  702. }
  703. if len(ep.virtualIP) != 0 {
  704. vipAlias := &net.IPNet{IP: ep.virtualIP, Mask: net.CIDRMask(32, 32)}
  705. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().IPAliases([]*net.IPNet{vipAlias}))
  706. }
  707. if i.mac != nil {
  708. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().MacAddress(i.mac))
  709. }
  710. if err := sb.osSbox.AddInterface(i.srcName, i.dstPrefix, ifaceOptions...); err != nil {
  711. return fmt.Errorf("failed to add interface %s to sandbox: %v", i.srcName, err)
  712. }
  713. }
  714. if joinInfo != nil {
  715. // Set up non-interface routes.
  716. for _, r := range joinInfo.StaticRoutes {
  717. if err := sb.osSbox.AddStaticRoute(r); err != nil {
  718. return fmt.Errorf("failed to add static route %s: %v", r.Destination.String(), err)
  719. }
  720. }
  721. }
  722. if ep == sb.getGatewayEndpoint() {
  723. if err := sb.updateGateway(ep); err != nil {
  724. return err
  725. }
  726. }
  727. // Make sure to add the endpoint to the populated endpoint set
  728. // before populating loadbalancers.
  729. sb.Lock()
  730. sb.populatedEndpoints[ep.ID()] = struct{}{}
  731. sb.Unlock()
  732. // Populate load balancer only after updating all the other
  733. // information including gateway and other routes so that
  734. // loadbalancers are populated all the network state is in
  735. // place in the sandbox.
  736. sb.populateLoadbalancers(ep)
  737. // Only update the store if we did not come here as part of
  738. // sandbox delete. If we came here as part of delete then do
  739. // not bother updating the store. The sandbox object will be
  740. // deleted anyway
  741. if !inDelete {
  742. return sb.storeUpdate()
  743. }
  744. return nil
  745. }
  746. func (sb *sandbox) clearNetworkResources(origEp *endpoint) error {
  747. ep := sb.getEndpoint(origEp.id)
  748. if ep == nil {
  749. return fmt.Errorf("could not find the sandbox endpoint data for endpoint %s",
  750. origEp.id)
  751. }
  752. sb.Lock()
  753. osSbox := sb.osSbox
  754. inDelete := sb.inDelete
  755. sb.Unlock()
  756. if osSbox != nil {
  757. releaseOSSboxResources(osSbox, ep)
  758. }
  759. sb.Lock()
  760. delete(sb.populatedEndpoints, ep.ID())
  761. if len(sb.endpoints) == 0 {
  762. // sb.endpoints should never be empty and this is unexpected error condition
  763. // We log an error message to note this down for debugging purposes.
  764. logrus.Errorf("No endpoints in sandbox while trying to remove endpoint %s", ep.Name())
  765. sb.Unlock()
  766. return nil
  767. }
  768. var (
  769. gwepBefore, gwepAfter *endpoint
  770. index = -1
  771. )
  772. for i, e := range sb.endpoints {
  773. if e == ep {
  774. index = i
  775. }
  776. if len(e.Gateway()) > 0 && gwepBefore == nil {
  777. gwepBefore = e
  778. }
  779. if index != -1 && gwepBefore != nil {
  780. break
  781. }
  782. }
  783. heap.Remove(&sb.endpoints, index)
  784. for _, e := range sb.endpoints {
  785. if len(e.Gateway()) > 0 {
  786. gwepAfter = e
  787. break
  788. }
  789. }
  790. delete(sb.epPriority, ep.ID())
  791. sb.Unlock()
  792. if gwepAfter != nil && gwepBefore != gwepAfter {
  793. sb.updateGateway(gwepAfter)
  794. }
  795. // Only update the store if we did not come here as part of
  796. // sandbox delete. If we came here as part of delete then do
  797. // not bother updating the store. The sandbox object will be
  798. // deleted anyway
  799. if !inDelete {
  800. return sb.storeUpdate()
  801. }
  802. return nil
  803. }
  804. func (sb *sandbox) isEndpointPopulated(ep *endpoint) bool {
  805. sb.Lock()
  806. _, ok := sb.populatedEndpoints[ep.ID()]
  807. sb.Unlock()
  808. return ok
  809. }
  810. // joinLeaveStart waits to ensure there are no joins or leaves in progress and
  811. // marks this join/leave in progress without race
  812. func (sb *sandbox) joinLeaveStart() {
  813. sb.Lock()
  814. defer sb.Unlock()
  815. for sb.joinLeaveDone != nil {
  816. joinLeaveDone := sb.joinLeaveDone
  817. sb.Unlock()
  818. select {
  819. case <-joinLeaveDone:
  820. }
  821. sb.Lock()
  822. }
  823. sb.joinLeaveDone = make(chan struct{})
  824. }
  825. // joinLeaveEnd marks the end of this join/leave operation and
  826. // signals the same without race to other join and leave waiters
  827. func (sb *sandbox) joinLeaveEnd() {
  828. sb.Lock()
  829. defer sb.Unlock()
  830. if sb.joinLeaveDone != nil {
  831. close(sb.joinLeaveDone)
  832. sb.joinLeaveDone = nil
  833. }
  834. }
  835. func (sb *sandbox) hasPortConfigs() bool {
  836. opts := sb.Labels()
  837. _, hasExpPorts := opts[netlabel.ExposedPorts]
  838. _, hasPortMaps := opts[netlabel.PortMap]
  839. return hasExpPorts || hasPortMaps
  840. }
  841. // OptionHostname function returns an option setter for hostname option to
  842. // be passed to NewSandbox method.
  843. func OptionHostname(name string) SandboxOption {
  844. return func(sb *sandbox) {
  845. sb.config.hostName = name
  846. }
  847. }
  848. // OptionDomainname function returns an option setter for domainname option to
  849. // be passed to NewSandbox method.
  850. func OptionDomainname(name string) SandboxOption {
  851. return func(sb *sandbox) {
  852. sb.config.domainName = name
  853. }
  854. }
  855. // OptionHostsPath function returns an option setter for hostspath option to
  856. // be passed to NewSandbox method.
  857. func OptionHostsPath(path string) SandboxOption {
  858. return func(sb *sandbox) {
  859. sb.config.hostsPath = path
  860. }
  861. }
  862. // OptionOriginHostsPath function returns an option setter for origin hosts file path
  863. // to be passed to NewSandbox method.
  864. func OptionOriginHostsPath(path string) SandboxOption {
  865. return func(sb *sandbox) {
  866. sb.config.originHostsPath = path
  867. }
  868. }
  869. // OptionExtraHost function returns an option setter for extra /etc/hosts options
  870. // which is a name and IP as strings.
  871. func OptionExtraHost(name string, IP string) SandboxOption {
  872. return func(sb *sandbox) {
  873. sb.config.extraHosts = append(sb.config.extraHosts, extraHost{name: name, IP: IP})
  874. }
  875. }
  876. // OptionParentUpdate function returns an option setter for parent container
  877. // which needs to update the IP address for the linked container.
  878. func OptionParentUpdate(cid string, name, ip string) SandboxOption {
  879. return func(sb *sandbox) {
  880. sb.config.parentUpdates = append(sb.config.parentUpdates, parentUpdate{cid: cid, name: name, ip: ip})
  881. }
  882. }
  883. // OptionResolvConfPath function returns an option setter for resolvconfpath option to
  884. // be passed to net container methods.
  885. func OptionResolvConfPath(path string) SandboxOption {
  886. return func(sb *sandbox) {
  887. sb.config.resolvConfPath = path
  888. }
  889. }
  890. // OptionOriginResolvConfPath function returns an option setter to set the path to the
  891. // origin resolv.conf file to be passed to net container methods.
  892. func OptionOriginResolvConfPath(path string) SandboxOption {
  893. return func(sb *sandbox) {
  894. sb.config.originResolvConfPath = path
  895. }
  896. }
  897. // OptionDNS function returns an option setter for dns entry option to
  898. // be passed to container Create method.
  899. func OptionDNS(dns string) SandboxOption {
  900. return func(sb *sandbox) {
  901. sb.config.dnsList = append(sb.config.dnsList, dns)
  902. }
  903. }
  904. // OptionDNSSearch function returns an option setter for dns search entry option to
  905. // be passed to container Create method.
  906. func OptionDNSSearch(search string) SandboxOption {
  907. return func(sb *sandbox) {
  908. sb.config.dnsSearchList = append(sb.config.dnsSearchList, search)
  909. }
  910. }
  911. // OptionDNSOptions function returns an option setter for dns options entry option to
  912. // be passed to container Create method.
  913. func OptionDNSOptions(options string) SandboxOption {
  914. return func(sb *sandbox) {
  915. sb.config.dnsOptionsList = append(sb.config.dnsOptionsList, options)
  916. }
  917. }
  918. // OptionUseDefaultSandbox function returns an option setter for using default sandbox to
  919. // be passed to container Create method.
  920. func OptionUseDefaultSandbox() SandboxOption {
  921. return func(sb *sandbox) {
  922. sb.config.useDefaultSandBox = true
  923. }
  924. }
  925. // OptionUseExternalKey function returns an option setter for using provided namespace
  926. // instead of creating one.
  927. func OptionUseExternalKey() SandboxOption {
  928. return func(sb *sandbox) {
  929. sb.config.useExternalKey = true
  930. }
  931. }
  932. // OptionGeneric function returns an option setter for Generic configuration
  933. // that is not managed by libNetwork but can be used by the Drivers during the call to
  934. // net container creation method. Container Labels are a good example.
  935. func OptionGeneric(generic map[string]interface{}) SandboxOption {
  936. return func(sb *sandbox) {
  937. if sb.config.generic == nil {
  938. sb.config.generic = make(map[string]interface{}, len(generic))
  939. }
  940. for k, v := range generic {
  941. sb.config.generic[k] = v
  942. }
  943. }
  944. }
  945. // OptionExposedPorts function returns an option setter for the container exposed
  946. // ports option to be passed to container Create method.
  947. func OptionExposedPorts(exposedPorts []types.TransportPort) SandboxOption {
  948. return func(sb *sandbox) {
  949. if sb.config.generic == nil {
  950. sb.config.generic = make(map[string]interface{})
  951. }
  952. // Defensive copy
  953. eps := make([]types.TransportPort, len(exposedPorts))
  954. copy(eps, exposedPorts)
  955. // Store endpoint label and in generic because driver needs it
  956. sb.config.exposedPorts = eps
  957. sb.config.generic[netlabel.ExposedPorts] = eps
  958. }
  959. }
  960. // OptionPortMapping function returns an option setter for the mapping
  961. // ports option to be passed to container Create method.
  962. func OptionPortMapping(portBindings []types.PortBinding) SandboxOption {
  963. return func(sb *sandbox) {
  964. if sb.config.generic == nil {
  965. sb.config.generic = make(map[string]interface{})
  966. }
  967. // Store a copy of the bindings as generic data to pass to the driver
  968. pbs := make([]types.PortBinding, len(portBindings))
  969. copy(pbs, portBindings)
  970. sb.config.generic[netlabel.PortMap] = pbs
  971. }
  972. }
  973. // OptionIngress function returns an option setter for marking a
  974. // sandbox as the controller's ingress sandbox.
  975. func OptionIngress() SandboxOption {
  976. return func(sb *sandbox) {
  977. sb.ingress = true
  978. }
  979. }
  980. func (eh epHeap) Len() int { return len(eh) }
  981. func (eh epHeap) Less(i, j int) bool {
  982. var (
  983. cip, cjp int
  984. ok bool
  985. )
  986. ci, _ := eh[i].getSandbox()
  987. cj, _ := eh[j].getSandbox()
  988. epi := eh[i]
  989. epj := eh[j]
  990. if epi.endpointInGWNetwork() {
  991. return false
  992. }
  993. if epj.endpointInGWNetwork() {
  994. return true
  995. }
  996. if epi.getNetwork().Internal() {
  997. return false
  998. }
  999. if epj.getNetwork().Internal() {
  1000. return true
  1001. }
  1002. if epi.joinInfo != nil && epj.joinInfo != nil {
  1003. if (epi.joinInfo.gw != nil && epi.joinInfo.gw6 != nil) &&
  1004. (epj.joinInfo.gw == nil || epj.joinInfo.gw6 == nil) {
  1005. return true
  1006. }
  1007. if (epj.joinInfo.gw != nil && epj.joinInfo.gw6 != nil) &&
  1008. (epi.joinInfo.gw == nil || epi.joinInfo.gw6 == nil) {
  1009. return false
  1010. }
  1011. }
  1012. if ci != nil {
  1013. cip, ok = ci.epPriority[eh[i].ID()]
  1014. if !ok {
  1015. cip = 0
  1016. }
  1017. }
  1018. if cj != nil {
  1019. cjp, ok = cj.epPriority[eh[j].ID()]
  1020. if !ok {
  1021. cjp = 0
  1022. }
  1023. }
  1024. if cip == cjp {
  1025. return eh[i].network.Name() < eh[j].network.Name()
  1026. }
  1027. return cip > cjp
  1028. }
  1029. func (eh epHeap) Swap(i, j int) { eh[i], eh[j] = eh[j], eh[i] }
  1030. func (eh *epHeap) Push(x interface{}) {
  1031. *eh = append(*eh, x.(*endpoint))
  1032. }
  1033. func (eh *epHeap) Pop() interface{} {
  1034. old := *eh
  1035. n := len(old)
  1036. x := old[n-1]
  1037. *eh = old[0 : n-1]
  1038. return x
  1039. }
  1040. func (sb *sandbox) NdotsSet() bool {
  1041. return sb.ndotsSet
  1042. }