kube.go 9.8 KB

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