kube.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. // Copyright 2016 flannel 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 kube
  15. import (
  16. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "io/ioutil"
  20. "net"
  21. "os"
  22. "time"
  23. "github.com/coreos/flannel/pkg/ip"
  24. "github.com/coreos/flannel/subnet"
  25. "github.com/golang/glog"
  26. "golang.org/x/net/context"
  27. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  28. "k8s.io/apimachinery/pkg/runtime"
  29. "k8s.io/apimachinery/pkg/types"
  30. "k8s.io/apimachinery/pkg/util/strategicpatch"
  31. "k8s.io/apimachinery/pkg/util/wait"
  32. "k8s.io/apimachinery/pkg/watch"
  33. clientset "k8s.io/client-go/kubernetes"
  34. listers "k8s.io/client-go/listers/core/v1"
  35. "k8s.io/client-go/pkg/api"
  36. "k8s.io/client-go/pkg/api/v1"
  37. "k8s.io/client-go/rest"
  38. "k8s.io/client-go/tools/cache"
  39. )
  40. var (
  41. ErrUnimplemented = errors.New("unimplemented")
  42. )
  43. const (
  44. resyncPeriod = 5 * time.Minute
  45. nodeControllerSyncTimeout = 10 * time.Minute
  46. subnetKubeManagedAnnotation = "flannel.alpha.coreos.com/kube-subnet-manager"
  47. backendDataAnnotation = "flannel.alpha.coreos.com/backend-data"
  48. backendTypeAnnotation = "flannel.alpha.coreos.com/backend-type"
  49. backendPublicIPAnnotation = "flannel.alpha.coreos.com/public-ip"
  50. netConfPath = "/etc/kube-flannel/net-conf.json"
  51. )
  52. type kubeSubnetManager struct {
  53. client clientset.Interface
  54. nodeName string
  55. nodeStore listers.NodeLister
  56. nodeController cache.Controller
  57. subnetConf *subnet.Config
  58. events chan subnet.Event
  59. }
  60. func NewSubnetManager() (subnet.Manager, error) {
  61. cfg, err := rest.InClusterConfig()
  62. if err != nil {
  63. return nil, fmt.Errorf("unable to initialize inclusterconfig: %v", err)
  64. }
  65. c, err := clientset.NewForConfig(cfg)
  66. if err != nil {
  67. return nil, fmt.Errorf("unable to initialize client: %v", err)
  68. }
  69. podName := os.Getenv("POD_NAME")
  70. podNamespace := os.Getenv("POD_NAMESPACE")
  71. if podName == "" || podNamespace == "" {
  72. return nil, fmt.Errorf("env variables POD_NAME and POD_NAMESPACE must be set")
  73. }
  74. pod, err := c.Pods(podNamespace).Get(podName, metav1.GetOptions{})
  75. if err != nil {
  76. return nil, fmt.Errorf("error retrieving pod spec for '%s/%s': %v", podNamespace, podName, err)
  77. }
  78. nodeName := pod.Spec.NodeName
  79. if nodeName == "" {
  80. return nil, fmt.Errorf("node name not present in pod spec '%s/%s'", podNamespace, podName)
  81. }
  82. netConf, err := ioutil.ReadFile(netConfPath)
  83. if err != nil {
  84. return nil, fmt.Errorf("failed to read net conf: %v", err)
  85. }
  86. sc, err := subnet.ParseConfig(string(netConf))
  87. if err != nil {
  88. return nil, fmt.Errorf("error parsing subnet config: %s", err)
  89. }
  90. sm, err := newKubeSubnetManager(c, sc, nodeName)
  91. if err != nil {
  92. return nil, fmt.Errorf("error creating network manager: %s", err)
  93. }
  94. go sm.Run(context.Background())
  95. glog.Infof("Waiting %s for node controller to sync", nodeControllerSyncTimeout)
  96. err = wait.Poll(time.Second, nodeControllerSyncTimeout, func() (bool, error) {
  97. return sm.nodeController.HasSynced(), nil
  98. })
  99. if err != nil {
  100. return nil, fmt.Errorf("error waiting for nodeController to sync state: %v", err)
  101. }
  102. glog.Infof("Node controller sync successful")
  103. return sm, nil
  104. }
  105. func newKubeSubnetManager(c clientset.Interface, sc *subnet.Config, nodeName string) (*kubeSubnetManager, error) {
  106. var ksm kubeSubnetManager
  107. ksm.client = c
  108. ksm.nodeName = nodeName
  109. ksm.subnetConf = sc
  110. ksm.events = make(chan subnet.Event, 100)
  111. indexer, controller := cache.NewIndexerInformer(
  112. &cache.ListWatch{
  113. ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
  114. return ksm.client.CoreV1().Nodes().List(options)
  115. },
  116. WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
  117. return ksm.client.CoreV1().Nodes().Watch(options)
  118. },
  119. },
  120. &v1.Node{},
  121. resyncPeriod,
  122. cache.ResourceEventHandlerFuncs{
  123. AddFunc: func(obj interface{}) {
  124. ksm.handleAddLeaseEvent(subnet.EventAdded, obj)
  125. },
  126. UpdateFunc: ksm.handleUpdateLeaseEvent,
  127. DeleteFunc: func(obj interface{}) {
  128. ksm.handleAddLeaseEvent(subnet.EventRemoved, obj)
  129. },
  130. },
  131. cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
  132. )
  133. ksm.nodeController = controller
  134. ksm.nodeStore = listers.NewNodeLister(indexer)
  135. return &ksm, nil
  136. }
  137. func (ksm *kubeSubnetManager) handleAddLeaseEvent(et subnet.EventType, obj interface{}) {
  138. n := obj.(*v1.Node)
  139. if s, ok := n.Annotations[subnetKubeManagedAnnotation]; !ok || s != "true" {
  140. return
  141. }
  142. l, err := nodeToLease(*n)
  143. if err != nil {
  144. glog.Infof("Error turning node %q to lease: %v", n.ObjectMeta.Name, err)
  145. return
  146. }
  147. ksm.events <- subnet.Event{et, l}
  148. }
  149. func (ksm *kubeSubnetManager) handleUpdateLeaseEvent(oldObj, newObj interface{}) {
  150. o := oldObj.(*v1.Node)
  151. n := newObj.(*v1.Node)
  152. if s, ok := n.Annotations[subnetKubeManagedAnnotation]; !ok || s != "true" {
  153. return
  154. }
  155. if o.Annotations[backendDataAnnotation] == n.Annotations[backendDataAnnotation] &&
  156. o.Annotations[backendTypeAnnotation] == n.Annotations[backendTypeAnnotation] &&
  157. o.Annotations[backendPublicIPAnnotation] == n.Annotations[backendPublicIPAnnotation] {
  158. return // No change to lease
  159. }
  160. l, err := nodeToLease(*n)
  161. if err != nil {
  162. glog.Infof("Error turning node %q to lease: %v", n.ObjectMeta.Name, err)
  163. return
  164. }
  165. ksm.events <- subnet.Event{subnet.EventAdded, l}
  166. }
  167. func (ksm *kubeSubnetManager) GetNetworkConfig(ctx context.Context) (*subnet.Config, error) {
  168. return ksm.subnetConf, nil
  169. }
  170. func (ksm *kubeSubnetManager) AcquireLease(ctx context.Context, attrs *subnet.LeaseAttrs) (*subnet.Lease, error) {
  171. cachedNode, err := ksm.nodeStore.Get(ksm.nodeName)
  172. if err != nil {
  173. return nil, err
  174. }
  175. nobj, err := api.Scheme.DeepCopy(cachedNode)
  176. if err != nil {
  177. return nil, err
  178. }
  179. n := nobj.(*v1.Node)
  180. if n.Spec.PodCIDR == "" {
  181. return nil, fmt.Errorf("node %q pod cidr not assigned", ksm.nodeName)
  182. }
  183. bd, err := attrs.BackendData.MarshalJSON()
  184. if err != nil {
  185. return nil, err
  186. }
  187. _, cidr, err := net.ParseCIDR(n.Spec.PodCIDR)
  188. if err != nil {
  189. return nil, err
  190. }
  191. if n.Annotations[backendDataAnnotation] != string(bd) ||
  192. n.Annotations[backendTypeAnnotation] != attrs.BackendType ||
  193. n.Annotations[backendPublicIPAnnotation] != attrs.PublicIP.String() ||
  194. n.Annotations[subnetKubeManagedAnnotation] != "true" {
  195. n.Annotations[backendTypeAnnotation] = attrs.BackendType
  196. n.Annotations[backendDataAnnotation] = string(bd)
  197. n.Annotations[backendPublicIPAnnotation] = attrs.PublicIP.String()
  198. n.Annotations[subnetKubeManagedAnnotation] = "true"
  199. oldData, err := json.Marshal(cachedNode)
  200. if err != nil {
  201. return nil, err
  202. }
  203. newData, err := json.Marshal(n)
  204. if err != nil {
  205. return nil, err
  206. }
  207. patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, v1.Node{})
  208. if err != nil {
  209. return nil, fmt.Errorf("failed to create patch for node %q: %v", ksm.nodeName, err)
  210. }
  211. _, err = ksm.client.CoreV1().Nodes().Patch(ksm.nodeName, types.StrategicMergePatchType, patchBytes, "status")
  212. if err != nil {
  213. return nil, err
  214. }
  215. }
  216. return &subnet.Lease{
  217. Subnet: ip.FromIPNet(cidr),
  218. Attrs: *attrs,
  219. Expiration: time.Now().Add(24 * time.Hour),
  220. }, nil
  221. }
  222. func (ksm *kubeSubnetManager) WatchLeases(ctx context.Context, cursor interface{}) (subnet.LeaseWatchResult, error) {
  223. select {
  224. case event := <-ksm.events:
  225. return subnet.LeaseWatchResult{
  226. Events: []subnet.Event{event},
  227. }, nil
  228. case <-ctx.Done():
  229. return subnet.LeaseWatchResult{}, nil
  230. }
  231. }
  232. func (ksm *kubeSubnetManager) Run(ctx context.Context) {
  233. glog.Infof("Starting kube subnet manager")
  234. ksm.nodeController.Run(ctx.Done())
  235. }
  236. func nodeToLease(n v1.Node) (l subnet.Lease, err error) {
  237. l.Attrs.PublicIP, err = ip.ParseIP4(n.Annotations[backendPublicIPAnnotation])
  238. if err != nil {
  239. return l, err
  240. }
  241. l.Attrs.BackendType = n.Annotations[backendTypeAnnotation]
  242. l.Attrs.BackendData = json.RawMessage(n.Annotations[backendDataAnnotation])
  243. _, cidr, err := net.ParseCIDR(n.Spec.PodCIDR)
  244. if err != nil {
  245. return l, err
  246. }
  247. l.Subnet = ip.FromIPNet(cidr)
  248. return l, nil
  249. }
  250. // unimplemented
  251. func (ksm *kubeSubnetManager) RenewLease(ctx context.Context, lease *subnet.Lease) error {
  252. return ErrUnimplemented
  253. }
  254. func (ksm *kubeSubnetManager) WatchLease(ctx context.Context, sn ip.IP4Net, cursor interface{}) (subnet.LeaseWatchResult, error) {
  255. return subnet.LeaseWatchResult{}, ErrUnimplemented
  256. }
  257. func (ksm *kubeSubnetManager) RevokeLease(ctx context.Context, sn ip.IP4Net) error {
  258. return ErrUnimplemented
  259. }
  260. func (ksm *kubeSubnetManager) AddReservation(ctx context.Context, r *subnet.Reservation) error {
  261. return ErrUnimplemented
  262. }
  263. func (ksm *kubeSubnetManager) RemoveReservation(ctx context.Context, subnet ip.IP4Net) error {
  264. return ErrUnimplemented
  265. }
  266. func (ksm *kubeSubnetManager) ListReservations(ctx context.Context) ([]subnet.Reservation, error) {
  267. return nil, ErrUnimplemented
  268. }