sandbox.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  1. package libnetwork
  2. import (
  3. "container/heap"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "sync"
  11. log "github.com/Sirupsen/logrus"
  12. "github.com/docker/libnetwork/etchosts"
  13. "github.com/docker/libnetwork/osl"
  14. "github.com/docker/libnetwork/resolvconf"
  15. "github.com/docker/libnetwork/types"
  16. )
  17. // Sandbox provides the control over the network container entity. It is a one to one mapping with the container.
  18. type Sandbox interface {
  19. // ID returns the ID of the sandbox
  20. ID() string
  21. // Key returns the sandbox's key
  22. Key() string
  23. // ContainerID returns the container id associated to this sandbox
  24. ContainerID() string
  25. // Labels returns the sandbox's labels
  26. Labels() map[string]interface{}
  27. // Statistics retrieves the interfaces' statistics for the sandbox
  28. Statistics() (map[string]*osl.InterfaceStatistics, error)
  29. // Refresh leaves all the endpoints, resets and re-apply the options,
  30. // re-joins all the endpoints without destroying the osl sandbox
  31. Refresh(options ...SandboxOption) error
  32. // SetKey updates the Sandbox Key
  33. SetKey(key string) error
  34. // Delete destroys this container after detaching it from all connected endpoints.
  35. Delete() error
  36. }
  37. // SandboxOption is a option setter function type used to pass varios options to
  38. // NewNetContainer method. The various setter functions of type SandboxOption are
  39. // provided by libnetwork, they look like ContainerOptionXXXX(...)
  40. type SandboxOption func(sb *sandbox)
  41. func (sb *sandbox) processOptions(options ...SandboxOption) {
  42. for _, opt := range options {
  43. if opt != nil {
  44. opt(sb)
  45. }
  46. }
  47. }
  48. type epHeap []*endpoint
  49. type sandbox struct {
  50. id string
  51. containerID string
  52. config containerConfig
  53. osSbox osl.Sandbox
  54. controller *controller
  55. refCnt int
  56. hostsOnce sync.Once
  57. endpoints epHeap
  58. epPriority map[string]int
  59. joinLeaveDone chan struct{}
  60. sync.Mutex
  61. }
  62. // These are the container configs used to customize container /etc/hosts file.
  63. type hostsPathConfig struct {
  64. hostName string
  65. domainName string
  66. hostsPath string
  67. originHostsPath string
  68. extraHosts []extraHost
  69. parentUpdates []parentUpdate
  70. }
  71. type parentUpdate struct {
  72. cid string
  73. name string
  74. ip string
  75. }
  76. type extraHost struct {
  77. name string
  78. IP string
  79. }
  80. // These are the container configs used to customize container /etc/resolv.conf file.
  81. type resolvConfPathConfig struct {
  82. resolvConfPath string
  83. originResolvConfPath string
  84. resolvConfHashFile string
  85. dnsList []string
  86. dnsSearchList []string
  87. dnsOptionsList []string
  88. }
  89. type containerConfig struct {
  90. hostsPathConfig
  91. resolvConfPathConfig
  92. generic map[string]interface{}
  93. useDefaultSandBox bool
  94. useExternalKey bool
  95. prio int // higher the value, more the priority
  96. }
  97. func (sb *sandbox) ID() string {
  98. return sb.id
  99. }
  100. func (sb *sandbox) ContainerID() string {
  101. return sb.containerID
  102. }
  103. func (sb *sandbox) Key() string {
  104. if sb.config.useDefaultSandBox {
  105. return osl.GenerateKey("default")
  106. }
  107. return osl.GenerateKey(sb.id)
  108. }
  109. func (sb *sandbox) Labels() map[string]interface{} {
  110. return sb.config.generic
  111. }
  112. func (sb *sandbox) Statistics() (map[string]*osl.InterfaceStatistics, error) {
  113. m := make(map[string]*osl.InterfaceStatistics)
  114. if sb.osSbox == nil {
  115. return m, nil
  116. }
  117. var err error
  118. for _, i := range sb.osSbox.Info().Interfaces() {
  119. if m[i.DstName()], err = i.Statistics(); err != nil {
  120. return m, err
  121. }
  122. }
  123. return m, nil
  124. }
  125. func (sb *sandbox) Delete() error {
  126. c := sb.controller
  127. // Detach from all endpoints
  128. for _, ep := range sb.getConnectedEndpoints() {
  129. // endpoint in the Gateway network will be cleaned up
  130. // when when sandbox no longer needs external connectivity
  131. if ep.endpointInGWNetwork() {
  132. continue
  133. }
  134. if err := ep.Leave(sb); err != nil {
  135. log.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  136. }
  137. }
  138. if sb.osSbox != nil {
  139. sb.osSbox.Destroy()
  140. }
  141. c.Lock()
  142. delete(c.sandboxes, sb.ID())
  143. c.Unlock()
  144. return nil
  145. }
  146. func (sb *sandbox) Refresh(options ...SandboxOption) error {
  147. // Store connected endpoints
  148. epList := sb.getConnectedEndpoints()
  149. // Detach from all endpoints
  150. for _, ep := range epList {
  151. if err := ep.Leave(sb); err != nil {
  152. log.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  153. }
  154. }
  155. // Re-apply options
  156. sb.config = containerConfig{}
  157. sb.processOptions(options...)
  158. // Setup discovery files
  159. if err := sb.setupResolutionFiles(); err != nil {
  160. return err
  161. }
  162. // Re -connect to all endpoints
  163. for _, ep := range epList {
  164. if err := ep.Join(sb); err != nil {
  165. log.Warnf("Failed attach sandbox %s to endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  166. }
  167. }
  168. return nil
  169. }
  170. func (sb *sandbox) MarshalJSON() ([]byte, error) {
  171. sb.Lock()
  172. defer sb.Unlock()
  173. // We are just interested in the container ID. This can be expanded to include all of containerInfo if there is a need
  174. return json.Marshal(sb.id)
  175. }
  176. func (sb *sandbox) UnmarshalJSON(b []byte) (err error) {
  177. sb.Lock()
  178. defer sb.Unlock()
  179. var id string
  180. if err := json.Unmarshal(b, &id); err != nil {
  181. return err
  182. }
  183. sb.id = id
  184. return nil
  185. }
  186. func (sb *sandbox) setupResolutionFiles() error {
  187. if err := sb.buildHostsFile(); err != nil {
  188. return err
  189. }
  190. if err := sb.updateParentHosts(); err != nil {
  191. return err
  192. }
  193. if err := sb.setupDNS(); err != nil {
  194. return err
  195. }
  196. return nil
  197. }
  198. func (sb *sandbox) getConnectedEndpoints() []*endpoint {
  199. sb.Lock()
  200. defer sb.Unlock()
  201. eps := make([]*endpoint, len(sb.endpoints))
  202. for i, ep := range sb.endpoints {
  203. eps[i] = ep
  204. }
  205. return eps
  206. }
  207. func (sb *sandbox) updateGateway(ep *endpoint) error {
  208. sb.Lock()
  209. osSbox := sb.osSbox
  210. sb.Unlock()
  211. if osSbox == nil {
  212. return nil
  213. }
  214. osSbox.UnsetGateway()
  215. osSbox.UnsetGatewayIPv6()
  216. if ep == nil {
  217. return nil
  218. }
  219. ep.Lock()
  220. joinInfo := ep.joinInfo
  221. ep.Unlock()
  222. if err := osSbox.SetGateway(joinInfo.gw); err != nil {
  223. return fmt.Errorf("failed to set gateway while updating gateway: %v", err)
  224. }
  225. if err := osSbox.SetGatewayIPv6(joinInfo.gw6); err != nil {
  226. return fmt.Errorf("failed to set IPv6 gateway while updating gateway: %v", err)
  227. }
  228. return nil
  229. }
  230. func (sb *sandbox) SetKey(basePath string) error {
  231. var err error
  232. if basePath == "" {
  233. return types.BadRequestErrorf("invalid sandbox key")
  234. }
  235. sb.Lock()
  236. if sb.osSbox != nil {
  237. sb.Unlock()
  238. return types.ForbiddenErrorf("failed to set sandbox key : already assigned")
  239. }
  240. sb.Unlock()
  241. osSbox, err := osl.GetSandboxForExternalKey(basePath, sb.Key())
  242. if err != nil {
  243. return err
  244. }
  245. sb.Lock()
  246. sb.osSbox = osSbox
  247. sb.Unlock()
  248. defer func() {
  249. if err != nil {
  250. sb.Lock()
  251. sb.osSbox = nil
  252. sb.Unlock()
  253. }
  254. }()
  255. for _, ep := range sb.getConnectedEndpoints() {
  256. if err = sb.populateNetworkResources(ep); err != nil {
  257. return err
  258. }
  259. }
  260. return nil
  261. }
  262. func (sb *sandbox) populateNetworkResources(ep *endpoint) error {
  263. sb.Lock()
  264. if sb.osSbox == nil {
  265. sb.Unlock()
  266. return nil
  267. }
  268. sb.Unlock()
  269. ep.Lock()
  270. joinInfo := ep.joinInfo
  271. i := ep.iface
  272. ep.Unlock()
  273. if i.srcName != "" {
  274. var ifaceOptions []osl.IfaceOption
  275. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes))
  276. if i.addrv6 != nil && i.addrv6.IP.To16() != nil {
  277. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(i.addrv6))
  278. }
  279. if err := sb.osSbox.AddInterface(i.srcName, i.dstPrefix, ifaceOptions...); err != nil {
  280. return fmt.Errorf("failed to add interface %s to sandbox: %v", i.srcName, err)
  281. }
  282. }
  283. if joinInfo != nil {
  284. // Set up non-interface routes.
  285. for _, r := range joinInfo.StaticRoutes {
  286. if err := sb.osSbox.AddStaticRoute(r); err != nil {
  287. return fmt.Errorf("failed to add static route %s: %v", r.Destination.String(), err)
  288. }
  289. }
  290. }
  291. for _, gwep := range sb.getConnectedEndpoints() {
  292. if len(gwep.Gateway()) > 0 {
  293. if gwep != ep {
  294. return nil
  295. }
  296. if err := sb.updateGateway(gwep); err != nil {
  297. return err
  298. }
  299. }
  300. }
  301. return nil
  302. }
  303. func (sb *sandbox) clearNetworkResources(ep *endpoint) error {
  304. sb.Lock()
  305. osSbox := sb.osSbox
  306. sb.Unlock()
  307. if osSbox != nil {
  308. for _, i := range osSbox.Info().Interfaces() {
  309. // Only remove the interfaces owned by this endpoint from the sandbox.
  310. if ep.hasInterface(i.SrcName()) {
  311. if err := i.Remove(); err != nil {
  312. log.Debugf("Remove interface failed: %v", err)
  313. }
  314. }
  315. }
  316. ep.Lock()
  317. joinInfo := ep.joinInfo
  318. ep.Unlock()
  319. // Remove non-interface routes.
  320. for _, r := range joinInfo.StaticRoutes {
  321. if err := osSbox.RemoveStaticRoute(r); err != nil {
  322. log.Debugf("Remove route failed: %v", err)
  323. }
  324. }
  325. }
  326. sb.Lock()
  327. if len(sb.endpoints) == 0 {
  328. // sb.endpoints should never be empty and this is unexpected error condition
  329. // We log an error message to note this down for debugging purposes.
  330. log.Errorf("No endpoints in sandbox while trying to remove endpoint %s", ep.Name())
  331. sb.Unlock()
  332. return nil
  333. }
  334. var (
  335. gwepBefore, gwepAfter *endpoint
  336. index = -1
  337. )
  338. for i, e := range sb.endpoints {
  339. if e == ep {
  340. index = i
  341. }
  342. if len(e.Gateway()) > 0 && gwepBefore == nil {
  343. gwepBefore = e
  344. }
  345. if index != -1 && gwepBefore != nil {
  346. break
  347. }
  348. }
  349. heap.Remove(&sb.endpoints, index)
  350. for _, e := range sb.endpoints {
  351. if len(e.Gateway()) > 0 {
  352. gwepAfter = e
  353. break
  354. }
  355. }
  356. delete(sb.epPriority, ep.ID())
  357. sb.Unlock()
  358. if gwepAfter != nil && gwepBefore != gwepAfter {
  359. sb.updateGateway(gwepAfter)
  360. }
  361. return nil
  362. }
  363. const (
  364. defaultPrefix = "/var/lib/docker/network/files"
  365. dirPerm = 0755
  366. filePerm = 0644
  367. )
  368. func (sb *sandbox) buildHostsFile() error {
  369. if sb.config.hostsPath == "" {
  370. sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
  371. }
  372. dir, _ := filepath.Split(sb.config.hostsPath)
  373. if err := createBasePath(dir); err != nil {
  374. return err
  375. }
  376. // This is for the host mode networking
  377. if sb.config.originHostsPath != "" {
  378. if err := copyFile(sb.config.originHostsPath, sb.config.hostsPath); err != nil && !os.IsNotExist(err) {
  379. return types.InternalErrorf("could not copy source hosts file %s to %s: %v", sb.config.originHostsPath, sb.config.hostsPath, err)
  380. }
  381. return nil
  382. }
  383. extraContent := make([]etchosts.Record, 0, len(sb.config.extraHosts))
  384. for _, extraHost := range sb.config.extraHosts {
  385. extraContent = append(extraContent, etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
  386. }
  387. return etchosts.Build(sb.config.hostsPath, "", sb.config.hostName, sb.config.domainName, extraContent)
  388. }
  389. func (sb *sandbox) updateHostsFile(ifaceIP string, svcRecords []etchosts.Record) error {
  390. var err error
  391. if sb.config.originHostsPath != "" {
  392. return nil
  393. }
  394. max := func(a, b int) int {
  395. if a < b {
  396. return b
  397. }
  398. return a
  399. }
  400. extraContent := make([]etchosts.Record, 0,
  401. max(len(sb.config.extraHosts), len(svcRecords)))
  402. sb.hostsOnce.Do(func() {
  403. // Rebuild the hosts file accounting for the passed
  404. // interface IP and service records
  405. for _, extraHost := range sb.config.extraHosts {
  406. extraContent = append(extraContent,
  407. etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
  408. }
  409. err = etchosts.Build(sb.config.hostsPath, ifaceIP,
  410. sb.config.hostName, sb.config.domainName, extraContent)
  411. })
  412. if err != nil {
  413. return err
  414. }
  415. extraContent = extraContent[:0]
  416. for _, svc := range svcRecords {
  417. extraContent = append(extraContent, svc)
  418. }
  419. sb.addHostsEntries(extraContent)
  420. return nil
  421. }
  422. func (sb *sandbox) addHostsEntries(recs []etchosts.Record) {
  423. if err := etchosts.Add(sb.config.hostsPath, recs); err != nil {
  424. log.Warnf("Failed adding service host entries to the running container: %v", err)
  425. }
  426. }
  427. func (sb *sandbox) deleteHostsEntries(recs []etchosts.Record) {
  428. if err := etchosts.Delete(sb.config.hostsPath, recs); err != nil {
  429. log.Warnf("Failed deleting service host entries to the running container: %v", err)
  430. }
  431. }
  432. func (sb *sandbox) updateParentHosts() error {
  433. var pSb Sandbox
  434. for _, update := range sb.config.parentUpdates {
  435. sb.controller.WalkSandboxes(SandboxContainerWalker(&pSb, update.cid))
  436. if pSb == nil {
  437. continue
  438. }
  439. if err := etchosts.Update(pSb.(*sandbox).config.hostsPath, update.ip, update.name); err != nil {
  440. return err
  441. }
  442. }
  443. return nil
  444. }
  445. func (sb *sandbox) setupDNS() error {
  446. var newRC *resolvconf.File
  447. if sb.config.resolvConfPath == "" {
  448. sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
  449. }
  450. sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
  451. dir, _ := filepath.Split(sb.config.resolvConfPath)
  452. if err := createBasePath(dir); err != nil {
  453. return err
  454. }
  455. // This is for the host mode networking
  456. if sb.config.originResolvConfPath != "" {
  457. if err := copyFile(sb.config.originResolvConfPath, sb.config.resolvConfPath); err != nil {
  458. return fmt.Errorf("could not copy source resolv.conf file %s to %s: %v", sb.config.originResolvConfPath, sb.config.resolvConfPath, err)
  459. }
  460. return nil
  461. }
  462. currRC, err := resolvconf.Get()
  463. if err != nil {
  464. return err
  465. }
  466. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  467. var (
  468. err error
  469. dnsList = resolvconf.GetNameservers(currRC.Content)
  470. dnsSearchList = resolvconf.GetSearchDomains(currRC.Content)
  471. dnsOptionsList = resolvconf.GetOptions(currRC.Content)
  472. )
  473. if len(sb.config.dnsList) > 0 {
  474. dnsList = sb.config.dnsList
  475. }
  476. if len(sb.config.dnsSearchList) > 0 {
  477. dnsSearchList = sb.config.dnsSearchList
  478. }
  479. if len(sb.config.dnsOptionsList) > 0 {
  480. dnsOptionsList = sb.config.dnsOptionsList
  481. }
  482. newRC, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
  483. if err != nil {
  484. return err
  485. }
  486. } else {
  487. // Replace any localhost/127.* (at this point we have no info about ipv6, pass it as true)
  488. if newRC, err = resolvconf.FilterResolvDNS(currRC.Content, true); err != nil {
  489. return err
  490. }
  491. // No contention on container resolv.conf file at sandbox creation
  492. if err := ioutil.WriteFile(sb.config.resolvConfPath, newRC.Content, filePerm); err != nil {
  493. return types.InternalErrorf("failed to write unhaltered resolv.conf file content when setting up dns for sandbox %s: %v", sb.ID(), err)
  494. }
  495. }
  496. // Write hash
  497. if err := ioutil.WriteFile(sb.config.resolvConfHashFile, []byte(newRC.Hash), filePerm); err != nil {
  498. return types.InternalErrorf("failed to write resolv.conf hash file when setting up dns for sandbox %s: %v", sb.ID(), err)
  499. }
  500. return nil
  501. }
  502. func (sb *sandbox) updateDNS(ipv6Enabled bool) error {
  503. var (
  504. currHash string
  505. hashFile = sb.config.resolvConfHashFile
  506. )
  507. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  508. return nil
  509. }
  510. currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
  511. if err != nil {
  512. if !os.IsNotExist(err) {
  513. return err
  514. }
  515. } else {
  516. h, err := ioutil.ReadFile(hashFile)
  517. if err != nil {
  518. if !os.IsNotExist(err) {
  519. return err
  520. }
  521. } else {
  522. currHash = string(h)
  523. }
  524. }
  525. if currHash != "" && currHash != currRC.Hash {
  526. // Seems the user has changed the container resolv.conf since the last time
  527. // we checked so return without doing anything.
  528. log.Infof("Skipping update of resolv.conf file with ipv6Enabled: %t because file was touched by user", ipv6Enabled)
  529. return nil
  530. }
  531. // replace any localhost/127.* and remove IPv6 nameservers if IPv6 disabled.
  532. newRC, err := resolvconf.FilterResolvDNS(currRC.Content, ipv6Enabled)
  533. if err != nil {
  534. return err
  535. }
  536. // for atomic updates to these files, use temporary files with os.Rename:
  537. dir := path.Dir(sb.config.resolvConfPath)
  538. tmpHashFile, err := ioutil.TempFile(dir, "hash")
  539. if err != nil {
  540. return err
  541. }
  542. tmpResolvFile, err := ioutil.TempFile(dir, "resolv")
  543. if err != nil {
  544. return err
  545. }
  546. // Change the perms to filePerm (0644) since ioutil.TempFile creates it by default as 0600
  547. if err := os.Chmod(tmpResolvFile.Name(), filePerm); err != nil {
  548. return err
  549. }
  550. // write the updates to the temp files
  551. if err = ioutil.WriteFile(tmpHashFile.Name(), []byte(newRC.Hash), filePerm); err != nil {
  552. return err
  553. }
  554. if err = ioutil.WriteFile(tmpResolvFile.Name(), newRC.Content, filePerm); err != nil {
  555. return err
  556. }
  557. // rename the temp files for atomic replace
  558. if err = os.Rename(tmpHashFile.Name(), hashFile); err != nil {
  559. return err
  560. }
  561. return os.Rename(tmpResolvFile.Name(), sb.config.resolvConfPath)
  562. }
  563. // joinLeaveStart waits to ensure there are no joins or leaves in progress and
  564. // marks this join/leave in progress without race
  565. func (sb *sandbox) joinLeaveStart() {
  566. sb.Lock()
  567. defer sb.Unlock()
  568. for sb.joinLeaveDone != nil {
  569. joinLeaveDone := sb.joinLeaveDone
  570. sb.Unlock()
  571. select {
  572. case <-joinLeaveDone:
  573. }
  574. sb.Lock()
  575. }
  576. sb.joinLeaveDone = make(chan struct{})
  577. }
  578. // joinLeaveEnd marks the end of this join/leave operation and
  579. // signals the same without race to other join and leave waiters
  580. func (sb *sandbox) joinLeaveEnd() {
  581. sb.Lock()
  582. defer sb.Unlock()
  583. if sb.joinLeaveDone != nil {
  584. close(sb.joinLeaveDone)
  585. sb.joinLeaveDone = nil
  586. }
  587. }
  588. // OptionHostname function returns an option setter for hostname option to
  589. // be passed to NewSandbox method.
  590. func OptionHostname(name string) SandboxOption {
  591. return func(sb *sandbox) {
  592. sb.config.hostName = name
  593. }
  594. }
  595. // OptionDomainname function returns an option setter for domainname option to
  596. // be passed to NewSandbox method.
  597. func OptionDomainname(name string) SandboxOption {
  598. return func(sb *sandbox) {
  599. sb.config.domainName = name
  600. }
  601. }
  602. // OptionHostsPath function returns an option setter for hostspath option to
  603. // be passed to NewSandbox method.
  604. func OptionHostsPath(path string) SandboxOption {
  605. return func(sb *sandbox) {
  606. sb.config.hostsPath = path
  607. }
  608. }
  609. // OptionOriginHostsPath function returns an option setter for origin hosts file path
  610. // tbeo passed to NewSandbox method.
  611. func OptionOriginHostsPath(path string) SandboxOption {
  612. return func(sb *sandbox) {
  613. sb.config.originHostsPath = path
  614. }
  615. }
  616. // OptionExtraHost function returns an option setter for extra /etc/hosts options
  617. // which is a name and IP as strings.
  618. func OptionExtraHost(name string, IP string) SandboxOption {
  619. return func(sb *sandbox) {
  620. sb.config.extraHosts = append(sb.config.extraHosts, extraHost{name: name, IP: IP})
  621. }
  622. }
  623. // OptionParentUpdate function returns an option setter for parent container
  624. // which needs to update the IP address for the linked container.
  625. func OptionParentUpdate(cid string, name, ip string) SandboxOption {
  626. return func(sb *sandbox) {
  627. sb.config.parentUpdates = append(sb.config.parentUpdates, parentUpdate{cid: cid, name: name, ip: ip})
  628. }
  629. }
  630. // OptionResolvConfPath function returns an option setter for resolvconfpath option to
  631. // be passed to net container methods.
  632. func OptionResolvConfPath(path string) SandboxOption {
  633. return func(sb *sandbox) {
  634. sb.config.resolvConfPath = path
  635. }
  636. }
  637. // OptionOriginResolvConfPath function returns an option setter to set the path to the
  638. // origin resolv.conf file to be passed to net container methods.
  639. func OptionOriginResolvConfPath(path string) SandboxOption {
  640. return func(sb *sandbox) {
  641. sb.config.originResolvConfPath = path
  642. }
  643. }
  644. // OptionDNS function returns an option setter for dns entry option to
  645. // be passed to container Create method.
  646. func OptionDNS(dns string) SandboxOption {
  647. return func(sb *sandbox) {
  648. sb.config.dnsList = append(sb.config.dnsList, dns)
  649. }
  650. }
  651. // OptionDNSSearch function returns an option setter for dns search entry option to
  652. // be passed to container Create method.
  653. func OptionDNSSearch(search string) SandboxOption {
  654. return func(sb *sandbox) {
  655. sb.config.dnsSearchList = append(sb.config.dnsSearchList, search)
  656. }
  657. }
  658. // OptionDNSOptions function returns an option setter for dns options entry option to
  659. // be passed to container Create method.
  660. func OptionDNSOptions(options string) SandboxOption {
  661. return func(sb *sandbox) {
  662. sb.config.dnsOptionsList = append(sb.config.dnsOptionsList, options)
  663. }
  664. }
  665. // OptionUseDefaultSandbox function returns an option setter for using default sandbox to
  666. // be passed to container Create method.
  667. func OptionUseDefaultSandbox() SandboxOption {
  668. return func(sb *sandbox) {
  669. sb.config.useDefaultSandBox = true
  670. }
  671. }
  672. // OptionUseExternalKey function returns an option setter for using provided namespace
  673. // instead of creating one.
  674. func OptionUseExternalKey() SandboxOption {
  675. return func(sb *sandbox) {
  676. sb.config.useExternalKey = true
  677. }
  678. }
  679. // OptionGeneric function returns an option setter for Generic configuration
  680. // that is not managed by libNetwork but can be used by the Drivers during the call to
  681. // net container creation method. Container Labels are a good example.
  682. func OptionGeneric(generic map[string]interface{}) SandboxOption {
  683. return func(sb *sandbox) {
  684. sb.config.generic = generic
  685. }
  686. }
  687. func (eh epHeap) Len() int { return len(eh) }
  688. func (eh epHeap) Less(i, j int) bool {
  689. ci, _ := eh[i].getSandbox()
  690. cj, _ := eh[j].getSandbox()
  691. epi := eh[i]
  692. epj := eh[j]
  693. if epi.endpointInGWNetwork() {
  694. return false
  695. }
  696. if epj.endpointInGWNetwork() {
  697. return true
  698. }
  699. cip, ok := ci.epPriority[eh[i].ID()]
  700. if !ok {
  701. cip = 0
  702. }
  703. cjp, ok := cj.epPriority[eh[j].ID()]
  704. if !ok {
  705. cjp = 0
  706. }
  707. if cip == cjp {
  708. return eh[i].getNetwork().Name() < eh[j].getNetwork().Name()
  709. }
  710. return cip > cjp
  711. }
  712. func (eh epHeap) Swap(i, j int) { eh[i], eh[j] = eh[j], eh[i] }
  713. func (eh *epHeap) Push(x interface{}) {
  714. *eh = append(*eh, x.(*endpoint))
  715. }
  716. func (eh *epHeap) Pop() interface{} {
  717. old := *eh
  718. n := len(old)
  719. x := old[n-1]
  720. *eh = old[0 : n-1]
  721. return x
  722. }
  723. func createBasePath(dir string) error {
  724. return os.MkdirAll(dir, dirPerm)
  725. }
  726. func createFile(path string) error {
  727. var f *os.File
  728. dir, _ := filepath.Split(path)
  729. err := createBasePath(dir)
  730. if err != nil {
  731. return err
  732. }
  733. f, err = os.Create(path)
  734. if err == nil {
  735. f.Close()
  736. }
  737. return err
  738. }
  739. func copyFile(src, dst string) error {
  740. sBytes, err := ioutil.ReadFile(src)
  741. if err != nil {
  742. return err
  743. }
  744. return ioutil.WriteFile(dst, sBytes, filePerm)
  745. }