sandbox.go 29 KB

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