forked from ptrxyz/chemotion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtag.py
271 lines (231 loc) · 7.17 KB
/
tag.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
264
265
266
267
268
269
270
271
import os
import sys
from dataclasses import dataclass
from functools import cache
import subprocess
import argparse
class Globals:
services = [
"base",
"converter",
"ketchersvc",
"ketchersvc-sc",
"spectra",
"msconvert",
"eln",
]
class RepoNameTag:
def __init__(self, repo, name, tag):
self.repo = repo
self.name = name
self.tag = tag
def toStr(self):
return self.__str__()
def __str__(self):
if "/" in self.repo:
return f"{self.repo}:{self.name}-{self.tag}"
else:
return f"{self.repo}/{self.name}:{self.tag}"
class Docker:
ALLOWED_NAME_CHARACTERS = "abcdefghijklmnopqrstuvwxyz0123456789"
ALLOWED_TAG_CHARACTERS = (
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-"
)
TAG_SEPARATORS = ".-"
NAME_SEPARATORS = [".", "_", "__", "-", "--", "---"]
@staticmethod
def validTag(s: str):
return (
all([x in Docker.ALLOWED_TAG_CHARACTERS for x in s])
and all([not s.startswith(y) for y in Docker.TAG_SEPARATORS])
and len(s) > 0
and len(s) < 128
)
@staticmethod
def validName(s: str):
return (
all([x in Docker.ALLOWED_NAME_CHARACTERS for x in s])
and all(
[
not s.startswith(y) and not s.endswith(y)
for y in Docker.NAME_SEPARATORS
]
)
and len(s) > 0
and len(s) < 128
)
@staticmethod
def validImageName(s: str):
if ":" in s:
name, tag = s.split(":")
return Docker.validName(name) and Docker.validTag(tag)
else:
return Docker.validName(s)
@staticmethod
@cache
def allImages():
def splitLSLine(line):
repoNSvc, id, tag, *_ = line.split("|")
repo, svc = repoNSvc.split("/")
imageInfo = ImageInfo(repo, svc, id, tag)
return imageInfo
proc = subprocess.run(
["docker", "image", "ls", "--format", "{{.Repository}}|{{.ID}}|{{.Tag}}"],
stdout=subprocess.PIPE,
)
if proc.returncode != 0:
print("Error: docker image ls failed")
sys.exit(1)
imageList = [
splitLSLine(x.strip())
for x in proc.stdout.decode("utf-8").splitlines()
if x
]
return imageList
@staticmethod
def addTag(src: RepoNameTag, dst: RepoNameTag):
proc = subprocess.run(
["docker", "image", "tag", src.toStr(), dst.toStr()],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
Docker.allImages.cache_clear()
if proc.returncode != 0:
print(f"Error: failed to tag image.")
print(
" "
+ proc.stderr.decode("utf-8")
.replace("Error response from daemon:", "")
.strip()
.replace("\n", "\n ")
)
print()
return False
else:
print(f"Tagged {src.toStr()}\t\t\t\t as {dst.toStr()}")
return True
@staticmethod
def pushImage(what: RepoNameTag):
proc = subprocess.run(
["docker", "image", "push", what.toStr()],
)
if proc.returncode != 0:
print(f"Error: failed to push image {what.toStr()}")
return False
else:
print(f"Pushed {what.toStr()}")
return True
@dataclass
class Args:
sourceTag: str
newTag: str
sourceRepo: str
targetRepo: str
push: bool
latest: bool
sourceLatest: bool
def printConfig(self):
print("Config:")
print("Source Tag :", self.sourceTag)
print("New Tag :", self.newTag)
print("Source Repo :", self.sourceRepo)
print("Target Repo :", self.targetRepo)
print("Push :", self.push)
print("Apply Latest:", self.latest)
print("--\n")
@dataclass
class ImageInfo:
repo: str
svc: str
id: str
tag: str
parser = argparse.ArgumentParser()
parser.add_argument("sourceTag", help="Tag shared for all services.", type=str)
parser.add_argument(
"newTag",
help="New tag to attach to all services. Use '-' to use sourceTag as targetTag.",
type=str,
default="-",
)
parser.add_argument(
"--sourceRepo",
help="source repo (default: chemotion-build)",
default="chemotion-build",
)
parser.add_argument(
"--targetRepo",
help="target repo (default: ptrxyz/chemotion)",
default="ptrxyz/chemotion",
)
parser.add_argument("--push", help="Also push to Docker Hub.", action="store_true")
parser.add_argument("--latest", help="Also tag as latest", action="store_true")
parser.add_argument(
"--sourceLatest", help="Also tag as latest in source repo", action="store_true"
)
# if targetRepo does contain "/", the new image name will be
# `<targetRepo>:<service>-<tag>`, otherwise `<targetRepo>/<service>:<tag>`
args = Args(**dict(parser.parse_args()._get_kwargs()))
if args.newTag == "-":
args.newTag = args.sourceTag
if (not Docker.validTag(args.sourceTag)) or (not Docker.validTag(args.newTag)):
print("Invalid tag")
sys.exit(1)
class Helpers:
@staticmethod
def grep(cmp, lines):
return [x for x in lines if cmp(x)]
@staticmethod
def checkDockerImageExists(repo, svc, tag):
allDockerImages = Docker.allImages()
return (
len(
Helpers.grep(
lambda x: x.repo == repo and x.svc == svc and x.tag == tag,
allDockerImages,
)
)
> 0
)
@staticmethod
def checkAllServiceImagesExist(repo, tag):
ret = dict(
[
(
RepoNameTag(repo, svc, tag),
Helpers.checkDockerImageExists(repo, svc, tag),
)
for svc in Globals.services
]
)
if not all(ret.values()):
print("Error: Not all images exist")
for k, v in ret.items():
if not v:
print(f" Missing: {k}")
return False
else:
return True
# if not Helpers.checkAllServiceImagesExist(args.sourceRepo, args.sourceTag):
# sys.exit(1)
for svc in Globals.services:
Docker.addTag(
src=RepoNameTag(args.sourceRepo, svc, args.sourceTag),
dst=RepoNameTag(args.targetRepo, svc, args.newTag),
)
if args.latest:
Docker.addTag(
src=RepoNameTag(args.sourceRepo, svc, args.sourceTag),
dst=RepoNameTag(args.targetRepo, svc, "latest"),
)
if args.sourceLatest:
Docker.addTag(
src=RepoNameTag(args.sourceRepo, svc, args.sourceTag),
dst=RepoNameTag(args.sourceRepo, svc, "latest"),
)
print("Tagged all images.")
if args.push:
print("Pushing images...")
for svc in Globals.services:
Docker.pushImage(RepoNameTag(args.targetRepo, svc, args.newTag))
if args.latest:
Docker.pushImage(RepoNameTag(args.targetRepo, svc, "latest"))