[libvirt] [PATCH v5 00/23] scripts: convert most perl scripts to python

This series is an effort to reduce the number of different languages we use by eliminating most use of perl in favour of python. This aligns with fact that the likely future build system we'll use (meson) is written in python, and that python is much more commonly used/understood by developers these days than perl. With this applied we use perl in a handful of places only: - src/rpc/gendispatch.pl - this is a horrendously large script and very hard to understand/follow. A straight syntax conversion to Python would still leave a hgue and hard to understand/follow script. It really needs a clean room rewrite from scratch, with better structure. - src/rpc/genprotocol.pl - fairly easy to convert, but might be obsolete depending on approach for rewriting gendispatch.pl, so ignored for now - tests/oomtrace.pl - will be purge by the patches that drop OOM handling anyway - tools/wireshark/util/genxdrstub.pl - a very large script, which I haven't got the courage to tackle yet. - cfg.mk/maint.mk - many syntax rules involve regexes which are fed to perl. Decision on what to do with syntax-check rules punted to another time. - build-aux/gitlog-to-changelog - build-aux/useless-if-before-free - Both pulled in from gnulib. Could be rewritten quite easily if desired, but given that we aren't maintainers of them right now, they're ignored as they don't really impact our developers. Note that the check-spacing.py script is significantly slower in Python than in Perl. After researching this it appears there is nothing that can be done. The Perl regex engine is simply much better optimized than the Python one. As previously discussed we need to loook at uncrustify or clang-format or some other tool to validate whitespace formatting. This is ongoing. We can either accept the slow down in the short term or keep the Perl version in the short term. In v5: - Rebased to cope with changes to require VPATH build - Merged the already-ACKd scripts In v4: - Moved all scripts into the scripts/ directory instead of having them scattered around source tree - Use re.search instead of re.match - Don't bother re-compiling regexes In v3: - All scripts comply with all flake8 style rules with exception of E129 visually indented line with same indent as next logical line In v2: - Pulled in patch to hacking file - Converted many more scripts - Forced UTF-8 character set to avoid ascii codec on py3 < 3.7 Daniel P. Berrangé (23): build-aux: rewrite duplicate header checker in Python build-aux: rewrite whitespace checker in Python build-aux: rewrite mock inline checker in Python build-aux: rewrite header ifdef checker in Python src: rewrite ACL permissions checker in Python src: rewrite symfile sorting checker in Python src: rewrite symfile library checker in Python src: rewrite systemtap probe generator in Python src: rewrite systemtap function generator in Python src: rewrite driver name checker in Python src: rewrite driver impl checker in Python src: rewrite ACL rule checker in Python src: rewrite polkit ACL generator in Python src: rewrite remote protocol checker in Python tests: rewrite test argv line wrapper in Python tests: rewrite qemu capability grouper in Python tests: rewrite file access checker in Python docs: rewrite hvsupport.html page generator in python docs: rewrite polkit docs generator in Python docs: move apibuild.py to the scripts/ directory docs: move reformat-news.py to the scripts/ directory docs: move esx_vi_generator.py to the scripts/ directory docs: move hyperv_wmi_generator.py to the scripts/ directory Makefile.am | 33 +- build-aux/check-spacing.pl | 198 ------- build-aux/header-ifdef.pl | 182 ------- build-aux/mock-noinline.pl | 75 --- build-aux/prohibit-duplicate-header.pl | 26 - build-aux/syntax-check.mk | 32 +- docs/Makefile.am | 16 +- docs/genaclperms.pl | 125 ----- docs/hvsupport.pl | 459 ---------------- {docs => scripts}/apibuild.py | 0 scripts/check-aclperms.py | 75 +++ scripts/check-aclrules.py | 263 +++++++++ scripts/check-driverimpls.py | 102 ++++ scripts/check-drivername.py | 114 ++++ scripts/check-file-access.py | 123 +++++ scripts/check-remote-protocol.py | 136 +++++ scripts/check-spacing.py | 229 ++++++++ scripts/check-symfile.py | 80 +++ scripts/check-symsorting.py | 117 ++++ scripts/dtrace2systemtap.py | 143 +++++ {src/esx => scripts}/esx_vi_generator.py | 0 scripts/genaclperms.py | 123 +++++ scripts/genpolkit.py | 122 +++++ scripts/gensystemtap.py | 184 +++++++ scripts/group-qemu-caps.py | 123 +++++ scripts/header-ifdef.py | 231 ++++++++ scripts/hvsupport.py | 504 ++++++++++++++++++ .../hyperv_wmi_generator.py | 0 scripts/mock-noinline.py | 85 +++ scripts/prohibit-duplicate-header.py | 56 ++ {docs => scripts}/reformat-news.py | 0 scripts/test-wrap-argv.py | 170 ++++++ src/Makefile.am | 146 ++--- src/access/Makefile.inc.am | 6 +- src/access/genpolkit.pl | 119 ----- src/admin/Makefile.inc.am | 6 +- src/check-aclperms.pl | 73 --- src/check-aclrules.pl | 252 --------- src/check-driverimpls.pl | 80 --- src/check-drivername.pl | 83 --- src/check-symfile.pl | 70 --- src/check-symsorting.pl | 106 ---- src/dtrace2systemtap.pl | 130 ----- src/esx/Makefile.inc.am | 6 +- src/hyperv/Makefile.inc.am | 5 +- src/rpc/Makefile.inc.am | 1 - src/rpc/gensystemtap.pl | 193 ------- tests/Makefile.am | 3 +- tests/check-file-access.pl | 126 ----- tests/file_access_whitelist.txt | 2 +- tests/group-qemu-caps.pl | 124 ----- tests/test-wrap-argv.pl | 174 ------ tests/testutils.c | 16 +- 53 files changed, 3092 insertions(+), 2755 deletions(-) delete mode 100755 build-aux/check-spacing.pl delete mode 100644 build-aux/header-ifdef.pl delete mode 100644 build-aux/mock-noinline.pl delete mode 100644 build-aux/prohibit-duplicate-header.pl delete mode 100755 docs/genaclperms.pl delete mode 100755 docs/hvsupport.pl rename {docs => scripts}/apibuild.py (100%) create mode 100755 scripts/check-aclperms.py create mode 100755 scripts/check-aclrules.py create mode 100755 scripts/check-driverimpls.py create mode 100644 scripts/check-drivername.py create mode 100755 scripts/check-file-access.py create mode 100644 scripts/check-remote-protocol.py create mode 100755 scripts/check-spacing.py create mode 100755 scripts/check-symfile.py create mode 100755 scripts/check-symsorting.py create mode 100755 scripts/dtrace2systemtap.py rename {src/esx => scripts}/esx_vi_generator.py (100%) create mode 100755 scripts/genaclperms.py create mode 100755 scripts/genpolkit.py create mode 100755 scripts/gensystemtap.py create mode 100755 scripts/group-qemu-caps.py create mode 100644 scripts/header-ifdef.py create mode 100755 scripts/hvsupport.py rename {src/hyperv => scripts}/hyperv_wmi_generator.py (100%) create mode 100644 scripts/mock-noinline.py create mode 100644 scripts/prohibit-duplicate-header.py rename {docs => scripts}/reformat-news.py (100%) create mode 100755 scripts/test-wrap-argv.py delete mode 100755 src/access/genpolkit.pl delete mode 100755 src/check-aclperms.pl delete mode 100755 src/check-aclrules.pl delete mode 100755 src/check-driverimpls.pl delete mode 100755 src/check-drivername.pl delete mode 100755 src/check-symfile.pl delete mode 100755 src/check-symsorting.pl delete mode 100755 src/dtrace2systemtap.pl delete mode 100755 src/rpc/gensystemtap.pl delete mode 100755 tests/check-file-access.pl delete mode 100755 tests/group-qemu-caps.pl delete mode 100755 tests/test-wrap-argv.pl -- 2.21.0

As part of an goal to eliminate Perl from libvirt build tools, rewrite the prohibit-duplicate-header.pl tool in Python. This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same. Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 2 +- build-aux/prohibit-duplicate-header.pl | 26 ------------ build-aux/syntax-check.mk | 4 +- scripts/prohibit-duplicate-header.py | 56 ++++++++++++++++++++++++++ 4 files changed, 59 insertions(+), 29 deletions(-) delete mode 100644 build-aux/prohibit-duplicate-header.pl create mode 100644 scripts/prohibit-duplicate-header.py diff --git a/Makefile.am b/Makefile.am index f758745d91..9471cf7117 100644 --- a/Makefile.am +++ b/Makefile.am @@ -50,7 +50,7 @@ EXTRA_DIST = \ build-aux/header-ifdef.pl \ scripts/minimize-po.py \ build-aux/mock-noinline.pl \ - build-aux/prohibit-duplicate-header.pl \ + scripts/prohibit-duplicate-header.py \ build-aux/syntax-check.mk \ build-aux/useless-if-before-free \ build-aux/vc-list-files \ diff --git a/build-aux/prohibit-duplicate-header.pl b/build-aux/prohibit-duplicate-header.pl deleted file mode 100644 index 4a2ea65665..0000000000 --- a/build-aux/prohibit-duplicate-header.pl +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env perl - -use strict; - -my $file = " "; -my $ret = 0; -my %includes = ( ); -my $lineno = 0; - -while (<>) { - if (not $file eq $ARGV) { - %includes = ( ); - $file = $ARGV; - $lineno = 0; - } - $lineno++; - if (/^# *include *[<"]([^>"]*\.h)[">]/) { - $includes{$1}++; - if ($includes{$1} == 2) { - $ret = 1; - print STDERR "$ARGV:$lineno: $_"; - print STDERR "Do not include a header more than once per file\n"; - } - } -} -exit $ret; diff --git a/build-aux/syntax-check.mk b/build-aux/syntax-check.mk index 427f12fd24..9b6c157029 100644 --- a/build-aux/syntax-check.mk +++ b/build-aux/syntax-check.mk @@ -2153,8 +2153,8 @@ endif # Don't include duplicate header in the source (either *.c or *.h) prohibit-duplicate-header: - $(AM_V_GEN)$(VC_LIST_EXCEPT) | $(GREP) '\.[chx]$$' | xargs \ - $(PERL) -W $(top_srcdir)/build-aux/prohibit-duplicate-header.pl + $(AM_V_GEN)$(VC_LIST_EXCEPT) | $(GREP) '\.[chx]$$' | $(RUNUTF8) xargs \ + $(PYTHON) $(top_srcdir)/scripts/prohibit-duplicate-header.py spacing-check: $(AM_V_GEN)$(VC_LIST) | $(GREP) '\.c$$' | xargs \ diff --git a/scripts/prohibit-duplicate-header.py b/scripts/prohibit-duplicate-header.py new file mode 100644 index 0000000000..dfdfa0bf0b --- /dev/null +++ b/scripts/prohibit-duplicate-header.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python +# +# Copyright (C) 2016-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. + +from __future__ import print_function + +import re +import sys + + +def check_file(filename): + includes = {} + lineno = 0 + errs = False + with open(filename, "r") as fh: + for line in fh: + lineno = lineno + 1 + + headermatch = re.search(r'''^# *include *[<"]([^>"]*\.h)[">]''', line) + if headermatch is not None: + inc = headermatch.group(1) + + if inc in includes: + print("%s:%d: %s" % (filename, lineno, inc), + file=sys.stderr) + errs = True + else: + includes[inc] = True + + return errs + + +ret = 0 + +for filename in sys.argv[1:]: + if check_file(filename): + ret = 1 + +if ret == 1: + print("Do not include a header more than once per file", file=sys.stderr) + +sys.exit(ret) -- 2.21.0

On Mon, Nov 11, 2019 at 02:38:04PM +0000, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the prohibit-duplicate-header.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 2 +- build-aux/prohibit-duplicate-header.pl | 26 ------------ build-aux/syntax-check.mk | 4 +- scripts/prohibit-duplicate-header.py | 56 ++++++++++++++++++++++++++ 4 files changed, 59 insertions(+), 29 deletions(-) delete mode 100644 build-aux/prohibit-duplicate-header.pl create mode 100644 scripts/prohibit-duplicate-header.py
Reviewed-by: Ján Tomko <jtomko@redhat.com> Jano

As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-spacing.pl tool in Python. This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same. Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 2 +- build-aux/check-spacing.pl | 198 -------------------------------- build-aux/syntax-check.mk | 4 +- scripts/check-spacing.py | 229 +++++++++++++++++++++++++++++++++++++ 4 files changed, 232 insertions(+), 201 deletions(-) delete mode 100755 build-aux/check-spacing.pl create mode 100755 scripts/check-spacing.py diff --git a/Makefile.am b/Makefile.am index 9471cf7117..5187ca6cc2 100644 --- a/Makefile.am +++ b/Makefile.am @@ -46,7 +46,7 @@ EXTRA_DIST = \ README.md \ AUTHORS.in \ scripts/augeas-gentest.py \ - build-aux/check-spacing.pl \ + scripts/check-spacing.py \ build-aux/header-ifdef.pl \ scripts/minimize-po.py \ build-aux/mock-noinline.pl \ diff --git a/build-aux/check-spacing.pl b/build-aux/check-spacing.pl deleted file mode 100755 index 33377f3dd3..0000000000 --- a/build-aux/check-spacing.pl +++ /dev/null @@ -1,198 +0,0 @@ -#!/usr/bin/env perl -# -# check-spacing.pl: Report any usage of 'function (..args..)' -# Also check for other syntax issues, such as correct use of ';' -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library. If not, see -# <http://www.gnu.org/licenses/>. - -use strict; -use warnings; - -my $ret = 0; -my $incomment = 0; - -foreach my $file (@ARGV) { - # Per-file variables for multiline Curly Bracket (cb_) check - my $cb_linenum = 0; - my $cb_code = ""; - my $cb_scolon = 0; - - open FILE, $file; - - while (defined (my $line = <FILE>)) { - my $data = $line; - # For temporary modifications - my $tmpdata; - - # Kill any quoted , ; = or " - $data =~ s/'[";,=]'/'X'/g; - - # Kill any quoted strings - $data =~ s,"(?:[^\\\"]|\\.)*","XXX",g; - - next if $data =~ /^#/; - - # Kill contents of multi-line comments - # and detect end of multi-line comments - if ($incomment) { - if ($data =~ m,\*/,) { - $incomment = 0; - $data =~ s,^.*\*/,*/,; - } else { - $data = ""; - } - } - - # Kill single line comments, and detect - # start of multi-line comments - if ($data =~ m,/\*.*\*/,) { - $data =~ s,/\*.*\*/,/* */,; - } elsif ($data =~ m,/\*,) { - $incomment = 1; - $data =~ s,/\*.*,/*,; - } - - # We need to match things like - # - # int foo (int bar, bool wizz); - # foo (bar, wizz); - # - # but not match things like: - # - # typedef int (*foo)(bar wizz) - # - # we can't do this (efficiently) without - # missing things like - # - # foo (*bar, wizz); - # - # We also don't want to spoil the $data so it can be used - # later on. - $tmpdata = $data; - while ($tmpdata =~ /(\w+)\s\((?!\*)/) { - my $kw = $1; - - # Allow space after keywords only - if ($kw =~ /^(?:if|for|while|switch|return)$/) { - $tmpdata =~ s/(?:$kw\s\()/XXX(/; - } else { - print "Whitespace after non-keyword:\n"; - print "$file:$.: $line"; - $ret = 1; - last; - } - } - - # Require whitespace immediately after keywords - if ($data =~ /\b(?:if|for|while|switch|return)\(/) { - print "No whitespace after keyword:\n"; - print "$file:$.: $line"; - $ret = 1; - } - - # Forbid whitespace between )( of a function typedef - if ($data =~ /\(\*\w+\)\s+\(/) { - print "Whitespace between ')' and '(':\n"; - print "$file:$.: $line"; - $ret = 1; - } - - # Forbid whitespace following ( or prior to ) - # but allow whitespace before ) on a single line - # (optionally followed by a semicolon) - if (($data =~ /\s\)/ && not $data =~ /^\s+\);?$/) || - $data =~ /\((?!$)\s/) { - print "Whitespace after '(' or before ')':\n"; - print "$file:$.: $line"; - $ret = 1; - } - - # Forbid whitespace before ";" or ",". Things like below are allowed: - # - # 1) The expression is empty for "for" loop. E.g. - # for (i = 0; ; i++) - # - # 2) An empty statement. E.g. - # while (write(statuswrite, &status, 1) == -1 && - # errno == EINTR) - # ; - # - if ($data =~ /\s[;,]/) { - unless ($data =~ /\S; ; / || - $data =~ /^\s+;/) { - print "Whitespace before semicolon or comma:\n"; - print "$file:$.: $line"; - $ret = 1; - } - } - - # Require EOL, macro line continuation, or whitespace after ";". - # Allow "for (;;)" as an exception. - if ($data =~ /;[^ \\\n;)]/) { - print "Invalid character after semicolon:\n"; - print "$file:$.: $line"; - $ret = 1; - } - - # Require EOL, space, or enum/struct end after comma. - if ($data =~ /,[^ \\\n)}]/) { - print "Invalid character after comma:\n"; - print "$file:$.: $line"; - $ret = 1; - } - - # Require spaces around assignment '=', compounds and '==' - if ($data =~ /[^ ]\b[!<>&|\-+*\/%\^=]?=/ || - $data =~ /=[^= \\\n]/) { - print "Spacing around '=' or '==':\n"; - print "$file:$.: $line"; - $ret = 1; - } - - # One line conditional statements with one line bodies should - # not use curly brackets. - if ($data =~ /^\s*(if|while|for)\b.*\{$/) { - $cb_linenum = $.; - $cb_code = $line; - $cb_scolon = 0; - } - - # We need to check for exactly one semicolon inside the body, - # because empty statements (e.g. with comment only) are - # allowed - if ($cb_linenum == $. - 1 && $data =~ /^[^;]*;[^;]*$/) { - $cb_code .= $line; - $cb_scolon = 1; - } - - if ($data =~ /^\s*}\s*$/ && - $cb_linenum == $. - 2 && - $cb_scolon) { - - print "Curly brackets around single-line body:\n"; - print "$file:$cb_linenum-$.:\n$cb_code$line"; - $ret = 1; - - # There _should_ be no need to reset the values; but to - # keep my inner peace... - $cb_linenum = 0; - $cb_scolon = 0; - $cb_code = ""; - } - } - close FILE; -} - -exit $ret; diff --git a/build-aux/syntax-check.mk b/build-aux/syntax-check.mk index 9b6c157029..d308896b26 100644 --- a/build-aux/syntax-check.mk +++ b/build-aux/syntax-check.mk @@ -2157,8 +2157,8 @@ prohibit-duplicate-header: $(PYTHON) $(top_srcdir)/scripts/prohibit-duplicate-header.py spacing-check: - $(AM_V_GEN)$(VC_LIST) | $(GREP) '\.c$$' | xargs \ - $(PERL) $(top_srcdir)/build-aux/check-spacing.pl || \ + $(AM_V_GEN)$(VC_LIST) | $(GREP) '\.c$$' | $(RUNUTF8) xargs \ + $(PYTHON) $(top_srcdir)/scripts/check-spacing.py || \ { echo '$(ME): incorrect formatting' 1>&2; exit 1; } mock-noinline: diff --git a/scripts/check-spacing.py b/scripts/check-spacing.py new file mode 100755 index 0000000000..6b9f3ec1ba --- /dev/null +++ b/scripts/check-spacing.py @@ -0,0 +1,229 @@ +#!/usr/bin/env python +# +# Copyright (C) 2012-2019 Red Hat, Inc. +# +# check-spacing.pl: Report any usage of 'function (..args..)' +# Also check for other syntax issues, such as correct use of ';' +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. + +from __future__ import print_function + +import re +import sys + + +def check_whitespace(filename): + errs = False + with open(filename, 'r') as fh: + quotedmetaprog = re.compile(r"""'[";,=]'""") + quotedstringprog = re.compile(r'''"(?:[^\\\"]|\\.)*"''') + commentstartprog = re.compile(r'''^(.*)/\*.*$''') + commentendprog = re.compile(r'''^.*\*/(.*)$''') + commentprog = re.compile(r'''^(.*)/\*.*\*/(.*)''') + funcprog = re.compile(r'''(\w+)\s\((?!\*)''') + keywordprog = re.compile( + r'''^.*\b(?:if|for|while|switch|return)\(.*$''') + functypedefprog = re.compile(r'''^.*\(\*\w+\)\s+\(.*$''') + whitespaceprog1 = re.compile(r'''^.*\s\).*$''') + whitespaceprog2 = re.compile(r'''^\s+\);?$''') + whitespaceprog3 = re.compile(r'''^.*\((?!$)\s.*''') + commasemiprog1 = re.compile(r'''.*\s[;,].*''') + commasemiprog2 = re.compile(r'''.*\S; ; .*''') + commasemiprog3 = re.compile(r'''^\s+;''') + semicolonprog = re.compile(r'''.*;[^ \\\n;)].*''') + commaprog = re.compile(r'''.*,[^ \\\n)}].*''') + assignprog1 = re.compile(r'''[^ ]\b[!<>&|\-+*\/%\^=]?=''') + assignprog2 = re.compile(r'''=[^= \\\n]''') + condstartprog = re.compile(r'''^\s*(if|while|for)\b.*\{$''') + statementprog = re.compile(r'''^[^;]*;[^;]*$''') + condendprog = re.compile(r'''^\s*}\s*$''') + + incomment = False + # Per-file variables for multiline Curly Bracket (cb_) check + cb_lineno = 0 + cb_code = "" + cb_scolon = False + + lineno = 0 + for line in fh: + lineno = lineno + 1 + data = line + # For temporary modifications + + # Kill any quoted , ; = or " + data = quotedmetaprog.sub("'X'", data) + + # Kill any quoted strings + data = quotedstringprog.sub('"XXX"', data) + + if data[0] == '#': + continue + + # Kill contents of multi-line comments + # and detect end of multi-line comments + if incomment: + if commentendprog.match(data): + data = commentendprog.sub('*/\2', data) + incomment = False + else: + data = "" + + # Kill single line comments, and detect + # start of multi-line comments + if commentprog.match(data): + data = commentprog.sub(r'''\1/* */\2''', data) + elif commentstartprog.match(data): + data = commentstartprog.sub(r'''\1/*''', data) + incomment = True + + # We need to match things like + # + # int foo (int bar, bool wizz); + # foo (bar, wizz); + # + # but not match things like: + # + # typedef int (*foo)(bar wizz) + # + # we can't do this (efficiently) without + # missing things like + # + # foo (*bar, wizz); + # + for match in funcprog.finditer(data): + kw = match.group(1) + + # Allow space after keywords only + if kw not in ["if", "for", "while", "switch", "return"]: + print("Whitespace after non-keyword:", + file=sys.stderr) + print("%s:%d: %s" % (filename, lineno, line), + file=sys.stderr) + errs = True + break + + # Require whitespace immediately after keywords + if keywordprog.match(data): + print("No whitespace after keyword:", + file=sys.stderr) + print("%s:%d: %s" % (filename, lineno, line), + file=sys.stderr) + errs = True + + # Forbid whitespace between )( of a function typedef + if functypedefprog.match(data): + print("Whitespace between ')' and '(':", + file=sys.stderr) + print("%s:%d: %s" % (filename, lineno, line), + file=sys.stderr) + errs = True + + # Forbid whitespace following ( or prior to ) + # but allow whitespace before ) on a single line + # (optionally followed by a semicolon) + if ((whitespaceprog1.match(data) and + not whitespaceprog2.match(data)) + or whitespaceprog3.match(data)): + print("Whitespace after '(' or before ')':", + file=sys.stderr) + print("%s:%d: %s" % (filename, lineno, line), + file=sys.stderr) + errs = True + + # Forbid whitespace before ";" or ",". Things like + # below are allowed: + # + # 1) The expression is empty for "for" loop. E.g. + # for (i = 0; ; i++) + # + # 2) An empty statement. E.g. + # while (write(statuswrite, &status, 1) == -1 && + # errno == EINTR) + # ; + # + if commasemiprog1.match(data) and not ( + commasemiprog2.match(data) or + commasemiprog3.match(data)): + print("Whitespace before semicolon or comma:", + file=sys.stderr) + print("%s:%d: %s" % (filename, lineno, line), + file=sys.stderr) + errs = True + + # Require EOL, macro line continuation, or whitespace after ";". + # Allow "for (;;)" as an exception. + if semicolonprog.match(data): + print("Invalid character after semicolon:", + file=sys.stderr) + print("%s:%d: %s" % (filename, lineno, line), + file=sys.stderr) + errs = True + + # Require EOL, space, or enum/struct end after comma. + if commaprog.match(data): + print("Invalid character after comma:", + file=sys.stderr) + print("%s:%d: %s" % (filename, lineno, line), + file=sys.stderr) + errs = True + + # Require spaces around assignment '=', compounds and '==' + if assignprog1.match(data) or assignprog2.match(data): + print("Spacing around '=' or '==':", + file=sys.stderr) + print("%s:%d: %s" % (filename, lineno, line), + file=sys.stderr) + errs = True + + # One line conditional statements with one line bodies should + # not use curly brackets. + if condstartprog.match(data): + cb_lineno = lineno + cb_code = line + cb_scolon = False + + # We need to check for exactly one semicolon inside the body, + # because empty statements (e.g. with comment only) are + # allowed + if (cb_lineno == lineno - 1) and statementprog.match(data): + cb_code = cb_code + line + cb_scolon = True + + if (condendprog.match(data) and + (cb_lineno == lineno - 2) and + cb_scolon): + print("Curly brackets around single-line body:", + file=sys.stderr) + print("%s:%d:\n%s%s" % (filename, cb_lineno - lineno, + cb_code, line), + file=sys.stderr) + errs = True + + # There _should_ be no need to reset the values; but to + # keep my inner peace... + cb_lineno = 0 + cb_scolon = False + cb_code = "" + + return errs + + +ret = 0 +for filename in sys.argv[1:]: + if check_whitespace(filename): + ret = 1 + +sys.exit(ret) -- 2.21.0

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-spacing.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
I checked the speed difference mentioned in the cover letter. Old: time ./build-aux/check-spacing.pl `cat ~/src/libvirt/cfiles` real 0m1.423s New: time ./scripts/check-spacing.py `cat cfiles` real 0m5.607s About around there. The script can easily be parallelized though: diff --git a/scripts/check-spacing.py b/scripts/check-spacing.py index 6b9f3ec1ba..f2ce376e80 100755 --- a/scripts/check-spacing.py +++ b/scripts/check-spacing.py @@ -222,8 +222,12 @@ def check_whitespace(filename): ret = 0 -for filename in sys.argv[1:]: - if check_whitespace(filename): - ret = 1 +filenames = sys.argv[1:] +import multiprocessing +pool = multiprocessing.Pool() +results = pool.map(check_whitespace, filenames) +pool.close() +pool.join() +ret = int(any(results)) sys.exit(ret) After that: [:~/src/libvirt] (python3 *) $ time ./scripts/check-spacing.py `cat cfiles` real 0m1.674s user 0m10.506s sys 0m0.041s Which is pretty close to the perl version, but at the cost of more cycles. Not sure how that will play with 'make' job control. I believe the Pool defaults to number of logical host CPUs, which is 8 on my T480s. Going above 4 doesn't seem to make much of a difference in my testing for this case - Cole

On Fri, Nov 15, 2019 at 03:30:15PM -0500, Cole Robinson wrote:
On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-spacing.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
I checked the speed difference mentioned in the cover letter.
Old: time ./build-aux/check-spacing.pl `cat ~/src/libvirt/cfiles` real 0m1.423s
New: time ./scripts/check-spacing.py `cat cfiles` real 0m5.607s
About around there. The script can easily be parallelized though:
diff --git a/scripts/check-spacing.py b/scripts/check-spacing.py index 6b9f3ec1ba..f2ce376e80 100755 --- a/scripts/check-spacing.py +++ b/scripts/check-spacing.py @@ -222,8 +222,12 @@ def check_whitespace(filename):
ret = 0 -for filename in sys.argv[1:]: - if check_whitespace(filename): - ret = 1 +filenames = sys.argv[1:] +import multiprocessing +pool = multiprocessing.Pool() +results = pool.map(check_whitespace, filenames) +pool.close() +pool.join() +ret = int(any(results))
sys.exit(ret)
After that:
[:~/src/libvirt] (python3 *) $ time ./scripts/check-spacing.py `cat cfiles`
real 0m1.674s user 0m10.506s sys 0m0.041s
Which is pretty close to the perl version, but at the cost of more cycles. Not sure how that will play with 'make' job control. I believe the Pool defaults to number of logical host CPUs, which is 8 on my T480s. Going above 4 doesn't seem to make much of a difference in my testing for this case
FWIW, I always run with "make -j 8 syntax-check" so while this will speed up the job when run individually, it won't help a full syntax check as then it'll be competing with the other syntx checks that are running in parallel. I'd already said I'd drop this check previously but mistakenly re-posted it in this v5. Regards, Daniel -- |: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|

As part of an goal to eliminate Perl from libvirt build tools, rewrite the mock-noinline.pl tool in Python. This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same. Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 2 +- build-aux/mock-noinline.pl | 75 --------------------------------- build-aux/syntax-check.mk | 4 +- scripts/mock-noinline.py | 85 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 88 insertions(+), 78 deletions(-) delete mode 100644 build-aux/mock-noinline.pl create mode 100644 scripts/mock-noinline.py diff --git a/Makefile.am b/Makefile.am index 5187ca6cc2..d9369c9197 100644 --- a/Makefile.am +++ b/Makefile.am @@ -49,7 +49,7 @@ EXTRA_DIST = \ scripts/check-spacing.py \ build-aux/header-ifdef.pl \ scripts/minimize-po.py \ - build-aux/mock-noinline.pl \ + scripts/mock-noinline.py \ scripts/prohibit-duplicate-header.py \ build-aux/syntax-check.mk \ build-aux/useless-if-before-free \ diff --git a/build-aux/mock-noinline.pl b/build-aux/mock-noinline.pl deleted file mode 100644 index b005b8d95e..0000000000 --- a/build-aux/mock-noinline.pl +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env perl - -my %noninlined; -my %mocked; - -# Functions in public header don't get the noinline annotation -# so whitelist them here -$noninlined{"virEventAddTimeout"} = 1; -# This one confuses the script as its defined in the mock file -# but is actually just a local helper -$noninlined{"virMockStatRedirect"} = 1; - -foreach my $arg (@ARGV) { - if ($arg =~ /\.h$/) { - #print "Scan header $arg\n"; - &scan_annotations($arg); - } elsif ($arg =~ /mock\.c$/) { - #print "Scan mock $arg\n"; - &scan_overrides($arg); - } -} - -my $warned = 0; -foreach my $func (keys %mocked) { - next if exists $noninlined{$func}; - - $warned++; - print STDERR "$func is mocked at $mocked{$func} but missing noinline annotation\n"; -} - -exit $warned ? 1 : 0; - - -sub scan_annotations { - my $file = shift; - - open FH, $file or die "cannot read $file: $!"; - - my $func; - while (<FH>) { - if (/^\s*(\w+)\(/ || /^(?:\w+\*?\s+)+(?:\*\s*)?(\w+)\(/) { - my $name = $1; - if ($name !~ /(?:G_GNUC|ATTRIBUTE)/) { - $func = $name; - } - } elsif (/^\s*$/) { - $func = undef; - } - if (/G_GNUC_NO_INLINE/) { - if (defined $func) { - $noninlined{$func} = 1; - } - } - } - - close FH -} - -sub scan_overrides { - my $file = shift; - - open FH, $file or die "cannot read $file: $!"; - - my $func; - while (<FH>) { - if (/^(\w+)\(/ || /^\w+\s*(?:\*\s*)?(\w+)\(/) { - my $name = $1; - if ($name =~ /^vir/) { - $mocked{$name} = "$file:$."; - } - } - } - - close FH -} diff --git a/build-aux/syntax-check.mk b/build-aux/syntax-check.mk index d308896b26..0cfd181224 100644 --- a/build-aux/syntax-check.mk +++ b/build-aux/syntax-check.mk @@ -2162,8 +2162,8 @@ spacing-check: { echo '$(ME): incorrect formatting' 1>&2; exit 1; } mock-noinline: - $(AM_V_GEN)$(VC_LIST) | $(GREP) '\.[ch]$$' | xargs \ - $(PERL) $(top_srcdir)/build-aux/mock-noinline.pl + $(AM_V_GEN)$(VC_LIST) | $(GREP) '\.[ch]$$' | $(RUNUTF8) xargs \ + $(PYTHON) $(top_srcdir)/scripts/mock-noinline.py header-ifdef: $(AM_V_GEN)$(VC_LIST) | $(GREP) '\.[h]$$' | xargs \ diff --git a/scripts/mock-noinline.py b/scripts/mock-noinline.py new file mode 100644 index 0000000000..2770ea1238 --- /dev/null +++ b/scripts/mock-noinline.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright (C) 2017-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. + +from __future__ import print_function + +import re +import sys + +noninlined = {} +mocked = {} + +# Functions in public header don't get the noinline annotation +# so whitelist them here +noninlined["virEventAddTimeout"] = True +# This one confuses the script as its defined in the mock file +# but is actually just a local helper +noninlined["virMockStatRedirect"] = True + + +def scan_annotations(filename): + with open(filename, "r") as fh: + func = None + for line in fh: + line = line.strip() + m = re.search(r'''^\s*(\w+)\(''', line) + if m is None: + m = re.search(r'''^(?:\w+\*?\s+)+(?:\*\s*)?(\w+)\(''', line) + if m is not None: + name = m.group(1) + if name.find("ATTRIBUTE") == -1 and name.find("G_GNUC_") == -1: + func = name + elif line == "": + func = None + + if line.find("G_GNUC_NO_INLINE") != -1: + if func is not None: + noninlined[func] = True + + +def scan_overrides(filename): + with open(filename, "r") as fh: + lineno = 0 + for line in fh: + lineno = lineno + 1 + + m = re.search(r'''^(\w+)\(''', line) + if m is None: + m = re.search(r'''^\w+\s*(?:\*\s*)?(\w+)\(''', line) + if m is not None: + name = m.group(1) + if name.startswith("vir"): + mocked[name] = "%s:%d" % (filename, lineno) + + +for filename in sys.argv[1:]: + if filename.endswith(".h"): + scan_annotations(filename) + elif filename.endswith("mock.c"): + scan_overrides(filename) + +warned = False +for func in mocked.keys(): + if func not in noninlined: + warned = True + print("%s is mocked at %s but missing noinline annotation" % + (func, mocked[func]), file=sys.stderr) + +if warned: + sys.exit(1) +sys.exit(0) -- 2.21.0

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the mock-noinline.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com>
Verified it catches a single failure case Tested-by: Cole Robinson <crobinso@redhat.com> - Cole

On Mon, Nov 11, 2019 at 02:38:06PM +0000, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the mock-noinline.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 2 +- build-aux/mock-noinline.pl | 75 --------------------------------- build-aux/syntax-check.mk | 4 +- scripts/mock-noinline.py | 85 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 88 insertions(+), 78 deletions(-) delete mode 100644 build-aux/mock-noinline.pl create mode 100644 scripts/mock-noinline.py
diff --git a/scripts/mock-noinline.py b/scripts/mock-noinline.py new file mode 100644 index 0000000000..2770ea1238 --- /dev/null +++ b/scripts/mock-noinline.py @@ -0,0 +1,85 @@
+# Functions in public header don't get the noinline annotation +# so whitelist them here +noninlined["virEventAddTimeout"] = True +# This one confuses the script as its defined in the mock file +# but is actually just a local helper +noninlined["virMockStatRedirect"] = True + + +def scan_annotations(filename): + with open(filename, "r") as fh: + func = None + for line in fh: + line = line.strip() + m = re.search(r'''^\s*(\w+)\(''', line) + if m is None: + m = re.search(r'''^(?:\w+\*?\s+)+(?:\*\s*)?(\w+)\(''', line) + if m is not None: + name = m.group(1) + if name.find("ATTRIBUTE") == -1 and name.find("G_GNUC_") == -1: + func = name
More readable as: if "ATTRIBUTE" not in name and "G_GNUC_" not in name:
+ elif line == "":
If you use line.isspace() here, you don't need to strip the whitespace above.
+ func = None + + if line.find("G_GNUC_NO_INLINE") != -1:
if "G_GNUC_NO_INLINE" in line:
+ if func is not None: + noninlined[func] = True + +
Reviewed-by: Ján Tomko <jtomko@redhat.com> Jano

As part of an goal to eliminate Perl from libvirt build tools, rewrite the header-ifdef.pl tool in Python. This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same. Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 2 +- build-aux/header-ifdef.pl | 182 ------------------------------ build-aux/syntax-check.mk | 4 +- scripts/header-ifdef.py | 231 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 234 insertions(+), 185 deletions(-) delete mode 100644 build-aux/header-ifdef.pl create mode 100644 scripts/header-ifdef.py diff --git a/Makefile.am b/Makefile.am index d9369c9197..6cccbf38da 100644 --- a/Makefile.am +++ b/Makefile.am @@ -47,7 +47,7 @@ EXTRA_DIST = \ AUTHORS.in \ scripts/augeas-gentest.py \ scripts/check-spacing.py \ - build-aux/header-ifdef.pl \ + scripts/header-ifdef.py \ scripts/minimize-po.py \ scripts/mock-noinline.py \ scripts/prohibit-duplicate-header.py \ diff --git a/build-aux/header-ifdef.pl b/build-aux/header-ifdef.pl deleted file mode 100644 index dba3dbcbdc..0000000000 --- a/build-aux/header-ifdef.pl +++ /dev/null @@ -1,182 +0,0 @@ -#!/usr/bin/perl -# -# Validate that header files follow a standard layout: -# -# /* -# ...copyright header... -# */ -# <one blank line> -# #pragma once -# ....content.... -# -#--- -# -# For any file ending priv.h, before the #pragma once -# We will have a further section -# -# #ifndef SYMBOL_ALLOW -# # error .... -# #endif /* SYMBOL_ALLOW */ -# <one blank line> -# -#--- -# -# For public headers (files in include/), use the standard header guard instead of #pragma once: -# #ifndef SYMBOL -# # define SYMBOL -# ....content.... -# #endif /* SYMBOL */ - -use strict; -use warnings; - -my $STATE_COPYRIGHT_COMMENT = 0; -my $STATE_COPYRIGHT_BLANK = 1; -my $STATE_PRIV_START = 2; -my $STATE_PRIV_ERROR = 3; -my $STATE_PRIV_END = 4; -my $STATE_PRIV_BLANK = 5; -my $STATE_GUARD_START = 6; -my $STATE_GUARD_DEFINE = 7; -my $STATE_GUARD_END = 8; -my $STATE_EOF = 9; -my $STATE_PRAGMA = 10; - -my $file = " "; -my $ret = 0; -my $ifdef = ""; -my $ifdefpriv = ""; -my $publicheader = 0; - -my $state = $STATE_EOF; -my $mistake = 0; - -sub mistake { - my $msg = shift; - warn $msg; - $mistake = 1; - $ret = 1; -} - -while (<>) { - if (not $file eq $ARGV) { - if ($state == $STATE_COPYRIGHT_COMMENT) { - &mistake("$file: missing copyright comment"); - } elsif ($state == $STATE_COPYRIGHT_BLANK) { - &mistake("$file: missing blank line after copyright header"); - } elsif ($state == $STATE_PRIV_START) { - &mistake("$file: missing '#ifndef $ifdefpriv'"); - } elsif ($state == $STATE_PRIV_ERROR) { - &mistake("$file: missing '# error ...priv allow...'"); - } elsif ($state == $STATE_PRIV_END) { - &mistake("$file: missing '#endif /* $ifdefpriv */'"); - } elsif ($state == $STATE_PRIV_BLANK) { - &mistake("$file: missing blank line after priv header check"); - } elsif ($state == $STATE_GUARD_START) { - if ($publicheader) { - &mistake("$file: missing '#ifndef $ifdef'"); - } else { - &mistake("$file: missing '#pragma once' header guard"); - } - } elsif ($state == $STATE_GUARD_DEFINE) { - &mistake("$file: missing '# define $ifdef'"); - } elsif ($state == $STATE_GUARD_END) { - &mistake("$file: missing '#endif /* $ifdef */'"); - } - - $ifdef = uc $ARGV; - $ifdef =~ s,.*/,,; - $ifdef =~ s,[^A-Z0-9],_,g; - $ifdef =~ s,__+,_,g; - unless ($ifdef =~ /^LIBVIRT_/ && $ARGV !~ /libvirt_internal.h/) { - $ifdef = "LIBVIRT_" . $ifdef; - } - $ifdefpriv = $ifdef . "_ALLOW"; - - $file = $ARGV; - $state = $STATE_COPYRIGHT_COMMENT; - $mistake = 0; - $publicheader = ($ARGV =~ /include\//); - } - - if ($mistake || - $ARGV =~ /config-post\.h$/ || - $ARGV =~ /vbox_(CAPI|XPCOM)/) { - $state = $STATE_EOF; - next; - } - - if ($state == $STATE_COPYRIGHT_COMMENT) { - if (m,\*/,) { - $state = $STATE_COPYRIGHT_BLANK; - } - } elsif ($state == $STATE_COPYRIGHT_BLANK) { - if (! /^$/) { - &mistake("$file: missing blank line after copyright header"); - } - if ($ARGV =~ /priv\.h$/) { - $state = $STATE_PRIV_START; - } else { - $state = $STATE_GUARD_START; - } - } elsif ($state == $STATE_PRIV_START) { - if (/^$/) { - &mistake("$file: too many blank lines after copyright header"); - } elsif (/#ifndef $ifdefpriv$/) { - $state = $STATE_PRIV_ERROR; - } else { - &mistake("$file: missing '#ifndef $ifdefpriv'"); - } - } elsif ($state == $STATE_PRIV_ERROR) { - if (/# error ".*"$/) { - $state = $STATE_PRIV_END; - } else { - &mistake("$file: missing '# error ...priv allow...'"); - } - } elsif ($state == $STATE_PRIV_END) { - if (m,#endif /\* $ifdefpriv \*/,) { - $state = $STATE_PRIV_BLANK; - } else { - &mistake("$file: missing '#endif /* $ifdefpriv */'"); - } - } elsif ($state == $STATE_PRIV_BLANK) { - if (! /^$/) { - &mistake("$file: missing blank line after priv guard"); - } - $state = $STATE_GUARD_START; - } elsif ($state == $STATE_GUARD_START) { - if (/^$/) { - &mistake("$file: too many blank lines after copyright header"); - } - if ($publicheader) { - if (/#ifndef $ifdef$/) { - $state = $STATE_GUARD_DEFINE; - } else { - &mistake("$file: missing '#ifndef $ifdef'"); - } - } else { - if (/#pragma once/) { - $state = $STATE_PRAGMA; - } else { - &mistake("$file: missing '#pragma once' header guard"); - } - } - } elsif ($state == $STATE_GUARD_DEFINE) { - if (/# define $ifdef$/) { - $state = $STATE_GUARD_END; - } else { - &mistake("$file: missing '# define $ifdef'"); - } - } elsif ($state == $STATE_GUARD_END) { - if (m,#endif /\* $ifdef \*/$,) { - $state = $STATE_EOF; - } - } elsif ($state == $STATE_PRAGMA) { - next; - } elsif ($state == $STATE_EOF) { - die "$file: unexpected content after '#endif /* $ifdef */'"; - } else { - die "$file: unexpected state $state"; - } -} -exit $ret; diff --git a/build-aux/syntax-check.mk b/build-aux/syntax-check.mk index 0cfd181224..016e05e7a2 100644 --- a/build-aux/syntax-check.mk +++ b/build-aux/syntax-check.mk @@ -2166,8 +2166,8 @@ mock-noinline: $(PYTHON) $(top_srcdir)/scripts/mock-noinline.py header-ifdef: - $(AM_V_GEN)$(VC_LIST) | $(GREP) '\.[h]$$' | xargs \ - $(PERL) $(top_srcdir)/build-aux/header-ifdef.pl + $(AM_V_GEN)$(VC_LIST) | $(GREP) '\.[h]$$' | $(RUNUTF8) xargs \ + $(PYTHON) $(top_srcdir)/scripts/header-ifdef.py test-wrap-argv: $(AM_V_GEN)$(VC_LIST) | $(GREP) -E '\.(ldargs|args)' | xargs \ diff --git a/scripts/header-ifdef.py b/scripts/header-ifdef.py new file mode 100644 index 0000000000..94c2882225 --- /dev/null +++ b/scripts/header-ifdef.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python +# +# Copyright (C) 2018-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# +# Validate that header files follow a standard layout: +# +# /* +# ...copyright header... +# */ +# <one blank line> +# #pragma once +# ....content.... +# +# --- +# +# For any file ending priv.h, before the #pragma once +# We will have a further section +# +# #ifndef SYMBOL_ALLOW +# # error .... +# #endif /* SYMBOL_ALLOW */ +# <one blank line> +# +# --- +# +# For public headers (files in include/), use the standard +# header guard instead of #pragma once: +# #ifndef SYMBOL +# # define SYMBOL +# ....content.... +# #endif /* SYMBOL */ + +from __future__ import print_function + +import os.path +import re +import sys + +STATE_COPYRIGHT_COMMENT = 0 +STATE_COPYRIGHT_BLANK = 1 +STATE_PRIV_START = 2 +STATE_PRIV_ERROR = 3 +STATE_PRIV_END = 4 +STATE_PRIV_BLANK = 5 +STATE_GUARD_START = 6 +STATE_GUARD_DEFINE = 7 +STATE_GUARD_END = 8 +STATE_EOF = 9 +STATE_PRAGMA = 10 + + +def check_header(filename): + ifdef = "" + ifdefpriv = "" + + state = STATE_EOF + + ifdef = os.path.basename(filename).upper() + ifdef = re.sub(r"""[^A-Z0-9]""", "_", ifdef) + ifdef = re.sub(r"""__+""", "_", ifdef) + + if (not ifdef.startswith("LIBVIRT_") or + filename.find("libvirt_internal.h") != -1): + ifdef = "LIBVIRT_" + ifdef + + ifdefpriv = ifdef + "_ALLOW" + + state = STATE_COPYRIGHT_COMMENT + publicheader = False + if filename.find("include/") != -1: + publicheader = True + + with open(filename, "r") as fh: + for line in fh: + line = line.rstrip("\n") + if state == STATE_COPYRIGHT_COMMENT: + if line.find("*/") != -1: + state = STATE_COPYRIGHT_BLANK + elif state == STATE_COPYRIGHT_BLANK: + if line != "": + print("%s: missing blank line after copyright header" % + filename, file=sys.stderr) + return True + + if filename.endswith("priv.h"): + state = STATE_PRIV_START + else: + state = STATE_GUARD_START + elif state == STATE_PRIV_START: + if line == "": + print("%s: too many blank lines after copyright header" % + filename, file=sys.stderr) + return True + elif re.search(r"""#ifndef %s$""" % ifdefpriv, line): + state = STATE_PRIV_ERROR + else: + print("%s: missing '#ifndef %s'" % (filename, ifdefpriv), + file=sys.stderr) + return True + elif state == STATE_PRIV_ERROR: + if re.search(r"""# error ".*"$""", line): + state = STATE_PRIV_END + else: + print("%s: missing '# error ...priv allow...'" % + filename, file=sys.stderr) + return True + elif state == STATE_PRIV_END: + if re.search(r"""#endif /\* %s \*/""" % ifdefpriv, line): + state = STATE_PRIV_BLANK + else: + print("%s: missing '#endif /* %s */'" % + (filename, ifdefpriv), file=sys.stderr) + return True + elif state == STATE_PRIV_BLANK: + if line != "": + print("%s: missing blank line after priv guard" % + filename, file=sys.stderr) + return True + state = STATE_GUARD_START + elif state == STATE_GUARD_START: + if line == "": + print("%s: too many blank lines after copyright header" % + filename, file=sys.stderr) + return True + if publicheader: + if re.search(r"""#ifndef %s$""" % ifdef, line): + state = STATE_GUARD_DEFINE + else: + print("%s: missing '#ifndef %s'" % + (filename, ifdef), file=sys.stderr) + return True + else: + if re.search(r"""#pragma once""", line): + state = STATE_PRAGMA + else: + print("%s: missing '#pragma once' header guard" % + filename, file=sys.stderr) + return True + elif state == STATE_GUARD_DEFINE: + if re.search(r"""# define %s$""" % ifdef, line): + state = STATE_GUARD_END + else: + print("%s: missing '# define %s'" % + (filename, ifdef), file=sys.stderr) + return True + elif state == STATE_GUARD_END: + if re.search(r"""#endif /\* %s \*/$""" % ifdef, line): + state = STATE_EOF + elif state == STATE_PRAGMA: + next + elif state == STATE_EOF: + print("%s: unexpected content after '#endif /* %s */'" % + (filename, ifdef), file=sys.stderr) + return True + else: + print("%s: unexpected state $state" % + filename, file=sys.stderr) + return True + + if state == STATE_COPYRIGHT_COMMENT: + print("%s: missing copyright comment" % + filename, file=sys.stderr) + return True + elif state == STATE_COPYRIGHT_BLANK: + print("%s: missing blank line after copyright header" % + filename, file=sys.stderr) + return True + elif state == STATE_PRIV_START: + print("%s: missing '#ifndef %s'" % + (filename, ifdefpriv), file=sys.stderr) + return True + elif state == STATE_PRIV_ERROR: + print("%s: missing '# error ...priv allow...'" % + filename, file=sys.stderr) + return True + elif state == STATE_PRIV_END: + print("%s: missing '#endif /* %s */'" % + (filename, ifdefpriv), file=sys.stderr) + return True + elif state == STATE_PRIV_BLANK: + print("%s: missing blank line after priv header check" % + filename, file=sys.stderr) + return True + elif state == STATE_GUARD_START: + if publicheader: + print("%s: missing '#ifndef %s'" % + (filename, ifdef), file=sys.stderr) + return True + else: + print("%s: missing '#pragma once' header guard" % + filename, file=sys.stderr) + return True + elif state == STATE_GUARD_DEFINE: + print("%s: missing '# define %s'" % + (filename, ifdef), file=sys.stderr) + return True + elif state == STATE_GUARD_END: + print("%s: missing '#endif /* %s */'" % + (filename, ifdef), file=sys.stderr) + return True + + return False + + +ret = 0 + +for filename in sys.argv[1:]: + if filename.find("config-post.h") != -1: + continue + if filename.find("vbox_CAPI") != -1: + continue + if filename.find("vbox_XPCOM") != -1: + continue + if check_header(filename): + ret = 1 + +sys.exit(ret) -- 2.21.0

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the header-ifdef.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 2 +- build-aux/header-ifdef.pl | 182 ------------------------------ build-aux/syntax-check.mk | 4 +- scripts/header-ifdef.py | 231 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 234 insertions(+), 185 deletions(-) delete mode 100644 build-aux/header-ifdef.pl create mode 100644 scripts/header-ifdef.py
I verified it catches all 3 errors described in the top comment Tested-by: Cole Robinson <crobinso@redhat.com> - Cole

On Mon, Nov 11, 2019 at 02:38:07PM +0000, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the header-ifdef.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 2 +- build-aux/header-ifdef.pl | 182 ------------------------------ build-aux/syntax-check.mk | 4 +- scripts/header-ifdef.py | 231 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 234 insertions(+), 185 deletions(-) delete mode 100644 build-aux/header-ifdef.pl create mode 100644 scripts/header-ifdef.py
+ if filename.find("include/") != -1: + publicheader = True + + with open(filename, "r") as fh: + for line in fh: + line = line.rstrip("\n")
The stripping was not present in the perl version.
+ if state == STATE_COPYRIGHT_COMMENT: + if line.find("*/") != -1:
Same comment about find vs in here.
+ state = STATE_COPYRIGHT_BLANK + elif state == STATE_COPYRIGHT_BLANK: + if line != "": + print("%s: missing blank line after copyright header" % + filename, file=sys.stderr) + return True +
Reviewed-by: Ján Tomko <jtomko@redhat.com> Jano

As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-aclperms.pl tool in Python. This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same. Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-aclperms.py | 75 +++++++++++++++++++++++++++++++++++++++ src/Makefile.am | 4 +-- src/check-aclperms.pl | 73 ------------------------------------- 4 files changed, 78 insertions(+), 75 deletions(-) create mode 100755 scripts/check-aclperms.py delete mode 100755 src/check-aclperms.pl diff --git a/Makefile.am b/Makefile.am index 6cccbf38da..ab9d09fcd4 100644 --- a/Makefile.am +++ b/Makefile.am @@ -46,6 +46,7 @@ EXTRA_DIST = \ README.md \ AUTHORS.in \ scripts/augeas-gentest.py \ + scripts/check-aclperms.py \ scripts/check-spacing.py \ scripts/header-ifdef.py \ scripts/minimize-po.py \ diff --git a/scripts/check-aclperms.py b/scripts/check-aclperms.py new file mode 100755 index 0000000000..b1084a3758 --- /dev/null +++ b/scripts/check-aclperms.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# +# Copyright (C) 2013-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# +# This script just validates that the stringified version of +# a virAccessPerm enum matches the enum constant name. We do +# a lot of auto-generation of code, so when these don't match +# problems occur, preventing auth from succeeding at all. + +from __future__ import print_function + +import re +import sys + +if len(sys.argv) != 3: + print("syntax: %s HEADER IMPL" % (sys.argv[0]), file=sys.stderr) + sys.exit(1) + +hdr = sys.argv[1] +impl = sys.argv[2] + +perms = {} + +with open(hdr) as fh: + for line in fh: + symmatch = re.search(r"^\s+VIR_ACCESS_PERM_([_A-Z]+)(,?|\s|$)", line) + if symmatch is not None: + perm = symmatch.group(1) + + if not perm.endswith("_LAST"): + perms[perm] = 1 + +warned = False + +with open(impl) as fh: + group = None + + for line in fh: + symlastmatch = re.search(r"VIR_ACCESS_PERM_([_A-Z]+)_LAST", line) + if symlastmatch is not None: + group = symlastmatch.group(1) + elif re.search(r'''"[_a-z]+"''', line) is not None: + bits = line.split(",") + for bit in bits: + m = re.search(r'''"([_a-z]+)"''', bit) + if m is not None: + perm = (group + "_" + m.group(1)).upper() + if perm not in perms: + print("Unknown perm string %s for group %s" % + (m.group(1), group), file=sys.stderr) + warned = True + + del perms[perm] + +for perm in perms.keys(): + print("Perm %s had not string form" % perm, file=sys.stderr) + warned = True + +if warned: + sys.exit(1) +sys.exit(0) diff --git a/src/Makefile.am b/src/Makefile.am index 9b0a46702b..318dd6c20f 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -353,11 +353,11 @@ check-aclrules: $(addprefix $(srcdir)/,$(filter-out /%,$(STATEFUL_DRIVER_SOURCE_FILES))) check-aclperms: - $(AM_V_GEN)$(PERL) $(srcdir)/check-aclperms.pl \ + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(top_srcdir)/scripts/check-aclperms.py \ $(srcdir)/access/viraccessperm.h \ $(srcdir)/access/viraccessperm.c -EXTRA_DIST += check-driverimpls.pl check-aclrules.pl check-aclperms.pl +EXTRA_DIST += check-driverimpls.pl check-aclrules.pl check-local: check-protocol check-symfile check-symsorting \ check-drivername check-driverimpls check-aclrules \ diff --git a/src/check-aclperms.pl b/src/check-aclperms.pl deleted file mode 100755 index 55b6598313..0000000000 --- a/src/check-aclperms.pl +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env perl -# -# Copyright (C) 2013 Red Hat, Inc. -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library. If not, see -# <http://www.gnu.org/licenses/>. -# -# This script just validates that the stringified version of -# a virAccessPerm enum matches the enum constant name. We do -# a lot of auto-generation of code, so when these don't match -# problems occur, preventing auth from succeeding at all. - -my $hdr = shift; -my $impl = shift; - -my %perms; - -my @perms; - -open HDR, $hdr or die "cannot read $hdr: $!"; - -while (<HDR>) { - if (/^\s+VIR_ACCESS_PERM_([_A-Z]+)(,?|\s|$)/) { - my $perm = $1; - - $perms{$perm} = 1 unless ($perm =~ /_LAST$/); - } -} - -close HDR; - - -open IMPL, $impl or die "cannot read $impl: $!"; - -my $group; -my $warned = 0; - -while (defined (my $line = <IMPL>)) { - if ($line =~ /VIR_ACCESS_PERM_([_A-Z]+)_LAST/) { - $group = $1; - } elsif ($line =~ /"[_a-z]+"/) { - my @bits = split /,/, $line; - foreach my $bit (@bits) { - if ($bit =~ /"([_a-z]+)"/) { - my $perm = uc($group . "_" . $1); - if (!exists $perms{$perm}) { - print STDERR "Unknown perm string $1 for group $group\n"; - $warned = 1; - } - delete $perms{$perm}; - } - } - } -} -close IMPL; - -foreach my $perm (keys %perms) { - print STDERR "Perm $perm had not string form\n"; - $warned = 1; -} - -exit $warned; -- 2.21.0

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-aclperms.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-aclperms.py | 75 +++++++++++++++++++++++++++++++++++++++ src/Makefile.am | 4 +-- src/check-aclperms.pl | 73 ------------------------------------- 4 files changed, 78 insertions(+), 75 deletions(-) create mode 100755 scripts/check-aclperms.py delete mode 100755 src/check-aclperms.pl
I verified changing the name of a string permission in viraccessperm.c triggers the first error. not sure if the second one at the end of the file is even triggerable due to compile time protections, but it's still safe to have Tested-by: Cole Robinson <crobinso@redhat.com> - Cole

On Mon, Nov 11, 2019 at 02:38:08PM +0000, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools,
I just realized all of these say "an goal" in the commit message.
rewrite the check-aclperms.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-aclperms.py | 75 +++++++++++++++++++++++++++++++++++++++ src/Makefile.am | 4 +-- src/check-aclperms.pl | 73 ------------------------------------- 4 files changed, 78 insertions(+), 75 deletions(-) create mode 100755 scripts/check-aclperms.py delete mode 100755 src/check-aclperms.pl
Reviewed-by: Ján Tomko <jtomko@redhat.com> Jano

As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-symsorting.pl tool in Python. This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same. Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-symsorting.py | 117 ++++++++++++++++++++++++++++++++++++ src/Makefile.am | 4 +- src/admin/Makefile.inc.am | 2 +- src/check-symsorting.pl | 106 -------------------------------- 5 files changed, 121 insertions(+), 109 deletions(-) create mode 100755 scripts/check-symsorting.py delete mode 100755 src/check-symsorting.pl diff --git a/Makefile.am b/Makefile.am index ab9d09fcd4..b98c932ff7 100644 --- a/Makefile.am +++ b/Makefile.am @@ -48,6 +48,7 @@ EXTRA_DIST = \ scripts/augeas-gentest.py \ scripts/check-aclperms.py \ scripts/check-spacing.py \ + scripts/check-symsorting.py \ scripts/header-ifdef.py \ scripts/minimize-po.py \ scripts/mock-noinline.py \ diff --git a/scripts/check-symsorting.py b/scripts/check-symsorting.py new file mode 100755 index 0000000000..a6de8df9ec --- /dev/null +++ b/scripts/check-symsorting.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python + +# Copyright (C) 2012-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. + +from __future__ import print_function + +import os.path +import re +import sys + +if len(sys.argv) < 3: + print("syntax: %s SRCDIR SYMFILE..." % sys.argv[0], file=sys.stderr) + sys.exit(1) + + +def check_sorting(group, symfile, line, groupfile, lastgroup): + sortedgroup = sorted(group, key=str.lower) + issorted = True + first = None + last = None + + err = False + # Check that groups are in order and groupfile exists + if lastgroup is not None and lastgroup.lower() > groupfile.lower(): + print("Symbol block at %s:%s: block not sorted" % + (symfile, line), file=sys.stderr) + print("Move %s block before %s block" % + (groupfile, lastgroup), file=sys.stderr) + print("", file=sys.stderr) + err = True + + if not os.path.exists(os.path.join(srcdir, groupfile)): + print("Symbol block at %s:%s: %s not found" % + (symfile, line, groupfile), file=sys.stderr) + print("", file=sys.stderr) + err = True + + # Check that symbols within a group are in order + for i in range(len(group)): + if sortedgroup[i] != group[i]: + if first is None: + first = i + + last = i + issorted = False + + if not issorted: + actual = group[first:(last-first+1)] + expect = sortedgroup[first:(last-first+1)] + print("Symbol block at %s:%s: symbols not sorted" % + (symfile, line), file=sys.stderr) + for g in actual: + print(" %s" % g, file=sys.stderr) + print("Correct ordering", file=sys.stderr) + for g in expect: + print(" %s" % g, file=sys.stderr) + print("", file=sys.stderr) + err = True + + return err + + +ret = 0 +srcdir = sys.argv[1] +lastgroup = None +for symfile in sys.argv[2:]: + with open(symfile, "r") as fh: + lineno = 0 + groupfile = "" + group = [] + thisline = 0 + + for line in fh: + thisline = thisline + 1 + line = line.strip() + + filenamematch = re.search(r'''^#\s*((\w+\/)*(\w+\.h))\s*$''', line) + if filenamematch is not None: + groupfile = filenamematch.group(1) + elif line == "": + if len(group) > 0: + if check_sorting(group, symfile, lineno, + groupfile, lastgroup): + ret = 1 + + group = [] + lineno = thisline + lastgroup = groupfile + elif line[0] == '#': + # Ignore comments + pass + else: + line = line.strip(";") + group.append(line) + + if len(group) > 0: + if check_sorting(group, symfile, lineno, + groupfile, lastgroup): + ret = 1 + + lastgroup = None + +sys.exit(ret) diff --git a/src/Makefile.am b/src/Makefile.am index 318dd6c20f..41cfd79ad3 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -283,9 +283,9 @@ else ! WITH_LINUX check-symfile: endif ! WITH_LINUX check-symsorting: - $(AM_V_GEN)$(PERL) $(srcdir)/check-symsorting.pl \ + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(top_srcdir)/scripts/check-symsorting.py \ $(srcdir) $(SYM_FILES) -EXTRA_DIST += check-symfile.pl check-symsorting.pl +EXTRA_DIST += check-symfile.pl # Keep this list synced with RPC_PROBE_FILES PROTOCOL_STRUCTS = \ diff --git a/src/admin/Makefile.inc.am b/src/admin/Makefile.inc.am index 3feb23aa20..97048df6f3 100644 --- a/src/admin/Makefile.inc.am +++ b/src/admin/Makefile.inc.am @@ -112,7 +112,7 @@ check-admin-symfile: endif ! WITH_LINUX check-admin-symsorting: - $(AM_V_GEN)$(PERL) $(srcdir)/check-symsorting.pl \ + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(top_srcdir)/scripts/check-symsorting.py \ $(srcdir) $(ADMIN_SYM_FILES) check-admin-drivername: diff --git a/src/check-symsorting.pl b/src/check-symsorting.pl deleted file mode 100755 index 51e38bdedb..0000000000 --- a/src/check-symsorting.pl +++ /dev/null @@ -1,106 +0,0 @@ -#!/usr/bin/env perl - -# Copyright (C) 2012-2013 Red Hat, Inc. -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library. If not, see -# <http://www.gnu.org/licenses/>. - -use strict; -use warnings; - -die "syntax: $0 SRCDIR SYMFILE..." unless int(@ARGV) >= 2; - -my $ret = 0; -my $srcdir = shift; -my $lastgroup = undef; -foreach my $symfile (@ARGV) { - open SYMFILE, $symfile or die "cannot read $symfile: $!"; - - my $line = 0; - my $groupfile = ""; - my @group; - - while (<SYMFILE>) { - chomp; - - if (/^#\s*((\w+\/)*(\w+\.h))\s*$/) { - $groupfile = $1; - } elsif (/^#/) { - # Ignore comments - } elsif (/^\s*$/) { - if (@group) { - &check_sorting(\@group, $symfile, $line, $groupfile); - } - @group = (); - $line = $.; - } else { - $_ =~ s/;//; - push @group, $_; - } - } - - close SYMFILE; - if (@group) { - &check_sorting(\@group, $symfile, $line, $groupfile); - } - $lastgroup = undef; -} - -sub check_sorting { - my $group = shift; - my $symfile = shift; - my $line = shift; - my $groupfile = shift; - - my @group = @{$group}; - my @sorted = sort { lc $a cmp lc $b } @group; - my $sorted = 1; - my $first; - my $last; - - # Check that groups are in order and groupfile exists - if (defined $lastgroup && lc $lastgroup ge lc $groupfile) { - print "Symbol block at $symfile:$line: block not sorted\n"; - print "Move $groupfile block before $lastgroup block\n"; - print "\n"; - $ret = 1; - } - if (! -e "$srcdir/$groupfile") { - print "Symbol block at $symfile:$line: $groupfile not found\n"; - print "\n"; - $ret = 1; - } - $lastgroup = $groupfile; - - # Check that symbols within a group are in order - for (my $i = 0 ; $i <= $#sorted ; $i++) { - if ($sorted[$i] ne $group[$i]) { - $first = $i unless defined $first; - $last = $i; - $sorted = 0; - } - } - if (!$sorted) { - @group = splice @group, $first, ($last-$first+1); - @sorted = splice @sorted, $first, ($last-$first+1); - print "Symbol block at $symfile:$line: symbols not sorted\n"; - print map { " " . $_ . "\n" } @group; - print "Correct ordering\n"; - print map { " " . $_ . "\n" } @sorted; - print "\n"; - $ret = 1; - } -} - -exit $ret; -- 2.21.0

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-symsorting.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-symsorting.py | 117 ++++++++++++++++++++++++++++++++++++ src/Makefile.am | 4 +- src/admin/Makefile.inc.am | 2 +- src/check-symsorting.pl | 106 -------------------------------- 5 files changed, 121 insertions(+), 109 deletions(-) create mode 100755 scripts/check-symsorting.py delete mode 100755 src/check-symsorting.pl
I verified this catches out of order libvirt_private.syms Tested-by: Cole Robinson <crobinso@redhat.com> - Cole

On Mon, Nov 11, 2019 at 02:38:09PM +0000, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-symsorting.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-symsorting.py | 117 ++++++++++++++++++++++++++++++++++++ src/Makefile.am | 4 +- src/admin/Makefile.inc.am | 2 +- src/check-symsorting.pl | 106 -------------------------------- 5 files changed, 121 insertions(+), 109 deletions(-) create mode 100755 scripts/check-symsorting.py delete mode 100755 src/check-symsorting.pl
Reviewed-by: Ján Tomko <jtomko@redhat.com> Jano

As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-symfile.pl tool in Python. This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same. Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-symfile.py | 80 +++++++++++++++++++++++++++++++++++++++ src/Makefile.am | 5 +-- src/admin/Makefile.inc.am | 4 +- src/check-symfile.pl | 70 ---------------------------------- 5 files changed, 85 insertions(+), 75 deletions(-) create mode 100755 scripts/check-symfile.py delete mode 100755 src/check-symfile.pl diff --git a/Makefile.am b/Makefile.am index b98c932ff7..1c7b8045c2 100644 --- a/Makefile.am +++ b/Makefile.am @@ -48,6 +48,7 @@ EXTRA_DIST = \ scripts/augeas-gentest.py \ scripts/check-aclperms.py \ scripts/check-spacing.py \ + scripts/check-symfile.py \ scripts/check-symsorting.py \ scripts/header-ifdef.py \ scripts/minimize-po.py \ diff --git a/scripts/check-symfile.py b/scripts/check-symfile.py new file mode 100755 index 0000000000..a543a0fbcd --- /dev/null +++ b/scripts/check-symfile.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python +# +# Copyright (C) 2012-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. + +from __future__ import print_function + +import re +import subprocess +import sys + +if len(sys.argv) < 3: + print("syntax: %s SYMFILE ELFLIB(S)" % sys.argv[0], file=sys.stderr) + +symfile = sys.argv[1] +elflibs = sys.argv[2:] + +wantsyms = {} +gotsyms = {} + +ret = 0 + +with open(symfile, "r") as fh: + for line in fh: + line = line.strip() + if line.find("{") != -1: + continue + if line.find("}") != -1: + continue + if line in ["global:", "local:"]: + continue + if line == "": + continue + if line[0] == '#': + continue + if line.find("*") != -1: + continue + + line = line.strip(";") + + if line in wantsyms: + print("Symbol $1 is listed twice", file=sys.stderr) + ret = 1 + else: + wantsyms[line] = True + +for elflib in elflibs: + nm = subprocess.Popen(["nm", elflib], shell=False, + stdout=subprocess.PIPE).stdout + + for line in nm: + line = line.decode("utf-8") + symmatch = re.search(r'''^\S+\s(?:[TBD])\s(\S+)\s*$''', line) + if symmatch is None: + continue + + gotsyms[symmatch.group(1)] = True + + +for sym in wantsyms.keys(): + if sym in gotsyms: + continue + + print("Expected symbol '%s' is not in ELF library" % sym, file=sys.stderr) + ret = 1 + +sys.exit(ret) diff --git a/src/Makefile.am b/src/Makefile.am index 41cfd79ad3..929eef784c 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -277,15 +277,14 @@ PDWTAGS = \ # rule for libvirt.la. However, checking symbols relies on Linux ELF layout if WITH_LINUX check-symfile: libvirt.syms libvirt.la - $(AM_V_GEN)$(PERL) $(srcdir)/check-symfile.pl libvirt.syms \ - .libs/libvirt.so + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(top_srcdir)/scripts/check-symfile.py \ + libvirt.syms .libs/libvirt.so else ! WITH_LINUX check-symfile: endif ! WITH_LINUX check-symsorting: $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(top_srcdir)/scripts/check-symsorting.py \ $(srcdir) $(SYM_FILES) -EXTRA_DIST += check-symfile.pl # Keep this list synced with RPC_PROBE_FILES PROTOCOL_STRUCTS = \ diff --git a/src/admin/Makefile.inc.am b/src/admin/Makefile.inc.am index 97048df6f3..a02991df68 100644 --- a/src/admin/Makefile.inc.am +++ b/src/admin/Makefile.inc.am @@ -105,8 +105,8 @@ libvirt_admin_la_CFLAGS = \ if WITH_LINUX check-admin-symfile: admin/libvirt_admin.syms libvirt-admin.la - $(AM_V_GEN)$(PERL) $(srcdir)/check-symfile.pl admin/libvirt_admin.syms \ - .libs/libvirt-admin.so + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(top_srcdir)/scripts/check-symfile.py \ + admin/libvirt_admin.syms .libs/libvirt-admin.so else ! WITH_LINUX check-admin-symfile: endif ! WITH_LINUX diff --git a/src/check-symfile.pl b/src/check-symfile.pl deleted file mode 100755 index 4f88300864..0000000000 --- a/src/check-symfile.pl +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env perl - -# Copyright (C) 2012-2013 Red Hat, Inc. -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library. If not, see -# <http://www.gnu.org/licenses/>. - -die "syntax: $0 SYMFILE ELFLIB(S)" unless int(@ARGV) >= 2; - -my $symfile = shift @ARGV; -my @elflibs = @ARGV; - -my %wantsyms; -my %gotsyms; - -my $ret = 0; - -open SYMFILE, $symfile or die "cannot read $symfile: $!"; - -while (<SYMFILE>) { - next if /{/; - next if /}/; - next if /global:/; - next if /local:/; - next if /^\s*$/; - next if /^\s*#/; - next if /\*/; - - die "malformed line $_" unless /^\s*(\S+);$/; - - if (exists $wantsyms{$1}) { - print STDERR "Symbol $1 is listed twice\n"; - $ret = 1; - } else { - $wantsyms{$1} = 1; - } -} -close SYMFILE; - -foreach my $elflib (@elflibs) { - open NM, "-|", "nm", $elflib or die "cannot run 'nm $elflib': $!"; - - while (<NM>) { - next unless /^\S+\s(?:[TBD])\s(\S+)\s*$/; - - $gotsyms{$1} = 1; - } - - close NM; -} - -foreach my $sym (keys(%wantsyms)) { - next if exists $gotsyms{$sym}; - - print STDERR "Expected symbol $sym is not in ELF library\n"; - $ret = 1; -} - -exit($ret); -- 2.21.0

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-symfile.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
I verified this catches a bogus symbol name in libvirt_private.syms Tested-by: Cole Robinson <crobinso@redhat.com> - Cole

On Mon, Nov 11, 2019 at 02:38:10PM +0000, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-symfile.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-symfile.py | 80 +++++++++++++++++++++++++++++++++++++++ src/Makefile.am | 5 +-- src/admin/Makefile.inc.am | 4 +- src/check-symfile.pl | 70 ---------------------------------- 5 files changed, 85 insertions(+), 75 deletions(-) create mode 100755 scripts/check-symfile.py delete mode 100755 src/check-symfile.pl
+with open(symfile, "r") as fh: + for line in fh: + line = line.strip() + if line.find("{") != -1: + continue + if line.find("}") != -1: + continue + if line in ["global:", "local:"]: + continue + if line == "": + continue + if line[0] == '#': + continue + if line.find("*") != -1: + continue + + line = line.strip(";")
Unlike the perl version, this quietly ignores a missing semicolon. But that will be caught by the linker earlier.
+ + if line in wantsyms: + print("Symbol $1 is listed twice", file=sys.stderr) + ret = 1 + else: + wantsyms[line] = True +
Reviewed-by: Ján Tomko <jtomko@redhat.com> Jano

As part of an goal to eliminate Perl from libvirt build tools, rewrite the dtrace2systemtap.pl tool in Python. This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same. Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/dtrace2systemtap.py | 143 ++++++++++++++++++++++++++++++++++++ src/Makefile.am | 10 +-- src/dtrace2systemtap.pl | 130 -------------------------------- 4 files changed, 147 insertions(+), 137 deletions(-) create mode 100755 scripts/dtrace2systemtap.py delete mode 100755 src/dtrace2systemtap.pl diff --git a/Makefile.am b/Makefile.am index 1c7b8045c2..e50a29635b 100644 --- a/Makefile.am +++ b/Makefile.am @@ -50,6 +50,7 @@ EXTRA_DIST = \ scripts/check-spacing.py \ scripts/check-symfile.py \ scripts/check-symsorting.py \ + scripts/dtrace2systemtap.py \ scripts/header-ifdef.py \ scripts/minimize-po.py \ scripts/mock-noinline.py \ diff --git a/scripts/dtrace2systemtap.py b/scripts/dtrace2systemtap.py new file mode 100755 index 0000000000..922713e599 --- /dev/null +++ b/scripts/dtrace2systemtap.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python +# +# Copyright (C) 2011-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# +# +# Generate a set of systemtap probe definitions corresponding to +# DTrace probe markers in libvirt.so +# +# python dtrace2systemtap.py probes.d > libvirt_probes.stp +# + +from __future__ import print_function + +import re +import sys + +file = None +filelist = [] +files = {} + +bindir = sys.argv[1] +sbindir = sys.argv[2] +libdir = sys.argv[3] +dtrace = sys.argv[4] + +probe = None +args = None + +# Read the DTraceprobes definition + +with open(dtrace, "r") as fh: + lineno = 0 + for line in fh: + lineno = lineno + 1 + line = line.strip() + if line == "": + continue + if line.find("provider ") != -1 and line.find("{") != -1: + continue + if line.find("};") != -1: + continue + + if line.startswith("#"): + m = re.search(r'''^\#\s*file:\s*(\S+)$''', line) + if m is not None: + file = m.group(1) + filelist.append(file) + files[file] = {"prefix": None, "probes": []} + continue + + m = re.search(r'''^\#\s*prefix:\s*(\S+)$''', line) + if m is not None: + files[file]["prefix"] = m.group(1) + continue + + m = re.search(r'''^\#\s*binary:\s*(\S+)$''', line) + if m is not None: + files[file]["binary"] = m.group(1) + continue + + m = re.search(r'''^\#\s*module:\s*(\S+)$''', line) + if m is not None: + files[file]["module"] = m.group(1) + + # ignore unknown comments + else: + m = re.search(r'''probe\s+([a-zA-Z0-9_]+)\((.*?)(\);)?$''', line) + if m is not None: + probe = m.group(1) + args = m.group(2) + if m.group(3) is not None: + files[file]["probes"].append([probe, args]) + probe = None + args = None + elif probe is not None: + m = re.search(r'''^(.*?)(\);)?$''', line) + if m is not None: + args = args + m.group(1) + if m.group(2) is not None: + files[file]["probes"].append([probe, args]) + probe = None + args = None + else: + raise Exception("unexpected data %s on line %d" % + (line, lineno)) + else: + raise Exception("unexpected data %s on line %d" % + (line, lineno)) + +# Write out the SystemTap probes +for file in filelist: + prefix = files[file]["prefix"] + probes = files[file]["probes"] + + print("# %s\n" % file) + for probe in probes: + name = probe[0] + args = probe[1] + + pname = name.replace(prefix + "_", "libvirt." + prefix + ".") + + binary = libdir + "/libvirt.so" + if "binary" in files[file]: + binary = sbindir + "/" + files[file]["binary"] + if "module" in files[file]: + binary = libdir + "/" + files[file]["module"] + + print("probe %s = process(\"%s\").mark(\"%s\") {" % + (pname, binary, name)) + + argbits = args.split(",") + for idx in range(len(argbits)): + arg = argbits[idx] + isstr = False + if arg.find("char *") != -1: + isstr = True + + m = re.search(r'''^.*\s\*?(\S+)$''', arg) + if m is not None: + arg = m.group(1) + else: + raise Exception("Malformed arg %s" % arg) + + if isstr: + print(" %s = user_string($arg%d);" % (arg, idx + 1)) + else: + print(" %s = $arg%d;" % (arg, idx + 1)) + print("}\n") + print("") diff --git a/src/Makefile.am b/src/Makefile.am index 929eef784c..085c193013 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -530,7 +530,6 @@ if WITH_DTRACE_PROBES libvirt_la_BUILT_LIBADD += libvirt_probes.lo libvirt_la_DEPENDENCIES += libvirt_probes.lo libvirt_probes.o nodist_libvirt_la_SOURCES = libvirt_probes.h -DTRACE2SYSTEMTAP_FLAGS = --with-modules BUILT_SOURCES += libvirt_probes.h libvirt_probes.stp libvirt_functions.stp @@ -565,10 +564,10 @@ RPC_PROBE_FILES += $(srcdir)/rpc/virnetprotocol.x \ libvirt_functions.stp: $(RPC_PROBE_FILES) $(srcdir)/rpc/gensystemtap.pl $(AM_V_GEN)$(PERL) -w $(srcdir)/rpc/gensystemtap.pl $(RPC_PROBE_FILES) > $@ -%_probes.stp: %_probes.d $(srcdir)/dtrace2systemtap.pl \ +%_probes.stp: %_probes.d $(top_srcdir)/scripts/dtrace2systemtap.py \ $(top_builddir)/config.status - $(AM_V_GEN)$(PERL) -w $(srcdir)/dtrace2systemtap.pl \ - $(DTRACE2SYSTEMTAP_FLAGS) $(bindir) $(sbindir) $(libdir) $< > $@ + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(top_srcdir)/scripts/dtrace2systemtap.py \ + $(bindir) $(sbindir) $(libdir) $< > $@ CLEANFILES += libvirt_probes.h libvirt_probes.o libvirt_probes.lo \ libvirt_functions.stp libvirt_probes.stp @@ -689,9 +688,6 @@ endif LIBVIRT_INIT_SCRIPT_SYSTEMD endif WITH_LIBVIRTD -EXTRA_DIST += dtrace2systemtap.pl - - if WITH_LIBVIRTD libexec_PROGRAMS += libvirt_iohelper libvirt_iohelper_SOURCES = $(UTIL_IO_HELPER_SOURCES) diff --git a/src/dtrace2systemtap.pl b/src/dtrace2systemtap.pl deleted file mode 100755 index c5fce248b4..0000000000 --- a/src/dtrace2systemtap.pl +++ /dev/null @@ -1,130 +0,0 @@ -#!/usr/bin/env perl -# -# Copyright (C) 2011-2012 Red Hat, Inc. -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library. If not, see -# <http://www.gnu.org/licenses/>. -# -# -# Generate a set of systemtap probe definitions corresponding to -# DTrace probe markers in libvirt.so -# -# perl dtrace2systemtap.pl probes.d > libvirt_probes.stp -# - -use strict; -use warnings; - -my $file; -my @files; -my %files; - -my $with_modules = 0; -if ($ARGV[0] eq "--with-modules") { - # set if we want to honor the "module" setting in the .d file - $with_modules = 1; - shift @ARGV; -} - -my $bindir = shift @ARGV; -my $sbindir = shift @ARGV; -my $libdir = shift @ARGV; - -my $probe; -my $args; - -# Read the DTraceprobes definition -while (<>) { - next if m,^\s*$,; - - next if /^\s*provider\s+\w+\s*{\s*$/; - next if /^\s*};\s*$/; - - if (m,^\s*\#,) { - if (m,^\s*\#\s*file:\s*(\S+)\s*$,) { - $file = $1; - push @files, $file; - $files{$file} = { prefix => undef, probes => [] }; - } elsif (m,^\s*\#\s*prefix:\s*(\S+)\s*$,) { - $files{$file}->{prefix} = $1; - } elsif (m,^\s*\#\s*binary:\s*(\S+)\s*$,) { - $files{$file}->{binary} = $1; - } elsif (m,^\s*\#\s*module:\s*(\S+)\s*$,) { - $files{$file}->{module} = $1; - } else { - # ignore unknown comments - } - } else { - if (m,\s*probe\s+([a-zA-Z0-9_]+)\((.*?)(\);)?$,) { - $probe = $1; - $args = $2; - if ($3) { - push @{$files{$file}->{probes}}, [$probe, $args]; - $probe = $args = undef; - } - } elsif ($probe) { - if (m,^(.*?)(\);)?$,) { - $args .= $1; - if ($2) { - push @{$files{$file}->{probes}}, [$probe, $args]; - $probe = $args = undef; - } - } else { - die "unexpected data $_ on line $."; - } - } else { - die "unexpected data $_ on line $."; - } - } -} - -# Write out the SystemTap probes -foreach my $file (@files) { - my $prefix = $files{$file}->{prefix}; - my @probes = @{$files{$file}->{probes}}; - - print "# $file\n\n"; - foreach my $probe (@probes) { - my $name = $probe->[0]; - my $args = $probe->[1]; - - my $pname = $name; - $pname =~ s/${prefix}_/libvirt.$prefix./; - - my $binary = "$libdir/libvirt.so"; - if (exists $files{$file}->{binary}) { - $binary = $sbindir . "/" . $files{$file}->{binary}; - } - if ($with_modules && exists $files{$file}->{module}) { - $binary = $libdir . "/" . $files{$file}->{module}; - } - - print "probe $pname = process(\"$binary\").mark(\"$name\") {\n"; - - my @args = split /,/, $args; - for (my $i = 0 ; $i <= $#args ; $i++) { - my $arg = $args[$i]; - my $isstr = $arg =~ /char\s+\*/; - $arg =~ s/^.*\s\*?(\S+)$/$1/; - - if ($isstr) { - print " $arg = user_string(\$arg", $i + 1, ");\n"; - } else { - print " $arg = \$arg", $i + 1, ";\n"; - } - } - print "}\n\n"; - } - print "\n"; -} -- 2.21.0

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the dtrace2systemtap.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com>
I verified *.stp generated output is the same across old and new versions Tested-by: Cole Robinson <crobinso@redhat.com> - Cole

On Mon, Nov 11, 2019 at 02:38:11PM +0000, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the dtrace2systemtap.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/dtrace2systemtap.py | 143 ++++++++++++++++++++++++++++++++++++ src/Makefile.am | 10 +-- src/dtrace2systemtap.pl | 130 -------------------------------- 4 files changed, 147 insertions(+), 137 deletions(-) create mode 100755 scripts/dtrace2systemtap.py delete mode 100755 src/dtrace2systemtap.pl
diff --git a/src/Makefile.am b/src/Makefile.am index 929eef784c..085c193013 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -530,7 +530,6 @@ if WITH_DTRACE_PROBES libvirt_la_BUILT_LIBADD += libvirt_probes.lo libvirt_la_DEPENDENCIES += libvirt_probes.lo libvirt_probes.o nodist_libvirt_la_SOURCES = libvirt_probes.h -DTRACE2SYSTEMTAP_FLAGS = --with-modules
Dropping the (now implied) --with-modules flag deserves a mention in the commit message.
BUILT_SOURCES += libvirt_probes.h libvirt_probes.stp libvirt_functions.stp
Reviewed-by: Ján Tomko <jtomko@redhat.com> Jano

As part of an goal to eliminate Perl from libvirt build tools, rewrite the gensystemtap.pl tool in Python. This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same. Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + build-aux/syntax-check.mk | 4 +- scripts/gensystemtap.py | 184 ++++++++++++++++++++++++++++++++++++ src/Makefile.am | 5 +- src/rpc/Makefile.inc.am | 1 - src/rpc/gensystemtap.pl | 193 -------------------------------------- 6 files changed, 189 insertions(+), 199 deletions(-) create mode 100755 scripts/gensystemtap.py delete mode 100755 src/rpc/gensystemtap.pl diff --git a/Makefile.am b/Makefile.am index e50a29635b..afed409c94 100644 --- a/Makefile.am +++ b/Makefile.am @@ -51,6 +51,7 @@ EXTRA_DIST = \ scripts/check-symfile.py \ scripts/check-symsorting.py \ scripts/dtrace2systemtap.py \ + scripts/gensystemtap.py \ scripts/header-ifdef.py \ scripts/minimize-po.py \ scripts/mock-noinline.py \ diff --git a/build-aux/syntax-check.mk b/build-aux/syntax-check.mk index 016e05e7a2..26eb5b94d9 100644 --- a/build-aux/syntax-check.mk +++ b/build-aux/syntax-check.mk @@ -466,6 +466,7 @@ sc_prohibit_risky_id_promotion: # since gnulib has more guarantees for snprintf portability sc_prohibit_sprintf: @prohibit='\<[s]printf\>' \ + in_vc_files='\.[ch]$$' \ halt='use snprintf, not sprintf' \ $(_sc_search_regexp) @@ -2261,9 +2262,6 @@ exclude_file_name_regexp--sc_prohibit_readlink = \ exclude_file_name_regexp--sc_prohibit_setuid = ^src/util/virutil\.c|tools/virt-login-shell\.c$$ -exclude_file_name_regexp--sc_prohibit_sprintf = \ - ^(build-aux/syntax-check\.mk|docs/hacking\.html\.in|.*\.stp|.*\.pl)$$ - exclude_file_name_regexp--sc_prohibit_strncpy = ^src/util/virstring\.c$$ exclude_file_name_regexp--sc_prohibit_strtol = ^examples/.*$$ diff --git a/scripts/gensystemtap.py b/scripts/gensystemtap.py new file mode 100755 index 0000000000..c4bc1620d0 --- /dev/null +++ b/scripts/gensystemtap.py @@ -0,0 +1,184 @@ +#!/usr/bin/env python +# +# Copyright (C) 2011-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# +# Generate a set of systemtap functions for translating various +# RPC enum values into strings +# +# python gensystemtap.py */*.x > libvirt_functions.stp +# + +from __future__ import print_function + +import re +import sys + +funcs = {} + +types = {} +status = {} +auth = {} + + +def load_file(fh): + instatus = False + intype = False + inauth = False + + for line in fh: + if re.search(r'''enum\s+virNetMessageType''', line): + intype = True + elif re.search(r'''enum\s+virNetMessageStatus''', line): + instatus = True + elif re.search(r'''enum remote_auth_type''', line): + inauth = True + elif line.find("}") != -1: + intype = False + instatus = False + inauth = False + elif instatus: + m = re.search(r'''^\s+VIR_NET_(\w+)\s*=\s*(\d+),?$''', line) + if m is not None: + status[m.group(2)] = m.group(1).lower() + elif intype: + m = re.search(r'''^\s+VIR_NET_(\w+)\s*=\s*(\d+),?$''', line) + if m is not None: + types[m.group(2)] = m.group(1).lower() + elif inauth: + m = re.search(r'''^\s+REMOTE_AUTH_(\w+)\s*=\s*(\d+),?$''', line) + if m is not None: + auth[m.group(2)] = m.group(1).lower() + else: + m = re.search(r'''(?:VIR_)?(\w+?)(?:_PROTOCOL)?''' + + r'''_PROGRAM\s*=\s*0x([a-fA-F0-9]+)\s*;''', line) + if m is not None: + funcs[m.group(1).lower()] = { + "id": int(m.group(2), 16), + "version": None, + "progs": [] + } + continue + + m = re.search(r'''(?:VIR_)?(\w+?)(?:_PROTOCOL)?_''' + + r'''(?:PROGRAM|PROTOCOL)_VERSION\s*=\s*(\d+)\s*;''', + line) + if m is not None: + funcs[m.group(1).lower()]["version"] = m.group(2) + continue + + m = re.search(r'''(?:VIR_)?(\w+?)(?:_PROTOCOL)?''' + + r'''_PROC_(.*?)\s+=\s+(\d+)''', line) + if m is not None: + funcs[m.group(1).lower()]["progs"].insert( + int(m.group(3)), m.group(2).lower()) + + +for file in sys.argv[1:]: + with open(file, "r") as fh: + load_file(fh) + + +def genfunc(name, varname, types): + print("function %s(%s, verbose)" % (name, varname)) + print("{") + + first = True + for typename in sorted(types.keys()): + cond = "} else if" + if first: + cond = "if" + first = False + + print(" %s (%s == %s) {" % (cond, varname, typename)) + print(" %sstr = \"%s\"" % (varname, types[typename])) + + print(" } else {") + print(" %sstr = \"unknown\";" % varname) + print(" verbose = 1;") + print(" }") + print(" if (verbose) {") + print(" %sstr = %sstr . sprintf(\":%%d\", %s)" % + (varname, varname, varname)) + print(" }") + print(" return %sstr;" % varname) + print("}") + + +genfunc("libvirt_rpc_auth_name", "type", auth) +genfunc("libvirt_rpc_type_name", "type", types) +genfunc("libvirt_rpc_status_name", "status", status) + +print("function libvirt_rpc_program_name(program, verbose)") +print("{") + +first = True +for funcname in sorted(funcs.keys()): + cond = "} else if" + if first: + cond = "if" + first = False + + print(" %s (program == %s) {" % (cond, funcs[funcname]["id"])) + print(" programstr = \"%s\"" % funcname) + +print(" } else {") +print(" programstr = \"unknown\";") +print(" verbose = 1;") +print(" }") +print(" if (verbose) {") +print(" programstr = programstr . sprintf(\":%d\", program)") +print(" }") +print(" return programstr;") +print("}") + +print("function libvirt_rpc_procedure_name(program, version, proc, verbose)") +print("{") + +first = True +for prog in sorted(funcs.keys()): + cond = "} else if" + if first: + cond = "if" + first = False + + print(" %s (program == %s && version == %s) {" % + (cond, funcs[prog]["id"], funcs[prog]["version"])) + + pfirst = True + for id in range(len(funcs[prog]["progs"])): + pcond = "} else if" + if pfirst: + pcond = "if" + pfirst = False + + print(" %s (proc == %s) {" % (pcond, id + 1)) + print(" procstr = \"%s\";" % funcs[prog]["progs"][id]) + + print(" } else {") + print(" procstr = \"unknown\";") + print(" verbose = 1;") + print(" }") + +print(" } else {") +print(" procstr = \"unknown\";") +print(" verbose = 1;") +print(" }") +print(" if (verbose) {") +print(" procstr = procstr . sprintf(\":%d\", proc)") +print(" }") +print(" return procstr;") +print("}") diff --git a/src/Makefile.am b/src/Makefile.am index 085c193013..b0ca9d3442 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -561,8 +561,9 @@ RPC_PROBE_FILES += $(srcdir)/rpc/virnetprotocol.x \ $(srcdir)/remote/qemu_protocol.x \ $(srcdir)/admin/admin_protocol.x -libvirt_functions.stp: $(RPC_PROBE_FILES) $(srcdir)/rpc/gensystemtap.pl - $(AM_V_GEN)$(PERL) -w $(srcdir)/rpc/gensystemtap.pl $(RPC_PROBE_FILES) > $@ +libvirt_functions.stp: $(RPC_PROBE_FILES) $(top_srcdir)/scripts/gensystemtap.py + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(top_srcdir)/scripts/gensystemtap.py \ + $(RPC_PROBE_FILES) > $@ %_probes.stp: %_probes.d $(top_srcdir)/scripts/dtrace2systemtap.py \ $(top_builddir)/config.status diff --git a/src/rpc/Makefile.inc.am b/src/rpc/Makefile.inc.am index a5bde92c9f..11920b3270 100644 --- a/src/rpc/Makefile.inc.am +++ b/src/rpc/Makefile.inc.am @@ -3,7 +3,6 @@ EXTRA_DIST += \ rpc/gendispatch.pl \ rpc/genprotocol.pl \ - rpc/gensystemtap.pl \ rpc/virnetprotocol.x \ rpc/virkeepaliveprotocol.x \ $(NULL) diff --git a/src/rpc/gensystemtap.pl b/src/rpc/gensystemtap.pl deleted file mode 100755 index 6693d4d6f5..0000000000 --- a/src/rpc/gensystemtap.pl +++ /dev/null @@ -1,193 +0,0 @@ -#!/usr/bin/env perl -# -# Copyright (C) 2011-2012 Red Hat, Inc. -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library. If not, see -# <http://www.gnu.org/licenses/>. -# -# Generate a set of systemtap functions for translating various -# RPC enum values into strings -# -# perl gensystemtap.pl */*.x > libvirt_functions.stp -# - -use strict; - -my %funcs; - -my %type; -my %status; -my %auth; - -my $instatus = 0; -my $intype = 0; -my $inauth = 0; -while (<>) { - if (/enum\s+virNetMessageType/) { - $intype = 1; - } elsif (/enum\s+virNetMessageStatus/) { - $instatus = 1; - } elsif (/enum remote_auth_type/) { - $inauth = 1; - } elsif (/}/) { - $instatus = $intype = $inauth = 0; - } elsif ($instatus) { - if (/^\s+VIR_NET_(\w+)\s*=\s*(\d+),?$/) { - $status{$2} = lc $1; - } - } elsif ($intype) { - if (/^\s+VIR_NET_(\w+)\s*=\s*(\d+),?$/) { - $type{$2} = lc $1; - } - } elsif ($inauth) { - if (/^\s+REMOTE_AUTH_(\w+)\s*=\s*(\d+),?$/) { - $auth{$2} = lc $1; - } - } else { - if (/(?:VIR_)?(\w+?)(?:_PROTOCOL)?_PROGRAM\s*=\s*0x([a-fA-F0-9]+)\s*;/) { - $funcs{lc $1} = { id => hex($2), version => undef, progs => [] }; - } elsif (/(?:VIR_)?(\w+?)(?:_PROTOCOL)?_(?:PROGRAM|PROTOCOL)_VERSION\s*=\s*(\d+)\s*;/) { - $funcs{lc $1}->{version} = $2; - } elsif (/(?:VIR_)?(\w+?)(?:_PROTOCOL)?_PROC_(.*?)\s+=\s+(\d+)/) { - $funcs{lc $1}->{progs}->[$3] = lc $2; - } - } -} - -print <<EOF; -function libvirt_rpc_auth_name(type, verbose) -{ -EOF -my $first = 1; -foreach my $type (sort(keys %auth)) { - my $cond = $first ? "if" : "} else if"; - $first = 0; - print " $cond (type == ", $type, ") {\n"; - print " typestr = \"", $auth{$type}, "\"\n"; -} -print <<EOF; - } else { - typestr = "unknown"; - verbose = 1; - } - if (verbose) { - typestr = typestr . sprintf(":%d", type) - } - return typestr; -} -EOF - -print <<EOF; -function libvirt_rpc_type_name(type, verbose) -{ -EOF -$first = 1; -foreach my $type (sort(keys %type)) { - my $cond = $first ? "if" : "} else if"; - $first = 0; - print " $cond (type == ", $type, ") {\n"; - print " typestr = \"", $type{$type}, "\"\n"; -} -print <<EOF; - } else { - typestr = "unknown"; - verbose = 1; - } - if (verbose) { - typestr = typestr . sprintf(":%d", type) - } - return typestr; -} -EOF - -print <<EOF; -function libvirt_rpc_status_name(status, verbose) -{ -EOF -$first = 1; -foreach my $status (sort(keys %status)) { - my $cond = $first ? "if" : "} else if"; - $first = 0; - print " $cond (status == ", $status, ") {\n"; - print " statusstr = \"", $status{$status}, "\"\n"; -} -print <<EOF; - } else { - statusstr = "unknown"; - verbose = 1; - } - if (verbose) { - statusstr = statusstr . sprintf(":%d", status) - } - return statusstr; -} -EOF - -print <<EOF; -function libvirt_rpc_program_name(program, verbose) -{ -EOF -$first = 1; -foreach my $prog (sort(keys %funcs)) { - my $cond = $first ? "if" : "} else if"; - $first = 0; - print " $cond (program == ", $funcs{$prog}->{id}, ") {\n"; - print " programstr = \"", $prog, "\"\n"; -} -print <<EOF; - } else { - programstr = "unknown"; - verbose = 1; - } - if (verbose) { - programstr = programstr . sprintf(":%d", program) - } - return programstr; -} -EOF - - -print <<EOF; -function libvirt_rpc_procedure_name(program, version, proc, verbose) -{ -EOF -$first = 1; -foreach my $prog (sort(keys %funcs)) { - my $cond = $first ? "if" : "} else if"; - $first = 0; - print " $cond (program == ", $funcs{$prog}->{id}, " && version == ", $funcs{$prog}->{version}, ") {\n"; - - my $pfirst = 1; - for (my $id = 1 ; $id <= $#{$funcs{$prog}->{progs}} ; $id++) { - my $cond = $pfirst ? "if" : "} else if"; - $pfirst = 0; - print " $cond (proc == $id) {\n"; - print " procstr = \"", $funcs{$prog}->{progs}->[$id], "\";\n"; - } - print " } else {\n"; - print " procstr = \"unknown\";\n"; - print " verbose = 1;\n"; - print " }\n"; -} -print <<EOF; - } else { - procstr = "unknown"; - verbose = 1; - } - if (verbose) { - procstr = procstr . sprintf(":%d", proc) - } - return procstr; -} -EOF -- 2.21.0

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the gensystemtap.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com>
libvirt_functions.stp looks the same before and after Tested-by: Cole Robinson <crobinso@redhat.com> - Cole

On Mon, Nov 11, 2019 at 02:38:12PM +0000, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the gensystemtap.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + build-aux/syntax-check.mk | 4 +- scripts/gensystemtap.py | 184 ++++++++++++++++++++++++++++++++++++ src/Makefile.am | 5 +- src/rpc/Makefile.inc.am | 1 - src/rpc/gensystemtap.pl | 193 -------------------------------------- 6 files changed, 189 insertions(+), 199 deletions(-) create mode 100755 scripts/gensystemtap.py delete mode 100755 src/rpc/gensystemtap.pl
Reviewed-by: Ján Tomko <jtomko@redhat.com> Jano

As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-drivername.pl tool in Python. This was mostly a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same. In testing though it was discovered the existing code was broken since it hadn't been updated after driver.h was split into many files. Since the old code is being thrown away, the fix was done as part of the rewrite rather than split into a separate commit. Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-drivername.py | 114 ++++++++++++++++++++++++++++++++++++ src/Makefile.am | 18 ++++-- src/check-drivername.pl | 83 -------------------------- 4 files changed, 129 insertions(+), 87 deletions(-) create mode 100644 scripts/check-drivername.py delete mode 100755 src/check-drivername.pl diff --git a/Makefile.am b/Makefile.am index afed409c94..7155ab6ce9 100644 --- a/Makefile.am +++ b/Makefile.am @@ -47,6 +47,7 @@ EXTRA_DIST = \ AUTHORS.in \ scripts/augeas-gentest.py \ scripts/check-aclperms.py \ + scripts/check-drivername.py \ scripts/check-spacing.py \ scripts/check-symfile.py \ scripts/check-symsorting.py \ diff --git a/scripts/check-drivername.py b/scripts/check-drivername.py new file mode 100644 index 0000000000..3226ee7962 --- /dev/null +++ b/scripts/check-drivername.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python +# +# Copyright (C) 2013-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# + +from __future__ import print_function + +import re +import sys + +drvfiles = [] +symfiles = [] +for arg in sys.argv: + if arg.endswith(".h"): + drvfiles.append(arg) + else: + symfiles.append(arg) + +symbols = {} + +for symfile in symfiles: + with open(symfile, "r") as fh: + for line in fh: + m = re.search(r'''^\s*(vir\w+)\s*;\s*$''', line) + if m is not None: + symbols[m.group(1)] = True + +status = 0 +for drvfile in drvfiles: + with open(drvfile, "r") as fh: + for line in fh: + if line.find("virDrvConnectSupportsFeature") != -1: + continue + + m = re.search(r'''\*(virDrv\w+)\s*\)''', line) + if m is not None: + drv = m.group(1) + + skip = [ + "virDrvStateInitialize", + "virDrvStateCleanup", + "virDrvStateReload", + "virDrvStateStop", + "virDrvConnectURIProbe", + "virDrvDomainMigratePrepare", + "virDrvDomainMigratePrepare2", + "virDrvDomainMigratePrepare3", + "virDrvDomainMigratePrepare3Params", + "virDrvDomainMigratePrepareTunnel", + "virDrvDomainMigratePrepareTunnelParams", + "virDrvDomainMigratePrepareTunnel3", + "virDrvDomainMigratePrepareTunnel3Params", + "virDrvDomainMigratePerform", + "virDrvDomainMigratePerform3", + "virDrvDomainMigratePerform3Params", + "virDrvDomainMigrateConfirm", + "virDrvDomainMigrateConfirm3", + "virDrvDomainMigrateConfirm3Params", + "virDrvDomainMigrateBegin", + "virDrvDomainMigrateBegin3", + "virDrvDomainMigrateBegin3Params", + "virDrvDomainMigrateFinish", + "virDrvDomainMigrateFinish2", + "virDrvDomainMigrateFinish3", + "virDrvDomainMigrateFinish3Params", + "virDrvStreamInData", + ] + if drv in skip: + continue + + sym = drv.replace("virDrv", "vir") + + if sym not in symbols: + print("Driver method name %s doesn't match public API" % + drv) + continue + + m = re.search(r'''^\*(vir\w+)\s*\)''', line) + if m is not None: + name = m.group(1) + print("Bogus name %s" % name) + status = 1 + continue + + m = re.search(r'''^\s*(virDrv\w+)\s+(\w+);\s*''', line) + if m is not None: + drv = m.group(1) + field = m.group(2) + + tmp = drv.replace("virDrv", "") + if tmp.startswith("NWFilter"): + tmp = "nwfilter" + tmp[8:] + tmp = tmp[0:1].lower() + tmp[1:] + + if tmp != field: + print("Driver struct field %s should be named %s" % + (field, tmp)) + status = 1 + +sys.exit(status) diff --git a/src/Makefile.am b/src/Makefile.am index b0ca9d3442..55ad51abf1 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -330,15 +330,25 @@ check-protocol: endif !WITH_REMOTE EXTRA_DIST += $(PROTOCOL_STRUCTS) +DRIVERS = \ + $(srcdir)/driver-hypervisor.h \ + $(srcdir)/driver-interface.h \ + $(srcdir)/driver-network.h \ + $(srcdir)/driver-nodedev.h \ + $(srcdir)/driver-nwfilter.h \ + $(srcdir)/driver-secret.h \ + $(srcdir)/driver-state.h \ + $(srcdir)/driver-storage.h \ + $(srcdir)/driver-stream.h \ + $(NULL) + check-drivername: - $(AM_V_GEN)$(PERL) $(srcdir)/check-drivername.pl \ - $(srcdir)/driver.h \ + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(top_srcdir)/scripts/check-drivername.py \ + $(DRIVERS) \ $(srcdir)/libvirt_public.syms \ $(srcdir)/libvirt_qemu.syms \ $(srcdir)/libvirt_lxc.syms -EXTRA_DIST += check-drivername.pl - check-driverimpls: $(AM_V_GEN)$(PERL) $(srcdir)/check-driverimpls.pl \ $(filter /%,$(DRIVER_SOURCE_FILES)) \ diff --git a/src/check-drivername.pl b/src/check-drivername.pl deleted file mode 100755 index 3a62193e33..0000000000 --- a/src/check-drivername.pl +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env perl -# -# Copyright (C) 2013 Red Hat, Inc. -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library. If not, see -# <http://www.gnu.org/licenses/>. -# - -use strict; -use warnings; - -my $drvfile = shift; -my @symfiles = @ARGV; - -my %symbols; - -foreach my $symfile (@symfiles) { - open SYMFILE, "<", $symfile - or die "cannot read $symfile: $!"; - while (<SYMFILE>) { - if (/^\s*(vir\w+)\s*;\s*$/) { - $symbols{$1} = 1; - } - } - - close SYMFILE; -} - -open DRVFILE, "<", $drvfile - or die "cannot read $drvfile: $!"; - -my $status = 0; - -while (<DRVFILE>) { - next if /virDrvConnectSupportsFeature/; - if (/\*(virDrv\w+)\s*\)/) { - - my $drv = $1; - - next if $drv =~ /virDrvState/; - next if $drv =~ /virDrvDomainMigrate(Prepare|Perform|Confirm|Begin|Finish)/; - - my $sym = $drv; - $sym =~ s/virDrv/vir/; - - unless (exists $symbols{$sym}) { - print "Driver method name $drv doesn't match public API name\n"; - $status = 1; - } - } elsif (/^\*(vir\w+)\s*\)/) { - my $name = $1; - print "Bogus name $1\n"; - $status = 1; - } elsif (/^\s*(virDrv\w+)\s+(\w+);\s*/) { - my $drv = $1; - my $field = $2; - - my $tmp = $drv; - $tmp =~ s/virDrv//; - $tmp =~ s/^NWFilter/nwfilter/; - $tmp =~ s/^(\w)/lc $1/e; - - unless ($tmp eq $field) { - print "Driver struct field $field should be named $tmp\n"; - $status = 1; - } - } -} - -close DRVFILE; - -exit $status; -- 2.21.0

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-drivername.pl tool in Python.
This was mostly a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
In testing though it was discovered the existing code was broken since it hadn't been updated after driver.h was split into many files. Since the old code is being thrown away, the fix was done as part of the rewrite rather than split into a separate commit.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-drivername.py | 114 ++++++++++++++++++++++++++++++++++++ src/Makefile.am | 18 ++++-- src/check-drivername.pl | 83 -------------------------- 4 files changed, 129 insertions(+), 87 deletions(-) create mode 100644 scripts/check-drivername.py delete mode 100755 src/check-drivername.pl
There's a check-drivername.pl usage still in src/admin/Makefile.inc.am after this - Cole

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-drivername.pl tool in Python.
This was mostly a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
In testing though it was discovered the existing code was broken since it hadn't been updated after driver.h was split into many files. Since the old code is being thrown away, the fix was done as part of the rewrite rather than split into a separate commit.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-drivername.py | 114 ++++++++++++++++++++++++++++++++++++ src/Makefile.am | 18 ++++-- src/check-drivername.pl | 83 -------------------------- 4 files changed, 129 insertions(+), 87 deletions(-) create mode 100644 scripts/check-drivername.py delete mode 100755 src/check-drivername.pl
diff --git a/Makefile.am b/Makefile.am index afed409c94..7155ab6ce9 100644 --- a/Makefile.am +++ b/Makefile.am @@ -47,6 +47,7 @@ EXTRA_DIST = \ AUTHORS.in \ scripts/augeas-gentest.py \ scripts/check-aclperms.py \ + scripts/check-drivername.py \ scripts/check-spacing.py \ scripts/check-symfile.py \ scripts/check-symsorting.py \ diff --git a/scripts/check-drivername.py b/scripts/check-drivername.py new file mode 100644 index 0000000000..3226ee7962 --- /dev/null +++ b/scripts/check-drivername.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python +# +# Copyright (C) 2013-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# + +from __future__ import print_function + +import re +import sys + +drvfiles = [] +symfiles = [] +for arg in sys.argv: + if arg.endswith(".h"): + drvfiles.append(arg) + else: + symfiles.append(arg) + +symbols = {} + +for symfile in symfiles: + with open(symfile, "r") as fh: + for line in fh: + m = re.search(r'''^\s*(vir\w+)\s*;\s*$''', line) + if m is not None: + symbols[m.group(1)] = True + +status = 0 +for drvfile in drvfiles: + with open(drvfile, "r") as fh: + for line in fh: + if line.find("virDrvConnectSupportsFeature") != -1: + continue +
I think this bit is just another mechanism for the skip list below. I can't really figure out what other purpose it could be serving
+ m = re.search(r'''\*(virDrv\w+)\s*\)''', line) + if m is not None: + drv = m.group(1) + + skip = [ + "virDrvStateInitialize", + "virDrvStateCleanup", + "virDrvStateReload", + "virDrvStateStop", + "virDrvConnectURIProbe", + "virDrvDomainMigratePrepare", + "virDrvDomainMigratePrepare2", + "virDrvDomainMigratePrepare3", + "virDrvDomainMigratePrepare3Params", + "virDrvDomainMigratePrepareTunnel", + "virDrvDomainMigratePrepareTunnelParams", + "virDrvDomainMigratePrepareTunnel3", + "virDrvDomainMigratePrepareTunnel3Params", + "virDrvDomainMigratePerform", + "virDrvDomainMigratePerform3", + "virDrvDomainMigratePerform3Params", + "virDrvDomainMigrateConfirm", + "virDrvDomainMigrateConfirm3", + "virDrvDomainMigrateConfirm3Params", + "virDrvDomainMigrateBegin", + "virDrvDomainMigrateBegin3", + "virDrvDomainMigrateBegin3Params", + "virDrvDomainMigrateFinish", + "virDrvDomainMigrateFinish2", + "virDrvDomainMigrateFinish3", + "virDrvDomainMigrateFinish3Params", + "virDrvStreamInData", + ] + if drv in skip: + continue + + sym = drv.replace("virDrv", "vir") + + if sym not in symbols: + print("Driver method name %s doesn't match public API" % + drv)
Missing status = 1 here
+ continue + + m = re.search(r'''^\*(vir\w+)\s*\)''', line) + if m is not None: + name = m.group(1) + print("Bogus name %s" % name) + status = 1 + continue +
Not quite sure what this condition is supposed to be catching. It's trying to match lines that start with '*vir'. I guess it's trying to warning against anything that doesn't start with 'virDrv' and instead plain 'vir', but the anchor usage is messed up. But it looks pre-existing. Anyways, the two other error messages trigger correctly Tested-by: Cole Robinson <crobinso@redhat.com>
+ m = re.search(r'''^\s*(virDrv\w+)\s+(\w+);\s*''', line) + if m is not None: + drv = m.group(1) + field = m.group(2) + + tmp = drv.replace("virDrv", "") + if tmp.startswith("NWFilter"): + tmp = "nwfilter" + tmp[8:] + tmp = tmp[0:1].lower() + tmp[1:] + + if tmp != field: + print("Driver struct field %s should be named %s" % + (field, tmp)) + status = 1 + +sys.exit(status) diff --git a/src/Makefile.am b/src/Makefile.am index b0ca9d3442..55ad51abf1 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -330,15 +330,25 @@ check-protocol: endif !WITH_REMOTE EXTRA_DIST += $(PROTOCOL_STRUCTS)
+DRIVERS = \ + $(srcdir)/driver-hypervisor.h \ + $(srcdir)/driver-interface.h \ + $(srcdir)/driver-network.h \ + $(srcdir)/driver-nodedev.h \ + $(srcdir)/driver-nwfilter.h \ + $(srcdir)/driver-secret.h \ + $(srcdir)/driver-state.h \ + $(srcdir)/driver-storage.h \ + $(srcdir)/driver-stream.h \ + $(NULL) + check-drivername: - $(AM_V_GEN)$(PERL) $(srcdir)/check-drivername.pl \ - $(srcdir)/driver.h \ + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(top_srcdir)/scripts/check-drivername.py \ + $(DRIVERS) \ $(srcdir)/libvirt_public.syms \ $(srcdir)/libvirt_qemu.syms \ $(srcdir)/libvirt_lxc.syms
-EXTRA_DIST += check-drivername.pl - check-driverimpls: $(AM_V_GEN)$(PERL) $(srcdir)/check-driverimpls.pl \ $(filter /%,$(DRIVER_SOURCE_FILES)) \ diff --git a/src/check-drivername.pl b/src/check-drivername.pl deleted file mode 100755 index 3a62193e33..0000000000 --- a/src/check-drivername.pl +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env perl -# -# Copyright (C) 2013 Red Hat, Inc. -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library. If not, see -# <http://www.gnu.org/licenses/>. -# - -use strict; -use warnings; - -my $drvfile = shift; -my @symfiles = @ARGV; - -my %symbols; - -foreach my $symfile (@symfiles) { - open SYMFILE, "<", $symfile - or die "cannot read $symfile: $!"; - while (<SYMFILE>) { - if (/^\s*(vir\w+)\s*;\s*$/) { - $symbols{$1} = 1; - } - } - - close SYMFILE; -} - -open DRVFILE, "<", $drvfile - or die "cannot read $drvfile: $!"; - -my $status = 0; - -while (<DRVFILE>) { - next if /virDrvConnectSupportsFeature/; - if (/\*(virDrv\w+)\s*\)/) { - - my $drv = $1; - - next if $drv =~ /virDrvState/; - next if $drv =~ /virDrvDomainMigrate(Prepare|Perform|Confirm|Begin|Finish)/; - - my $sym = $drv; - $sym =~ s/virDrv/vir/; - - unless (exists $symbols{$sym}) { - print "Driver method name $drv doesn't match public API name\n"; - $status = 1; - } - } elsif (/^\*(vir\w+)\s*\)/) { - my $name = $1; - print "Bogus name $1\n"; - $status = 1; - } elsif (/^\s*(virDrv\w+)\s+(\w+);\s*/) { - my $drv = $1; - my $field = $2; - - my $tmp = $drv; - $tmp =~ s/virDrv//; - $tmp =~ s/^NWFilter/nwfilter/; - $tmp =~ s/^(\w)/lc $1/e; - - unless ($tmp eq $field) { - print "Driver struct field $field should be named $tmp\n"; - $status = 1; - } - } -} - -close DRVFILE; - -exit $status;
- Cole

On Fri, Nov 15, 2019 at 04:50:57PM -0500, Cole Robinson wrote:
On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-drivername.pl tool in Python.
This was mostly a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
In testing though it was discovered the existing code was broken since it hadn't been updated after driver.h was split into many files. Since the old code is being thrown away, the fix was done as part of the rewrite rather than split into a separate commit.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-drivername.py | 114 ++++++++++++++++++++++++++++++++++++ src/Makefile.am | 18 ++++-- src/check-drivername.pl | 83 -------------------------- 4 files changed, 129 insertions(+), 87 deletions(-) create mode 100644 scripts/check-drivername.py delete mode 100755 src/check-drivername.pl
diff --git a/Makefile.am b/Makefile.am index afed409c94..7155ab6ce9 100644 --- a/Makefile.am +++ b/Makefile.am @@ -47,6 +47,7 @@ EXTRA_DIST = \ AUTHORS.in \ scripts/augeas-gentest.py \ scripts/check-aclperms.py \ + scripts/check-drivername.py \ scripts/check-spacing.py \ scripts/check-symfile.py \ scripts/check-symsorting.py \ diff --git a/scripts/check-drivername.py b/scripts/check-drivername.py new file mode 100644 index 0000000000..3226ee7962 --- /dev/null +++ b/scripts/check-drivername.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python +# +# Copyright (C) 2013-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# + +from __future__ import print_function + +import re +import sys + +drvfiles = [] +symfiles = [] +for arg in sys.argv: + if arg.endswith(".h"): + drvfiles.append(arg) + else: + symfiles.append(arg) + +symbols = {} + +for symfile in symfiles: + with open(symfile, "r") as fh: + for line in fh: + m = re.search(r'''^\s*(vir\w+)\s*;\s*$''', line) + if m is not None: + symbols[m.group(1)] = True + +status = 0 +for drvfile in drvfiles: + with open(drvfile, "r") as fh: + for line in fh: + if line.find("virDrvConnectSupportsFeature") != -1: + continue +
I think this bit is just another mechanism for the skip list below. I can't really figure out what other purpose it could be serving
Yes, this is just an artifact of the original code. It can be merged below.
+ m = re.search(r'''\*(virDrv\w+)\s*\)''', line) + if m is not None: + drv = m.group(1) + + skip = [ + "virDrvStateInitialize", + "virDrvStateCleanup", + "virDrvStateReload", + "virDrvStateStop", + "virDrvConnectURIProbe", + "virDrvDomainMigratePrepare", + "virDrvDomainMigratePrepare2", + "virDrvDomainMigratePrepare3", + "virDrvDomainMigratePrepare3Params", + "virDrvDomainMigratePrepareTunnel", + "virDrvDomainMigratePrepareTunnelParams", + "virDrvDomainMigratePrepareTunnel3", + "virDrvDomainMigratePrepareTunnel3Params", + "virDrvDomainMigratePerform", + "virDrvDomainMigratePerform3", + "virDrvDomainMigratePerform3Params", + "virDrvDomainMigrateConfirm", + "virDrvDomainMigrateConfirm3", + "virDrvDomainMigrateConfirm3Params", + "virDrvDomainMigrateBegin", + "virDrvDomainMigrateBegin3", + "virDrvDomainMigrateBegin3Params", + "virDrvDomainMigrateFinish", + "virDrvDomainMigrateFinish2", + "virDrvDomainMigrateFinish3", + "virDrvDomainMigrateFinish3Params", + "virDrvStreamInData", + ] + if drv in skip: + continue + + sym = drv.replace("virDrv", "vir") + + if sym not in symbols: + print("Driver method name %s doesn't match public API" % + drv)
Missing status = 1 here
+ continue + + m = re.search(r'''^\*(vir\w+)\s*\)''', line) + if m is not None: + name = m.group(1) + print("Bogus name %s" % name) + status = 1 + continue +
Not quite sure what this condition is supposed to be catching. It's trying to match lines that start with '*vir'. I guess it's trying to warning against anything that doesn't start with 'virDrv' and instead plain 'vir', but the anchor usage is messed up. But it looks pre-existing. Anyways, the two other error messages trigger correctly
It matches if you define an API without the 'Drv' prefix. I just need to drop the "^" eg if i did diff --git a/src/driver-secret.h b/src/driver-secret.h index 125238fe7b..ee93eaba68 100644 --- a/src/driver-secret.h +++ b/src/driver-secret.h @@ -35,7 +35,7 @@ typedef virSecretPtr const unsigned char *uuid); typedef virSecretPtr -(*virDrvSecretLookupByUsage)(virConnectPtr conn, +(*virFishSecretLookupByUsage)(virConnectPtr conn, int usageType, const char *usageID); then it would report Bogus name *virFishSecretLookupByUsage Regards, Daniel -- |: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|

On Mon, Nov 11, 2019 at 02:38:13PM +0000, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-drivername.pl tool in Python.
This was mostly a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
In testing though it was discovered the existing code was broken since it hadn't been updated after driver.h was split into many files. Since the old code is being thrown away, the fix was done as part of the rewrite rather than split into a separate commit.
It's nice that we haven't broken anything in those years :)
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-drivername.py | 114 ++++++++++++++++++++++++++++++++++++ src/Makefile.am | 18 ++++-- src/check-drivername.pl | 83 -------------------------- 4 files changed, 129 insertions(+), 87 deletions(-) create mode 100644 scripts/check-drivername.py delete mode 100755 src/check-drivername.pl
Reviewed-by: Ján Tomko <jtomko@redhat.com> Jano

As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-driverimpls.pl tool in Python. This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same. Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-driverimpls.py | 102 +++++++++++++++++++++++++++++++++++ src/Makefile.am | 4 +- src/check-driverimpls.pl | 80 --------------------------- 4 files changed, 105 insertions(+), 82 deletions(-) create mode 100755 scripts/check-driverimpls.py delete mode 100755 src/check-driverimpls.pl diff --git a/Makefile.am b/Makefile.am index 7155ab6ce9..407a664626 100644 --- a/Makefile.am +++ b/Makefile.am @@ -48,6 +48,7 @@ EXTRA_DIST = \ scripts/augeas-gentest.py \ scripts/check-aclperms.py \ scripts/check-drivername.py \ + scripts/check-driverimpls.py \ scripts/check-spacing.py \ scripts/check-symfile.py \ scripts/check-symsorting.py \ diff --git a/scripts/check-driverimpls.py b/scripts/check-driverimpls.py new file mode 100755 index 0000000000..78d53e75a4 --- /dev/null +++ b/scripts/check-driverimpls.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python +# +# Copyright (C) 2013-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# + +from __future__ import print_function + +import re +import sys + + +def checkdriverimpls(filename): + intable = False + mainprefix = None + + errs = False + with open(filename, "r") as fh: + lineno = 0 + for line in fh: + lineno = lineno + 1 + if intable: + if line.find("}") != -1: + intable = False + mainprefix = None + continue + + m = re.search(r'''\.(\w+)\s*=\s*(\w+),?/''', line) + if m is not None: + api = m.group(1) + impl = m.group(2) + + if api in ["no", "name"]: + continue + if impl in ["NULL"]: + continue + + suffix = impl + prefix = re.sub(r'''^([a-z]+)(.*?)$''', r'''\1''', impl) + + if mainprefix is not None: + if mainprefix != prefix: + print("%s:%d Bad prefix '%s' for API '%s', " + + "expecting '%s'" % + (filename, lineno, prefix, api, mainprefix), + file=sys.stderr) + errs = True + else: + mainprefix = prefix + + if not api.startswith(mainprefix): + suffix = re.sub(r'''^[a-z]+''', "", suffix) + suffix = re.sub(r'''^([A-Z]+)''', + lambda m: m.group(1).lower(), suffix) + + if api != suffix: + want = api + if want.startswith("nwf"): + want = "NWF" + want[3:] + + if not api.startswith(mainprefix): + want = re.sub(r'''^([a-z])''', + lambda m: m.group(1).upper(), want) + want = mainprefix + want + + print("%s:%d Bad impl name '%s' for API " + + "'%s', expecting '%s'" % + (filename, lineno, impl, api, want), + file=sys.stderr) + errs = True + else: + m = re.search(r'''^(?:static\s+)?(vir(?:\w+)?Driver)''' + + r'''\s+(?!.*;)''', line) + if m is not None: + drv = m.group(1) + if drv in ["virNWFilterCallbackDriver", + "virNWFilterTechDriver", + "virConnectDriver"]: + continue + intable = True + + return errs + + +status = 0 +for filename in sys.argv[1:]: + if checkdriverimpls(filename): + status = 1 +sys.exit(status) diff --git a/src/Makefile.am b/src/Makefile.am index 55ad51abf1..62f1d55402 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -350,7 +350,7 @@ check-drivername: $(srcdir)/libvirt_lxc.syms check-driverimpls: - $(AM_V_GEN)$(PERL) $(srcdir)/check-driverimpls.pl \ + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(top_srcdir)/scripts/check-driverimpls.py \ $(filter /%,$(DRIVER_SOURCE_FILES)) \ $(filter $(srcdir)/%,$(DRIVER_SOURCE_FILES)) \ $(addprefix $(srcdir)/,$(filter-out $(srcdir)/%, \ @@ -366,7 +366,7 @@ check-aclperms: $(srcdir)/access/viraccessperm.h \ $(srcdir)/access/viraccessperm.c -EXTRA_DIST += check-driverimpls.pl check-aclrules.pl +EXTRA_DIST += check-aclrules.pl check-local: check-protocol check-symfile check-symsorting \ check-drivername check-driverimpls check-aclrules \ diff --git a/src/check-driverimpls.pl b/src/check-driverimpls.pl deleted file mode 100755 index 3c0d54724c..0000000000 --- a/src/check-driverimpls.pl +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env perl -# -# Copyright (C) 2013 Red Hat, Inc. -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library. If not, see -# <http://www.gnu.org/licenses/>. -# - -use strict; -use warnings; - -my $intable = 0; -my $table; -my $mainprefix; - -my $status = 0; -while (<>) { - if ($intable) { - if (/}/) { - $intable = 0; - $table = undef; - $mainprefix = undef; - } elsif (/\.(\w+)\s*=\s*(\w+),?/) { - my $api = $1; - my $impl = $2; - - next if $api eq "no"; - next if $api eq "name"; - next if $impl eq "NULL"; - - my $suffix = $impl; - my $prefix = $impl; - $prefix =~ s/^([a-z]+)(.*?)$/$1/; - - if (defined $mainprefix) { - if ($mainprefix ne $prefix) { - print "$ARGV:$. Bad prefix '$prefix' for API '$api', expecting '$mainprefix'\n"; - $status = 1; - } - } else { - $mainprefix = $prefix; - } - - if ($api !~ /^$mainprefix/) { - $suffix =~ s/^[a-z]+//; - $suffix =~ s/^([A-Z]+)/lc $1/e; - } - - if ($api ne $suffix) { - my $want = $api; - $want =~ s/^nwf/NWF/; - if ($api !~ /^$mainprefix/) { - $want =~ s/^([a-z])/uc $1/e; - $want = $mainprefix . $want; - } - print "$ARGV:$. Bad impl name '$impl' for API '$api', expecting '$want'\n"; - $status = 1; - } - } - } elsif (/^(?:static\s+)?(vir(?:\w+)?Driver)\s+(?!.*;)/) { - next if $1 eq "virNWFilterCallbackDriver" || - $1 eq "virNWFilterTechDriver" || - $1 eq "virConnectDriver"; - $intable = 1; - $table = $1; - } -} - -exit $status; -- 2.21.0

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-driverimpls.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-driverimpls.py | 102 +++++++++++++++++++++++++++++++++++ src/Makefile.am | 4 +- src/check-driverimpls.pl | 80 --------------------------- 4 files changed, 105 insertions(+), 82 deletions(-) create mode 100755 scripts/check-driverimpls.py delete mode 100755 src/check-driverimpls.pl
diff --git a/Makefile.am b/Makefile.am index 7155ab6ce9..407a664626 100644 --- a/Makefile.am +++ b/Makefile.am @@ -48,6 +48,7 @@ EXTRA_DIST = \ scripts/augeas-gentest.py \ scripts/check-aclperms.py \ scripts/check-drivername.py \ + scripts/check-driverimpls.py \ scripts/check-spacing.py \ scripts/check-symfile.py \ scripts/check-symsorting.py \ diff --git a/scripts/check-driverimpls.py b/scripts/check-driverimpls.py new file mode 100755 index 0000000000..78d53e75a4 --- /dev/null +++ b/scripts/check-driverimpls.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python +# +# Copyright (C) 2013-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# + +from __future__ import print_function + +import re +import sys + + +def checkdriverimpls(filename): + intable = False + mainprefix = None + + errs = False + with open(filename, "r") as fh: + lineno = 0 + for line in fh: + lineno = lineno + 1 + if intable: + if line.find("}") != -1: + intable = False + mainprefix = None + continue + + m = re.search(r'''\.(\w+)\s*=\s*(\w+),?/''', line)
The ending / here breaks things. If the intent is to match lines like: .connectSupportsFeature = qemuConnectSupportsFeature, /* 0.5.0 */ Then there needs to be something between '?' and '/'. But this script could still be useful for sanitizing virStateDriver structs too, which don't have those ending comments, so maybe just drop the / entirely. With that and the pep8 issues fixed, all the errors trigger as expected Tested-by: Cole Robinson <crobinso@redhat.com> - Cole

On Mon, Nov 11, 2019 at 02:38:14PM +0000, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-driverimpls.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-driverimpls.py | 102 +++++++++++++++++++++++++++++++++++ src/Makefile.am | 4 +- src/check-driverimpls.pl | 80 --------------------------- 4 files changed, 105 insertions(+), 82 deletions(-) create mode 100755 scripts/check-driverimpls.py delete mode 100755 src/check-driverimpls.pl
diff --git a/Makefile.am b/Makefile.am index 7155ab6ce9..407a664626 100644 --- a/Makefile.am +++ b/Makefile.am @@ -48,6 +48,7 @@ EXTRA_DIST = \ scripts/augeas-gentest.py \ scripts/check-aclperms.py \ scripts/check-drivername.py \ + scripts/check-driverimpls.py \ scripts/check-spacing.py \ scripts/check-symfile.py \ scripts/check-symsorting.py \ diff --git a/scripts/check-driverimpls.py b/scripts/check-driverimpls.py new file mode 100755 index 0000000000..78d53e75a4 --- /dev/null +++ b/scripts/check-driverimpls.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python +# +# Copyright (C) 2013-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# + +from __future__ import print_function + +import re +import sys + + +def checkdriverimpls(filename): + intable = False + mainprefix = None + + errs = False + with open(filename, "r") as fh: + lineno = 0 + for line in fh: + lineno = lineno + 1 + if intable: + if line.find("}") != -1: + intable = False + mainprefix = None + continue + + m = re.search(r'''\.(\w+)\s*=\s*(\w+),?/''', line)
With the leftover '/' removed: Reviewed-by: Ján Tomko <jtomko@redhat.com> Jano

As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-aclrules.pl tool in Python. This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same. Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-aclrules.py | 263 ++++++++++++++++++++++++++++++++++++++ src/Makefile.am | 4 +- src/check-aclrules.pl | 252 ------------------------------------ 4 files changed, 265 insertions(+), 255 deletions(-) create mode 100755 scripts/check-aclrules.py delete mode 100755 src/check-aclrules.pl diff --git a/Makefile.am b/Makefile.am index 407a664626..f28b07d814 100644 --- a/Makefile.am +++ b/Makefile.am @@ -47,6 +47,7 @@ EXTRA_DIST = \ AUTHORS.in \ scripts/augeas-gentest.py \ scripts/check-aclperms.py \ + scripts/check-aclrules.py \ scripts/check-drivername.py \ scripts/check-driverimpls.py \ scripts/check-spacing.py \ diff --git a/scripts/check-aclrules.py b/scripts/check-aclrules.py new file mode 100755 index 0000000000..3fab126a4a --- /dev/null +++ b/scripts/check-aclrules.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python +# +# Copyright (C) 2013-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# +# This script validates that the driver implementation of any +# public APIs contain ACL checks. +# +# As the script reads each source file, it attempts to identify +# top level function names. +# +# When reading the body of the functions, it looks for anything +# that looks like an API called named XXXEnsureACL. It will +# validate that the XXX prefix matches the name of the function +# it occurs in. +# +# When it later finds the virDriverPtr table, for each entry +# point listed, it will validate if there was a previously +# detected EnsureACL call recorded. +# + +from __future__ import print_function + +import re +import sys + +whitelist = { + "connectClose": True, + "connectIsEncrypted": True, + "connectIsSecure": True, + "connectIsAlive": True, + "networkOpen": True, + "networkClose": True, + "nwfilterOpen": True, + "nwfilterClose": True, + "secretOpen": True, + "secretClose": True, + "storageOpen": True, + "storageClose": True, + "interfaceOpen": True, + "interfaceClose": True, + "connectURIProbe": True, + "localOnly": True, + "domainQemuAttach": True, +} + +# XXX this vzDomainMigrateConfirm3Params looks +# bogus - determine why it doesn't have a valid +# ACL check. +implwhitelist = { + "vzDomainMigrateConfirm3Params": True, +} + +lastfile = None + + +def fixup_name(name): + name.replace("Nwfilter", "NWFilter") + name.replace("Pm", "PM") + name.replace("Scsi", "SCSI") + if name.endswith("Xml"): + name = name[:-3] + "XML" + elif name.endswith("Uri"): + name = name[:-3] + "URI" + elif name.endswith("Uuid"): + name = name[:-4] + "UUID" + elif name.endswith("Id"): + name = name[:-2] + "ID" + elif name.endswith("Mac"): + name = name[:-3] + "MAC" + elif name.endswith("Cpu"): + name = name[:-3] + "MAC" + elif name.endswith("Os"): + name = name[:-2] + "OS" + elif name.endswith("Nmi"): + name = name[:-3] + "NMI" + elif name.endswith("Fstrim"): + name = name[:-6] + "FSTrim" + elif name.endswith("Wwn"): + name = name[:-3] + "WWN" + + return name + + +def name_to_ProcName(name): + elems = [] + if name.find("_") != -1 or name.lower() in ["open", "close"]: + elems = [n.lower().capitalize() for n in name.split("_")] + else: + elems = [name] + + elems = [fixup_name(n) for n in elems] + procname = "".join(elems) + + return procname[0:1].lower() + procname[1:] + + +proto = sys.argv[1] + +filteredmap = {} +with open(proto, "r") as fh: + incomment = False + filtered = False + + for line in fh: + if line.find("/**") != -1: + incomment = True + filtered = False + elif incomment: + if line.find("* @aclfilter") != -1: + filtered = True + elif filtered: + m = re.search(r'''REMOTE_PROC_(.*)\s+=\s*\d+''', line) + if m is not None: + api = name_to_ProcName(m.group(1)) + # Event filtering is handled in daemon/remote.c + # instead of drivers + if line.find("_EVENT_REGISTER") == -1: + filteredmap[api] = True + incomment = False + + +def process_file(filename): + brace = 0 + maybefunc = None + intable = False + table = None + + acls = {} + aclfilters = {} + errs = False + with open(filename, "r") as fh: + lineno = 0 + for line in fh: + lineno = lineno + 1 + if brace == 0: + # Looks for anything which appears to be a function + # body name. Doesn't matter if we pick up bogus stuff + # here, as long as we don't miss valid stuff + m = re.search(r'''\b(\w+)\(''', line) + if m is not None: + maybefunc = m.group(1) + elif brace > 0: + ensureacl = re.search(r'''(\w+)EnsureACL''', line) + checkacl = re.search(r'''(\w+)CheckACL''', line) + stub = re.search(r'''\b(\w+)\(''', line) + if ensureacl is not None: + # Record the fact that maybefunc contains an + # ACL call, and make sure it is the right call! + func = ensureacl.group(1) + if func.startswith("vir"): + func = func[3:] + + if maybefunc is None: + print("%s:%d Unexpected check '%s' outside function" % + (filename, lineno, func), file=sys.stderr) + errs = True + else: + if not maybefunc.lower().endswith(func.lower()): + print("%s:%d Mismatch check 'vir%sEnsureACL'" + + "for function '%s'" % + (filename, lineno, func, maybefunc), + file=sys.stderr) + errs = True + acls[maybefunc] = True + elif checkacl: + # Record the fact that maybefunc contains an + # ACL filter call, and make sure it is the right call! + func = checkacl.group(1) + if func.startswith("vir"): + func = func[3:] + + if maybefunc is None: + print("%s:%d Unexpected check '%s' outside function" % + (filename, lineno, func), file=sys.stderr) + errs = True + else: + if not maybefunc.lower().endswith(func.lower()): + print("%s:%d Mismatch check 'vir%sEnsureACL' " + + "for function '%s'" % + (filename, lineno, func, maybefunc), + file=sys.stderr) + errs = True + aclfilters[maybefunc] = True + elif stub: + # Handles case where we replaced an API with a new + # one which adds new parameters, and we're left with + # a simple stub calling the new API. + callfunc = stub.group(1) + if callfunc in acls: + acls[maybefunc] = True + + if callfunc in aclfilters: + aclfilters[maybefunc] = True + + # Pass the vir*DriverPtr tables and make sure that + # every func listed there, has an impl which calls + # an ACL function + if intable: + assign = re.search(r'''\.(\w+)\s*=\s*(\w+),?''', line) + if line.find("}") != -1: + intable = False + table = None + elif assign is not None: + api = assign.group(1) + impl = assign.group(2) + + if (impl != "NULL" and + api not in ["no", "name"] and + table != "virStateDriver"): + if (impl not in acls and + api not in whitelist and + impl not in implwhitelist): + print("%s:%d Missing ACL check in " + + "function '%s' for '%s'" % + (filename, lineno, impl, api), + file=sys.stderr) + errs = True + + if api in filteredmap and impl not in aclfilters: + print("%s:%d Missing ACL filter in " + + "function '%s' for '%s'" % + (filename, lineno, impl, api), + file=sys.stderr) + errs = True + else: + m = re.search(r'''^(?:static\s+)?(vir(?:\w+)?Driver)\s+''', + line) + if m is not None: + name = m.group(1) + if name not in ["virNWFilterCallbackDriver", + "virNWFilterTechDriver", + "virDomainConfNWFilterDriver"]: + intable = True + table = name + + if line.find("{") != -1: + brace = brace + 1 + if line.find("}") != -1: + brace = brace - 1 + + return errs + + +status = 0 +for filename in sys.argv[2:]: + if process_file(filename): + status = 1 + +sys.exit(status) diff --git a/src/Makefile.am b/src/Makefile.am index 62f1d55402..bb63e2486c 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -357,7 +357,7 @@ check-driverimpls: $(filter-out /%,$(DRIVER_SOURCE_FILES)))) check-aclrules: - $(AM_V_GEN)$(PERL) $(srcdir)/check-aclrules.pl \ + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(top_srcdir)/scripts/check-aclrules.py \ $(REMOTE_PROTOCOL) \ $(addprefix $(srcdir)/,$(filter-out /%,$(STATEFUL_DRIVER_SOURCE_FILES))) @@ -366,8 +366,6 @@ check-aclperms: $(srcdir)/access/viraccessperm.h \ $(srcdir)/access/viraccessperm.c -EXTRA_DIST += check-aclrules.pl - check-local: check-protocol check-symfile check-symsorting \ check-drivername check-driverimpls check-aclrules \ check-aclperms check-admin diff --git a/src/check-aclrules.pl b/src/check-aclrules.pl deleted file mode 100755 index 0d4cac17ca..0000000000 --- a/src/check-aclrules.pl +++ /dev/null @@ -1,252 +0,0 @@ -#!/usr/bin/env perl -# -# Copyright (C) 2013-2014 Red Hat, Inc. -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library. If not, see -# <http://www.gnu.org/licenses/>. -# -# This script validates that the driver implementation of any -# public APIs contain ACL checks. -# -# As the script reads each source file, it attempts to identify -# top level function names. -# -# When reading the body of the functions, it looks for anything -# that looks like an API called named XXXEnsureACL. It will -# validate that the XXX prefix matches the name of the function -# it occurs in. -# -# When it later finds the virDriverPtr table, for each entry -# point listed, it will validate if there was a previously -# detected EnsureACL call recorded. -# -use strict; -use warnings; - -my $status = 0; - -my $brace = 0; -my $maybefunc; -my $intable = 0; -my $table; - -my %acls; -my %aclfilters; - -my %whitelist = ( - "connectClose" => 1, - "connectIsEncrypted" => 1, - "connectIsSecure" => 1, - "connectIsAlive" => 1, - "networkOpen" => 1, - "networkClose" => 1, - "nwfilterOpen" => 1, - "nwfilterClose" => 1, - "secretOpen" => 1, - "secretClose" => 1, - "storageOpen" => 1, - "storageClose" => 1, - "interfaceOpen" => 1, - "interfaceClose" => 1, - "connectURIProbe" => 1, - "localOnly" => 1, - "domainQemuAttach" => 1, - ); - -# XXX this vzDomainMigrateConfirm3Params looks -# bogus - determine why it doesn't have a valid -# ACL check. -my %implwhitelist = ( - "vzDomainMigrateConfirm3Params" => 1, - ); - -my $lastfile; - -sub fixup_name { - my $name = shift; - - $name =~ s/Nwfilter/NWFilter/; - $name =~ s/Xml$/XML/; - $name =~ s/Uri$/URI/; - $name =~ s/Uuid$/UUID/; - $name =~ s/Id$/ID/; - $name =~ s/Mac$/MAC/; - $name =~ s/Cpu$/CPU/; - $name =~ s/Os$/OS/; - $name =~ s/Nmi$/NMI/; - $name =~ s/Pm/PM/; - $name =~ s/Fstrim$/FSTrim/; - $name =~ s/Scsi/SCSI/; - $name =~ s/Wwn$/WWN/; - - return $name; -} - -sub name_to_ProcName { - my $name = shift; - - my @elems; - if ($name =~ /_/ || (lc $name) eq "open" || (lc $name) eq "close") { - @elems = split /_/, $name; - @elems = map lc, @elems; - @elems = map ucfirst, @elems; - } else { - @elems = $name; - } - @elems = map { fixup_name($_) } @elems; - my $procname = join "", @elems; - - $procname =~ s/^([A-Z])/lc $1/e; - - return $procname; -} - - -my $proto = shift @ARGV; - -open PROTO, "<$proto" or die "cannot read $proto"; - -my %filtered; -my $incomment = 0; -my $filtered = 0; -while (<PROTO>) { - if (m,/\*\*,) { - $incomment = 1; - $filtered = 0; - } elsif ($incomment) { - if (m,\*\s\@aclfilter,) { - $filtered = 1; - } elsif ($filtered && - m,REMOTE_PROC_(.*)\s+=\s*\d+,) { - my $api = name_to_ProcName($1); - # Event filtering is handled in daemon/remote.c instead of drivers - if (! m,_EVENT_REGISTER,) { - $filtered{$api} = 1; - } - $incomment = 0; - } - } -} - -close PROTO; - -while (<>) { - if (!defined $lastfile || - $lastfile ne $ARGV) { - %acls = (); - $brace = 0; - $maybefunc = undef; - $lastfile = $ARGV; - } - if ($brace == 0) { - # Looks for anything which appears to be a function - # body name. Doesn't matter if we pick up bogus stuff - # here, as long as we don't miss valid stuff - if (m,\b(\w+)\(,) { - $maybefunc = $1; - } - } elsif ($brace > 0) { - if (m,(\w+)EnsureACL,) { - # Record the fact that maybefunc contains an - # ACL call, and make sure it is the right call! - my $func = $1; - $func =~ s/^vir//; - if (!defined $maybefunc) { - print "$ARGV:$. Unexpected check '$func' outside function\n"; - $status = 1; - } else { - unless ($maybefunc =~ /$func$/i) { - print "$ARGV:$. Mismatch check 'vir${func}EnsureACL' for function '$maybefunc'\n"; - $status = 1; - } - } - $acls{$maybefunc} = 1; - } elsif (m,(\w+)CheckACL,) { - # Record the fact that maybefunc contains an - # ACL filter call, and make sure it is the right call! - my $func = $1; - $func =~ s/^vir//; - if (!defined $maybefunc) { - print "$ARGV:$. Unexpected check '$func' outside function\n"; - $status = 1; - } else { - unless ($maybefunc =~ /$func$/i) { - print "$ARGV:$. Mismatch check 'vir${func}CheckACL' for function '$maybefunc'\n"; - $status = 1; - } - } - $aclfilters{$maybefunc} = 1; - } elsif (m,\b(\w+)\(,) { - # Handles case where we replaced an API with a new - # one which adds new parameters, and we're left with - # a simple stub calling the new API. - my $callfunc = $1; - if (exists $acls{$callfunc}) { - $acls{$maybefunc} = 1; - } - if (exists $aclfilters{$callfunc}) { - $aclfilters{$maybefunc} = 1; - } - } - } - - # Pass the vir*DriverPtr tables and make sure that - # every func listed there, has an impl which calls - # an ACL function - if ($intable) { - if (/\}/) { - $intable = 0; - $table = undef; - } elsif (/\.(\w+)\s*=\s*(\w+),?/) { - my $api = $1; - my $impl = $2; - - next if $impl eq "NULL"; - - if ($api ne "no" && - $api ne "name" && - $table ne "virStateDriver" && - !exists $acls{$impl} && - !exists $whitelist{$api} && - !exists $implwhitelist{$impl}) { - print "$ARGV:$. Missing ACL check in function '$impl' for '$api'\n"; - $status = 1; - } - - if (exists $filtered{$api} && - !exists $aclfilters{$impl}) { - print "$ARGV:$. Missing ACL filter in function '$impl' for '$api'\n"; - $status = 1; - } - } - } elsif (/^(?:static\s+)?(vir(?:\w+)?Driver)\s+/) { - if ($1 ne "virNWFilterCallbackDriver" && - $1 ne "virNWFilterTechDriver" && - $1 ne "virDomainConfNWFilterDriver") { - $intable = 1; - $table = $1; - } - } - - - my $count; - $count = s/{//g; - $brace += $count; - $count = s/}//g; - $brace -= $count; -} continue { - close ARGV if eof; -} - -exit $status; -- 2.21.0

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-aclrules.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-aclrules.py | 263 ++++++++++++++++++++++++++++++++++++++ src/Makefile.am | 4 +- src/check-aclrules.pl | 252 ------------------------------------ 4 files changed, 265 insertions(+), 255 deletions(-) create mode 100755 scripts/check-aclrules.py delete mode 100755 src/check-aclrules.pl
diff --git a/Makefile.am b/Makefile.am index 407a664626..f28b07d814 100644 --- a/Makefile.am +++ b/Makefile.am @@ -47,6 +47,7 @@ EXTRA_DIST = \ AUTHORS.in \ scripts/augeas-gentest.py \ scripts/check-aclperms.py \ + scripts/check-aclrules.py \ scripts/check-drivername.py \ scripts/check-driverimpls.py \ scripts/check-spacing.py \ diff --git a/scripts/check-aclrules.py b/scripts/check-aclrules.py new file mode 100755 index 0000000000..3fab126a4a --- /dev/null +++ b/scripts/check-aclrules.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python +# +# Copyright (C) 2013-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# +# This script validates that the driver implementation of any +# public APIs contain ACL checks. +# +# As the script reads each source file, it attempts to identify +# top level function names. +# +# When reading the body of the functions, it looks for anything +# that looks like an API called named XXXEnsureACL. It will +# validate that the XXX prefix matches the name of the function +# it occurs in. +# +# When it later finds the virDriverPtr table, for each entry +# point listed, it will validate if there was a previously +# detected EnsureACL call recorded. +# + +from __future__ import print_function + +import re +import sys + +whitelist = { + "connectClose": True, + "connectIsEncrypted": True, + "connectIsSecure": True, + "connectIsAlive": True, + "networkOpen": True, + "networkClose": True, + "nwfilterOpen": True, + "nwfilterClose": True, + "secretOpen": True, + "secretClose": True, + "storageOpen": True, + "storageClose": True, + "interfaceOpen": True, + "interfaceClose": True, + "connectURIProbe": True, + "localOnly": True, + "domainQemuAttach": True, +} + +# XXX this vzDomainMigrateConfirm3Params looks +# bogus - determine why it doesn't have a valid +# ACL check. +implwhitelist = { + "vzDomainMigrateConfirm3Params": True, +} + +lastfile = None + + +def fixup_name(name): + name.replace("Nwfilter", "NWFilter") + name.replace("Pm", "PM") + name.replace("Scsi", "SCSI") + if name.endswith("Xml"): + name = name[:-3] + "XML" + elif name.endswith("Uri"): + name = name[:-3] + "URI" + elif name.endswith("Uuid"): + name = name[:-4] + "UUID" + elif name.endswith("Id"): + name = name[:-2] + "ID" + elif name.endswith("Mac"): + name = name[:-3] + "MAC" + elif name.endswith("Cpu"): + name = name[:-3] + "MAC" + elif name.endswith("Os"): + name = name[:-2] + "OS" + elif name.endswith("Nmi"): + name = name[:-3] + "NMI" + elif name.endswith("Fstrim"): + name = name[:-6] + "FSTrim" + elif name.endswith("Wwn"): + name = name[:-3] + "WWN" + + return name + + +def name_to_ProcName(name): + elems = [] + if name.find("_") != -1 or name.lower() in ["open", "close"]: + elems = [n.lower().capitalize() for n in name.split("_")] + else: + elems = [name] + + elems = [fixup_name(n) for n in elems] + procname = "".join(elems) + + return procname[0:1].lower() + procname[1:] + + +proto = sys.argv[1] + +filteredmap = {} +with open(proto, "r") as fh: + incomment = False + filtered = False + + for line in fh: + if line.find("/**") != -1: + incomment = True + filtered = False + elif incomment: + if line.find("* @aclfilter") != -1: + filtered = True + elif filtered: + m = re.search(r'''REMOTE_PROC_(.*)\s+=\s*\d+''', line) + if m is not None: + api = name_to_ProcName(m.group(1)) + # Event filtering is handled in daemon/remote.c + # instead of drivers + if line.find("_EVENT_REGISTER") == -1: + filteredmap[api] = True + incomment = False + + +def process_file(filename): + brace = 0 + maybefunc = None + intable = False + table = None + + acls = {} + aclfilters = {} + errs = False + with open(filename, "r") as fh: + lineno = 0 + for line in fh: + lineno = lineno + 1 + if brace == 0: + # Looks for anything which appears to be a function + # body name. Doesn't matter if we pick up bogus stuff + # here, as long as we don't miss valid stuff + m = re.search(r'''\b(\w+)\(''', line) + if m is not None: + maybefunc = m.group(1) + elif brace > 0: + ensureacl = re.search(r'''(\w+)EnsureACL''', line) + checkacl = re.search(r'''(\w+)CheckACL''', line) + stub = re.search(r'''\b(\w+)\(''', line) + if ensureacl is not None: + # Record the fact that maybefunc contains an + # ACL call, and make sure it is the right call! + func = ensureacl.group(1) + if func.startswith("vir"): + func = func[3:] + + if maybefunc is None: + print("%s:%d Unexpected check '%s' outside function" % + (filename, lineno, func), file=sys.stderr) + errs = True + else: + if not maybefunc.lower().endswith(func.lower()): + print("%s:%d Mismatch check 'vir%sEnsureACL'" + + "for function '%s'" % + (filename, lineno, func, maybefunc), + file=sys.stderr) + errs = True + acls[maybefunc] = True + elif checkacl: + # Record the fact that maybefunc contains an + # ACL filter call, and make sure it is the right call! + func = checkacl.group(1) + if func.startswith("vir"): + func = func[3:] + + if maybefunc is None: + print("%s:%d Unexpected check '%s' outside function" % + (filename, lineno, func), file=sys.stderr) + errs = True + else: + if not maybefunc.lower().endswith(func.lower()): + print("%s:%d Mismatch check 'vir%sEnsureACL' " +
The string here should be vir%sCheckACL After that, and the flake8 fixes, I could trigger the two 'mismatch check' and 'Missing ACL' errors in qemu_driver.c, which are the important ones Tested-by: Cole Robinson <crobinso@redhat.com> - Cole

On Mon, Nov 11, 2019 at 02:38:15PM +0000, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-aclrules.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-aclrules.py | 263 ++++++++++++++++++++++++++++++++++++++ src/Makefile.am | 4 +- src/check-aclrules.pl | 252 ------------------------------------ 4 files changed, 265 insertions(+), 255 deletions(-) create mode 100755 scripts/check-aclrules.py delete mode 100755 src/check-aclrules.pl
diff --git a/Makefile.am b/Makefile.am index 407a664626..f28b07d814 100644 --- a/Makefile.am +++ b/Makefile.am @@ -47,6 +47,7 @@ EXTRA_DIST = \ AUTHORS.in \ scripts/augeas-gentest.py \ scripts/check-aclperms.py \ + scripts/check-aclrules.py \ scripts/check-drivername.py \ scripts/check-driverimpls.py \ scripts/check-spacing.py \ diff --git a/scripts/check-aclrules.py b/scripts/check-aclrules.py new file mode 100755 index 0000000000..3fab126a4a --- /dev/null +++ b/scripts/check-aclrules.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python +# +# Copyright (C) 2013-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# +# This script validates that the driver implementation of any +# public APIs contain ACL checks. +# +# As the script reads each source file, it attempts to identify +# top level function names. +# +# When reading the body of the functions, it looks for anything +# that looks like an API called named XXXEnsureACL. It will +# validate that the XXX prefix matches the name of the function +# it occurs in. +# +# When it later finds the virDriverPtr table, for each entry +# point listed, it will validate if there was a previously +# detected EnsureACL call recorded. +# + +from __future__ import print_function + +import re +import sys + +whitelist = { + "connectClose": True, + "connectIsEncrypted": True, + "connectIsSecure": True, + "connectIsAlive": True, + "networkOpen": True, + "networkClose": True, + "nwfilterOpen": True, + "nwfilterClose": True, + "secretOpen": True, + "secretClose": True, + "storageOpen": True, + "storageClose": True, + "interfaceOpen": True, + "interfaceClose": True, + "connectURIProbe": True, + "localOnly": True, + "domainQemuAttach": True, +} + +# XXX this vzDomainMigrateConfirm3Params looks +# bogus - determine why it doesn't have a valid +# ACL check. +implwhitelist = { + "vzDomainMigrateConfirm3Params": True, +} + +lastfile = None + + +def fixup_name(name): + name.replace("Nwfilter", "NWFilter") + name.replace("Pm", "PM") + name.replace("Scsi", "SCSI") + if name.endswith("Xml"): + name = name[:-3] + "XML" + elif name.endswith("Uri"): + name = name[:-3] + "URI" + elif name.endswith("Uuid"): + name = name[:-4] + "UUID" + elif name.endswith("Id"): + name = name[:-2] + "ID" + elif name.endswith("Mac"): + name = name[:-3] + "MAC" + elif name.endswith("Cpu"): + name = name[:-3] + "MAC" + elif name.endswith("Os"): + name = name[:-2] + "OS" + elif name.endswith("Nmi"): + name = name[:-3] + "NMI" + elif name.endswith("Fstrim"): + name = name[:-6] + "FSTrim" + elif name.endswith("Wwn"): + name = name[:-3] + "WWN" + + return name + + +def name_to_ProcName(name): + elems = [] + if name.find("_") != -1 or name.lower() in ["open", "close"]: + elems = [n.lower().capitalize() for n in name.split("_")] + else: + elems = [name] + + elems = [fixup_name(n) for n in elems] + procname = "".join(elems) + + return procname[0:1].lower() + procname[1:] + + +proto = sys.argv[1] + +filteredmap = {} +with open(proto, "r") as fh: + incomment = False + filtered = False + + for line in fh: + if line.find("/**") != -1: + incomment = True + filtered = False + elif incomment: + if line.find("* @aclfilter") != -1: + filtered = True + elif filtered: + m = re.search(r'''REMOTE_PROC_(.*)\s+=\s*\d+''', line) + if m is not None: + api = name_to_ProcName(m.group(1)) + # Event filtering is handled in daemon/remote.c + # instead of drivers + if line.find("_EVENT_REGISTER") == -1: + filteredmap[api] = True + incomment = False + + +def process_file(filename): + brace = 0 + maybefunc = None + intable = False + table = None + + acls = {} + aclfilters = {} + errs = False + with open(filename, "r") as fh: + lineno = 0 + for line in fh: + lineno = lineno + 1 + if brace == 0: + # Looks for anything which appears to be a function + # body name. Doesn't matter if we pick up bogus stuff + # here, as long as we don't miss valid stuff + m = re.search(r'''\b(\w+)\(''', line) + if m is not None: + maybefunc = m.group(1) + elif brace > 0: + ensureacl = re.search(r'''(\w+)EnsureACL''', line) + checkacl = re.search(r'''(\w+)CheckACL''', line) + stub = re.search(r'''\b(\w+)\(''', line) + if ensureacl is not None: + # Record the fact that maybefunc contains an + # ACL call, and make sure it is the right call! + func = ensureacl.group(1) + if func.startswith("vir"): + func = func[3:] + + if maybefunc is None: + print("%s:%d Unexpected check '%s' outside function" % + (filename, lineno, func), file=sys.stderr) + errs = True + else: + if not maybefunc.lower().endswith(func.lower()): + print("%s:%d Mismatch check 'vir%sEnsureACL'" + + "for function '%s'" % + (filename, lineno, func, maybefunc), + file=sys.stderr) + errs = True + acls[maybefunc] = True + elif checkacl: + # Record the fact that maybefunc contains an + # ACL filter call, and make sure it is the right call! + func = checkacl.group(1) + if func.startswith("vir"): + func = func[3:] + + if maybefunc is None: + print("%s:%d Unexpected check '%s' outside function" % + (filename, lineno, func), file=sys.stderr) + errs = True + else: + if not maybefunc.lower().endswith(func.lower()): + print("%s:%d Mismatch check 'vir%sEnsureACL' " + + "for function '%s'" % + (filename, lineno, func, maybefunc), + file=sys.stderr) + errs = True + aclfilters[maybefunc] = True + elif stub: + # Handles case where we replaced an API with a new + # one which adds new parameters, and we're left with + # a simple stub calling the new API. + callfunc = stub.group(1) + if callfunc in acls: + acls[maybefunc] = True + + if callfunc in aclfilters: + aclfilters[maybefunc] = True + + # Pass the vir*DriverPtr tables and make sure that + # every func listed there, has an impl which calls + # an ACL function + if intable: + assign = re.search(r'''\.(\w+)\s*=\s*(\w+),?''', line) + if line.find("}") != -1: + intable = False + table = None + elif assign is not None: + api = assign.group(1) + impl = assign.group(2) + + if (impl != "NULL" and + api not in ["no", "name"] and + table != "virStateDriver"): + if (impl not in acls and + api not in whitelist and + impl not in implwhitelist): + print("%s:%d Missing ACL check in " + + "function '%s' for '%s'" % + (filename, lineno, impl, api), + file=sys.stderr) + errs = True + + if api in filteredmap and impl not in aclfilters: + print("%s:%d Missing ACL filter in " + + "function '%s' for '%s'" % + (filename, lineno, impl, api), + file=sys.stderr) + errs = True + else: + m = re.search(r'''^(?:static\s+)?(vir(?:\w+)?Driver)\s+''', + line) + if m is not None: + name = m.group(1) + if name not in ["virNWFilterCallbackDriver", + "virNWFilterTechDriver", + "virDomainConfNWFilterDriver"]: + intable = True + table = name + + if line.find("{") != -1: + brace = brace + 1 + if line.find("}") != -1: + brace = brace - 1 +
The perl version actually counted the braces - hopefully we're not quirky enough to have multiple of them on one line.
+ return errs + + +status = 0 +for filename in sys.argv[2:]: + if process_file(filename): + status = 1 + +sys.exit(status)
Reviewed-by: Ján Tomko <jtomko@redhat.com> Jano

As part of an goal to eliminate Perl from libvirt build tools, rewrite the genpolkit.pl tool in Python. This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same. Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/genpolkit.py | 122 +++++++++++++++++++++++++++++++++++++ src/access/Makefile.inc.am | 6 +- src/access/genpolkit.pl | 119 ------------------------------------ 4 files changed, 126 insertions(+), 122 deletions(-) create mode 100755 scripts/genpolkit.py delete mode 100755 src/access/genpolkit.pl diff --git a/Makefile.am b/Makefile.am index f28b07d814..e7ebe7281a 100644 --- a/Makefile.am +++ b/Makefile.am @@ -54,6 +54,7 @@ EXTRA_DIST = \ scripts/check-symfile.py \ scripts/check-symsorting.py \ scripts/dtrace2systemtap.py \ + scripts/genpolkit.py \ scripts/gensystemtap.py \ scripts/header-ifdef.py \ scripts/minimize-po.py \ diff --git a/scripts/genpolkit.py b/scripts/genpolkit.py new file mode 100755 index 0000000000..0cdba2bd3c --- /dev/null +++ b/scripts/genpolkit.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python +# +# Copyright (C) 2012-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# + +from __future__ import print_function + +import re +import sys + +objects = [ + "CONNECT", "DOMAIN", "INTERFACE", "NETWORK_PORT", + "NETWORK", "NODE_DEVICE", "NWFILTER_BINDING", + "NWFILTER", "SECRET", "STORAGE_POOL", "STORAGE_VOL", +] + +objectstr = "|".join(objects) + +# Data we're going to be generating looks like this +# +# <policyconfig> +# <action id="org.libvirt.unix.monitor"> +# <description>Monitor local virtualized systems</description> +# <message>System policy prevents monitoring of +# local virtualized systems</message> +# <defaults> +# <allow_any>yes</allow_any> +# <allow_inactive>yes</allow_inactive> +# <allow_active>yes</allow_active> +# </defaults> +# </action> +# ...more <action> rules... +# </policyconfig> + +opts = {} +in_opts = False + +perms = {} + +aclfile = sys.argv[1] +with open(aclfile, "r") as fh: + for line in fh: + if in_opts: + if line.find("*/") != -1: + in_opts = False + else: + m = re.search(r'''\*\s*\@(\w+):\s*(.*?)\s*$''', line) + if m is not None: + opts[m.group(1)] = m.group(2) + elif line.find("**") != -1: + in_opts = True + else: + m = re.search(r'''VIR_ACCESS_PERM_(%s)_((?:\w|_)+),''' % + objectstr, line) + if m is not None: + obj = m.group(1).lower() + perm = m.group(2).lower() + if perm == "last": + continue + + obj = obj.replace("_", "-") + perm = perm.replace("_", "-") + + if obj not in perms: + perms[obj] = {} + perms[obj][perm] = { + "desc": opts.get("desc", None), + "message": opts.get("message", None), + "anonymous": opts.get("anonymous", None), + } + opts = {} + +print('<?xml version="1.0" encoding="UTF-8"?>') +print('<!DOCTYPE policyconfig PUBLIC ' + + '"-//freedesktop//DTD polkit Policy Configuration 1.0//EN"') +print(' "http://www.freedesktop.org/software/polkit/policyconfig-1.dtd">') +print('<policyconfig>') +print(' <vendor>Libvirt Project</vendor>') +print(' <vendor_url>https://libvirt.org</vendor_url>') + +for obj in sorted(perms.keys()): + for perm in sorted(perms[obj].keys()): + description = perms[obj][perm]["desc"] + message = perms[obj][perm]["message"] + anonymous = perms[obj][perm]["anonymous"] + + if description is None: + raise Exception("missing description for %s.%s" % (obj, perm)) + if message is None: + raise Exception("missing message for %s.%s" % (obj, perm)) + + allow_any = "no" + if anonymous: + allow_any = "yes" + allow_inactive = allow_any + allow_active = allow_any + + print(' <action id="org.libvirt.api.%s.%s">' % (obj, perm)) + print(' <description>%s</description>' % description) + print(' <message>%s</message>' % message) + print(' <defaults>') + print(' <allow_any>%s</allow_any>' % allow_any) + print(' <allow_inactive>%s</allow_inactive>' % allow_inactive) + print(' <allow_active>%s</allow_active>' % allow_active) + print(' </defaults>') + print(' </action>') + +print('</policyconfig>') diff --git a/src/access/Makefile.inc.am b/src/access/Makefile.inc.am index fd0a5d8098..11f87c6aa7 100644 --- a/src/access/Makefile.inc.am +++ b/src/access/Makefile.inc.am @@ -43,7 +43,6 @@ ACCESS_DRIVER_POLKIT_POLICY = access/org.libvirt.api.policy GENERATED_SYM_FILES += $(ACCESS_DRIVER_SYM_FILES) EXTRA_DIST += \ - access/genpolkit.pl \ $(NULL) @@ -66,8 +65,9 @@ libvirt_driver_access_la_LIBADD = \ $(ACCESS_DRIVER_POLKIT_POLICY): $(srcdir)/access/viraccessperm.h \ - $(srcdir)/access/genpolkit.pl Makefile.am - $(AM_V_GEN)$(PERL) $(srcdir)/access/genpolkit.pl < $< > $@ || rm -f $@ + $(top_srcdir)/scripts/genpolkit.py Makefile.am + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) \ + $(top_srcdir)/scripts/genpolkit.py $< > $@ || rm -f $@ if WITH_POLKIT libvirt_driver_access_la_SOURCES += $(ACCESS_DRIVER_POLKIT_SOURCES) diff --git a/src/access/genpolkit.pl b/src/access/genpolkit.pl deleted file mode 100755 index f8f20caf65..0000000000 --- a/src/access/genpolkit.pl +++ /dev/null @@ -1,119 +0,0 @@ -#!/usr/bin/env perl -# -# Copyright (C) 2012-2013 Red Hat, Inc. -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library. If not, see -# <http://www.gnu.org/licenses/>. -# - -use strict; -use warnings; - -my @objects = ( - "CONNECT", "DOMAIN", "INTERFACE", "NETWORK_PORT", - "NETWORK","NODE_DEVICE", "NWFILTER_BINDING", "NWFILTER", - "SECRET", "STORAGE_POOL", "STORAGE_VOL", - ); - -my $objects = join ("|", @objects); - -# Data we're going to be generating looks like this -# -# <policyconfig> -# <action id="org.libvirt.unix.monitor"> -# <description>Monitor local virtualized systems</description> -# <message>System policy prevents monitoring of local virtualized systems</message> -# <defaults> -# <allow_any>yes</allow_any> -# <allow_inactive>yes</allow_inactive> -# <allow_active>yes</allow_active> -# </defaults> -# </action> -# ...more <action> rules... -# </policyconfig> - -my %opts; -my $in_opts = 0; - -my %perms; - -while (<>) { - if ($in_opts) { - if (m,\*/,) { - $in_opts = 0; - } elsif (/\*\s*\@(\w+):\s*(.*?)\s*$/) { - $opts{$1} = $2; - } - } elsif (m,/\*\*,) { - $in_opts = 1; - } elsif (/VIR_ACCESS_PERM_($objects)_((?:\w|_)+),/) { - my $object = lc $1; - my $perm = lc $2; - next if $perm eq "last"; - - $object =~ s/_/-/g; - $perm =~ s/_/-/g; - - $perms{$object} = {} unless exists $perms{$object}; - $perms{$object}->{$perm} = { - desc => $opts{desc}, - message => $opts{message}, - anonymous => $opts{anonymous} - }; - %opts = (); - } -} - -print <<EOF; -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD polkit Policy Configuration 1.0//EN" - "http://www.freedesktop.org/software/polkit/policyconfig-1.dtd"> -<policyconfig> - <vendor>Libvirt Project</vendor> - <vendor_url>https://libvirt.org</vendor_url> -EOF - -foreach my $object (sort { $a cmp $b } keys %perms) { - foreach my $perm (sort { $a cmp $b } keys %{$perms{$object}}) { - my $description = $perms{$object}->{$perm}->{desc}; - my $message = $perms{$object}->{$perm}->{message}; - my $anonymous = $perms{$object}->{$perm}->{anonymous}; - - die "missing description for $object.$perm" unless - defined $description; - die "missing message for $object.$perm" unless - defined $message; - - my $allow_any = $anonymous ? "yes" : "no"; - my $allow_inactive = $allow_any; - my $allow_active = $allow_any; - - print <<EOF; - <action id="org.libvirt.api.$object.$perm"> - <description>$description</description> - <message>$message</message> - <defaults> - <allow_any>$allow_any</allow_any> - <allow_inactive>$allow_inactive</allow_inactive> - <allow_active>$allow_active</allow_active> - </defaults> - </action> -EOF - - } -} - -print <<EOF; -</policyconfig> -EOF -- 2.21.0

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the genpolkit.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/genpolkit.py | 122 +++++++++++++++++++++++++++++++++++++ src/access/Makefile.inc.am | 6 +- src/access/genpolkit.pl | 119 ------------------------------------ 4 files changed, 126 insertions(+), 122 deletions(-) create mode 100755 scripts/genpolkit.py delete mode 100755 src/access/genpolkit.pl
Generates identical org.libvirt.api.policy for me Tested-by: Cole Robinson <crobinso@redhat.com> - Cole

On Mon, Nov 11, 2019 at 02:38:16PM +0000, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the genpolkit.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/genpolkit.py | 122 +++++++++++++++++++++++++++++++++++++ src/access/Makefile.inc.am | 6 +- src/access/genpolkit.pl | 119 ------------------------------------ 4 files changed, 126 insertions(+), 122 deletions(-) create mode 100755 scripts/genpolkit.py delete mode 100755 src/access/genpolkit.pl
Reviewed-by: Ján Tomko <jtomko@redhat.com> Jano

As part of an goal to eliminate Perl from libvirt build tools, rewrite the pdwtags processing script in Python. The original inline shell and perl code was completely unintelligible. The new python code is a manual conversion that attempts todo basically the same thing. Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + build-aux/syntax-check.mk | 3 +- scripts/check-remote-protocol.py | 136 +++++++++++++++++++++++++++++++ src/Makefile.am | 98 ++++------------------ 4 files changed, 155 insertions(+), 83 deletions(-) create mode 100644 scripts/check-remote-protocol.py diff --git a/Makefile.am b/Makefile.am index e7ebe7281a..8c9c73c715 100644 --- a/Makefile.am +++ b/Makefile.am @@ -50,6 +50,7 @@ EXTRA_DIST = \ scripts/check-aclrules.py \ scripts/check-drivername.py \ scripts/check-driverimpls.py \ + scripts/check-remote-protocol.py \ scripts/check-spacing.py \ scripts/check-symfile.py \ scripts/check-symsorting.py \ diff --git a/build-aux/syntax-check.mk b/build-aux/syntax-check.mk index 26eb5b94d9..a61818855c 100644 --- a/build-aux/syntax-check.mk +++ b/build-aux/syntax-check.mk @@ -412,6 +412,7 @@ sc_prohibit_mkstemp: # access with F_OK or R_OK is okay, though. sc_prohibit_access_xok: @prohibit='access(at)? *\(.*X_OK' \ + in_vc_files='\.[ch]$$' \ halt='use virFileIsExecutable instead of access(,X_OK)' \ $(_sc_search_regexp) @@ -2216,7 +2217,7 @@ exclude_file_name_regexp--sc_prohibit_PATH_MAX = \ ^build-aux/syntax-check\.mk$$ exclude_file_name_regexp--sc_prohibit_access_xok = \ - ^(build-aux/syntax-check\.mk|src/util/virutil\.c)$$ + ^(src/util/virutil\.c)$$ exclude_file_name_regexp--sc_prohibit_asprintf = \ ^(build-aux/syntax-check\.mk|bootstrap.conf$$|examples/|src/util/virstring\.[ch]$$|tests/vircgroupmock\.c|tools/virt-login-shell\.c|tools/nss/libvirt_nss\.c$$) diff --git a/scripts/check-remote-protocol.py b/scripts/check-remote-protocol.py new file mode 100644 index 0000000000..074f8c0ae1 --- /dev/null +++ b/scripts/check-remote-protocol.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python +# +# Copyright (C) 2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# +# This uses pdwtags to check remote protocol defs +# +# * the "split" splits on the /* DD */ comments, so that $p iterates +# through the struct definitions. +# * process only "struct remote_..." entries +# * remove comments and preceding TAB throughout +# * remove empty lines throughout +# * remove white space at end of buffer + +from __future__ import print_function + +import os +import os.path +import re +import subprocess +import sys + +cc = sys.argv[1] +objext = sys.argv[2] +proto_lo = sys.argv[3] +expected = sys.argv[4] + +proto_lo = proto_lo.replace("/", "/.libs/") + +ccargv = cc.split(" ") +ccargv.append("-v") +ccproc = subprocess.Popen(ccargv, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) +out, err = ccproc.communicate() +out = out.decode("utf-8") +if out.find("clang") != -1: + print("WARNING: skipping pdwtags test with Clang", file=sys.stderr) + sys.exit(0) + + +def which(program): + def is_exe(fpath): + return (os.path.isfile(fpath) and + os.access(fpath, os.X_OK)) + + fpath, fname = os.path.split(program) + if fpath: + if is_exe(program): + return program + else: + for path in os.environ["PATH"].split(os.pathsep): + exe_file = os.path.join(path, program) + if is_exe(exe_file): + return exe_file + + return None + + +pdwtags = which("pdwtags") +if pdwtags is None: + print("WARNING: you lack pdwtags; skipping the protocol test", + file=sys.stderr) + print("WARNING: install the dwarves package to get pdwtags", + file=sys.stderr) + sys.exit(0) + +proto_o = proto_lo.replace(".lo", ".o") + +if not os.path.exists(proto_o): + raise Exception("Missing %s", proto_o) + +pdwtagsproc = subprocess.Popen(["pdwtags", "--verbose", proto_o], + stdout=subprocess.PIPE, stderr=subprocess.PIPE) +out, err = pdwtagsproc.communicate() +out = out.decode("utf-8") +err = err.decode("utf-8") + +if out == "" and err != "": + print("WARNING: no output, pdwtags appears broken:", file=sys.stderr) + for l in err.strip().split("\n"): + print("WARNING: %s" % l, file=sys.stderr) + print("WARNING: skipping the remote protocol test", file=sys.stderr) + sys.exit(0) + +# With pdwtags 1.8, --verbose output includes separators like these: +# /* 93 */ +# /* <0> (null):0 */ +# with the second line omitted for intrinsic types. +# Whereas with pdwtags 1.3, they look like this: +# /* <2d2> /usr/include/libio.h:180 */ +# The alternation of the following regexps matches both cases. +r1 = r'''/\* \d+ \*/''' +r2 = r'''/\* <[0-9a-fA-F]+> \S+:\d+ \*/''' + +libs_prefix = "remote_|qemu_|lxc_|admin_" +other_prefix = "keepalive|vir(Net|LockSpace|LXCMonitor)" +struct_prefix = "(" + libs_prefix + "|" + other_prefix + ")" + +n = 0 +bits = re.split(r'''\n*(?:%s|%s)\n''' % (r1, r2), out) +actual = ["/* -*- c -*- */"] + +for bit in bits: + if re.search(r'''^(struct|enum)\s+''' + struct_prefix, bit): + bit = re.sub(r'''\t*/\*.*?\*/''', "", bit) + bit = re.sub(r'''\s+\n''', '''\n''', bit) + bit = re.sub(r'''\s+$''', "", bit) + bit = re.sub(r'''\t''', " ", bit) + actual.append(bit) + n = n + 1 + +if n < 1: + print("WARNING: No structs/enums matched. Your", file=sys.stderr) + print("WARNING: pdwtags program is probably too old", file=sys.stderr) + print("WARNING: skipping the remote protocol test", file=sys.stderr) + print("WARNING: install dwarves-1.3 or newer", file=sys.stderr) + sys.exit(8) + +diff = subprocess.Popen(["diff", "-u", expected, "-"], stdin=subprocess.PIPE) +actualstr = "\n".join(actual) + "\n" +diff.communicate(input=actualstr.encode("utf-8")) + +sys.exit(diff.returncode) diff --git a/src/Makefile.am b/src/Makefile.am index bb63e2486c..c40e61e7ee 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -196,83 +196,6 @@ DRIVER_SOURCES += \ -# Ensure that we don't change the struct or member names or member ordering -# in remote_protocol.x The embedded perl below needs a few comments, and -# presumes you know what pdwtags output looks like: -# * use -0777 -n to slurp the entire file into $_. -# * the "split" splits on the /* DD */ comments, so that $p iterates -# through the struct definitions. -# * process only "struct remote_..." entries -# * remove comments and preceding TAB throughout -# * remove empty lines throughout -# * remove white space at end of buffer - -# With pdwtags 1.8, --verbose output includes separators like these: -# /* 93 */ -# /* <0> (null):0 */ -# with the second line omitted for intrinsic types. -# Whereas with pdwtags 1.3, they look like this: -# /* <2d2> /usr/include/libio.h:180 */ -# The alternation of the following regexps matches both cases. -r1 = /\* \d+ \*/ -r2 = /\* <[[:xdigit:]]+> \S+:\d+ \*/ -libs_prefix = remote_|qemu_|lxc_|admin_ -other_prefix = keepalive|vir(Net|LockSpace|LXCMonitor) -struct_prefix = ($(libs_prefix)|$(other_prefix)) - -# Depending on configure options, libtool creates one or both of -# remote/{,.libs/}libvirt_driver_remote_la-remote_protocol.o. We want -# the newest of the two, in case configure options changed and a stale -# file is left around from an earlier build. -# The pdwtags output is completely different when building with clang -# which causes the comparison against expected output to fail, so skip -# if using clang as CC. -PDWTAGS = \ - $(AM_V_GEN)if $(CC) -v 2>&1 | grep -q clang; then \ - echo 'WARNING: skipping pdwtags test with Clang' >&2; \ - exit 0; \ - fi; \ - if (pdwtags --help) > /dev/null 2>&1; then \ - o=`ls -t $(<:.lo=.$(OBJEXT)) \ - $(subst /,/.libs/,$(<:.lo=.$(OBJEXT))) \ - 2>/dev/null | sed -n 1p`; \ - test -f "$$o" || { echo ".o for $< not found" >&2; exit 1; }; \ - pdwtags --verbose $$o > $(@F)-t1 2> $(@F)-t2; \ - if test ! -s $(@F)-t1 && test -s $(@F)-t2; then \ - rm -rf $(@F)-t?; \ - echo 'WARNING: pdwtags appears broken; skipping the $@ test' >&2;\ - else \ - $(PERL) -0777 -n \ - -e 'foreach my $$p (split m!\n*(?:$(r1)|$(r2))\n!) {' \ - -e ' if ($$p =~ /^(struct|enum) $(struct_prefix)/) {' \ - -e ' $$p =~ s!\t*/\*.*?\*/!!sg;' \ - -e ' $$p =~ s!\s+\n!\n!sg;' \ - -e ' $$p =~ s!\s+$$!!;' \ - -e ' $$p =~ s!\t! !g;' \ - -e ' print "$$p\n";' \ - -e ' $$n++;' \ - -e ' }' \ - -e '}' \ - -e 'BEGIN {' \ - -e ' print "/* -*- c -*- */\n";' \ - -e '}' \ - -e 'END {' \ - -e ' if ($$n < 1) {' \ - -e ' warn "WARNING: your pdwtags program is too old\n";' \ - -e ' warn "WARNING: skipping the $@ test\n";' \ - -e ' warn "WARNING: install dwarves-1.3 or newer\n";' \ - -e ' exit 8;' \ - -e ' }' \ - -e '}' \ - < $(@F)-t1 > $(@F)-t3; \ - case $$? in 8) rm -f $(@F)-t?; exit 0;; 0) ;; *) exit 1;; esac;\ - diff -u $(@)s $(@F)-t3; st=$$?; rm -f $(@F)-t?; exit $$st; \ - fi; \ - else \ - echo 'WARNING: you lack pdwtags; skipping the $@ test' >&2; \ - echo 'WARNING: install the dwarves package to get pdwtags' >&2; \ - fi - # .libs/libvirt.so is built by libtool as a side-effect of the Makefile # rule for libvirt.la. However, checking symbols relies on Linux ELF layout if WITH_LINUX @@ -301,27 +224,38 @@ PROTOCOL_STRUCTS = \ if WITH_REMOTE check-protocol: $(PROTOCOL_STRUCTS) $(PROTOCOL_STRUCTS:structs=struct) +# Ensure that we don't change the struct or member names or member ordering +# in remote_protocol.x The process-pdwtags.py post-processes output to +# extract the bits we want. + +CHECK_REMOTE_PROTOCOL = $(top_srcdir)/scripts/check-remote-protocol.py + # The .o file that pdwtags parses is created as a side effect of running # libtool; but from make's perspective we depend on the .lo file. $(srcdir)/remote_protocol-struct \ $(srcdir)/qemu_protocol-struct \ $(srcdir)/lxc_protocol-struct: \ $(srcdir)/%-struct: remote/libvirt_driver_remote_la-%.lo - $(PDWTAGS) + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(CHECK_REMOTE_PROTOCOL) \ + "$(CC)" "$(OBJEXT)" $< $(@)s $(srcdir)/virnetprotocol-struct $(srcdir)/virkeepaliveprotocol-struct: \ $(srcdir)/%-struct: rpc/libvirt_net_rpc_la-%.lo - $(PDWTAGS) + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(CHECK_REMOTE_PROTOCOL) \ + "$(CC)" "$(OBJEXT)" $< $(@)s if WITH_LXC $(srcdir)/lxc_monitor_protocol-struct: \ $(srcdir)/%-struct: lxc/libvirt_driver_lxc_impl_la-%.lo - $(PDWTAGS) + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(CHECK_REMOTE_PROTOCOL) \ + "$(CC)" "$(OBJEXT)" $< $(@)s endif WITH_LXC $(srcdir)/lock_protocol-struct: \ $(srcdir)/%-struct: locking/lockd_la-%.lo - $(PDWTAGS) + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(CHECK_REMOTE_PROTOCOL) \ + "$(CC)" "$(OBJEXT)" $< $(@)s $(srcdir)/admin_protocol-struct: \ $(srcdir)/%-struct: admin/libvirt_admin_la-%.lo - $(PDWTAGS) + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(CHECK_REMOTE_PROTOCOL) \ + "$(CC)" "$(OBJEXT)" $< $(@)s else !WITH_REMOTE # The $(PROTOCOL_STRUCTS) files must live in git, because they cannot be -- 2.21.0

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the pdwtags processing script in Python.
The original inline shell and perl code was completely unintelligible. The new python code is a manual conversion that attempts todo basically the same thing.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + build-aux/syntax-check.mk | 3 +- scripts/check-remote-protocol.py | 136 +++++++++++++++++++++++++++++++ src/Makefile.am | 98 ++++------------------ 4 files changed, 155 insertions(+), 83 deletions(-) create mode 100644 scripts/check-remote-protocol.py
I verified the script detected a difference in src/qemu_protocol-structs Tested-by: Cole Robinson <crobinso@redhat.com> - Cole

On Mon, Nov 11, 2019 at 02:38:17PM +0000, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the pdwtags processing script in Python.
The original inline shell and perl code was completely unintelligible. The new python code is a manual conversion that attempts todo basically the same thing.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + build-aux/syntax-check.mk | 3 +- scripts/check-remote-protocol.py | 136 +++++++++++++++++++++++++++++++ src/Makefile.am | 98 ++++------------------ 4 files changed, 155 insertions(+), 83 deletions(-) create mode 100644 scripts/check-remote-protocol.py
+if n < 1: + print("WARNING: No structs/enums matched. Your", file=sys.stderr) + print("WARNING: pdwtags program is probably too old", file=sys.stderr) + print("WARNING: skipping the remote protocol test", file=sys.stderr) + print("WARNING: install dwarves-1.3 or newer", file=sys.stderr) + sys.exit(8) + +diff = subprocess.Popen(["diff", "-u", expected, "-"], stdin=subprocess.PIPE) +actualstr = "\n".join(actual) + "\n" +diff.communicate(input=actualstr.encode("utf-8")) + +sys.exit(diff.returncode) diff --git a/src/Makefile.am b/src/Makefile.am index bb63e2486c..c40e61e7ee 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -196,83 +196,6 @@ DRIVER_SOURCES += \
-# Ensure that we don't change the struct or member names or member ordering -# in remote_protocol.x The embedded perl below needs a few comments, and -# presumes you know what pdwtags output looks like: -# * use -0777 -n to slurp the entire file into $_. -# * the "split" splits on the /* DD */ comments, so that $p iterates -# through the struct definitions. -# * process only "struct remote_..." entries -# * remove comments and preceding TAB throughout -# * remove empty lines throughout -# * remove white space at end of buffer - -# With pdwtags 1.8, --verbose output includes separators like these: -# /* 93 */ -# /* <0> (null):0 */ -# with the second line omitted for intrinsic types. -# Whereas with pdwtags 1.3, they look like this: -# /* <2d2> /usr/include/libio.h:180 */ -# The alternation of the following regexps matches both cases. -r1 = /\* \d+ \*/ -r2 = /\* <[[:xdigit:]]+> \S+:\d+ \*/ -libs_prefix = remote_|qemu_|lxc_|admin_ -other_prefix = keepalive|vir(Net|LockSpace|LXCMonitor) -struct_prefix = ($(libs_prefix)|$(other_prefix)) - -# Depending on configure options, libtool creates one or both of -# remote/{,.libs/}libvirt_driver_remote_la-remote_protocol.o. We want -# the newest of the two, in case configure options changed and a stale -# file is left around from an earlier build.
So I assume the configure option that gives you the path without .libs is gone?
-# The pdwtags output is completely different when building with clang -# which causes the comparison against expected output to fail, so skip -# if using clang as CC. -PDWTAGS = \ - $(AM_V_GEN)if $(CC) -v 2>&1 | grep -q clang; then \ - echo 'WARNING: skipping pdwtags test with Clang' >&2; \ - exit 0; \ - fi; \ - if (pdwtags --help) > /dev/null 2>&1; then \ - o=`ls -t $(<:.lo=.$(OBJEXT)) \ - $(subst /,/.libs/,$(<:.lo=.$(OBJEXT))) \ - 2>/dev/null | sed -n 1p`; \
And that OBJEXT is always .o
- test -f "$$o" || { echo ".o for $< not found" >&2; exit 1; }; \ - pdwtags --verbose $$o > $(@F)-t1 2> $(@F)-t2; \ - if test ! -s $(@F)-t1 && test -s $(@F)-t2; then \ - rm -rf $(@F)-t?; \ - echo 'WARNING: pdwtags appears broken; skipping the $@ test' >&2;\ - else \ - $(PERL) -0777 -n \ - -e 'foreach my $$p (split m!\n*(?:$(r1)|$(r2))\n!) {' \ - -e ' if ($$p =~ /^(struct|enum) $(struct_prefix)/) {' \ - -e ' $$p =~ s!\t*/\*.*?\*/!!sg;' \ - -e ' $$p =~ s!\s+\n!\n!sg;' \ - -e ' $$p =~ s!\s+$$!!;' \ - -e ' $$p =~ s!\t! !g;' \ - -e ' print "$$p\n";' \ - -e ' $$n++;' \ - -e ' }' \ - -e '}' \ - -e 'BEGIN {' \ - -e ' print "/* -*- c -*- */\n";' \ - -e '}' \ - -e 'END {' \ - -e ' if ($$n < 1) {' \ - -e ' warn "WARNING: your pdwtags program is too old\n";' \ - -e ' warn "WARNING: skipping the $@ test\n";' \ - -e ' warn "WARNING: install dwarves-1.3 or newer\n";' \ - -e ' exit 8;' \ - -e ' }' \ - -e '}' \ - < $(@F)-t1 > $(@F)-t3; \ - case $$? in 8) rm -f $(@F)-t?; exit 0;; 0) ;; *) exit 1;; esac;\ - diff -u $(@)s $(@F)-t3; st=$$?; rm -f $(@F)-t?; exit $$st; \ - fi; \ - else \ - echo 'WARNING: you lack pdwtags; skipping the $@ test' >&2; \ - echo 'WARNING: install the dwarves package to get pdwtags' >&2; \ - fi - # .libs/libvirt.so is built by libtool as a side-effect of the Makefile # rule for libvirt.la. However, checking symbols relies on Linux ELF layout if WITH_LINUX @@ -301,27 +224,38 @@ PROTOCOL_STRUCTS = \ if WITH_REMOTE check-protocol: $(PROTOCOL_STRUCTS) $(PROTOCOL_STRUCTS:structs=struct)
+# Ensure that we don't change the struct or member names or member ordering +# in remote_protocol.x The process-pdwtags.py post-processes output to
Here you refer to process-pdwtags.py but the script is called check-remote-protocol.py
+# extract the bits we want. + +CHECK_REMOTE_PROTOCOL = $(top_srcdir)/scripts/check-remote-protocol.py +
With the comment fixed or the script renamed: Reviewed-by: Ján Tomko <jtomko@redhat.com> Jano

On Wed, Nov 20, 2019 at 02:13:37PM +0100, Ján Tomko wrote:
On Mon, Nov 11, 2019 at 02:38:17PM +0000, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the pdwtags processing script in Python.
The original inline shell and perl code was completely unintelligible. The new python code is a manual conversion that attempts todo basically the same thing.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + build-aux/syntax-check.mk | 3 +- scripts/check-remote-protocol.py | 136 +++++++++++++++++++++++++++++++ src/Makefile.am | 98 ++++------------------ 4 files changed, 155 insertions(+), 83 deletions(-) create mode 100644 scripts/check-remote-protocol.py
+if n < 1: + print("WARNING: No structs/enums matched. Your", file=sys.stderr) + print("WARNING: pdwtags program is probably too old", file=sys.stderr) + print("WARNING: skipping the remote protocol test", file=sys.stderr) + print("WARNING: install dwarves-1.3 or newer", file=sys.stderr) + sys.exit(8) + +diff = subprocess.Popen(["diff", "-u", expected, "-"], stdin=subprocess.PIPE) +actualstr = "\n".join(actual) + "\n" +diff.communicate(input=actualstr.encode("utf-8")) + +sys.exit(diff.returncode) diff --git a/src/Makefile.am b/src/Makefile.am index bb63e2486c..c40e61e7ee 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -196,83 +196,6 @@ DRIVER_SOURCES += \
-# Ensure that we don't change the struct or member names or member ordering -# in remote_protocol.x The embedded perl below needs a few comments, and -# presumes you know what pdwtags output looks like: -# * use -0777 -n to slurp the entire file into $_. -# * the "split" splits on the /* DD */ comments, so that $p iterates -# through the struct definitions. -# * process only "struct remote_..." entries -# * remove comments and preceding TAB throughout -# * remove empty lines throughout -# * remove white space at end of buffer - -# With pdwtags 1.8, --verbose output includes separators like these: -# /* 93 */ -# /* <0> (null):0 */ -# with the second line omitted for intrinsic types. -# Whereas with pdwtags 1.3, they look like this: -# /* <2d2> /usr/include/libio.h:180 */ -# The alternation of the following regexps matches both cases. -r1 = /\* \d+ \*/ -r2 = /\* <[[:xdigit:]]+> \S+:\d+ \*/ -libs_prefix = remote_|qemu_|lxc_|admin_ -other_prefix = keepalive|vir(Net|LockSpace|LXCMonitor) -struct_prefix = ($(libs_prefix)|$(other_prefix)) - -# Depending on configure options, libtool creates one or both of -# remote/{,.libs/}libvirt_driver_remote_la-remote_protocol.o. We want -# the newest of the two, in case configure options changed and a stale -# file is left around from an earlier build.
So I assume the configure option that gives you the path without .libs is gone?
I honestly don't know what configure option it might have been referring to in the first place. My guess was perhaps related to --disable-shared to force a static library build. Libvirt fails to link when doing this and we never test it, so I considerd static build out of scope, and in any case when i try it a .libs dir still appears In absence of a clear need I figured just ignore this comment and lets see if anyone reports breakage that our CI systems don't catch.
-# The pdwtags output is completely different when building with clang -# which causes the comparison against expected output to fail, so skip -# if using clang as CC. -PDWTAGS = \ - $(AM_V_GEN)if $(CC) -v 2>&1 | grep -q clang; then \ - echo 'WARNING: skipping pdwtags test with Clang' >&2; \ - exit 0; \ - fi; \ - if (pdwtags --help) > /dev/null 2>&1; then \ - o=`ls -t $(<:.lo=.$(OBJEXT)) \ - $(subst /,/.libs/,$(<:.lo=.$(OBJEXT))) \ - 2>/dev/null | sed -n 1p`; \
And that OBJEXT is always .o
Same note as above.
- test -f "$$o" || { echo ".o for $< not found" >&2; exit 1; }; \ - pdwtags --verbose $$o > $(@F)-t1 2> $(@F)-t2; \ - if test ! -s $(@F)-t1 && test -s $(@F)-t2; then \ - rm -rf $(@F)-t?; \ - echo 'WARNING: pdwtags appears broken; skipping the $@ test' >&2;\ - else \ - $(PERL) -0777 -n \ - -e 'foreach my $$p (split m!\n*(?:$(r1)|$(r2))\n!) {' \ - -e ' if ($$p =~ /^(struct|enum) $(struct_prefix)/) {' \ - -e ' $$p =~ s!\t*/\*.*?\*/!!sg;' \ - -e ' $$p =~ s!\s+\n!\n!sg;' \ - -e ' $$p =~ s!\s+$$!!;' \ - -e ' $$p =~ s!\t! !g;' \ - -e ' print "$$p\n";' \ - -e ' $$n++;' \ - -e ' }' \ - -e '}' \ - -e 'BEGIN {' \ - -e ' print "/* -*- c -*- */\n";' \ - -e '}' \ - -e 'END {' \ - -e ' if ($$n < 1) {' \ - -e ' warn "WARNING: your pdwtags program is too old\n";' \ - -e ' warn "WARNING: skipping the $@ test\n";' \ - -e ' warn "WARNING: install dwarves-1.3 or newer\n";' \ - -e ' exit 8;' \ - -e ' }' \ - -e '}' \ - < $(@F)-t1 > $(@F)-t3; \ - case $$? in 8) rm -f $(@F)-t?; exit 0;; 0) ;; *) exit 1;; esac;\ - diff -u $(@)s $(@F)-t3; st=$$?; rm -f $(@F)-t?; exit $$st; \ - fi; \ - else \ - echo 'WARNING: you lack pdwtags; skipping the $@ test' >&2; \ - echo 'WARNING: install the dwarves package to get pdwtags' >&2; \ - fi - # .libs/libvirt.so is built by libtool as a side-effect of the Makefile # rule for libvirt.la. However, checking symbols relies on Linux ELF layout if WITH_LINUX @@ -301,27 +224,38 @@ PROTOCOL_STRUCTS = \ if WITH_REMOTE check-protocol: $(PROTOCOL_STRUCTS) $(PROTOCOL_STRUCTS:structs=struct)
+# Ensure that we don't change the struct or member names or member ordering +# in remote_protocol.x The process-pdwtags.py post-processes output to
Here you refer to process-pdwtags.py but the script is called check-remote-protocol.py
+# extract the bits we want. + +CHECK_REMOTE_PROTOCOL = $(top_srcdir)/scripts/check-remote-protocol.py +
With the comment fixed or the script renamed:
Reviewed-by: Ján Tomko <jtomko@redhat.com>
Jano
Regards, Daniel -- |: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|

As part of an goal to eliminate Perl from libvirt build tools, rewrite the test-wrap-argv.pl tool in Python. This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same. Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + build-aux/syntax-check.mk | 4 +- scripts/test-wrap-argv.py | 170 +++++++++++++++++++++++++++++++++++++ tests/test-wrap-argv.pl | 174 -------------------------------------- tests/testutils.c | 16 ++-- 5 files changed, 181 insertions(+), 184 deletions(-) create mode 100755 scripts/test-wrap-argv.py delete mode 100755 tests/test-wrap-argv.pl diff --git a/Makefile.am b/Makefile.am index 8c9c73c715..6f6cead526 100644 --- a/Makefile.am +++ b/Makefile.am @@ -61,6 +61,7 @@ EXTRA_DIST = \ scripts/minimize-po.py \ scripts/mock-noinline.py \ scripts/prohibit-duplicate-header.py \ + scripts/test-wrap-argv.py \ build-aux/syntax-check.mk \ build-aux/useless-if-before-free \ build-aux/vc-list-files \ diff --git a/build-aux/syntax-check.mk b/build-aux/syntax-check.mk index a61818855c..7d54df182a 100644 --- a/build-aux/syntax-check.mk +++ b/build-aux/syntax-check.mk @@ -2172,8 +2172,8 @@ header-ifdef: $(PYTHON) $(top_srcdir)/scripts/header-ifdef.py test-wrap-argv: - $(AM_V_GEN)$(VC_LIST) | $(GREP) -E '\.(ldargs|args)' | xargs \ - $(PERL) $(top_srcdir)/tests/test-wrap-argv.pl --check + $(AM_V_GEN)$(VC_LIST) | $(GREP) -E '\.(ldargs|args)' | $(RUNUTF8) xargs \ + $(PYTHON) $(top_srcdir)/scripts/test-wrap-argv.py --check group-qemu-caps: $(AM_V_GEN)$(PERL) $(top_srcdir)/tests/group-qemu-caps.pl --check $(top_srcdir)/ diff --git a/scripts/test-wrap-argv.py b/scripts/test-wrap-argv.py new file mode 100755 index 0000000000..dd9e7de824 --- /dev/null +++ b/scripts/test-wrap-argv.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python +# +# Copyright (C) 2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# +# This script is intended to be passed a list of .args files, used +# to store command line ARGV for the test suites. It will reformat +# them such that there is at most one '-param value' on each line +# of the file. Parameter values that are longer than 80 chars will +# also be split. +# +# If --in-place is supplied as the first parameter of this script, +# the files will be changed in place. +# If --check is the first parameter, the script will return +# a non-zero value if a file is not wrapped correctly. +# Otherwise the rewrapped files are printed to the standard output. + +from __future__ import print_function + +import argparse +import subprocess +import sys + + +def rewrap_line(line): + bits = line.split(" ") + + # bits contains env vars, then the command line + # and then the arguments + env = [] + cmd = None + args = [] + + if bits[0].find("=") == -1: + cmd = bits[0] + bits = bits[1:] + + for bit in bits: + # If no command is defined yet, we must still + # have env vars + if cmd is None: + # Look for leading / to indicate command name + if bit.startswith("/"): + cmd = bit + else: + env.append(bit) + else: + # If there's a leading '-' then this is a new + # parameter, otherwise its a value for the prev + # parameter. + if bit.startswith("-"): + args.append(bit) + else: + args[-1] = args[-1] + " " + bit + + # We might have to split line argument values... + args = [rewrap_arg(arg) for arg in args] + + # Print env + command first + return " \\\n".join(env + [cmd] + args) + "\n" + + +def rewrap_arg(arg): + ret = [] + max_len = 78 + + while len(arg) > max_len: + split = arg.rfind(",", 0, max_len + 1) + if split == -1: + split = arg.rfind(":", 0, max_len + 1) + if split == -1: + split = arg.rfind(" ", 0, max_len + 1) + if split == -1: + print("cannot find nice place to split '%s' below 80 chars" % + arg, file=sys.stderr) + split = max_len - 1 + + split = split + 1 + + ret.append(arg[0:split]) + arg = arg[split:] + + ret.append(arg) + return "\\\n".join(ret) + + +def rewrap(filename, in_place, check): + # Read the original file + with open(filename, 'r') as fh: + orig_lines = [] + for line in fh: + orig_lines.append(line) + + if len(orig_lines) == 0: + return + + lines = [] + for line in orig_lines: + if line.endswith("\\\n"): + line = line[:-2] + lines.append(line) + + # Kill the last new line in the file + lines[-1] = lines[-1].rstrip("\n") + + # Reconstruct the master data by joining all lines + # and then split again based on the real desired + # newlines + lines = "".join(lines).split("\n") + + # Now each 'lines' entry represents a single command, we + # can process them + new_lines = [] + for line in lines: + new_lines.append(rewrap_line(line)) + + if in_place: + with open(filename, "w") as fh: + for line in new_lines: + print(line, file=fh) + elif check: + orig = "".join(orig_lines) + new = "".join(new_lines) + if new != orig: + diff = subprocess.Popen(["diff", "-u", filename, "-"], + stdin=subprocess.PIPE) + diff.communicate(input=new.encode('utf-8')) + + print("Incorrect line wrapping in $file", + file=sys.stderr) + print("Use test-wrap-argv.py to wrap test data files", + file=sys.stderr) + return False + else: + for line in new_lines: + print(line) + + return True + + +parser = argparse.ArgumentParser(description='Test arg line wrapper') +parser.add_argument('--in-place', '-i', action="store_true", + help='modify files in-place') +parser.add_argument('--check', action="store_true", + help='check existing files only') +parser.add_argument('files', nargs="+", + help="filenames to check") +args = parser.parse_args() + +errs = False +for filename in args.files: + if not rewrap(filename, args.in_place, args.check): + errs = True + +if errs: + sys.exit(1) +sys.exit(0) diff --git a/tests/test-wrap-argv.pl b/tests/test-wrap-argv.pl deleted file mode 100755 index 7867e9d719..0000000000 --- a/tests/test-wrap-argv.pl +++ /dev/null @@ -1,174 +0,0 @@ -#!/usr/bin/env perl -# -# Copyright (C) 2015 Red Hat, Inc. -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library. If not, see -# <http://www.gnu.org/licenses/>. -# -# This script is intended to be passed a list of .args files, used -# to store command line ARGV for the test suites. It will reformat -# them such that there is at most one '-param value' on each line -# of the file. Parameter values that are longer than 80 chars will -# also be split. -# -# If --in-place is supplied as the first parameter of this script, -# the files will be changed in place. -# If --check is the first parameter, the script will return -# a non-zero value if a file is not wrapped correctly. -# Otherwise the rewrapped files are printed to the standard output. - -$in_place = 0; -$check = 0; - -if (@ARGV[0] eq "--in-place" or @ARGV[0] eq "-i") { - $in_place = 1; - shift @ARGV; -} elsif (@ARGV[0] eq "--check") { - $check = 1; - shift @ARGV; -} - -$ret = 0; -foreach my $file (@ARGV) { - if (&rewrap($file) < 0) { - $ret = 1; - } -} - -exit $ret; - -sub rewrap { - my $file = shift; - - # Read the original file - open FILE, "<", $file or die "cannot read $file: $!"; - my @orig_lines = <FILE>; - close FILE; - my @lines = @orig_lines; - foreach (@lines) { - # If there is a trailing '\' then kill the new line - if (/\\$/) { - chomp; - $_ =~ s/\\$//; - } - } - - # Skip empty files - return unless @lines; - - # Kill the last new line in the file - chomp @lines[$#lines]; - - # Reconstruct the master data by joining all lines - # and then split again based on the real desired - # newlines - @lines = split /\n/, join('', @lines); - - # Now each @lines represents a single command, we - # can process them - @lines = map { &rewrap_line($_) } @lines; - - if ($in_place) { - open FILE, ">", $file or die "cannot write $file: $!"; - foreach my $line (@lines) { - print FILE $line; - } - close FILE; - } elsif ($check) { - my $nl = join('', @lines); - my $ol = join('', @orig_lines); - unless ($nl eq $ol) { - open DIFF, "| diff -u $file -" or die "cannot run diff: $!"; - print DIFF $nl; - close DIFF; - - print STDERR "Incorrect line wrapping in $file\n"; - print STDERR "Use test-wrap-argv.pl to wrap test data files\n"; - return -1; - } - } else { - foreach my $line (@lines) { - print $line; - } - } - return 0; -} - -sub rewrap_line { - my $line = shift; - my @bits = split / /, join('', $line); - - # @bits contains env vars, then the command line - # and then the arguments - my @env; - my $cmd; - my @args; - - if ($bits[0] !~ /=/) { - $cmd = shift @bits; - } - - foreach my $bit (@bits) { - # If no command is defined yet, we must still - # have env vars - if (!defined $cmd) { - # Look for leading / to indicate command name - if ($bit =~ m,^/,) { - $cmd = $bit; - } else { - push @env, $bit; - } - } else { - # If there's a leading '-' then this is a new - # parameter, otherwise its a value for the prev - # parameter. - if ($bit =~ m,^-,) { - push @args, $bit; - } else { - $args[$#args] .= " " . $bit; - } - } - } - - # We might have to split line argument values... - @args = map { &rewrap_arg($_) } @args; - # Print env + command first - return join(" \\\n", @env, $cmd, @args), "\n"; -} - -sub rewrap_arg { - my $arg = shift; - my @ret; - my $max_len = 78; - - while (length($arg) > $max_len) { - my $split = rindex $arg, ",", $max_len; - if ($split == -1) { - $split = rindex $arg, ":", $max_len; - } - if ($split == -1) { - $split = rindex $arg, " ", $max_len; - } - if ($split == -1) { - warn "cannot find nice place to split '$arg' below 80 chars\n"; - $split = $max_len - 1; - } - $split++; - - push @ret, substr $arg, 0, $split; - $arg = substr $arg, $split; - } - push @ret, $arg; - return join("\\\n", @ret); -} diff --git a/tests/testutils.c b/tests/testutils.c index da236c74a1..1acdc71fca 100644 --- a/tests/testutils.c +++ b/tests/testutils.c @@ -59,7 +59,7 @@ static size_t testCounter; static virBitmapPtr testBitmap; char *progname; -static char *perl; +static char *python; static int virTestUseTerminalColors(void) { @@ -399,15 +399,15 @@ virTestRewrapFile(const char *filename) virStringHasSuffix(filename, ".ldargs"))) return 0; - if (!perl) { - fprintf(stderr, "cannot rewrap %s: unable to find perl in path", filename); + if (!python) { + fprintf(stderr, "cannot rewrap %s: unable to find python in path", filename); return -1; } - if (virAsprintf(&script, "%s/test-wrap-argv.pl", abs_srcdir) < 0) + if (virAsprintf(&script, "%s/scripts/test-wrap-argv.py", abs_top_srcdir) < 0) goto cleanup; - cmd = virCommandNewArgList(perl, script, "--in-place", filename, NULL); + cmd = virCommandNewArgList(python, script, "--in-place", filename, NULL); if (virCommandRun(cmd, NULL) < 0) goto cleanup; @@ -895,8 +895,8 @@ int virTestMain(int argc, } } - /* Find perl early because some tests override PATH */ - perl = virFindFileInPath("perl"); + /* Find python early because some tests override PATH */ + python = virFindFileInPath("python"); ret = (func)(); @@ -907,7 +907,7 @@ int virTestMain(int argc, fprintf(stderr, " %-3zu %s\n", testCounter, ret == 0 ? "OK" : "FAIL"); } virLogReset(); - VIR_FREE(perl); + VIR_FREE(python); return ret; } -- 2.21.0

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the test-wrap-argv.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + build-aux/syntax-check.mk | 4 +- scripts/test-wrap-argv.py | 170 +++++++++++++++++++++++++++++++++++++ tests/test-wrap-argv.pl | 174 -------------------------------------- tests/testutils.c | 16 ++-- 5 files changed, 181 insertions(+), 184 deletions(-) create mode 100755 scripts/test-wrap-argv.py delete mode 100755 tests/test-wrap-argv.pl
./scripts/test-wrap-argv.py --in-place tests/qemuxml2argvdata/*.args isn't idempotent, it adds trailing whitespace, but I didn't investigate. The perl script doesn't alter those files - Cole

On Mon, Nov 11, 2019 at 02:38:18PM +0000, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools,
a goal? the goal?
rewrite the test-wrap-argv.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + build-aux/syntax-check.mk | 4 +- scripts/test-wrap-argv.py | 170 +++++++++++++++++++++++++++++++++++++ tests/test-wrap-argv.pl | 174 -------------------------------------- tests/testutils.c | 16 ++-- 5 files changed, 181 insertions(+), 184 deletions(-) create mode 100755 scripts/test-wrap-argv.py delete mode 100755 tests/test-wrap-argv.pl
+def rewrap_line(line): + bits = line.split(" ") + + # bits contains env vars, then the command line + # and then the arguments + env = [] + cmd = None + args = [] + + if bits[0].find("=") == -1:
if "=" not in bits[0]:
+ cmd = bits[0] + bits = bits[1:] +
[...]
+ + # Now each 'lines' entry represents a single command, we + # can process them + new_lines = [] + for line in lines: + new_lines.append(rewrap_line(line)) + + if in_place: + with open(filename, "w") as fh: + for line in new_lines: + print(line, file=fh)
This print needs an end='' to match the perl script behavior.
+ elif check: + orig = "".join(orig_lines) + new = "".join(new_lines) + if new != orig: + diff = subprocess.Popen(["diff", "-u", filename, "-"], + stdin=subprocess.PIPE) + diff.communicate(input=new.encode('utf-8')) + + print("Incorrect line wrapping in $file", + file=sys.stderr) + print("Use test-wrap-argv.py to wrap test data files", + file=sys.stderr) + return False + else: + for line in new_lines: + print(line)
Same here.
+ + return True + +
Reviewed-by: Ján Tomko <jtomko@redhat.com> Jano

As part of an goal to eliminate Perl from libvirt build tools, rewrite the group-qemu-caps.pl tool in Python. This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same. Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + build-aux/syntax-check.mk | 3 +- scripts/group-qemu-caps.py | 123 ++++++++++++++++++++++++++++++++++++ tests/group-qemu-caps.pl | 124 ------------------------------------- 4 files changed, 126 insertions(+), 125 deletions(-) create mode 100755 scripts/group-qemu-caps.py delete mode 100755 tests/group-qemu-caps.pl diff --git a/Makefile.am b/Makefile.am index 6f6cead526..769cd4ce64 100644 --- a/Makefile.am +++ b/Makefile.am @@ -57,6 +57,7 @@ EXTRA_DIST = \ scripts/dtrace2systemtap.py \ scripts/genpolkit.py \ scripts/gensystemtap.py \ + scripts/group-qemu-caps.py \ scripts/header-ifdef.py \ scripts/minimize-po.py \ scripts/mock-noinline.py \ diff --git a/build-aux/syntax-check.mk b/build-aux/syntax-check.mk index 7d54df182a..44639f499e 100644 --- a/build-aux/syntax-check.mk +++ b/build-aux/syntax-check.mk @@ -2176,7 +2176,8 @@ test-wrap-argv: $(PYTHON) $(top_srcdir)/scripts/test-wrap-argv.py --check group-qemu-caps: - $(AM_V_GEN)$(PERL) $(top_srcdir)/tests/group-qemu-caps.pl --check $(top_srcdir)/ + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(top_srcdir)/scripts/group-qemu-caps.py \ + --check --prefix $(top_srcdir)/ # List all syntax-check exemptions: exclude_file_name_regexp--sc_avoid_strcase = ^tools/vsh\.h$$ diff --git a/scripts/group-qemu-caps.py b/scripts/group-qemu-caps.py new file mode 100755 index 0000000000..3edaf5d09f --- /dev/null +++ b/scripts/group-qemu-caps.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# +# +# Regroup array values into smaller groups separated by numbered comments. +# +# If --check is the first parameter, the script will return +# a non-zero value if a file is not grouped correctly. +# Otherwise the files are regrouped in place. + +from __future__ import print_function + +import argparse +import re +import subprocess +import sys + + +def regroup_caps(check, filename, start_regex, end_regex, + trailing_newline, counter_prefix): + step = 5 + + original = [] + with open(filename, "r") as fh: + for line in fh: + original.append(line) + + fixed = [] + game_on = False + counter = 0 + for line in original: + line = line.rstrip("\n") + if game_on: + if re.search(r'''.*/\* [0-9]+ \*/.*''', line): + continue + if re.search(r'''^\s*$''', line): + continue + if counter % step == 0: + if counter != 0: + fixed.append("\n") + fixed.append("%s/* %d */\n" % (counter_prefix, counter)) + + if not (line.find("/*") != -1 and line.find("*/") == -1): + # count two-line comments as one line + counter = counter + 1 + + if re.search(start_regex, line): + game_on = True + elif game_on and re.search(end_regex, line): + if (counter - 1) % step == 0: + fixed = fixed[:-1] # /* $counter */ + if counter != 1: + fixed = fixed[:-1] # \n + + if trailing_newline: + fixed.append("\n") + + game_on = False + + fixed.append(line + "\n") + + if check: + orig = "".join(original) + new = "".join(fixed) + if new != orig: + diff = subprocess.Popen(["diff", "-u", filename, "-"], + stdin=subprocess.PIPE) + diff.communicate(input=new.encode('utf-8')) + + print("Incorrect line wrapping in $file", + file=sys.stderr) + print("Use test-wrap-argv.py to wrap test data files", + file=sys.stderr) + return False + else: + with open(filename, "w") as fh: + for line in fixed: + print(line, file=fh, end='') + + return True + + +parser = argparse.ArgumentParser(description='Test arg line wrapper') +parser.add_argument('--check', action="store_true", + help='check existing files only') +parser.add_argument('--prefix', default='', + help='source code tree prefix') +args = parser.parse_args() + +errs = False + +if not regroup_caps(args.check, + args.prefix + 'src/qemu/qemu_capabilities.c', + r'virQEMUCaps grouping marker', + r'\);', + 0, + " "): + errs = True + +if not regroup_caps(args.check, + args.prefix + 'src/qemu/qemu_capabilities.h', + r'virQEMUCapsFlags grouping marker', + r'QEMU_CAPS_LAST \/\* this must', + 1, + " "): + errs = True + +if errs: + sys.exit(1) +sys.exit(0) diff --git a/tests/group-qemu-caps.pl b/tests/group-qemu-caps.pl deleted file mode 100755 index 829e63a562..0000000000 --- a/tests/group-qemu-caps.pl +++ /dev/null @@ -1,124 +0,0 @@ -#!/usr/bin/env perl -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library. If not, see -# <http://www.gnu.org/licenses/>. -# -# -# Regroup array values into smaller groups separated by numbered comments. -# -# If --check is the first parameter, the script will return -# a non-zero value if a file is not grouped correctly. -# Otherwise the files are regrouped in place. - -use strict; -use warnings; - -my $check = 0; - -if (defined $ARGV[0] && $ARGV[0] eq "--check") { - $check = 1; - shift @ARGV; -} - -my $prefix = ''; -if (defined $ARGV[0]) { - $prefix = $ARGV[0]; - shift @ARGV; -} - -my $ret = 0; -if (®roup_caps($prefix . 'src/qemu/qemu_capabilities.c', - 'virQEMUCaps grouping marker', - '\);', - 0, - " ") < 0) { - $ret = 1; -} -if (®roup_caps($prefix . 'src/qemu/qemu_capabilities.h', - 'virQEMUCapsFlags grouping marker', - 'QEMU_CAPS_LAST \/\* this must', - 1, - " ") < 0) { - $ret = 1; -} - -exit $ret; - -sub regroup_caps { - my $filename = shift; - my $start_regex = shift; - my $end_regex = shift; - my $trailing_newline = shift; - my $counter_prefix = shift; - my $step = 5; - - open FILE, '<', $filename or die "cannot open $filename: $!"; - my @original = <FILE>; - close FILE; - - my @fixed; - my $game_on = 0; - my $counter = 0; - foreach (@original) { - if ($game_on) { - next if ($_ =~ '/\* [0-9]+ \*/'); - next if (/^\s+$/); - if ($counter % $step == 0) { - if ($counter != 0) { - push @fixed, "\n"; - } - push @fixed, "$counter_prefix/* $counter */\n"; - } - if (!($_ =~ '/\*' && !($_ =~ '\*/'))) { - # count two-line comments as one line - $counter++; - } - } - if (/$start_regex/) { - $game_on = 1; - } elsif ($game_on && $_ =~ /$end_regex/) { - if (($counter -1) % $step == 0) { - pop @fixed; # /* $counter */ - if ($counter != 1) { - pop @fixed; # \n - } - } - if ($trailing_newline) { - push @fixed, "\n"; - } - $game_on = 0; - } - push @fixed, $_; - } - - if ($check) { - my $nl = join('', @fixed); - my $ol = join('', @original); - unless ($nl eq $ol) { - open DIFF, "| diff -u $filename -" or die "cannot run diff: $!"; - print DIFF $nl; - close DIFF; - - print STDERR "Incorrect array grouping in $filename\n"; - print STDERR "Use group-qemu-caps.pl to group long array members\n"; - return -1; - } - } else { - open FILE, '>', $filename or die "cannot open $filename: $!"; - foreach my $line (@fixed) { - print FILE $line; - } - close FILE; - } -} -- 2.21.0

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the group-qemu-caps.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + build-aux/syntax-check.mk | 3 +- scripts/group-qemu-caps.py | 123 ++++++++++++++++++++++++++++++++++++ tests/group-qemu-caps.pl | 124 ------------------------------------- 4 files changed, 126 insertions(+), 125 deletions(-) create mode 100755 scripts/group-qemu-caps.py delete mode 100755 tests/group-qemu-caps.pl
diff --git a/Makefile.am b/Makefile.am index 6f6cead526..769cd4ce64 100644 --- a/Makefile.am +++ b/Makefile.am @@ -57,6 +57,7 @@ EXTRA_DIST = \ scripts/dtrace2systemtap.py \ scripts/genpolkit.py \ scripts/gensystemtap.py \ + scripts/group-qemu-caps.py \ scripts/header-ifdef.py \ scripts/minimize-po.py \ scripts/mock-noinline.py \ diff --git a/build-aux/syntax-check.mk b/build-aux/syntax-check.mk index 7d54df182a..44639f499e 100644 --- a/build-aux/syntax-check.mk +++ b/build-aux/syntax-check.mk @@ -2176,7 +2176,8 @@ test-wrap-argv: $(PYTHON) $(top_srcdir)/scripts/test-wrap-argv.py --check
group-qemu-caps: - $(AM_V_GEN)$(PERL) $(top_srcdir)/tests/group-qemu-caps.pl --check $(top_srcdir)/ + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(top_srcdir)/scripts/group-qemu-caps.py \ + --check --prefix $(top_srcdir)/
# List all syntax-check exemptions: exclude_file_name_regexp--sc_avoid_strcase = ^tools/vsh\.h$$ diff --git a/scripts/group-qemu-caps.py b/scripts/group-qemu-caps.py new file mode 100755 index 0000000000..3edaf5d09f --- /dev/null +++ b/scripts/group-qemu-caps.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# +# +# Regroup array values into smaller groups separated by numbered comments. +# +# If --check is the first parameter, the script will return +# a non-zero value if a file is not grouped correctly. +# Otherwise the files are regrouped in place. + +from __future__ import print_function + +import argparse +import re +import subprocess +import sys + + +def regroup_caps(check, filename, start_regex, end_regex, + trailing_newline, counter_prefix): + step = 5 + + original = [] + with open(filename, "r") as fh: + for line in fh: + original.append(line) + + fixed = [] + game_on = False + counter = 0 + for line in original: + line = line.rstrip("\n") + if game_on: + if re.search(r'''.*/\* [0-9]+ \*/.*''', line): + continue + if re.search(r'''^\s*$''', line): + continue + if counter % step == 0: + if counter != 0: + fixed.append("\n") + fixed.append("%s/* %d */\n" % (counter_prefix, counter)) + + if not (line.find("/*") != -1 and line.find("*/") == -1): + # count two-line comments as one line + counter = counter + 1 + + if re.search(start_regex, line): + game_on = True + elif game_on and re.search(end_regex, line): + if (counter - 1) % step == 0: + fixed = fixed[:-1] # /* $counter */ + if counter != 1: + fixed = fixed[:-1] # \n + + if trailing_newline: + fixed.append("\n") + + game_on = False + + fixed.append(line + "\n") + + if check: + orig = "".join(original) + new = "".join(fixed) + if new != orig: + diff = subprocess.Popen(["diff", "-u", filename, "-"], + stdin=subprocess.PIPE) + diff.communicate(input=new.encode('utf-8')) + + print("Incorrect line wrapping in $file", + file=sys.stderr) + print("Use test-wrap-argv.py to wrap test data files", + file=sys.stderr)
test-wrap-arg reference here
+ return False + else: + with open(filename, "w") as fh: + for line in fixed: + print(line, file=fh, end='') + + return True + + +parser = argparse.ArgumentParser(description='Test arg line wrapper')
test-wrap-arg reference here, should be group-qemu-caps Otherwise it seems to work as expected Tested-by: Cole Robinson <crobinso@redhat.com>

As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-file-access.pl tool in Python. This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same. Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-file-access.py | 123 +++++++++++++++++++++++++++++++ tests/Makefile.am | 3 +- tests/check-file-access.pl | 126 -------------------------------- tests/file_access_whitelist.txt | 2 +- 5 files changed, 126 insertions(+), 129 deletions(-) create mode 100755 scripts/check-file-access.py delete mode 100755 tests/check-file-access.pl diff --git a/Makefile.am b/Makefile.am index 769cd4ce64..19114069e3 100644 --- a/Makefile.am +++ b/Makefile.am @@ -50,6 +50,7 @@ EXTRA_DIST = \ scripts/check-aclrules.py \ scripts/check-drivername.py \ scripts/check-driverimpls.py \ + scripts/check-file-access.py \ scripts/check-remote-protocol.py \ scripts/check-spacing.py \ scripts/check-symfile.py \ diff --git a/scripts/check-file-access.py b/scripts/check-file-access.py new file mode 100755 index 0000000000..cdcbf2666f --- /dev/null +++ b/scripts/check-file-access.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python +# +# Copyright (C) 2016-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# +# This script is supposed to check test_file_access.txt file and +# warn about file accesses outside our working tree. +# +# + +from __future__ import print_function + +import re +import sys + +access_file = "test_file_access.txt" +whitelist_file = "file_access_whitelist.txt" + +known_actions = ["open", "fopen", "access", "stat", "lstat", "connect"] + +files = [] +whitelist = [] + +with open(access_file, "r") as fh: + for line in fh: + line = line.rstrip("\n") + + m = re.search(r'''^(\S*):\s*(\S*):\s*(\S*)(\s*:\s*(.*))?$''', line) + if m is not None: + rec = { + "path": m.group(1), + "action": m.group(2), + "progname": m.group(3), + "testname": m.group(5), + } + files.append(rec) + else: + raise Exception("Malformed line %s" % line) + +with open(whitelist_file, "r") as fh: + for line in fh: + line = line.rstrip("\n") + + if re.search(r'''^\s*#.*$''', line): + continue # comment + if line == "": + continue + + m = re.search(r'''^(\S*):\s*(\S*)(:\s*(\S*)(\s*:\s*(.*))?)?$''', line) + if m is not None and m.group(2) in known_actions: + # $path: $action: $progname: $testname + rec = { + "path": m.group(1), + "action": m.group(3), + "progname": m.group(4), + "testname": m.group(6), + } + whitelist.append(rec) + else: + m = re.search(r'''^(\S*)(:\s*(\S*)(\s*:\s*(.*))?)?$''', line) + if m is not None: + # $path: $progname: $testname + rec = { + "path": m.group(1), + "action": None, + "progname": m.group(3), + "testname": m.group(5), + } + whitelist.append(rec) + else: + raise Exception("Malformed line %s" % line) + + +# Now we should check if %traces is included in $whitelist. For +# now checking just keys is sufficient +err = False +for file in files: + match = False + + for rule in whitelist: + if not re.search("^" + rule["path"], file["path"]): + continue + + if (rule["action"] is not None and + not re.search("^" + rule["action"], file["action"])): + continue + + if (rule["progname"] is not None and + not re.search("^" + rule["progname"], file["progname"])): + continue + + if (rule["testname"] is not None and + file["testname"] is not None and + not re.search("^" + rule["testname"], file["testname"])): + continue + + match = True + + if not match: + err = True + print("%s: %s: %s" % + (file["path"], file["action"], file["progname"]), + file=sys.stderr, end="") + if file["testname"] is not None: + print(": %s" % file["testname"], file=sys.stderr, end="") + print("", file=sys.stderr) + +if err: + sys.exit(1) +sys.exit(0) diff --git a/tests/Makefile.am b/tests/Makefile.am index 9d9c582e42..c3bca26019 100644 --- a/tests/Makefile.am +++ b/tests/Makefile.am @@ -453,14 +453,13 @@ EXTRA_DIST += $(test_scripts) if WITH_LINUX check-access: file-access-clean VIR_TEST_FILE_ACCESS=1 $(MAKE) $(AM_MAKEFLAGS) check - $(PERL) check-file-access.pl | sort -u + $(RUNUTF8) $(PYTHON) $(top_srcdir)/scripts/check-file-access.py | sort -u file-access-clean: > test_file_access.txt endif WITH_LINUX EXTRA_DIST += \ - check-file-access.pl \ file_access_whitelist.txt if WITH_TESTS diff --git a/tests/check-file-access.pl b/tests/check-file-access.pl deleted file mode 100755 index ea0b7a18a2..0000000000 --- a/tests/check-file-access.pl +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env perl -# -# Copyright (C) 2016 Red Hat, Inc. -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library. If not, see -# <http://www.gnu.org/licenses/>. -# -# This script is supposed to check test_file_access.txt file and -# warn about file accesses outside our working tree. -# -# - -use strict; -use warnings; - -my $access_file = "test_file_access.txt"; -my $whitelist_file = "file_access_whitelist.txt"; - -my @known_actions = ("open", "fopen", "access", "stat", "lstat", "connect"); - -my @files; -my @whitelist; - -open FILE, "<", $access_file or die "Unable to open $access_file: $!"; -while (<FILE>) { - chomp; - if (/^(\S*):\s*(\S*):\s*(\S*)(\s*:\s*(.*))?$/) { - my %rec; - ${rec}{path} = $1; - ${rec}{action} = $2; - ${rec}{progname} = $3; - if (defined $5) { - ${rec}{testname} = $5; - } - push (@files, \%rec); - } else { - die "Malformed line $_"; - } -} -close FILE; - -open FILE, "<", $whitelist_file or die "Unable to open $whitelist_file: $!"; -while (<FILE>) { - chomp; - if (/^\s*#.*$/) { - # comment - } elsif (/^(\S*):\s*(\S*)(:\s*(\S*)(\s*:\s*(.*))?)?$/ and - grep /^$2$/, @known_actions) { - # $path: $action: $progname: $testname - my %rec; - ${rec}{path} = $1; - ${rec}{action} = $3; - if (defined $4) { - ${rec}{progname} = $4; - } - if (defined $6) { - ${rec}{testname} = $6; - } - push (@whitelist, \%rec); - } elsif (/^(\S*)(:\s*(\S*)(\s*:\s*(.*))?)?$/) { - # $path: $progname: $testname - my %rec; - ${rec}{path} = $1; - if (defined $3) { - ${rec}{progname} = $3; - } - if (defined $5) { - ${rec}{testname} = $5; - } - push (@whitelist, \%rec); - } else { - die "Malformed line $_"; - } -} -close FILE; - -# Now we should check if %traces is included in $whitelist. For -# now checking just keys is sufficient -my $error = 0; -for my $file (@files) { - my $match = 0; - - for my $rule (@whitelist) { - if (not %${file}{path} =~ m/^$rule->{path}$/) { - next; - } - - if (defined %${rule}{action} and - not %${file}{action} =~ m/^$rule->{action}$/) { - next; - } - - if (defined %${rule}{progname} and - not %${file}{progname} =~ m/^$rule->{progname}$/) { - next; - } - - if (defined %${rule}{testname} and - defined %${file}{testname} and - not %${file}{testname} =~ m/^$rule->{testname}$/) { - next; - } - - $match = 1; - } - - if (not $match) { - $error = 1; - print "$file->{path}: $file->{action}: $file->{progname}"; - print ": $file->{testname}" if defined %${file}{testname}; - print "\n"; - } -} - -exit $error; diff --git a/tests/file_access_whitelist.txt b/tests/file_access_whitelist.txt index 3fb318cbab..5ec7ee63bb 100644 --- a/tests/file_access_whitelist.txt +++ b/tests/file_access_whitelist.txt @@ -5,7 +5,7 @@ # $path: $progname: $testname # $path: $action: $progname: $testname # -# All these variables are evaluated as perl RE. So to allow +# All these variables are evaluated as python RE. So to allow # /dev/sda and /dev/sdb, you can just '/dev/sd[a-b]', or to allow # /proc/$pid/status you can '/proc/\d+/status' and so on. # Moreover, $action, $progname and $testname can be empty, in which -- 2.21.0

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-file-access.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-file-access.py | 123 +++++++++++++++++++++++++++++++ tests/Makefile.am | 3 +- tests/check-file-access.pl | 126 -------------------------------- tests/file_access_whitelist.txt | 2 +- 5 files changed, 126 insertions(+), 129 deletions(-) create mode 100755 scripts/check-file-access.py delete mode 100755 tests/check-file-access.pl
`make -C builddir check-access` fails like: LC_ALL= LANG=C LC_CTYPE=en_US.UTF-8 /usr/bin/python3 /home/crobinso/src/libvirt/scripts/check-file-access.py | sort -u Traceback (most recent call last): File "/home/crobinso/src/libvirt/scripts/check-file-access.py", line 53, in <module> with open(whitelist_file, "r") as fh: FileNotFoundError: [Errno 2] No such file or directory: 'file_access_whitelist.txt' make[1]: Leaving directory '/home/crobinso/src/libvirt/builddir/tests' make: Leaving directory '/home/crobinso/src/libvirt/builddir' - Cole

On Mon, Nov 18, 2019 at 02:11:33PM -0500, Cole Robinson wrote:
On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-file-access.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-file-access.py | 123 +++++++++++++++++++++++++++++++ tests/Makefile.am | 3 +- tests/check-file-access.pl | 126 -------------------------------- tests/file_access_whitelist.txt | 2 +- 5 files changed, 126 insertions(+), 129 deletions(-) create mode 100755 scripts/check-file-access.py delete mode 100755 tests/check-file-access.pl
`make -C builddir check-access` fails like:
LC_ALL= LANG=C LC_CTYPE=en_US.UTF-8 /usr/bin/python3 /home/crobinso/src/libvirt/scripts/check-file-access.py | sort -u Traceback (most recent call last): File "/home/crobinso/src/libvirt/scripts/check-file-access.py", line 53, in <module> with open(whitelist_file, "r") as fh: FileNotFoundError: [Errno 2] No such file or directory: 'file_access_whitelist.txt' make[1]: Leaving directory '/home/crobinso/src/libvirt/builddir/tests' make: Leaving directory '/home/crobinso/src/libvirt/builddir'
Looks like this is unrelated to this patch - the original script has the same flaw wrt VPATH builds, and indeed even the Makefile.am is currently broken. Regards, Daniel -- |: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|

On 12/4/19 2:19 PM, Daniel P. Berrangé wrote:
On Mon, Nov 18, 2019 at 02:11:33PM -0500, Cole Robinson wrote:
On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the check-file-access.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + scripts/check-file-access.py | 123 +++++++++++++++++++++++++++++++ tests/Makefile.am | 3 +- tests/check-file-access.pl | 126 -------------------------------- tests/file_access_whitelist.txt | 2 +- 5 files changed, 126 insertions(+), 129 deletions(-) create mode 100755 scripts/check-file-access.py delete mode 100755 tests/check-file-access.pl
`make -C builddir check-access` fails like:
LC_ALL= LANG=C LC_CTYPE=en_US.UTF-8 /usr/bin/python3 /home/crobinso/src/libvirt/scripts/check-file-access.py | sort -u Traceback (most recent call last): File "/home/crobinso/src/libvirt/scripts/check-file-access.py", line 53, in <module> with open(whitelist_file, "r") as fh: FileNotFoundError: [Errno 2] No such file or directory: 'file_access_whitelist.txt' make[1]: Leaving directory '/home/crobinso/src/libvirt/builddir/tests' make: Leaving directory '/home/crobinso/src/libvirt/builddir'
Looks like this is unrelated to this patch - the original script has the same flaw wrt VPATH builds, and indeed even the Makefile.am is currently broken.
Yes, I guess it never worked with VPATH. Anyway, patch proposed here: https://www.redhat.com/archives/libvir-list/2019-December/msg00204.html Michal

As part of an goal to eliminate Perl from libvirt build tools, rewrite the hvsupport.pl tool in Python. This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same. The new impl generates byte-for-byte identical output to the old impl. Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + docs/Makefile.am | 7 +- docs/hvsupport.pl | 459 --------------------------------------- scripts/hvsupport.py | 504 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 508 insertions(+), 463 deletions(-) delete mode 100755 docs/hvsupport.pl create mode 100755 scripts/hvsupport.py diff --git a/Makefile.am b/Makefile.am index 19114069e3..bc8aecc4a2 100644 --- a/Makefile.am +++ b/Makefile.am @@ -60,6 +60,7 @@ EXTRA_DIST = \ scripts/gensystemtap.py \ scripts/group-qemu-caps.py \ scripts/header-ifdef.py \ + scripts/hvsupport.py \ scripts/minimize-po.py \ scripts/mock-noinline.py \ scripts/prohibit-duplicate-header.py \ diff --git a/docs/Makefile.am b/docs/Makefile.am index 0311bbedd8..cf83949168 100644 --- a/docs/Makefile.am +++ b/docs/Makefile.am @@ -172,7 +172,6 @@ EXTRA_DIST= \ $(internals_html_in) $(fonts) \ $(kbase_html_in) \ aclperms.htmlinc \ - hvsupport.pl \ $(schema_DATA) acl_generated = aclperms.htmlinc @@ -212,12 +211,12 @@ web: $(dot_html) $(internals_html) $(kbase_html) \ hvsupport.html: hvsupport.html.in -hvsupport.html.in: $(srcdir)/hvsupport.pl $(api_DATA) \ +hvsupport.html.in: $(top_srcdir)/scripts/hvsupport.py $(api_DATA) \ $(top_srcdir)/src/libvirt_public.syms \ $(top_srcdir)/src/libvirt_qemu.syms $(top_srcdir)/src/libvirt_lxc.syms \ $(top_srcdir)/src/driver.h - $(AM_V_GEN)$(PERL) $(srcdir)/hvsupport.pl $(top_srcdir) $(top_builddir) > $@ \ - || { rm $@ && exit 1; } + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(top_srcdir)/scripts/hvsupport.py \ + $(top_srcdir) $(top_builddir) > $@ || { rm $@ && exit 1; } news.html.in: \ $(srcdir)/news.xml \ diff --git a/docs/hvsupport.pl b/docs/hvsupport.pl deleted file mode 100755 index 0977098eac..0000000000 --- a/docs/hvsupport.pl +++ /dev/null @@ -1,459 +0,0 @@ -#!/usr/bin/env perl - -use strict; -use warnings; - -use File::Find; - -die "syntax: $0 SRCDIR BUILDDIR\n" unless int(@ARGV) == 2; - -my $srcdir = shift @ARGV; -my $builddir = shift @ARGV; - -my $symslibvirt = "$srcdir/src/libvirt_public.syms"; -my $symsqemu = "$srcdir/src/libvirt_qemu.syms"; -my $symslxc = "$srcdir/src/libvirt_lxc.syms"; -my @drivertable = ( - "$srcdir/src/driver-hypervisor.h", - "$srcdir/src/driver-interface.h", - "$srcdir/src/driver-network.h", - "$srcdir/src/driver-nodedev.h", - "$srcdir/src/driver-nwfilter.h", - "$srcdir/src/driver-secret.h", - "$srcdir/src/driver-state.h", - "$srcdir/src/driver-storage.h", - "$srcdir/src/driver-stream.h", - ); - -my %groupheaders = ( - "virHypervisorDriver" => "Hypervisor APIs", - "virNetworkDriver" => "Virtual Network APIs", - "virInterfaceDriver" => "Host Interface APIs", - "virNodeDeviceDriver" => "Host Device APIs", - "virStorageDriver" => "Storage Pool APIs", - "virSecretDriver" => "Secret APIs", - "virNWFilterDriver" => "Network Filter APIs", - ); - - -my @srcs; -find({ - wanted => sub { - if (m!$srcdir/src/.*/\w+_(driver|common|tmpl|monitor|hal|udev)\.c$!) { - push @srcs, $_ if $_ !~ /vbox_driver\.c/; - } - }, no_chdir => 1}, "$srcdir/src"); - -# Map API functions to the header and documentation files they're in -# so that we can generate proper hyperlinks to their documentation. -# -# The function names are grep'd from the XML output of apibuild.py. -sub getAPIFilenames { - my $filename = shift; - - my %files; - my $line; - - open FILE, "<", $filename or die "cannot read $filename: $!"; - - while (defined($line = <FILE>)) { - if ($line =~ /function name='([^']+)' file='([^']+)'/) { - $files{$1} = $2; - } - } - - close FILE; - - if (keys %files == 0) { - die "No functions found in $filename. Has the apibuild.py output changed?"; - } - return \%files; -} - -sub parseSymsFile { - my $apisref = shift; - my $prefix = shift; - my $filename = shift; - my $xmlfilename = shift; - - my $line; - my $vers; - my $prevvers; - - my $filenames = getAPIFilenames($xmlfilename); - - open FILE, "<$filename" - or die "cannot read $filename: $!"; - - while (defined($line = <FILE>)) { - chomp $line; - next if $line =~ /^\s*#/; - next if $line =~ /^\s*$/; - next if $line =~ /^\s*(global|local):/; - if ($line =~ /^\s*${prefix}_(\d+\.\d+\.\d+)\s*{\s*$/) { - if (defined $vers) { - die "malformed syms file"; - } - $vers = $1; - } elsif ($line =~ /\s*}\s*;\s*$/) { - if (defined $prevvers) { - die "malformed syms file"; - } - $prevvers = $vers; - $vers = undef; - } elsif ($line =~ /\s*}\s*${prefix}_(\d+\.\d+\.\d+)\s*;\s*$/) { - if ($1 ne $prevvers) { - die "malformed syms file $1 != $vers"; - } - $prevvers = $vers; - $vers = undef; - } elsif ($line =~ /\s*(\w+)\s*;\s*$/) { - $$apisref{$1} = {}; - $$apisref{$1}->{vers} = $vers; - $$apisref{$1}->{file} = $$filenames{$1}; - } else { - die "unexpected data $line\n"; - } - } - - close FILE; -} - -my %apis; -# Get the list of all public APIs and their corresponding version -parseSymsFile(\%apis, "LIBVIRT", $symslibvirt, "$builddir/docs/libvirt-api.xml"); - -# And the same for the QEMU specific APIs -parseSymsFile(\%apis, "LIBVIRT_QEMU", $symsqemu, "$builddir/docs/libvirt-qemu-api.xml"); - -# And the same for the LXC specific APIs -parseSymsFile(\%apis, "LIBVIRT_LXC", $symslxc, "$builddir/docs/libvirt-lxc-api.xml"); - - -# Some special things which aren't public APIs, -# but we want to report -$apis{virConnectSupportsFeature}->{vers} = "0.3.2"; -$apis{virDomainMigratePrepare}->{vers} = "0.3.2"; -$apis{virDomainMigratePerform}->{vers} = "0.3.2"; -$apis{virDomainMigrateFinish}->{vers} = "0.3.2"; -$apis{virDomainMigratePrepare2}->{vers} = "0.5.0"; -$apis{virDomainMigrateFinish2}->{vers} = "0.5.0"; -$apis{virDomainMigratePrepareTunnel}->{vers} = "0.7.2"; - -$apis{virDomainMigrateBegin3}->{vers} = "0.9.2"; -$apis{virDomainMigratePrepare3}->{vers} = "0.9.2"; -$apis{virDomainMigratePrepareTunnel3}->{vers} = "0.9.2"; -$apis{virDomainMigratePerform3}->{vers} = "0.9.2"; -$apis{virDomainMigrateFinish3}->{vers} = "0.9.2"; -$apis{virDomainMigrateConfirm3}->{vers} = "0.9.2"; - -$apis{virDomainMigrateBegin3Params}->{vers} = "1.1.0"; -$apis{virDomainMigratePrepare3Params}->{vers} = "1.1.0"; -$apis{virDomainMigratePrepareTunnel3Params}->{vers} = "1.1.0"; -$apis{virDomainMigratePerform3Params}->{vers} = "1.1.0"; -$apis{virDomainMigrateFinish3Params}->{vers} = "1.1.0"; -$apis{virDomainMigrateConfirm3Params}->{vers} = "1.1.0"; - - - -# Now we want to get the mapping between public APIs -# and driver struct fields. This lets us later match -# update the driver impls with the public APis. - -my $line; - -# Group name -> hash of APIs { fields -> api name } -my %groups; -my $ingrp; -foreach my $drivertable (@drivertable) { - open FILE, "<$drivertable" - or die "cannot read $drivertable: $!"; - - while (defined($line = <FILE>)) { - if ($line =~ /struct _(vir\w*Driver)/) { - my $grp = $1; - if ($grp ne "virStateDriver" && - $grp ne "virStreamDriver") { - $ingrp = $grp; - $groups{$ingrp} = { apis => {}, drivers => {} }; - } - } elsif ($ingrp) { - if ($line =~ /^\s*vir(?:Drv)(\w+)\s+(\w+);\s*$/) { - my $field = $2; - my $name = $1; - - my $api; - if (exists $apis{"vir$name"}) { - $api = "vir$name"; - } elsif ($name =~ /\w+(Open|Close|URIProbe)/) { - next; - } else { - die "driver $name does not have a public API"; - } - $groups{$ingrp}->{apis}->{$field} = $api; - } elsif ($line =~ /};/) { - $ingrp = undef; - } - } - } - - close FILE; -} - - -# Finally, we read all the primary driver files and extract -# the driver API tables from each one. - -foreach my $src (@srcs) { - open FILE, "<$src" or - die "cannot read $src: $!"; - - my $groups_regex = join("|", keys %groups); - $ingrp = undef; - my $impl; - while (defined($line = <FILE>)) { - if (!$ingrp) { - # skip non-matching lines early to save time - next if not $line =~ /$groups_regex/; - - if ($line =~ /^\s*(?:static\s+)?($groups_regex)\s+(\w+)\s*=\s*{/ || - $line =~ /^\s*(?:static\s+)?($groups_regex)\s+NAME\(\w+\)\s*=\s*{/) { - $ingrp = $1; - $impl = $src; - - if ($impl =~ m,.*/node_device_(\w+)\.c,) { - $impl = $1; - } else { - $impl =~ s,.*/(\w+?)_((\w+)_)?(\w+)\.c,$1,; - } - - if ($groups{$ingrp}->{drivers}->{$impl}) { - die "Group $ingrp already contains $impl"; - } - - $groups{$ingrp}->{drivers}->{$impl} = {}; - } - - } else { - if ($line =~ m!\s*\.(\w+)\s*=\s*(\w+)\s*,?\s*(?:/\*\s*(\d+\.\d+\.\d+)\s*(?:-\s*(\d+\.\d+\.\d+))?\s*\*/\s*)?$!) { - my $api = $1; - my $meth = $2; - my $vers = $3; - my $deleted = $4; - - next if $api eq "no" || $api eq "name"; - - if ($meth eq "NULL" && !defined $deleted) { - die "Method impl for $api is NULL, but no deleted version is provided"; - } - if ($meth ne "NULL" && defined $deleted) { - die "Method impl for $api is non-NULL, but deleted version is provided"; - } - - die "Method $meth in $src is missing version" unless defined $vers || $api eq "connectURIProbe"; - - if (!exists($groups{$ingrp}->{apis}->{$api})) { - next if $api =~ /\w(Open|Close|URIProbe)/; - - die "Found unexpected method $api in $ingrp\n"; - } - - $groups{$ingrp}->{drivers}->{$impl}->{$api} = {}; - $groups{$ingrp}->{drivers}->{$impl}->{$api}->{vers} = $vers; - $groups{$ingrp}->{drivers}->{$impl}->{$api}->{deleted} = $deleted; - if ($api eq "domainMigratePrepare" || - $api eq "domainMigratePrepare2" || - $api eq "domainMigratePrepare3") { - if (!$groups{$ingrp}->{drivers}->{$impl}->{"domainMigrate"}) { - $groups{$ingrp}->{drivers}->{$impl}->{"domainMigrate"} = {}; - $groups{$ingrp}->{drivers}->{$impl}->{"domainMigrate"}->{vers} = $vers; - } - } - - } elsif ($line =~ /}/) { - $ingrp = undef; - } - } - } - - close FILE; -} - - -# The '.open' driver method is used for 3 public APIs, so we -# have a bit of manual fixup todo with the per-driver versioning -# and support matrix - -$groups{virHypervisorDriver}->{apis}->{"openAuth"} = "virConnectOpenAuth"; -$groups{virHypervisorDriver}->{apis}->{"openReadOnly"} = "virConnectOpenReadOnly"; -$groups{virHypervisorDriver}->{apis}->{"domainMigrate"} = "virDomainMigrate"; - -my $openAuthVers = (0 * 1000 * 1000) + (4 * 1000) + 0; - -foreach my $drv (keys %{$groups{"virHypervisorDriver"}->{drivers}}) { - my $openVersStr = $groups{"virHypervisorDriver"}->{drivers}->{$drv}->{"connectOpen"}->{vers}; - my $openVers; - if ($openVersStr =~ /(\d+)\.(\d+)\.(\d+)/) { - $openVers = ($1 * 1000 * 1000) + ($2 * 1000) + $3; - } - - # virConnectOpenReadOnly always matches virConnectOpen version - $groups{"virHypervisorDriver"}->{drivers}->{$drv}->{"connectOpenReadOnly"} = - $groups{"virHypervisorDriver"}->{drivers}->{$drv}->{"connectOpen"}; - - $groups{"virHypervisorDriver"}->{drivers}->{$drv}->{"connectOpenAuth"} = {}; - - # virConnectOpenAuth is always 0.4.0 if the driver existed - # before this time, otherwise it matches the version of - # the driver's virConnectOpen entry - if ($openVersStr eq "Y" || - $openVers >= $openAuthVers) { - $groups{"virHypervisorDriver"}->{drivers}->{$drv}->{"connectOpenAuth"}->{vers} = $openVersStr; - } else { - $groups{"virHypervisorDriver"}->{drivers}->{$drv}->{"connectOpenAuth"}->{vers} = "0.4.0"; - } -} - - -# Another special case for the virDomainCreateLinux which was replaced -# with virDomainCreateXML -$groups{virHypervisorDriver}->{apis}->{"domainCreateLinux"} = "virDomainCreateLinux"; - -my $createAPIVers = (0 * 1000 * 1000) + (0 * 1000) + 3; - -foreach my $drv (keys %{$groups{"virHypervisorDriver"}->{drivers}}) { - my $createVersStr = $groups{"virHypervisorDriver"}->{drivers}->{$drv}->{"domainCreateXML"}->{vers}; - next unless defined $createVersStr; - my $createVers; - if ($createVersStr =~ /(\d+)\.(\d+)\.(\d+)/) { - $createVers = ($1 * 1000 * 1000) + ($2 * 1000) + $3; - } - - $groups{"virHypervisorDriver"}->{drivers}->{$drv}->{"domainCreateLinux"} = {}; - - # virCreateLinux is always 0.0.3 if the driver existed - # before this time, otherwise it matches the version of - # the driver's virCreateXML entry - if ($createVersStr eq "Y" || - $createVers >= $createAPIVers) { - $groups{"virHypervisorDriver"}->{drivers}->{$drv}->{"domainCreateLinux"}->{vers} = $createVersStr; - } else { - $groups{"virHypervisorDriver"}->{drivers}->{$drv}->{"domainCreateLinux"}->{vers} = "0.0.3"; - } -} - - -# Finally we generate the HTML file with the tables - -print <<EOF; -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE html> -<html xmlns="http://www.w3.org/1999/xhtml"> -<body class="hvsupport"> -<h1>libvirt API support matrix</h1> - -<ul id="toc"></ul> - -<p> -This page documents which <a href="html/">libvirt calls</a> work on -which libvirt drivers / hypervisors, and which version the API appeared -in. If a hypervisor driver later dropped support for the API, the version -when it was removed is also mentioned (highlighted in -<span class="removedhv">dark red</span>). -</p> - -EOF - - foreach my $grp (sort { $a cmp $b } keys %groups) { - print "<h2><a id=\"$grp\">", $groupheaders{$grp}, "</a></h2>\n"; - print <<EOF; -<table class="top_table"> -<thead> -<tr> -<th>API</th> -<th>Version</th> -EOF - - foreach my $drv (sort { $a cmp $b } keys %{$groups{$grp}->{drivers}}) { - print " <th>$drv</th>\n"; - } - - print <<EOF; -</tr> -</thead> -<tbody> -EOF - - my $row = 0; - foreach my $field (sort { - $groups{$grp}->{apis}->{$a} - cmp - $groups{$grp}->{apis}->{$b} - } keys %{$groups{$grp}->{apis}}) { - my $api = $groups{$grp}->{apis}->{$field}; - my $vers = $apis{$api}->{vers}; - my $htmlgrp = $apis{$api}->{file}; - print <<EOF; -<tr> -<td> -EOF - - if (defined $htmlgrp) { - print <<EOF; -<a href=\"html/libvirt-$htmlgrp.html#$api\">$api</a> -EOF - - } else { - print $api; - } - print <<EOF; -</td> -<td>$vers</td> -EOF - - foreach my $drv (sort {$a cmp $b } keys %{$groups{$grp}->{drivers}}) { - print "<td>"; - if (exists $groups{$grp}->{drivers}->{$drv}->{$field}) { - if ($groups{$grp}->{drivers}->{$drv}->{$field}->{vers}) { - print $groups{$grp}->{drivers}->{$drv}->{$field}->{vers}; - } - if ($groups{$grp}->{drivers}->{$drv}->{$field}->{deleted}) { - print " - <span class=\"removedhv\">", $groups{$grp}->{drivers}->{$drv}->{$field}->{deleted}, "</span>"; - } - } - print "</td>\n"; - } - - print <<EOF; -</tr> -EOF - - $row++; - if (($row % 15) == 0) { - print <<EOF; -<tr> -<th>API</th> -<th>Version</th> -EOF - - foreach my $drv (sort { $a cmp $b } keys %{$groups{$grp}->{drivers}}) { - print " <th>$drv</th>\n"; - } - - print <<EOF; -</tr> -EOF - } - - } - - print <<EOF; -</tbody> -</table> -EOF -} - -print <<EOF; -</body> -</html> -EOF diff --git a/scripts/hvsupport.py b/scripts/hvsupport.py new file mode 100755 index 0000000000..7900f86f0f --- /dev/null +++ b/scripts/hvsupport.py @@ -0,0 +1,504 @@ +#!/usr/bin/env python +# +# Copyright (C) 2011-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. + +from __future__ import print_function + +import sys +import os.path +import re + +if len(sys.argv) != 3: + print("syntax: %s TOP-SRCDIR TOP-BUILDDIR\n" % sys.argv[0], file=sys.stderr) + +srcdir = sys.argv[1] +builddir = sys.argv[2] + +symslibvirt = os.path.join(srcdir, "src", "libvirt_public.syms") +symsqemu = os.path.join(srcdir, "src", "libvirt_qemu.syms") +symslxc = os.path.join(srcdir, "src", "libvirt_lxc.syms") +drivertablefiles = [ + os.path.join(srcdir, "src", "driver-hypervisor.h"), + os.path.join(srcdir, "src", "driver-interface.h"), + os.path.join(srcdir, "src", "driver-network.h"), + os.path.join(srcdir, "src", "driver-nodedev.h"), + os.path.join(srcdir, "src", "driver-nwfilter.h"), + os.path.join(srcdir, "src", "driver-secret.h"), + os.path.join(srcdir, "src", "driver-state.h"), + os.path.join(srcdir, "src", "driver-storage.h"), + os.path.join(srcdir, "src", "driver-stream.h"), +] + +groupheaders = { + "virHypervisorDriver": "Hypervisor APIs", + "virNetworkDriver": "Virtual Network APIs", + "virInterfaceDriver": "Host Interface APIs", + "virNodeDeviceDriver": "Host Device APIs", + "virStorageDriver": "Storage Pool APIs", + "virSecretDriver": "Secret APIs", + "virNWFilterDriver": "Network Filter APIs", +} + + +srcs = [] +for root, dirs, files in os.walk(os.path.join(srcdir, "src")): + for file in files: + if ((file.endswith("driver.c") and + not file.endswith("vbox_driver.c")) or + file.endswith("common.c") or + file.endswith("tmpl.c") or + file.endswith("monitor.c") or + file.endswith("hal.c") or + file.endswith("udev.c")): + srcs.append(os.path.join(root, file)) + + +# Map API functions to the header and documentation files they're in +# so that we can generate proper hyperlinks to their documentation. +# +# The function names are grep'd from the XML output of apibuild.py. +def getAPIFilenames(filename): + files = {} + + with open(filename) as fh: + for line in fh: + res = re.search(r"function name='([^']+)' file='([^']+)'", line) + if res is not None: + files[res.group(1)] = res.group(2) + + if len(files) == 0: + raise Exception(("No functions found in %s. " + + "Has the apibuild.py output changed?") % + filename) + + return files + + +def parseSymsFile(apisref, prefix, filename, xmlfilename): + vers = None + prevvers = None + + filenames = getAPIFilenames(xmlfilename) + + with open(filename) as fh: + for line in fh: + line = line.strip() + + if line == "": + continue + if line[0] == '#': + continue + if line.startswith("global:"): + continue + if line.startswith("local:"): + continue + + groupstartmatch = re.search(r"^\s*%s_(\d+\.\d+\.\d+)\s*{\s*$" % + prefix, line) + groupendmatch1 = re.search(r"^\s*}\s*;\s*$", line) + groupendmatch2 = re.search(r"^\s*}\s*%s_(\d+\.\d+\.\d+)\s*;\s*$" % + prefix, line) + symbolmatch = re.search(r"^\s*(\w+)\s*;\s*$", line) + if groupstartmatch is not None: + if vers is not None: + raise Exception("malformed syms file when starting group") + + vers = groupstartmatch.group(1) + elif groupendmatch1 is not None: + if prevvers is not None: + raise Exception("malformed syms file when ending group") + + prevvers = vers + vers = None + elif groupendmatch2 is not None: + if groupendmatch2.group(1) != prevvers: + raise Exception("malformed syms file %s != %s " + + "when ending group" % + (groupendmatch2.group(1), prevvers)) + + prevvers = vers + vers = None + elif symbolmatch is not None: + name = symbolmatch.group(1) + apisref[name] = { + "vers": vers, + "file": filenames.get(name), + } + else: + raise Exception("unexpected data %s" % line) + + +apis = {} +# Get the list of all public APIs and their corresponding version +parseSymsFile(apis, "LIBVIRT", symslibvirt, + os.path.join(builddir, "docs", "libvirt-api.xml")) + +# And the same for the QEMU specific APIs +parseSymsFile(apis, "LIBVIRT_QEMU", symsqemu, + os.path.join(builddir, "docs", "libvirt-qemu-api.xml")) + +# And the same for the LXC specific APIs +parseSymsFile(apis, "LIBVIRT_LXC", symslxc, + os.path.join(builddir, "docs", "libvirt-lxc-api.xml")) + + +# Some special things which aren't public APIs, +# but we want to report +apis["virConnectSupportsFeature"] = { + "vers": "0.3.2" +} +apis["virDomainMigratePrepare"] = { + "vers": "0.3.2" +} +apis["virDomainMigratePerform"] = { + "vers": "0.3.2" +} +apis["virDomainMigrateFinish"] = { + "vers": "0.3.2" +} +apis["virDomainMigratePrepare2"] = { + "vers": "0.5.0" +} +apis["virDomainMigrateFinish2"] = { + "vers": "0.5.0" +} +apis["virDomainMigratePrepareTunnel"] = { + "vers": "0.7.2" +} + +apis["virDomainMigrateBegin3"] = { + "vers": "0.9.2" +} +apis["virDomainMigratePrepare3"] = { + "vers": "0.9.2" +} +apis["virDomainMigratePrepareTunnel3"] = { + "vers": "0.9.2" +} +apis["virDomainMigratePerform3"] = { + "vers": "0.9.2" +} +apis["virDomainMigrateFinish3"] = { + "vers": "0.9.2" +} +apis["virDomainMigrateConfirm3"] = { + "vers": "0.9.2" +} + +apis["virDomainMigrateBegin3Params"] = { + "vers": "1.1.0" +} +apis["virDomainMigratePrepare3Params"] = { + "vers": "1.1.0" +} +apis["virDomainMigratePrepareTunnel3Params"] = { + "vers": "1.1.0" +} +apis["virDomainMigratePerform3Params"] = { + "vers": "1.1.0" +} +apis["virDomainMigrateFinish3Params"] = { + "vers": "1.1.0" +} +apis["virDomainMigrateConfirm3Params"] = { + "vers": "1.1.0" +} + + +# Now we want to get the mapping between public APIs +# and driver struct fields. This lets us later match +# update the driver impls with the public APis. + +# Group name -> hash of APIs { fields -> api name } +groups = {} +ingrp = None +for drivertablefile in drivertablefiles: + with open(drivertablefile) as fh: + for line in fh: + starttablematch = re.search(r"struct _(vir\w*Driver)", line) + if starttablematch is not None: + grp = starttablematch.group(1) + if grp != "virStateDriver" and grp != "virStreamDriver": + ingrp = grp + groups[ingrp] = { + "apis": {}, + "drivers": {} + } + elif ingrp is not None: + callbackmatch = re.search(r"^\s*vir(?:Drv)(\w+)\s+(\w+);\s*$", + line) + if callbackmatch is not None: + name = callbackmatch.group(1) + field = callbackmatch.group(2) + + api = "vir" + name + if api in apis: + groups[ingrp]["apis"][field] = api + elif re.search(r"\w+(Open|Close|URIProbe)", api) is not None: + continue + else: + raise Exception(("driver %s does not have " + + "a public API") % name) + elif re.search(r"};", line): + ingrp = None + + +# Finally, we read all the primary driver files and extract +# the driver API tables from each one. + +for src in srcs: + with open(src) as fh: + groupsre = "|".join(groups.keys()) + + ingrp = None + impl = None + for line in fh: + if ingrp is None: + m = re.search(r"^\s*(static\s+)?(" + + groupsre + + r")\s+(\w+)\s*=\s*{", line) + if m is None: + m = re.search(r"^\s*(static\s+)?(" + + groupsre + + r")\s+NAME\(\w+\)\s*=\s*{", line) + if m is not None: + ingrp = m.group(2) + impl = src + + implmatch = re.search(r".*/node_device_(\w+)\.c", impl) + if implmatch is None: + implmatch = re.search(r".*/(\w+?)_((\w+)_)?(\w+)\.c", impl) + if implmatch is None: + raise Exception("Unexpected impl format '%s'" % impl) + impl = implmatch.group(1) + + if impl in groups[ingrp]["drivers"]: + raise Exception( + "Group %s already contains %s" % (ingrp, impl)) + + groups[ingrp]["drivers"][impl] = {} + else: + callbackmatch = re.search(r"\s*\.(\w+)\s*=\s*(\w+)\s*,?\s*" + + r"(?:/\*\s*(\d+\.\d+\.\d+)\s*" + + r"(?:-\s*(\d+\.\d+\.\d+))?\s*\*/\s*)?$", + line) + if callbackmatch is not None: + api = callbackmatch.group(1) + meth = callbackmatch.group(2) + vers = callbackmatch.group(3) + deleted = callbackmatch.group(4) + + if api == "no" or api == "name": + continue + + if meth == "NULL" and deleted is None: + raise Exception( + ("Method impl for %s is NULL, but " + + "no deleted version is provided") % api) + + if meth != "NULL" and deleted is not None: + raise Exception( + ("Method impl for %s is non-NULL, but " + + "deleted version is provided") % api) + + if vers is None and api != "connectURIProbe": + raise Exception( + "Method %s in %s is missing version" % + (meth, src)) + + if api not in groups[ingrp]["apis"]: + if re.search(r"\w+(Open|Close|URIProbe)", api): + continue + + raise Exception("Found unexpected method " + + "%s in %s" % (api, ingrp)) + + groups[ingrp]["drivers"][impl][api] = { + "vers": vers, + "deleted": deleted, + } + + if (api == "domainMigratePrepare" or + api == "domainMigratePrepare2" or + api == "domainMigratePrepare3"): + if ("domainMigrate" not in + groups[ingrp]["drivers"][impl]): + groups[ingrp]["drivers"][impl]["domainMigrate"] = { + "vers": vers, + } + elif line.find("}") != -1: + ingrp = None + + +# The '.open' driver method is used for 3 public APIs, so we +# have a bit of manual fixup todo with the per-driver versioning +# and support matrix + +groups["virHypervisorDriver"]["apis"]["openAuth"] = \ + "virConnectOpenAuth" +groups["virHypervisorDriver"]["apis"]["openReadOnly"] = \ + "virConnectOpenReadOnly" +groups["virHypervisorDriver"]["apis"]["domainMigrate"] = \ + "virDomainMigrate" + +openAuthVers = (0 * 1000 * 1000) + (4 * 1000) + 0 + +drivers = groups["virHypervisorDriver"]["drivers"] +for drv in drivers.keys(): + openVersStr = drivers[drv]["connectOpen"]["vers"] + openVers = 0 + if openVersStr != "Y": + openVersBits = openVersStr.split(".") + if len(openVersBits) != 3: + raise Exception("Expected 3 digit version for %s" % openVersStr) + openVers = ((int(openVersBits[0]) * 1000 * 1000) + + (int(openVersBits[1]) * 1000) + + int(openVersBits[2])) + + # virConnectOpenReadOnly always matches virConnectOpen version + drivers[drv]["connectOpenReadOnly"] = \ + drivers[drv]["connectOpen"] + + # virConnectOpenAuth is always 0.4.0 if the driver existed + # before this time, otherwise it matches the version of + # the driver's virConnectOpen entry + if openVersStr == "Y" or openVers >= openAuthVers: + vers = openVersStr + else: + vers = "0.4.0" + drivers[drv]["connectOpenAuth"] = { + "vers": vers, + } + + +# Another special case for the virDomainCreateLinux which was replaced +# with virDomainCreateXML +groups["virHypervisorDriver"]["apis"]["domainCreateLinux"] = \ + "virDomainCreateLinux" + +createAPIVers = (0 * 1000 * 1000) + (0 * 1000) + 3 + +for drv in drivers.keys(): + if "domainCreateXML" not in drivers[drv]: + continue + createVersStr = drivers[drv]["domainCreateXML"]["vers"] + createVers = 0 + if createVersStr != "Y": + createVersBits = createVersStr.split(".") + if len(createVersBits) != 3: + raise Exception("Expected 3 digit version for %s" % createVersStr) + createVers = ((int(createVersBits[0]) * 1000 * 1000) + + (int(createVersBits[1]) * 1000) + + int(createVersBits[2])) + + # virCreateLinux is always 0.0.3 if the driver existed + # before this time, otherwise it matches the version of + # the driver's virCreateXML entry + if createVersStr == "Y" or createVers >= createAPIVers: + vers = createVersStr + else: + vers = "0.0.3" + + drivers[drv]["domainCreateLinux"] = { + "vers": vers, + } + + +# Finally we generate the HTML file with the tables + +print('''<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE html> +<html xmlns="http://www.w3.org/1999/xhtml"> +<body class="hvsupport"> +<h1>libvirt API support matrix</h1> + +<ul id="toc"></ul> + +<p> +This page documents which <a href="html/">libvirt calls</a> work on +which libvirt drivers / hypervisors, and which version the API appeared +in. If a hypervisor driver later dropped support for the API, the version +when it was removed is also mentioned (highlighted in +<span class="removedhv">dark red</span>). +</p> +''') + +for grp in sorted(groups.keys()): + print("<h2><a id=\"%s\">%s</a></h2>" % (grp, groupheaders[grp])) + print('''<table class="top_table"> +<thead> +<tr> +<th>API</th> +<th>Version</th>''') + + for drv in sorted(groups[grp]["drivers"].keys()): + print(" <th>%s</th>" % drv) + + print('''</tr> +</thead> +<tbody>''') + + row = 0 + + def sortkey(field): + return groups[grp]["apis"][field] + + for field in sorted(groups[grp]["apis"].keys(), key=sortkey): + api = groups[grp]["apis"][field] + vers = apis[api]["vers"] + htmlgrp = apis[api].get("file") + print("<tr>") + + if htmlgrp is not None: + print(('''<td>\n<a href=\"html/libvirt-%s.html#%s\">''' + + '''%s</a>\n</td>''') % + (htmlgrp, api, api)) + else: + print("<td>\n%s</td>" % api) + + print("<td>%s</td>" % vers) + + for drv in sorted(groups[grp]["drivers"].keys()): + info = "" + if field in groups[grp]["drivers"][drv]: + vers = groups[grp]["drivers"][drv][field]["vers"] + if vers is not None: + info = info + vers + + deleted = groups[grp]["drivers"][drv][field].get("deleted") + if deleted is not None: + info = info + (''' - <span class="removedhv">''' + + '''%s</span>''' % deleted) + + print("<td>%s</td>" % info) + + print("</tr>") + + row = row + 1 + if (row % 15) == 0: + print('''<tr> +<th>API</th> +<th>Version</th>''') + + for drv in sorted(groups[grp]["drivers"].keys()): + print(" <th>%s</th>" % drv) + + print("</tr>") + + print("</tbody>\n</table>") + +print("</body>\n</html>") -- 2.21.0

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the hvsupport.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
The new impl generates byte-for-byte identical output to the old impl.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + docs/Makefile.am | 7 +- docs/hvsupport.pl | 459 --------------------------------------- scripts/hvsupport.py | 504 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 508 insertions(+), 463 deletions(-) delete mode 100755 docs/hvsupport.pl create mode 100755 scripts/hvsupport.py
Generates identical output to the perl script (modulo expected timestamp change) Tested-by: Cole Robinson <crobinso@redhat.com> - Cole

As part of an goal to eliminate Perl from libvirt build tools, rewrite the genaclperms.pl tool in Python. This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same. Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + docs/Makefile.am | 6 +- docs/genaclperms.pl | 125 ----------------------------------------- scripts/genaclperms.py | 123 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 127 insertions(+), 128 deletions(-) delete mode 100755 docs/genaclperms.pl create mode 100755 scripts/genaclperms.py diff --git a/Makefile.am b/Makefile.am index bc8aecc4a2..a14474f535 100644 --- a/Makefile.am +++ b/Makefile.am @@ -56,6 +56,7 @@ EXTRA_DIST = \ scripts/check-symfile.py \ scripts/check-symsorting.py \ scripts/dtrace2systemtap.py \ + scripts/genaclperms.py \ scripts/genpolkit.py \ scripts/gensystemtap.py \ scripts/group-qemu-caps.py \ diff --git a/docs/Makefile.am b/docs/Makefile.am index cf83949168..ca7a2ec260 100644 --- a/docs/Makefile.am +++ b/docs/Makefile.am @@ -163,7 +163,7 @@ schemadir = $(pkgdatadir)/schemas schema_DATA = $(wildcard $(srcdir)/schemas/*.rng) EXTRA_DIST= \ - apibuild.py genaclperms.pl \ + apibuild.py \ site.xsl subsite.xsl newapi.xsl page.xsl \ wrapstring.xsl \ $(dot_html_in) $(gif) $(apipng) \ @@ -177,8 +177,8 @@ EXTRA_DIST= \ acl_generated = aclperms.htmlinc aclperms.htmlinc: $(top_srcdir)/src/access/viraccessperm.h \ - $(srcdir)/genaclperms.pl Makefile.am - $(AM_V_GEN)$(PERL) $(srcdir)/genaclperms.pl $< > $@ + $(top_srcdir)/scripts/genaclperms.py Makefile.am + $(AM_V_GEN)$(RUNUTF8) $(PYTHON) $(top_srcdir)/scripts/genaclperms.py $< > $@ CLEANFILES = \ $(dot_html) \ diff --git a/docs/genaclperms.pl b/docs/genaclperms.pl deleted file mode 100755 index e20b4c11c3..0000000000 --- a/docs/genaclperms.pl +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env perl -# -# Copyright (C) 2013 Red Hat, Inc. -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library. If not, see -# <http://www.gnu.org/licenses/>. -# - -use strict; -use warnings; - -my @objects = ( - "CONNECT", "DOMAIN", "INTERFACE", - "NETWORK_PORT", "NETWORK", "NODE_DEVICE", - "NWFILTER_BINDING", "NWFILTER", - "SECRET", "STORAGE_POOL", "STORAGE_VOL", - ); - -my %class; - -foreach my $object (@objects) { - my $class = lc $object; - - $class =~ s/(^\w|_\w)/uc $1/eg; - $class =~ s/_//g; - $class =~ s/Nwfilter/NWFilter/; - $class = "vir" . $class . "Ptr"; - - $class{$object} = $class; -} - -my $objects = join ("|", @objects); - -my %opts; -my $in_opts = 0; - -my %perms; - -while (<>) { - if ($in_opts) { - if (m,\*/,) { - $in_opts = 0; - } elsif (/\*\s*\@(\w+):\s*(.*?)\s*$/) { - $opts{$1} = $2; - } - } elsif (m,/\*\*,) { - $in_opts = 1; - } elsif (/VIR_ACCESS_PERM_($objects)_((?:\w|_)+),/) { - my $object = $1; - my $perm = lc $2; - next if $perm eq "last"; - - $perm =~ s/_/-/g; - - $perms{$object} = {} unless exists $perms{$object}; - $perms{$object}->{$perm} = { - desc => $opts{desc}, - message => $opts{message}, - anonymous => $opts{anonymous} - }; - %opts = (); - } -} - -print <<EOF; -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE html> -<html xmlns="http://www.w3.org/1999/xhtml"> - <body> -EOF - -foreach my $object (sort { $a cmp $b } keys %perms) { - my $class = $class{$object}; - my $olink = lc "object_" . $object; - print <<EOF; -<h3><a id="$olink">$class</a></h3> -<table class="acl"> - <thead> - <tr> - <th>Permission</th> - <th>Description</th> - </tr> - </thead> - <tbody> -EOF - - foreach my $perm (sort { $a cmp $b } keys %{$perms{$object}}) { - my $description = $perms{$object}->{$perm}->{desc}; - - die "missing description for $object.$perm" unless - defined $description; - - my $plink = lc "perm_" . $object . "_" . $perm; - $plink =~ s/-/_/g; - - print <<EOF; - <tr> - <td><a id="$plink">$perm</a></td> - <td>$description</td> - </tr> -EOF - - } - - print <<EOF; - </tbody> -</table> -EOF -} - -print <<EOF; - </body> -</html> -EOF diff --git a/scripts/genaclperms.py b/scripts/genaclperms.py new file mode 100755 index 0000000000..cd92346449 --- /dev/null +++ b/scripts/genaclperms.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python +# +# Copyright (C) 2013-2019 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# <http://www.gnu.org/licenses/>. +# + +from __future__ import print_function + +import re +import sys + +objects = [ + "CONNECT", "DOMAIN", "INTERFACE", + "NETWORK_PORT", "NETWORK", "NODE_DEVICE", + "NWFILTER_BINDING", "NWFILTER", + "SECRET", "STORAGE_POOL", "STORAGE_VOL", +] + + +classes = {} + +for obj in objects: + klass = obj.lower() + + klass = re.sub(r'''(^\w|_\w)''', lambda a: a.group(1).upper(), klass) + klass = klass.replace("_", "") + klass = klass.replace("Nwfilter", "NWFilter") + klass = "vir" + klass + "Ptr" + + classes[obj] = klass + + +objectstr = "|".join(objects) + +opts = {} +in_opts = {} + +perms = {} + +aclfile = sys.argv[1] +with open(aclfile, "r") as fh: + for line in fh: + if in_opts: + if line.find("*/") != -1: + in_opts = False + else: + m = re.search(r'''\*\s*\@(\w+):\s*(.*?)\s*$''', line) + if m is not None: + opts[m.group(1)] = m.group(2) + elif line.find("**") != -1: + in_opts = True + else: + m = re.search(r'''VIR_ACCESS_PERM_(%s)_((?:\w|_)+),''' % + objectstr, line) + if m is not None: + obj = m.group(1) + perm = m.group(2).lower() + if perm == "last": + continue + + perm = perm.replace("_", "-") + + if obj not in perms: + perms[obj] = {} + perms[obj][perm] = { + "desc": opts.get("desc", None), + "message": opts.get("message", None), + "anonymous": opts.get("anonymous", None), + } + opts = {} + +print('<?xml version="1.0" encoding="UTF-8"?>') +print('<!DOCTYPE html>') +print('<html xmlns="http://www.w3.org/1999/xhtml">') +print(' <body>') + +for obj in sorted(perms.keys()): + klass = classes[obj] + + olink = "object_" + obj.lower() + + print(' <h3><a id="%s">%s</a></h3>' % (olink, klass)) + print(' <table class="acl">') + print(' <thead>') + print(' <tr>') + print(' <th>Permission</th>') + print(' <th>Description</th>') + print(' </tr>') + print(' </thead>') + print(' <tbody>') + + for perm in sorted(perms[obj].keys()): + description = perms[obj][perm]["desc"] + + if description is None: + raise Exception("missing description for %s.%s" % (obj, perm)) + + plink = "perm_" + obj.lower() + "_" + perm.lower() + plink = plink.replace("-", "_") + + print(' <tr>') + print(' <td><a id="%s">%s</a></td>' % (plink, perm)) + print(' <td>%s</td>' % description) + print(' </tr>') + + print(' </tbody>') + print(' </table>') + +print(' </body>') +print('</html>') -- 2.21.0

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
As part of an goal to eliminate Perl from libvirt build tools, rewrite the genaclperms.pl tool in Python.
This was a straight conversion, manually going line-by-line to change the syntax from Perl to Python. Thus the overall structure of the file and approach is the same.
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + docs/Makefile.am | 6 +- docs/genaclperms.pl | 125 ----------------------------------------- scripts/genaclperms.py | 123 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 127 insertions(+), 128 deletions(-) delete mode 100755 docs/genaclperms.pl create mode 100755 scripts/genaclperms.py
The new script fixes indentation, but otherwise seems to generate identical aclperms.htmlinc Tested-by: Cole Robinson <crobinso@redhat.com> - Cole

Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + build-aux/syntax-check.mk | 2 +- docs/Makefile.am | 5 ++--- {docs => scripts}/apibuild.py | 0 4 files changed, 4 insertions(+), 4 deletions(-) rename {docs => scripts}/apibuild.py (100%) diff --git a/Makefile.am b/Makefile.am index a14474f535..67d07eff41 100644 --- a/Makefile.am +++ b/Makefile.am @@ -45,6 +45,7 @@ EXTRA_DIST = \ run.in \ README.md \ AUTHORS.in \ + scripts/apibuild.py \ scripts/augeas-gentest.py \ scripts/check-aclperms.py \ scripts/check-aclrules.py \ diff --git a/build-aux/syntax-check.mk b/build-aux/syntax-check.mk index 44639f499e..ee8a496efa 100644 --- a/build-aux/syntax-check.mk +++ b/build-aux/syntax-check.mk @@ -2284,7 +2284,7 @@ exclude_file_name_regexp--sc_trailing_blank = \ /sysinfodata/.*\.data|/virhostcpudata/.*\.cpuinfo|^gnulib/local/.*/.*diff$$ exclude_file_name_regexp--sc_unmarked_diagnostics = \ - ^(docs/apibuild.py|tests/virt-aa-helper-test|docs/js/.*\.js)$$ + ^(scripts/apibuild.py|tests/virt-aa-helper-test|docs/js/.*\.js)$$ exclude_file_name_regexp--sc_size_of_brackets = build-aux/syntax-check\.mk diff --git a/docs/Makefile.am b/docs/Makefile.am index ca7a2ec260..f37417cafb 100644 --- a/docs/Makefile.am +++ b/docs/Makefile.am @@ -163,7 +163,6 @@ schemadir = $(pkgdatadir)/schemas schema_DATA = $(wildcard $(srcdir)/schemas/*.rng) EXTRA_DIST= \ - apibuild.py \ site.xsl subsite.xsl newapi.xsl page.xsl \ wrapstring.xsl \ $(dot_html_in) $(gif) $(apipng) \ @@ -278,13 +277,13 @@ python_generated_files = \ libvirt-admin-refs.xml \ $(NULL) -APIBUILD=$(srcdir)/apibuild.py +APIBUILD=$(top_srcdir)/scripts/apibuild.py APIBUILD_STAMP=apibuild.py.stamp CLEANFILES += $(APIBUILD_STAMP) $(python_generated_files): $(APIBUILD_STAMP) -$(APIBUILD_STAMP): $(srcdir)/apibuild.py \ +$(APIBUILD_STAMP): $(top_srcdir)/scripts/apibuild.py \ $(top_srcdir)/include/libvirt/libvirt.h \ $(top_srcdir)/include/libvirt/libvirt-common.h.in \ $(top_srcdir)/include/libvirt/libvirt-domain-checkpoint.h \ diff --git a/docs/apibuild.py b/scripts/apibuild.py similarity index 100% rename from docs/apibuild.py rename to scripts/apibuild.py -- 2.21.0

Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 7 ++++--- {docs => scripts}/reformat-news.py | 0 2 files changed, 4 insertions(+), 3 deletions(-) rename {docs => scripts}/reformat-news.py (100%) diff --git a/Makefile.am b/Makefile.am index 67d07eff41..8359ebc6ad 100644 --- a/Makefile.am +++ b/Makefile.am @@ -66,6 +66,7 @@ EXTRA_DIST = \ scripts/minimize-po.py \ scripts/mock-noinline.py \ scripts/prohibit-duplicate-header.py \ + scripts/reformat-news.py \ scripts/test-wrap-argv.py \ build-aux/syntax-check.mk \ build-aux/useless-if-before-free \ @@ -81,7 +82,7 @@ pkgconfig_DATA = libvirt.pc libvirt-qemu.pc libvirt-lxc.pc libvirt-admin.pc NEWS: \ $(srcdir)/docs/news.xml \ $(srcdir)/docs/news-ascii.xsl \ - $(srcdir)/docs/reformat-news.py + $(top_srcdir)/scripts/reformat-news.py $(AM_V_GEN) \ if [ -x $(XSLTPROC) ]; then \ $(XSLTPROC) --nonet \ @@ -89,14 +90,14 @@ NEWS: \ $(srcdir)/docs/news.xml \ >$@-tmp \ || { rm -f $@-tmp; exit 1; }; \ - $(RUNUTF8) $(PYTHON) $(srcdir)/docs/reformat-news.py $@-tmp >$@ \ + $(RUNUTF8) $(PYTHON) $(top_srcdir)/scripts/reformat-news.py $@-tmp >$@ \ || { rm -f $@-tmp; exit 1; }; \ rm -f $@-tmp; \ fi EXTRA_DIST += \ $(srcdir)/docs/news.xml \ $(srcdir)/docs/news-ascii.xsl \ - $(srcdir)/docs/reformat-news.py + $(NULL) rpm: clean @(unset CDPATH ; $(MAKE) dist && rpmbuild -ta $(distdir).tar.xz) diff --git a/docs/reformat-news.py b/scripts/reformat-news.py similarity index 100% rename from docs/reformat-news.py rename to scripts/reformat-news.py -- 2.21.0

Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + {src/esx => scripts}/esx_vi_generator.py | 0 src/esx/Makefile.inc.am | 6 +++--- 3 files changed, 4 insertions(+), 3 deletions(-) rename {src/esx => scripts}/esx_vi_generator.py (100%) diff --git a/Makefile.am b/Makefile.am index 8359ebc6ad..14456161c3 100644 --- a/Makefile.am +++ b/Makefile.am @@ -57,6 +57,7 @@ EXTRA_DIST = \ scripts/check-symfile.py \ scripts/check-symsorting.py \ scripts/dtrace2systemtap.py \ + scripts/esx_vi_generator.py \ scripts/genaclperms.py \ scripts/genpolkit.py \ scripts/gensystemtap.py \ diff --git a/src/esx/esx_vi_generator.py b/scripts/esx_vi_generator.py similarity index 100% rename from src/esx/esx_vi_generator.py rename to scripts/esx_vi_generator.py diff --git a/src/esx/Makefile.inc.am b/src/esx/Makefile.inc.am index 6b10755b7e..aa2d17c791 100644 --- a/src/esx/Makefile.inc.am +++ b/src/esx/Makefile.inc.am @@ -43,7 +43,6 @@ ESX_DRIVER_GENERATED = \ ESX_DRIVER_EXTRA_DIST = \ esx/README \ esx/esx_vi_generator.input \ - esx/esx_vi_generator.py \ $(NULL) ESX_GENERATED_STAMP = .esx_vi_generator.stamp @@ -60,9 +59,10 @@ BUILT_SOURCES += $(ESX_DRIVER_GENERATED) $(ESX_DRIVER_GENERATED): $(ESX_GENERATED_STAMP) $(ESX_GENERATED_STAMP): $(srcdir)/esx/esx_vi_generator.input \ - $(srcdir)/esx/esx_vi_generator.py + $(top_srcdir)/scripts/esx_vi_generator.py $(AM_V_GEN) $(RUNUTF8) $(PYTHON) \ - $(srcdir)/esx/esx_vi_generator.py $(srcdir) $(builddir) && touch $@ + $(top_srcdir)/scripts/esx_vi_generator.py \ + $(srcdir) $(builddir) && touch $@ CLEANFILES += $(ESX_DRIVER_GENERATED) $(ESX_GENERATED_STAMP) -- 2.21.0

Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + {src/hyperv => scripts}/hyperv_wmi_generator.py | 0 src/hyperv/Makefile.inc.am | 5 ++--- 3 files changed, 3 insertions(+), 3 deletions(-) rename {src/hyperv => scripts}/hyperv_wmi_generator.py (100%) diff --git a/Makefile.am b/Makefile.am index 14456161c3..adad46f1f0 100644 --- a/Makefile.am +++ b/Makefile.am @@ -64,6 +64,7 @@ EXTRA_DIST = \ scripts/group-qemu-caps.py \ scripts/header-ifdef.py \ scripts/hvsupport.py \ + scripts/hyperv_wmi_generator.py \ scripts/minimize-po.py \ scripts/mock-noinline.py \ scripts/prohibit-duplicate-header.py \ diff --git a/src/hyperv/hyperv_wmi_generator.py b/scripts/hyperv_wmi_generator.py similarity index 100% rename from src/hyperv/hyperv_wmi_generator.py rename to scripts/hyperv_wmi_generator.py diff --git a/src/hyperv/Makefile.inc.am b/src/hyperv/Makefile.inc.am index b71602c971..5d801b28b6 100644 --- a/src/hyperv/Makefile.inc.am +++ b/src/hyperv/Makefile.inc.am @@ -23,7 +23,6 @@ HYPERV_GENERATED_STAMP = .hyperv_wmi_generator.stamp HYPERV_DRIVER_EXTRA_DIST = \ hyperv/hyperv_wmi_generator.input \ - hyperv/hyperv_wmi_generator.py \ $(NULL) DRIVER_SOURCE_FILES += $(HYPERV_DRIVER_SOURCES) @@ -38,9 +37,9 @@ BUILT_SOURCES += $(HYPERV_DRIVER_GENERATED) $(HYPERV_DRIVER_GENERATED): $(HYPERV_GENERATED_STAMP) $(HYPERV_GENERATED_STAMP): $(srcdir)/hyperv/hyperv_wmi_generator.input \ - $(srcdir)/hyperv/hyperv_wmi_generator.py + $(top_srcdir)/scripts/hyperv_wmi_generator.py $(AM_V_GEN) $(RUNUTF8) $(PYTHON) \ - $(srcdir)/hyperv/hyperv_wmi_generator.py $(srcdir) $(builddir) \ + $(top_srcdir)/scripts/hyperv_wmi_generator.py $(srcdir) $(builddir) \ && touch $@ CLEANFILES += $(HYPERV_DRIVER_GENERATED) $(HYPERV_GENERATED_STAMP) -- 2.21.0

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com> --- Makefile.am | 1 + {src/hyperv => scripts}/hyperv_wmi_generator.py | 0 src/hyperv/Makefile.inc.am | 5 ++--- 3 files changed, 3 insertions(+), 3 deletions(-) rename {src/hyperv => scripts}/hyperv_wmi_generator.py (100%)
For 20-23: Reviewed-by: Cole Robinson <crobinso@redhat.com> - Cole

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
This series is an effort to reduce the number of different languages we use by eliminating most use of perl in favour of python.
I'm testing the series now. On fedora 31, make syntax-check is showing some flake8 errors, see attached. I also attach a run of pycodestyle and pylint using my standard configs. There's nothing that looks like a legitimate bug in any of the output, though I didn't look too closely at the overridden variable warnings - Cole

On Fri, Nov 15, 2019 at 03:07:32PM -0500, Cole Robinson wrote:
On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
This series is an effort to reduce the number of different languages we use by eliminating most use of perl in favour of python.
I'm testing the series now. On fedora 31, make syntax-check is showing some flake8 errors, see attached. I also attach a run of pycodestyle and pylint using my standard configs. There's nothing that looks like a legitimate bug in any of the output, though I didn't look too closely at the overridden variable warnings
The obvious errors here these ones:
scripts/check-aclrules.py:174:34: E1305: Too many arguments for format string (too-many-format-args) scripts/check-aclrules.py:193:34: E1305: Too many arguments for format string (too-many-format-args) scripts/check-aclrules.py:228:34: E1305: Too many arguments for format string (too-many-format-args) scripts/check-aclrules.py:235:34: E1305: Too many arguments for format string (too-many-format-args)
scripts/check-driverimpls.py:57:34: E1305: Too many arguments for format string (too-many-format-args) scripts/check-driverimpls.py:80:30: E1305: Too many arguments for format string (too-many-format-args)
scripts/hvsupport.py:130:36: E1305: Too many arguments for format string (too-many-format-args)
all were in exception formatting where we broke the message across lines - % binds more strongly than + So "foo %s bar" + "wizz" % "eek" Needs to be ("foo %s bar" + "wizz") % "eek" Regards, Daniel -- |: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|

On 11/11/19 9:38 AM, Daniel P. Berrangé wrote:
This series is an effort to reduce the number of different languages we use by eliminating most use of perl in favour of python.
I tested all the new scripts, see individual mails. I didn't really 'review' any of them; since many are just direct conversions from the old scripts, it's unclear if it's worth the effort of doing a full review. I think testing is reasonable grounds for pushing to git Thanks, Cole
participants (4)
-
Cole Robinson
-
Daniel P. Berrangé
-
Ján Tomko
-
Michal Privoznik