Skip to contentSkip to conversation

oeqa/utils/gitarchive: fix tag name computation

PATCH In review Alexis Lothoré 1 participant 5 messages Aug 18, 2023 – Aug 23, 2023 1 message not in the archive

lore
Share & tools
lore
#0 lore raw

v2 cover oeqa/utils/gitarchive: fix tag name computation

Hello,
this series brings a fix to a sporadic tag push issue observed in autobuilder. The bug is documented in bugzilla #15140 ([1]). Basically, whenever the autobuilder creates a new tag on test results, it is only aware of "local" tags, which is kind of faulty since used repository is a shallow clone.
A first attempt has been merged a few days ago, but quickly reverted because of a new issue linked to the fact that some use cases involve git repositories without any remote configured, which makes the new git-ls remote strategy fail (detected by Richard, see [2])

V2:
- mutualize ls-remote usage in a "get_tags" helper
- add a fallback case in the helper if no remote is configured (use push url if provided

[1] https://bugzilla.yoctoproject.org/show_bug.cgi?id=15140
[2] https://lore.kernel.org/openembedded-core/16b82ce9979d4a09ad3dc42ebef2cbb85c1729c3.camel@linuxfoundation.org/

Alexis Lothoré (3):
oeqa/selftest: introduce gitarchive tests oeqa/utils/gitarchive: fix tag computation when creating archive oeqa/selftest/gitarchive: add tests about tags lisiting when no remote
is configured

 .../oeqa/selftest/cases/gitarchivetests.py    | 127 ++++++++++++++++++
 meta/lib/oeqa/utils/gitarchive.py             |  36 ++++-
 2 files changed, 159 insertions(+), 4 deletions(-)
 create mode 100644 meta/lib/oeqa/selftest/cases/gitarchivetests.py
Signature · 1 line
2.41.0
#1 lore raw

PATCH v2 1/3 oeqa/selftest: introduce gitarchive tests

From: Alexis Lothoré <[email protected]>

Add a test suite for gitarchive.py. For now, only introduce tests on methods which needs to read existing tags

The tests rely on tmpdirs to create local, "fake" results repository in order to allow basic git commands

---
V2: no change

---
 .../oeqa/selftest/cases/gitarchivetests.py    | 96 +++++++++++++++++++
 1 file changed, 96 insertions(+)
 create mode 100644 meta/lib/oeqa/selftest/cases/gitarchivetests.py
meta/lib/oeqa/selftest/cases/gitarchivetests.py new file +96 -0
new file mode 100644
index 000000000000..4f7acd3311d5
@@ -0,0 +1,96 @@
+#
+# Copyright OpenEmbedded Contributors
+#
+# SPDX-License-Identifier: MIT
+#
+
+import os
+import sys
+basepath = os.path.abspath(os.path.dirname(__file__) + '/../../../../../')
+lib_path = basepath + '/scripts/lib'
+sys.path = sys.path + [lib_path]
+import oeqa.utils.gitarchive as ga
+import tempfile
+import shutil
+import scriptutils
+from oeqa.selftest.case import OESelftestTestCase
+
+logger = scriptutils.logger_create('resulttool')
+
+def create_fake_repository(commit, tag_list=[]):
+    """ Create a testing git directory
+
+    Initialize a simple git repository with one initial commit, and as many
+    tags on this commit as listed in tag_list
+    Returns both git directory path and gitarchive git object
+    If commit is true, fake data will be commited, otherwise it will stay in staging area
+    If commit is true and tag_lsit is non empty, all tags in tag_list will be
+    created on the initial commit
+    Fake remote will also be added to make git ls-remote work
+    """
+    fake_data_file = "fake_data.txt"
+    tempdir = tempfile.mkdtemp(prefix='fake_results.')
+    repo = ga.init_git_repo(tempdir, False, False, logger)
+    repo.run_cmd(["remote", "add", "origin", "."])
+    with open(os.path.join(tempdir, fake_data_file), "w") as fake_data:
+        fake_data.write("Fake data")
+    if commit:
+        repo.run_cmd(["add", fake_data_file])
+        repo.run_cmd(["commit", "-m", "\"Add fake data\""])
+        for tag in tag_list:
+            repo.run_cmd(["tag", tag])
+    
+    return tempdir, repo
+
+def delete_fake_repository(path):
+    shutil.rmtree(path)
+
+def tag_exists(git_obj, target_tag):
+    for tag in git_obj.run_cmd(["tag"]).splitlines():
+        if target_tag == tag:
+            return True
+    return False
+
+class GitArchiveTests(OESelftestTestCase):
+    TEST_BRANCH="main"
+    TEST_COMMIT="0f7d5df"
+    TEST_COMMIT_COUNT="42"
+
+    def test_create_first_test_tag(self):
+        path, git_obj = create_fake_repository(False)
+        keywords = {'commit': self.TEST_COMMIT, 'branch': self.TEST_BRANCH, "commit_count": self.TEST_COMMIT_COUNT}
+        target_tag = f"{self.TEST_BRANCH}/{self.TEST_COMMIT_COUNT}-g{self.TEST_COMMIT}/0"
+
+        ga.gitarchive(path, path, True, False,
+                              "Results of {branch}:{commit}", "branch: {branch}\ncommit: {commit}", "{branch}",
+                              False, "{branch}/{commit_count}-g{commit}/{tag_number}",
+                              'Test run #{tag_number} of {branch}:{commit}', '',
+                              [], [], False, keywords, logger)
+        self.assertTrue(tag_exists(git_obj, target_tag), msg=f"Tag {target_tag} has not been created")
+        delete_fake_repository(path)
+
+    def test_create_second_test_tag(self):
+        first_tag = f"{self.TEST_BRANCH}/{self.TEST_COMMIT_COUNT}-g{self.TEST_COMMIT}/0"
+        second_tag = f"{self.TEST_BRANCH}/{self.TEST_COMMIT_COUNT}-g{self.TEST_COMMIT}/1"
+        keywords = {'commit': self.TEST_COMMIT, 'branch': self.TEST_BRANCH, "commit_count": self.TEST_COMMIT_COUNT}
+
+        path, git_obj = create_fake_repository(True, [first_tag])
+        ga.gitarchive(path, path, True, False,
+                              "Results of {branch}:{commit}", "branch: {branch}\ncommit: {commit}", "{branch}",
+                              False, "{branch}/{commit_count}-g{commit}/{tag_number}",
+                              'Test run #{tag_number} of {branch}:{commit}', '',
+                              [], [], False, keywords, logger)
+        self.assertTrue(tag_exists(git_obj, second_tag), msg=f"Second tag {second_tag} has not been created")
+        delete_fake_repository(path)
+
+    def test_get_revs_on_branch(self):
+        fake_tags_list=["main/10-g0f7d5df/0", "main/10-g0f7d5df/1", "foo/20-g2468f5d/0"]
+        tag_name = "{branch}/{commit_number}-g{commit}/{tag_number}"
+
+        path, git_obj = create_fake_repository(True, fake_tags_list)
+        revs = ga.get_test_revs(logger, git_obj, tag_name, branch="main")
+        self.assertEqual(len(revs), 1)
+        self.assertEqual(revs[0].commit, "0f7d5df")
+        self.assertEqual(len(revs[0].tags), 2)
+        self.assertEqual(revs[0].tags, ['main/10-g0f7d5df/0', 'main/10-g0f7d5df/1'])
+        delete_fake_repository(path)
Signature · 1 line
2.41.0
#2 lore raw

PATCH v2 2/3 oeqa/utils/gitarchive: fix tag computation when creating archive

In reply to Alexis Lothoré

From: Alexis Lothoré <[email protected]>

Sporadic errors have been observed in autobuilder when trying to store new tests results:

error: failed to push some refs to 'push.yoctoproject.org:yocto-testresults'
hint: Updates were rejected because the tag already exists in the remote.

The new tag name is generated by gitarchive based on known tags from the repository (learnt with git tag). In autobuilder case, this repository is a shallow clone, so git tag only returns most recent tags, which mean we could miss some older tags which exist in remote but not locally. In this case, gitarchive will likely create a tag which already exists in remote, and so will fail to push

Fix this tag duplication by using git ls-remote to learn about existing tags instead of git tag. To do so, create a helper ("get_tags") which manages both nominal case (target directory is a git repository with a proper remote) and fallback case (target directory is not from a clone, no remote has been configured)

Fixes [YOCTO #15140]

---
V2:
- mutualize ls-remote usage in a single helper
- add a fallback when no remote is properly configured: use push url if provided

---
 meta/lib/oeqa/utils/gitarchive.py | 36 +++++++++++++++++++++++++++----
 1 file changed, 32 insertions(+), 4 deletions(-)
meta/lib/oeqa/utils/gitarchive.py +32 -4
index 6e8040eb5c96..1a28a09efef7 100644
@@ -100,9 +100,36 @@ def git_commit_data(repo, data_dir, branch, message, exclude, notes, log):
         if os.path.exists(tmp_index):
             os.unlink(tmp_index)
 
+def get_tags(repo, pattern=None, url=None):
+    """ Fetch remote tags from current repository
+
+    A pattern can be provided to filter returned tags list
+    An URL can be provided if local repository has no valid remote configured
+    """
+
+    base_cmd = ['ls-remote', '--refs', '--tags', '-q']
+    cmd = base_cmd.copy()
+
+    # First try to fetch tags from repository configured remote
+    cmd.append('origin')
+    if pattern:
+        cmd.append(pattern)
+    try:
+        tags_refs = repo.run_cmd(cmd)
+    except GitError as e:
+        # If it fails, retry with repository url if one is provided
+        if not url:
+            raise(e)
+        cmd = base_cmd.copy()
+        cmd.append(url)
+        if pattern:
+            cmd.append(pattern)
+        tags_refs = repo.run_cmd(cmd)
+
+    return ["".join(d.split()[1].split('/', 2)[2:]) for d in tags_refs.splitlines()]
 
 def expand_tag_strings(repo, name_pattern, msg_subj_pattern, msg_body_pattern,
-                       keywords):
+                       url, keywords):
     """Generate tag name and message, with support for running id number"""
     keyws = keywords.copy()
     # Tag number is handled specially: if not defined, we autoincrement it
@@ -116,7 +143,7 @@ def expand_tag_strings(repo, name_pattern, msg_subj_pattern, msg_body_pattern,
         tag_re = tag_re.format(tag_number='(?P<tag_number>[0-9]{1,5})')
 
         keyws['tag_number'] = 0
-        for existing_tag in repo.run_cmd('tag').splitlines():
+        for existing_tag in get_tags(repo, url=url):
             match = re.match(tag_re, existing_tag)
 
             if match and int(match.group('tag_number')) >= keyws['tag_number']:
@@ -143,7 +170,8 @@ def gitarchive(data_dir, git_dir, no_create, bare, commit_msg_subject, commit_ms
     if not no_tag and tagname:
         tag_name, tag_msg = expand_tag_strings(data_repo, tagname,
                                                tag_msg_subject,
-                                               tag_msg_body, keywords)
+                                               tag_msg_body,
+                                               push, keywords)
 
     # Commit data
     commit = git_commit_data(data_repo, data_dir, branch_name,
@@ -181,7 +209,7 @@ def get_test_runs(log, repo, tag_name, **kwargs):
 
     # Get a list of all matching tags
     tag_pattern = tag_name.format(**str_fields)
-    tags = repo.run_cmd(['tag', '-l', tag_pattern]).splitlines()
+    tags = get_tags(repo, pattern=tag_pattern)
     log.debug("Found %d tags matching pattern '%s'", len(tags), tag_pattern)
 
     # Parse undefined fields from tag names
Signature · 1 line
2.41.0
#3 lore raw

PATCH v2 3/3 oeqa/selftest/gitarchive: add tests about tags lisiting when no remote is configured

In reply to Alexis Lothoré

From: Alexis Lothoré <[email protected]>

Add specific tests on gitarchive for when tag listing is required but no remote is configured in target directory: it should either succeed if valid url is provided, or fail is url is not provided or wrong

---
 .../oeqa/selftest/cases/gitarchivetests.py    | 35 +++++++++++++++++--
 1 file changed, 33 insertions(+), 2 deletions(-)
meta/lib/oeqa/selftest/cases/gitarchivetests.py +33 -2
index 4f7acd3311d5..11b88daab860 100644
@@ -10,6 +10,7 @@ basepath = os.path.abspath(os.path.dirname(__file__) + '/../../../../../')
 lib_path = basepath + '/scripts/lib'
 sys.path = sys.path + [lib_path]
 import oeqa.utils.gitarchive as ga
+from oeqa.utils.git import GitError
 import tempfile
 import shutil
 import scriptutils
@@ -17,7 +18,7 @@ from oeqa.selftest.case import OESelftestTestCase
 
 logger = scriptutils.logger_create('resulttool')
 
-def create_fake_repository(commit, tag_list=[]):
+def create_fake_repository(commit, tag_list=[], add_remote=True):
     """ Create a testing git directory
 
     Initialize a simple git repository with one initial commit, and as many
@@ -31,7 +32,8 @@ def create_fake_repository(commit, tag_list=[]):
     fake_data_file = "fake_data.txt"
     tempdir = tempfile.mkdtemp(prefix='fake_results.')
     repo = ga.init_git_repo(tempdir, False, False, logger)
-    repo.run_cmd(["remote", "add", "origin", "."])
+    if add_remote:
+        repo.run_cmd(["remote", "add", "origin", "."])
     with open(os.path.join(tempdir, fake_data_file), "w") as fake_data:
         fake_data.write("Fake data")
     if commit:
@@ -94,3 +96,32 @@ class GitArchiveTests(OESelftestTestCase):
         self.assertEqual(len(revs[0].tags), 2)
         self.assertEqual(revs[0].tags, ['main/10-g0f7d5df/0', 'main/10-g0f7d5df/1'])
         delete_fake_repository(path)
+
+    def test_get_tags_without_valid_remote(self):
+        url = 'git://git.yoctoproject.org/poky'
+        path, git_obj = create_fake_repository(False, None, False)
+
+        tags = ga.get_tags(git_obj, pattern="yocto-*", url=url)
+        """Test for some well established tags (released tags)"""
+        self.assertIn("yocto-4.0", tags)
+        self.assertIn("yocto-4.1", tags)
+        self.assertIn("yocto-4.2", tags)
+        delete_fake_repository(path)
+
+    def test_get_tags_without_valid_remote_neither_url(self):
+        url = 'git://git.yoctoproject.org/poky'
+        path, git_obj = create_fake_repository(False, None, False)
+
+        """Test for some well established tags (released tags)"""
+        with self.assertRaises(GitError):
+            tags = ga.get_tags(git_obj, pattern="yocto-*")
+        delete_fake_repository(path)
+
+    def test_get_tags_without_valid_remote_and_wrong_url(self):
+        url = 'git://git.foo.org/bar'
+        path, git_obj = create_fake_repository(False, None, False)
+
+        """Test for some well established tags (released tags)"""
+        with self.assertRaises(GitError):
+            tags = ga.get_tags(git_obj, pattern="yocto-*", url=url)
+        delete_fake_repository(path)
Signature · 1 line
2.41.0

A message that is not in the archive (sent off-list or not yet received): [email protected]

#5 lore raw

Re: [OE-Core][PATCH v2 3/3] oeqa/selftest/gitarchive: add tests about tags lisiting when no remote is configured

Hello Richard,

Quoted 65 lines · Alexis Lothoré via lists.openembedded.org

From: Alexis Lothoré <[email protected]>

Add specific tests on gitarchive for when tag listing is required but no remote is configured in target directory: it should either succeed if valid url is provided, or fail is url is not provided or wrong

---
 .../oeqa/selftest/cases/gitarchivetests.py    | 35 +++++++++++++++++--
 1 file changed, 33 insertions(+), 2 deletions(-)
meta/lib/oeqa/selftest/cases/gitarchivetests.py +23 -2
index 4f7acd3311d5..11b88daab860 100644
@@ -10,6 +10,7 @@ basepath = os.path.abspath(os.path.dirname(__file__) + '/../../../../../')
 lib_path = basepath + '/scripts/lib'
 sys.path = sys.path + [lib_path]
 import oeqa.utils.gitarchive as ga
+from oeqa.utils.git import GitError
 import tempfile
 import shutil
 import scriptutils
@@ -17,7 +18,7 @@ from oeqa.selftest.case import OESelftestTestCase
 
 logger = scriptutils.logger_create('resulttool')
 
-def create_fake_repository(commit, tag_list=[]):
+def create_fake_repository(commit, tag_list=[], add_remote=True):
     """ Create a testing git directory
 
     Initialize a simple git repository with one initial commit, and as many
@@ -31,7 +32,8 @@ def create_fake_repository(commit, tag_list=[]):
     fake_data_file = "fake_data.txt"
     tempdir = tempfile.mkdtemp(prefix='fake_results.')
     repo = ga.init_git_repo(tempdir, False, False, logger)
-    repo.run_cmd(["remote", "add", "origin", "."])
+    if add_remote:
+        repo.run_cmd(["remote", "add", "origin", "."])
     with open(os.path.join(tempdir, fake_data_file), "w") as fake_data:
         fake_data.write("Fake data")
     if commit:
@@ -94,3 +96,32 @@ class GitArchiveTests(OESelftestTestCase):
         self.assertEqual(len(revs[0].tags), 2)
         self.assertEqual(revs[0].tags, ['main/10-g0f7d5df/0', 'main/10-g0f7d5df/1'])
         delete_fake_repository(path)
+
+    def test_get_tags_without_valid_remote(self):
+        url = 'git://git.yoctoproject.org/poky'
+        path, git_obj = create_fake_repository(False, None, False)
+
+        tags = ga.get_tags(git_obj, pattern="yocto-*", url=url)
+        """Test for some well established tags (released tags)"""
+        self.assertIn("yocto-4.0", tags)
+        self.assertIn("yocto-4.1", tags)
+        self.assertIn("yocto-4.2", tags)
+        delete_fake_repository(path)
+
+    def test_get_tags_without_valid_remote_neither_url(self):
+        url = 'git://git.yoctoproject.org/poky'
+        path, git_obj = create_fake_repository(False, None, False)
+
+        """Test for some well established tags (released tags)"""
+        with self.assertRaises(GitError):
+            tags = ga.get_tags(git_obj, pattern="yocto-*")

meta/lib/oeqa/selftest/cases/gitarchivetests.py class GitArchiveTests(OESelftestTestCase): · line 127

Quoted 10 lines
meta/lib/oeqa/selftest/cases/gitarchivetests.py +10 -0
+        delete_fake_repository(path)
+
+    def test_get_tags_without_valid_remote_and_wrong_url(self):
+        url = 'git://git.foo.org/bar'
+        path, git_obj = create_fake_repository(False, None, False)
+
+        """Test for some well established tags (released tags)"""
+        with self.assertRaises(GitError):
+            tags = ga.get_tags(git_obj, pattern="yocto-*", url=url)
+        delete_fake_repository(path)

Now that this v2 has been merged, I observe that the last raised failure is now passed, but a new one occurs a bit later, because I missed some use cases where gitarchive APIs that can be called without a gitarchive object being created before:

https://autobuilder.yoctoproject.org/typhoon/#/builders/133/builds/2125/steps/12/logs/stdio

Sorry for the disturbance, I am working on it right now.

Quoted 10 lines

-=-=-=-=-=-=-=-=-=-=-=-
Links: You receive all messages sent to this group.
View/Reply Online (#186369): https://lists.openembedded.org/g/openembedded-core/message/186369
Mute This Topic: https://lists.openembedded.org/mt/100821194/7394887
Group Owner: [email protected]
Unsubscribe: https://lists.openembedded.org/g/openembedded-core/unsub [[email protected]]
-=-=-=-=-=-=-=-=-=-=-=-

Signature · 3 lines
Alexis Lothoré, Bootlin
Embedded Linux and Kernel engineering
https://bootlin.com