0%

Harbor 镜像定期删除

Harbor:过期镜像定期删除

背景

定期删除过期镜像,释放磁盘空间。

操作

Python脚本

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
'''
# @ Author: zhaohongye
# @ Mail: vip@zhaohongye.com
# @ Create Time: 2022-08-19 16:16:15
# @ Modified by: zhaohongye
# @ Modified time: 2022-11-16 14:11:38
# @ Description: Better tomorrow
'''


import requests


class HarborApi(object):

def __init__(self):
url = "https://harbor.zhaohongye.com"
version = "v2.0"
username = "admin"
password = ""

self.base_url = "{}/api/{}".format(url, version)
self.auth_info = (username, password)

def get_projects(self, page=1, page_size=10):
"""
获取projects
"""
# api_url = "{}/projects".format(self.base_url,)
api_url = f"{self.base_url}/projects"
payload = {
'page': page,
'page_size': page_size
}
r = requests.get(api_url, params=payload, auth=self.auth_info)
if r.status_code == 200:
data = {
'list': r.json(),
'total': int(r.headers.get('X-Total-Count'))
}
return data
else:
return False

def get_all_repositories_name(self, project_name):
"""
获取所有镜像库名称
"""
page_size = 100
r_data = self.get_repositories(
project_name=project_name, page_size=page_size)
r_total = r_data.get('total')
if r_total <= page_size:
r_name_list = [i.get('name').split(
f'{project_name}/')[1] for i in r_data.get('list')]
else:
r_page_count = int(r_total // page_size) + 1
r_list = list()

if r_page_count > 0:
for page_num in range(1, r_page_count+1):
tmp_r_data = self.get_repositories(
project_name=project_name, page=page_num, page_size=page_size)
r_list += tmp_r_data.get('list')
r_name_list = [i.get('name').split(
f'{project_name}/')[1] for i in r_list]
return r_name_list

# repositories
def get_repositories(self, project_name, page=1, page_size=10):
"""
获取repositories
"""
api_url = f"{self.base_url}/projects/{project_name}/repositories"
payload = {
'page': page,
'page_size': page_size
}
r = requests.get(api_url, params=payload, auth=self.auth_info)
if r.status_code == 200:
data = {
'list': r.json(),
'total': int(r.headers.get('X-Total-Count'))
}
return data
else:
return False

# artifacts
def get_artifacts(self, project_name, repository_name, page=1, page_size=10):
"""
获取artifacts
"""
# api_url = self.base_url + 'projects/' + \
# project_name + '/repositories/' + repository_name + '/artifacts'
api_url = f"{self.base_url}/projects/{project_name}/repositories/{repository_name}/artifacts"
payload = {
'page': page,
'page_size': page_size
}
r = requests.get(api_url, params=payload, auth=self.auth_info)
if r.status_code == 200:
data = {
'list': r.json(),
'total': int(r.headers.get('X-Total-Count'))
}
return data
else:
return False

def get_artifacts_info(self, project_name, repository_name, page_size=100):
"""
返回字典
{
2202: {
'digest': 'sha256:42c81fef9bab44db198fb4123dc41a8511f491c0c5977803ad226184d0a8c93a',
'tags': ['dev-20220902151655']
},
2200: {
'digest': 'sha256:b8b98515dc61054fa19b74b7bb31f8414382585cdfff12c370c53d22b48a3021',
'tags': ['dev-20220902150345']
}
}
"""
a_data = self.get_artifacts(
project_name=project_name, repository_name=repository_name, page_size=page_size)
a_total = a_data.get('total')
if a_total <= page_size:
tmp_a_list = a_data.get('list')
else:
a_page_count = int(a_total // page_size) + 1
tmp_a_list = list()
if a_page_count > 0:
for page_num in range(1, a_page_count+1):
tmp_a_data = self.get_artifacts(
project_name=project_name, repository_name=repository_name, page=page_num, page_size=page_size)
tmp_a_list += tmp_a_data.get('list')
a_dict = dict()
tags_list = list()
for artifact in tmp_a_list:
if artifact['tags'] and len(artifact['tags']) >= 0:
tags = [g['name'] for g in artifact.get('tags')]
a_dict[artifact.get('id')] = {
'digest': artifact.get('digest'),
'tags': tags
}
tags_list += tags
a_dict['tags'] = tags_list
return a_dict

def generate_delete_list(self, project_name, repository_name):
"""
生成删除列表
"""
save_max_num = 5

a_data = self.get_artifacts_info(
project_name=project_name, repository_name=repository_name)
tags_list = a_data.get('tags')

dev_tags_list = list()
test_tags_list = list()
pre_tags_list = list()
del_tags_list = list()

for tag in tags_list:
if 'dev' in tag:
dev_tags_list.append(tag)
if 'test' in tag:
test_tags_list.append(tag)
if 'pre' in tag:
pre_tags_list.append(tag)

if dev_tags_list and len(dev_tags_list) > save_max_num:
dev_tags_list = sorted(dev_tags_list)
del_tags_list += dev_tags_list[:-5]
if test_tags_list and len(test_tags_list) > save_max_num:
test_tags_list = sorted(test_tags_list)
del_tags_list += test_tags_list[:-5]
if pre_tags_list and len(pre_tags_list) > save_max_num:
pre_tags_list = sorted(pre_tags_list)
del_tags_list += pre_tags_list[:-5]
del_digest_list = list()
for k, v in a_data.items():
if type(v) is dict:
if v.get('tags')[0] in del_tags_list:
del_digest_list.append(v.get('digest'))
return del_digest_list

# del artifacts
def del_artifact(self, project_name, repository_name, digest):
"""
删除镜像artifact
curl -u admin:fPrVLaUGd6TZ3HSt -X DELETE "https://harbor.izuche.com/api/v2.0/projects/izu/repositories/izu-mrcar-workflow/artifacts/sha256:26249cff21efc04d7b696c4c86bbae88d4e042407471ff8951aa292d583c34ff"
"""
api_url = f"{self.base_url}/projects/{project_name}/repositories/{repository_name}/artifacts/{digest}"
r = requests.delete(api_url, auth=self.auth_info)
if r.status_code == 200:
return True
else:
return False

def clean_artifact(self, project_name, repository_name):
"""
自动清理空间
1.获取所有仓库名称 get_all_repositories_name
2.获取仓库内制品 get_artifacts_info
3.根据制品tags来判断哪些需要删除
判断删除的依据:
只删除应用镜像,基础镜像不动。
如果tag包含dev、test、pre的,只保留最近的5个
如果不包含关键词的,也只保留最近的5个。
4.删除制品
"""
if project_name != 'izu':
return False
del_digest_list = self.generate_delete_list(
project_name=project_name, repository_name=repository_name)
real_del_num = 0
for digest in del_digest_list:
result = self.del_artifact(
project_name=project_name, repository_name=repository_name, digest=digest)
if result:
real_del_num += 1
return f"项目:{project_name},仓库:{repository_name},应删除{len(del_digest_list)},已删除{real_del_num}"


if __name__ == '__main__':
hb = HarborApi()
project_name = 'izu'
r_name_list = hb.get_all_repositories_name(project_name=project_name)
for r_name in r_name_list:
print(hb.clean_artifact(project_name=project_name, repository_name=r_name))

垃圾清理

由于删除镜像后磁盘空间未释放,需在Harbor控制台上手动执行垃圾清理