backend.go 17 KB

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