sandbox.go 29 KB

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