sandbox.go 27 KB

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