provider.go 18.0 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 calico

import (
D
Duan Jiong 已提交
20
	"encoding/json"
D
Duan Jiong 已提交
21 22
	"errors"
	"fmt"
D
Duan Jiong 已提交
23 24
	"net"
	"time"
D
Duan Jiong 已提交
25 26 27 28

	v3 "github.com/projectcalico/libcalico-go/lib/apis/v3"
	"github.com/projectcalico/libcalico-go/lib/backend/model"
	cnet "github.com/projectcalico/libcalico-go/lib/net"
D
Duan Jiong 已提交
29
	corev1 "k8s.io/api/core/v1"
D
Duan Jiong 已提交
30 31
	k8serrors "k8s.io/apimachinery/pkg/api/errors"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
D
Duan Jiong 已提交
32 33 34 35 36 37 38
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	"k8s.io/apimachinery/pkg/util/wait"
	informercorev1 "k8s.io/client-go/informers/core/v1"
	clientset "k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/cache"
D
Duan Jiong 已提交
39
	"k8s.io/client-go/tools/clientcmd"
D
Duan Jiong 已提交
40
	"k8s.io/client-go/util/retry"
D
Duan Jiong 已提交
41 42 43 44 45 46
	"k8s.io/client-go/util/workqueue"
	"k8s.io/klog"
	"kubesphere.io/kubesphere/pkg/apis/network/calicov3"
	"kubesphere.io/kubesphere/pkg/apis/network/v1alpha1"
	kubesphereclient "kubesphere.io/kubesphere/pkg/client/clientset/versioned"
	"kubesphere.io/kubesphere/pkg/client/clientset/versioned/scheme"
D
Duan Jiong 已提交
47
	"kubesphere.io/kubesphere/pkg/constants"
D
Duan Jiong 已提交
48 49
	"kubesphere.io/kubesphere/pkg/simple/client/k8s"
	calicoset "kubesphere.io/kubesphere/pkg/simple/client/network/ippool/calico/client/clientset/versioned"
D
Duan Jiong 已提交
50 51
	calicoInformer "kubesphere.io/kubesphere/pkg/simple/client/network/ippool/calico/client/informers/externalversions"
	blockInformer "kubesphere.io/kubesphere/pkg/simple/client/network/ippool/calico/client/informers/externalversions/network/calicov3"
D
Duan Jiong 已提交
52 53 54 55
	"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)

const (
D
Duan Jiong 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
	CalicoAnnotationIPPoolV4  = "cni.projectcalico.org/ipv4pools"
	CalicoAnnotationIPPoolV6  = "cni.projectcalico.org/ipv6pools"
	CalicoPodAnnotationIPAddr = "cni.projectcalico.org/ipAddrs"
	CalicoPodAnnotationPodIP  = "cni.projectcalico.org/podIP"

	// Common attributes which may be set on allocations by clients.
	IPAMBlockAttributePod       = "pod"
	IPAMBlockAttributeNamespace = "namespace"
	IPAMBlockAttributeNode      = "node"
	IPAMBlockAttributeType      = "type"
	IPAMBlockAttributeTypeIPIP  = "ipipTunnelAddress"
	IPAMBlockAttributeTypeVXLAN = "vxlanTunnelAddress"

	CALICO_IPV4POOL_IPIP         = "CALICO_IPV4POOL_IPIP"
	CALICO_IPV4POOL_VXLAN        = "CALICO_IPV4POOL_VXLAN"
	CALICO_IPV4POOL_NAT_OUTGOING = "CALICO_IPV4POOL_NAT_OUTGOING"
	CalicoNodeDaemonset          = "calico-node"
	CalicoNodeNamespace          = "kube-system"

	DefaultBlockSize = 25
	// default re-sync period for all informer factories
	defaultResync = 600 * time.Second
D
Duan Jiong 已提交
78 79 80 81 82 83 84
)

var (
	ErrBlockInuse = errors.New("ipamblock in using")
)

type provider struct {
D
Duan Jiong 已提交
85 86 87 88 89 90 91 92 93
	client    calicoset.Interface
	ksclient  kubesphereclient.Interface
	k8sclient clientset.Interface
	pods      informercorev1.PodInformer
	block     blockInformer.IPAMBlockInformer
	queue     workqueue.RateLimitingInterface
	poolQueue workqueue.RateLimitingInterface

	options Options
D
Duan Jiong 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
}

func (c provider) CreateIPPool(pool *v1alpha1.IPPool) error {
	calicoPool := &calicov3.IPPool{
		TypeMeta: v1.TypeMeta{},
		ObjectMeta: v1.ObjectMeta{
			Name: pool.Name,
		},
		Spec: v3.IPPoolSpec{
			CIDR:         pool.Spec.CIDR,
			Disabled:     pool.Spec.Disabled,
			NodeSelector: "all()",
			VXLANMode:    v3.VXLANMode(c.options.VXLANMode),
			IPIPMode:     v3.IPIPMode(c.options.IPIPMode),
			NATOutgoing:  c.options.NATOutgoing,
		},
	}

D
Duan Jiong 已提交
112 113 114 115 116 117
	_, cidr, _ := net.ParseCIDR(pool.Spec.CIDR)
	size, _ := cidr.Mask.Size()
	if size > DefaultBlockSize {
		calicoPool.Spec.BlockSize = size
	}

D
Duan Jiong 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
	err := controllerutil.SetControllerReference(pool, calicoPool, scheme.Scheme)
	if err != nil {
		klog.Warningf("cannot set reference for calico ippool %s, err=%v", pool.Name, err)
	}

	_, err = c.client.CrdCalicov3().IPPools().Create(calicoPool)
	if k8serrors.IsAlreadyExists(err) {
		return nil
	}

	return err
}

func (c provider) UpdateIPPool(pool *v1alpha1.IPPool) error {
	return nil
}

func (c provider) GetIPPoolStats(pool *v1alpha1.IPPool) (*v1alpha1.IPPool, error) {
D
Duan Jiong 已提交
136
	stats := pool.DeepCopy()
D
Duan Jiong 已提交
137 138 139 140 141 142 143 144 145 146 147

	calicoPool, err := c.client.CrdCalicov3().IPPools().Get(pool.Name, v1.GetOptions{})
	if err != nil {
		return nil, err
	}

	blocks, err := c.listBlocks(calicoPool)
	if err != nil {
		return nil, err
	}

D
Duan Jiong 已提交
148 149 150
	if stats.Status.Capacity == 0 {
		stats.Status.Capacity = pool.NumAddresses()
	}
D
Duan Jiong 已提交
151 152
	stats.Status.Synced = true
	stats.Status.Allocations = 0
D
Duan Jiong 已提交
153 154 155 156
	stats.Status.Reserved = 0
	if stats.Status.Workspaces == nil {
		stats.Status.Workspaces = make(map[string]v1alpha1.WorkspaceStatus)
	}
D
Duan Jiong 已提交
157 158 159 160

	if len(blocks) <= 0 {
		stats.Status.Unallocated = pool.NumAddresses()
		stats.Status.Allocations = 0
D
Duan Jiong 已提交
161 162 163 164 165 166 167
	} else {
		for _, block := range blocks {
			stats.Status.Allocations += block.NumAddresses() - block.NumFreeAddresses() - block.NumReservedAddresses()
			stats.Status.Reserved += block.NumReservedAddresses()
		}

		stats.Status.Unallocated = stats.Status.Capacity - stats.Status.Allocations - stats.Status.Reserved
D
Duan Jiong 已提交
168 169
	}

D
Duan Jiong 已提交
170 171 172 173 174 175 176 177 178 179 180
	wks, err := c.getAssociatedWorkspaces(pool)
	if err != nil {
		return nil, err
	}

	for _, wk := range wks {
		status, err := c.getWorkspaceStatus(wk, pool.GetName())
		if err != nil {
			return nil, err
		}
		stats.Status.Workspaces[wk] = *status
D
Duan Jiong 已提交
181 182
	}

D
Duan Jiong 已提交
183 184 185 186 187
	for name, wk := range stats.Status.Workspaces {
		if wk.Allocations == 0 {
			delete(stats.Status.Workspaces, name)
		}
	}
D
Duan Jiong 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 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

	return stats, nil
}

func setBlockAffiDeletion(c calicoset.Interface, blockAffi *calicov3.BlockAffinity) error {
	if blockAffi.Spec.State == string(model.StatePendingDeletion) {
		return nil
	}

	blockAffi.Spec.State = string(model.StatePendingDeletion)
	_, err := c.CrdCalicov3().BlockAffinities().Update(blockAffi)
	return err
}

func deleteBlockAffi(c calicoset.Interface, blockAffi *calicov3.BlockAffinity) error {
	trueStr := fmt.Sprintf("%t", true)
	if blockAffi.Spec.Deleted != trueStr {
		blockAffi.Spec.Deleted = trueStr
		_, err := c.CrdCalicov3().BlockAffinities().Update(blockAffi)
		if err != nil {
			return err
		}
	}

	err := c.CrdCalicov3().BlockAffinities().Delete(blockAffi.Name, &v1.DeleteOptions{})
	if err != nil {
		return err
	}

	return nil
}

func (c provider) doBlockAffis(pool *calicov3.IPPool, do func(calicoset.Interface, *calicov3.BlockAffinity) error) error {
	_, cidrNet, _ := cnet.ParseCIDR(pool.Spec.CIDR)

	blockAffis, err := c.client.CrdCalicov3().BlockAffinities().List(v1.ListOptions{})
	if err != nil {
		return err
	}

	for _, blockAffi := range blockAffis.Items {
		_, blockCIDR, _ := cnet.ParseCIDR(blockAffi.Spec.CIDR)
		if !cidrNet.IsNetOverlap(blockCIDR.IPNet) {
			continue
		}

		err = do(c.client, &blockAffi)
		if err != nil {
			return err
		}
	}

	return nil
}

func (c provider) listBlocks(pool *calicov3.IPPool) ([]calicov3.IPAMBlock, error) {
	_, cidrNet, _ := cnet.ParseCIDR(pool.Spec.CIDR)

	blocks, err := c.client.CrdCalicov3().IPAMBlocks().List(v1.ListOptions{})
	if err != nil {
		return nil, err
	}

	var result []calicov3.IPAMBlock
	for _, block := range blocks.Items {
		_, blockCIDR, _ := cnet.ParseCIDR(block.Spec.CIDR)
		if !cidrNet.IsNetOverlap(blockCIDR.IPNet) {
			continue
		}
		result = append(result, block)
	}

	return result, nil
}

func (c provider) doBlocks(pool *calicov3.IPPool, do func(calicoset.Interface, *calicov3.IPAMBlock) error) error {
	blocks, err := c.listBlocks(pool)
	if err != nil {
		return err
	}

	for _, block := range blocks {
		err = do(c.client, &block)
		if err != nil {
			return err
		}
	}

	return nil
}

func deleteBlock(c calicoset.Interface, block *calicov3.IPAMBlock) error {
	if block.Empty() {
		if !block.Spec.Deleted {
			block.Spec.Deleted = true
			_, err := c.CrdCalicov3().IPAMBlocks().Update(block)
			if err != nil {
				return err
			}
		}
	} else {
		return ErrBlockInuse
	}
	err := c.CrdCalicov3().IPAMBlocks().Delete(block.Name, &v1.DeleteOptions{})
	if err != nil {
		return err
	}

	return nil
}

func (c provider) DeleteIPPool(pool *v1alpha1.IPPool) (bool, error) {
	// Deleting a pool requires a little care because of existing endpoints
	// using IP addresses allocated in the pool.  We do the deletion in
	// the following steps:
	// -  disable the pool so no more IPs are assigned from it
	// -  remove all affinities associated with the pool
	// -  delete the pool

	// Get the pool so that we can find the CIDR associated with it.
	calicoPool, err := c.client.CrdCalicov3().IPPools().Get(pool.Name, v1.GetOptions{})
	if err != nil {
D
Duan Jiong 已提交
310 311 312
		if k8serrors.IsNotFound(err) {
			return true, nil
		}
D
Duan Jiong 已提交
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 344 345 346 347 348 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 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
		return false, err
	}

	// If the pool is active, set the disabled flag to ensure we stop allocating from this pool.
	if !calicoPool.Spec.Disabled {
		calicoPool.Spec.Disabled = true

		calicoPool, err = c.client.CrdCalicov3().IPPools().Update(calicoPool)
		if err != nil {
			return false, err
		}
	}

	//If the address pool is being used, we return, avoiding deletions that cause other problems.
	stat, err := c.GetIPPoolStats(pool)
	if err != nil {
		return false, err
	}
	if stat.Status.Allocations > 0 {
		return false, nil
	}

	//set blockaffi to pendingdelete
	err = c.doBlockAffis(calicoPool, setBlockAffiDeletion)
	if err != nil {
		return false, err
	}

	//delete block
	err = c.doBlocks(calicoPool, deleteBlock)
	if err != nil {
		if errors.Is(err, ErrBlockInuse) {
			return false, nil
		}
		return false, err
	}

	//delete blockaffi
	err = c.doBlockAffis(calicoPool, deleteBlockAffi)
	if err != nil {
		return false, err
	}

	//delete calico ippool
	err = c.client.CrdCalicov3().IPPools().Delete(calicoPool.Name, &v1.DeleteOptions{})
	if err != nil {
		return false, err
	}

	//Congratulations, the ippool has been completely cleared.
	return true, nil
}

//Synchronizing address pools at boot time
func (c provider) syncIPPools() error {
	calicoPools, err := c.client.CrdCalicov3().IPPools().List(v1.ListOptions{})
	if err != nil {
		klog.V(4).Infof("syncIPPools: cannot list calico ippools, err=%v", err)
		return err
	}

	pools, err := c.ksclient.NetworkV1alpha1().IPPools().List(v1.ListOptions{})
	if err != nil {
		klog.V(4).Infof("syncIPPools: cannot list kubesphere ippools, err=%v", err)
		return err
	}

	existPools := map[string]bool{}
	for _, pool := range pools.Items {
		existPools[pool.Name] = true
	}

	for _, calicoPool := range calicoPools.Items {
		if _, ok := existPools[calicoPool.Name]; !ok {
			pool := &v1alpha1.IPPool{
				TypeMeta: v1.TypeMeta{},
				ObjectMeta: v1.ObjectMeta{
					Name: calicoPool.Name,
D
Duan Jiong 已提交
391 392 393
					Labels: map[string]string{
						v1alpha1.IPPoolDefaultLabel: "",
					},
D
Duan Jiong 已提交
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
				},
				Spec: v1alpha1.IPPoolSpec{
					Type:      v1alpha1.Calico,
					CIDR:      calicoPool.Spec.CIDR,
					Disabled:  calicoPool.Spec.Disabled,
					BlockSize: calicoPool.Spec.BlockSize,
				},
				Status: v1alpha1.IPPoolStatus{},
			}

			_, err = c.ksclient.NetworkV1alpha1().IPPools().Create(pool)
			if err != nil {
				klog.V(4).Infof("syncIPPools: cannot create kubesphere ippools, err=%v", err)
				return err
			}
		}
	}

	return nil
}

D
Duan Jiong 已提交
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
func (p provider) getAssociatedWorkspaces(pool *v1alpha1.IPPool) ([]string, error) {
	var result []string

	poolLabel := constants.WorkspaceLabelKey
	if pool.GetLabels() == nil || pool.GetLabels()[poolLabel] == "" {
		wks, err := p.ksclient.TenantV1alpha1().Workspaces().List(v1.ListOptions{})
		if err != nil {
			return nil, err
		}

		for _, wk := range wks.Items {
			result = append(result, wk.GetName())
		}

		return result, nil
	}

	return append(result, pool.GetLabels()[poolLabel]), nil
}

func (p provider) getWorkspaceStatus(name string, poolName string) (*v1alpha1.WorkspaceStatus, error) {
	var result v1alpha1.WorkspaceStatus

	namespaces, err := p.k8sclient.CoreV1().Namespaces().List(v1.ListOptions{
		LabelSelector: labels.SelectorFromSet(
			map[string]string{
				constants.WorkspaceLabelKey: name,
			},
		).String(),
	})
D
Duan Jiong 已提交
445
	if err != nil {
D
Duan Jiong 已提交
446
		return nil, err
D
Duan Jiong 已提交
447 448
	}

D
Duan Jiong 已提交
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
	for _, ns := range namespaces.Items {
		pods, err := p.k8sclient.CoreV1().Pods(ns.GetName()).List(v1.ListOptions{})
		if err != nil {
			return nil, err
		}
		for _, pod := range pods.Items {
			if pod.GetLabels() != nil && pod.GetLabels()[v1alpha1.IPPoolNameLabel] == poolName {
				result.Allocations++
			}
		}
	}

	return &result, nil
}

func (p provider) Type() string {
	return v1alpha1.IPPoolTypeCalico
}

func (p provider) SyncStatus(stopCh <-chan struct{}, q workqueue.RateLimitingInterface) error {
	defer utilruntime.HandleCrash()
	defer p.queue.ShutDown()

	klog.Info("starting calico block controller")
	defer klog.Info("shutting down calico block controller")

	p.poolQueue = q
	go p.block.Informer().Run(stopCh)

	if !cache.WaitForCacheSync(stopCh, p.pods.Informer().HasSynced, p.block.Informer().HasSynced) {
		klog.Fatal("failed to wait for caches to sync")
	}

	for i := 0; i < 5; i++ {
		go wait.Until(p.runWorker, time.Second, stopCh)
	}
D
Duan Jiong 已提交
485

D
Duan Jiong 已提交
486 487 488 489 490 491 492 493
	<-stopCh
	return nil
}

func (p provider) processBlock(name string) error {
	block, err := p.block.Lister().Get(name)
	if err != nil {
		if k8serrors.IsNotFound(err) {
D
Duan Jiong 已提交
494
			return nil
D
Duan Jiong 已提交
495 496 497 498
		}
		return err
	}
	_, blockCIDR, _ := cnet.ParseCIDR(block.Spec.CIDR)
D
Duan Jiong 已提交
499

D
Duan Jiong 已提交
500 501 502 503 504 505
	poolName := block.Labels[v1alpha1.IPPoolNameLabel]
	if poolName == "" {
		pools, err := p.ksclient.NetworkV1alpha1().IPPools().List(v1.ListOptions{})
		if err != nil {
			return err
		}
D
Duan Jiong 已提交
506

D
Duan Jiong 已提交
507 508 509 510
		for _, pool := range pools.Items {
			_, poolCIDR, _ := cnet.ParseCIDR(pool.Spec.CIDR)
			if poolCIDR.IsNetOverlap(blockCIDR.IPNet) {
				poolName = pool.Name
D
Duan Jiong 已提交
511

D
Duan Jiong 已提交
512 513
				block.Labels = map[string]string{
					v1alpha1.IPPoolNameLabel: pool.Name,
D
Duan Jiong 已提交
514
				}
D
Duan Jiong 已提交
515 516 517 518 519
				p.client.CrdCalicov3().IPAMBlocks().Update(block)
				break
			}
		}
	}
D
Duan Jiong 已提交
520

D
Duan Jiong 已提交
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
	for _, podAttr := range block.Spec.Attributes {
		name := podAttr.AttrSecondary[IPAMBlockAttributePod]
		namespace := podAttr.AttrSecondary[IPAMBlockAttributeNamespace]

		if name == "" || namespace == "" {
			continue
		}

		pod, err := p.pods.Lister().Pods(namespace).Get(name)
		if err != nil {
			continue
		}

		labels := pod.GetLabels()
		if labels != nil {
			poolLabel := labels[v1alpha1.IPPoolNameLabel]
			if poolLabel != "" {
				continue
			}
		}

		retry.RetryOnConflict(retry.DefaultBackoff, func() error {
			pod, err = p.k8sclient.CoreV1().Pods(namespace).Get(name, v1.GetOptions{})
			if err != nil {
				return err
			}

			labels := pod.GetLabels()
			if labels != nil {
				poolLabel := labels[v1alpha1.IPPoolNameLabel]
				if poolLabel != "" {
					return nil
D
Duan Jiong 已提交
553
				}
D
Duan Jiong 已提交
554 555 556 557 558 559
			} else {
				pod.Labels = make(map[string]string)
			}

			if pod.GetAnnotations() == nil {
				pod.Annotations = make(map[string]string)
D
Duan Jiong 已提交
560
			}
D
Duan Jiong 已提交
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634

			annostrs, _ := json.Marshal([]string{poolName})
			pod.GetAnnotations()[CalicoAnnotationIPPoolV4] = string(annostrs)
			pod.Labels[v1alpha1.IPPoolNameLabel] = poolName

			_, err = p.k8sclient.CoreV1().Pods(namespace).Update(pod)

			return err
		})
	}

	p.poolQueue.Add(poolName)
	return nil
}

func (p provider) processBlockItem() bool {
	key, quit := p.queue.Get()
	if quit {
		return false
	}
	defer p.queue.Done(key)

	err := p.processBlock(key.(string))
	if err == nil {
		p.queue.Forget(key)
		return true
	}

	utilruntime.HandleError(fmt.Errorf("error processing calico block %v (will retry): %v", key, err))
	p.queue.AddRateLimited(key)
	return true
}

func (p provider) runWorker() {
	for p.processBlockItem() {
	}
}

func (p provider) addBlock(obj interface{}) {
	block, ok := obj.(*calicov3.IPAMBlock)
	if !ok {
		return
	}

	p.queue.Add(block.Name)
}

func (p provider) Default(obj runtime.Object) error {
	pod, ok := obj.(*corev1.Pod)
	if !ok {
		return nil
	}

	annos := pod.GetAnnotations()
	if annos == nil {
		pod.Annotations = make(map[string]string)
	}

	if annos[CalicoAnnotationIPPoolV4] == "" {
		pools, err := p.ksclient.NetworkV1alpha1().IPPools().List(v1.ListOptions{
			LabelSelector: labels.SelectorFromSet(map[string]string{
				v1alpha1.IPPoolDefaultLabel: "",
			}).String(),
		})
		if err != nil {
			return err
		}
		var poolNames []string
		for _, pool := range pools.Items {
			poolNames = append(poolNames, pool.Name)
		}
		if len(poolNames) > 0 {
			annostrs, _ := json.Marshal(poolNames)
			pod.Annotations[CalicoAnnotationIPPoolV4] = string(annostrs)
D
Duan Jiong 已提交
635 636
		}
	}
D
Duan Jiong 已提交
637 638

	return nil
D
Duan Jiong 已提交
639 640
}

D
Duan Jiong 已提交
641
func NewProvider(podInformer informercorev1.PodInformer, ksclient kubesphereclient.Interface, k8sClient clientset.Interface, k8sOptions *k8s.KubernetesOptions) provider {
D
Duan Jiong 已提交
642 643 644 645 646 647 648 649 650 651 652
	config, err := clientcmd.BuildConfigFromFlags("", k8sOptions.KubeConfig)
	if err != nil {
		klog.Fatalf("failed to build k8s config , err=%v", err)
	}
	config.QPS = k8sOptions.QPS
	config.Burst = k8sOptions.Burst
	client, err := calicoset.NewForConfig(config)
	if err != nil {
		klog.Fatalf("failed to new calico client , err=%v", err)
	}

D
Duan Jiong 已提交
653 654 655
	ds, err := k8sClient.AppsV1().DaemonSets(CalicoNodeNamespace).Get(CalicoNodeDaemonset, v1.GetOptions{})
	if err != nil {
		klog.Fatalf("failed to get calico-node deployment in kube-system, err=%v", err)
D
Duan Jiong 已提交
656
	}
D
Duan Jiong 已提交
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
	opts := Options{
		IPIPMode:    "Always",
		VXLANMode:   "Never",
		NATOutgoing: true,
	}
	envs := ds.Spec.Template.Spec.Containers[0].Env
	for _, env := range envs {
		if env.Name == CALICO_IPV4POOL_IPIP {
			opts.IPIPMode = env.Value
		}

		if env.Name == CALICO_IPV4POOL_VXLAN {
			opts.VXLANMode = env.Value
		}

		if env.Name == CALICO_IPV4POOL_NAT_OUTGOING {
			if env.Value != "true" {
				opts.NATOutgoing = false
			}
		}
	}

	p := provider{
		client:    client,
		ksclient:  ksclient,
		k8sclient: k8sClient,
		pods:      podInformer,
		queue:     workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "calicoBlock"),
		options:   opts,
	}

	blockI := calicoInformer.NewSharedInformerFactory(client, defaultResync).Crd().Calicov3().IPAMBlocks()
	blockI.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: p.addBlock,
		UpdateFunc: func(old, new interface{}) {
			p.addBlock(new)
		},
	})
	p.block = blockI
D
Duan Jiong 已提交
696 697 698 699 700 701 702

	if err := p.syncIPPools(); err != nil {
		klog.Fatalf("failed to sync calico ippool to kubesphere ippool, err=%v", err)
	}

	return p
}