sandbox.go 32 KB

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