sandbox.go 31 KB

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