backend.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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. package k8s
  15. import (
  16. "context"
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "net"
  21. "path"
  22. "strconv"
  23. "strings"
  24. "time"
  25. "github.com/go-kit/kit/log"
  26. "github.com/go-kit/kit/log/level"
  27. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  28. v1 "k8s.io/api/core/v1"
  29. apiextensions "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
  30. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  31. "k8s.io/apimachinery/pkg/labels"
  32. "k8s.io/apimachinery/pkg/types"
  33. "k8s.io/apimachinery/pkg/util/strategicpatch"
  34. v1informers "k8s.io/client-go/informers/core/v1"
  35. "k8s.io/client-go/kubernetes"
  36. v1listers "k8s.io/client-go/listers/core/v1"
  37. "k8s.io/client-go/tools/cache"
  38. "github.com/squat/kilo/pkg/k8s/apis/kilo/v1alpha1"
  39. kiloclient "github.com/squat/kilo/pkg/k8s/clientset/versioned"
  40. v1alpha1informers "github.com/squat/kilo/pkg/k8s/informers/kilo/v1alpha1"
  41. v1alpha1listers "github.com/squat/kilo/pkg/k8s/listers/kilo/v1alpha1"
  42. "github.com/squat/kilo/pkg/mesh"
  43. "github.com/squat/kilo/pkg/wireguard"
  44. )
  45. const (
  46. // Backend is the name of this mesh backend.
  47. Backend = "kubernetes"
  48. endpointAnnotationKey = "kilo.squat.ai/endpoint"
  49. forceEndpointAnnotationKey = "kilo.squat.ai/force-endpoint"
  50. forceInternalIPAnnotationKey = "kilo.squat.ai/force-internal-ip"
  51. internalIPAnnotationKey = "kilo.squat.ai/internal-ip"
  52. keyAnnotationKey = "kilo.squat.ai/key"
  53. lastSeenAnnotationKey = "kilo.squat.ai/last-seen"
  54. leaderAnnotationKey = "kilo.squat.ai/leader"
  55. locationAnnotationKey = "kilo.squat.ai/location"
  56. persistentKeepaliveKey = "kilo.squat.ai/persistent-keepalive"
  57. wireGuardIPAnnotationKey = "kilo.squat.ai/wireguard-ip"
  58. discoveredEndpointsKey = "kilo.squat.ai/discovered-endpoints"
  59. allowedLocationIPsKey = "kilo.squat.ai/allowed-location-ips"
  60. granularityKey = "kilo.squat.ai/granularity"
  61. // RegionLabelKey is the key for the well-known Kubernetes topology region label.
  62. RegionLabelKey = "topology.kubernetes.io/region"
  63. jsonPatchSlash = "~1"
  64. jsonRemovePatch = `{"op": "remove", "path": "%s"}`
  65. )
  66. var logger = log.NewNopLogger()
  67. type backend struct {
  68. nodes *nodeBackend
  69. peers *peerBackend
  70. }
  71. // Nodes implements the mesh.Backend interface.
  72. func (b *backend) Nodes() mesh.NodeBackend {
  73. return b.nodes
  74. }
  75. // Peers implements the mesh.Backend interface.
  76. func (b *backend) Peers() mesh.PeerBackend {
  77. return b.peers
  78. }
  79. type nodeBackend struct {
  80. client kubernetes.Interface
  81. events chan *mesh.NodeEvent
  82. informer cache.SharedIndexInformer
  83. lister v1listers.NodeLister
  84. topologyLabel string
  85. }
  86. type peerBackend struct {
  87. client kiloclient.Interface
  88. extensionsClient apiextensions.Interface
  89. events chan *mesh.PeerEvent
  90. informer cache.SharedIndexInformer
  91. lister v1alpha1listers.PeerLister
  92. }
  93. // New creates a new instance of a mesh.Backend.
  94. func New(c kubernetes.Interface, kc kiloclient.Interface, ec apiextensions.Interface, topologyLabel string, l log.Logger) mesh.Backend {
  95. ni := v1informers.NewNodeInformer(c, 5*time.Minute, nil)
  96. pi := v1alpha1informers.NewPeerInformer(kc, 5*time.Minute, nil)
  97. logger = l
  98. return &backend{
  99. &nodeBackend{
  100. client: c,
  101. events: make(chan *mesh.NodeEvent),
  102. informer: ni,
  103. lister: v1listers.NewNodeLister(ni.GetIndexer()),
  104. topologyLabel: topologyLabel,
  105. },
  106. &peerBackend{
  107. client: kc,
  108. extensionsClient: ec,
  109. events: make(chan *mesh.PeerEvent),
  110. informer: pi,
  111. lister: v1alpha1listers.NewPeerLister(pi.GetIndexer()),
  112. },
  113. }
  114. }
  115. // CleanUp removes configuration applied to the backend.
  116. func (nb *nodeBackend) CleanUp(ctx context.Context, name string) error {
  117. patch := []byte("[" + strings.Join([]string{
  118. fmt.Sprintf(jsonRemovePatch, path.Join("/metadata", "annotations", strings.Replace(endpointAnnotationKey, "/", jsonPatchSlash, 1))),
  119. fmt.Sprintf(jsonRemovePatch, path.Join("/metadata", "annotations", strings.Replace(internalIPAnnotationKey, "/", jsonPatchSlash, 1))),
  120. fmt.Sprintf(jsonRemovePatch, path.Join("/metadata", "annotations", strings.Replace(keyAnnotationKey, "/", jsonPatchSlash, 1))),
  121. fmt.Sprintf(jsonRemovePatch, path.Join("/metadata", "annotations", strings.Replace(lastSeenAnnotationKey, "/", jsonPatchSlash, 1))),
  122. fmt.Sprintf(jsonRemovePatch, path.Join("/metadata", "annotations", strings.Replace(wireGuardIPAnnotationKey, "/", jsonPatchSlash, 1))),
  123. fmt.Sprintf(jsonRemovePatch, path.Join("/metadata", "annotations", strings.Replace(discoveredEndpointsKey, "/", jsonPatchSlash, 1))),
  124. fmt.Sprintf(jsonRemovePatch, path.Join("/metadata", "annotations", strings.Replace(granularityKey, "/", jsonPatchSlash, 1))),
  125. }, ",") + "]")
  126. if _, err := nb.client.CoreV1().Nodes().Patch(ctx, name, types.JSONPatchType, patch, metav1.PatchOptions{}); err != nil {
  127. return fmt.Errorf("failed to patch node: %v", err)
  128. }
  129. return nil
  130. }
  131. // Get gets a single Node by name.
  132. func (nb *nodeBackend) Get(name string) (*mesh.Node, error) {
  133. n, err := nb.lister.Get(name)
  134. if err != nil {
  135. return nil, err
  136. }
  137. return translateNode(n, nb.topologyLabel), nil
  138. }
  139. // Init initializes the backend; for this backend that means
  140. // syncing the informer cache.
  141. func (nb *nodeBackend) Init(ctx context.Context) error {
  142. go nb.informer.Run(ctx.Done())
  143. if ok := cache.WaitForCacheSync(ctx.Done(), func() bool {
  144. return nb.informer.HasSynced()
  145. }); !ok {
  146. return errors.New("failed to sync node cache")
  147. }
  148. _, err := nb.informer.AddEventHandler(
  149. cache.ResourceEventHandlerFuncs{
  150. AddFunc: func(obj interface{}) {
  151. n, ok := obj.(*v1.Node)
  152. if !ok {
  153. // Failed to decode Node; ignoring...
  154. return
  155. }
  156. nb.events <- &mesh.NodeEvent{Type: mesh.AddEvent, Node: translateNode(n, nb.topologyLabel)}
  157. },
  158. UpdateFunc: func(old, obj interface{}) {
  159. n, ok := obj.(*v1.Node)
  160. if !ok {
  161. // Failed to decode Node; ignoring...
  162. return
  163. }
  164. o, ok := old.(*v1.Node)
  165. if !ok {
  166. // Failed to decode Node; ignoring...
  167. return
  168. }
  169. nb.events <- &mesh.NodeEvent{Type: mesh.UpdateEvent, Node: translateNode(n, nb.topologyLabel), Old: translateNode(o, nb.topologyLabel)}
  170. },
  171. DeleteFunc: func(obj interface{}) {
  172. n, ok := obj.(*v1.Node)
  173. if !ok {
  174. // Failed to decode Node; ignoring...
  175. return
  176. }
  177. nb.events <- &mesh.NodeEvent{Type: mesh.DeleteEvent, Node: translateNode(n, nb.topologyLabel)}
  178. },
  179. },
  180. )
  181. return err
  182. }
  183. // List gets all the Nodes in the cluster.
  184. func (nb *nodeBackend) List() ([]*mesh.Node, error) {
  185. ns, err := nb.lister.List(labels.Everything())
  186. if err != nil {
  187. return nil, err
  188. }
  189. nodes := make([]*mesh.Node, len(ns))
  190. for i := range ns {
  191. nodes[i] = translateNode(ns[i], nb.topologyLabel)
  192. }
  193. return nodes, nil
  194. }
  195. // Set sets the fields of a node.
  196. func (nb *nodeBackend) Set(ctx context.Context, name string, node *mesh.Node) error {
  197. old, err := nb.lister.Get(name)
  198. if err != nil {
  199. return fmt.Errorf("failed to find node: %v", err)
  200. }
  201. n := old.DeepCopy()
  202. n.Annotations[endpointAnnotationKey] = node.Endpoint.String()
  203. if node.InternalIP == nil {
  204. n.Annotations[internalIPAnnotationKey] = ""
  205. } else {
  206. n.Annotations[internalIPAnnotationKey] = node.InternalIP.String()
  207. }
  208. n.Annotations[keyAnnotationKey] = node.Key.String()
  209. n.Annotations[lastSeenAnnotationKey] = strconv.FormatInt(node.LastSeen, 10)
  210. if node.WireGuardIP == nil {
  211. n.Annotations[wireGuardIPAnnotationKey] = ""
  212. } else {
  213. n.Annotations[wireGuardIPAnnotationKey] = node.WireGuardIP.String()
  214. }
  215. if node.DiscoveredEndpoints == nil {
  216. n.Annotations[discoveredEndpointsKey] = ""
  217. } else {
  218. discoveredEndpoints, err := json.Marshal(node.DiscoveredEndpoints)
  219. if err != nil {
  220. return err
  221. }
  222. n.Annotations[discoveredEndpointsKey] = string(discoveredEndpoints)
  223. }
  224. n.Annotations[granularityKey] = string(node.Granularity)
  225. oldData, err := json.Marshal(old)
  226. if err != nil {
  227. return err
  228. }
  229. newData, err := json.Marshal(n)
  230. if err != nil {
  231. return err
  232. }
  233. patch, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, v1.Node{})
  234. if err != nil {
  235. return fmt.Errorf("failed to create patch for node %q: %v", n.Name, err)
  236. }
  237. if _, err = nb.client.CoreV1().Nodes().Patch(ctx, name, types.StrategicMergePatchType, patch, metav1.PatchOptions{}); err != nil {
  238. return fmt.Errorf("failed to patch node: %v", err)
  239. }
  240. return nil
  241. }
  242. // Watch returns a chan of node events.
  243. func (nb *nodeBackend) Watch() <-chan *mesh.NodeEvent {
  244. return nb.events
  245. }
  246. // translateNode translates a Kubernetes Node to a mesh.Node.
  247. func translateNode(node *v1.Node, topologyLabel string) *mesh.Node {
  248. if node == nil {
  249. return nil
  250. }
  251. _, subnet, err := net.ParseCIDR(node.Spec.PodCIDR)
  252. // The subnet should only ever fail to parse if the pod CIDR has not been set,
  253. // so in this case set the subnet to nil and let the node be updated.
  254. if err != nil {
  255. subnet = nil
  256. }
  257. _, leader := node.Annotations[leaderAnnotationKey]
  258. // Allow the region to be overridden by an explicit location.
  259. location, ok := node.Annotations[locationAnnotationKey]
  260. if !ok {
  261. location = node.Labels[topologyLabel]
  262. }
  263. // Allow the endpoint to be overridden.
  264. endpoint := wireguard.ParseEndpoint(node.Annotations[forceEndpointAnnotationKey])
  265. if endpoint == nil {
  266. endpoint = wireguard.ParseEndpoint(node.Annotations[endpointAnnotationKey])
  267. }
  268. // Allow the internal IP to be overridden.
  269. internalIP := normalizeIP(node.Annotations[forceInternalIPAnnotationKey])
  270. if internalIP == nil {
  271. internalIP = normalizeIP(node.Annotations[internalIPAnnotationKey])
  272. }
  273. // Set the ForceInternalIP flag, if force-internal-ip annotation was set to "".
  274. noInternalIP := false
  275. if s, ok := node.Annotations[forceInternalIPAnnotationKey]; ok && (s == "" || s == "-") {
  276. noInternalIP = true
  277. internalIP = nil
  278. }
  279. // Set Wireguard PersistentKeepalive setting for the node.
  280. var persistentKeepalive time.Duration
  281. if keepAlive, ok := node.Annotations[persistentKeepaliveKey]; ok {
  282. // We can ignore the error, because p will be set to 0 if an error occures.
  283. p, _ := strconv.ParseInt(keepAlive, 10, 64)
  284. persistentKeepalive = time.Duration(p) * time.Second
  285. }
  286. var lastSeen int64
  287. if ls, ok := node.Annotations[lastSeenAnnotationKey]; !ok {
  288. lastSeen = 0
  289. } else {
  290. if lastSeen, err = strconv.ParseInt(ls, 10, 64); err != nil {
  291. lastSeen = 0
  292. }
  293. }
  294. var discoveredEndpoints map[string]*net.UDPAddr
  295. if de, ok := node.Annotations[discoveredEndpointsKey]; ok {
  296. err := json.Unmarshal([]byte(de), &discoveredEndpoints)
  297. if err != nil {
  298. discoveredEndpoints = nil
  299. }
  300. }
  301. // Set allowed IPs for a location.
  302. var allowedLocationIPs []net.IPNet
  303. if str, ok := node.Annotations[allowedLocationIPsKey]; ok {
  304. for _, ip := range strings.Split(str, ",") {
  305. if ipnet := normalizeIP(ip); ipnet != nil {
  306. allowedLocationIPs = append(allowedLocationIPs, *ipnet)
  307. }
  308. }
  309. }
  310. var meshGranularity mesh.Granularity
  311. if gr, ok := node.Annotations[granularityKey]; ok {
  312. meshGranularity = mesh.Granularity(gr)
  313. switch meshGranularity {
  314. case mesh.LogicalGranularity:
  315. case mesh.FullGranularity:
  316. default:
  317. meshGranularity = ""
  318. }
  319. }
  320. // TODO log some error or warning.
  321. key, _ := wgtypes.ParseKey(node.Annotations[keyAnnotationKey])
  322. return &mesh.Node{
  323. // Endpoint and InternalIP should only ever fail to parse if the
  324. // remote node's agent has not yet set its IP address;
  325. // in this case the IP will be nil and
  326. // the mesh can wait for the node to be updated.
  327. // It is valid for the InternalIP to be nil,
  328. // if the given node only has public IP addresses.
  329. Endpoint: endpoint,
  330. NoInternalIP: noInternalIP,
  331. InternalIP: internalIP,
  332. Key: key,
  333. LastSeen: lastSeen,
  334. Leader: leader,
  335. Location: location,
  336. Name: node.Name,
  337. PersistentKeepalive: persistentKeepalive,
  338. Subnet: subnet,
  339. // WireGuardIP can fail to parse if the node is not a leader or if
  340. // the node's agent has not yet reconciled. In either case, the IP
  341. // will parse as nil.
  342. WireGuardIP: normalizeIP(node.Annotations[wireGuardIPAnnotationKey]),
  343. DiscoveredEndpoints: discoveredEndpoints,
  344. AllowedLocationIPs: allowedLocationIPs,
  345. Granularity: meshGranularity,
  346. }
  347. }
  348. // translatePeer translates a Peer CRD to a mesh.Peer.
  349. func translatePeer(peer *v1alpha1.Peer) *mesh.Peer {
  350. if peer == nil {
  351. return nil
  352. }
  353. var aips []net.IPNet
  354. for _, aip := range peer.Spec.AllowedIPs {
  355. aip := normalizeIP(aip)
  356. // Skip any invalid IPs.
  357. if aip == nil {
  358. continue
  359. }
  360. aips = append(aips, *aip)
  361. }
  362. var endpoint *wireguard.Endpoint
  363. if peer.Spec.Endpoint != nil {
  364. ip := net.ParseIP(peer.Spec.Endpoint.IP)
  365. if ip4 := ip.To4(); ip4 != nil {
  366. ip = ip4
  367. } else {
  368. ip = ip.To16()
  369. }
  370. if peer.Spec.Endpoint.Port > 0 {
  371. if ip != nil {
  372. endpoint = wireguard.NewEndpoint(ip, int(peer.Spec.Endpoint.Port))
  373. }
  374. if peer.Spec.Endpoint.DNS != "" {
  375. endpoint = wireguard.ParseEndpoint(fmt.Sprintf("%s:%d", peer.Spec.Endpoint.DNS, peer.Spec.Endpoint.Port))
  376. }
  377. }
  378. }
  379. key, err := wgtypes.ParseKey(peer.Spec.PublicKey)
  380. if err != nil {
  381. _ = level.Error(logger).Log("msg", "failed to parse public key", "peer", peer.Name, "err", err.Error())
  382. }
  383. var psk *wgtypes.Key
  384. if k, err := wgtypes.ParseKey(peer.Spec.PresharedKey); err != nil {
  385. // Set key to nil to avoid setting a key to the zero value wgtypes.Key{}
  386. psk = nil
  387. } else {
  388. psk = &k
  389. }
  390. var pka time.Duration
  391. if peer.Spec.PersistentKeepalive > 0 {
  392. pka = time.Duration(peer.Spec.PersistentKeepalive) * time.Second
  393. }
  394. return &mesh.Peer{
  395. Name: peer.Name,
  396. Peer: wireguard.Peer{
  397. PeerConfig: wgtypes.PeerConfig{
  398. AllowedIPs: aips,
  399. PersistentKeepaliveInterval: &pka,
  400. PresharedKey: psk,
  401. PublicKey: key,
  402. },
  403. Endpoint: endpoint,
  404. },
  405. }
  406. }
  407. // CleanUp removes configuration applied to the backend.
  408. func (pb *peerBackend) CleanUp(_ context.Context, _ string) error {
  409. return nil
  410. }
  411. // Get gets a single Peer by name.
  412. func (pb *peerBackend) Get(name string) (*mesh.Peer, error) {
  413. p, err := pb.lister.Get(name)
  414. if err != nil {
  415. return nil, err
  416. }
  417. return translatePeer(p), nil
  418. }
  419. // Init initializes the backend; for this backend that means
  420. // syncing the informer cache.
  421. func (pb *peerBackend) Init(ctx context.Context) error {
  422. // Check the presents of the CRD peers.kilo.squat.ai.
  423. if _, err := pb.extensionsClient.ApiextensionsV1().CustomResourceDefinitions().Get(ctx, strings.Join([]string{v1alpha1.PeerPlural, v1alpha1.GroupName}, "."), metav1.GetOptions{}); err != nil {
  424. return fmt.Errorf("CRD is not present: %v", err)
  425. }
  426. go pb.informer.Run(ctx.Done())
  427. if ok := cache.WaitForCacheSync(ctx.Done(), func() bool {
  428. return pb.informer.HasSynced()
  429. }); !ok {
  430. return errors.New("failed to sync peer cache")
  431. }
  432. _, err := pb.informer.AddEventHandler(
  433. cache.ResourceEventHandlerFuncs{
  434. AddFunc: func(obj interface{}) {
  435. p, ok := obj.(*v1alpha1.Peer)
  436. if !ok || p.Validate() != nil {
  437. // Failed to decode Peer; ignoring...
  438. return
  439. }
  440. pb.events <- &mesh.PeerEvent{Type: mesh.AddEvent, Peer: translatePeer(p)}
  441. },
  442. UpdateFunc: func(old, obj interface{}) {
  443. p, ok := obj.(*v1alpha1.Peer)
  444. if !ok || p.Validate() != nil {
  445. // Failed to decode Peer; ignoring...
  446. return
  447. }
  448. o, ok := old.(*v1alpha1.Peer)
  449. if !ok || o.Validate() != nil {
  450. // Failed to decode Peer; ignoring...
  451. return
  452. }
  453. pb.events <- &mesh.PeerEvent{Type: mesh.UpdateEvent, Peer: translatePeer(p), Old: translatePeer(o)}
  454. },
  455. DeleteFunc: func(obj interface{}) {
  456. p, ok := obj.(*v1alpha1.Peer)
  457. if !ok || p.Validate() != nil {
  458. // Failed to decode Peer; ignoring...
  459. return
  460. }
  461. pb.events <- &mesh.PeerEvent{Type: mesh.DeleteEvent, Peer: translatePeer(p)}
  462. },
  463. },
  464. )
  465. return err
  466. }
  467. // List gets all the Peers in the cluster.
  468. func (pb *peerBackend) List() ([]*mesh.Peer, error) {
  469. ps, err := pb.lister.List(labels.Everything())
  470. if err != nil {
  471. return nil, err
  472. }
  473. peers := make([]*mesh.Peer, len(ps))
  474. for i := range ps {
  475. // Skip invalid peers.
  476. if ps[i].Validate() != nil {
  477. continue
  478. }
  479. peers[i] = translatePeer(ps[i])
  480. }
  481. return peers, nil
  482. }
  483. // Set sets the fields of a peer.
  484. func (pb *peerBackend) Set(ctx context.Context, name string, peer *mesh.Peer) error {
  485. old, err := pb.lister.Get(name)
  486. if err != nil {
  487. return fmt.Errorf("failed to find peer: %v", err)
  488. }
  489. p := old.DeepCopy()
  490. p.Spec.AllowedIPs = make([]string, len(peer.AllowedIPs))
  491. for i := range peer.AllowedIPs {
  492. p.Spec.AllowedIPs[i] = peer.AllowedIPs[i].String()
  493. }
  494. if peer.Endpoint != nil {
  495. p.Spec.Endpoint = &v1alpha1.PeerEndpoint{
  496. DNSOrIP: v1alpha1.DNSOrIP{
  497. IP: peer.Endpoint.IP().String(),
  498. DNS: peer.Endpoint.DNS(),
  499. },
  500. Port: uint32(peer.Endpoint.Port()),
  501. }
  502. }
  503. if peer.PersistentKeepaliveInterval == nil {
  504. p.Spec.PersistentKeepalive = 0
  505. } else {
  506. p.Spec.PersistentKeepalive = int(*peer.PersistentKeepaliveInterval / time.Second)
  507. }
  508. if peer.PresharedKey == nil {
  509. p.Spec.PresharedKey = ""
  510. } else {
  511. p.Spec.PresharedKey = peer.PresharedKey.String()
  512. }
  513. p.Spec.PublicKey = peer.PublicKey.String()
  514. if _, err = pb.client.KiloV1alpha1().Peers().Update(ctx, p, metav1.UpdateOptions{}); err != nil {
  515. return fmt.Errorf("failed to update peer: %v", err)
  516. }
  517. return nil
  518. }
  519. // Watch returns a chan of peer events.
  520. func (pb *peerBackend) Watch() <-chan *mesh.PeerEvent {
  521. return pb.events
  522. }
  523. func normalizeIP(ip string) *net.IPNet {
  524. i, ipNet, err := net.ParseCIDR(ip)
  525. if err != nil || ipNet == nil {
  526. return nil
  527. }
  528. if ip4 := i.To4(); ip4 != nil {
  529. ipNet.IP = ip4
  530. return ipNet
  531. }
  532. ipNet.IP = i.To16()
  533. return ipNet
  534. }