sandbox.go 30 KB

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