Skip to contentSkip to conversation

fetch2: Add support for upstream source tracing

PATCH Superseded [email protected] 3 participants 5 messages Aug 24, 2023 – Aug 29, 2023

v4 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

PATCH v4 1/3 fetch2: Add support for upstream source tracing

From: Alberto Pianon <[email protected]>

License compliance and SBoM generation require to be able to trace each source file back to its corresponding upstream source. The current implementation of bb.fetch2 makes it difficult, especially when multiple upstream sources are combined together.

This patch provides an interface to solve the issue by implementing a process that unpacks each SRC_URI element into a temporary directory, creates an entrypoint to collect relevant provenance metadata on each source file, moves everything to the recipe rootdir, and saves metadata in a JSON file.

This patch contains required modifications to fetchers' code plus a TraceUnpackBase class that implements the above described process. Data collection logic should be separately implemented by subclassing TraceUnpackBase, implementing _collect_data() and _process_data() methods.

Splitting the above described solution in multiple patches and in multiple modules/classes aims at easing review and merge process, and also at decoupling the development of the data collection logic from the process that enables it.

---
 bin/bitbake-selftest        |   1 +
 lib/bb/fetch2/__init__.py   |  55 +++++++-
 lib/bb/fetch2/crate.py      |   2 +
 lib/bb/fetch2/gitsm.py      |  24 +++-
 lib/bb/fetch2/hg.py         |   1 +
 lib/bb/fetch2/npm.py        |   1 +
 lib/bb/fetch2/npmsw.py      |  25 +++-
 lib/bb/fetch2/trace_base.py | 256 ++++++++++++++++++++++++++++++++++++
 lib/bb/tests/trace_base.py  | 227 ++++++++++++++++++++++++++++++++
 9 files changed, 583 insertions(+), 9 deletions(-)
 create mode 100644 lib/bb/fetch2/trace_base.py
 create mode 100644 lib/bb/tests/trace_base.py
bin/bitbake-selftest +1 -0
index f25f23b1..6d60a5d2 100755
@@ -31,6 +31,7 @@ tests = ["bb.tests.codeparser",
          "bb.tests.runqueue",
          "bb.tests.siggen",
          "bb.tests.utils",
+         "bb.tests.trace_base",
          "bb.tests.compression",
          "hashserv.tests",
          "layerindexlib.tests.layerindexobj",
lib/bb/fetch2/__init__.py +52 -3

102 lines not on this page · raw message

lib/bb/fetch2/crate.py +2 -0
index 3310ed00..68250974 100644
@@ -101,8 +101,10 @@ class Crate(Wget):
         bp = d.getVar('BP')
         if bp == ud.parm.get('name'):
             cmd = "tar -xz --no-same-owner -f %s" % thefile
+            ud.destdir = rootdir
         else:
             cargo_bitbake = self._cargo_bitbake_path(rootdir)
+            ud.destdir = cargo_bitbake
 
             cmd = "tar -xz --no-same-owner -f %s -C %s" % (thefile, cargo_bitbake)
 
lib/bb/fetch2/gitsm.py +23 -1
index 47225b97..ed7ad39e 100644
@@ -34,6 +34,11 @@ class GitSM(Git):
         """
         return ud.type in ['gitsm']
 
+    def urldata_init(self, ud, d):
+        super(GitSM, self).urldata_init(ud, d)
+        ud.module_data = []
+        ud.checkout_destdir = None
+
     def process_submodules(self, ud, workdir, function, d):
         """
         Iterate over all of the submodules in this repository and execute
@@ -144,6 +149,15 @@ class GitSM(Git):
 
             function(ud, url, module, paths[module], workdir, ld)
 
+            if function.__name__ == "unpack_submodules":
+                destdir = os.path.join(ud.checkout_destdir, paths[module])
+                ud.module_data.append({
+                    "url": url,
+                    "destdir": destdir.rstrip("/"),
+                    "parent_destdir": ud.checkout_destdir.rstrip("/"),
+                    "revision": subrevision[module]
+                })
+
         return submodules != []
 
     def need_update(self, ud, d):
@@ -215,9 +229,13 @@ class GitSM(Git):
             else:
                 repo_conf = os.path.join(ud.destdir, '.git')
 
+            checkout_destdir = os.path.join(ud.checkout_destdir, modpath)
+
             try:
                 newfetch = Fetch([url], d, cache=False)
-                newfetch.unpack(root=os.path.dirname(os.path.join(repo_conf, 'modules', module)))
+                newfetch.unpack(root=os.path.dirname(os.path.join(repo_conf, 'modules', module)), is_module=True, checkout_destdir=checkout_destdir)
+                # add nested submodules' data
+                ud.module_data += newfetch.ud[url].module_data
             except Exception as e:
                 logger.error('gitsm: submodule unpack failed: %s %s' % (type(e).__name__, str(e)))
                 raise
@@ -239,6 +257,10 @@ class GitSM(Git):
 
         Git.unpack(self, ud, destdir, d)
 
+        if not ud.checkout_destdir:
+            # for main git repo, checkout destdir corresponds with unpack destdir
+            ud.checkout_destdir = ud.destdir
+
         ret = self.process_submodules(ud, ud.destdir, unpack_submodules, d)
 
         if not ud.bareclone and ret:
lib/bb/fetch2/hg.py +1 -0
index 063e1300..0fd69db7 100644
@@ -242,6 +242,7 @@ class Hg(FetchMethod):
         revflag = "-r %s" % ud.revision
         subdir = ud.parm.get("destsuffix", ud.module)
         codir = "%s/%s" % (destdir, subdir)
+        ud.destdir = codir
 
         scmdata = ud.parm.get("scmdata", "")
         if scmdata != "nokeep":
lib/bb/fetch2/npm.py +1 -0
index f83485ad..4ddb53e7 100644
@@ -298,6 +298,7 @@ class Npm(FetchMethod):
         destsuffix = ud.parm.get("destsuffix", "npm")
         destdir = os.path.join(rootdir, destsuffix)
         npm_unpack(ud.localpath, destdir, d)
+        ud.destdir = destdir
 
     def clean(self, ud, d):
         """Clean any existing full or partial download"""
lib/bb/fetch2/npmsw.py +20 -5
index 4ff2c8ff..2516aef4 100644
@@ -80,6 +80,9 @@ class NpmShrinkWrap(FetchMethod):
     def urldata_init(self, ud, d):
         """Init npmsw specific variables within url data"""
 
+        # initialize module_data (for module source tracing)
+        ud.module_data = []
+
         # Get the 'shrinkwrap' parameter
         ud.shrinkwrap_file = re.sub(r"^npmsw://", "", ud.url.split(";")[0])
 
@@ -192,6 +195,7 @@ class NpmShrinkWrap(FetchMethod):
                 raise ParameterError("Unsupported dependency: %s" % name, ud.url)
 
             ud.deps.append({
+                "name": name,
                 "url": url,
                 "localpath": localpath,
                 "extrapaths": extrapaths,
@@ -266,20 +270,31 @@ class NpmShrinkWrap(FetchMethod):
 
     def unpack(self, ud, rootdir, d):
         """Unpack the downloaded dependencies"""
-        destdir = d.getVar("S")
-        destsuffix = ud.parm.get("destsuffix")
-        if destsuffix:
-            destdir = os.path.join(rootdir, destsuffix)
+        # rootdir param is a temporary dir. The real rootdir, where sources are
+        # moved after being traced, is stored in ud.rootdir.
+        destsuffix = ud.parm.get("destsuffix") or os.path.relpath(d.getVar("S"), ud.rootdir)
+        destdir = os.path.join(rootdir, destsuffix)
+        ud.destdir = destdir
 
         bb.utils.mkdirhier(destdir)
         bb.utils.copyfile(ud.shrinkwrap_file,
                           os.path.join(destdir, "npm-shrinkwrap.json"))
 
+        for dep in ud.deps:
+            dep_destdir = os.path.join(destdir, dep["destsuffix"])
+            dep_parent_destdir = re.sub("/node_modules/"+dep["name"]+"$", "", dep_destdir) # this works also with scoped package names, like @foo/bar
+            ud.module_data.append({
+                "url": dep["url"] or dep["localpath"],
+                "destdir": dep_destdir.rstrip("/"),
+                "parent_destdir": dep_parent_destdir.rstrip("/"),
+                "revision": None
+            })
+
         auto = [dep["url"] for dep in ud.deps if not dep["localpath"]]
         manual = [dep for dep in ud.deps if dep["localpath"]]
 
         if auto:
-            ud.proxy.unpack(destdir, auto)
+            ud.proxy.unpack(destdir, auto, is_module=True)
 
         for dep in manual:
             depdestdir = os.path.join(destdir, dep["destsuffix"])
lib/bb/fetch2/trace_base.py new file +256 -0

257 lines not on this page · raw message

lib/bb/tests/trace_base.py new file +227 -0

227 lines not on this page · raw message

Signature · 1 line
2.34.1
#1 lore raw

PATCH v4 2/3 fetch2: Add metadata collection for upstream source tracing

From: Alberto Pianon <[email protected]>

This patch subclasses TraceUnpackBase by implementing _collect_data() and _process_data() methods, in order to implement upstream metadata collection logic for bb.fetch2.

The final output is a compressed json file, stored in <rootdir>/temp. Data format is described in the help text of the trace module.

---
 lib/bb/fetch2/__init__.py |   4 +-
 lib/bb/fetch2/trace.py    | 535 ++++++++++++++++++++++++++++++++++++++
 2 files changed, 537 insertions(+), 2 deletions(-)
 create mode 100644 lib/bb/fetch2/trace.py
lib/bb/fetch2/__init__.py +2 -2
index aef5fcb4..f15811e5 100644
@@ -28,7 +28,7 @@ import bb.checksum
 import bb.process
 import bb.event
 
-from .trace_base import TraceUnpackBase
+from .trace import TraceUnpack
 
 __version__ = "2"
 _checksum_cache = bb.checksum.FileChecksumCache()
@@ -1877,7 +1877,7 @@ class Fetch(object):
         if is_module:
             destdir = root
         else:
-            trace = TraceUnpackBase(root, self.d)
+            trace = TraceUnpack(root, self.d)
             destdir = trace.tmpdir
 
         for u in urls:
lib/bb/fetch2/trace.py new file +535 -0

535 lines not on this page · raw message

Signature · 1 line
2.34.1
#2 lore raw

PATCH v4 3/3 fetch2: Add tests for upstream source tracing

In reply to [email protected]

Hi,
I submit this third patch by just sending the link to the commit, since the patch contains some big compressed JSON files that would be too large for an email message. From reading tests and test data, you may get what is the final goal/result of this series of patches.

http://cgit.openembedded.org/bitbake-contrib/commit/?h=alpianon/srctrace3&id=43707aefb22c59a6508af04c02219423f42806ba

This series of patches works also with the new format of npm-shrinkwrap.json files, supported by the latest revision of the npmsw fetcher. I included a specific test case also for that one.

Cheers,
Alberto

#3 lore raw
In reply to [email protected]
Quoted 152 lines · On Thu, 2023-08-24 at 17:56 +0200, [email protected] wrote:

From: Alberto Pianon <[email protected]>

License compliance and SBoM generation require to be able to trace each source file back to its corresponding upstream source. The current implementation of bb.fetch2 makes it difficult, especially when multiple upstream sources are combined together.

This patch provides an interface to solve the issue by implementing a process that unpacks each SRC_URI element into a temporary directory, creates an entrypoint to collect relevant provenance metadata on each source file, moves everything to the recipe rootdir, and saves metadata in a JSON file.

This patch contains required modifications to fetchers' code plus a TraceUnpackBase class that implements the above described process. Data collection logic should be separately implemented by subclassing TraceUnpackBase, implementing _collect_data() and _process_data() methods.

Splitting the above described solution in multiple patches and in multiple modules/classes aims at easing review and merge process, and also at decoupling the development of the data collection logic from the process that enables it.

---
 bin/bitbake-selftest        |   1 +
 lib/bb/fetch2/__init__.py   |  55 +++++++-
 lib/bb/fetch2/crate.py      |   2 +
 lib/bb/fetch2/gitsm.py      |  24 +++-
 lib/bb/fetch2/hg.py         |   1 +
 lib/bb/fetch2/npm.py        |   1 +
 lib/bb/fetch2/npmsw.py      |  25 +++-
 lib/bb/fetch2/trace_base.py | 256 ++++++++++++++++++++++++++++++++++++
 lib/bb/tests/trace_base.py  | 227 ++++++++++++++++++++++++++++++++
 9 files changed, 583 insertions(+), 9 deletions(-)
 create mode 100644 lib/bb/fetch2/trace_base.py
 create mode 100644 lib/bb/tests/trace_base.py
bin/bitbake-selftest +1 -0
index f25f23b1..6d60a5d2 100755
@@ -31,6 +31,7 @@ tests = ["bb.tests.codeparser",
          "bb.tests.runqueue",
          "bb.tests.siggen",
          "bb.tests.utils",
+         "bb.tests.trace_base",
          "bb.tests.compression",
          "hashserv.tests",
          "layerindexlib.tests.layerindexobj",
lib/bb/fetch2/__init__.py +45 -3
index e4c1d206..aef5fcb4 100644
@@ -28,6 +28,8 @@ import bb.checksum
 import bb.process
 import bb.event
 
+from .trace_base import TraceUnpackBase
+
 __version__ = "2"
 _checksum_cache = bb.checksum.FileChecksumCache()
 
@@ -1279,6 +1281,7 @@ class FetchData(object):
         if not self.pswd and "pswd" in self.parm:
             self.pswd = self.parm["pswd"]
         self.setup = False
+        self.destdir = None
 
         def configure_checksum(checksum_id):
             if "name" in self.parm:
@@ -1557,6 +1560,8 @@ class FetchMethod(object):
             bb.utils.mkdirhier(unpackdir)
         else:
             unpackdir = rootdir
+        urldata.destdir = unpackdir
+        urldata.is_unpacked_archive = unpack and cmd
 
         if not unpack or not cmd:
             # If file == dest, then avoid any copies, as we already put the file into dest!
@@ -1572,6 +1577,7 @@ class FetchMethod(object):
                     if urlpath.find("/") != -1:
                         destdir = urlpath.rsplit("/", 1)[0] + '/'
                         bb.utils.mkdirhier("%s/%s" % (unpackdir, destdir))
+                        urldata.destdir = "%s/%s" % (unpackdir, destdir)
                 cmd = 'cp -fpPRH "%s" "%s"' % (file, destdir)
 
         if not cmd:
@@ -1855,26 +1861,69 @@ class Fetch(object):
             if not ret:
                 raise FetchError("URL %s doesn't work" % u, u)
 
-    def unpack(self, root, urls=None):
+    def unpack(self, root, urls=None, is_module=False, checkout_destdir=None):
         """
-        Unpack urls to root
+        Unpack urls to a tmp dir, trace, and then move everything to root
+
+        is_module needs to be set to true when this method is recursively called
+        by a fetcher's unpack method to unpack (sub)modules (gitsm, npmsw)
+
+        checkout_destdir needs to be passed when this method is recursively
+        called by gitsm fetcher
         """
 
         if not urls:
             urls = self.urls
+        if is_module:
+            destdir = root
+        else:
+            trace = TraceUnpackBase(root, self.d)
+            destdir = trace.tmpdir
 
         for u in urls:
             ud = self.ud[u]
+            # absolute subdir, destsuffix and subpath params wouldn't work when
+            # unpacking in the tmp dir, convert them to relative paths
+            realroot = os.path.realpath(root)
+            params = [ 'subdir', 'destsuffix', 'subpath' ]
+            for p in params:
+                if not ud.parm.get(p):
+                    continue
+                if os.path.isabs(ud.parm[p]):
+                    realpath = os.path.realpath(ud.parm[p])
+                    if realpath.startswith(realroot):
+                        ud.parm[p] = os.path.relpath(realpath, realroot)
             ud.setup_localpath(self.d)
+            ud.rootdir = root
+
+            if hasattr(ud, "checkout_destdir"):
+                ud.checkout_destdir = checkout_destdir
 
             if ud.lockfile:
                 lf = bb.utils.lockfile(ud.lockfile)
 
-            ud.method.unpack(ud, root, self.d)
+            ud.method.unpack(ud, destdir, self.d)
 
             if ud.lockfile:
                 bb.utils.unlockfile(lf)
 
+            if is_module:
+                continue
+
+            if hasattr(ud, "nocheckout") and ud.nocheckout:
+                logger.warning(
+                    "Can't trace sources for"
+                    " %s because repo has not been checked out" % u)
+            else:
+                trace.commit(u, ud)
+

lib/bb/fetch2/__init__.py class Fetch(object): · line 1929

Quoted 10 lines
lib/bb/fetch2/__init__.py +7 -0
+            trace.move2root()
+
+        if is_module:
+            return
+        trace.write_data()
+        trace.close()
+
     def clean(self, urls=None):
         """
         Clean files that the fetcher gets or places

This patch takes a relatively clean function and adds logic which isn't particularly clear or easy to follow. For example why should the function skip the trace.commit() if it is a module? Surely you need the trace data for modules as well? I guess you collect this differently for things registered as modules?

Other things which concern me:

* backend specific parameters such as nocheckout are now appearing in the core function
* we're switching absolute paths for relative paths for very unclear reasons which will make the code more fragile to changes
* gitsm specific handling is being added to the core

I was willing to accept intercept hooks on this code but this rewrites the code paths and the fetcher behaviour significantly in ways most of our users don't need or want.

Whilst I know I did say to submit it, getting the code 1 working day before feature freeze does also limit my options somewhat in what I can do with it during review.

I'm basically worried that this convolutes the unpack process so badly that nobody is going to be able to follow, maintain or modify this code in future. I know I can barely follow what this is doing and it won't encourage anyone else to touch it :(.

I do understand why you want to do this but I'm not convinced that the project should be taking changes like this for what I personally think are very marginal gains.

I appreciate from some legal perspectives, you feel you absolutely must resolve every file back to every original source but in reality for 99.9% of our users, they just don't need to do this.

This puts me in a really difficult position. I appreciate the work you've put into this and I do see what you want to do but in it's current form, I don't think I'll do the project any favours by accepting it.

I do think there must be a way for improving the interface so that my concerns are alleviated and the risk is pushed to the people enabling it, but without diving into the code myself to try and illustrate that, I'm not sure how I can help us get there.

Cheers,

Richard

#4 lore raw
In reply to [email protected]
Quoted 4 lines · Alberto Pianon via lists.openembedded.org

License compliance and SBoM generation require to be able to trace each source file back to its corresponding upstream source. The current implementation of bb.fetch2 makes it difficult, especially when multiple upstream sources are combined together.

I’ll have a look at the actual patches shortly, but just so that it is clear: this won’t be merged for the next release as it’s invasive, non-trivial, and didn’t arrive in time for review before the freeze.

This isn’t a rejection, but a simple matter of the release cycle. We encourage large and invasive patches to land during M1 or M2 so that they have time to settle in and be proven. The discussion on these patches can happen now so that, assuming they get approved, the patches can be merged after the next release.

Ross