-
Notifications
You must be signed in to change notification settings - Fork 51
/
activities.go
284 lines (253 loc) · 8.47 KB
/
activities.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
package activities
import (
"context"
"sort"
"strings"
"time"
v1 "github.com/jenkins-x/jx-api/v4/pkg/apis/jenkins.io/v1"
jxc "github.com/jenkins-x/jx-api/v4/pkg/client/clientset/versioned"
jv1 "github.com/jenkins-x/jx-api/v4/pkg/client/clientset/versioned/typed/jenkins.io/v1"
"github.com/jenkins-x/jx-helpers/v3/pkg/cobras/helper"
"github.com/jenkins-x/jx-helpers/v3/pkg/cobras/templates"
"github.com/jenkins-x/jx-helpers/v3/pkg/kube/jxclient"
"github.com/jenkins-x/jx-helpers/v3/pkg/termcolor"
"github.com/jenkins-x/jx-kube-client/v3/pkg/kubeclient"
"github.com/jenkins-x/jx-logging/v3/pkg/log"
lhclient "github.com/jenkins-x/lighthouse-client/pkg/client/clientset/versioned"
"github.com/pkg/errors"
"github.com/spf13/cobra"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
)
// Options command line arguments and flags
type Options struct {
DryRun bool
ReleaseHistoryLimit int
PullRequestHistoryLimit int
ReleaseAgeLimit time.Duration
PullRequestAgeLimit time.Duration
PipelineRunAgeLimit time.Duration
ProwJobAgeLimit time.Duration
Namespace string
JXClient jxc.Interface
LHClient lhclient.Interface
}
var (
info = termcolor.ColorInfo
cmdLong = templates.LongDesc(`
Garbage collect the Jenkins X PipelineActivity resources
`)
cmdExample = templates.Examples(`
# garbage collect PipelineActivity resources
jx gitops gc activities
# dry run mode
jx gitops gc pa --dry-run
`)
)
type buildCounter struct {
ReleaseCount int
PRCount int
}
type buildsCount struct {
cache map[string]*buildCounter
}
// AddBuild adds the build and returns the number of builds for this repo and branch
func (c *buildsCount) AddBuild(repoAndBranch string, isPR bool) int {
if c.cache == nil {
c.cache = map[string]*buildCounter{}
}
bc := c.cache[repoAndBranch]
if bc == nil {
bc = &buildCounter{}
c.cache[repoAndBranch] = bc
}
if isPR {
bc.PRCount++
return bc.PRCount
}
bc.ReleaseCount++
return bc.ReleaseCount
}
// NewCmd s a command object for the "step" command
func NewCmdGCActivities() (*cobra.Command, *Options) {
o := &Options{}
cmd := &cobra.Command{
Use: "activities",
Aliases: []string{"pa", "act", "pr"},
Short: "garbage collection for PipelineActivity resources",
Long: cmdLong,
Example: cmdExample,
Run: func(cmd *cobra.Command, args []string) {
err := o.Run()
helper.CheckErr(err)
},
}
cmd.Flags().BoolVarP(&o.DryRun, "dry-run", "d", false, "Dry run mode. If enabled just list the resources that would be removed")
cmd.Flags().IntVarP(&o.ReleaseHistoryLimit, "release-history-limit", "l", 5, "Maximum number of PipelineActivities to keep around per repository release")
cmd.Flags().IntVarP(&o.PullRequestHistoryLimit, "pr-history-limit", "", 2, "Minimum number of PipelineActivities to keep around per repository Pull Request")
cmd.Flags().DurationVarP(&o.PullRequestAgeLimit, "pull-request-age", "p", time.Hour*48, "Maximum age to keep PipelineActivities for Pull Requests")
cmd.Flags().DurationVarP(&o.ReleaseAgeLimit, "release-age", "r", time.Hour*24*30, "Maximum age to keep PipelineActivities for Releases")
cmd.Flags().DurationVarP(&o.PipelineRunAgeLimit, "pipelinerun-age", "", time.Hour*12, "Maximum age to keep completed PipelineRuns for all pipelines")
cmd.Flags().DurationVarP(&o.ProwJobAgeLimit, "prowjob-age", "", time.Hour*24*7, "Maximum age to keep completed ProwJobs for all pipelines")
return cmd, o
}
// Run implements this command
func (o *Options) Run() error {
var err error
o.JXClient, o.Namespace, err = jxclient.LazyCreateJXClientAndNamespace(o.JXClient, o.Namespace)
if err != nil {
return errors.Wrapf(err, "failed to create jx client")
}
o.LHClient, err = LazyCreateLHClient(o.LHClient)
if err != nil {
return errors.Wrapf(err, "failed to create the lighthouse client")
}
client := o.JXClient
currentNs := o.Namespace
ctx := context.TODO()
// cannot use field selectors like `spec.kind=Preview` on CRDs so list all environments
activityInterface := client.JenkinsV1().PipelineActivities(currentNs)
activities, err := activityInterface.List(ctx, metav1.ListOptions{})
if err != nil {
return err
}
if len(activities.Items) == 0 {
// no preview environments found so lets return gracefully
log.Logger().Debug("no activities found")
return nil
}
now := time.Now()
counters := &buildsCount{}
var completedActivities []v1.PipelineActivity
// Filter out running activities
for _, a := range activities.Items {
if a.Spec.CompletedTimestamp != nil {
completedActivities = append(completedActivities, a)
}
}
// Sort with newest created activities first
sort.Slice(completedActivities, func(i, j int) bool {
return !completedActivities[i].Spec.CompletedTimestamp.Before(completedActivities[j].Spec.CompletedTimestamp)
})
//
for _, a := range completedActivities {
activity := a
branchName := a.BranchName()
isPR, isBatch := o.isPullRequestOrBatchBranch(branchName)
maxAge, revisionHistory := o.ageAndHistoryLimits(isPR, isBatch)
// lets remove activities that are too old
if activity.Spec.CompletedTimestamp != nil && activity.Spec.CompletedTimestamp.Add(maxAge).Before(now) {
err = o.deleteLighthouseJob(ctx, &activity)
if err != nil {
return err
}
err = o.deleteActivity(ctx, activityInterface, &activity)
if err != nil {
return err
}
continue
}
repoBranchAndContext := activity.RepositoryOwner() + "/" + activity.RepositoryName() + "/" + activity.BranchName() + "/" + activity.Spec.Context
c := counters.AddBuild(repoBranchAndContext, isPR)
if c > revisionHistory && a.Spec.CompletedTimestamp != nil {
err = o.deleteActivity(ctx, activityInterface, &activity)
if err != nil {
return err
}
continue
}
}
// Clean up completed PipelineRuns
/*
err = o.gcPipelineRuns(currentNs)
if err != nil {
return err
}
*/
return nil
}
func (o *Options) deleteActivity(ctx context.Context, activityInterface jv1.PipelineActivityInterface, a *v1.PipelineActivity) error {
prefix := ""
if o.DryRun {
prefix = "not "
}
log.Logger().Infof("%sdeleting PipelineActivity %s", prefix, info(a.Name))
if o.DryRun {
return nil
}
return activityInterface.Delete(ctx, a.Name, *metav1.NewDeleteOptions(0))
}
func (o *Options) ageAndHistoryLimits(isPR, isBatch bool) (time.Duration, int) {
maxAge := o.ReleaseAgeLimit
revisionLimit := o.ReleaseHistoryLimit
if isPR || isBatch {
maxAge = o.PullRequestAgeLimit
revisionLimit = o.PullRequestHistoryLimit
}
return maxAge, revisionLimit
}
func (o *Options) isPullRequestOrBatchBranch(branchName string) (bool, bool) {
return strings.HasPrefix(branchName, "PR-"), branchName == "batch"
}
func (o *Options) deleteLighthouseJob(ctx context.Context, pa *v1.PipelineActivity) error {
if pa.Labels == nil {
return nil
}
labelMap := map[string]string{}
for k, v := range pa.Labels {
if k != "lighthouse.jenkins-x.io/id" && strings.HasPrefix(k, "lighthouse.jenkins-x.io/") {
labelMap[k] = v
}
}
if len(labelMap) < 4 {
log.Logger().Infof("ignoring PipelineActivity %s which only has lighthouse labels %v", pa.Name, labelMap)
return nil
}
selector := labels.SelectorFromSet(labelMap).String()
lighthouseJobInterface := o.LHClient.LighthouseV1alpha1().LighthouseJobs(o.Namespace)
list, err := lighthouseJobInterface.List(ctx, metav1.ListOptions{
LabelSelector: selector,
})
if err != nil {
if apierrors.IsNotFound(err) {
return nil
}
return errors.Wrapf(err, "failed to list LighthouseJob resources with selector %s", selector)
}
if list == nil {
return nil
}
for i := range list.Items {
r := &list.Items[i]
prefix := ""
if o.DryRun {
prefix = "not "
}
log.Logger().Infof("%sdeleting LighthouseJob %s", prefix, info(r.Name))
if o.DryRun {
continue
}
err = lighthouseJobInterface.Delete(ctx, r.Name, metav1.DeleteOptions{})
if err != nil {
return errors.Wrapf(err, "failed to delete LighthouseJob %s", r.Name)
}
}
return nil
}
// LazyCreateLHClient lazy creates the jx client if its not defined
func LazyCreateLHClient(client lhclient.Interface) (lhclient.Interface, error) {
if client != nil {
return client, nil
}
f := kubeclient.NewFactory()
cfg, err := f.CreateKubeConfig()
if err != nil {
return client, errors.Wrap(err, "failed to get kubernetes config")
}
client, err = lhclient.NewForConfig(cfg)
if err != nil {
return client, errors.Wrap(err, "error building lighthouse clientset")
}
return client, nil
}