sandbox.go 28 KB

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