backend.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "net"
  20. "path"
  21. "strconv"
  22. "strings"
  23. "time"
  24. v1 "k8s.io/api/core/v1"
  25. "k8s.io/apimachinery/pkg/labels"
  26. "k8s.io/apimachinery/pkg/types"
  27. "k8s.io/apimachinery/pkg/util/strategicpatch"
  28. v1informers "k8s.io/client-go/informers/core/v1"
  29. "k8s.io/client-go/kubernetes"
  30. v1listers "k8s.io/client-go/listers/core/v1"
  31. "k8s.io/client-go/tools/cache"
  32. "github.com/squat/kilo/pkg/mesh"
  33. )
  34. const (
  35. // Backend is the name of this mesh backend.
  36. Backend = "kubernetes"
  37. externalIPAnnotationKey = "kilo.squat.ai/external-ip"
  38. forceExternalIPAnnotationKey = "kilo.squat.ai/force-external-ip"
  39. internalIPAnnotationKey = "kilo.squat.ai/internal-ip"
  40. keyAnnotationKey = "kilo.squat.ai/key"
  41. lastSeenAnnotationKey = "kilo.squat.ai/last-seen"
  42. leaderAnnotationKey = "kilo.squat.ai/leader"
  43. locationAnnotationKey = "kilo.squat.ai/location"
  44. regionLabelKey = "failure-domain.beta.kubernetes.io/region"
  45. jsonPatchSlash = "~1"
  46. jsonRemovePatch = `{"op": "remove", "path": "%s"}`
  47. )
  48. type backend struct {
  49. client kubernetes.Interface
  50. events chan *mesh.Event
  51. informer cache.SharedIndexInformer
  52. lister v1listers.NodeLister
  53. }
  54. // New creates a new instance of a mesh.Backend.
  55. func New(client kubernetes.Interface) mesh.Backend {
  56. informer := v1informers.NewNodeInformer(client, 5*time.Minute, nil)
  57. b := &backend{
  58. client: client,
  59. events: make(chan *mesh.Event),
  60. informer: informer,
  61. lister: v1listers.NewNodeLister(informer.GetIndexer()),
  62. }
  63. return b
  64. }
  65. // CleanUp removes configuration applied to the backend.
  66. func (b *backend) CleanUp(name string) error {
  67. patch := []byte("[" + strings.Join([]string{
  68. fmt.Sprintf(jsonRemovePatch, path.Join("/metadata", "annotations", strings.Replace(externalIPAnnotationKey, "/", jsonPatchSlash, 1))),
  69. fmt.Sprintf(jsonRemovePatch, path.Join("/metadata", "annotations", strings.Replace(internalIPAnnotationKey, "/", jsonPatchSlash, 1))),
  70. fmt.Sprintf(jsonRemovePatch, path.Join("/metadata", "annotations", strings.Replace(keyAnnotationKey, "/", jsonPatchSlash, 1))),
  71. fmt.Sprintf(jsonRemovePatch, path.Join("/metadata", "annotations", strings.Replace(lastSeenAnnotationKey, "/", jsonPatchSlash, 1))),
  72. }, ",") + "]")
  73. if _, err := b.client.CoreV1().Nodes().Patch(name, types.JSONPatchType, patch); err != nil {
  74. return fmt.Errorf("failed to patch node: %v", err)
  75. }
  76. return nil
  77. }
  78. // Get gets a single Node by name.
  79. func (b *backend) Get(name string) (*mesh.Node, error) {
  80. n, err := b.lister.Get(name)
  81. if err != nil {
  82. return nil, err
  83. }
  84. return translateNode(n), nil
  85. }
  86. // Init initializes the backend; for this backend that means
  87. // syncing the informer cache.
  88. func (b *backend) Init(stop <-chan struct{}) error {
  89. go b.informer.Run(stop)
  90. if ok := cache.WaitForCacheSync(stop, func() bool {
  91. return b.informer.HasSynced()
  92. }); !ok {
  93. return errors.New("failed to start sync node cache")
  94. }
  95. b.informer.AddEventHandler(
  96. cache.ResourceEventHandlerFuncs{
  97. AddFunc: func(obj interface{}) {
  98. n, ok := obj.(*v1.Node)
  99. if !ok {
  100. // Failed to decode Node; ignoring...
  101. return
  102. }
  103. b.events <- &mesh.Event{Type: mesh.AddEvent, Node: translateNode(n)}
  104. },
  105. UpdateFunc: func(_, obj interface{}) {
  106. n, ok := obj.(*v1.Node)
  107. if !ok {
  108. // Failed to decode Node; ignoring...
  109. return
  110. }
  111. b.events <- &mesh.Event{Type: mesh.UpdateEvent, Node: translateNode(n)}
  112. },
  113. DeleteFunc: func(obj interface{}) {
  114. n, ok := obj.(*v1.Node)
  115. if !ok {
  116. // Failed to decode Node; ignoring...
  117. return
  118. }
  119. b.events <- &mesh.Event{Type: mesh.DeleteEvent, Node: translateNode(n)}
  120. },
  121. },
  122. )
  123. return nil
  124. }
  125. // List gets all the Nodes in the cluster.
  126. func (b *backend) List() ([]*mesh.Node, error) {
  127. ns, err := b.lister.List(labels.Everything())
  128. if err != nil {
  129. return nil, err
  130. }
  131. nodes := make([]*mesh.Node, len(ns))
  132. for i := range ns {
  133. nodes[i] = translateNode(ns[i])
  134. }
  135. return nodes, nil
  136. }
  137. // Set sets the fields of a node.
  138. func (b *backend) Set(name string, node *mesh.Node) error {
  139. old, err := b.lister.Get(name)
  140. if err != nil {
  141. return fmt.Errorf("failed to find node: %v", err)
  142. }
  143. n := old.DeepCopy()
  144. n.ObjectMeta.Annotations[externalIPAnnotationKey] = node.ExternalIP.String()
  145. n.ObjectMeta.Annotations[internalIPAnnotationKey] = node.InternalIP.String()
  146. n.ObjectMeta.Annotations[keyAnnotationKey] = string(node.Key)
  147. n.ObjectMeta.Annotations[lastSeenAnnotationKey] = strconv.FormatInt(node.LastSeen, 10)
  148. oldData, err := json.Marshal(old)
  149. if err != nil {
  150. return err
  151. }
  152. newData, err := json.Marshal(n)
  153. if err != nil {
  154. return err
  155. }
  156. patch, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, v1.Node{})
  157. if err != nil {
  158. return fmt.Errorf("failed to create patch for node %q: %v", n.Name, err)
  159. }
  160. if _, err = b.client.CoreV1().Nodes().Patch(name, types.StrategicMergePatchType, patch); err != nil {
  161. return fmt.Errorf("failed to patch node: %v", err)
  162. }
  163. return nil
  164. }
  165. // Watch returns a chan of node events.
  166. func (b *backend) Watch() <-chan *mesh.Event {
  167. return b.events
  168. }
  169. // translateNode translates a Kubernetes Node to a mesh.Node.
  170. func translateNode(node *v1.Node) *mesh.Node {
  171. if node == nil {
  172. return nil
  173. }
  174. _, subnet, err := net.ParseCIDR(node.Spec.PodCIDR)
  175. // The subnet should only ever fail to parse if the pod CIDR has not been set,
  176. // so in this case set the subnet to nil and let the node be updated.
  177. if err != nil {
  178. subnet = nil
  179. }
  180. _, leader := node.ObjectMeta.Annotations[leaderAnnotationKey]
  181. // Allow the region to be overridden by an explicit location.
  182. location, ok := node.ObjectMeta.Annotations[locationAnnotationKey]
  183. if !ok {
  184. location = node.ObjectMeta.Labels[regionLabelKey]
  185. }
  186. // Allow the external IP to be overridden.
  187. externalIP, ok := node.ObjectMeta.Annotations[forceExternalIPAnnotationKey]
  188. if !ok {
  189. externalIP = node.ObjectMeta.Annotations[externalIPAnnotationKey]
  190. }
  191. var lastSeen int64
  192. if ls, ok := node.ObjectMeta.Annotations[lastSeenAnnotationKey]; !ok {
  193. lastSeen = 0
  194. } else {
  195. if lastSeen, err = strconv.ParseInt(ls, 10, 64); err != nil {
  196. lastSeen = 0
  197. }
  198. }
  199. return &mesh.Node{
  200. // ExternalIP and InternalIP should only ever fail to parse if the
  201. // remote node's mesh has not yet set its IP address;
  202. // in this case the IP will be nil and
  203. // the mesh can wait for the node to be updated.
  204. ExternalIP: normalizeIP(externalIP),
  205. InternalIP: normalizeIP(node.ObjectMeta.Annotations[internalIPAnnotationKey]),
  206. Key: []byte(node.ObjectMeta.Annotations[keyAnnotationKey]),
  207. LastSeen: lastSeen,
  208. Leader: leader,
  209. Location: location,
  210. Name: node.Name,
  211. Subnet: subnet,
  212. }
  213. }
  214. func normalizeIP(ip string) *net.IPNet {
  215. i, ipNet, _ := net.ParseCIDR(ip)
  216. if ipNet == nil {
  217. return ipNet
  218. }
  219. if ip4 := i.To4(); ip4 != nil {
  220. ipNet.IP = ip4
  221. return ipNet
  222. }
  223. ipNet.IP = i.To16()
  224. return ipNet
  225. }