sandbox.go 29 KB

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