sandbox.go 31 KB

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