sandbox.go 32 KB

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