sandbox.go 30 KB

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