sandbox.go 29 KB

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