backend.go 18 KB

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