Implement scripts/oe-git-archive
cover Implement scripts/oe-git-archive
This patchset implements a helper script for committing data to git and pushing it into an upstream repository. The new script re-uses some code from oe-build-perf-test script (the code is eventually removed from oe-build-perf-test in the last patch). The script supports flexible (pattern-based) tag and branch naming, and, similarly flexible commit and tag messages. It is also able to directly work with (local) bare repositories.
The first four patches implement the new script. The last two patches takes the script in use in build performance testing scripts.
[YOCTO #10582]
The following changes since commit 68da6c98841f4450736ae170e443aa744c8b77eb:
oeqa/selftest/pkgdata: use m4 instead of bash (2017-02-07 14:48:56 +0000)
are available in the git repository at:
git://git.openembedded.org/openembedded-core-contrib marquiz/fixes-10582
http://git.openembedded.org/openembedded-core-contrib/log/?h=marquiz/fixes-10582
Markus Lehtonen (6):
oeqa.utils.git: add git_dir property
scripts: Implement oe-git-archive oeqa.utils.git: support bare repos scripts/oe-git-archive: support creating bare repositories build-perf-test-wrapper.sh: use oe-git-archive
oe-build-perf-test: drop --commit-results
meta/lib/oeqa/utils/git.py | 20 ++- scripts/contrib/build-perf-test-wrapper.sh | 18 ++- scripts/oe-build-perf-test | 104 ------------ scripts/oe-git-archive | 247 +++++++++++++++++++++++++++++ 4 files changed, 275 insertions(+), 114 deletions(-) create mode 100755 scripts/oe-git-archive
Signature · 1 line
2.10.2
PATCH 1/6 oeqa.utils.git: add git_dir property
[YOCTO #10582]
--- meta/lib/oeqa/utils/git.py | 4 ++++ 1 file changed, 4 insertions(+)
meta/lib/oeqa/utils/git.py +4 -0
@@ -18,6 +18,10 @@ class GitRepo(object): def __init__(self, path, is_topdir=False): self.top_dir = self._run_git_cmd_at(['rev-parse', '--show-toplevel'], path) + git_dir = self._run_git_cmd_at(['rev-parse', '--git-dir'], path) + git_dir = git_dir if os.path.isabs(git_dir) else os.path.join(path, git_dir) + self.git_dir = os.path.realpath(git_dir) + realpath = os.path.realpath(path) if is_topdir and realpath != self.top_dir: raise GitError("{} is not a Git top directory".format(realpath))
Signature · 1 line
2.10.2
PATCH 2/6 scripts: Implement oe-git-archive
In reply to Markus LehtonenA helper script for committing data to git and pushing it upstream. The motivation for the script stems from the need to archiving QA test results in git, but it could be used elsewhere, of course. The script needs to be run under an initialized build environment because it utilizes bitbake configuration information.
[YOCTO #10582]
--- scripts/oe-git-archive | 244 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 244 insertions(+) create mode 100755 scripts/oe-git-archive
scripts/oe-git-archive new file +244 -0
@@ -0,0 +1,244 @@ +#!/usr/bin/python3 +# +# Helper script for committing data to git and pushing upstream +# +# Copyright (c) 2017, Intel Corporation. +# +# This program is free software; you can redistribute it and/or modify it +# under the terms and conditions of the GNU General Public License, +# version 2, as published by the Free Software Foundation. +# +# This program is distributed in the hope it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +# more details. +# +import argparse +import glob +import json +import logging +import math +import os +import re +import sys +from collections import namedtuple, OrderedDict +from datetime import datetime, timedelta, tzinfo +from operator import attrgetter + +# Import oe and bitbake libs +scripts_path = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(os.path.join(scripts_path, 'lib')) +import scriptpath +scriptpath.add_bitbake_lib_path() +scriptpath.add_oe_lib_path() + +from oeqa.utils.git import GitRepo, GitError +from oeqa.utils.metadata import metadata_from_bb + + +# Setup logging +logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") +log = logging.getLogger() + + +class ArchiveError(Exception): + """Internal error handling of this script""" + + +def format_str(string, fields): + """Format string using the given fields (dict)""" + try: + return string.format(**fields) + except KeyError as err: + raise ArchiveError("Unable to expand string '{}': unknown field {} " + "(valid fields are: {})".format( + string, err, ', '.join(sorted(fields.keys())))) + + +def init_git_repo(path, no_create): + """Initialize local Git repository""" + path = os.path.abspath(path) + if os.path.isfile(path): + raise ArchiveError("Invalid Git repo at {}: path exists but is not a " + "directory".format(path)) + if not os.path.isdir(path) or not os.listdir(path): + if no_create: + raise ArchiveError("No git repo at {}, refusing to create " + "one".format(path)) + if not os.path.isdir(path): + try: + os.mkdir(path) + except (FileNotFoundError, PermissionError) as err: + raise ArchiveError("Failed to mkdir {}: {}".format(path, err)) + if not os.listdir(path): + log.info("Initializing a new Git repo at %s", path) + repo = GitRepo.init(path) + try: + repo = GitRepo(path, is_topdir=True) + except GitError: + raise ArchiveError("Non-empty directory that is not a Git repository " + "at {}\nPlease specify an existing Git repository, " + "an empty directory or a non-existing directory " + "path.".format(path)) + return repo + + +def git_commit_data(repo, data_dir, branch, message): + """Commit data into a Git repository""" + log.info("Committing data into to branch %s", branch) + tmp_index = os.path.join(repo.git_dir, 'index.oe-git-archive') + try: + # Create new tree object from the data + env_update = {'GIT_INDEX_FILE': tmp_index, + 'GIT_WORK_TREE': os.path.abspath(data_dir)} + repo.run_cmd('add .', env_update) + tree = repo.run_cmd('write-tree', env_update) + + # Create new commit object from the tree + parent = repo.rev_parse(branch) + git_cmd = ['commit-tree', tree, '-m', message] + if parent: + git_cmd += ['-p', parent] + commit = repo.run_cmd(git_cmd, env_update) + + # Update branch head + git_cmd = ['update-ref', 'refs/heads/' + branch, commit] + if parent: + git_cmd.append(parent) + repo.run_cmd(git_cmd) + + # Update current HEAD, if we're on branch 'branch' + if repo.get_current_branch() == branch: + log.info("Updating %s HEAD to latest commit", repo.top_dir) + repo.run_cmd('reset --hard') + + return commit + finally: + if os.path.exists(tmp_index): + os.unlink(tmp_index) + + +def expand_tag_strings(repo, name_pattern, msg_subj_pattern, msg_body_pattern, + 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 + if 'tag_number' not in keyws: + # Fill in all other fields than 'tag_number' + keyws['tag_number'] = '{tag_number}' + tag_re = format_str(name_pattern, keyws) + # Replace parentheses for proper regex matching + tag_re = tag_re.replace('(', '\(').replace(')', '\)') + '$' + # Inject regex group pattern for 'tag_number' + 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(): + match = re.match(tag_re, existing_tag) + + if match and int(match.group('tag_number')) >= keyws['tag_number']: + keyws['tag_number'] = int(match.group('tag_number')) + 1 + + tag_name = format_str(name_pattern, keyws) + msg_subj= format_str(msg_subj_pattern.strip(), keyws) + msg_body = format_str(msg_body_pattern, keyws) + return tag_name, msg_subj + '\n\n' + msg_body + + +def parse_args(argv): + """Parse command line arguments""" + parser = argparse.ArgumentParser( + description="Commit data to git and push upstream", + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + + parser.add_argument('--debug', '-D', action='store_true', + help="Verbose logging") + parser.add_argument('--git-dir', '-g', required=True, + help="Local git directory to use") + parser.add_argument('--no-create', action='store_true', + help="If GIT_DIR is not a valid Git repository, do not " + "try to create one") + parser.add_argument('--push', '-p', nargs='?', default=False, const=True, + help="Push to remote") + parser.add_argument('--branch-name', '-b', + default='{hostname}/{branch}/{machine}', + help="Git branch name (pattern) to use") + parser.add_argument('--no-tag', action='store_true', + help="Do not create Git tag") + parser.add_argument('--tag-name', '-t', + default='{hostname}/{branch}/{machine}/{commit_count}-g{commit}/{tag_number}', + help="Tag name (pattern) to use") + parser.add_argument('--commit-msg-subject', + default='Results of {branch}:{commit} on {hostname}', + help="Subject line (pattern) to use in the commit message") + parser.add_argument('--commit-msg-body', + default='branch: {branch}\ncommit: {commit}\nhostname: {hostname}', + help="Commit message body (pattern)") + parser.add_argument('--tag-msg-subject', + default='Test run #{tag_number} of {branch}:{commit} on {hostname}', + help="Subject line (pattern) of the tag message") + parser.add_argument('--tag-msg-body', + default='', + help="Tag message body (pattern)") + parser.add_argument('data_dir', metavar='DATA_DIR', + help="Data to commit") + return parser.parse_args(argv) + + +def main(argv=None): + """Script entry point""" + args = parse_args(argv) + if args.debug: + log.setLevel(logging.DEBUG) + + try: + if not os.path.isdir(args.data_dir): + raise ArchiveError("Not a directory: {}".format(args.data_dir)) + + data_repo = init_git_repo(args.git_dir, args.no_create) + + # Get keywords to be used in tag and branch names and messages + metadata = metadata_from_bb() + keywords = {'hostname': metadata['hostname'], + 'branch': metadata['layers']['meta']['branch'], + 'commit': metadata['layers']['meta']['commit'], + 'commit_count': metadata['layers']['meta']['commit_count'], + 'machine': metadata['config']['MACHINE']} + + # Expand strings early in order to avoid getting into inconsistent + # state (e.g. no tag even if data was committed) + commit_msg = format_str(args.commit_msg_subject.strip(), keywords) + commit_msg += '\n\n' + format_str(args.commit_msg_body, keywords) + branch_name = format_str(args.branch_name, keywords) + tag_name = None + if not args.no_tag and args.tag_name: + tag_name, tag_msg = expand_tag_strings(data_repo, args.tag_name, + args.tag_msg_subject, + args.tag_msg_body, keywords) + + # Commit data + commit = git_commit_data(data_repo, args.data_dir, branch_name, + commit_msg) + + # Create tag + if tag_name: + log.info("Creating tag %s", tag_name) + data_repo.run_cmd(['tag', '-a', '-m', tag_msg, tag_name, commit]) + + # Push data to remote + if args.push: + cmd = ['push', '--tags'] + if args.push is not True: + cmd.extend(['--repo', args.push]) + cmd.append(branch_name) + log.info("Pushing data to remote") + data_repo.run_cmd(cmd) + + except ArchiveError as err: + log.error(str(err)) + return 1 + + return 0 + +if __name__ == "__main__": + sys.exit(main())
Signature · 1 line
2.10.2
PATCH 3/6 oeqa.utils.git: support bare repos
In reply to Markus Lehtonen[YOCTO #10582]
--- meta/lib/oeqa/utils/git.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-)
meta/lib/oeqa/utils/git.py +12 -4
@@ -16,12 +16,17 @@ class GitError(Exception): class GitRepo(object): """Class representing a Git repository clone""" def __init__(self, path, is_topdir=False): - self.top_dir = self._run_git_cmd_at(['rev-parse', '--show-toplevel'], - path) git_dir = self._run_git_cmd_at(['rev-parse', '--git-dir'], path) git_dir = git_dir if os.path.isabs(git_dir) else os.path.join(path, git_dir) self.git_dir = os.path.realpath(git_dir) + if self._run_git_cmd_at(['rev-parse', '--is-bare-repository'], path) == 'true': + self.bare = True + self.top_dir = self.git_dir + else: + self.bare = False + self.top_dir = self._run_git_cmd_at(['rev-parse', '--show-toplevel'], + path) realpath = os.path.realpath(path) if is_topdir and realpath != self.top_dir: raise GitError("{} is not a Git top directory".format(realpath))
@@ -40,9 +45,12 @@ class GitRepo(object): return ret.output.strip() @staticmethod - def init(path): + def init(path, bare=False): """Initialize a new Git repository""" - GitRepo._run_git_cmd_at('init', cwd=path) + cmd = ['init'] + if bare: + cmd.append('--bare') + GitRepo._run_git_cmd_at(cmd, cwd=path) return GitRepo(path, is_topdir=True) def run_cmd(self, git_args, env_update=None):
Signature · 1 line
2.10.2
PATCH 4/6 scripts/oe-git-archive: support creating bare repositories
In reply to Markus Lehtonen[YOCTO #10582]
--- scripts/oe-git-archive | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-)
scripts/oe-git-archive +7 -4
@@ -55,7 +55,7 @@ def format_str(string, fields): string, err, ', '.join(sorted(fields.keys())))) -def init_git_repo(path, no_create): +def init_git_repo(path, no_create, bare): """Initialize local Git repository""" path = os.path.abspath(path) if os.path.isfile(path):
@@ -72,7 +72,7 @@ def init_git_repo(path, no_create): raise ArchiveError("Failed to mkdir {}: {}".format(path, err)) if not os.listdir(path): log.info("Initializing a new Git repo at %s", path) - repo = GitRepo.init(path) + repo = GitRepo.init(path, bare) try: repo = GitRepo(path, is_topdir=True) except GitError:
@@ -108,7 +108,7 @@ def git_commit_data(repo, data_dir, branch, message): repo.run_cmd(git_cmd) # Update current HEAD, if we're on branch 'branch' - if repo.get_current_branch() == branch: + if not repo.bare and repo.get_current_branch() == branch: log.info("Updating %s HEAD to latest commit", repo.top_dir) repo.run_cmd('reset --hard')
@@ -158,6 +158,9 @@ def parse_args(argv): parser.add_argument('--no-create', action='store_true', help="If GIT_DIR is not a valid Git repository, do not " "try to create one") + parser.add_argument('--bare', action='store_true', + help="Initialize a bare repository when creating a " + "new one") parser.add_argument('--push', '-p', nargs='?', default=False, const=True, help="Push to remote") parser.add_argument('--branch-name', '-b',
@@ -195,7 +198,7 @@ def main(argv=None): if not os.path.isdir(args.data_dir): raise ArchiveError("Not a directory: {}".format(args.data_dir)) - data_repo = init_git_repo(args.git_dir, args.no_create) + data_repo = init_git_repo(args.git_dir, args.no_create, args.bare) # Get keywords to be used in tag and branch names and messages metadata = metadata_from_bb()
Signature · 1 line
2.10.2
PATCH 5/6 build-perf-test-wrapper.sh: use oe-git-archive
In reply to Markus LehtonenStart to use the new helper script for archiving results data in Git.
[YOCTO #10582]
--- scripts/contrib/build-perf-test-wrapper.sh | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-)
scripts/contrib/build-perf-test-wrapper.sh +12 -6
@@ -48,8 +48,7 @@ while getopts "ha:c:C:w:" opt; do ;; c) commitish=$OPTARG ;; - C) results_repo=`realpath "$OPTARG"` - commit_results=("--commit-results" "$results_repo") + C) results_repo=`realpath -s "$OPTARG"` ;; w) base_dir=`realpath "$OPTARG"` ;;
@@ -130,10 +129,17 @@ fi # Run actual test script oe-build-perf-test --out-dir "$results_dir" \ --globalres-file "$globalres_log" \ - --lock-file "$base_dir/oe-build-perf.lock" \ - "${commit_results[@]}" \ - --commit-results-branch "{tester_host}/{git_branch}/$machine" \ - --commit-results-tag "{tester_host}/{git_branch}/$machine/{git_commit_count}-g{git_commit}/{tag_num}" + --lock-file "$base_dir/oe-build-perf.lock" + +# Commit results to git +if [ -n "$results_repo" ]; then + echo -e "\nArchiving results in $results_repo" + oe-git-archive \ + --git-dir "$results_repo" \ + --branch-name "{hostname}/{branch}/{machine}" \ + --tag-name "{hostname}/{branch}/{machine}/{commit_count}-g{commit}/{tag_number}" \ + "$results_dir" +fi case $? in 1) echo "ERROR: oe-build-perf-test script failed!"
Signature · 1 line
2.10.2
PATCH 6/6 oe-build-perf-test: drop --commit-results
In reply to Markus LehtonenDrop support for committing results into Git repository. The functionality was not directly related to testing and feels unnecessary complication of the script. The functionality has been moved into a separate oe-git-archive script.
[YOCTO #10582]
--- scripts/oe-build-perf-test | 104 --------------------------------------------- 1 file changed, 104 deletions(-)
scripts/oe-build-perf-test +0 -104
@@ -33,7 +33,6 @@ import oeqa.buildperf from oeqa.buildperf import (BuildPerfTestLoader, BuildPerfTestResult, BuildPerfTestRunner, KernelDropCaches) from oeqa.utils.commands import runCmd -from oeqa.utils.git import GitRepo, GitError from oeqa.utils.metadata import metadata_from_bb, write_metadata_file
@@ -74,31 +73,6 @@ def pre_run_sanity_check(): return False return True -def init_git_repo(path): - """Check/create Git repository where to store results""" - path = os.path.abspath(path) - if os.path.isfile(path): - log.error("Invalid Git repo %s: path exists but is not a directory", path) - return False - if not os.path.isdir(path): - try: - os.mkdir(path) - except (FileNotFoundError, PermissionError) as err: - log.error("Failed to mkdir %s: %s", path, err) - return False - if not os.listdir(path): - log.info("Initializing a new Git repo at %s", path) - GitRepo.init(path) - try: - GitRepo(path, is_topdir=True) - except GitError: - log.error("No Git repository but a non-empty directory found at %s.\n" - "Please specify a Git repository, an empty directory or " - "a non-existing directory", path) - return False - return True - - def setup_file_logging(log_file): """Setup loggin to file""" log_dir = os.path.dirname(log_file)
@@ -118,68 +92,6 @@ def archive_build_conf(out_dir): shutil.copytree(src_dir, tgt_dir) -def git_commit_results(repo_dir, results_dir, branch, tag, metadata): - """Commit results into a Git repository""" - repo = GitRepo(repo_dir, is_topdir=True) - distro_branch = metadata['layers']['meta']['branch'] - distro_commit = metadata['layers']['meta']['commit'] - distro_commit_count = metadata['layers']['meta']['commit_count'] - - # Replace keywords - branch = branch.format(git_branch=distro_branch, - tester_host=metadata['hostname']) - - log.info("Committing test results into %s %s", repo_dir, branch) - tmp_index = os.path.join(repo_dir, '.git', 'index.oe-build-perf') - try: - # Create new commit object from the new results - env_update = {'GIT_INDEX_FILE': tmp_index, - 'GIT_WORK_TREE': results_dir} - repo.run_cmd('add .', env_update) - tree = repo.run_cmd('write-tree', env_update) - parent = repo.rev_parse(branch) - msg = "Results of {}:{}\n".format(distro_branch, distro_commit) - git_cmd = ['commit-tree', tree, '-m', msg] - if parent: - git_cmd += ['-p', parent] - commit = repo.run_cmd(git_cmd, env_update) - - # Update branch head - git_cmd = ['update-ref', 'refs/heads/' + branch, commit] - if parent: - git_cmd.append(parent) - repo.run_cmd(git_cmd) - - # Update current HEAD, if we're on branch 'branch' - if repo.get_current_branch() == branch: - log.info("Updating %s HEAD to latest commit", repo_dir) - repo.run_cmd('reset --hard') - - # Create (annotated) tag - if tag: - # Find tags matching the pattern - tag_keywords = dict(git_branch=distro_branch, - git_commit=distro_commit, - git_commit_count=distro_commit_count, - tester_host=metadata['hostname'], - tag_num='[0-9]{1,5}') - tag_re = re.compile(tag.format(**tag_keywords) + '$') - tag_keywords['tag_num'] = 0 - for existing_tag in repo.run_cmd('tag').splitlines(): - if tag_re.match(existing_tag): - tag_keywords['tag_num'] += 1 - - tag = tag.format(**tag_keywords) - msg = "Test run #{} of {}:{}\n".format(tag_keywords['tag_num'], - distro_branch, - distro_commit) - repo.run_cmd(['tag', '-a', '-m', msg, tag, commit]) - - finally: - if os.path.exists(tmp_index): - os.unlink(tmp_index) - - def update_globalres_file(result_obj, filename, metadata): """Write results to globalres csv file""" # Map test names to time and size columns in globalres
@@ -235,15 +147,6 @@ def parse_args(argv): help="Log file of this script") parser.add_argument('--run-tests', nargs='+', metavar='TEST', help="List of tests to run") - parser.add_argument('--commit-results', metavar='GIT_DIR', - type=os.path.abspath, - help="Commit result data to a (local) git repository") - parser.add_argument('--commit-results-branch', metavar='BRANCH', - default="{git_branch}", - help="Commit results to branch BRANCH.") - parser.add_argument('--commit-results-tag', metavar='TAG', - default="{git_branch}/{git_commit_count}-g{git_commit}/{tag_num}", - help="Tag results commit with TAG.") return parser.parse_args(argv)
@@ -266,9 +169,6 @@ def main(argv=None): if not pre_run_sanity_check(): return 1 - if args.commit_results: - if not init_git_repo(args.commit_results): - return 1 # Check our capability to drop caches and ask pass if needed KernelDropCaches.check()
@@ -311,10 +211,6 @@ def main(argv=None): result.write_results_json() if args.globalres_file: update_globalres_file(result, args.globalres_file, metadata) - if args.commit_results: - git_commit_results(args.commit_results, out_dir, - args.commit_results_branch, args.commit_results_tag, - metadata) if result.wasSuccessful(): return 0
Signature · 1 line
2.10.2