This repository was archived by the owner on Jul 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.go
318 lines (299 loc) · 8.25 KB
/
main.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
package main
import (
"github.com/TimeBye/go-harbor"
"fmt"
"github.com/golang/glog"
"time"
"github.com/ghodss/yaml"
"io/ioutil"
"regexp"
"strings"
"flag"
"os"
"sort"
)
const (
PROJECTS_PAGE_SIZE = 50
REPOSITORIES_PAGE_SIZE = 100
)
var (
HClient *harbor.Client
deletePolicy DeletePolicy
policyFilePath string
)
type DeletePolicy struct {
RegistryUrl string `json:"registry_url"`
UserName string `json:"username"`
Password string `json:"password"`
DryRun bool `json:"dry_run"`
IntervalHour time.Duration `json:"interval_hour"`
IgnoreProjects string `json:"ignore_projects"`
MixCount int `json:"mix_count"`
IgnoreProjectsRegex string
Projects struct {
DeleteEmpty bool `json:"delete_empty"`
Include struct {
Keys string
Regex string
KeysRegex string
}
Exclude struct {
Keys string
Regex string
KeysRegex string
}
}
Tags struct {
Include struct {
Keys string
Regex string
KeysRegex string
}
Exclude struct {
Keys string
Regex string
KeysRegex string
}
}
}
type TagSlice []harbor.TagResp
func (tagSlice TagSlice) Len() int {
return len(tagSlice)
}
func (tagSlice TagSlice) Swap(i, j int) {
tagSlice[i], tagSlice[j] = tagSlice[j], tagSlice[i]
}
func (tagSlice TagSlice) Less(i, j int) bool {
return tagSlice[j].Created.Before(tagSlice[i].Created)
}
func checkErrs(errs []error, info string) {
if errs != nil {
glog.Exit(func() string {
for _, v := range errs {
info = fmt.Sprintf("%v\n%v", info, v)
}
return info
}())
}
}
func checkErr(err error) {
if err != nil {
glog.Exit(err)
}
}
func getProjects(page int) []harbor.Project {
projects, resp, errs := HClient.Projects.ListProject(
&harbor.ListProjectsOptions{
ListOptions: harbor.ListOptions{
Page: page,
PageSize: PROJECTS_PAGE_SIZE,
},
})
checkErrs(errs, (*resp).Status)
glog.V(3).Info(func() string {
s := ""
for _, v := range projects {
s = fmt.Sprintf("%v\n%v", v, s)
}
return s
}())
return projects
}
func getRepositories(projectID int64) []harbor.RepoRecord {
repositories, resp, errs := HClient.Repositories.ListRepository(
&harbor.ListRepositoriesOption{
ListOptions: harbor.ListOptions{
Page: 1,
PageSize: REPOSITORIES_PAGE_SIZE,
},
ProjectId: projectID,
})
checkErrs(errs, (*resp).Status)
glog.V(3).Info(func() string {
s := ""
for _, v := range repositories {
s = fmt.Sprintf("%v\n%v", v, s)
}
return s
}())
return repositories
}
func getRepositoryTags(repoName string) []harbor.TagResp {
tagResp, resp, errs := HClient.Repositories.ListRepositoryTags(repoName)
checkErrs(errs, (*resp).Status)
glog.V(3).Info(func() string {
s := ""
for _, v := range tagResp {
s = fmt.Sprintf("%v\n%v", v, s)
}
return s
}())
return tagResp
}
func generateRegexByKeys(keys string) string {
if strings.HasPrefix(keys, ",") {
keys = keys[1:]
}
if strings.HasSuffix(keys, ",") {
keys = keys[:len(keys)-1]
}
if len(keys) == 0 || len(strings.Replace(keys, ",", "", -1)) == 0 {
return ":"
}
return fmt.Sprintf(".*%s.*", strings.Replace(keys, ",", ".*|.*", -1))
}
func needDeleteTag(tag harbor.TagResp, count *int) bool {
baseTime, _ := time.ParseDuration("1h")
if time.Now().Sub(tag.Created) < deletePolicy.IntervalHour*baseTime || *count < deletePolicy.MixCount {
*count += 1
return false
}
match, err := regexp.MatchString(deletePolicy.Tags.Exclude.Regex, tag.Name)
checkErr(err)
if match {
return false
}
match, err = regexp.MatchString(deletePolicy.Tags.Exclude.KeysRegex, tag.Name)
checkErr(err)
if match {
return false
}
match, err = regexp.MatchString(deletePolicy.Tags.Include.Regex, tag.Name)
checkErr(err)
if match {
glog.V(2).Infof("%s match Tags.Regex: %s", tag.Name, deletePolicy.Tags.Include.Regex)
return true
}
match, err = regexp.MatchString(deletePolicy.Tags.Include.KeysRegex, tag.Name)
checkErr(err)
if match {
glog.V(2).Infof("%s match Tags.KeysRegex: %s", tag.Name, deletePolicy.Tags.Include.KeysRegex)
return true
}
return false
}
func needDeleteProject(project harbor.Project) bool {
match, err := regexp.MatchString(deletePolicy.Projects.Exclude.Regex, project.Name)
checkErr(err)
if match {
return false
}
match, err = regexp.MatchString(deletePolicy.Projects.Exclude.KeysRegex, project.Name)
checkErr(err)
if match {
return false
}
match, err = regexp.MatchString(deletePolicy.Projects.Include.Regex, project.Name)
checkErr(err)
if match {
glog.V(2).Infof("%s match Projects.Regex: %s", project.Name, deletePolicy.Projects.Include.Regex)
return true
}
match, err = regexp.MatchString(deletePolicy.Projects.Include.KeysRegex, project.Name)
checkErr(err)
if match {
glog.V(2).Infof("%s match Projects.KeysRegex: %s", project.Name, deletePolicy.Projects.Include.KeysRegex)
return true
}
if project.RepoCount == 0 && deletePolicy.Projects.DeleteEmpty {
glog.V(2).Infof("Empty Project %s", project.Name)
return true
}
return false
}
func doDelete(statisticMap harbor.StatisticMap) {
pageCount := statisticMap.TotalProjectCount/PROJECTS_PAGE_SIZE + 1
for i := pageCount; i != 0; i-- {
projects := getProjects(i)
for _, project := range projects {
match, err := regexp.MatchString(deletePolicy.IgnoreProjectsRegex, project.Name)
checkErr(err)
if match {
continue
}
repositories := getRepositories(project.ProjectID)
for _, repository := range repositories {
tags := getRepositoryTags(repository.Name)
sort.Sort(TagSlice(tags))
var count = 0
for _, tag := range tags {
if needDeleteTag(tag, &count) {
glog.Infof("Untagged: %s:%s", repository.Name, tag.Name)
if !deletePolicy.DryRun {
resp, errs := HClient.Repositories.DeleteRepositoryTag(repository.Name, tag.Name)
if errs != nil {
glog.Error((*resp).Status)
}
}
}
}
}
if needDeleteProject(project) {
glog.Infof("Delete Project: %s", project.Name)
if !deletePolicy.DryRun {
resp, errs := HClient.Projects.DeleteProject(project.ProjectID)
if errs != nil {
glog.Error((*resp).Status)
}
}
}
}
}
}
func readDeletePolicy() {
data, err := ioutil.ReadFile(policyFilePath)
checkErr(err)
deletePolicy.DryRun = true
deletePolicy.IntervalHour = 72
deletePolicy.MixCount = 10
err = yaml.Unmarshal(data, &deletePolicy)
checkErr(err)
deletePolicy.Projects.Include.KeysRegex = generateRegexByKeys(deletePolicy.Projects.Include.Keys)
deletePolicy.Projects.Exclude.KeysRegex = generateRegexByKeys(deletePolicy.Projects.Exclude.Keys)
deletePolicy.Tags.Include.KeysRegex = generateRegexByKeys(deletePolicy.Tags.Include.Keys)
deletePolicy.Tags.Exclude.KeysRegex = generateRegexByKeys(deletePolicy.Tags.Exclude.Keys)
deletePolicy.IgnoreProjectsRegex = strings.Replace(deletePolicy.IgnoreProjects, ",", "|", -1)
if len(deletePolicy.IgnoreProjectsRegex) == 0 {
deletePolicy.IgnoreProjectsRegex = ":"
}
if len(deletePolicy.Projects.Include.Regex) == 0 {
deletePolicy.Projects.Include.Regex = ":"
}
if len(deletePolicy.Projects.Include.KeysRegex) == 0 {
deletePolicy.Projects.Include.KeysRegex = ":"
}
if len(deletePolicy.Projects.Exclude.Regex) == 0 {
deletePolicy.Projects.Exclude.Regex = ":"
}
if len(deletePolicy.Projects.Exclude.KeysRegex) == 0 {
deletePolicy.Projects.Exclude.KeysRegex = ":"
}
if len(deletePolicy.Tags.Include.Regex) == 0 {
deletePolicy.Tags.Include.Regex = ":"
}
if len(deletePolicy.Tags.Include.KeysRegex) == 0 {
deletePolicy.Tags.Include.KeysRegex = ":"
}
if len(deletePolicy.Tags.Exclude.Regex) == 0 {
deletePolicy.Tags.Exclude.Regex = ":"
}
if len(deletePolicy.Tags.Exclude.KeysRegex) == 0 {
deletePolicy.Tags.Exclude.KeysRegex = ":"
}
}
func init() {
flag.Set("logtostderr", "true")
if len(os.Getenv("LOG_LEVEL")) != 0 {
logLevel := os.Getenv("LOG_LEVEL")
flag.Set("v", logLevel)
}
flag.StringVar(&policyFilePath, "f", "delete_policy.yml", "Filename, directory, or URL to files that delete policy.")
flag.Parse()
}
func main() {
readDeletePolicy()
HClient = harbor.NewClient(nil, deletePolicy.RegistryUrl, deletePolicy.UserName, deletePolicy.Password)
statisticMap, resp, errs := HClient.GetStatistics()
checkErrs(errs, (*resp).Status)
doDelete(statisticMap)
}