devopsproject_controller.go 7.5 KB
Newer Older
R
runzexia 已提交
1
package devopsproject
R
runzexia 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

import (
	"fmt"
	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	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"
	v1core "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"
	devopsv1alpha3 "kubesphere.io/kubesphere/pkg/apis/devops/v1alpha3"
	devopsClient "kubesphere.io/kubesphere/pkg/simple/client/devops"
	"kubesphere.io/kubesphere/pkg/utils/sliceutil"
	"net/http"
	"time"

	kubesphereclient "kubesphere.io/kubesphere/pkg/client/clientset/versioned"
	devopsinformers "kubesphere.io/kubesphere/pkg/client/informers/externalversions/devops/v1alpha3"
	devopslisters "kubesphere.io/kubesphere/pkg/client/listers/devops/v1alpha3"
)

R
runzexia 已提交
27 28 29 30
/**
	DevOps project controller is used to maintain the state of the DevOps project.
*/

R
runzexia 已提交
31
type Controller struct {
R
runzexia 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
	client           clientset.Interface
	kubesphereClient kubesphereclient.Interface

	eventBroadcaster record.EventBroadcaster
	eventRecorder    record.EventRecorder

	devOpsProjectLister devopslisters.DevOpsProjectLister
	devOpsProjectSynced cache.InformerSynced

	workqueue workqueue.RateLimitingInterface

	workerLoopPeriod time.Duration

	devopsClient devopsClient.Interface
}

R
runzexia 已提交
48 49
func NewController(client clientset.Interface,
	kubesphereClient kubesphereclient.Interface,
R
runzexia 已提交
50
	devopsClinet devopsClient.Interface,
R
runzexia 已提交
51
	devopsInformer devopsinformers.DevOpsProjectInformer) *Controller {
R
runzexia 已提交
52 53 54 55 56 57 58 59

	broadcaster := record.NewBroadcaster()
	broadcaster.StartLogging(func(format string, args ...interface{}) {
		klog.Info(fmt.Sprintf(format, args))
	})
	broadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: client.CoreV1().Events("")})
	recorder := broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: "devopsproject-controller"})

R
runzexia 已提交
60
	v := &Controller{
R
runzexia 已提交
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
		client:              client,
		devopsClient:        devopsClinet,
		kubesphereClient:    kubesphereClient,
		workqueue:           workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "devopsproject"),
		devOpsProjectLister: devopsInformer.Lister(),
		devOpsProjectSynced: devopsInformer.Informer().HasSynced,
		workerLoopPeriod:    time.Second,
	}

	v.eventBroadcaster = broadcaster
	v.eventRecorder = recorder

	devopsInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: v.enqueueDevOpsProject,
		UpdateFunc: func(oldObj, newObj interface{}) {
			old := oldObj.(*devopsv1alpha3.DevOpsProject)
			new := newObj.(*devopsv1alpha3.DevOpsProject)
			if old.ResourceVersion == new.ResourceVersion {
				return
			}
			v.enqueueDevOpsProject(newObj)
		},
		DeleteFunc: v.enqueueDevOpsProject,
	})
	return v
}

// enqueueDevOpsProject takes a Foo resource and converts it into a namespace/name
// string which is then put onto the work workqueue. This method should *not* be
// passed resources of any type other than DevOpsProject.
R
runzexia 已提交
91
func (c *Controller) enqueueDevOpsProject(obj interface{}) {
R
runzexia 已提交
92 93 94 95 96 97 98 99 100
	var key string
	var err error
	if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil {
		utilruntime.HandleError(err)
		return
	}
	c.workqueue.Add(key)
}

R
runzexia 已提交
101
func (c *Controller) processNextWorkItem() bool {
R
runzexia 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
	obj, shutdown := c.workqueue.Get()

	if shutdown {
		return false
	}

	err := func(obj interface{}) error {
		defer c.workqueue.Done(obj)
		var key string
		var ok bool

		if key, ok = obj.(string); !ok {
			c.workqueue.Forget(obj)
			utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj))
			return nil
		}
		if err := c.syncHandler(key); err != nil {
			c.workqueue.AddRateLimited(key)
			return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error())
		}
		c.workqueue.Forget(obj)
		klog.V(5).Infof("Successfully synced '%s'", key)
		return nil
	}(obj)

	if err != nil {
		klog.Error(err, "could not reconcile devopsProject")
		utilruntime.HandleError(err)
		return true
	}

	return true
}

R
runzexia 已提交
136
func (c *Controller) worker() {
R
runzexia 已提交
137 138 139 140 141

	for c.processNextWorkItem() {
	}
}

R
runzexia 已提交
142
func (c *Controller) Start(stopCh <-chan struct{}) error {
R
runzexia 已提交
143 144 145
	return c.Run(1, stopCh)
}

R
runzexia 已提交
146
func (c *Controller) Run(workers int, stopCh <-chan struct{}) error {
R
runzexia 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
	defer utilruntime.HandleCrash()
	defer c.workqueue.ShutDown()

	klog.Info("starting devops project controller")
	defer klog.Info("shutting down devops project controller")

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

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

	<-stopCh
	return nil
}

// syncHandler compares the actual state with the desired, and attempts to
// converge the two. It then updates the Status block of the devopsproject resource
// with the current status of the resource.
R
runzexia 已提交
168
func (c *Controller) syncHandler(key string) error {
R
runzexia 已提交
169 170 171 172 173 174 175 176 177
	project, err := c.devOpsProjectLister.Get(key)
	if err != nil {
		if errors.IsNotFound(err) {
			klog.Info(fmt.Sprintf("devopsproject '%s' in work queue no longer exists ", key))
			return nil
		}
		klog.Error(err, fmt.Sprintf("could not get devopsproject %s ", key))
		return err
	}
R
runzexia 已提交
178
	// DeletionTimestamp.IsZero() means DevOps project has not been deleted.
R
runzexia 已提交
179
	if project.ObjectMeta.DeletionTimestamp.IsZero() {
R
runzexia 已提交
180 181
		// Use Finalizers to sync DevOps status when DevOps project was deleted
		// https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/#finalizers
R
runzexia 已提交
182 183 184 185 186 187 188 189
		if !sliceutil.HasString(project.ObjectMeta.Finalizers, devopsv1alpha3.DevOpsProjectFinalizerName) {
			project.ObjectMeta.Finalizers = append(project.ObjectMeta.Finalizers, devopsv1alpha3.DevOpsProjectFinalizerName)
			_, err := c.kubesphereClient.DevopsV1alpha3().DevOpsProjects().Update(project)
			if err != nil {
				klog.Error(err, fmt.Sprintf("failed to update project %s ", key))
				return err
			}
		}
R
runzexia 已提交
190
		// Check project exists, otherwise we will create it.
R
runzexia 已提交
191 192 193 194 195 196 197 198 199 200 201
		_, err := c.devopsClient.GetDevOpsProject(key)
		if err != nil && devopsClient.GetDevOpsStatusCode(err) != http.StatusNotFound {
			klog.Error(err, fmt.Sprintf("failed to get project %s ", key))
			return err
		} else {
			_, err := c.devopsClient.CreateDevOpsProject(key)
			if err != nil {
				klog.Error(err, fmt.Sprintf("failed to get project %s ", key))
				return err
			}
		}
R
runzexia 已提交
202
	} else {
R
runzexia 已提交
203
		// Finalizers processing logic
R
runzexia 已提交
204
		if sliceutil.HasString(project.ObjectMeta.Finalizers, devopsv1alpha3.DevOpsProjectFinalizerName) {
R
runzexia 已提交
205 206 207
			_, err := c.devopsClient.GetDevOpsProject(key)
			if err != nil && devopsClient.GetDevOpsStatusCode(err) != http.StatusNotFound {
				klog.Error(err, fmt.Sprintf("failed to get project %s ", key))
R
runzexia 已提交
208
				return err
R
runzexia 已提交
209 210 211 212 213 214
			} else if err != nil && devopsClient.GetDevOpsStatusCode(err) == http.StatusNotFound {
			} else {
				if err := c.deleteDevOpsProjectInDevOps(project); err != nil {
					klog.Error(err, fmt.Sprintf("failed to delete resource %s in devops", key))
					return err
				}
R
runzexia 已提交
215 216 217 218 219
			}
			project.ObjectMeta.Finalizers = sliceutil.RemoveString(project.ObjectMeta.Finalizers, func(item string) bool {
				return item == devopsv1alpha3.DevOpsProjectFinalizerName
			})

R
runzexia 已提交
220
			_, err = c.kubesphereClient.DevopsV1alpha3().DevOpsProjects().Update(project)
R
runzexia 已提交
221
			if err != nil {
R
runzexia 已提交
222
				klog.Error(err, fmt.Sprintf("failed to update project %s ", key))
R
runzexia 已提交
223 224 225 226 227 228 229 230
				return err
			}
		}
	}

	return nil
}

R
runzexia 已提交
231
func (c *Controller) deleteDevOpsProjectInDevOps(project *devopsv1alpha3.DevOpsProject) error {
R
runzexia 已提交
232 233 234 235 236 237 238 239

	err := c.devopsClient.DeleteDevOpsProject(project.Name)
	if err != nil {
		klog.Errorf("error happened while deleting %s, %v", project.Name, err)
	}

	return nil
}