mesh.go 22 KB

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