-
Notifications
You must be signed in to change notification settings - Fork 15
/
build_stage_repository
executable file
·370 lines (284 loc) · 11.2 KB
/
build_stage_repository
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
#!/usr/bin/env python3
from email.utils import parsedate_to_datetime
from subprocess import check_output, STDOUT, CalledProcessError
from urllib.request import urlretrieve
from urllib.error import ContentTooShortError
import os
import yaml
import glob
import shutil
import time
import hashlib
import sys
import tempfile
import dnf.comps
import argparse
def filter_packages(target_dir, packages):
files = glob.glob(f"{target_dir}/*.rpm")
for file in files:
file_name = os.path.basename(file)
rpm_name = get_rpm_name(file)
if rpm_name not in packages:
print(f"Removed {rpm_name}. Package not in comps.")
os.remove(os.path.join(target_dir, file_name))
def get_rpm_name(rpm):
command = [
'rpmquery',
'--nosignature',
'--queryformat',
'%{name}',
'--package',
rpm
]
return check_output(command, universal_newlines=True)
def modulemd_yaml(collection, version, foreman_version, dist):
branch = 'develop' if foreman_version == 'nightly' else foreman_version
path, headers = urlretrieve(f"https://raw.githubusercontent.com/theforeman/foreman-packaging/rpm/{branch}/modulemd/modulemd-{collection}-{dist}.yaml")
return path
def comps(collection, version, dist, foreman_version):
branch = 'develop' if foreman_version == 'nightly' else foreman_version
repo = 'foreman-packaging'
name = collection
if collection == 'client':
name = 'foreman-client'
elif collection == 'plugins':
name = 'foreman-plugins'
elif collection == 'candlepin':
repo = 'candlepin-packaging'
branch = version if version != 'nightly' else branch
elif collection == 'pulpcore':
repo = 'pulpcore-packaging'
branch = 'develop' if version == 'nightly' else version
if collection == 'client' and dist == 'el7':
dist = 'rhel7'
url = f"https://raw.githubusercontent.com/theforeman/{repo}/rpm/{branch}/comps/comps-{name}-{dist}.xml"
print(f"Fetching comps: {url}")
path, headers = urlretrieve(url)
return path
def generate_modulemd_version(version):
if version == 'nightly':
modulemd_version_prefix = '9999'
else:
major, minor = version.split('.')
modulemd_version_prefix = int(major)*100 + int(minor)
modulemd_version_string = time.strftime(f"{modulemd_version_prefix}%Y%m%d%H%M%S", time.gmtime())
return int(modulemd_version_string)
def generate_modulemd_context(collection, version):
context_string = f"{collection}-{version}"
digest = hashlib.sha256(context_string.encode()).hexdigest()
return digest[:8]
def create_modulemd(collection, version, stage_dir, foreman_version, dist):
print("Adding modulemd to stage repository")
cmd = [
'rpm',
'--nosignature',
'--query',
'--package',
f"{stage_dir}/*.rpm",
"--queryformat=%{name}-%{epochnum}:%{version}-%{release}.%{arch}\n"
]
output = check_output(cmd, universal_newlines=True)
with open(modulemd_yaml(collection, version, foreman_version, dist), 'r') as file:
modules = list(yaml.safe_load_all(file))
module_version = generate_modulemd_version(version)
module_context = generate_modulemd_context(collection, version)
for module in modules:
module['data']['version'] = module_version
module['data']['context'] = module_context
if module['data']['name'] == collection:
module['data']['artifacts'] = {'rpms': output.splitlines()}
modules_yaml = os.path.join(stage_dir, 'repodata', 'modules.yaml')
with open(modules_yaml, 'w') as modules_file:
yaml.dump_all(modules, modules_file, default_flow_style=False, explicit_start=True, explicit_end=True)
check_output(['modifyrepo_c', '--compress-type=gz', '--mdtype=modules', modules_yaml, f"{stage_dir}/repodata"])
def create_repository(repo_dir):
check_output(['createrepo_c', "--general-compress-type=gz", "--database" ,repo_dir], stderr=STDOUT)
def sync_prod_repository(collection, version, target_dir, dist, arch):
repository_url = prod_repository(collection, version, dist, arch)
if arch == 'source':
print(f"Syncing {collection} {version} Source RPM repository from {repository_url}")
else:
print(f"Syncing {collection} {version} RPM repository from {repository_url}")
cmd = [
'dnf',
'--config',
f'tmp/dnf.conf',
'reposync',
'--refresh',
'--remote-time',
'--download-metadata',
'--norepopath',
'--repo',
f"{dist}-{collection}-{version}-{arch}",
'--repofrompath',
f"{dist}-{collection}-{version}-{arch},{repository_url}",
'--download-path',
target_dir
]
if arch == 'source':
cmd.extend([
'--source',
])
else:
cmd.extend([
'--exclude',
'*.src',
])
check_output(cmd)
def packages_from_comps(comps):
dnf_comps = dnf.comps.Comps()
try:
dnf_comps._add_from_xml_filename(comps)
except libcomps.ParserError:
errors = comps.get_last_errors()
raise CompsError(' '.join(errors))
packages = set()
for group in dnf_comps.groups:
for package in group.default_packages:
packages.add(package.name)
return packages
def copr_repository(collection, version, dist, arch):
return f"https://download.copr.fedorainfracloud.org/results/@theforeman/{collection}-{version}-staging/rhel-{dist.replace('el', '')}-{arch}"
def prod_repository(collection, version, dist, arch):
if collection == "foreman":
subdir = "releases"
else:
subdir = collection.replace('foreman-', '')
if collection == 'katello':
version = f'{version}/katello'
return f"https://yum.theforeman.org/{subdir}/{version}/{dist}/{arch}"
def copr_repository_urls(repository):
cmd = [
'dnf',
'reposync',
'--urls',
'--refresh',
'--repofrompath',
f"copr,{repository}",
'--repo',
'copr'
]
urls = check_output(cmd, universal_newlines=True, stderr=STDOUT)
return urls.split("\n")
def compare_repositories(new_repository, old_repository, arch, source=False):
cmd = [
'dnf',
'--config',
f'tmp/dnf.conf',
'repodiff',
'--simple',
'--refresh',
'--compare-arch',
'--repofrompath',
f"new,{new_repository}",
'--repofrompath',
f"old,{old_repository}",
'--repo-old',
'old',
'--repo-new',
'new'
]
if not source:
cmd.extend(['--arch', f'noarch,{arch}'])
print(' '.join(cmd))
return check_output(cmd, universal_newlines=True)
def parse_repodiff(diff):
split_diff = diff.split("\n")
packages = []
for line in split_diff:
if line.startswith('Added package :'):
packages.append(line.replace('Added package : ', ''))
elif ' -> ' in line:
packages.append(line.split(' -> ')[1])
return packages
def download_copr_packages(packages, urls, repository, downloads_dir, included_packages=None):
for package in packages:
name, version, release = package.rsplit('-', 2)
if included_packages is None or name in included_packages:
version_without_epoch = version.rsplit(':', 1)[-1]
name = f"{name}-{version_without_epoch}-{release}.rpm"
for url in urls:
if name == os.path.basename(url):
download_url = url
if not os.path.exists(f"{downloads_dir}/{name}"):
print(f"Downloading {repository}/{name} to {downloads_dir}")
try:
filename, headers = urlretrieve(download_url, f"{downloads_dir}/{name}")
except ContentTooShortError:
try:
os.unlink(f"{downloads_dir}/{name}")
except OSError:
pass
raise
if 'Last-Modified' in headers:
modification_ts = parsedate_to_datetime(headers['Last-Modified']).timestamp()
os.utime(filename, (modification_ts, modification_ts))
else:
print(f"Skipping {repository}/{name}. Already downloaded.")
else:
print(f"Skipping {package}. Package not present in comps.")
def handle_args():
parser = argparse.ArgumentParser(description='Generate a stage repository')
parser.add_argument(
'collection',
help='Repository to generate for (e.g. foreman)'
)
parser.add_argument(
'version',
help='Version to generate the repository for (e.g. nightly)'
)
parser.add_argument(
'dist',
help='Dist to generate repository for (e.g. el8)'
)
parser.add_argument(
'foreman_version',
nargs='?',
help='Foreman Version for one specefic katello version'
)
return parser.parse_args()
def initialize_repository(collection, version, dist, arch, rpm_dir, srpm_dir):
if version != 'nightly':
sync_prod_repository(collection, version, rpm_dir, dist, arch)
sync_prod_repository(collection, version, srpm_dir, dist, 'source')
else:
create_repository(rpm_dir)
create_repository(srpm_dir)
def add_packages_from_copr(collection, version, dist, arch, rpm_dir, srpm_dir, foreman_version):
packages_to_include = packages_from_comps(comps(collection, version, dist, foreman_version))
copr_repo = copr_repository(collection, version, dist, arch)
copr_package_urls = copr_repository_urls(copr_repo)
rpm_diff = compare_repositories(copr_repo, rpm_dir, arch)
packages = parse_repodiff(rpm_diff)
download_copr_packages(packages, copr_package_urls, copr_repo, rpm_dir, packages_to_include)
filter_packages(rpm_dir, packages_to_include)
srpm_diff = compare_repositories(copr_repo, srpm_dir, arch, True)
srpm_packages = parse_repodiff(srpm_diff)
download_copr_packages(srpm_packages, copr_package_urls, copr_repo, srpm_dir)
def update_repositories(collection, version, dist, rpm_dir, srpm_dir, foreman_version):
create_repository(rpm_dir)
create_repository(srpm_dir)
if collection in ['foreman'] or (collection in ['katello'] and dist == 'el8'):
create_modulemd(collection, version, rpm_dir, foreman_version, dist)
def main():
args = handle_args()
collection = args.collection
version = args.version
dist = args.dist
arch = 'x86_64'
foreman_version = args.foreman_version or args.version
base_dir = 'tmp'
stage_dir = f"{base_dir}/{collection}/{version}/{dist}"
rpm_dir = f"{stage_dir}/{arch}"
srpm_dir = f"{stage_dir}/source"
if not os.path.exists(rpm_dir):
os.makedirs(rpm_dir)
if not os.path.exists(srpm_dir):
os.makedirs(srpm_dir)
with open(f"{base_dir}/dnf.conf", "w") as dnf_conf:
dnf_conf.write("[main]\nskip_if_unavailable=True")
initialize_repository(collection, version, dist, arch, rpm_dir, srpm_dir)
add_packages_from_copr(collection, version, dist, arch, rpm_dir, srpm_dir, foreman_version)
update_repositories(collection, version, dist, rpm_dir, srpm_dir, foreman_version)
if __name__ == '__main__':
main()