Skip to content

Commit 4818082

Browse files
committed
cmd-fetch: derive hermeto lockfile from rpm-ostree
Instead of redoing the depsolving, simply pull NEVRA fields from the rpm-lockfiles and use `dnf repoquery` to get the packages URLs. This is the bare minimum for a hermeto lockfile but works.
1 parent 1206db7 commit 4818082

File tree

2 files changed

+73
-143
lines changed

2 files changed

+73
-143
lines changed

src/cmd-fetch

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -183,14 +183,9 @@ if [ -n "${UPDATE_LOCKFILE}" ]; then
183183
echo "Wrote out lockfile ${outfile}"
184184

185185
if [ -n "${KONFLUX}" ]; then
186-
echo "Generating hermeto input file..."
187-
/usr/lib/coreos-assembler/konflux-rpm-lockfile generate "${manifest}" --context "${configdir}" --output "${tmprepo}/tmp/rpm.in.${arch}.yaml"
188-
rpm-lockfile-prototype "${tmprepo}/tmp/rpm.in.${arch}.yaml" --outfile "${tmprepo}/tmp/rpms.lock.${arch}.yaml"
189-
# Sanity check the generated hermeto lockfile
190-
echo "Sanity check consistency between konflux and rpm-ostree lockfiles..."
191-
/usr/lib/coreos-assembler/konflux-rpm-lockfile compare "${configdir}/manifest-lock.${arch}.json" "${tmprepo}/tmp/rpms.lock.${arch}.yaml"
186+
echo "Generating hermeto lockfile..."
187+
/usr/lib/coreos-assembler/konflux-rpm-lockfile "${manifest}" --context "${configdir}" --output "${tmprepo}/tmp/rpms.lock.${arch}.yaml"
192188
(cd "${workdir}" && mv -f "${tmprepo}/tmp/rpms.lock.${arch}.yaml" "konflux-rpms-lock.${arch}.yaml")
193-
echo "Wrote out hermeto lockfile: /tmp/rpms.lock.${arch}.yaml
194-
189+
echo "Wrote out hermeto lockfile: konflux-rpms-lock.${arch}.yaml"
195190
fi
196191
fi

src/konflux-rpm-lockfile

Lines changed: 70 additions & 135 deletions
Original file line numberDiff line numberDiff line change
@@ -1,198 +1,133 @@
11
#!/usr/bin/python
22

33
import argparse
4-
import json
54
import os
65
import re
76
import sys
7+
import subprocess
88
import yaml
99

1010
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
1111
from cosalib.cmdlib import get_treefile, get_locked_nevras, get_basearch
1212

1313

14-
ARCH = get_basearch()
15-
16-
17-
def locks_mismatch(rpm_ostree_lock, hermeto_lock):
18-
"""
19-
Compares a JSON manifest lock with a YAML RPM lock for x86_64.
20-
21-
Args:
22-
rpm_ostree_lock (str): Path to the rpm-ostree JSON manifest lock file.
23-
hermeto_lock (str): Path to the hermeto YAML lock file.
24-
25-
Returns:
26-
bool: True if there are differences, False otherwise.
27-
"""
28-
with open(rpm_ostree_lock, 'r') as f:
29-
manifest_data = {name: details['evra'] for name, details in json.load(f).get('packages', {}).items()}
30-
31-
with open(hermeto_lock, 'r') as f:
32-
yaml_data = {pkg['name']: str(pkg['evr']) for arch in yaml.safe_load(f).get('arches', []) if arch.get('arch') == 'x86_64' for pkg in arch.get('packages', [])}
33-
34-
rpm_ostree_lock_set = set(manifest_data.keys())
35-
hermeto_lock_set = set(yaml_data.keys())
36-
37-
differences_found = False
38-
39-
if only_in_manifest := sorted(list(rpm_ostree_lock_set - hermeto_lock_set)):
40-
differences_found = True
41-
print("Packages only in rpm-ostree lockfile:")
42-
for pkg in only_in_manifest:
43-
print(f"- {pkg} ({manifest_data[pkg]})")
44-
45-
if only_in_yaml := sorted(list(hermeto_lock_set - rpm_ostree_lock_set)):
46-
differences_found = True
47-
print("\nPackages only in hermeto lockfile:")
48-
for pkg in only_in_yaml:
49-
print(f"- {pkg} ({yaml_data[pkg]})")
50-
51-
mismatches = []
52-
for pkg in sorted(list(rpm_ostree_lock_set.intersection(hermeto_lock_set))):
53-
manifest_evr = manifest_data[pkg].rsplit('.', 1)[0]
54-
if manifest_evr != yaml_data[pkg]:
55-
mismatches.append(f"- {pkg}:\n - rpm-ostree: {manifest_data[pkg]}\n - hermeto: {yaml_data[pkg]}")
56-
57-
if mismatches:
58-
differences_found = True
59-
print("\nVersion mismatches:")
60-
for mismatch in mismatches:
61-
print(mismatch)
62-
else:
63-
print(f"\u2705 No mismatches founds between {rpm_ostree_lock} and {hermeto_lock}")
64-
65-
return differences_found
66-
67-
68-
def filter_repofile(repos, locked_nevras, repo_path, output_dir):
14+
def get_repo_url(repo_path, repoid):
6915
if not os.path.exists(repo_path):
70-
print(f"Error: {repo_path} not found. Cannot inject includepkg filter.")
71-
return
72-
73-
include_str = ','.join(locked_nevras)
16+
print(f"Error: {repo_path} not found.")
17+
return None
7418

75-
with open(repo_path, 'r') as f:
19+
with open(repo_path, 'r', encoding="utf8") as f:
7620
repofile = f.read()
7721

78-
# We use a regex that looks for [reo_name] on a line by itself,
22+
# We use a regex that looks for [repo_name] on a line by itself,
7923
# possibly with whitespace.
8024
sections = re.split(r'^\s*(\[.+\])\s*', repofile, flags=re.MULTILINE)
8125

82-
new_content = sections[0] # part before any section
83-
keep = False
84-
85-
# sections will be [before, section1_name, section1_content, section2_name, section2_content, ...]
8626
for i in range(1, len(sections), 2):
8727
name = sections[i]
8828
# ignore repos that don't match the repos we want to use
89-
if name.strip("[]") in repos:
29+
if name.strip("[]") == repoid:
9030
repodef = sections[i+1]
91-
if 'includepkgs=' not in repodef:
92-
# We only keep the repo definition that we edited
93-
# to avoid accidentaly taking in other packages
94-
# from a repofile already having an includepkgs
95-
# directive.
96-
keep = True
97-
new_content += name + '\n'
98-
repodef += f"includepkgs={include_str}\n"
99-
new_content += repodef
100-
101-
filename = None
102-
if keep:
103-
filename = os.path.basename(repo_path.removesuffix(".repo"))
104-
filename = os.path.join(output_dir, f"{filename}-hermeto.repo")
105-
with open(filename, 'w') as f:
106-
f.write(new_content)
107-
print(f"Wrote filtered repo to: {filename}")
108-
109-
return keep, filename
110-
111-
112-
def build_rpm_lockfile_config(packages, repo_files):
113-
"""
114-
Augments package names in rpm_in_data with version numbers from locks.
115-
Populates contentOrigin and repofiles.
116-
"""
117-
# Initialize the structure for rpm_lockfile_input, similar to write_rpms_input_file
118-
# This ensures consistency whether it comes from a manifest or directly
119-
rpm_lockfile_config = {
120-
'contentOrigin': {
121-
'repofiles': repo_files
122-
},
123-
'installWeakDeps': False,
124-
'context': {
125-
'bare': True,
126-
},
127-
'packages': packages
31+
if 'baseurl=' in repodef:
32+
for line in repodef.splitlines():
33+
if line.strip().startswith('baseurl='):
34+
return line.split('=', 1)[1].strip()
35+
36+
37+
def write_hermeto_lockfile(pkgs):
38+
39+
packages = []
40+
for pkg in pkgs:
41+
packages.append({"url": pkg})
42+
43+
lockfile = {
44+
'lockfileVersion': 1,
45+
"lockfileVendor": "redhat",
46+
"arches": [
47+
{'arch': get_basearch(),
48+
'packages': packages}
49+
]
12850
}
12951

130-
return rpm_lockfile_config
52+
return lockfile
53+
13154

13255
def generate_lockfile(contextdir, manifest, output_path):
13356
"""
134-
Generates the rpm-lockfile-prototype input file.
57+
Generates the cachi2/hermeto RPM lock file.
13558
"""
13659
manifest_data = get_treefile(manifest, deriving=False)
13760
repos = manifest_data.get('repos', [])
13861
repos += manifest_data.get('lockfile-repos', [])
139-
packages = manifest_data.get('packages', [])
14062
locks = get_locked_nevras(contextdir)
14163
repofiles = [file for file in os.listdir(contextdir) if file.endswith('.repo')]
142-
relevant_repofiles = []
143-
output_dir = os.path.dirname(output_path)
14464

65+
for entry in manifest_data.get('repo-packages', []):
66+
repos += entry.get('repo', [])
67+
68+
repoquery_args = ["--queryformat", "%{name} %{location}\n", "--disablerepo=*"]
69+
for repoid in set(repos):
70+
for file in repofiles:
71+
url = get_repo_url(os.path.join(contextdir, file), repoid)
72+
if url:
73+
repoquery_args.extend([f"--repofrompath=temp{repoid},{url}", f"--enablerepo=temp{repoid}"])
74+
break # Found repo, no need to check other files for same repoid
75+
76+
pkg_urls = []
14577
if locks:
14678
locked_nevras = [f'{k}-{v}' for (k, v) in locks.items()]
147-
for repofile in repofiles:
148-
keep, newrepo = filter_repofile(repos, locked_nevras, os.path.join(contextdir, repofile), output_dir)
149-
if keep:
150-
relevant_repofiles.append(newrepo)
79+
cmd = ['dnf', 'repoquery'] + locked_nevras + repoquery_args
80+
result = subprocess.run(cmd, capture_output=True, text=True)
81+
82+
if result.returncode == 0:
83+
processed_urls = {}
84+
for line in result.stdout.strip().split('\n'):
85+
# ignore empty lines
86+
if not line:
87+
continue
88+
parts = line.split(' ', 1)
89+
if len(parts) == 2:
90+
name, url = parts
91+
if name not in processed_urls:
92+
processed_urls[name] = url
93+
pkg_urls = list(processed_urls.values())
94+
else:
95+
print(f"Error running dnf repoquery:\n{result.stderr}", file=sys.stderr)
96+
sys.exit(1)
15197

152-
augmented_rpm_in = build_rpm_lockfile_config(packages, relevant_repofiles)
98+
lockfile = write_hermeto_lockfile(pkg_urls)
15399

154100
try:
155-
with open(output_path, 'w') as f:
156-
yaml.safe_dump(augmented_rpm_in, f, default_flow_style=False)
157-
print(f"rpm-lockfile-prototype input config wrote to: {output_path}")
101+
with open(output_path, 'w', encoding="utf8") as f:
102+
yaml.safe_dump(lockfile, f, default_flow_style=False)
158103
except IOError as e:
159104
print(f"\u274c Error: Could not write to final output file '{output_path}'. Reason: {e}")
160105
sys.exit(1)
161106

162107

163108
if __name__ == "__main__":
164109
parser = argparse.ArgumentParser(
165-
description="Generate and compare rpm-lockfile-prototype input files."
110+
description="Generate hermeto lock files."
166111
)
167-
subparsers = parser.add_subparsers(dest='command', required=True)
168112

169-
parser_generate = subparsers.add_parser('generate', help='Generate rpm-lockfile-prototype input file.')
170-
parser_generate.add_argument(
113+
parser.add_argument(
171114
'manifest',
172115
help='Path to the rpm-ostree manifest (e.g., fedora-coreos-config/manifest.yaml)'
173116
)
174117

175-
parser_generate.add_argument(
118+
parser.add_argument(
176119
'--context',
177120
default='.',
178121
help="Path to the directory containing repofiles and lockfiles. (default: '.')"
179122
)
180123

181-
parser_generate.add_argument(
124+
parser.add_argument(
182125
'--output',
183-
default='./rpms.in.yaml',
184-
help="Path for the final rpm-lockfile-protoype config file. (default: './rpms.in.yaml')"
126+
default='./rpms.lock.yaml',
127+
help="Path for the hermeto lockfile. (default: './rpms.lock.yaml')"
185128
)
186129

187-
parser_compare = subparsers.add_parser('compare', help='Compare rpm-ostree JSON lockfile with hermeto RPM lock.')
188-
parser_compare.add_argument('rpmostree_lockfile', help='Path to the rpm-ostree manifest lock file (JSON).')
189-
parser_compare.add_argument('hermeto_lockfile', help='Path to the hermeto RPM lock file (YAML).')
190-
191130
args = parser.parse_args()
192131

193-
if args.command == 'generate':
194-
manifest_abs_path = os.path.abspath(args.manifest)
195-
generate_lockfile(args.context, manifest_abs_path, args.output)
196-
elif args.command == 'compare':
197-
if locks_mismatch(args.rpmostree_lockfile, args.hermeto_lockfile):
198-
sys.exit(1)
132+
manifest_abs_path = os.path.abspath(args.manifest)
133+
generate_lockfile(args.context, manifest_abs_path, args.output)

0 commit comments

Comments
 (0)