sandbox.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. package libnetwork
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "sort"
  8. "strings"
  9. "sync"
  10. "github.com/containerd/log"
  11. "github.com/docker/docker/libnetwork/etchosts"
  12. "github.com/docker/docker/libnetwork/osl"
  13. "github.com/docker/docker/libnetwork/types"
  14. "go.opentelemetry.io/otel"
  15. "go.opentelemetry.io/otel/attribute"
  16. "go.opentelemetry.io/otel/trace"
  17. )
  18. // SandboxOption is an option setter function type used to pass various options to
  19. // NewNetContainer method. The various setter functions of type SandboxOption are
  20. // provided by libnetwork, they look like ContainerOptionXXXX(...)
  21. type SandboxOption func(sb *Sandbox)
  22. func (sb *Sandbox) processOptions(options ...SandboxOption) {
  23. for _, opt := range options {
  24. if opt != nil {
  25. opt(sb)
  26. }
  27. }
  28. }
  29. // Sandbox provides the control over the network container entity.
  30. // It is a one to one mapping with the container.
  31. type Sandbox struct {
  32. id string
  33. containerID string
  34. config containerConfig
  35. extDNS []extDNSEntry
  36. osSbox *osl.Namespace
  37. controller *Controller
  38. resolver *Resolver
  39. resolverOnce sync.Once
  40. endpoints []*Endpoint
  41. epPriority map[string]int
  42. populatedEndpoints map[string]struct{}
  43. joinLeaveDone chan struct{}
  44. dbIndex uint64
  45. dbExists bool
  46. isStub bool
  47. inDelete bool
  48. ingress bool
  49. ndotsSet bool
  50. oslTypes []osl.SandboxType // slice of properties of this sandbox
  51. loadBalancerNID string // NID that this SB is a load balancer for
  52. mu sync.Mutex
  53. // This mutex is used to serialize service related operation for an endpoint
  54. // The lock is here because the endpoint is saved into the store so is not unique
  55. service sync.Mutex
  56. }
  57. // These are the container configs used to customize container /etc/hosts file.
  58. type hostsPathConfig struct {
  59. hostName string
  60. domainName string
  61. hostsPath string
  62. originHostsPath string
  63. extraHosts []extraHost
  64. parentUpdates []parentUpdate
  65. }
  66. type parentUpdate struct {
  67. cid string
  68. name string
  69. ip string
  70. }
  71. type extraHost struct {
  72. name string
  73. IP string
  74. }
  75. // These are the container configs used to customize container /etc/resolv.conf file.
  76. type resolvConfPathConfig struct {
  77. resolvConfPath string
  78. originResolvConfPath string
  79. resolvConfHashFile string
  80. dnsList []string
  81. dnsSearchList []string
  82. dnsOptionsList []string
  83. }
  84. type containerConfig struct {
  85. hostsPathConfig
  86. resolvConfPathConfig
  87. generic map[string]interface{}
  88. useDefaultSandBox bool
  89. useExternalKey bool
  90. exposedPorts []types.TransportPort
  91. }
  92. // ID returns the ID of the sandbox.
  93. func (sb *Sandbox) ID() string {
  94. return sb.id
  95. }
  96. // ContainerID returns the container id associated to this sandbox.
  97. func (sb *Sandbox) ContainerID() string {
  98. return sb.containerID
  99. }
  100. // Key returns the sandbox's key.
  101. func (sb *Sandbox) Key() string {
  102. if sb.config.useDefaultSandBox {
  103. return osl.GenerateKey("default")
  104. }
  105. return osl.GenerateKey(sb.id)
  106. }
  107. // Labels returns the sandbox's labels.
  108. func (sb *Sandbox) Labels() map[string]interface{} {
  109. sb.mu.Lock()
  110. defer sb.mu.Unlock()
  111. opts := make(map[string]interface{}, len(sb.config.generic))
  112. for k, v := range sb.config.generic {
  113. opts[k] = v
  114. }
  115. return opts
  116. }
  117. // Delete destroys this container after detaching it from all connected endpoints.
  118. func (sb *Sandbox) Delete() error {
  119. return sb.delete(false)
  120. }
  121. func (sb *Sandbox) delete(force bool) error {
  122. sb.mu.Lock()
  123. if sb.inDelete {
  124. sb.mu.Unlock()
  125. return types.ForbiddenErrorf("another sandbox delete in progress")
  126. }
  127. // Set the inDelete flag. This will ensure that we don't
  128. // update the store until we have completed all the endpoint
  129. // leaves and deletes. And when endpoint leaves and deletes
  130. // are completed then we can finally delete the sandbox object
  131. // altogether from the data store. If the daemon exits
  132. // ungracefully in the middle of a sandbox delete this way we
  133. // will have all the references to the endpoints in the
  134. // sandbox so that we can clean them up when we restart
  135. sb.inDelete = true
  136. sb.mu.Unlock()
  137. c := sb.controller
  138. // Detach from all endpoints
  139. retain := false
  140. for _, ep := range sb.Endpoints() {
  141. // gw network endpoint detach and removal are automatic
  142. if ep.endpointInGWNetwork() && !force {
  143. continue
  144. }
  145. // Retain the sanbdox if we can't obtain the network from store.
  146. if _, err := c.getNetworkFromStore(ep.getNetwork().ID()); err != nil {
  147. if !c.isSwarmNode() {
  148. retain = true
  149. }
  150. log.G(context.TODO()).Warnf("Failed getting network for ep %s during sandbox %s delete: %v", ep.ID(), sb.ID(), err)
  151. continue
  152. }
  153. if !force {
  154. if err := ep.Leave(sb); err != nil {
  155. log.G(context.TODO()).Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  156. }
  157. }
  158. if err := ep.Delete(force); err != nil {
  159. log.G(context.TODO()).Warnf("Failed deleting endpoint %s: %v\n", ep.ID(), err)
  160. }
  161. }
  162. if retain {
  163. sb.mu.Lock()
  164. sb.inDelete = false
  165. sb.mu.Unlock()
  166. return fmt.Errorf("could not cleanup all the endpoints in container %s / sandbox %s", sb.containerID, sb.id)
  167. }
  168. // Container is going away. Path cache in etchosts is most
  169. // likely not required any more. Drop it.
  170. etchosts.Drop(sb.config.hostsPath)
  171. if sb.resolver != nil {
  172. sb.resolver.Stop()
  173. }
  174. if sb.osSbox != nil && !sb.config.useDefaultSandBox {
  175. if err := sb.osSbox.Destroy(); err != nil {
  176. log.G(context.TODO()).WithError(err).Warn("error destroying network sandbox")
  177. }
  178. }
  179. if err := sb.storeDelete(); err != nil {
  180. log.G(context.TODO()).Warnf("Failed to delete sandbox %s from store: %v", sb.ID(), err)
  181. }
  182. c.mu.Lock()
  183. if sb.ingress {
  184. c.ingressSandbox = nil
  185. }
  186. delete(c.sandboxes, sb.ID())
  187. c.mu.Unlock()
  188. return nil
  189. }
  190. // Rename changes the name of all attached Endpoints.
  191. func (sb *Sandbox) Rename(name string) error {
  192. var err error
  193. for _, ep := range sb.Endpoints() {
  194. if ep.endpointInGWNetwork() {
  195. continue
  196. }
  197. oldName := ep.Name()
  198. lEp := ep
  199. if err = ep.rename(name); err != nil {
  200. break
  201. }
  202. defer func() {
  203. if err != nil {
  204. if err2 := lEp.rename(oldName); err2 != nil {
  205. log.G(context.TODO()).WithField("old", oldName).WithField("origError", err).WithError(err2).Error("error renaming sandbox")
  206. }
  207. }
  208. }()
  209. }
  210. return err
  211. }
  212. // Refresh leaves all the endpoints, resets and re-applies the options,
  213. // re-joins all the endpoints without destroying the osl sandbox
  214. func (sb *Sandbox) Refresh(options ...SandboxOption) error {
  215. // Store connected endpoints
  216. epList := sb.Endpoints()
  217. // Detach from all endpoints
  218. for _, ep := range epList {
  219. if err := ep.Leave(sb); err != nil {
  220. log.G(context.TODO()).Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  221. }
  222. }
  223. // Re-apply options
  224. sb.config = containerConfig{}
  225. sb.processOptions(options...)
  226. // Setup discovery files
  227. if err := sb.setupResolutionFiles(); err != nil {
  228. return err
  229. }
  230. // Re-connect to all endpoints
  231. for _, ep := range epList {
  232. if err := ep.Join(sb); err != nil {
  233. log.G(context.TODO()).Warnf("Failed attach sandbox %s to endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  234. }
  235. }
  236. return nil
  237. }
  238. func (sb *Sandbox) MarshalJSON() ([]byte, error) {
  239. sb.mu.Lock()
  240. defer sb.mu.Unlock()
  241. // We are just interested in the container ID. This can be expanded to include all of containerInfo if there is a need
  242. return json.Marshal(sb.id)
  243. }
  244. func (sb *Sandbox) UnmarshalJSON(b []byte) (err error) {
  245. sb.mu.Lock()
  246. defer sb.mu.Unlock()
  247. var id string
  248. if err := json.Unmarshal(b, &id); err != nil {
  249. return err
  250. }
  251. sb.id = id
  252. return nil
  253. }
  254. // Endpoints returns all the endpoints connected to the sandbox.
  255. func (sb *Sandbox) Endpoints() []*Endpoint {
  256. sb.mu.Lock()
  257. defer sb.mu.Unlock()
  258. eps := make([]*Endpoint, len(sb.endpoints))
  259. copy(eps, sb.endpoints)
  260. return eps
  261. }
  262. func (sb *Sandbox) addEndpoint(ep *Endpoint) {
  263. sb.mu.Lock()
  264. defer sb.mu.Unlock()
  265. l := len(sb.endpoints)
  266. i := sort.Search(l, func(j int) bool {
  267. return ep.Less(sb.endpoints[j])
  268. })
  269. sb.endpoints = append(sb.endpoints, nil)
  270. copy(sb.endpoints[i+1:], sb.endpoints[i:])
  271. sb.endpoints[i] = ep
  272. }
  273. func (sb *Sandbox) removeEndpoint(ep *Endpoint) {
  274. sb.mu.Lock()
  275. defer sb.mu.Unlock()
  276. sb.removeEndpointRaw(ep)
  277. }
  278. func (sb *Sandbox) removeEndpointRaw(ep *Endpoint) {
  279. for i, e := range sb.endpoints {
  280. if e == ep {
  281. sb.endpoints = append(sb.endpoints[:i], sb.endpoints[i+1:]...)
  282. return
  283. }
  284. }
  285. }
  286. func (sb *Sandbox) getEndpoint(id string) *Endpoint {
  287. sb.mu.Lock()
  288. defer sb.mu.Unlock()
  289. for _, ep := range sb.endpoints {
  290. if ep.id == id {
  291. return ep
  292. }
  293. }
  294. return nil
  295. }
  296. func (sb *Sandbox) HandleQueryResp(name string, ip net.IP) {
  297. for _, ep := range sb.Endpoints() {
  298. n := ep.getNetwork()
  299. n.HandleQueryResp(name, ip)
  300. }
  301. }
  302. func (sb *Sandbox) ResolveIP(ctx context.Context, ip string) string {
  303. var svc string
  304. log.G(ctx).Debugf("IP To resolve %v", ip)
  305. for _, ep := range sb.Endpoints() {
  306. n := ep.getNetwork()
  307. svc = n.ResolveIP(ctx, ip)
  308. if len(svc) != 0 {
  309. return svc
  310. }
  311. }
  312. return svc
  313. }
  314. // ResolveService returns all the backend details about the containers or hosts
  315. // backing a service. Its purpose is to satisfy an SRV query.
  316. func (sb *Sandbox) ResolveService(ctx context.Context, name string) ([]*net.SRV, []net.IP) {
  317. log.G(ctx).Debugf("Service name To resolve: %v", name)
  318. // There are DNS implementations that allow SRV queries for names not in
  319. // the format defined by RFC 2782. Hence specific validations checks are
  320. // not done
  321. if parts := strings.SplitN(name, ".", 3); len(parts) < 3 {
  322. return nil, nil
  323. }
  324. for _, ep := range sb.Endpoints() {
  325. n := ep.getNetwork()
  326. srv, ip := n.ResolveService(ctx, name)
  327. if len(srv) > 0 {
  328. return srv, ip
  329. }
  330. }
  331. return nil, nil
  332. }
  333. func getDynamicNwEndpoints(epList []*Endpoint) []*Endpoint {
  334. eps := []*Endpoint{}
  335. for _, ep := range epList {
  336. n := ep.getNetwork()
  337. if n.dynamic && !n.ingress {
  338. eps = append(eps, ep)
  339. }
  340. }
  341. return eps
  342. }
  343. func getIngressNwEndpoint(epList []*Endpoint) *Endpoint {
  344. for _, ep := range epList {
  345. n := ep.getNetwork()
  346. if n.ingress {
  347. return ep
  348. }
  349. }
  350. return nil
  351. }
  352. func getLocalNwEndpoints(epList []*Endpoint) []*Endpoint {
  353. eps := []*Endpoint{}
  354. for _, ep := range epList {
  355. n := ep.getNetwork()
  356. if !n.dynamic && !n.ingress {
  357. eps = append(eps, ep)
  358. }
  359. }
  360. return eps
  361. }
  362. func (sb *Sandbox) ResolveName(ctx context.Context, name string, ipType int) ([]net.IP, bool) {
  363. // Embedded server owns the docker network domain. Resolution should work
  364. // for both container_name and container_name.network_name
  365. // We allow '.' in service name and network name. For a name a.b.c.d the
  366. // following have to tried;
  367. // {a.b.c.d in the networks container is connected to}
  368. // {a.b.c in network d},
  369. // {a.b in network c.d},
  370. // {a in network b.c.d},
  371. log.G(ctx).Debugf("Name To resolve: %v", name)
  372. name = strings.TrimSuffix(name, ".")
  373. reqName := []string{name}
  374. networkName := []string{""}
  375. if strings.Contains(name, ".") {
  376. var i int
  377. dup := name
  378. for {
  379. if i = strings.LastIndex(dup, "."); i == -1 {
  380. break
  381. }
  382. networkName = append(networkName, name[i+1:])
  383. reqName = append(reqName, name[:i])
  384. dup = dup[:i]
  385. }
  386. }
  387. epList := sb.Endpoints()
  388. // In swarm mode services with exposed ports are connected to user overlay
  389. // network, ingress network and docker_gwbridge network. Name resolution
  390. // should prioritize returning the VIP/IPs on user overlay network.
  391. newList := []*Endpoint{}
  392. if sb.controller.isSwarmNode() {
  393. newList = append(newList, getDynamicNwEndpoints(epList)...)
  394. ingressEP := getIngressNwEndpoint(epList)
  395. if ingressEP != nil {
  396. newList = append(newList, ingressEP)
  397. }
  398. newList = append(newList, getLocalNwEndpoints(epList)...)
  399. epList = newList
  400. }
  401. for i := 0; i < len(reqName); i++ {
  402. // First check for local container alias
  403. ip, ipv6Miss := sb.resolveName(ctx, reqName[i], networkName[i], epList, true, ipType)
  404. if ip != nil {
  405. return ip, false
  406. }
  407. if ipv6Miss {
  408. return ip, ipv6Miss
  409. }
  410. // Resolve the actual container name
  411. ip, ipv6Miss = sb.resolveName(ctx, reqName[i], networkName[i], epList, false, ipType)
  412. if ip != nil {
  413. return ip, false
  414. }
  415. if ipv6Miss {
  416. return ip, ipv6Miss
  417. }
  418. }
  419. return nil, false
  420. }
  421. func (sb *Sandbox) resolveName(ctx context.Context, nameOrAlias string, networkName string, epList []*Endpoint, lookupAlias bool, ipType int) (_ []net.IP, ipv6Miss bool) {
  422. ctx, span := otel.Tracer("").Start(ctx, "Sandbox.resolveName", trace.WithAttributes(
  423. attribute.String("libnet.resolver.name-or-alias", nameOrAlias),
  424. attribute.String("libnet.network.name", networkName),
  425. attribute.Bool("libnet.resolver.alias-lookup", lookupAlias),
  426. attribute.Int("libnet.resolver.ip-family", ipType)))
  427. defer span.End()
  428. for _, ep := range epList {
  429. if lookupAlias && len(ep.aliases) == 0 {
  430. continue
  431. }
  432. nw := ep.getNetwork()
  433. if networkName != "" && networkName != nw.Name() {
  434. continue
  435. }
  436. name := nameOrAlias
  437. if lookupAlias {
  438. ep.mu.Lock()
  439. alias, ok := ep.aliases[nameOrAlias]
  440. ep.mu.Unlock()
  441. if !ok {
  442. continue
  443. }
  444. name = alias
  445. } else {
  446. // If it is a regular lookup and if the requested name is an alias
  447. // don't perform a svc lookup for this endpoint.
  448. ep.mu.Lock()
  449. _, ok := ep.aliases[nameOrAlias]
  450. ep.mu.Unlock()
  451. if ok {
  452. continue
  453. }
  454. }
  455. ip, miss := nw.ResolveName(ctx, name, ipType)
  456. if ip != nil {
  457. return ip, false
  458. }
  459. if miss {
  460. ipv6Miss = miss
  461. }
  462. }
  463. return nil, ipv6Miss
  464. }
  465. // EnableService makes a managed container's service available by adding the
  466. // endpoint to the service load balancer and service discovery.
  467. func (sb *Sandbox) EnableService() (err error) {
  468. log.G(context.TODO()).Debugf("EnableService %s START", sb.containerID)
  469. defer func() {
  470. if err != nil {
  471. if err2 := sb.DisableService(); err2 != nil {
  472. log.G(context.TODO()).WithError(err2).WithField("origError", err).Error("Error while disabling service after original error")
  473. }
  474. }
  475. }()
  476. for _, ep := range sb.Endpoints() {
  477. if !ep.isServiceEnabled() {
  478. if err := ep.addServiceInfoToCluster(sb); err != nil {
  479. return fmt.Errorf("could not update state for endpoint %s into cluster: %v", ep.Name(), err)
  480. }
  481. ep.enableService()
  482. }
  483. }
  484. log.G(context.TODO()).Debugf("EnableService %s DONE", sb.containerID)
  485. return nil
  486. }
  487. // DisableService removes a managed container's endpoints from the load balancer
  488. // and service discovery.
  489. func (sb *Sandbox) DisableService() (err error) {
  490. log.G(context.TODO()).Debugf("DisableService %s START", sb.containerID)
  491. failedEps := []string{}
  492. defer func() {
  493. if len(failedEps) > 0 {
  494. err = fmt.Errorf("failed to disable service on sandbox:%s, for endpoints %s", sb.ID(), strings.Join(failedEps, ","))
  495. }
  496. }()
  497. for _, ep := range sb.Endpoints() {
  498. if ep.isServiceEnabled() {
  499. if err := ep.deleteServiceInfoFromCluster(sb, false, "DisableService"); err != nil {
  500. failedEps = append(failedEps, ep.Name())
  501. log.G(context.TODO()).Warnf("failed update state for endpoint %s into cluster: %v", ep.Name(), err)
  502. }
  503. ep.disableService()
  504. }
  505. }
  506. log.G(context.TODO()).Debugf("DisableService %s DONE", sb.containerID)
  507. return nil
  508. }
  509. func (sb *Sandbox) clearNetworkResources(origEp *Endpoint) error {
  510. ep := sb.getEndpoint(origEp.id)
  511. if ep == nil {
  512. return fmt.Errorf("could not find the sandbox endpoint data for endpoint %s",
  513. origEp.id)
  514. }
  515. sb.mu.Lock()
  516. osSbox := sb.osSbox
  517. inDelete := sb.inDelete
  518. sb.mu.Unlock()
  519. if osSbox != nil {
  520. releaseOSSboxResources(osSbox, ep)
  521. }
  522. sb.mu.Lock()
  523. delete(sb.populatedEndpoints, ep.ID())
  524. if len(sb.endpoints) == 0 {
  525. // sb.endpoints should never be empty and this is unexpected error condition
  526. // We log an error message to note this down for debugging purposes.
  527. log.G(context.TODO()).Errorf("No endpoints in sandbox while trying to remove endpoint %s", ep.Name())
  528. sb.mu.Unlock()
  529. return nil
  530. }
  531. var (
  532. gwepBefore, gwepAfter *Endpoint
  533. index = -1
  534. )
  535. for i, e := range sb.endpoints {
  536. if e == ep {
  537. index = i
  538. }
  539. if len(e.Gateway()) > 0 && gwepBefore == nil {
  540. gwepBefore = e
  541. }
  542. if index != -1 && gwepBefore != nil {
  543. break
  544. }
  545. }
  546. if index == -1 {
  547. log.G(context.TODO()).Warnf("Endpoint %s has already been deleted", ep.Name())
  548. sb.mu.Unlock()
  549. return nil
  550. }
  551. sb.removeEndpointRaw(ep)
  552. for _, e := range sb.endpoints {
  553. if len(e.Gateway()) > 0 {
  554. gwepAfter = e
  555. break
  556. }
  557. }
  558. delete(sb.epPriority, ep.ID())
  559. sb.mu.Unlock()
  560. if gwepAfter != nil && gwepBefore != gwepAfter {
  561. if err := sb.updateGateway(gwepAfter); err != nil {
  562. return err
  563. }
  564. }
  565. // Only update the store if we did not come here as part of
  566. // sandbox delete. If we came here as part of delete then do
  567. // not bother updating the store. The sandbox object will be
  568. // deleted anyway
  569. if !inDelete {
  570. return sb.storeUpdate()
  571. }
  572. return nil
  573. }
  574. // joinLeaveStart waits to ensure there are no joins or leaves in progress and
  575. // marks this join/leave in progress without race
  576. func (sb *Sandbox) joinLeaveStart() {
  577. sb.mu.Lock()
  578. defer sb.mu.Unlock()
  579. for sb.joinLeaveDone != nil {
  580. joinLeaveDone := sb.joinLeaveDone
  581. sb.mu.Unlock()
  582. <-joinLeaveDone
  583. sb.mu.Lock()
  584. }
  585. sb.joinLeaveDone = make(chan struct{})
  586. }
  587. // joinLeaveEnd marks the end of this join/leave operation and
  588. // signals the same without race to other join and leave waiters
  589. func (sb *Sandbox) joinLeaveEnd() {
  590. sb.mu.Lock()
  591. defer sb.mu.Unlock()
  592. if sb.joinLeaveDone != nil {
  593. close(sb.joinLeaveDone)
  594. sb.joinLeaveDone = nil
  595. }
  596. }
  597. // <=> Returns true if a < b, false if a > b and advances to next level if a == b
  598. // epi.prio <=> epj.prio # 2 < 1
  599. // epi.gw <=> epj.gw # non-gw < gw
  600. // epi.internal <=> epj.internal # non-internal < internal
  601. // epi.joininfo <=> epj.joininfo # ipv6 < ipv4
  602. // epi.name <=> epj.name # bar < foo
  603. func (epi *Endpoint) Less(epj *Endpoint) bool {
  604. var prioi, prioj int
  605. sbi, _ := epi.getSandbox()
  606. sbj, _ := epj.getSandbox()
  607. // Prio defaults to 0
  608. if sbi != nil {
  609. prioi = sbi.epPriority[epi.ID()]
  610. }
  611. if sbj != nil {
  612. prioj = sbj.epPriority[epj.ID()]
  613. }
  614. if prioi != prioj {
  615. return prioi > prioj
  616. }
  617. gwi := epi.endpointInGWNetwork()
  618. gwj := epj.endpointInGWNetwork()
  619. if gwi != gwj {
  620. return gwj
  621. }
  622. inti := epi.getNetwork().Internal()
  623. intj := epj.getNetwork().Internal()
  624. if inti != intj {
  625. return intj
  626. }
  627. jii := 0
  628. if epi.joinInfo != nil {
  629. if epi.joinInfo.gw != nil {
  630. jii = jii + 1
  631. }
  632. if epi.joinInfo.gw6 != nil {
  633. jii = jii + 2
  634. }
  635. }
  636. jij := 0
  637. if epj.joinInfo != nil {
  638. if epj.joinInfo.gw != nil {
  639. jij = jij + 1
  640. }
  641. if epj.joinInfo.gw6 != nil {
  642. jij = jij + 2
  643. }
  644. }
  645. if jii != jij {
  646. return jii > jij
  647. }
  648. return epi.network.Name() < epj.network.Name()
  649. }
  650. func (sb *Sandbox) NdotsSet() bool {
  651. return sb.ndotsSet
  652. }