forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipelineexecution.go
424 lines (380 loc) · 13.5 KB
/
pipelineexecution.go
1
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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
96
97
98
99
100
101
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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
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
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package pipelineexecution
import (
"context"
"github.com/pkg/errors"
"github.com/rancher/rancher/pkg/pipeline/engine"
"github.com/rancher/rancher/pkg/pipeline/utils"
"github.com/rancher/rancher/pkg/ref"
"github.com/rancher/types/apis/apps/v1beta2"
"github.com/rancher/types/apis/core/v1"
networkv1 "github.com/rancher/types/apis/networking.k8s.io/v1"
"github.com/rancher/types/apis/project.cattle.io/v3"
rbacv1 "github.com/rancher/types/apis/rbac.authorization.k8s.io/v1"
"github.com/rancher/types/config"
corev1 "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"
"strconv"
"strings"
)
//This controller is responsible for
// a) setup necessary components when pipeline executions are triggered
// b) maintain the execution queue
// c) terminate an execution when it is aborted
const (
projectIDLabel = "field.cattle.io/projectId"
roleCreateNs = "create-ns"
roleEditNsSuffix = "-namespaces-edit"
roleAdmin = "admin"
)
type Lifecycle struct {
namespaceLister v1.NamespaceLister
namespaces v1.NamespaceInterface
secrets v1.SecretInterface
serviceLister v1.ServiceLister
managementSecrets v1.SecretInterface
services v1.ServiceInterface
serviceAccounts v1.ServiceAccountInterface
configMapLister v1.ConfigMapLister
configMaps v1.ConfigMapInterface
podLister v1.PodLister
pods v1.PodInterface
networkPolicies networkv1.NetworkPolicyInterface
clusterRoleBindings rbacv1.ClusterRoleBindingInterface
roleBindings rbacv1.RoleBindingInterface
deployments v1beta2.DeploymentInterface
daemonsets v1beta2.DaemonSetInterface
pipelineLister v3.PipelineLister
pipelines v3.PipelineInterface
pipelineExecutionLister v3.PipelineExecutionLister
pipelineExecutions v3.PipelineExecutionInterface
pipelineSettingLister v3.PipelineSettingLister
pipelineEngine engine.PipelineEngine
sourceCodeCredentialLister v3.SourceCodeCredentialLister
}
func Register(ctx context.Context, cluster *config.UserContext) {
clusterName := cluster.ClusterName
namespaces := cluster.Core.Namespaces("")
namespaceLister := cluster.Core.Namespaces("").Controller().Lister()
secrets := cluster.Core.Secrets("")
secretLister := secrets.Controller().Lister()
managementSecrets := cluster.Management.Core.Secrets("")
managementSecretLister := managementSecrets.Controller().Lister()
services := cluster.Core.Services("")
serviceLister := services.Controller().Lister()
serviceAccounts := cluster.Core.ServiceAccounts("")
networkPolicies := cluster.Networking.NetworkPolicies("")
clusterRoleBindings := cluster.RBAC.ClusterRoleBindings("")
roleBindings := cluster.RBAC.RoleBindings("")
deployments := cluster.Apps.Deployments("")
daemonsets := cluster.Apps.DaemonSets("")
pods := cluster.Core.Pods("")
podLister := pods.Controller().Lister()
configMaps := cluster.Core.ConfigMaps("")
configMapLister := configMaps.Controller().Lister()
pipelines := cluster.Management.Project.Pipelines("")
pipelineLister := pipelines.Controller().Lister()
pipelineExecutions := cluster.Management.Project.PipelineExecutions("")
pipelineExecutionLister := pipelineExecutions.Controller().Lister()
pipelineSettingLister := cluster.Management.Project.PipelineSettings("").Controller().Lister()
sourceCodeCredentialLister := cluster.Management.Project.SourceCodeCredentials("").Controller().Lister()
pipelineEngine := engine.New(cluster)
pipelineExecutionLifecycle := &Lifecycle{
namespaces: namespaces,
namespaceLister: namespaceLister,
secrets: secrets,
managementSecrets: managementSecrets,
services: services,
serviceLister: serviceLister,
serviceAccounts: serviceAccounts,
networkPolicies: networkPolicies,
clusterRoleBindings: clusterRoleBindings,
roleBindings: roleBindings,
deployments: deployments,
daemonsets: daemonsets,
pods: pods,
podLister: podLister,
configMaps: configMaps,
configMapLister: configMapLister,
pipelineLister: pipelineLister,
pipelines: pipelines,
pipelineExecutionLister: pipelineExecutionLister,
pipelineExecutions: pipelineExecutions,
pipelineSettingLister: pipelineSettingLister,
pipelineEngine: pipelineEngine,
sourceCodeCredentialLister: sourceCodeCredentialLister,
}
stateSyncer := &ExecutionStateSyncer{
clusterName: clusterName,
pipelineLister: pipelineLister,
pipelines: pipelines,
pipelineExecutionLister: pipelineExecutionLister,
pipelineExecutions: pipelineExecutions,
pipelineEngine: pipelineEngine,
}
registryCertSyncer := &RegistryCertSyncer{
clusterName: clusterName,
pods: pods,
podLister: podLister,
secrets: secrets,
secretLister: secretLister,
managementSecretLister: managementSecretLister,
namespaceLister: namespaceLister,
pipelineExecutionLister: pipelineExecutionLister,
pipelineSettingLister: pipelineSettingLister,
}
pipelineExecutions.AddClusterScopedLifecycle(pipelineExecutionLifecycle.GetName(), cluster.ClusterName, pipelineExecutionLifecycle)
go stateSyncer.sync(ctx, syncStateInterval)
go registryCertSyncer.sync(ctx, checkCertRotateInterval)
}
func (l *Lifecycle) Create(obj *v3.PipelineExecution) (*v3.PipelineExecution, error) {
return l.Sync(obj)
}
func (l *Lifecycle) Updated(obj *v3.PipelineExecution) (*v3.PipelineExecution, error) {
return l.Sync(obj)
}
func (l *Lifecycle) Sync(obj *v3.PipelineExecution) (*v3.PipelineExecution, error) {
if obj == nil || obj.DeletionTimestamp != nil {
return obj, nil
}
//doIfAbort
if obj.Status.ExecutionState == utils.StateAborted {
if err := l.doStop(obj); err != nil {
return obj, err
}
}
//doIfFinish
if obj.Labels != nil && obj.Labels[utils.PipelineFinishLabel] == "true" {
if err := l.doCleanup(obj); err != nil {
return obj, err
}
//start a queueing execution if there is any
if err := l.startQueueingExecution(obj); err != nil {
return obj, err
}
return obj, nil
}
//doIfRunning
if v3.PipelineExecutionConditionInitialized.GetStatus(obj) != "" {
return obj, nil
}
//doIfExceedQuota
exceed, err := l.exceedQuota(obj)
if err != nil {
return obj, err
}
if exceed {
obj.Status.ExecutionState = utils.StateQueueing
obj.Labels[utils.PipelineFinishLabel] = ""
if err := l.newExecutionUpdateLastRunState(obj); err != nil {
return obj, err
}
return obj, nil
}
//doIfOnCreation
if err := l.newExecutionUpdateLastRunState(obj); err != nil {
return obj, err
}
v3.PipelineExecutionConditionInitialized.CreateUnknownIfNotExists(obj)
obj.Labels[utils.PipelineFinishLabel] = "false"
if err := l.deploy(obj); err != nil {
obj.Labels[utils.PipelineFinishLabel] = "true"
obj.Status.ExecutionState = utils.StateFailed
v3.PipelineExecutionConditionInitialized.False(obj)
v3.PipelineExecutionConditionInitialized.ReasonAndMessageFromError(obj, err)
}
if err := l.markLocalRegistryPort(obj); err != nil {
return obj, err
}
return obj, nil
}
func (l *Lifecycle) markLocalRegistryPort(obj *v3.PipelineExecution) error {
cm, err := l.configMaps.GetNamespaced(utils.PipelineNamespace, utils.ProxyConfigMapName, metav1.GetOptions{})
if err != nil {
return err
}
portMap, err := utils.GetRegistryPortMapping(cm)
if err != nil {
return err
}
curPort := ""
if obj.Annotations != nil && obj.Annotations[utils.LocalRegistryPortLabel] != "" {
curPort = obj.Annotations[utils.LocalRegistryPortLabel]
}
_, projectID := ref.Parse(obj.Spec.ProjectName)
port := portMap[projectID]
if port != curPort {
toUpdate := obj.DeepCopy()
if toUpdate.Annotations == nil {
toUpdate.Annotations = map[string]string{}
}
toUpdate.Annotations[utils.LocalRegistryPortLabel] = port
if _, err := l.pipelineExecutions.Update(toUpdate); err != nil {
return err
}
}
return nil
}
func (l *Lifecycle) newExecutionUpdateLastRunState(obj *v3.PipelineExecution) error {
ns, name := ref.Parse(obj.Spec.PipelineName)
pipeline, err := l.pipelineLister.Get(ns, name)
if err != nil {
return err
}
if obj.Spec.Run == pipeline.Status.NextRun {
pipeline.Status.NextRun++
pipeline.Status.LastExecutionID = ref.Ref(obj)
pipeline.Status.LastStarted = obj.Status.Started
}
if pipeline.Status.LastExecutionID == ref.Ref(obj) {
pipeline.Status.LastRunState = obj.Status.ExecutionState
}
_, err = l.pipelines.Update(pipeline)
return err
}
func (l *Lifecycle) startQueueingExecution(obj *v3.PipelineExecution) error {
_, projectID := ref.Parse(obj.Spec.ProjectName)
set := labels.Set(map[string]string{utils.PipelineFinishLabel: ""})
queueingExecutions, err := l.pipelineExecutionLister.List(projectID, set.AsSelector())
if err != nil {
return err
}
if len(queueingExecutions) == 0 {
return nil
}
oldestTime := queueingExecutions[0].CreationTimestamp
toRunExecution := queueingExecutions[0]
for _, e := range queueingExecutions {
if e.CreationTimestamp.Before(&oldestTime) {
oldestTime = e.CreationTimestamp
toRunExecution = e
}
}
toRunExecution = toRunExecution.DeepCopy()
toRunExecution.Status.ExecutionState = utils.StateWaiting
_, err = l.pipelineExecutions.Update(toRunExecution)
return err
}
func (l *Lifecycle) exceedQuota(obj *v3.PipelineExecution) (bool, error) {
_, projectID := ref.Parse(obj.Spec.ProjectName)
quotaSetting, err := l.pipelineSettingLister.Get(projectID, utils.SettingExecutorQuota)
if apierrors.IsNotFound(err) {
return false, nil
} else if err != nil {
return false, err
}
quotaStr := quotaSetting.Default
if quotaSetting.Value != "" {
quotaStr = quotaSetting.Value
}
quota, err := strconv.Atoi(quotaStr)
if err != nil || quota <= 0 {
return false, nil
}
set := labels.Set(map[string]string{utils.PipelineFinishLabel: "false"})
runningExecutions, err := l.pipelineExecutionLister.List(projectID, set.AsSelector())
if err != nil {
return false, err
}
if len(runningExecutions) >= quota {
return true, nil
}
return false, nil
}
func (l *Lifecycle) doStop(obj *v3.PipelineExecution) error {
if v3.PipelineExecutionConditionInitialized.IsTrue(obj) {
if err := l.pipelineEngine.StopExecution(obj); err != nil {
return err
}
if _, err := l.pipelineEngine.SyncExecution(obj); err != nil {
return err
}
}
v3.PipelineExecutionConditionBuilt.Message(obj, "aborted by user")
for i := range obj.Status.Stages {
if obj.Status.Stages[i].State == utils.StateBuilding {
obj.Status.Stages[i].State = utils.StateAborted
}
for j := range obj.Status.Stages[i].Steps {
if obj.Status.Stages[i].Steps[j].State == utils.StateBuilding {
obj.Status.Stages[i].Steps[j].State = utils.StateAborted
}
}
}
//check and update lastrunstate of the pipeline when necessary
ns, name := ref.Parse(obj.Spec.PipelineName)
p, err := l.pipelineLister.Get(ns, name)
if err != nil && !apierrors.IsNotFound(err) {
return err
}
if p != nil && p.Status.LastExecutionID == obj.Namespace+":"+obj.Name &&
p.Status.LastRunState != obj.Status.ExecutionState {
p.Status.LastRunState = obj.Status.ExecutionState
if _, err := l.pipelines.Update(p); err != nil {
return err
}
}
return nil
}
func (l *Lifecycle) doCleanup(obj *v3.PipelineExecution) error {
//Clean up on exception cases
if err := l.pipelineEngine.StopExecution(obj); err != nil {
return err
}
ns := utils.GetPipelineCommonName(obj)
labelSet := labels.Set{
utils.LabelKeyApp: utils.JenkinsName,
utils.LabelKeyExecution: obj.Name,
}
slavePods, err := l.podLister.List(ns, labelSet.AsSelector())
if err != nil {
return err
}
for _, pod := range slavePods {
if err := l.pods.DeleteNamespaced(ns, pod.Name, &metav1.DeleteOptions{}); err != nil && !apierrors.IsNotFound(err) && !apierrors.IsGone(err) {
return err
}
}
return nil
}
func (l *Lifecycle) Remove(obj *v3.PipelineExecution) (*v3.PipelineExecution, error) {
return obj, nil
}
func (l *Lifecycle) GetName() string {
return "pipeline-execution-controller"
}
//reconcileRb grant access to pipeline service account inside project namespaces
func (l *Lifecycle) reconcileRb(obj *v3.PipelineExecution) error {
commonName := utils.GetPipelineCommonName(obj)
_, projectID := ref.Parse(obj.Spec.ProjectName)
namespaces, err := l.namespaceLister.List("", labels.NewSelector())
if err != nil {
return errors.Wrapf(err, "Error list cluster namespaces")
}
var namespacesInProject []*corev1.Namespace
for _, namespace := range namespaces {
parts := strings.Split(namespace.Annotations[projectIDLabel], ":")
if len(parts) == 2 && parts[1] == projectID {
namespacesInProject = append(namespacesInProject, namespace)
} else {
if err := l.roleBindings.DeleteNamespaced(namespace.Name, commonName, &metav1.DeleteOptions{}); err != nil && !apierrors.IsNotFound(err) {
return err
}
}
}
for _, namespace := range namespacesInProject {
rb := getRoleBindings(namespace.Name, commonName)
if _, err := l.roleBindings.Create(rb); err != nil && !apierrors.IsAlreadyExists(err) {
return errors.Wrapf(err, "Error create role binding")
}
}
clusterRbs := []string{roleCreateNs, projectID + roleEditNsSuffix}
for _, crbName := range clusterRbs {
crb := getClusterRoleBindings(commonName, crbName)
if _, err := l.clusterRoleBindings.Create(crb); err != nil && !apierrors.IsAlreadyExists(err) {
return errors.Wrapf(err, "Error create cluster role binding")
}
}
return nil
}