This repository has been archived by the owner on Nov 16, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
314 lines (284 loc) · 8.83 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
// Copyright © 2019 tnextday <fw2k4@163.com>
//
// 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 main
import (
"crypto/tls"
"errors"
"fmt"
"net/http"
"os"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"time"
"github.com/xanzy/go-gitlab"
"github.com/spf13/pflag"
)
var (
gitlabToken string
gitlabBaseUrl string
projectId string
registriesRegex []string
tagsRegex []string
excludesRegex []string
keepsN int
olderThen string
insecure bool
dryRun bool
verbose bool
printVersion bool
help bool
durationRegex = regexp.MustCompile(`(\d+)\s*([a-z]+)`)
httpClient *http.Client
AppVersion = "dev"
BuildTime = ""
)
func parserDuration(s string) (time.Duration, error) {
if s == "" {
return 0, nil
}
ss := durationRegex.FindStringSubmatch(strings.ToLower(s))
if len(ss) == 0 {
return 0, errors.New("can't parser the duration string")
}
i, _ := strconv.Atoi(ss[1])
switch ss[2][:1] {
case "h":
return time.Hour * time.Duration(i), nil
case "d":
return time.Hour * 24 * time.Duration(i), nil
case "m":
return time.Hour * 24 * 30 * time.Duration(i), nil
default:
return 0, fmt.Errorf("unsupport duration unit: %s", ss[2])
}
}
func verboseLogf(format string, v ...interface{}) {
if !verbose {
return
}
fmt.Printf(format, v...)
}
func matchRegexList(s string, list []*regexp.Regexp) bool {
for _, r := range list {
if r.MatchString(s) {
return true
}
}
return false
}
func usage() {
fmt.Printf(`Usage of gitlab-registry-cleaner
Options:
`)
pflag.PrintDefaults()
os.Exit(0)
}
func main() {
pflag.ErrHelp = nil
pflag.Usage = usage
pflag.StringVarP(&gitlabToken, "token", "T", "", "Gitlab private token, environment: GITLAB_TOKEN")
pflag.StringVar(&gitlabBaseUrl, "base-url", "https://gitlab.com/", "Gitlab base url, environment: GITLAB_BASE_URL")
pflag.StringVarP(&projectId, "project", "p", "", "[REQUIRED]The ID or path of the project, environment: GITLAB_PROJECT_ID")
pflag.StringArrayVarP(®istriesRegex, "registry", "r", []string{}, "Registry repository path regex list, clean all repositories in project if registry not set")
pflag.StringArrayVarP(&tagsRegex, "tag", "t", []string{}, "Image tag regex list")
pflag.StringArrayVarP(&excludesRegex, "exclude", "e", []string{}, "Exclude image tag regex list")
pflag.IntVarP(&keepsN, "keep-n", "n", 10, "Keeps N latest matching tagsRegex for each registry repositories")
pflag.StringVarP(&olderThen, "older-then", "o", "", "Tags to delete that are older than the given time, written in human readable form 1h, 1d, 1m")
pflag.BoolVarP(&dryRun, "dry-run", "d", false, "Only print which images would be deleted")
pflag.BoolVarP(&insecure, "insecure", "k", false, "Allow connections to SSL sites without certs")
pflag.BoolVarP(&verbose, "verbose", "v", false, "Verbose output")
pflag.BoolVarP(&printVersion, "version", "V", false, "Print version and exit")
pflag.BoolVarP(&help, "help", "h", false, "Print help and exit")
pflag.CommandLine.SortFlags = false
pflag.Parse()
if printVersion {
fmt.Println("App Version:", AppVersion)
fmt.Println("Go Version:", runtime.Version())
fmt.Println("Build Time:", BuildTime)
os.Exit(0)
}
if help {
usage()
}
if gitlabToken == "" {
if env := os.Getenv("GITLAB_TOKEN"); env != "" {
gitlabToken = env
}
}
if gitlabBaseUrl == "https://gitlab.com/" {
if env := os.Getenv("GITLAB_BASE_URL"); env != "" {
gitlabBaseUrl = env
}
}
if projectId == "" {
if env := os.Getenv("GITLAB_PROJECT"); env != "" {
projectId = env
} else {
fmt.Println("The project ID is required!")
fmt.Printf("try '%s -h' for more information\n", os.Args[0])
os.Exit(1)
}
}
olderThenDuration, err := parserDuration(olderThen)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
verboseLogf("Gitlab base url: %v\n", gitlabBaseUrl)
if gitlabToken != "" {
verboseLogf("Gitlab private token: **HIDDEN**\n")
}
verboseLogf("Gitlab project ID: %v\n", projectId)
if olderThen != "" {
verboseLogf("Older then duration: %v\n", olderThenDuration)
}
var (
registryRegs []*regexp.Regexp
tagRegs []*regexp.Regexp
excludeRegs []*regexp.Regexp
)
for _, rs := range registriesRegex {
if regx, err := regexp.Compile(rs); err == nil {
registryRegs = append(registryRegs, regx)
} else {
fmt.Printf("Compile regex %s error: %v\n", rs, err)
os.Exit(1)
}
}
for _, rs := range tagsRegex {
if regx, err := regexp.Compile(rs); err == nil {
tagRegs = append(tagRegs, regx)
} else {
fmt.Printf("Compile regex %s error: %v\n", rs, err)
os.Exit(1)
}
}
for _, rs := range excludesRegex {
if regx, err := regexp.Compile(rs); err == nil {
excludeRegs = append(excludeRegs, regx)
} else {
fmt.Printf("Compile regex %s error: %v\n", rs, err)
os.Exit(1)
}
}
if insecure {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
httpClient = &http.Client{Transport: tr}
}
gl := gitlab.NewClient(httpClient, gitlabToken)
if err := gl.SetBaseURL(gitlabBaseUrl); err != nil {
fmt.Printf("Set gitlab base url error: %v\n", err)
os.Exit(1)
}
repos, _, err := gl.ContainerRegistry.ListRegistryRepositories(projectId, nil)
if err != nil {
fmt.Printf("List registry repositories error: %v\n", err)
os.Exit(1)
}
var matchedRepos []*gitlab.RegistryRepository
for _, repo := range repos {
if len(registryRegs) > 0 && !matchRegexList(repo.Path, registryRegs) {
verboseLogf("Skipped registry repository: %v\n", repo.Path)
} else {
verboseLogf("Matched registry repository: %v\n", repo.Path)
matchedRepos = append(matchedRepos, repo)
}
}
if len(matchedRepos) == 0 {
fmt.Println("There is no registry repository found.")
os.Exit(1)
}
for _, repo := range matchedRepos {
fmt.Printf("Searching in %v\n", repo.Path)
opt := &gitlab.ListRegistryRepositoryTagsOptions{PerPage: 10000}
tags, _, err := gl.ContainerRegistry.ListRegistryRepositoryTags(projectId, repo.ID, opt)
if err != nil {
fmt.Printf("List registry repository tags failed, path: %s, error: %v\n", repo.Path, err)
continue
}
var matchedTags []*gitlab.RegistryRepositoryTag
for _, tag := range tags {
if tag.Name == "latest" {
verboseLogf("Skipped the latest tag\n")
continue
}
if len(excludeRegs) > 0 && matchRegexList(tag.Name, excludeRegs) {
verboseLogf("Skipped tag because of exclude rule: %v\n", tag.Name)
continue
}
if len(tagRegs) > 0 && !matchRegexList(tag.Name, tagRegs) {
verboseLogf("Skipped tag: %v\n", tag.Name)
} else {
verboseLogf("Matched tag: %v\n", tag.Name)
matchedTags = append(matchedTags, tag)
}
}
if keepsN > 0 && len(matchedTags) <= keepsN {
fmt.Printf("Skip because of less mathced tags(%v) then keeps N(%v)\n", len(matchedTags), keepsN)
continue
}
for _, tag := range matchedTags {
t, _, err := gl.ContainerRegistry.GetRegistryRepositoryTagDetail(projectId, repo.ID, tag.Name)
if err != nil {
fmt.Printf("Get registry repository tag detail failed, path: %s, error: %v\n", tag.Path, err)
continue
}
tag.CreatedAt = t.CreatedAt
}
sort.Slice(matchedTags, func(i, j int) bool {
return matchedTags[i].CreatedAt.After(*matchedTags[j].CreatedAt)
})
verboseLogf("Found %v matched tags in %v\n", len(matchedTags), repo.Path)
if keepsN > 0 {
verboseLogf("The latest %v matched tags will be keeps\n", keepsN)
matchedTags = matchedTags[keepsN:]
}
var tagsToDelete []*gitlab.RegistryRepositoryTag
if olderThenDuration > 0 {
now := time.Now()
for _, t := range matchedTags {
createDuration := now.Sub(*t.CreatedAt)
if createDuration > olderThenDuration {
tagsToDelete = append(tagsToDelete, t)
} else {
verboseLogf("Tag %v will be keep because of it's create only %v\n", t.Name, createDuration)
}
}
} else {
tagsToDelete = matchedTags
}
verboseLogf("%v tags in %v will be delete\n", len(tagsToDelete), repo.Path)
deletedCount := 0
for _, t := range tagsToDelete {
if dryRun {
fmt.Printf("[Dry run]%s will be delete\n", t.Path)
continue
}
fmt.Printf("Delete %s ", t.Path)
_, err := gl.ContainerRegistry.DeleteRegistryRepositoryTag(projectId, repo.ID, t.Name)
if err == nil {
deletedCount++
fmt.Println("OK")
} else {
fmt.Println("error:", err)
}
}
fmt.Printf("%v/%v tags have been deleted in %v\n", deletedCount, len(tagsToDelete), repo.Path)
}
}