sandbox.go 32 KB

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