This is an automated email from the ASF dual-hosted git repository.
rzo1 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/storm.git
The following commit(s) were added to refs/heads/master by this push:
new bc8d519ca1 Fix Python 3 incompatibilities in bin/docker-to-squash.py
(#9296)
bc8d519ca1 is described below
commit bc8d519ca15f34c14851a5e205f9b8bcd8e2b2d0
Author: Toni <[email protected]>
AuthorDate: Mon Nov 30 04:34:20 2026 -0800
Fix Python 3 incompatibilities in bin/docker-to-squash.py (#9296)
* Fix Python 3 incompatibilities in bin/docker-to-squash.py
The script cannot run on Python 3: Iterable is imported from collections
(removed in 3.10), the --untagged-transition-sec argument uses type=long,
calculate_string_hash passes a str to hashlib, and
write_local_image_tag_to_hash uses dict.iteritems(). Import Iterable from
collections.abc, use type=int, encode the string as UTF-8 before hashing, and
use dict.items(). Also replace two 'is not ""' comparisons with '!=' to silence
SyntaxWarning.
Signed-off-by: ToniAdreal <[email protected]>
* Address review: hash raw bytes, decode subprocess output, replace
remaining long()
Part of #9291. Per rzo1's review on #9296:
- Manifest hashes now computed over raw bytes (calculate_bytes_hash)
instead of the str(bytes) repr.
- Subprocess output and tag-file lines decoded to str at use sites
(decode_output helper); read_image_tag_to_hash no longer mangles
entries via str(line).
- Remaining long() calls replaced with int(); get_all_known_images
decodes hdfs_stat output before splitting.
- Tests: hash checked against hashlib.sha256, tag-file write/read
round-trip, decode_output cases. 4/4 pass on Python 3.12.
* Address review: drop redundant `or None` in manifest filters
reiabreu noted the `or None` in the two manifest list comprehensions
does nothing; `if image` filters empty strings the same way.
Signed-off-by: ToniAdreal <[email protected]>
---------
Signed-off-by: ToniAdreal <[email protected]>
---
bin/docker-to-squash.py | 56 +++++++++++++++++++++++++++++---------------
bin/test_docker_to_squash.py | 52 +++++++++++++++++++++++++++++++++-------
2 files changed, 80 insertions(+), 28 deletions(-)
diff --git a/bin/docker-to-squash.py b/bin/docker-to-squash.py
index 052b5a1d26..a81dd3fd34 100755
--- a/bin/docker-to-squash.py
+++ b/bin/docker-to-squash.py
@@ -24,7 +24,7 @@ Tool dependencies: skopeo, squashfs-tools, tar, setfattr
"""
import argparse
-from collections import Iterable
+from collections.abc import Iterable
import glob
import hashlib
import json
@@ -49,6 +49,19 @@ HDFS_LAYERS_DIR = "/undefined"
HDFS_UNREF_DIR = "/undefined"
+def decode_output(data):
+ """Decode subprocess output (bytes) to str for logging/display.
+
+ subprocess.Popen.communicate() returns bytes; str(bytes) would produce
+ the literal "b'...'" repr instead of the actual output.
+ """
+ if data is None:
+ return ""
+ if isinstance(data, bytes):
+ return data.decode("utf-8", errors="replace")
+ return data
+
+
def shell_command(command, print_stdout, print_stderr, raise_on_error,
timeout_sec=600):
global LOG_LEVEL
global ARG_MAX
@@ -81,9 +94,9 @@ def shell_command(command, print_stdout, print_stderr,
raise_on_error, timeout_s
if raise_on_error and process.returncode:
exception_string = f"Command: {command} failed with returncode:
{process.returncode}"
if out:
- exception_string = exception_string + "\nstdout: " + str(out)
+ exception_string = exception_string + "\nstdout: " +
decode_output(out)
if err:
- exception_string = exception_string + "\nstderr: " + str(err)
+ exception_string = exception_string + "\nstderr: " +
decode_output(err)
raise Exception(exception_string)
except Exception as ex:
if process and process.poll() is None:
@@ -285,30 +298,35 @@ def calculate_file_hash(filename):
return hex_digest
-def calculate_string_hash(string):
+def calculate_bytes_hash(data):
+ """sha256 hex digest of raw bytes (e.g. a manifest as returned by a
subprocess)."""
sha = hashlib.sha256()
- sha.update(string)
+ sha.update(data)
return sha.hexdigest()
+def calculate_string_hash(string):
+ return calculate_bytes_hash(string.encode("utf-8"))
+
+
def get_local_manifest_from_path(manifest_path):
with open(manifest_path, "rb") as file_pointer:
out = file_pointer.read()
- manifest_hash = calculate_string_hash(str(out))
+ manifest_hash = calculate_bytes_hash(out)
manifest = json.loads(out)
return manifest, manifest_hash
def get_hdfs_manifest_from_path(manifest_path):
out, err, rc = hdfs_cat(manifest_path)
- manifest_hash = calculate_string_hash(str(out))
+ manifest_hash = calculate_bytes_hash(out)
manifest = json.loads(out)
return manifest, manifest_hash
def get_hdfs_manifests_from_paths(manifest_paths):
out, err, rc = hdfs_cat(manifest_paths)
- manifests_list = out.split("}{")
+ manifests_list = out.decode("utf-8").split("}{")
manifests = []
for manifest_str in manifests_list:
if manifest_str[0] != "{":
@@ -402,7 +420,7 @@ def get_manifest_from_docker_image(pull_format, image):
manifest, manifest_hash = get_manifest_from_docker_image(pull_format,
image_and_sha)
else:
- manifest_hash = calculate_string_hash(str(out))
+ manifest_hash = calculate_bytes_hash(out)
logging.debug("manifest: %s", str(manifest))
return manifest, manifest_hash
@@ -423,7 +441,7 @@ def read_image_tag_to_hash(image_tag_to_hash):
line = file_pointer.readline()
if not line:
break
- line = str(line).rstrip()
+ line = line.decode("utf-8").rstrip()
if not line:
continue
@@ -514,7 +532,7 @@ def add_tag_to_dicts(hash_to_tags, tag_to_hash, tag,
manifest_hash, comment):
def write_local_image_tag_to_hash(image_tag_to_hash, hash_to_tags):
file_contents = []
- for key, value in hash_to_tags.iteritems():
+ for key, value in hash_to_tags.items():
manifest_hash = key
# Sort tags list to preserve consistent order
value[0].sort()
@@ -606,14 +624,14 @@ def make_whiteout_block_device(file_path, whiteout):
shell_command(["mknod", "-m", "000", file_path, "c", "0", "0"], False,
True, True)
out, err, rc = shell_command(["stat", "-c", "%U:%G", whiteout], False,
True, True)
- perms = str(out).strip()
+ perms = decode_output(out).strip()
shell_command(["chown", perms, file_path], False, True, True)
def convert_oci_whiteouts(tmp_dir):
out, err, rc = shell_command(["find", tmp_dir, "-name", ".wh.*"], False,
False, True)
- whiteouts = str(out).splitlines()
+ whiteouts = decode_output(out).splitlines()
for whiteout in whiteouts:
if whiteout == 0:
continue
@@ -1369,13 +1387,13 @@ def get_all_known_images():
global HDFS_UNREF_DIR
known_manifest_paths, err, returncode = hdfs_stat(HDFS_MANIFEST_DIR +
"/*", "%a %Y %n", False, False, False)
- known_manifests = [image for image in known_manifest_paths.split("\n") if
image is not "" or None]
+ known_manifests = [image for image in
decode_output(known_manifest_paths).split("\n") if image]
unref_manifest_paths, err, returncode = hdfs_stat(HDFS_UNREF_DIR + "/*",
"%a %Y %n", False, False, False)
logging.debug("unref_manifest_paths:\n%s", unref_manifest_paths)
unref_manifests = []
if unref_manifest_paths:
- unref_manifests = [image for image in unref_manifest_paths.split("\n")
if image is not "" or None]
+ unref_manifests = [image for image in
decode_output(unref_manifest_paths).split("\n") if image]
logging.debug("unref_manifests:\n%s", unref_manifests)
unref_manifests_stats_dict = {}
@@ -1383,7 +1401,7 @@ def get_all_known_images():
for unref_manifest in unref_manifests:
unref_manifest_split = unref_manifest.split()
unref_manifest_perms = unref_manifest_split[0]
- unref_manifest_mod_time = long(unref_manifest_split[1])
+ unref_manifest_mod_time = int(unref_manifest_split[1])
unref_manifest_name = unref_manifest_split[2]
unref_manifest_stat = Filestat(unref_manifest_perms,
unref_manifest_mod_time, unref_manifest_name)
unref_manifests_stats_dict[unref_manifest_name] =
unref_manifest_stat
@@ -1397,7 +1415,7 @@ def get_all_known_images():
for manifest in known_manifests:
manifest_split = manifest.split()
manifest_perms = manifest_split[0]
- manifest_mod_time = long(manifest_split[1])
+ manifest_mod_time = int(manifest_split[1])
manifest_name = manifest_split[2]
manifest_stat = Filestat(manifest_perms, manifest_mod_time,
manifest_name)
@@ -1491,7 +1509,7 @@ def does_image_have_dead_perms(image):
def is_mod_time_old(mod_time):
global UNTAGGED_TRANSITION_SEC
- cutoff_time = long(time.time() * 1000) - UNTAGGED_TRANSITION_SEC * 1000
+ cutoff_time = int(time.time() * 1000) - UNTAGGED_TRANSITION_SEC * 1000
logging.debug("Mod time: %d, Cutoff time: %d", mod_time, cutoff_time)
return mod_time < cutoff_time
@@ -1720,7 +1738,7 @@ def add_parser_default_arguments(parser):
default=37, help="Maximum number of layers an image is
allowed to have")
parser.add_argument("--max-size", type=int, dest='MAX_IMAGE_SIZE',
default=10 * 1024 * 1024 * 1024, help="Maximum size an
image is allowed to be")
- parser.add_argument("--untagged-transition-sec", type=long,
dest='UNTAGGED_TRANSITION_SEC',
+ parser.add_argument("--untagged-transition-sec", type=int,
dest='UNTAGGED_TRANSITION_SEC',
default=7 * 24 * 60 * 60, help="Time that untagged
images will spend in each state"
+ "before moving to the
next one")
parser.add_argument("--dead-perms", type=str, dest='DEAD_PERMS',
diff --git a/bin/test_docker_to_squash.py b/bin/test_docker_to_squash.py
index 0b17ead4ae..42934f703b 100644
--- a/bin/test_docker_to_squash.py
+++ b/bin/test_docker_to_squash.py
@@ -17,6 +17,7 @@
# limitations under the License.
import argparse
+import hashlib
import json
import os
import tempfile
@@ -244,13 +245,46 @@ class Test(TestCase):
mock.patch.object(dtsq, "shell_command",
side_effect=fake_shell_command):
self.assertEqual(1, dtsq.check_dependencies())
- # TODO:
- # def test_read_image_tag_to_hash(self):
- # """
- # The base method behaves differently, since string in python3 is
always unicode. Base method was flips between
- # byte arrays and strings. This may not always work properly in
python3.
- # :return:
- # """
- # image_tag_to_hash = ""
- # hash_to_tags, tag_to_hash =
dtsq.read_image_tag_to_hash(image_tag_to_hash)
+ def test_calculate_bytes_hash_matches_hashlib(self):
+ """
+ Manifest hashes must be computed over the raw manifest bytes, not over
+ str(bytes) (which hashes the literal "b'...'" repr and produces wrong
hashes).
+ """
+ manifest = b'{"schemaVersion":2,"config":{"digest":"sha256:abc"}}'
+ expected = hashlib.sha256(manifest).hexdigest()
+ self.assertEqual(expected, dtsq.calculate_bytes_hash(manifest))
+ # The old code hashed str(manifest); that must NOT equal the real hash.
+ self.assertNotEqual(expected,
dtsq.calculate_string_hash(str(manifest)))
+ # The str helper still agrees with the bytes helper for real text.
+ self.assertEqual(expected,
dtsq.calculate_string_hash(manifest.decode("utf-8")))
+
+ def test_decode_output(self):
+ self.assertEqual("root:root",
dtsq.decode_output(b"root:root\n").strip())
+ self.assertEqual("", dtsq.decode_output(None))
+ self.assertEqual("already text", dtsq.decode_output("already text"))
+
+ def test_read_write_image_tag_to_hash_round_trip(self):
+ """
+ The tag file written by write_local_image_tag_to_hash must read back
+ identically. Before the fix, read_image_tag_to_hash did str(line) on
+ bytes, mangling every entry (e.g. "b'img:hash\\n'") so the hash failed
+ validation and the entry was silently skipped.
+ """
+ manifest_hash = hashlib.sha256(b"fake-manifest").hexdigest()
+ other_hash = hashlib.sha256(b"other-manifest").hexdigest()
+ hash_to_tags = {
+ manifest_hash: (["img:latest", "img:1.0"], ["first upload"]),
+ other_hash: (["img:2.0"], []),
+ }
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ tag_file = os.path.join(tmp_dir, "image-tag-to-hash")
+ dtsq.write_local_image_tag_to_hash(tag_file, hash_to_tags)
+ read_hash_to_tags, read_tag_to_hash =
dtsq.read_image_tag_to_hash(tag_file)
+ self.assertEqual(sorted(["img:1.0", "img:latest"]),
+ sorted(read_hash_to_tags[manifest_hash][0]))
+ self.assertEqual(["first upload"], read_hash_to_tags[manifest_hash][1])
+ self.assertEqual(["img:2.0"], read_hash_to_tags[other_hash][0])
+ self.assertEqual(manifest_hash, read_tag_to_hash["img:latest"])
+ self.assertEqual(manifest_hash, read_tag_to_hash["img:1.0"])
+ self.assertEqual(other_hash, read_tag_to_hash["img:2.0"])