sandbox.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  1. package libnetwork
  2. import (
  3. "container/heap"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/docker/libnetwork/etchosts"
  11. "github.com/docker/libnetwork/netlabel"
  12. "github.com/docker/libnetwork/osl"
  13. "github.com/docker/libnetwork/types"
  14. "github.com/sirupsen/logrus"
  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.Since(start), sb.ContainerID())
  530. }()
  531. if basePath == "" {
  532. return types.BadRequestErrorf("invalid sandbox key")
  533. }
  534. sb.Lock()
  535. if sb.inDelete {
  536. sb.Unlock()
  537. return types.ForbiddenErrorf("failed to SetKey: sandbox %q delete in progress", sb.id)
  538. }
  539. oldosSbox := sb.osSbox
  540. sb.Unlock()
  541. if oldosSbox != nil {
  542. // If we already have an OS sandbox, release the network resources from that
  543. // and destroy the OS snab. We are moving into a new home further down. Note that none
  544. // of the network resources gets destroyed during the move.
  545. sb.releaseOSSbox()
  546. }
  547. osSbox, err := osl.GetSandboxForExternalKey(basePath, sb.Key())
  548. if err != nil {
  549. return err
  550. }
  551. sb.Lock()
  552. sb.osSbox = osSbox
  553. sb.Unlock()
  554. // If the resolver was setup before stop it and set it up in the
  555. // new osl sandbox.
  556. if oldosSbox != nil && sb.resolver != nil {
  557. sb.resolver.Stop()
  558. if err := sb.osSbox.InvokeFunc(sb.resolver.SetupFunc(0)); err == nil {
  559. if err := sb.resolver.Start(); err != nil {
  560. logrus.Errorf("Resolver Start failed for container %s, %q", sb.ContainerID(), err)
  561. }
  562. } else {
  563. logrus.Errorf("Resolver Setup Function failed for container %s, %q", sb.ContainerID(), err)
  564. }
  565. }
  566. for _, ep := range sb.getConnectedEndpoints() {
  567. if err = sb.populateNetworkResources(ep); err != nil {
  568. return err
  569. }
  570. }
  571. return nil
  572. }
  573. func (sb *sandbox) EnableService() error {
  574. logrus.Debugf("EnableService %s START", sb.containerID)
  575. for _, ep := range sb.getConnectedEndpoints() {
  576. if ep.enableService(true) {
  577. if err := ep.addServiceInfoToCluster(sb); err != nil {
  578. ep.enableService(false)
  579. return fmt.Errorf("could not update state for endpoint %s into cluster: %v", ep.Name(), err)
  580. }
  581. }
  582. }
  583. logrus.Debugf("EnableService %s DONE", sb.containerID)
  584. return nil
  585. }
  586. func (sb *sandbox) DisableService() error {
  587. logrus.Debugf("DisableService %s START", sb.containerID)
  588. for _, ep := range sb.getConnectedEndpoints() {
  589. ep.enableService(false)
  590. }
  591. logrus.Debugf("DisableService %s DONE", sb.containerID)
  592. return nil
  593. }
  594. func releaseOSSboxResources(osSbox osl.Sandbox, ep *endpoint) {
  595. for _, i := range osSbox.Info().Interfaces() {
  596. // Only remove the interfaces owned by this endpoint from the sandbox.
  597. if ep.hasInterface(i.SrcName()) {
  598. if err := i.Remove(); err != nil {
  599. logrus.Debugf("Remove interface %s failed: %v", i.SrcName(), err)
  600. }
  601. }
  602. }
  603. ep.Lock()
  604. joinInfo := ep.joinInfo
  605. vip := ep.virtualIP
  606. ep.Unlock()
  607. if len(vip) != 0 {
  608. if err := osSbox.RemoveLoopbackAliasIP(&net.IPNet{IP: vip, Mask: net.CIDRMask(32, 32)}); err != nil {
  609. logrus.Warnf("Remove virtual IP %v failed: %v", vip, err)
  610. }
  611. }
  612. if joinInfo == nil {
  613. return
  614. }
  615. // Remove non-interface routes.
  616. for _, r := range joinInfo.StaticRoutes {
  617. if err := osSbox.RemoveStaticRoute(r); err != nil {
  618. logrus.Debugf("Remove route failed: %v", err)
  619. }
  620. }
  621. }
  622. func (sb *sandbox) releaseOSSbox() {
  623. sb.Lock()
  624. osSbox := sb.osSbox
  625. sb.osSbox = nil
  626. sb.Unlock()
  627. if osSbox == nil {
  628. return
  629. }
  630. for _, ep := range sb.getConnectedEndpoints() {
  631. releaseOSSboxResources(osSbox, ep)
  632. }
  633. osSbox.Destroy()
  634. }
  635. func (sb *sandbox) restoreOslSandbox() error {
  636. var routes []*types.StaticRoute
  637. // restore osl sandbox
  638. Ifaces := make(map[string][]osl.IfaceOption)
  639. for _, ep := range sb.endpoints {
  640. var ifaceOptions []osl.IfaceOption
  641. ep.Lock()
  642. joinInfo := ep.joinInfo
  643. i := ep.iface
  644. ep.Unlock()
  645. if i == nil {
  646. logrus.Errorf("error restoring endpoint %s for container %s", ep.Name(), sb.ContainerID())
  647. continue
  648. }
  649. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes))
  650. if i.addrv6 != nil && i.addrv6.IP.To16() != nil {
  651. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(i.addrv6))
  652. }
  653. if i.mac != nil {
  654. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().MacAddress(i.mac))
  655. }
  656. if len(i.llAddrs) != 0 {
  657. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().LinkLocalAddresses(i.llAddrs))
  658. }
  659. Ifaces[fmt.Sprintf("%s+%s", i.srcName, i.dstPrefix)] = ifaceOptions
  660. if joinInfo != nil {
  661. routes = append(routes, joinInfo.StaticRoutes...)
  662. }
  663. if ep.needResolver() {
  664. sb.startResolver(true)
  665. }
  666. }
  667. gwep := sb.getGatewayEndpoint()
  668. if gwep == nil {
  669. return nil
  670. }
  671. // restore osl sandbox
  672. err := sb.osSbox.Restore(Ifaces, routes, gwep.joinInfo.gw, gwep.joinInfo.gw6)
  673. return err
  674. }
  675. func (sb *sandbox) populateNetworkResources(ep *endpoint) error {
  676. sb.Lock()
  677. if sb.osSbox == nil {
  678. sb.Unlock()
  679. return nil
  680. }
  681. inDelete := sb.inDelete
  682. sb.Unlock()
  683. ep.Lock()
  684. joinInfo := ep.joinInfo
  685. i := ep.iface
  686. ep.Unlock()
  687. if ep.needResolver() {
  688. sb.startResolver(false)
  689. }
  690. if i != nil && i.srcName != "" {
  691. var ifaceOptions []osl.IfaceOption
  692. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes))
  693. if i.addrv6 != nil && i.addrv6.IP.To16() != nil {
  694. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(i.addrv6))
  695. }
  696. if len(i.llAddrs) != 0 {
  697. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().LinkLocalAddresses(i.llAddrs))
  698. }
  699. if i.mac != nil {
  700. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().MacAddress(i.mac))
  701. }
  702. if err := sb.osSbox.AddInterface(i.srcName, i.dstPrefix, ifaceOptions...); err != nil {
  703. return fmt.Errorf("failed to add interface %s to sandbox: %v", i.srcName, err)
  704. }
  705. }
  706. if len(ep.virtualIP) != 0 {
  707. err := sb.osSbox.AddLoopbackAliasIP(&net.IPNet{IP: ep.virtualIP, Mask: net.CIDRMask(32, 32)})
  708. if err != nil {
  709. return fmt.Errorf("failed to add virtual IP %v: %v", ep.virtualIP, err)
  710. }
  711. }
  712. if joinInfo != nil {
  713. // Set up non-interface routes.
  714. for _, r := range joinInfo.StaticRoutes {
  715. if err := sb.osSbox.AddStaticRoute(r); err != nil {
  716. return fmt.Errorf("failed to add static route %s: %v", r.Destination.String(), err)
  717. }
  718. }
  719. }
  720. if ep == sb.getGatewayEndpoint() {
  721. if err := sb.updateGateway(ep); err != nil {
  722. return err
  723. }
  724. }
  725. // Make sure to add the endpoint to the populated endpoint set
  726. // before populating loadbalancers.
  727. sb.Lock()
  728. sb.populatedEndpoints[ep.ID()] = struct{}{}
  729. sb.Unlock()
  730. // Populate load balancer only after updating all the other
  731. // information including gateway and other routes so that
  732. // loadbalancers are populated all the network state is in
  733. // place in the sandbox.
  734. sb.populateLoadbalancers(ep)
  735. // Only update the store if we did not come here as part of
  736. // sandbox delete. If we came here as part of delete then do
  737. // not bother updating the store. The sandbox object will be
  738. // deleted anyway
  739. if !inDelete {
  740. return sb.storeUpdate()
  741. }
  742. return nil
  743. }
  744. func (sb *sandbox) clearNetworkResources(origEp *endpoint) error {
  745. ep := sb.getEndpoint(origEp.id)
  746. if ep == nil {
  747. return fmt.Errorf("could not find the sandbox endpoint data for endpoint %s",
  748. origEp.id)
  749. }
  750. sb.Lock()
  751. osSbox := sb.osSbox
  752. inDelete := sb.inDelete
  753. sb.Unlock()
  754. if osSbox != nil {
  755. releaseOSSboxResources(osSbox, ep)
  756. }
  757. sb.Lock()
  758. delete(sb.populatedEndpoints, ep.ID())
  759. if len(sb.endpoints) == 0 {
  760. // sb.endpoints should never be empty and this is unexpected error condition
  761. // We log an error message to note this down for debugging purposes.
  762. logrus.Errorf("No endpoints in sandbox while trying to remove endpoint %s", ep.Name())
  763. sb.Unlock()
  764. return nil
  765. }
  766. var (
  767. gwepBefore, gwepAfter *endpoint
  768. index = -1
  769. )
  770. for i, e := range sb.endpoints {
  771. if e == ep {
  772. index = i
  773. }
  774. if len(e.Gateway()) > 0 && gwepBefore == nil {
  775. gwepBefore = e
  776. }
  777. if index != -1 && gwepBefore != nil {
  778. break
  779. }
  780. }
  781. if index == -1 {
  782. logrus.Warnf("Endpoint %s has already been deleted", ep.Name())
  783. sb.Unlock()
  784. return nil
  785. }
  786. heap.Remove(&sb.endpoints, index)
  787. for _, e := range sb.endpoints {
  788. if len(e.Gateway()) > 0 {
  789. gwepAfter = e
  790. break
  791. }
  792. }
  793. delete(sb.epPriority, ep.ID())
  794. sb.Unlock()
  795. if gwepAfter != nil && gwepBefore != gwepAfter {
  796. sb.updateGateway(gwepAfter)
  797. }
  798. // Only update the store if we did not come here as part of
  799. // sandbox delete. If we came here as part of delete then do
  800. // not bother updating the store. The sandbox object will be
  801. // deleted anyway
  802. if !inDelete {
  803. return sb.storeUpdate()
  804. }
  805. return nil
  806. }
  807. func (sb *sandbox) isEndpointPopulated(ep *endpoint) bool {
  808. sb.Lock()
  809. _, ok := sb.populatedEndpoints[ep.ID()]
  810. sb.Unlock()
  811. return ok
  812. }
  813. // joinLeaveStart waits to ensure there are no joins or leaves in progress and
  814. // marks this join/leave in progress without race
  815. func (sb *sandbox) joinLeaveStart() {
  816. sb.Lock()
  817. defer sb.Unlock()
  818. for sb.joinLeaveDone != nil {
  819. joinLeaveDone := sb.joinLeaveDone
  820. sb.Unlock()
  821. <-joinLeaveDone
  822. sb.Lock()
  823. }
  824. sb.joinLeaveDone = make(chan struct{})
  825. }
  826. // joinLeaveEnd marks the end of this join/leave operation and
  827. // signals the same without race to other join and leave waiters
  828. func (sb *sandbox) joinLeaveEnd() {
  829. sb.Lock()
  830. defer sb.Unlock()
  831. if sb.joinLeaveDone != nil {
  832. close(sb.joinLeaveDone)
  833. sb.joinLeaveDone = nil
  834. }
  835. }
  836. func (sb *sandbox) hasPortConfigs() bool {
  837. opts := sb.Labels()
  838. _, hasExpPorts := opts[netlabel.ExposedPorts]
  839. _, hasPortMaps := opts[netlabel.PortMap]
  840. return hasExpPorts || hasPortMaps
  841. }
  842. // OptionHostname function returns an option setter for hostname option to
  843. // be passed to NewSandbox method.
  844. func OptionHostname(name string) SandboxOption {
  845. return func(sb *sandbox) {
  846. sb.config.hostName = name
  847. }
  848. }
  849. // OptionDomainname function returns an option setter for domainname option to
  850. // be passed to NewSandbox method.
  851. func OptionDomainname(name string) SandboxOption {
  852. return func(sb *sandbox) {
  853. sb.config.domainName = name
  854. }
  855. }
  856. // OptionHostsPath function returns an option setter for hostspath option to
  857. // be passed to NewSandbox method.
  858. func OptionHostsPath(path string) SandboxOption {
  859. return func(sb *sandbox) {
  860. sb.config.hostsPath = path
  861. }
  862. }
  863. // OptionOriginHostsPath function returns an option setter for origin hosts file path
  864. // to be passed to NewSandbox method.
  865. func OptionOriginHostsPath(path string) SandboxOption {
  866. return func(sb *sandbox) {
  867. sb.config.originHostsPath = path
  868. }
  869. }
  870. // OptionExtraHost function returns an option setter for extra /etc/hosts options
  871. // which is a name and IP as strings.
  872. func OptionExtraHost(name string, IP string) SandboxOption {
  873. return func(sb *sandbox) {
  874. sb.config.extraHosts = append(sb.config.extraHosts, extraHost{name: name, IP: IP})
  875. }
  876. }
  877. // OptionParentUpdate function returns an option setter for parent container
  878. // which needs to update the IP address for the linked container.
  879. func OptionParentUpdate(cid string, name, ip string) SandboxOption {
  880. return func(sb *sandbox) {
  881. sb.config.parentUpdates = append(sb.config.parentUpdates, parentUpdate{cid: cid, name: name, ip: ip})
  882. }
  883. }
  884. // OptionResolvConfPath function returns an option setter for resolvconfpath option to
  885. // be passed to net container methods.
  886. func OptionResolvConfPath(path string) SandboxOption {
  887. return func(sb *sandbox) {
  888. sb.config.resolvConfPath = path
  889. }
  890. }
  891. // OptionOriginResolvConfPath function returns an option setter to set the path to the
  892. // origin resolv.conf file to be passed to net container methods.
  893. func OptionOriginResolvConfPath(path string) SandboxOption {
  894. return func(sb *sandbox) {
  895. sb.config.originResolvConfPath = path
  896. }
  897. }
  898. // OptionDNS function returns an option setter for dns entry option to
  899. // be passed to container Create method.
  900. func OptionDNS(dns string) SandboxOption {
  901. return func(sb *sandbox) {
  902. sb.config.dnsList = append(sb.config.dnsList, dns)
  903. }
  904. }
  905. // OptionDNSSearch function returns an option setter for dns search entry option to
  906. // be passed to container Create method.
  907. func OptionDNSSearch(search string) SandboxOption {
  908. return func(sb *sandbox) {
  909. sb.config.dnsSearchList = append(sb.config.dnsSearchList, search)
  910. }
  911. }
  912. // OptionDNSOptions function returns an option setter for dns options entry option to
  913. // be passed to container Create method.
  914. func OptionDNSOptions(options string) SandboxOption {
  915. return func(sb *sandbox) {
  916. sb.config.dnsOptionsList = append(sb.config.dnsOptionsList, options)
  917. }
  918. }
  919. // OptionUseDefaultSandbox function returns an option setter for using default sandbox to
  920. // be passed to container Create method.
  921. func OptionUseDefaultSandbox() SandboxOption {
  922. return func(sb *sandbox) {
  923. sb.config.useDefaultSandBox = true
  924. }
  925. }
  926. // OptionUseExternalKey function returns an option setter for using provided namespace
  927. // instead of creating one.
  928. func OptionUseExternalKey() SandboxOption {
  929. return func(sb *sandbox) {
  930. sb.config.useExternalKey = true
  931. }
  932. }
  933. // OptionGeneric function returns an option setter for Generic configuration
  934. // that is not managed by libNetwork but can be used by the Drivers during the call to
  935. // net container creation method. Container Labels are a good example.
  936. func OptionGeneric(generic map[string]interface{}) SandboxOption {
  937. return func(sb *sandbox) {
  938. if sb.config.generic == nil {
  939. sb.config.generic = make(map[string]interface{}, len(generic))
  940. }
  941. for k, v := range generic {
  942. sb.config.generic[k] = v
  943. }
  944. }
  945. }
  946. // OptionExposedPorts function returns an option setter for the container exposed
  947. // ports option to be passed to container Create method.
  948. func OptionExposedPorts(exposedPorts []types.TransportPort) SandboxOption {
  949. return func(sb *sandbox) {
  950. if sb.config.generic == nil {
  951. sb.config.generic = make(map[string]interface{})
  952. }
  953. // Defensive copy
  954. eps := make([]types.TransportPort, len(exposedPorts))
  955. copy(eps, exposedPorts)
  956. // Store endpoint label and in generic because driver needs it
  957. sb.config.exposedPorts = eps
  958. sb.config.generic[netlabel.ExposedPorts] = eps
  959. }
  960. }
  961. // OptionPortMapping function returns an option setter for the mapping
  962. // ports option to be passed to container Create method.
  963. func OptionPortMapping(portBindings []types.PortBinding) SandboxOption {
  964. return func(sb *sandbox) {
  965. if sb.config.generic == nil {
  966. sb.config.generic = make(map[string]interface{})
  967. }
  968. // Store a copy of the bindings as generic data to pass to the driver
  969. pbs := make([]types.PortBinding, len(portBindings))
  970. copy(pbs, portBindings)
  971. sb.config.generic[netlabel.PortMap] = pbs
  972. }
  973. }
  974. // OptionIngress function returns an option setter for marking a
  975. // sandbox as the controller's ingress sandbox.
  976. func OptionIngress() SandboxOption {
  977. return func(sb *sandbox) {
  978. sb.ingress = true
  979. }
  980. }
  981. func (eh epHeap) Len() int { return len(eh) }
  982. func (eh epHeap) Less(i, j int) bool {
  983. var (
  984. cip, cjp int
  985. ok bool
  986. )
  987. ci, _ := eh[i].getSandbox()
  988. cj, _ := eh[j].getSandbox()
  989. epi := eh[i]
  990. epj := eh[j]
  991. if epi.endpointInGWNetwork() {
  992. return false
  993. }
  994. if epj.endpointInGWNetwork() {
  995. return true
  996. }
  997. if epi.getNetwork().Internal() {
  998. return false
  999. }
  1000. if epj.getNetwork().Internal() {
  1001. return true
  1002. }
  1003. if epi.joinInfo != nil && epj.joinInfo != nil {
  1004. if (epi.joinInfo.gw != nil && epi.joinInfo.gw6 != nil) &&
  1005. (epj.joinInfo.gw == nil || epj.joinInfo.gw6 == nil) {
  1006. return true
  1007. }
  1008. if (epj.joinInfo.gw != nil && epj.joinInfo.gw6 != nil) &&
  1009. (epi.joinInfo.gw == nil || epi.joinInfo.gw6 == nil) {
  1010. return false
  1011. }
  1012. }
  1013. if ci != nil {
  1014. cip, ok = ci.epPriority[eh[i].ID()]
  1015. if !ok {
  1016. cip = 0
  1017. }
  1018. }
  1019. if cj != nil {
  1020. cjp, ok = cj.epPriority[eh[j].ID()]
  1021. if !ok {
  1022. cjp = 0
  1023. }
  1024. }
  1025. if cip == cjp {
  1026. return eh[i].network.Name() < eh[j].network.Name()
  1027. }
  1028. return cip > cjp
  1029. }
  1030. func (eh epHeap) Swap(i, j int) { eh[i], eh[j] = eh[j], eh[i] }
  1031. func (eh *epHeap) Push(x interface{}) {
  1032. *eh = append(*eh, x.(*endpoint))
  1033. }
  1034. func (eh *epHeap) Pop() interface{} {
  1035. old := *eh
  1036. n := len(old)
  1037. x := old[n-1]
  1038. *eh = old[0 : n-1]
  1039. return x
  1040. }
  1041. func (sb *sandbox) NdotsSet() bool {
  1042. return sb.ndotsSet
  1043. }