mesh.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. // Copyright 2019 the Kilo authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // +build linux
  15. package mesh
  16. import (
  17. "bytes"
  18. "fmt"
  19. "io/ioutil"
  20. "net"
  21. "os"
  22. "sync"
  23. "time"
  24. "github.com/go-kit/kit/log"
  25. "github.com/go-kit/kit/log/level"
  26. "github.com/prometheus/client_golang/prometheus"
  27. "github.com/vishvananda/netlink"
  28. "github.com/squat/kilo/pkg/encapsulation"
  29. "github.com/squat/kilo/pkg/iproute"
  30. "github.com/squat/kilo/pkg/iptables"
  31. "github.com/squat/kilo/pkg/route"
  32. "github.com/squat/kilo/pkg/wireguard"
  33. )
  34. const (
  35. // kiloPath is the directory where Kilo stores its configuration.
  36. kiloPath = "/var/lib/kilo"
  37. // privateKeyPath is the filepath where the WireGuard private key is stored.
  38. privateKeyPath = kiloPath + "/key"
  39. // confPath is the filepath where the WireGuard configuration is stored.
  40. confPath = kiloPath + "/conf"
  41. )
  42. // Mesh is able to create Kilo network meshes.
  43. type Mesh struct {
  44. Backend
  45. cleanUpIface bool
  46. cni bool
  47. cniPath string
  48. enc encapsulation.Encapsulator
  49. externalIP *net.IPNet
  50. granularity Granularity
  51. hostname string
  52. internalIP *net.IPNet
  53. ipTables *iptables.Controller
  54. kiloIface int
  55. key []byte
  56. local bool
  57. port uint32
  58. priv []byte
  59. privIface int
  60. pub []byte
  61. stop chan struct{}
  62. subnet *net.IPNet
  63. table *route.Table
  64. wireGuardIP *net.IPNet
  65. // nodes and peers are mutable fields in the struct
  66. // and need to be guarded.
  67. nodes map[string]*Node
  68. peers map[string]*Peer
  69. mu sync.Mutex
  70. errorCounter *prometheus.CounterVec
  71. leaderGuage prometheus.Gauge
  72. nodesGuage prometheus.Gauge
  73. peersGuage prometheus.Gauge
  74. reconcileCounter prometheus.Counter
  75. logger log.Logger
  76. }
  77. // New returns a new Mesh instance.
  78. func New(backend Backend, enc encapsulation.Encapsulator, granularity Granularity, hostname string, port uint32, subnet *net.IPNet, local, cni bool, cniPath, iface string, cleanUpIface bool, createIface bool, logger log.Logger) (*Mesh, error) {
  79. if err := os.MkdirAll(kiloPath, 0700); err != nil {
  80. return nil, fmt.Errorf("failed to create directory to store configuration: %v", err)
  81. }
  82. private, err := ioutil.ReadFile(privateKeyPath)
  83. private = bytes.Trim(private, "\n")
  84. if err != nil {
  85. level.Warn(logger).Log("msg", "no private key found on disk; generating one now")
  86. if private, err = wireguard.GenKey(); err != nil {
  87. return nil, err
  88. }
  89. }
  90. public, err := wireguard.PubKey(private)
  91. if err != nil {
  92. return nil, err
  93. }
  94. if err := ioutil.WriteFile(privateKeyPath, private, 0600); err != nil {
  95. return nil, fmt.Errorf("failed to write private key to disk: %v", err)
  96. }
  97. cniIndex, err := cniDeviceIndex()
  98. if err != nil {
  99. return nil, fmt.Errorf("failed to query netlink for CNI device: %v", err)
  100. }
  101. var kiloIface int
  102. if createIface {
  103. kiloIface, _, err = wireguard.New(iface)
  104. if err != nil {
  105. return nil, fmt.Errorf("failed to create WireGuard interface: %v", err)
  106. }
  107. } else {
  108. link, err := netlink.LinkByName(iface)
  109. if err != nil {
  110. return nil, fmt.Errorf("failed to get interface index: %v", err)
  111. }
  112. kiloIface = link.Attrs().Index
  113. }
  114. privateIP, publicIP, err := getIP(hostname, kiloIface, enc.Index(), cniIndex)
  115. if err != nil {
  116. return nil, fmt.Errorf("failed to find public IP: %v", err)
  117. }
  118. var privIface int
  119. if privateIP != nil {
  120. ifaces, err := interfacesForIP(privateIP)
  121. if err != nil {
  122. return nil, fmt.Errorf("failed to find interface for private IP: %v", err)
  123. }
  124. privIface = ifaces[0].Index
  125. if enc.Strategy() != encapsulation.Never {
  126. if err := enc.Init(privIface); err != nil {
  127. return nil, fmt.Errorf("failed to initialize encapsulator: %v", err)
  128. }
  129. }
  130. level.Debug(logger).Log("msg", fmt.Sprintf("using %s as the private IP address", privateIP.String()))
  131. } else {
  132. enc = encapsulation.Noop(enc.Strategy())
  133. level.Debug(logger).Log("msg", "running without a private IP address")
  134. }
  135. level.Debug(logger).Log("msg", fmt.Sprintf("using %s as the public IP address", publicIP.String()))
  136. ipTables, err := iptables.New()
  137. if err != nil {
  138. return nil, fmt.Errorf("failed to IP tables controller: %v", err)
  139. }
  140. return &Mesh{
  141. Backend: backend,
  142. cleanUpIface: cleanUpIface,
  143. cni: cni,
  144. cniPath: cniPath,
  145. enc: enc,
  146. externalIP: publicIP,
  147. granularity: granularity,
  148. hostname: hostname,
  149. internalIP: privateIP,
  150. ipTables: ipTables,
  151. kiloIface: kiloIface,
  152. nodes: make(map[string]*Node),
  153. peers: make(map[string]*Peer),
  154. port: port,
  155. priv: private,
  156. privIface: privIface,
  157. pub: public,
  158. local: local,
  159. stop: make(chan struct{}),
  160. subnet: subnet,
  161. table: route.NewTable(),
  162. errorCounter: prometheus.NewCounterVec(prometheus.CounterOpts{
  163. Name: "kilo_errors_total",
  164. Help: "Number of errors that occurred while administering the mesh.",
  165. }, []string{"event"}),
  166. leaderGuage: prometheus.NewGauge(prometheus.GaugeOpts{
  167. Name: "kilo_leader",
  168. Help: "Leadership status of the node.",
  169. }),
  170. nodesGuage: prometheus.NewGauge(prometheus.GaugeOpts{
  171. Name: "kilo_nodes",
  172. Help: "Number of nodes in the mesh.",
  173. }),
  174. peersGuage: prometheus.NewGauge(prometheus.GaugeOpts{
  175. Name: "kilo_peers",
  176. Help: "Number of peers in the mesh.",
  177. }),
  178. reconcileCounter: prometheus.NewCounter(prometheus.CounterOpts{
  179. Name: "kilo_reconciles_total",
  180. Help: "Number of reconciliation attempts.",
  181. }),
  182. logger: logger,
  183. }, nil
  184. }
  185. // Run starts the mesh.
  186. func (m *Mesh) Run() error {
  187. if err := m.Nodes().Init(m.stop); err != nil {
  188. return fmt.Errorf("failed to initialize node backend: %v", err)
  189. }
  190. // Try to set the CNI config quickly.
  191. if m.cni {
  192. if n, err := m.Nodes().Get(m.hostname); err == nil {
  193. m.nodes[m.hostname] = n
  194. m.updateCNIConfig()
  195. } else {
  196. level.Warn(m.logger).Log("error", fmt.Errorf("failed to get node %q: %v", m.hostname, err))
  197. }
  198. }
  199. if err := m.Peers().Init(m.stop); err != nil {
  200. return fmt.Errorf("failed to initialize peer backend: %v", err)
  201. }
  202. ipTablesErrors, err := m.ipTables.Run(m.stop)
  203. if err != nil {
  204. return fmt.Errorf("failed to watch for IP tables updates: %v", err)
  205. }
  206. routeErrors, err := m.table.Run(m.stop)
  207. if err != nil {
  208. return fmt.Errorf("failed to watch for route table updates: %v", err)
  209. }
  210. go func() {
  211. for {
  212. var err error
  213. select {
  214. case err = <-ipTablesErrors:
  215. case err = <-routeErrors:
  216. case <-m.stop:
  217. return
  218. }
  219. if err != nil {
  220. level.Error(m.logger).Log("error", err)
  221. m.errorCounter.WithLabelValues("run").Inc()
  222. }
  223. }
  224. }()
  225. defer m.cleanUp()
  226. t := time.NewTimer(resyncPeriod)
  227. nw := m.Nodes().Watch()
  228. pw := m.Peers().Watch()
  229. var ne *NodeEvent
  230. var pe *PeerEvent
  231. for {
  232. select {
  233. case ne = <-nw:
  234. m.syncNodes(ne)
  235. case pe = <-pw:
  236. m.syncPeers(pe)
  237. case <-t.C:
  238. m.checkIn()
  239. if m.cni {
  240. m.updateCNIConfig()
  241. }
  242. m.applyTopology()
  243. t.Reset(resyncPeriod)
  244. case <-m.stop:
  245. return nil
  246. }
  247. }
  248. }
  249. func (m *Mesh) syncNodes(e *NodeEvent) {
  250. logger := log.With(m.logger, "event", e.Type)
  251. level.Debug(logger).Log("msg", "syncing nodes", "event", e.Type)
  252. if isSelf(m.hostname, e.Node) {
  253. level.Debug(logger).Log("msg", "processing local node", "node", e.Node)
  254. m.handleLocal(e.Node)
  255. return
  256. }
  257. var diff bool
  258. m.mu.Lock()
  259. if !e.Node.Ready() {
  260. level.Debug(logger).Log("msg", "received incomplete node", "node", e.Node)
  261. // An existing node is no longer valid
  262. // so remove it from the mesh.
  263. if _, ok := m.nodes[e.Node.Name]; ok {
  264. level.Info(logger).Log("msg", "node is no longer ready", "node", e.Node)
  265. diff = true
  266. }
  267. } else {
  268. switch e.Type {
  269. case AddEvent:
  270. fallthrough
  271. case UpdateEvent:
  272. if !nodesAreEqual(m.nodes[e.Node.Name], e.Node) {
  273. diff = true
  274. }
  275. // Even if the nodes are the same,
  276. // overwrite the old node to update the timestamp.
  277. m.nodes[e.Node.Name] = e.Node
  278. case DeleteEvent:
  279. delete(m.nodes, e.Node.Name)
  280. diff = true
  281. }
  282. }
  283. m.mu.Unlock()
  284. if diff {
  285. level.Info(logger).Log("node", e.Node)
  286. m.applyTopology()
  287. }
  288. }
  289. func (m *Mesh) syncPeers(e *PeerEvent) {
  290. logger := log.With(m.logger, "event", e.Type)
  291. level.Debug(logger).Log("msg", "syncing peers", "event", e.Type)
  292. var diff bool
  293. m.mu.Lock()
  294. // Peers are indexed by public key.
  295. key := string(e.Peer.PublicKey)
  296. if !e.Peer.Ready() {
  297. level.Debug(logger).Log("msg", "received incomplete peer", "peer", e.Peer)
  298. // An existing peer is no longer valid
  299. // so remove it from the mesh.
  300. if _, ok := m.peers[key]; ok {
  301. level.Info(logger).Log("msg", "peer is no longer ready", "peer", e.Peer)
  302. diff = true
  303. }
  304. } else {
  305. switch e.Type {
  306. case AddEvent:
  307. fallthrough
  308. case UpdateEvent:
  309. if e.Old != nil && key != string(e.Old.PublicKey) {
  310. delete(m.peers, string(e.Old.PublicKey))
  311. diff = true
  312. }
  313. if !peersAreEqual(m.peers[key], e.Peer) {
  314. m.peers[key] = e.Peer
  315. diff = true
  316. }
  317. case DeleteEvent:
  318. delete(m.peers, key)
  319. diff = true
  320. }
  321. }
  322. m.mu.Unlock()
  323. if diff {
  324. level.Info(logger).Log("peer", e.Peer)
  325. m.applyTopology()
  326. }
  327. }
  328. // checkIn will try to update the local node's LastSeen timestamp
  329. // in the backend.
  330. func (m *Mesh) checkIn() {
  331. m.mu.Lock()
  332. defer m.mu.Unlock()
  333. n := m.nodes[m.hostname]
  334. if n == nil {
  335. level.Debug(m.logger).Log("msg", "no local node found in backend")
  336. return
  337. }
  338. oldTime := n.LastSeen
  339. n.LastSeen = time.Now().Unix()
  340. if err := m.Nodes().Set(m.hostname, n); err != nil {
  341. level.Error(m.logger).Log("error", fmt.Sprintf("failed to set local node: %v", err), "node", n)
  342. m.errorCounter.WithLabelValues("checkin").Inc()
  343. // Revert time.
  344. n.LastSeen = oldTime
  345. return
  346. }
  347. level.Debug(m.logger).Log("msg", "successfully checked in local node in backend")
  348. }
  349. func (m *Mesh) handleLocal(n *Node) {
  350. // Allow the IPs to be overridden.
  351. if n.Endpoint == nil || (n.Endpoint.DNS == "" && n.Endpoint.IP == nil) {
  352. n.Endpoint = &wireguard.Endpoint{DNSOrIP: wireguard.DNSOrIP{IP: m.externalIP.IP}, Port: m.port}
  353. }
  354. if n.InternalIP == nil {
  355. n.InternalIP = m.internalIP
  356. }
  357. // Compare the given node to the calculated local node.
  358. // Take leader, location, and subnet from the argument, as these
  359. // are not determined by kilo.
  360. local := &Node{
  361. Endpoint: n.Endpoint,
  362. Key: m.pub,
  363. InternalIP: n.InternalIP,
  364. LastSeen: time.Now().Unix(),
  365. Leader: n.Leader,
  366. Location: n.Location,
  367. Name: m.hostname,
  368. PersistentKeepalive: n.PersistentKeepalive,
  369. Subnet: n.Subnet,
  370. WireGuardIP: m.wireGuardIP,
  371. }
  372. if !nodesAreEqual(n, local) {
  373. level.Debug(m.logger).Log("msg", "local node differs from backend")
  374. if err := m.Nodes().Set(m.hostname, local); err != nil {
  375. level.Error(m.logger).Log("error", fmt.Sprintf("failed to set local node: %v", err), "node", local)
  376. m.errorCounter.WithLabelValues("local").Inc()
  377. return
  378. }
  379. level.Debug(m.logger).Log("msg", "successfully reconciled local node against backend")
  380. }
  381. m.mu.Lock()
  382. n = m.nodes[m.hostname]
  383. if n == nil {
  384. n = &Node{}
  385. }
  386. m.mu.Unlock()
  387. if !nodesAreEqual(n, local) {
  388. m.mu.Lock()
  389. m.nodes[local.Name] = local
  390. m.mu.Unlock()
  391. m.applyTopology()
  392. }
  393. }
  394. func (m *Mesh) applyTopology() {
  395. m.reconcileCounter.Inc()
  396. m.mu.Lock()
  397. defer m.mu.Unlock()
  398. // If we can't resolve an endpoint, then fail and retry later.
  399. if err := m.resolveEndpoints(); err != nil {
  400. level.Error(m.logger).Log("error", err)
  401. m.errorCounter.WithLabelValues("apply").Inc()
  402. return
  403. }
  404. // Ensure only ready nodes are considered.
  405. nodes := make(map[string]*Node)
  406. var readyNodes float64
  407. for k := range m.nodes {
  408. if !m.nodes[k].Ready() {
  409. continue
  410. }
  411. // Make a shallow copy of the node.
  412. node := *m.nodes[k]
  413. nodes[k] = &node
  414. readyNodes++
  415. }
  416. // Ensure only ready nodes are considered.
  417. peers := make(map[string]*Peer)
  418. var readyPeers float64
  419. for k := range m.peers {
  420. if !m.peers[k].Ready() {
  421. continue
  422. }
  423. // Make a shallow copy of the peer.
  424. peer := *m.peers[k]
  425. peers[k] = &peer
  426. readyPeers++
  427. }
  428. m.nodesGuage.Set(readyNodes)
  429. m.peersGuage.Set(readyPeers)
  430. // We cannot do anything with the topology until the local node is available.
  431. if nodes[m.hostname] == nil {
  432. return
  433. }
  434. // Find the Kilo interface name.
  435. link, err := linkByIndex(m.kiloIface)
  436. if err != nil {
  437. level.Error(m.logger).Log("error", err)
  438. m.errorCounter.WithLabelValues("apply").Inc()
  439. return
  440. }
  441. // Find the old configuration.
  442. oldConfRaw, err := wireguard.ShowConf(link.Attrs().Name)
  443. if err != nil {
  444. level.Error(m.logger).Log("error", err)
  445. m.errorCounter.WithLabelValues("apply").Inc()
  446. return
  447. }
  448. oldConf := wireguard.Parse(oldConfRaw)
  449. updateNATEndpoints(nodes, peers, oldConf)
  450. t, err := NewTopology(nodes, peers, m.granularity, m.hostname, nodes[m.hostname].Endpoint.Port, m.priv, m.subnet, nodes[m.hostname].PersistentKeepalive)
  451. if err != nil {
  452. level.Error(m.logger).Log("error", err)
  453. m.errorCounter.WithLabelValues("apply").Inc()
  454. return
  455. }
  456. // Update the node's WireGuard IP.
  457. m.wireGuardIP = t.wireGuardCIDR
  458. conf := t.Conf()
  459. buf, err := conf.Bytes()
  460. if err != nil {
  461. level.Error(m.logger).Log("error", err)
  462. m.errorCounter.WithLabelValues("apply").Inc()
  463. return
  464. }
  465. if err := ioutil.WriteFile(confPath, buf, 0600); err != nil {
  466. level.Error(m.logger).Log("error", err)
  467. m.errorCounter.WithLabelValues("apply").Inc()
  468. return
  469. }
  470. ipRules := t.Rules(m.cni)
  471. // If we are handling local routes, ensure the local
  472. // tunnel has an IP address and IPIP traffic is allowed.
  473. if m.enc.Strategy() != encapsulation.Never && m.local {
  474. var cidrs []*net.IPNet
  475. for _, s := range t.segments {
  476. if s.location == nodes[m.hostname].Location {
  477. for i := range s.privateIPs {
  478. cidrs = append(cidrs, oneAddressCIDR(s.privateIPs[i]))
  479. }
  480. break
  481. }
  482. }
  483. ipRules = append(ipRules, m.enc.Rules(cidrs)...)
  484. // If we are handling local routes, ensure the local
  485. // tunnel has an IP address.
  486. if err := m.enc.Set(oneAddressCIDR(newAllocator(*nodes[m.hostname].Subnet).next().IP)); err != nil {
  487. level.Error(m.logger).Log("error", err)
  488. m.errorCounter.WithLabelValues("apply").Inc()
  489. return
  490. }
  491. }
  492. if err := m.ipTables.Set(ipRules); err != nil {
  493. level.Error(m.logger).Log("error", err)
  494. m.errorCounter.WithLabelValues("apply").Inc()
  495. return
  496. }
  497. if t.leader {
  498. m.leaderGuage.Set(1)
  499. if err := iproute.SetAddress(m.kiloIface, t.wireGuardCIDR); err != nil {
  500. level.Error(m.logger).Log("error", err)
  501. m.errorCounter.WithLabelValues("apply").Inc()
  502. return
  503. }
  504. // Setting the WireGuard configuration interrupts existing connections
  505. // so only set the configuration if it has changed.
  506. equal := conf.Equal(oldConf)
  507. if !equal {
  508. level.Info(m.logger).Log("msg", "WireGuard configurations are different")
  509. if err := wireguard.SetConf(link.Attrs().Name, confPath); err != nil {
  510. level.Error(m.logger).Log("error", err)
  511. m.errorCounter.WithLabelValues("apply").Inc()
  512. return
  513. }
  514. }
  515. if err := iproute.Set(m.kiloIface, true); err != nil {
  516. level.Error(m.logger).Log("error", err)
  517. m.errorCounter.WithLabelValues("apply").Inc()
  518. return
  519. }
  520. } else {
  521. m.leaderGuage.Set(0)
  522. level.Debug(m.logger).Log("msg", "local node is not the leader")
  523. if err := iproute.Set(m.kiloIface, false); err != nil {
  524. level.Error(m.logger).Log("error", err)
  525. m.errorCounter.WithLabelValues("apply").Inc()
  526. return
  527. }
  528. }
  529. // We need to add routes last since they may depend
  530. // on the WireGuard interface.
  531. routes, rules := t.Routes(link.Attrs().Name, m.kiloIface, m.privIface, m.enc.Index(), m.local, m.enc)
  532. if err := m.table.Set(routes, rules); err != nil {
  533. level.Error(m.logger).Log("error", err)
  534. m.errorCounter.WithLabelValues("apply").Inc()
  535. }
  536. }
  537. // RegisterMetrics registers Prometheus metrics on the given Prometheus
  538. // registerer.
  539. func (m *Mesh) RegisterMetrics(r prometheus.Registerer) {
  540. r.MustRegister(
  541. m.errorCounter,
  542. m.leaderGuage,
  543. m.nodesGuage,
  544. m.peersGuage,
  545. m.reconcileCounter,
  546. )
  547. }
  548. // Stop stops the mesh.
  549. func (m *Mesh) Stop() {
  550. close(m.stop)
  551. }
  552. func (m *Mesh) cleanUp() {
  553. if err := m.ipTables.CleanUp(); err != nil {
  554. level.Error(m.logger).Log("error", fmt.Sprintf("failed to clean up IP tables: %v", err))
  555. m.errorCounter.WithLabelValues("cleanUp").Inc()
  556. }
  557. if err := m.table.CleanUp(); err != nil {
  558. level.Error(m.logger).Log("error", fmt.Sprintf("failed to clean up routes: %v", err))
  559. m.errorCounter.WithLabelValues("cleanUp").Inc()
  560. }
  561. if err := os.Remove(confPath); err != nil {
  562. level.Error(m.logger).Log("error", fmt.Sprintf("failed to delete configuration file: %v", err))
  563. m.errorCounter.WithLabelValues("cleanUp").Inc()
  564. }
  565. if m.cleanUpIface {
  566. if err := iproute.RemoveInterface(m.kiloIface); err != nil {
  567. level.Error(m.logger).Log("error", fmt.Sprintf("failed to remove WireGuard interface: %v", err))
  568. m.errorCounter.WithLabelValues("cleanUp").Inc()
  569. }
  570. }
  571. if err := m.Nodes().CleanUp(m.hostname); err != nil {
  572. level.Error(m.logger).Log("error", fmt.Sprintf("failed to clean up node backend: %v", err))
  573. m.errorCounter.WithLabelValues("cleanUp").Inc()
  574. }
  575. if err := m.Peers().CleanUp(m.hostname); err != nil {
  576. level.Error(m.logger).Log("error", fmt.Sprintf("failed to clean up peer backend: %v", err))
  577. m.errorCounter.WithLabelValues("cleanUp").Inc()
  578. }
  579. if err := m.enc.CleanUp(); err != nil {
  580. level.Error(m.logger).Log("error", fmt.Sprintf("failed to clean up encapsulator: %v", err))
  581. m.errorCounter.WithLabelValues("cleanUp").Inc()
  582. }
  583. }
  584. func (m *Mesh) resolveEndpoints() error {
  585. for k := range m.nodes {
  586. // Skip unready nodes, since they will not be used
  587. // in the topology anyways.
  588. if !m.nodes[k].Ready() {
  589. continue
  590. }
  591. // If the node is ready, then the endpoint is not nil
  592. // but it may not have a DNS name.
  593. if m.nodes[k].Endpoint.DNS == "" {
  594. continue
  595. }
  596. if err := resolveEndpoint(m.nodes[k].Endpoint); err != nil {
  597. return err
  598. }
  599. }
  600. for k := range m.peers {
  601. // Skip unready peers, since they will not be used
  602. // in the topology anyways.
  603. if !m.peers[k].Ready() {
  604. continue
  605. }
  606. // Peers may have nil endpoints.
  607. if m.peers[k].Endpoint == nil || m.peers[k].Endpoint.DNS == "" {
  608. continue
  609. }
  610. if err := resolveEndpoint(m.peers[k].Endpoint); err != nil {
  611. return err
  612. }
  613. }
  614. return nil
  615. }
  616. func resolveEndpoint(endpoint *wireguard.Endpoint) error {
  617. ips, err := net.LookupIP(endpoint.DNS)
  618. if err != nil {
  619. return fmt.Errorf("failed to look up DNS name %q: %v", endpoint.DNS, err)
  620. }
  621. nets := make([]*net.IPNet, len(ips), len(ips))
  622. for i := range ips {
  623. nets[i] = oneAddressCIDR(ips[i])
  624. }
  625. sortIPs(nets)
  626. if len(nets) == 0 {
  627. return fmt.Errorf("did not find any addresses for DNS name %q", endpoint.DNS)
  628. }
  629. endpoint.IP = nets[0].IP
  630. return nil
  631. }
  632. func isSelf(hostname string, node *Node) bool {
  633. return node != nil && node.Name == hostname
  634. }
  635. func nodesAreEqual(a, b *Node) bool {
  636. if (a != nil) != (b != nil) {
  637. return false
  638. }
  639. if a == b {
  640. return true
  641. }
  642. if !(a.Endpoint != nil) == (b.Endpoint != nil) {
  643. return false
  644. }
  645. if a.Endpoint != nil {
  646. if a.Endpoint.Port != b.Endpoint.Port {
  647. return false
  648. }
  649. // Check the DNS name first since this package
  650. // is doing the DNS resolution.
  651. if a.Endpoint.DNS != b.Endpoint.DNS {
  652. return false
  653. }
  654. if a.Endpoint.DNS == "" && !a.Endpoint.IP.Equal(b.Endpoint.IP) {
  655. return false
  656. }
  657. }
  658. // Ignore LastSeen when comparing equality we want to check if the nodes are
  659. // equivalent. However, we do want to check if LastSeen has transitioned
  660. // between valid and invalid.
  661. return string(a.Key) == string(b.Key) && ipNetsEqual(a.WireGuardIP, b.WireGuardIP) && ipNetsEqual(a.InternalIP, b.InternalIP) && a.Leader == b.Leader && a.Location == b.Location && a.Name == b.Name && subnetsEqual(a.Subnet, b.Subnet) && a.Ready() == b.Ready() && a.PersistentKeepalive == b.PersistentKeepalive
  662. }
  663. func peersAreEqual(a, b *Peer) bool {
  664. if !(a != nil) == (b != nil) {
  665. return false
  666. }
  667. if a == b {
  668. return true
  669. }
  670. if !(a.Endpoint != nil) == (b.Endpoint != nil) {
  671. return false
  672. }
  673. if a.Endpoint != nil {
  674. if a.Endpoint.Port != b.Endpoint.Port {
  675. return false
  676. }
  677. // Check the DNS name first since this package
  678. // is doing the DNS resolution.
  679. if a.Endpoint.DNS != b.Endpoint.DNS {
  680. return false
  681. }
  682. if a.Endpoint.DNS == "" && !a.Endpoint.IP.Equal(b.Endpoint.IP) {
  683. return false
  684. }
  685. }
  686. if len(a.AllowedIPs) != len(b.AllowedIPs) {
  687. return false
  688. }
  689. for i := range a.AllowedIPs {
  690. if !ipNetsEqual(a.AllowedIPs[i], b.AllowedIPs[i]) {
  691. return false
  692. }
  693. }
  694. return string(a.PublicKey) == string(b.PublicKey) && string(a.PresharedKey) == string(b.PresharedKey) && a.PersistentKeepalive == b.PersistentKeepalive
  695. }
  696. func ipNetsEqual(a, b *net.IPNet) bool {
  697. if a == nil && b == nil {
  698. return true
  699. }
  700. if (a != nil) != (b != nil) {
  701. return false
  702. }
  703. if a.Mask.String() != b.Mask.String() {
  704. return false
  705. }
  706. return a.IP.Equal(b.IP)
  707. }
  708. func subnetsEqual(a, b *net.IPNet) bool {
  709. if a == nil && b == nil {
  710. return true
  711. }
  712. if (a != nil) != (b != nil) {
  713. return false
  714. }
  715. if a.Mask.String() != b.Mask.String() {
  716. return false
  717. }
  718. if !a.Contains(b.IP) {
  719. return false
  720. }
  721. if !b.Contains(a.IP) {
  722. return false
  723. }
  724. return true
  725. }
  726. func linkByIndex(index int) (netlink.Link, error) {
  727. link, err := netlink.LinkByIndex(index)
  728. if err != nil {
  729. return nil, fmt.Errorf("failed to get interface: %v", err)
  730. }
  731. return link, nil
  732. }
  733. // updateNATEndpoints ensures that nodes and peers behind NAT update
  734. // their endpoints from the WireGuard configuration so they can roam.
  735. func updateNATEndpoints(nodes map[string]*Node, peers map[string]*Peer, conf *wireguard.Conf) {
  736. keys := make(map[string]*wireguard.Peer)
  737. for i := range conf.Peers {
  738. keys[string(conf.Peers[i].PublicKey)] = conf.Peers[i]
  739. }
  740. for _, n := range nodes {
  741. if peer, ok := keys[string(n.Key)]; ok && n.PersistentKeepalive > 0 {
  742. n.Endpoint = peer.Endpoint
  743. }
  744. }
  745. for _, p := range peers {
  746. if peer, ok := keys[string(p.PublicKey)]; ok && p.PersistentKeepalive > 0 {
  747. p.Endpoint = peer.Endpoint
  748. }
  749. }
  750. }