sandbox.go 29 KB

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