ippool_controller.go 11.8 KB
Newer Older
D
Duan Jiong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
Copyright 2020 KubeSphere Authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package ippool

import (
Z
Zack Zhang 已提交
20
	"context"
D
Duan Jiong 已提交
21 22 23 24 25
	"fmt"
	"reflect"
	"time"

	cnet "github.com/projectcalico/libcalico-go/lib/net"
D
Duan Jiong 已提交
26
	podv1 "k8s.io/api/core/v1"
D
Duan Jiong 已提交
27 28 29 30
	v1 "k8s.io/api/core/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
D
Duan Jiong 已提交
31
	"k8s.io/apimachinery/pkg/runtime"
D
Duan Jiong 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	"k8s.io/apimachinery/pkg/util/wait"
	clientset "k8s.io/client-go/kubernetes"
	"k8s.io/client-go/kubernetes/scheme"
	corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/tools/record"
	"k8s.io/client-go/util/workqueue"
	"k8s.io/klog"
	networkv1alpha1 "kubesphere.io/kubesphere/pkg/apis/network/v1alpha1"
	kubesphereclient "kubesphere.io/kubesphere/pkg/client/clientset/versioned"
	networkInformer "kubesphere.io/kubesphere/pkg/client/informers/externalversions/network/v1alpha1"
	"kubesphere.io/kubesphere/pkg/controller/network/utils"
D
Duan Jiong 已提交
45
	"kubesphere.io/kubesphere/pkg/controller/network/webhooks"
D
Duan Jiong 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
	"kubesphere.io/kubesphere/pkg/simple/client/network/ippool"
	"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)

var (
	ErrCIDROverlap = fmt.Errorf("CIDR is overlap")
)

type IPPoolController struct {
	eventBroadcaster record.EventBroadcaster
	eventRecorder    record.EventRecorder

	provider ippool.Provider

	ippoolInformer networkInformer.IPPoolInformer
	ippoolSynced   cache.InformerSynced
	ippoolQueue    workqueue.RateLimitingInterface

	ipamblockInformer networkInformer.IPAMBlockInformer
	ipamblockSynced   cache.InformerSynced

	client           clientset.Interface
	kubesphereClient kubesphereclient.Interface
}

func (c *IPPoolController) ippoolHandle(obj interface{}) {
	pool, ok := obj.(*networkv1alpha1.IPPool)
	if !ok {
		utilruntime.HandleError(fmt.Errorf("IPPool informer returned non-ippool object: %#v", obj))
		return
	}
	key, err := cache.MetaNamespaceKeyFunc(pool)
	if err != nil {
		utilruntime.HandleError(fmt.Errorf("couldn't get key for ippool %#v: %v", pool, err))
		return
	}

	if utils.NeedToAddFinalizer(pool, networkv1alpha1.IPPoolFinalizer) || utils.IsDeletionCandidate(pool, networkv1alpha1.IPPoolFinalizer) {
		c.ippoolQueue.Add(key)
	}
}

func (c *IPPoolController) addFinalizer(pool *networkv1alpha1.IPPool) error {
	clone := pool.DeepCopy()
	controllerutil.AddFinalizer(clone, networkv1alpha1.IPPoolFinalizer)
	clone.Labels = map[string]string{
		networkv1alpha1.IPPoolNameLabel: clone.Name,
		networkv1alpha1.IPPoolTypeLabel: clone.Spec.Type,
		networkv1alpha1.IPPoolIDLabel:   fmt.Sprintf("%d", clone.ID()),
	}
Z
Zack Zhang 已提交
96
	pool, err := c.kubesphereClient.NetworkV1alpha1().IPPools().Update(context.TODO(), clone, metav1.UpdateOptions{})
D
Duan Jiong 已提交
97 98 99 100 101 102 103 104 105 106 107
	if err != nil {
		klog.V(3).Infof("Error adding  finalizer to pool %s: %v", pool.Name, err)
		return err
	}
	klog.V(3).Infof("Added finalizer to pool %s", pool.Name)
	return nil
}

func (c *IPPoolController) removeFinalizer(pool *networkv1alpha1.IPPool) error {
	clone := pool.DeepCopy()
	controllerutil.RemoveFinalizer(clone, networkv1alpha1.IPPoolFinalizer)
Z
Zack Zhang 已提交
108
	pool, err := c.kubesphereClient.NetworkV1alpha1().IPPools().Update(context.TODO(), clone, metav1.UpdateOptions{})
D
Duan Jiong 已提交
109 110 111 112 113 114 115 116
	if err != nil {
		klog.V(3).Infof("Error removing  finalizer from pool %s: %v", pool.Name, err)
		return err
	}
	klog.V(3).Infof("Removed protection finalizer from pool %s", pool.Name)
	return nil
}

D
Duan Jiong 已提交
117 118 119
func (c *IPPoolController) ValidateCreate(obj runtime.Object) error {
	b := obj.(*networkv1alpha1.IPPool)
	_, cidr, err := cnet.ParseCIDR(b.Spec.CIDR)
D
Duan Jiong 已提交
120
	if err != nil {
D
Duan Jiong 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
		return fmt.Errorf("invalid cidr")
	}

	size, _ := cidr.Mask.Size()
	if b.Spec.BlockSize > 0 && b.Spec.BlockSize < size {
		return fmt.Errorf("the blocksize should be larger than the cidr mask")
	}

	if b.Spec.RangeStart != "" || b.Spec.RangeEnd != "" {
		iStart := cnet.ParseIP(b.Spec.RangeStart)
		iEnd := cnet.ParseIP(b.Spec.RangeEnd)
		if iStart == nil || iEnd == nil {
			return fmt.Errorf("invalid rangeStart or rangeEnd")
		}
		offsetStart, err := b.IPToOrdinal(*iStart)
		if err != nil {
			return err
		}
		offsetEnd, err := b.IPToOrdinal(*iEnd)
		if err != nil {
			return err
		}
		if offsetEnd < offsetStart {
			return fmt.Errorf("rangeStart should not big than rangeEnd")
		}
D
Duan Jiong 已提交
146 147
	}

Z
Zack Zhang 已提交
148
	pools, err := c.kubesphereClient.NetworkV1alpha1().IPPools().List(context.TODO(), metav1.ListOptions{
D
Duan Jiong 已提交
149
		LabelSelector: labels.SelectorFromSet(labels.Set{
D
Duan Jiong 已提交
150
			networkv1alpha1.IPPoolIDLabel: fmt.Sprintf("%d", b.ID()),
D
Duan Jiong 已提交
151 152 153
		}).String(),
	})
	if err != nil {
D
Duan Jiong 已提交
154
		return err
D
Duan Jiong 已提交
155 156 157
	}

	for _, p := range pools.Items {
D
Duan Jiong 已提交
158 159
		if b.Overlapped(p) {
			return fmt.Errorf("ippool cidr is overlapped with %s", p.Name)
D
Duan Jiong 已提交
160
		}
D
Duan Jiong 已提交
161
	}
D
Duan Jiong 已提交
162

D
Duan Jiong 已提交
163 164 165 166 167 168 169 170 171
	return nil
}

func (c *IPPoolController) ValidateUpdate(old runtime.Object, new runtime.Object) error {
	oldP := old.(*networkv1alpha1.IPPool)
	newP := new.(*networkv1alpha1.IPPool)

	if newP.Spec.CIDR != oldP.Spec.CIDR {
		return fmt.Errorf("cidr cannot be modified")
D
Duan Jiong 已提交
172 173
	}

D
Duan Jiong 已提交
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
	if newP.Spec.Type != oldP.Spec.Type {
		return fmt.Errorf("ippool type cannot be modified")
	}

	if newP.Spec.BlockSize != oldP.Spec.BlockSize {
		return fmt.Errorf("ippool blockSize cannot be modified")
	}

	if newP.Spec.RangeEnd != oldP.Spec.RangeEnd || newP.Spec.RangeStart != oldP.Spec.RangeStart {
		return fmt.Errorf("ippool rangeEnd/rangeStart cannot be modified")
	}

	return nil
}

func (c *IPPoolController) ValidateDelete(obj runtime.Object) error {
	p := obj.(*networkv1alpha1.IPPool)

	if p.Status.Allocations > 0 {
		return fmt.Errorf("ippool is in use, please remove the workload before deleting")
	}

	return nil
D
Duan Jiong 已提交
197 198 199 200 201 202 203 204 205 206
}

func (c *IPPoolController) disableIPPool(old *networkv1alpha1.IPPool) error {
	if old.Spec.Disabled {
		return nil
	}

	clone := old.DeepCopy()
	clone.Spec.Disabled = true

Z
Zack Zhang 已提交
207
	old, err := c.kubesphereClient.NetworkV1alpha1().IPPools().Update(context.TODO(), clone, metav1.UpdateOptions{})
D
Duan Jiong 已提交
208 209 210 211 212 213 214

	return err
}

func (c *IPPoolController) updateIPPoolStatus(old *networkv1alpha1.IPPool) error {
	new, err := c.provider.GetIPPoolStats(old)
	if err != nil {
D
Duan Jiong 已提交
215
		return fmt.Errorf("failed to get ippool %s status %v", old.Name, err)
D
Duan Jiong 已提交
216 217 218 219 220 221
	}

	if reflect.DeepEqual(old.Status, new.Status) {
		return nil
	}

Z
Zack Zhang 已提交
222
	_, err = c.kubesphereClient.NetworkV1alpha1().IPPools().UpdateStatus(context.TODO(), new, metav1.UpdateOptions{})
D
Duan Jiong 已提交
223 224 225
	if err != nil {
		return fmt.Errorf("failed to update ippool %s status  %v", old.Name, err)
	}
D
Duan Jiong 已提交
226

D
Duan Jiong 已提交
227
	return nil
D
Duan Jiong 已提交
228 229 230 231 232 233 234 235 236 237
}

func (c *IPPoolController) processIPPool(name string) (*time.Duration, error) {
	klog.V(4).Infof("Processing IPPool %s", name)
	startTime := time.Now()
	defer func() {
		klog.V(4).Infof("Finished processing IPPool %s (%v)", name, time.Since(startTime))
	}()

	pool, err := c.ippoolInformer.Lister().Get(name)
D
Duan Jiong 已提交
238 239 240 241 242 243 244 245 246
	if err != nil {
		if apierrors.IsNotFound(err) {
			return nil, nil
		}
		return nil, fmt.Errorf("failed to get ippool %s: %v", name, err)
	}

	if pool.Type() != c.provider.Type() {
		klog.V(4).Infof("pool %s type not match, ignored", pool.Name)
D
Duan Jiong 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
		return nil, nil
	}

	if utils.IsDeletionCandidate(pool, networkv1alpha1.IPPoolFinalizer) {
		err = c.disableIPPool(pool)
		if err != nil {
			return nil, err
		}

		// Pool should be deleted. Check if it's used and remove finalizer if
		// it's not.
		canDelete, err := c.provider.DeleteIPPool(pool)
		if err != nil {
			return nil, err
		}
D
Duan Jiong 已提交
262

D
Duan Jiong 已提交
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
		if canDelete {
			return nil, c.removeFinalizer(pool)
		}

		//The  ippool is being used, update status and try again later.
		delay := time.Second * 3
		return &delay, c.updateIPPoolStatus(pool)
	}

	if utils.NeedToAddFinalizer(pool, networkv1alpha1.IPPoolFinalizer) {
		err = c.addFinalizer(pool)
		if err != nil {
			return nil, err
		}

		err = c.provider.CreateIPPool(pool)
		if err != nil {
			klog.V(4).Infof("Provider failed to create IPPool %s, err=%v", pool.Name, err)
			return nil, err
		}

		return nil, c.updateIPPoolStatus(pool)
	}

	err = c.provider.UpdateIPPool(pool)
	if err != nil {
		klog.V(4).Infof("Provider failed to update IPPool %s, err=%v", pool.Name, err)
		return nil, err
	}

	return nil, c.updateIPPoolStatus(pool)
}

func (c *IPPoolController) Start(stopCh <-chan struct{}) error {
	go c.provider.SyncStatus(stopCh, c.ippoolQueue)
	return c.Run(5, stopCh)
}

func (c *IPPoolController) Run(workers int, stopCh <-chan struct{}) error {
	defer utilruntime.HandleCrash()
	defer c.ippoolQueue.ShutDown()

	klog.Info("starting ippool controller")
	defer klog.Info("shutting down ippool controller")

	if !cache.WaitForCacheSync(stopCh, c.ippoolSynced, c.ipamblockSynced) {
		return fmt.Errorf("failed to wait for caches to sync")
	}

	for i := 0; i < workers; i++ {
		go wait.Until(c.runWorker, time.Second, stopCh)
	}

	<-stopCh
	return nil
}

func (c *IPPoolController) runWorker() {
	for c.processIPPoolItem() {
	}
}

func (c *IPPoolController) processIPPoolItem() bool {
	key, quit := c.ippoolQueue.Get()
	if quit {
		return false
	}
	defer c.ippoolQueue.Done(key)

	_, name, err := cache.SplitMetaNamespaceKey(key.(string))
	if err != nil {
		utilruntime.HandleError(fmt.Errorf("error parsing ippool key %q: %v", key, err))
		return true
	}

	delay, err := c.processIPPool(name)
	if err == nil {
		c.ippoolQueue.Forget(key)
		return true
	}

344 345 346 347 348
	if delay != nil {
		c.ippoolQueue.AddAfter(key, *delay)
	} else {
		c.ippoolQueue.AddRateLimited(key)
	}
D
Duan Jiong 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
	utilruntime.HandleError(fmt.Errorf("error processing ippool %v (will retry): %v", key, err))
	return true
}

func (c *IPPoolController) ipamblockHandle(obj interface{}) {
	block, ok := obj.(*networkv1alpha1.IPAMBlock)
	if !ok {
		return
	}

	poolName := block.Labels[networkv1alpha1.IPPoolNameLabel]
	c.ippoolQueue.Add(poolName)
}

func NewIPPoolController(
	ippoolInformer networkInformer.IPPoolInformer,
	ipamblockInformer networkInformer.IPAMBlockInformer,
	client clientset.Interface,
	kubesphereClient kubesphereclient.Interface,
	provider ippool.Provider) *IPPoolController {

	broadcaster := record.NewBroadcaster()
	broadcaster.StartLogging(func(format string, args ...interface{}) {
		klog.Info(fmt.Sprintf(format, args))
	})
	broadcaster.StartRecordingToSink(&corev1.EventSinkImpl{Interface: client.CoreV1().Events("")})
D
Duan Jiong 已提交
375
	recorder := broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: "ippool-controller"})
D
Duan Jiong 已提交
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405

	c := &IPPoolController{
		eventBroadcaster:  broadcaster,
		eventRecorder:     recorder,
		ippoolInformer:    ippoolInformer,
		ippoolSynced:      ippoolInformer.Informer().HasSynced,
		ippoolQueue:       workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "ippool"),
		ipamblockInformer: ipamblockInformer,
		ipamblockSynced:   ipamblockInformer.Informer().HasSynced,
		client:            client,
		kubesphereClient:  kubesphereClient,
		provider:          provider,
	}

	ippoolInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: c.ippoolHandle,
		UpdateFunc: func(old, new interface{}) {
			c.ippoolHandle(new)
		},
	})

	//just for update ippool status
	ipamblockInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: c.ipamblockHandle,
		UpdateFunc: func(old, new interface{}) {
			c.ipamblockHandle(new)
		},
		DeleteFunc: c.ipamblockHandle,
	})

D
Duan Jiong 已提交
406 407 408 409 410 411
	//register ippool webhook
	webhooks.RegisterValidator(networkv1alpha1.SchemeGroupVersion.WithKind(networkv1alpha1.ResourceKindIPPool).String(),
		&webhooks.ValidatorWrap{Obj: &networkv1alpha1.IPPool{}, Helper: c})
	webhooks.RegisterDefaulter(podv1.SchemeGroupVersion.WithKind("Pod").String(),
		&webhooks.DefaulterWrap{Obj: &podv1.Pod{}, Helper: provider})

D
Duan Jiong 已提交
412 413
	return c
}