sandbox.go 30 KB

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