sandbox.go 30 KB

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