sandbox.go 31 KB

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