sandbox.go 27 KB

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