backend.go 18 KB

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