-
Notifications
You must be signed in to change notification settings - Fork 15
/
clean_ghcr.py
263 lines (230 loc) · 7.71 KB
/
clean_ghcr.py
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
import json
import os
import subprocess
import urllib.parse
import requests
import argparse
API_ENDPOINT = "https://api.github.com"
PER_PAGE = 100 # max 100 defaults 30
DOCKER_ENDPOINT = "ghcr.io/"
def get_url(path):
if path.startswith(API_ENDPOINT):
return path
return f"{API_ENDPOINT}{path}"
def get_base_headers():
return {
"Authorization": "token {}".format(args.token),
"Accept": "application/vnd.github.v3+json",
}
def del_req(path):
res = requests.delete(get_url(path), headers=get_base_headers())
if res.ok:
print(f"Deleted {path}")
else:
print(
f"Error when trying to delete URL: {get_url(path)} MSG: {res.text}"
)
return res
def get_req(path, params=None):
if params is None:
params = {}
params.update(page=1)
if "per_page" not in params:
params["per_page"] = PER_PAGE
url = get_url(path)
result = []
while True:
response = requests.get(url, headers=get_base_headers(), params=params)
if not response.ok:
raise Exception(response.text)
result.extend(response.json())
if "next" not in response.links:
break
url = response.links["next"]["url"]
if "page" in params:
del params["page"]
return result
def get_list_packages(owner, repo_name, owner_type, package_names):
pkgs = []
if package_names:
for package_name in package_names:
clean_package_name = urllib.parse.quote(package_name, safe='')
url = get_url(
f"/{owner_type}s/{owner}/packages/container/{clean_package_name}"
)
response = requests.get(url, headers=get_base_headers())
if not response.ok:
if response.status_code == 404:
return []
raise Exception(response.text)
pkgs.append(response.json())
else:
pkgs = get_req(
f"/{owner_type}s/{owner}/packages?package_type=container")
# this is a strange bug in github api, it returns deleted packages
# I open a ticket for that
pkgs = [pkg for pkg in pkgs if not pkg["name"].startswith('deleted_')]
if repo_name:
pkgs = [
pkg for pkg in pkgs if pkg.get("repository")
and pkg["repository"]["name"].lower() == repo_name
]
return pkgs
def get_all_package_versions(owner, repo_name, package_names, owner_type):
packages = get_list_packages(
owner=owner,
repo_name=repo_name,
package_names=package_names,
owner_type=owner_type,
)
return {
pkg['name']: get_all_package_versions_per_pkg(pkg["url"])
for pkg in packages
}
def get_all_package_versions_per_pkg(package_url):
url = f"{package_url}/versions"
return get_req(url)
def get_deps_pkgs(owner, pkgs):
ids = []
successful = True
for pkg in pkgs:
for pkg_ver in pkgs[pkg]:
try:
image = f"{DOCKER_ENDPOINT}{owner}/{pkg}@{pkg_ver['name']}"
ids.extend(get_image_deps(image))
except Exception as e:
print(e)
successful = False
if not successful:
raise Exception("Error on image dependency resolution")
return ids
def get_image_deps(image):
manifest_txt = get_manifest(image)
data = json.loads(manifest_txt)
return [manifest['digest'] for manifest in data.get("manifests", [])]
def get_manifest(image):
cmd = f"docker manifest inspect {image}"
res = subprocess.run(cmd, shell=True, capture_output=True)
if res.returncode != 0:
print(cmd)
raise Exception(res.stderr)
return res.stdout.decode("utf-8")
def delete_pkgs(owner, repo_name, owner_type, package_names, untagged_only,
except_untagged_multiplatform):
if untagged_only:
all_packages = get_all_package_versions(
owner=owner,
repo_name=repo_name,
package_names=package_names,
owner_type=owner_type,
)
tagged_pkgs = {
pkg: [
pkg_ver for pkg_ver in all_packages[pkg]
if pkg_ver["metadata"]["container"]["tags"]
]
for pkg in all_packages
}
if except_untagged_multiplatform:
deps_pkgs = get_deps_pkgs(owner, tagged_pkgs)
else:
deps_pkgs = []
all_packages = [
pkg_ver for pkg in all_packages for pkg_ver in all_packages[pkg]
]
packages = [
pkg for pkg in all_packages
if not pkg["metadata"]["container"]["tags"]
and pkg["name"] not in deps_pkgs
]
else:
packages = get_list_packages(
owner=owner,
repo_name=repo_name,
package_names=package_names,
owner_type=owner_type,
)
status = [del_req(pkg["url"]).ok for pkg in packages]
len_ok = len([ok for ok in status if ok])
len_fail = len(status) - len_ok
print(f"Deleted {len_ok} package")
if "GITHUB_OUTPUT" in os.environ:
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
f.write(f"num_deleted={len_ok}\n")
if len_fail > 0:
raise Exception(f"fail delete {len_fail}")
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ("yes", "true", "t", "y", "1"):
return True
elif v.lower() in ("no", "false", "f", "n", "0"):
return False
else:
raise argparse.ArgumentTypeError("Boolean value expected.")
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--token",
type=str,
required=True,
help="Github Personal access token with delete:packages permissions",
)
parser.add_argument("--repository_owner",
type=str,
required=True,
help="The repository owner name")
parser.add_argument(
"--repository",
type=str,
required=False,
default="",
help="Delete only repository name",
)
parser.add_argument(
"--package_names",
type=str,
required=False,
default="",
help="Delete only comma separated package names",
)
parser.add_argument(
"--untagged_only",
type=str2bool,
help="Delete only package versions without tag",
)
parser.add_argument(
"--owner_type",
choices=["org", "user"],
default="org",
help="Owner type (org or user)",
)
parser.add_argument(
"--except_untagged_multiplatform",
type=str2bool,
help=
"Except untagged multiplatform packages from deletion (only for --untagged_only) needs docker installed",
)
args = parser.parse_args()
if "/" in args.repository:
repository_owner, repository = args.repository.split("/")
if repository_owner != args.repository_owner:
raise Exception(
f"Mismatch in repository:{args.repository} and repository_owner:{args.repository_owner}"
)
args.repository = repository
args.repository = args.repository.lower()
args.repository_owner = args.repository_owner.lower()
args.package_names = args.package_names.lower()
args.package_names = [p.strip() for p in args.package_names.split(",")
] if args.package_names else []
return args
if __name__ == "__main__":
args = get_args()
delete_pkgs(
owner=args.repository_owner,
repo_name=args.repository,
package_names=args.package_names,
untagged_only=args.untagged_only,
owner_type=args.owner_type,
except_untagged_multiplatform=args.except_untagged_multiplatform)