kube.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. "k8s.io/kubernetes/pkg/api"
  28. "k8s.io/kubernetes/pkg/client/cache"
  29. clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
  30. "k8s.io/kubernetes/pkg/client/restclient"
  31. "k8s.io/kubernetes/pkg/controller/framework"
  32. "k8s.io/kubernetes/pkg/runtime"
  33. utilruntime "k8s.io/kubernetes/pkg/util/runtime"
  34. "k8s.io/kubernetes/pkg/util/wait"
  35. "k8s.io/kubernetes/pkg/watch"
  36. )
  37. var (
  38. ErrUnimplemented = errors.New("unimplemented")
  39. kubeSubnetCfg *subnet.Config
  40. )
  41. const (
  42. resyncPeriod = 5 * time.Minute
  43. nodeControllerSyncTimeout = 10 * time.Minute
  44. subnetKubeManagedAnnotation = "flannel.alpha.coreos.com/kube-subnet-manager"
  45. backendDataAnnotation = "flannel.alpha.coreos.com/backend-data"
  46. backendTypeAnnotation = "flannel.alpha.coreos.com/backend-type"
  47. backendPublicIPAnnotation = "flannel.alpha.coreos.com/public-ip"
  48. netConfPath = "/etc/kube-flannel/net-conf.json"
  49. )
  50. type kubeSubnetManager struct {
  51. client clientset.Interface
  52. nodeName string
  53. nodeStore cache.StoreToNodeLister
  54. nodeController *framework.Controller
  55. subnetConf *subnet.Config
  56. events chan subnet.Event
  57. selfEvents chan subnet.Event
  58. }
  59. func NewSubnetManager() (subnet.Manager, error) {
  60. cfg, err := restclient.InClusterConfig()
  61. if err != nil {
  62. return nil, fmt.Errorf("unable to initialize inclusterconfig: %v", err)
  63. }
  64. c, err := clientset.NewForConfig(cfg)
  65. if err != nil {
  66. return nil, fmt.Errorf("unable to initialize client: %v", err)
  67. }
  68. podName := os.Getenv("POD_NAME")
  69. podNamespace := os.Getenv("POD_NAMESPACE")
  70. if podName == "" || podNamespace == "" {
  71. return nil, fmt.Errorf("env variables POD_NAME and POD_NAMESPACE must be set")
  72. }
  73. pod, err := c.Pods(podNamespace).Get(podName)
  74. if err != nil {
  75. return nil, fmt.Errorf("error retrieving pod spec for '%s/%s': %v", podNamespace, podName, err)
  76. }
  77. nodeName := pod.Spec.NodeName
  78. if nodeName == "" {
  79. return nil, fmt.Errorf("node name not present in pod spec '%s/%s'", podNamespace, podName)
  80. }
  81. netConf, err := ioutil.ReadFile(netConfPath)
  82. if err != nil {
  83. return nil, fmt.Errorf("failed to read net conf: %v", err)
  84. }
  85. sc, err := subnet.ParseConfig(string(netConf))
  86. if err != nil {
  87. return nil, fmt.Errorf("error parsing subnet config: %s", err)
  88. }
  89. sm, err := newKubeSubnetManager(c, sc, nodeName)
  90. if err != nil {
  91. return nil, fmt.Errorf("error creating network manager: %s", err)
  92. }
  93. go sm.Run(context.Background())
  94. glog.Infof("Waiting %s for node controller to sync", nodeControllerSyncTimeout)
  95. err = wait.Poll(time.Second, nodeControllerSyncTimeout, func() (bool, error) {
  96. return sm.nodeController.HasSynced(), nil
  97. })
  98. if err != nil {
  99. return nil, fmt.Errorf("error waiting for nodeController to sync state: %v", err)
  100. }
  101. glog.Infof("Node controller sync successful")
  102. return sm, nil
  103. }
  104. func newKubeSubnetManager(c clientset.Interface, sc *subnet.Config, nodeName string) (*kubeSubnetManager, error) {
  105. var ksm kubeSubnetManager
  106. ksm.client = c
  107. ksm.nodeName = nodeName
  108. ksm.subnetConf = sc
  109. ksm.events = make(chan subnet.Event, 100)
  110. ksm.selfEvents = make(chan subnet.Event, 100)
  111. ksm.nodeStore.Store, ksm.nodeController = framework.NewInformer(
  112. &cache.ListWatch{
  113. ListFunc: func(options api.ListOptions) (runtime.Object, error) {
  114. return ksm.client.Core().Nodes().List(options)
  115. },
  116. WatchFunc: func(options api.ListOptions) (watch.Interface, error) {
  117. return ksm.client.Core().Nodes().Watch(options)
  118. },
  119. },
  120. &api.Node{},
  121. resyncPeriod,
  122. framework.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. )
  132. return &ksm, nil
  133. }
  134. func (ksm *kubeSubnetManager) handleAddLeaseEvent(et subnet.EventType, obj interface{}) {
  135. n := obj.(*api.Node)
  136. if s, ok := n.Annotations[subnetKubeManagedAnnotation]; !ok || s != "true" {
  137. return
  138. }
  139. l, err := nodeToLease(*n)
  140. if err != nil {
  141. glog.Infof("Error turning node %q to lease: %v", n.ObjectMeta.Name, err)
  142. return
  143. }
  144. ksm.events <- subnet.Event{et, l, ""}
  145. if n.ObjectMeta.Name == ksm.nodeName {
  146. ksm.selfEvents <- subnet.Event{et, l, ""}
  147. }
  148. }
  149. func (ksm *kubeSubnetManager) handleUpdateLeaseEvent(oldObj, newObj interface{}) {
  150. o := oldObj.(*api.Node)
  151. n := newObj.(*api.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. if n.ObjectMeta.Name == ksm.nodeName {
  167. ksm.selfEvents <- subnet.Event{subnet.EventAdded, l, ""}
  168. }
  169. }
  170. func (ksm *kubeSubnetManager) GetNetworkConfig(ctx context.Context, network string) (*subnet.Config, error) {
  171. return ksm.subnetConf, nil
  172. }
  173. func (ksm *kubeSubnetManager) AcquireLease(ctx context.Context, network string, attrs *subnet.LeaseAttrs) (*subnet.Lease, error) {
  174. nobj, found, err := ksm.nodeStore.Store.GetByKey(ksm.nodeName)
  175. if err != nil {
  176. return nil, err
  177. }
  178. if !found {
  179. return nil, fmt.Errorf("node %q not found", ksm.nodeName)
  180. }
  181. cacheNode, ok := nobj.(*api.Node)
  182. if !ok {
  183. return nil, fmt.Errorf("nobj was not a *api.Node")
  184. }
  185. // Make a copy so we're not modifying state of our cache
  186. objCopy, err := api.Scheme.Copy(cacheNode)
  187. if err != nil {
  188. return nil, fmt.Errorf("failed to make copy of node: %v", err)
  189. }
  190. n := objCopy.(*api.Node)
  191. if n.Spec.PodCIDR == "" {
  192. return nil, fmt.Errorf("node %q pod cidr not assigned", ksm.nodeName)
  193. }
  194. bd, err := attrs.BackendData.MarshalJSON()
  195. if err != nil {
  196. return nil, err
  197. }
  198. _, cidr, err := net.ParseCIDR(n.Spec.PodCIDR)
  199. if err != nil {
  200. return nil, err
  201. }
  202. if n.Annotations[backendDataAnnotation] != string(bd) ||
  203. n.Annotations[backendTypeAnnotation] != attrs.BackendType ||
  204. n.Annotations[backendPublicIPAnnotation] != attrs.PublicIP.String() ||
  205. n.Annotations[subnetKubeManagedAnnotation] != "true" {
  206. n.Annotations[backendTypeAnnotation] = attrs.BackendType
  207. n.Annotations[backendDataAnnotation] = string(bd)
  208. n.Annotations[backendPublicIPAnnotation] = attrs.PublicIP.String()
  209. n.Annotations[subnetKubeManagedAnnotation] = "true"
  210. n, err = ksm.client.Core().Nodes().Update(n)
  211. if err != nil {
  212. return nil, err
  213. }
  214. }
  215. return &subnet.Lease{
  216. Subnet: ip.FromIPNet(cidr),
  217. Attrs: *attrs,
  218. Expiration: time.Now().Add(24 * time.Hour),
  219. }, nil
  220. }
  221. func (ksm *kubeSubnetManager) RenewLease(ctx context.Context, network string, lease *subnet.Lease) error {
  222. l, err := ksm.AcquireLease(ctx, network, &lease.Attrs)
  223. if err != nil {
  224. return err
  225. }
  226. lease.Subnet = l.Subnet
  227. lease.Attrs = l.Attrs
  228. lease.Expiration = l.Expiration
  229. return nil
  230. }
  231. func (ksm *kubeSubnetManager) WatchLease(ctx context.Context, network string, sn ip.IP4Net, cursor interface{}) (subnet.LeaseWatchResult, error) {
  232. select {
  233. case event := <-ksm.selfEvents:
  234. return subnet.LeaseWatchResult{
  235. Events: []subnet.Event{event},
  236. }, nil
  237. case <-ctx.Done():
  238. return subnet.LeaseWatchResult{}, nil
  239. }
  240. }
  241. func (ksm *kubeSubnetManager) WatchLeases(ctx context.Context, network string, cursor interface{}) (subnet.LeaseWatchResult, error) {
  242. select {
  243. case event := <-ksm.events:
  244. return subnet.LeaseWatchResult{
  245. Events: []subnet.Event{event},
  246. }, nil
  247. case <-ctx.Done():
  248. return subnet.LeaseWatchResult{}, nil
  249. }
  250. }
  251. func (ksm *kubeSubnetManager) WatchNetworks(ctx context.Context, cursor interface{}) (subnet.NetworkWatchResult, error) {
  252. time.Sleep(time.Second)
  253. return subnet.NetworkWatchResult{
  254. Snapshot: []string{""},
  255. }, nil
  256. }
  257. func (ksm *kubeSubnetManager) Run(ctx context.Context) {
  258. defer utilruntime.HandleCrash()
  259. glog.Infof("starting kube subnet manager")
  260. ksm.nodeController.Run(ctx.Done())
  261. }
  262. func nodeToLease(n api.Node) (l subnet.Lease, err error) {
  263. l.Attrs.PublicIP, err = ip.ParseIP4(n.Annotations[backendPublicIPAnnotation])
  264. if err != nil {
  265. return l, err
  266. }
  267. l.Attrs.BackendType = n.Annotations[backendTypeAnnotation]
  268. l.Attrs.BackendData = json.RawMessage(n.Annotations[backendDataAnnotation])
  269. _, cidr, err := net.ParseCIDR(n.Spec.PodCIDR)
  270. if err != nil {
  271. return l, err
  272. }
  273. l.Subnet = ip.FromIPNet(cidr)
  274. l.Expiration = time.Now().Add(24 * time.Hour)
  275. return l, nil
  276. }
  277. // unimplemented
  278. func (ksm *kubeSubnetManager) RevokeLease(ctx context.Context, network string, sn ip.IP4Net) error {
  279. return ErrUnimplemented
  280. }
  281. func (ksm *kubeSubnetManager) AddReservation(ctx context.Context, network string, r *subnet.Reservation) error {
  282. return ErrUnimplemented
  283. }
  284. func (ksm *kubeSubnetManager) RemoveReservation(ctx context.Context, network string, subnet ip.IP4Net) error {
  285. return ErrUnimplemented
  286. }
  287. func (ksm *kubeSubnetManager) ListReservations(ctx context.Context, network string) ([]subnet.Reservation, error) {
  288. return nil, ErrUnimplemented
  289. }