Skip to contentSkip to conversation

fetch2: Reorder unpack code to facilitate changes

PATCH New Richard Purdie 1 participant 5 messages Jun 4

lore
Share & tools
lore
#0 lore raw

PATCH 1/5 fetch2: Reorder unpack code to facilitate changes

In order to refactor the function, we need path and unpackdir to be set earlier in the function. This change just moves code to earlier in the function.

---
 lib/bb/fetch2/__init__.py | 29 +++++++++++++++--------------
 1 file changed, 15 insertions(+), 14 deletions(-)
lib/bb/fetch2/__init__.py +15 -14
index 93d8b1820d8..d94f54d1bc5 100644
@@ -1539,6 +1539,21 @@ class FetchMethod(object):
             bb.fatal("Invalid value for 'unpack' parameter for %s: %s" %
                      (file, urldata.parm.get('unpack')))
 
+        path = data.getVar('PATH')
+
+        # If 'subdir' param exists, create a dir and use it as destination for unpack cmd
+        if 'subdir' in urldata.parm:
+            subdir = urldata.parm.get('subdir')
+            if os.path.isabs(subdir):
+                if not os.path.realpath(subdir).startswith(os.path.realpath(rootdir)):
+                    raise UnpackError("subdir argument isn't a subdirectory of unpack root %s" % rootdir, urldata.url)
+                unpackdir = subdir
+            else:
+                unpackdir = os.path.join(rootdir, subdir)
+            bb.utils.mkdirhier(unpackdir)
+        else:
+            unpackdir = rootdir
+
         base, ext = os.path.splitext(file)
         if ext in ['.gz', '.bz2', '.Z', '.xz', '.lz', '.zst']:
             efile = os.path.join(rootdir, os.path.basename(base))
@@ -1614,19 +1629,6 @@ class FetchMethod(object):
                 quoted_datafile = shlex.quote(datafile)
                 cmd = 'ar x %s %s && %s -p -f %s && rm %s' % (shlex.quote(file), quoted_datafile, tar_cmd, quoted_datafile, quoted_datafile)
 
-        # If 'subdir' param exists, create a dir and use it as destination for unpack cmd
-        if 'subdir' in urldata.parm:
-            subdir = urldata.parm.get('subdir')
-            if os.path.isabs(subdir):
-                if not os.path.realpath(subdir).startswith(os.path.realpath(rootdir)):
-                    raise UnpackError("subdir argument isn't a subdirectory of unpack root %s" % rootdir, urldata.url)
-                unpackdir = subdir
-            else:
-                unpackdir = os.path.join(rootdir, subdir)
-            bb.utils.mkdirhier(unpackdir)
-        else:
-            unpackdir = rootdir
-
         if not unpack or not cmd:
             urldata.unpack_tracer.unpack("file-copy", unpackdir)
             # If file == dest, then avoid any copies, as we already put the file into dest!
@@ -1649,7 +1651,6 @@ class FetchMethod(object):
         if not cmd:
             return
 
-        path = data.getVar('PATH')
         if path:
             cmd = "PATH=\"%s\" %s" % (path, cmd)
         bb.note("Unpacking %s to %s/" % (file, unpackdir))
#1 lore raw

PATCH 2/5 fetch: Abstract command execution in unpack()

Make the command execution a function as we need to do this multiple times in some cases.

---
 lib/bb/fetch2/__init__.py | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)
lib/bb/fetch2/__init__.py +6 -4
index d94f54d1bc5..07997946e22 100644
@@ -1554,6 +1554,11 @@ class FetchMethod(object):
         else:
             unpackdir = rootdir
 
+        def _run(cmd):
+            ret = subprocess.call(cmd, preexec_fn=subprocess_setup, shell=True, cwd=unpackdir)
+            if ret != 0:
+                raise UnpackError("Unpack command %s failed with return value %s" % (cmd, ret), urldata.url)
+
         base, ext = os.path.splitext(file)
         if ext in ['.gz', '.bz2', '.Z', '.xz', '.lz', '.zst']:
             efile = os.path.join(rootdir, os.path.basename(base))
@@ -1654,10 +1659,7 @@ class FetchMethod(object):
         if path:
             cmd = "PATH=\"%s\" %s" % (path, cmd)
         bb.note("Unpacking %s to %s/" % (file, unpackdir))
-        ret = subprocess.call(cmd, preexec_fn=subprocess_setup, shell=True, cwd=unpackdir)
-
-        if ret != 0:
-            raise UnpackError("Unpack command %s failed with return value %s" % (cmd, ret), urldata.url)
+        _run(cmd)
 
         if iterate is True:
             iterate_urldata = urldata
#2 lore raw

PATCH 3/5 fetch2: Improve environment handling in unpack()

In reply to Richard Purdie

Rather than putting environment variables into command strings, pass them directly to subprocess.

This adds PATH to the environment to a subprocess call to 'ar' where it was previously missing too so the function is consistent.

---
 lib/bb/fetch2/__init__.py | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
lib/bb/fetch2/__init__.py +5 -4
index 07997946e22..845dd3baab1 100644
@@ -1539,7 +1539,10 @@ class FetchMethod(object):
             bb.fatal("Invalid value for 'unpack' parameter for %s: %s" %
                      (file, urldata.parm.get('unpack')))
 
+        env = os.environ.copy()
         path = data.getVar('PATH')
+        if path:
+            env['PATH'] = path
 
         # If 'subdir' param exists, create a dir and use it as destination for unpack cmd
         if 'subdir' in urldata.parm:
@@ -1555,7 +1558,7 @@ class FetchMethod(object):
             unpackdir = rootdir
 
         def _run(cmd):
-            ret = subprocess.call(cmd, preexec_fn=subprocess_setup, shell=True, cwd=unpackdir)
+            ret = subprocess.call(cmd, preexec_fn=subprocess_setup, shell=True, cwd=unpackdir, env=env)
             if ret != 0:
                 raise UnpackError("Unpack command %s failed with return value %s" % (cmd, ret), urldata.url)
 
@@ -1618,7 +1621,7 @@ class FetchMethod(object):
                 else:
                     cmd = 'rpm2cpio.sh %s | cpio --no-absolute-filenames -id' % (file)
             elif file.endswith('.deb') or file.endswith('.ipk'):
-                output = subprocess.check_output(['ar', '-t', file], preexec_fn=subprocess_setup)
+                output = subprocess.check_output(['ar', '-t', file], preexec_fn=subprocess_setup, env=env)
                 datafile = None
                 valid_datafiles = ('data.tar', 'data.tar.gz', 'data.tar.xz',
                                    'data.tar.zst', 'data.tar.bz2', 'data.tar.lzma')
@@ -1656,8 +1659,6 @@ class FetchMethod(object):
         if not cmd:
             return
 
-        if path:
-            cmd = "PATH=\"%s\" %s" % (path, cmd)
         bb.note("Unpacking %s to %s/" % (file, unpackdir))
         _run(cmd)
 
#3 lore raw

PATCH 4/5 fetch2: Convert parts of unpack() to use parameter lists

In reply to Richard Purdie

The unpack function makes heavy use of shell pipelines but start the conversion to avoid shell=True where possible.

---
 lib/bb/fetch2/__init__.py | 39 +++++++++++++++++++++++----------------
 1 file changed, 23 insertions(+), 16 deletions(-)
lib/bb/fetch2/__init__.py +23 -16
index 845dd3baab1..58359896602 100644
@@ -1558,7 +1558,10 @@ class FetchMethod(object):
             unpackdir = rootdir
 
         def _run(cmd):
-            ret = subprocess.call(cmd, preexec_fn=subprocess_setup, shell=True, cwd=unpackdir, env=env)
+            if isinstance(cmd, str):
+                ret = subprocess.call(cmd, preexec_fn=subprocess_setup, shell=True, cwd=unpackdir, env=env)
+            else:
+                ret = subprocess.call(cmd, preexec_fn=subprocess_setup, cwd=unpackdir, env=env)
             if ret != 0:
                 raise UnpackError("Unpack command %s failed with return value %s" % (cmd, ret), urldata.url)
 
@@ -1570,36 +1573,36 @@ class FetchMethod(object):
         cmd = None
 
         if unpack:
-            tar_cmd = 'tar --extract --no-same-owner'
+            tar_cmd = ['tar', '--extract', '--no-same-owner']
             if 'striplevel' in urldata.parm:
                 striplevel = urldata.parm['striplevel']
                 if not striplevel.isdigit():
                     raise UnpackError("Invalid striplevel parameter: %s" % striplevel, urldata.url)
-                tar_cmd += ' --strip-components=%s' % striplevel
+                tar_cmd.append('--strip-components=%s' % striplevel)
             if file.endswith('.tar'):
-                cmd = '%s -f %s' % (tar_cmd, file)
+                cmd = tar_cmd + ['-f', file]
             elif file.endswith('.tgz') or file.endswith('.tar.gz') or file.endswith('.tar.Z'):
-                cmd = '%s -z -f %s' % (tar_cmd, file)
+                cmd = tar_cmd + ['-z', '-f', file]
             elif file.endswith('.tbz') or file.endswith('.tbz2') or file.endswith('.tar.bz2'):
-                cmd = 'bzip2 -dc %s | %s -f -' % (file, tar_cmd)
+                cmd = 'bzip2 -dc %s | %s -f -' % (file, shlex.join(tar_cmd))
             elif file.endswith('.gz') or file.endswith('.Z') or file.endswith('.z'):
                 cmd = 'gzip -dc %s > %s' % (file, efile)
             elif file.endswith('.bz2'):
                 cmd = 'bzip2 -dc %s > %s' % (file, efile)
             elif file.endswith('.txz') or file.endswith('.tar.xz'):
-                cmd = 'xz -dc %s | %s -f -' % (file, tar_cmd)
+                cmd = 'xz -dc %s | %s -f -' % (file, shlex.join(tar_cmd))
             elif file.endswith('.xz'):
                 cmd = 'xz -dc %s > %s' % (file, efile)
             elif file.endswith('.tar.lz'):
-                cmd = 'lzip -dc %s | %s -f -' % (file, tar_cmd)
+                cmd = 'lzip -dc %s | %s -f -' % (file, shlex.join(tar_cmd))
             elif file.endswith('.lz'):
                 cmd = 'lzip -dc %s > %s' % (file, efile)
             elif file.endswith('.tar.7z'):
-                cmd = '7z x -so %s | %s -f -' % (file, tar_cmd)
+                cmd = '7z x -so %s | %s -f -' % (file, shlex.join(tar_cmd))
             elif file.endswith('.7z'):
                 cmd = '7za x -y %s 1>/dev/null' % file
             elif file.endswith('.tzst') or file.endswith('.tar.zst'):
-                cmd = 'zstd --decompress --stdout %s | %s -f -' % (file, tar_cmd)
+                cmd = 'zstd --decompress --stdout %s | %s -f -' % (file, shlex.join(tar_cmd))
             elif file.endswith('.zst'):
                 cmd = 'zstd --decompress --stdout %s > %s' % (file, efile)
             elif file.endswith('.zip') or file.endswith('.jar'):
@@ -1608,10 +1611,10 @@ class FetchMethod(object):
                 except ValueError as exc:
                     bb.fatal("Invalid value for 'dos' parameter for %s: %s" %
                              (file, urldata.parm.get('dos')))
-                cmd = 'unzip -q -o'
+                cmd = ['unzip', '-q', '-o']
                 if dos:
-                    cmd = '%s -a' % cmd
-                cmd = "%s '%s'" % (cmd, file)
+                    cmd.append('-a')
+                cmd.append(file)
             elif file.endswith('.rpm') or file.endswith('.srpm'):
                 if 'extract' in urldata.parm:
                     unpack_file = urldata.parm.get('extract')
@@ -1634,8 +1637,12 @@ class FetchMethod(object):
                         raise UnpackError("Unable to unpack deb/ipk package - does not contain supported data.tar* file", urldata.url)
                 else:
                     raise UnpackError("Unable to unpack deb/ipk package - could not list contents", urldata.url)
-                quoted_datafile = shlex.quote(datafile)
-                cmd = 'ar x %s %s && %s -p -f %s && rm %s' % (shlex.quote(file), quoted_datafile, tar_cmd, quoted_datafile, quoted_datafile)
+                bb.note("Unpacking %s to %s/" % (file, unpackdir))
+                urldata.unpack_tracer.unpack("archive-extract", unpackdir)
+                _run(['ar', 'x', file, datafile])
+                _run(tar_cmd + ['-p' ,'-f', datafile])
+                os.remove(os.path.join(unpackdir, datafile))
+                return
 
         if not unpack or not cmd:
             urldata.unpack_tracer.unpack("file-copy", unpackdir)
@@ -1652,7 +1659,7 @@ class FetchMethod(object):
                     if urlpath.find("/") != -1:
                         destdir = urlpath.rsplit("/", 1)[0] + '/'
                         bb.utils.mkdirhier("%s/%s" % (unpackdir, destdir))
-                cmd = 'cp --force --preserve=timestamps --no-dereference --recursive -H "%s" "%s"' % (file, destdir)
+                cmd = ['cp', '--force', '--preserve=timestamps', '--no-dereference', '--recursive', '-H', file, destdir]
         else:
             urldata.unpack_tracer.unpack("archive-extract", unpackdir)
 
#4 lore raw

PATCH 5/5 fetch: Improve tar pipeline unpack commands

In reply to Richard Purdie

When originally implemented, tar didn't support many of the compression options so it was easier for the code to use pipelines. tar does support these now, so we can switch to using them.

zstd isn't converted since the --zstd option isn't present in tar v1.30 present on RHEL 8 derived distros.

---
 lib/bb/fetch2/__init__.py | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
lib/bb/fetch2/__init__.py +3 -3
index 58359896602..088136bb627 100644
@@ -1584,17 +1584,17 @@ class FetchMethod(object):
             elif file.endswith('.tgz') or file.endswith('.tar.gz') or file.endswith('.tar.Z'):
                 cmd = tar_cmd + ['-z', '-f', file]
             elif file.endswith('.tbz') or file.endswith('.tbz2') or file.endswith('.tar.bz2'):
-                cmd = 'bzip2 -dc %s | %s -f -' % (file, shlex.join(tar_cmd))
+                cmd = tar_cmd + ['-j', '-f', file]
             elif file.endswith('.gz') or file.endswith('.Z') or file.endswith('.z'):
                 cmd = 'gzip -dc %s > %s' % (file, efile)
             elif file.endswith('.bz2'):
                 cmd = 'bzip2 -dc %s > %s' % (file, efile)
             elif file.endswith('.txz') or file.endswith('.tar.xz'):
-                cmd = 'xz -dc %s | %s -f -' % (file, shlex.join(tar_cmd))
+                cmd = tar_cmd + ['-J', '-f', file]
             elif file.endswith('.xz'):
                 cmd = 'xz -dc %s > %s' % (file, efile)
             elif file.endswith('.tar.lz'):
-                cmd = 'lzip -dc %s | %s -f -' % (file, shlex.join(tar_cmd))
+                cmd = tar_cmd + ['--lzip', '-f', file]
             elif file.endswith('.lz'):
                 cmd = 'lzip -dc %s > %s' % (file, efile)
             elif file.endswith('.tar.7z'):