flake8: apply E1 rules

This commit is contained in:
Yuming Zhu 2020-02-26 02:08:41 +08:00
parent 450f9249cd
commit ce1f9928af
30 changed files with 958 additions and 958 deletions

View file

@ -1,5 +1,5 @@
[flake8] [flake8]
select = I,C,F,E265 select = I,C,F,E1,E265
exclude = exclude =
.git, .git,
__pycache__, __pycache__,

File diff suppressed because it is too large Load diff

View file

@ -49,13 +49,13 @@ EXPAND_ARCHES = {
'armhfp': ['armv7hl', 'armv7hnl', 'armv6hl', 'armv6hnl'], 'armhfp': ['armv7hl', 'armv7hnl', 'armv6hl', 'armv6hnl'],
'arm': ['armv5tel', 'armv5tejl', 'armv6l','armv7l'], 'arm': ['armv5tel', 'armv5tejl', 'armv6l','armv7l'],
'sh4': ['sh4a'] 'sh4': ['sh4a']
} }
MULTILIB_ARCHES = { MULTILIB_ARCHES = {
'x86_64': 'i386', 'x86_64': 'i386',
'ppc64': 'ppc', 'ppc64': 'ppc',
's390x': 's390' 's390x': 's390'
} }
def parse_args(args): def parse_args(args):
"""Parse our opts/args""" """Parse our opts/args"""
@ -221,13 +221,13 @@ class RepoMerge(object):
# We found a rpm built from an srpm with the same name in a previous repo. # We found a rpm built from an srpm with the same name in a previous repo.
# The previous repo takes precedence, so ignore the srpm found here. # The previous repo takes precedence, so ignore the srpm found here.
sys.stderr.write('Package %s already provided by repo %s' sys.stderr.write('Package %s already provided by repo %s'
' (at %s in repo %s)\n' ' (at %s in repo %s)\n'
% (srpm_name, other_repoid, str(pkg), pkg.repoid)) % (srpm_name, other_repoid, str(pkg), pkg.repoid))
continue continue
else: else:
# We're in the same repo, so compare srpm NVRs # We're in the same repo, so compare srpm NVRs
other_srpm_name, other_ver, other_rel, other_epoch, other_arch = \ other_srpm_name, other_ver, other_rel, other_epoch, other_arch = \
rpmUtils.miscutils.splitFilename(other_srpm) rpmUtils.miscutils.splitFilename(other_srpm)
cmp = rpmUtils.miscutils.compareEVR((epoch, ver, rel), cmp = rpmUtils.miscutils.compareEVR((epoch, ver, rel),
(other_epoch, other_ver, other_rel)) (other_epoch, other_ver, other_rel))
if cmp > 0: if cmp > 0:
@ -235,10 +235,10 @@ class RepoMerge(object):
# existing srpm in the dict, so update the dict # existing srpm in the dict, so update the dict
include_srpms[srpm_name] = (pkg.sourcerpm, pkg.repoid) include_srpms[srpm_name] = (pkg.sourcerpm, pkg.repoid)
sys.stderr.write('Replacing older source nvr: ' sys.stderr.write('Replacing older source nvr: '
'%s > %s\n' % (pkg.sourcerpm, other_srpm)) '%s > %s\n' % (pkg.sourcerpm, other_srpm))
elif cmp < 0: elif cmp < 0:
sys.stderr.write('Ignoring older source nvr: ' sys.stderr.write('Ignoring older source nvr: '
'%s < %s\n' % (pkg.sourcerpm, other_srpm)) '%s < %s\n' % (pkg.sourcerpm, other_srpm))
# otherwise same, so we already have it # otherwise same, so we already have it
elif srpm_name in self.blocked: elif srpm_name in self.blocked:
sys.stderr.write('Ignoring blocked package: %s\n\n' % \ sys.stderr.write('Ignoring blocked package: %s\n\n' % \
@ -260,14 +260,14 @@ class RepoMerge(object):
sys.stderr.write('Duplicate rpm: %s\n' % pkg_nvra) sys.stderr.write('Duplicate rpm: %s\n' % pkg_nvra)
elif incl_srpm is None: elif incl_srpm is None:
sys.stderr.write('Excluding %s (%s is blocked)\n' sys.stderr.write('Excluding %s (%s is blocked)\n'
% (pkg_nvra, srpm_name)) % (pkg_nvra, srpm_name))
repo.sack.delPackage(pkg) repo.sack.delPackage(pkg)
elif incl_srpm == pkg.sourcerpm: elif incl_srpm == pkg.sourcerpm:
origins.write('%s\t%s\n' % (pkg_nvra, repo.urls[0])) origins.write('%s\t%s\n' % (pkg_nvra, repo.urls[0]))
seen_rpms[pkg_nvra] = 1 seen_rpms[pkg_nvra] = 1
else: else:
sys.stderr.write('Excluding %s (wrong srpm version ' sys.stderr.write('Excluding %s (wrong srpm version '
'%s != %s)\n' % (pkg_nvra, pkg.sourcerpm, incl_srpm)) '%s != %s)\n' % (pkg_nvra, pkg.sourcerpm, incl_srpm))
repo.sack.delPackage(pkg) repo.sack.delPackage(pkg)
origins.close() origins.close()

View file

@ -104,7 +104,7 @@ def get_options():
common_commands = ['build', 'help', 'download-build', common_commands = ['build', 'help', 'download-build',
'latest-build', 'search', 'list-targets'] 'latest-build', 'search', 'list-targets']
usage = _("%%prog [global-options] command [command-options-and-arguments]" usage = _("%%prog [global-options] command [command-options-and-arguments]"
"\n\nCommon commands: %s" % ', '.join(sorted(common_commands))) "\n\nCommon commands: %s" % ', '.join(sorted(common_commands)))
parser = OptionParser(usage=usage) parser = OptionParser(usage=usage)
parser.disable_interspersed_args() parser.disable_interspersed_args()
progname = os.path.basename(sys.argv[0]) or 'koji' progname = os.path.basename(sys.argv[0]) or 'koji'
@ -144,7 +144,7 @@ def get_options():
parser.add_option("--topurl", help=_("url for Koji file access")) parser.add_option("--topurl", help=_("url for Koji file access"))
parser.add_option("--pkgurl", help=SUPPRESS_HELP) parser.add_option("--pkgurl", help=SUPPRESS_HELP)
parser.add_option("--plugin-paths", metavar='PATHS', parser.add_option("--plugin-paths", metavar='PATHS',
help=_("specify additional plugin paths (colon separated)")) help=_("specify additional plugin paths (colon separated)"))
parser.add_option("--help-commands", action="store_true", default=False, help=_("list commands")) parser.add_option("--help-commands", action="store_true", default=False, help=_("list commands"))
(options, args) = parser.parse_args() (options, args) = parser.parse_args()

View file

@ -149,7 +149,7 @@ def handle_assign_task(goptions, session, args):
usage = _('usage: %prog assign-task <task_id> <hostname>') usage = _('usage: %prog assign-task <task_id> <hostname>')
parser = OptionParser(usage=get_usage_str(usage)) parser = OptionParser(usage=get_usage_str(usage))
parser.add_option('-f', '--force', action='store_true', default=False, parser.add_option('-f', '--force', action='store_true', default=False,
help=_('force to assign a non-free task')) help=_('force to assign a non-free task'))
(options, args) = parser.parse_args(args) (options, args) = parser.parse_args(args)
if len(args) != 2: if len(args) != 2:
@ -457,9 +457,9 @@ def handle_build(options, session, args):
parser.add_option("--nowait", action="store_false", dest="wait", parser.add_option("--nowait", action="store_false", dest="wait",
help=_("Don't wait on build")) help=_("Don't wait on build"))
parser.add_option("--wait-repo", action="store_true", parser.add_option("--wait-repo", action="store_true",
help=_("Wait for the actual buildroot repo of given target")) help=_("Wait for the actual buildroot repo of given target"))
parser.add_option("--wait-build", metavar="NVR", action="append", dest="wait_builds", parser.add_option("--wait-build", metavar="NVR", action="append", dest="wait_builds",
default=[], help=_("Wait for the given nvr to appear in buildroot repo")) default=[], help=_("Wait for the given nvr to appear in buildroot repo"))
parser.add_option("--quiet", action="store_true", parser.add_option("--quiet", action="store_true",
help=_("Do not print the task information"), default=options.quiet) help=_("Do not print the task information"), default=options.quiet)
parser.add_option("--arch-override", help=_("Override build arches")) parser.add_option("--arch-override", help=_("Override build arches"))
@ -521,7 +521,7 @@ def handle_build(options, session, args):
if build_opts.wait or (build_opts.wait is None and not _running_in_bg()): if build_opts.wait or (build_opts.wait is None and not _running_in_bg()):
session.logout() session.logout()
return watch_tasks(session, [task_id], quiet=build_opts.quiet, return watch_tasks(session, [task_id], quiet=build_opts.quiet,
poll_interval=options.poll_interval) poll_interval=options.poll_interval)
else: else:
return return
@ -598,7 +598,7 @@ def handle_chain_build(options, session, args):
else: else:
session.logout() session.logout()
return watch_tasks(session, [task_id], quiet=build_opts.quiet, return watch_tasks(session, [task_id], quiet=build_opts.quiet,
poll_interval=options.poll_interval) poll_interval=options.poll_interval)
def handle_maven_build(options, session, args): def handle_maven_build(options, session, args):
@ -697,7 +697,7 @@ def handle_maven_build(options, session, args):
else: else:
session.logout() session.logout()
return watch_tasks(session, [task_id], quiet=build_opts.quiet, return watch_tasks(session, [task_id], quiet=build_opts.quiet,
poll_interval=options.poll_interval) poll_interval=options.poll_interval)
def handle_wrapper_rpm(options, session, args): def handle_wrapper_rpm(options, session, args):
@ -764,7 +764,7 @@ def handle_wrapper_rpm(options, session, args):
else: else:
session.logout() session.logout()
return watch_tasks(session, [task_id], quiet=options.quiet, return watch_tasks(session, [task_id], quiet=options.quiet,
poll_interval=options.poll_interval) poll_interval=options.poll_interval)
def handle_maven_chain(options, session, args): def handle_maven_chain(options, session, args):
@ -816,7 +816,7 @@ def handle_maven_chain(options, session, args):
else: else:
session.logout() session.logout()
return watch_tasks(session, [task_id], quiet=options.quiet, return watch_tasks(session, [task_id], quiet=options.quiet,
poll_interval=options.poll_interval) poll_interval=options.poll_interval)
def handle_resubmit(goptions, session, args): def handle_resubmit(goptions, session, args):
@ -825,9 +825,9 @@ def handle_resubmit(goptions, session, args):
parser = OptionParser(usage=get_usage_str(usage)) parser = OptionParser(usage=get_usage_str(usage))
parser.add_option("--nowait", action="store_true", help=_("Don't wait on task")) parser.add_option("--nowait", action="store_true", help=_("Don't wait on task"))
parser.add_option("--nowatch", action="store_true", dest="nowait", parser.add_option("--nowatch", action="store_true", dest="nowait",
help=_("An alias for --nowait")) help=_("An alias for --nowait"))
parser.add_option("--quiet", action="store_true", default=goptions.quiet, parser.add_option("--quiet", action="store_true", default=goptions.quiet,
help=_("Do not print the task information")) help=_("Do not print the task information"))
(options, args) = parser.parse_args(args) (options, args) = parser.parse_args(args)
if len(args) != 1: if len(args) != 1:
parser.error(_("Please specify a single task ID")) parser.error(_("Please specify a single task ID"))
@ -844,7 +844,7 @@ def handle_resubmit(goptions, session, args):
else: else:
session.logout() session.logout()
return watch_tasks(session, [newID], quiet=options.quiet, return watch_tasks(session, [newID], quiet=options.quiet,
poll_interval=goptions.poll_interval) poll_interval=goptions.poll_interval)
def handle_call(goptions, session, args): def handle_call(goptions, session, args):
@ -1104,7 +1104,7 @@ def handle_restart_hosts(options, session, args):
'method': 'restartHosts', 'method': 'restartHosts',
'state': 'state':
[koji.TASK_STATES[s] for s in ('FREE', 'OPEN', 'ASSIGNED')], [koji.TASK_STATES[s] for s in ('FREE', 'OPEN', 'ASSIGNED')],
} }
others = session.listTasks(query) others = session.listTasks(query)
if others: if others:
print('Found other restartHosts tasks running.') print('Found other restartHosts tasks running.')
@ -1127,7 +1127,7 @@ def handle_restart_hosts(options, session, args):
if my_opts.wait or (my_opts.wait is None and not _running_in_bg()): if my_opts.wait or (my_opts.wait is None and not _running_in_bg()):
session.logout() session.logout()
return watch_tasks(session, [task_id], quiet=my_opts.quiet, return watch_tasks(session, [task_id], quiet=my_opts.quiet,
poll_interval=options.poll_interval) poll_interval=options.poll_interval)
else: else:
return return
@ -1154,7 +1154,7 @@ def handle_import(goptions, session, args):
to_import = {} to_import = {}
for path in args: for path in args:
data = koji.get_header_fields(path, ('name','version','release','epoch', data = koji.get_header_fields(path, ('name','version','release','epoch',
'arch','sigmd5','sourcepackage','sourcerpm')) 'arch','sigmd5','sourcepackage','sourcerpm'))
if data['sourcepackage']: if data['sourcepackage']:
data['arch'] = 'src' data['arch'] = 'src'
nvr = "%(name)s-%(version)s-%(release)s" % data nvr = "%(name)s-%(version)s-%(release)s" % data
@ -1190,7 +1190,7 @@ def handle_import(goptions, session, args):
print(_("WARNING: md5sum mismatch for %s") % path) print(_("WARNING: md5sum mismatch for %s") % path)
print(_(" A different rpm with the same name has already been imported")) print(_(" A different rpm with the same name has already been imported"))
print(_(" Existing sigmd5 is %r, your import has %r") % ( print(_(" Existing sigmd5 is %r, your import has %r") % (
prev['payloadhash'], koji.hex_string(data['sigmd5']))) prev['payloadhash'], koji.hex_string(data['sigmd5'])))
print(_("Skipping import")) print(_("Skipping import"))
return return
if options.test: if options.test:
@ -1371,16 +1371,16 @@ def _import_comps(session, filename, tag, options):
for group in comps.groups: for group in comps.groups:
print("Group: %s (%s)" % (group.id, group.name)) print("Group: %s (%s)" % (group.id, group.name))
session.groupListAdd( session.groupListAdd(
tag, group.id, force=force, display_name=group.name, tag, group.id, force=force, display_name=group.name,
is_default=bool(group.default), is_default=bool(group.default),
uservisible=bool(group.uservisible), uservisible=bool(group.uservisible),
description=group.desc, description=group.desc,
langonly=group.lang_only, langonly=group.lang_only,
biarchonly=bool(group.biarchonly)) biarchonly=bool(group.biarchonly))
for pkg in group.packages: for pkg in group.packages:
pkgopts = {'type' : ptypes[pkg.type], pkgopts = {'type' : ptypes[pkg.type],
'basearchonly' : bool(pkg.basearchonly), 'basearchonly' : bool(pkg.basearchonly),
} }
if pkg.type == libcomps.PACKAGE_TYPE_CONDITIONAL: if pkg.type == libcomps.PACKAGE_TYPE_CONDITIONAL:
pkgopts['requires'] = pkg.requires pkgopts['requires'] = pkg.requires
for k in pkgopts.keys(): for k in pkgopts.keys():
@ -1402,10 +1402,10 @@ def _import_comps_alt(session, filename, tag, options): # no cover 3.x
for group in comps.groups: for group in comps.groups:
print("Group: %(groupid)s (%(name)s)" % vars(group)) print("Group: %(groupid)s (%(name)s)" % vars(group))
session.groupListAdd(tag, group.groupid, force=force, display_name=group.name, session.groupListAdd(tag, group.groupid, force=force, display_name=group.name,
is_default=bool(group.default), is_default=bool(group.default),
uservisible=bool(group.user_visible), uservisible=bool(group.user_visible),
description=group.description, description=group.description,
langonly=group.langonly) langonly=group.langonly)
# yum.comps does not support the biarchonly field # yum.comps does not support the biarchonly field
for ptype, pdata in [('mandatory', group.mandatory_packages), for ptype, pdata in [('mandatory', group.mandatory_packages),
('default', group.default_packages), ('default', group.default_packages),
@ -1704,7 +1704,7 @@ def handle_prune_signed_copies(options, session, args):
# we were still tagged here sometime before the cutoff # we were still tagged here sometime before the cutoff
if options.debug: if options.debug:
print("Build %s had protected tag %s until %s" \ print("Build %s had protected tag %s until %s" \
% (nvr, tag_name, time.asctime(time.localtime(our_entry['revoke_ts'])))) % (nvr, tag_name, time.asctime(time.localtime(our_entry['revoke_ts']))))
is_protected = True is_protected = True
break break
replaced_ts = None replaced_ts = None
@ -1722,7 +1722,7 @@ def handle_prune_signed_copies(options, session, args):
if is_create: if is_create:
# shouldn't happen # shouldn't happen
raise koji.GenericError("Duplicate creation event found for %s in %s" \ raise koji.GenericError("Duplicate creation event found for %s in %s" \
% (nvr, tag_name)) % (nvr, tag_name))
else: else:
# we've been revoked # we've been revoked
revoke_ts = entry['revoke_ts'] revoke_ts = entry['revoke_ts']
@ -1763,20 +1763,20 @@ def handle_prune_signed_copies(options, session, args):
timestamps.append(replaced_ts) timestamps.append(replaced_ts)
if options.debug: if options.debug:
print("tag %s: %s not latest (replaced %s)" \ print("tag %s: %s not latest (replaced %s)" \
% (tag_name, nvr, time.asctime(time.localtime(replaced_ts)))) % (tag_name, nvr, time.asctime(time.localtime(replaced_ts))))
elif replaced_ts is None: elif replaced_ts is None:
# revoked but not replaced # revoked but not replaced
timestamps.append(revoke_ts) timestamps.append(revoke_ts)
if options.debug: if options.debug:
print("tag %s: %s not latest (revoked %s)" \ print("tag %s: %s not latest (revoked %s)" \
% (tag_name, nvr, time.asctime(time.localtime(revoke_ts)))) % (tag_name, nvr, time.asctime(time.localtime(revoke_ts))))
else: else:
# revoked AND replaced # revoked AND replaced
timestamps.append(min(revoke_ts, replaced_ts)) timestamps.append(min(revoke_ts, replaced_ts))
if options.debug: if options.debug:
print("tag %s: %s not latest (revoked %s, replaced %s)" \ print("tag %s: %s not latest (revoked %s, replaced %s)" \
% (tag_name, nvr, time.asctime(time.localtime(revoke_ts)), % (tag_name, nvr, time.asctime(time.localtime(revoke_ts)),
time.asctime(time.localtime(replaced_ts)))) time.asctime(time.localtime(replaced_ts))))
last_latest = max(timestamps) last_latest = max(timestamps)
if last_latest > cutoff_ts: if last_latest > cutoff_ts:
if options.debug: if options.debug:
@ -1867,7 +1867,7 @@ def handle_prune_signed_copies(options, session, args):
total_space += build_space total_space += build_space
if options.verbose: if options.verbose:
print("Build: %s, Removed %i signed copies (%i bytes). Total: %i/%i" \ print("Build: %s, Removed %i signed copies (%i bytes). Total: %i/%i" \
% (nvr, build_files, build_space, total_files, total_space)) % (nvr, build_files, build_space, total_files, total_space))
elif options.debug and by_sig: elif options.debug and by_sig:
print("(build has no signed copies)") print("(build has no signed copies)")
print("--- Grand Totals ---") print("--- Grand Totals ---")
@ -2300,7 +2300,7 @@ def anon_handle_latest_build(goptions, session, args):
parser.add_option("--arch", help=_("List all of the latest packages for this arch")) parser.add_option("--arch", help=_("List all of the latest packages for this arch"))
parser.add_option("--all", action="store_true", help=_("List all of the latest packages for this tag")) parser.add_option("--all", action="store_true", help=_("List all of the latest packages for this tag"))
parser.add_option("--quiet", action="store_true", default=goptions.quiet, parser.add_option("--quiet", action="store_true", default=goptions.quiet,
help=_("Do not print the header information")) help=_("Do not print the header information"))
parser.add_option("--paths", action="store_true", help=_("Show the file paths")) parser.add_option("--paths", action="store_true", help=_("Show the file paths"))
parser.add_option("--type", help=_("Show builds of the given type only. Currently supported types: maven")) parser.add_option("--type", help=_("Show builds of the given type only. Currently supported types: maven"))
(options, args) = parser.parse_args(args) (options, args) = parser.parse_args(args)
@ -2401,7 +2401,7 @@ def anon_handle_list_tagged(goptions, session, args):
parser.add_option("--latest", action="store_true", help=_("Only show the latest builds/rpms")) parser.add_option("--latest", action="store_true", help=_("Only show the latest builds/rpms"))
parser.add_option("--latest-n", type='int', metavar="N", help=_("Only show the latest N builds/rpms")) parser.add_option("--latest-n", type='int', metavar="N", help=_("Only show the latest N builds/rpms"))
parser.add_option("--quiet", action="store_true", default=goptions.quiet, parser.add_option("--quiet", action="store_true", default=goptions.quiet,
help=_("Do not print the header information")) help=_("Do not print the header information"))
parser.add_option("--paths", action="store_true", help=_("Show the file paths")) parser.add_option("--paths", action="store_true", help=_("Show the file paths"))
parser.add_option("--sigs", action="store_true", help=_("Show signatures")) parser.add_option("--sigs", action="store_true", help=_("Show signatures"))
parser.add_option("--type", help=_("Show builds of the given type only. Currently supported types: maven, win, image")) parser.add_option("--type", help=_("Show builds of the given type only. Currently supported types: maven, win, image"))
@ -2733,9 +2733,9 @@ def anon_handle_list_channels(goptions, session, args):
usage = _("usage: %prog list-channels") usage = _("usage: %prog list-channels")
parser = OptionParser(usage=get_usage_str(usage)) parser = OptionParser(usage=get_usage_str(usage))
parser.add_option("--simple", action="store_true", default=False, parser.add_option("--simple", action="store_true", default=False,
help=_("Print just list of channels without additional info")) help=_("Print just list of channels without additional info"))
parser.add_option("--quiet", action="store_true", default=goptions.quiet, parser.add_option("--quiet", action="store_true", default=goptions.quiet,
help=_("Do not print header information")) help=_("Do not print header information"))
(options, args) = parser.parse_args(args) (options, args) = parser.parse_args(args)
activate_session(session, goptions) activate_session(session, goptions)
channels = session.listChannels() channels = session.listChannels()
@ -2777,7 +2777,7 @@ def anon_handle_list_hosts(goptions, session, args):
parser.add_option("--not-enabled", action="store_false", dest="enabled", help=_("Limit to not enabled hosts")) parser.add_option("--not-enabled", action="store_false", dest="enabled", help=_("Limit to not enabled hosts"))
parser.add_option("--disabled", action="store_false", dest="enabled", help=_("Alias for --not-enabled")) parser.add_option("--disabled", action="store_false", dest="enabled", help=_("Alias for --not-enabled"))
parser.add_option("--quiet", action="store_true", default=goptions.quiet, parser.add_option("--quiet", action="store_true", default=goptions.quiet,
help=_("Do not print header information")) help=_("Do not print header information"))
parser.add_option("--show-channels", action="store_true", help=_("Show host's channels")) parser.add_option("--show-channels", action="store_true", help=_("Show host's channels"))
(options, args) = parser.parse_args(args) (options, args) = parser.parse_args(args)
opts = {} opts = {}
@ -2848,7 +2848,7 @@ def anon_handle_list_pkgs(goptions, session, args):
parser.add_option("--tag", help=_("Specify tag")) parser.add_option("--tag", help=_("Specify tag"))
parser.add_option("--package", help=_("Specify package")) parser.add_option("--package", help=_("Specify package"))
parser.add_option("--quiet", action="store_true", default=goptions.quiet, parser.add_option("--quiet", action="store_true", default=goptions.quiet,
help=_("Do not print header information")) help=_("Do not print header information"))
parser.add_option("--noinherit", action="store_true", help=_("Don't follow inheritance")) parser.add_option("--noinherit", action="store_true", help=_("Don't follow inheritance"))
parser.add_option("--show-blocked", action="store_true", help=_("Show blocked packages")) parser.add_option("--show-blocked", action="store_true", help=_("Show blocked packages"))
parser.add_option("--show-dups", action="store_true", help=_("Show superseded owners")) parser.add_option("--show-dups", action="store_true", help=_("Show superseded owners"))
@ -2945,7 +2945,7 @@ def anon_handle_list_builds(goptions, session, args):
parser.add_option("-r", "--reverse", action="store_true", default=False, parser.add_option("-r", "--reverse", action="store_true", default=False,
help=_("Print the list in reverse order")) help=_("Print the list in reverse order"))
parser.add_option("--quiet", action="store_true", default=goptions.quiet, parser.add_option("--quiet", action="store_true", default=goptions.quiet,
help=_("Do not print the header information")) help=_("Do not print the header information"))
(options, args) = parser.parse_args(args) (options, args) = parser.parse_args(args)
if len(args) != 0: if len(args) != 0:
parser.error(_("This command takes no arguments")) parser.error(_("This command takes no arguments"))
@ -3265,35 +3265,35 @@ def handle_clone_tag(goptions, session, args):
usage += _("\nclone-tag will create the destination tag if it does not already exist") usage += _("\nclone-tag will create the destination tag if it does not already exist")
parser = OptionParser(usage=get_usage_str(usage)) parser = OptionParser(usage=get_usage_str(usage))
parser.add_option('--config', action='store_true', parser.add_option('--config', action='store_true',
help=_("Copy config from the source to the dest tag")) help=_("Copy config from the source to the dest tag"))
parser.add_option('--groups', action='store_true', parser.add_option('--groups', action='store_true',
help=_("Copy group information")) help=_("Copy group information"))
parser.add_option('--pkgs', action='store_true', parser.add_option('--pkgs', action='store_true',
help=_("Copy package list from the source to the dest tag")) help=_("Copy package list from the source to the dest tag"))
parser.add_option('--builds', action='store_true', parser.add_option('--builds', action='store_true',
help=_("Tag builds into the dest tag")) help=_("Tag builds into the dest tag"))
parser.add_option('--all', action='store_true', parser.add_option('--all', action='store_true',
help=_("The same as --config --groups --pkgs --builds")) help=_("The same as --config --groups --pkgs --builds"))
parser.add_option('--latest-only', action='store_true', parser.add_option('--latest-only', action='store_true',
help=_("Tag only the latest build of each package")) help=_("Tag only the latest build of each package"))
parser.add_option('--inherit-builds', action='store_true', parser.add_option('--inherit-builds', action='store_true',
help=_("Include all builds inherited into the source tag into " help=_("Include all builds inherited into the source tag into "
"the dest tag")) "the dest tag"))
parser.add_option('--ts', type='int', metavar="TIMESTAMP", parser.add_option('--ts', type='int', metavar="TIMESTAMP",
help=_('Clone tag at last event before specific timestamp')) help=_('Clone tag at last event before specific timestamp'))
parser.add_option('--event', type='int', parser.add_option('--event', type='int',
help=_('Clone tag at a specific event')) help=_('Clone tag at a specific event'))
parser.add_option('--repo', type='int', parser.add_option('--repo', type='int',
help=_('Clone tag at a specific repo event')) help=_('Clone tag at a specific repo event'))
parser.add_option("-v", "--verbose", action="store_true", parser.add_option("-v", "--verbose", action="store_true",
help=_("show changes")) help=_("show changes"))
parser.add_option("--notify", action="store_true", default=False, parser.add_option("--notify", action="store_true", default=False,
help=_('Send tagging/untagging notifications')) help=_('Send tagging/untagging notifications'))
parser.add_option("-f", "--force", action="store_true", parser.add_option("-f", "--force", action="store_true",
help=_("override tag locks if necessary")) help=_("override tag locks if necessary"))
parser.add_option("-n", "--test", action="store_true", help=_("test mode")) parser.add_option("-n", "--test", action="store_true", help=_("test mode"))
parser.add_option("--batch", type='int', default=1000, metavar='SIZE', parser.add_option("--batch", type='int', default=1000, metavar='SIZE',
help=_("batch size of multicalls [0 to disable, default: %default]")) help=_("batch size of multicalls [0 to disable, default: %default]"))
(options, args) = parser.parse_args(args) (options, args) = parser.parse_args(args)
if len(args) != 2: if len(args) != 2:
@ -3866,7 +3866,7 @@ def anon_handle_list_targets(goptions, session, args):
parser = OptionParser(usage=get_usage_str(usage)) parser = OptionParser(usage=get_usage_str(usage))
parser.add_option("--name", help=_("Specify the build target name")) parser.add_option("--name", help=_("Specify the build target name"))
parser.add_option("--quiet", action="store_true", default=goptions.quiet, parser.add_option("--quiet", action="store_true", default=goptions.quiet,
help=_("Do not print the header information")) help=_("Do not print the header information"))
(options, args) = parser.parse_args(args) (options, args) = parser.parse_args(args)
if len(args) != 0: if len(args) != 0:
parser.error(_("This command takes no arguments")) parser.error(_("This command takes no arguments"))
@ -4329,7 +4329,7 @@ _table_keys = {
'group_config' : ['group_id', 'tag_id'], 'group_config' : ['group_id', 'tag_id'],
'group_req_listing' : ['group_id', 'tag_id', 'req_id'], 'group_req_listing' : ['group_id', 'tag_id', 'req_id'],
'group_package_listing' : ['group_id', 'tag_id', 'package'], 'group_package_listing' : ['group_id', 'tag_id', 'package'],
} }
def anon_handle_list_history(goptions, session, args): def anon_handle_list_history(goptions, session, args):
@ -4356,7 +4356,7 @@ def anon_handle_list_history(goptions, session, args):
parser.add_option("--watch", action="store_true", help=_("Monitor history data")) parser.add_option("--watch", action="store_true", help=_("Monitor history data"))
parser.add_option("--active", action='store_true', help=_("Only show entries that are currently active")) parser.add_option("--active", action='store_true', help=_("Only show entries that are currently active"))
parser.add_option("--revoked", action='store_false', dest='active', parser.add_option("--revoked", action='store_false', dest='active',
help=_("Only show entries that are currently revoked")) help=_("Only show entries that are currently revoked"))
parser.add_option("--context", action="store_true", help=_("Show related entries")) parser.add_option("--context", action="store_true", help=_("Show related entries"))
parser.add_option("-s", "--show", action="append", help=_("Show data from selected tables")) parser.add_option("-s", "--show", action="append", help=_("Show data from selected tables"))
parser.add_option("-v", "--verbose", action="store_true", help=_("Show more detail")) parser.add_option("-v", "--verbose", action="store_true", help=_("Show more detail"))
@ -4660,12 +4660,12 @@ def _printTaskInfo(session, task_id, topdir, level=0, recurse=True, verbose=True
for filename in files: for filename in files:
if filename.endswith('.log'): if filename.endswith('.log'):
logs += [os.path.join(koji.pathinfo.work(volume=volume), logs += [os.path.join(koji.pathinfo.work(volume=volume),
koji.pathinfo.taskrelpath(task_id), koji.pathinfo.taskrelpath(task_id),
filename) for volume in files[filename]] filename) for volume in files[filename]]
else: else:
output += [os.path.join(koji.pathinfo.work(volume=volume), output += [os.path.join(koji.pathinfo.work(volume=volume),
koji.pathinfo.taskrelpath(task_id), koji.pathinfo.taskrelpath(task_id),
filename) for volume in files[filename]] filename) for volume in files[filename]]
owner = session.getUser(info['owner'])['name'] owner = session.getUser(info['owner'])['name']
@ -5035,7 +5035,7 @@ def handle_add_tag_inheritance(goptions, session, args):
if sameParents and not options.force: if sameParents and not options.force:
print(_("Error: You are attempting to add %s as %s's parent even though it already is %s's parent.") print(_("Error: You are attempting to add %s as %s's parent even though it already is %s's parent.")
% (parent['name'], tag['name'], tag['name'])) % (parent['name'], tag['name'], tag['name']))
print(_("Please use --force if this is what you really want to do.")) print(_("Please use --force if this is what you really want to do."))
return return
if samePriority: if samePriority:
@ -5244,7 +5244,7 @@ def anon_handle_list_external_repos(goptions, session, args):
parser.add_option("--event", type='int', metavar="EVENT#", help=_("Query at event")) parser.add_option("--event", type='int', metavar="EVENT#", help=_("Query at event"))
parser.add_option("--ts", type='int', metavar="TIMESTAMP", help=_("Query at last event before timestamp")) parser.add_option("--ts", type='int', metavar="TIMESTAMP", help=_("Query at last event before timestamp"))
parser.add_option("--repo", type='int', metavar="REPO#", parser.add_option("--repo", type='int', metavar="REPO#",
help=_("Query at event corresponding to (nonexternal) repo")) help=_("Query at event corresponding to (nonexternal) repo"))
parser.add_option("--quiet", action="store_true", default=goptions.quiet, parser.add_option("--quiet", action="store_true", default=goptions.quiet,
help=_("Do not display the column headers")) help=_("Do not display the column headers"))
(options, args) = parser.parse_args(args) (options, args) = parser.parse_args(args)
@ -5372,7 +5372,7 @@ def handle_add_external_repo(goptions, session, args):
callopts['merge_mode'] = options.mode callopts['merge_mode'] = options.mode
session.addExternalRepoToTag(tag, rinfo['name'], priority, **callopts) session.addExternalRepoToTag(tag, rinfo['name'], priority, **callopts)
print("Added external repo %s to tag %s (priority %i)" \ print("Added external repo %s to tag %s (priority %i)" \
% (rinfo['name'], tag, priority)) % (rinfo['name'], tag, priority))
def handle_edit_external_repo(goptions, session, args): def handle_edit_external_repo(goptions, session, args):
@ -5443,27 +5443,27 @@ def handle_spin_livecd(options, session, args):
" <arch> <kickstart-file>") " <arch> <kickstart-file>")
parser = OptionParser(usage=get_usage_str(usage)) parser = OptionParser(usage=get_usage_str(usage))
parser.add_option("--wait", action="store_true", parser.add_option("--wait", action="store_true",
help=_("Wait on the livecd creation, even if running in the background")) help=_("Wait on the livecd creation, even if running in the background"))
parser.add_option("--nowait", action="store_false", dest="wait", parser.add_option("--nowait", action="store_false", dest="wait",
help=_("Don't wait on livecd creation")) help=_("Don't wait on livecd creation"))
parser.add_option("--noprogress", action="store_true", parser.add_option("--noprogress", action="store_true",
help=_("Do not display progress of the upload")) help=_("Do not display progress of the upload"))
parser.add_option("--background", action="store_true", parser.add_option("--background", action="store_true",
help=_("Run the livecd creation task at a lower priority")) help=_("Run the livecd creation task at a lower priority"))
parser.add_option("--ksurl", metavar="SCMURL", parser.add_option("--ksurl", metavar="SCMURL",
help=_("The URL to the SCM containing the kickstart file")) help=_("The URL to the SCM containing the kickstart file"))
parser.add_option("--ksversion", metavar="VERSION", parser.add_option("--ksversion", metavar="VERSION",
help=_("The syntax version used in the kickstart file")) help=_("The syntax version used in the kickstart file"))
parser.add_option("--scratch", action="store_true", parser.add_option("--scratch", action="store_true",
help=_("Create a scratch LiveCD image")) help=_("Create a scratch LiveCD image"))
parser.add_option("--repo", action="append", parser.add_option("--repo", action="append",
help=_("Specify a repo that will override the repo used to install " + help=_("Specify a repo that will override the repo used to install " +
"RPMs in the LiveCD. May be used multiple times. The " + "RPMs in the LiveCD. May be used multiple times. The " +
"build tag repo associated with the target is the default.")) "build tag repo associated with the target is the default."))
parser.add_option("--release", help=_("Forcibly set the release field")) parser.add_option("--release", help=_("Forcibly set the release field"))
parser.add_option("--volid", help=_("Set the volume id")) parser.add_option("--volid", help=_("Set the volume id"))
parser.add_option("--specfile", metavar="URL", parser.add_option("--specfile", metavar="URL",
help=_("SCM URL to spec file fragment to use to generate wrapper RPMs")) help=_("SCM URL to spec file fragment to use to generate wrapper RPMs"))
parser.add_option("--skip-tag", action="store_true", parser.add_option("--skip-tag", action="store_true",
help=_("Do not attempt to tag package")) help=_("Do not attempt to tag package"))
(task_options, args) = parser.parse_args(args) (task_options, args) = parser.parse_args(args)
@ -5488,34 +5488,34 @@ def handle_spin_livemedia(options, session, args):
" <arch> <kickstart-file>") " <arch> <kickstart-file>")
parser = OptionParser(usage=get_usage_str(usage)) parser = OptionParser(usage=get_usage_str(usage))
parser.add_option("--wait", action="store_true", parser.add_option("--wait", action="store_true",
help=_("Wait on the livemedia creation, even if running in the background")) help=_("Wait on the livemedia creation, even if running in the background"))
parser.add_option("--nowait", action="store_false", dest="wait", parser.add_option("--nowait", action="store_false", dest="wait",
help=_("Don't wait on livemedia creation")) help=_("Don't wait on livemedia creation"))
parser.add_option("--noprogress", action="store_true", parser.add_option("--noprogress", action="store_true",
help=_("Do not display progress of the upload")) help=_("Do not display progress of the upload"))
parser.add_option("--background", action="store_true", parser.add_option("--background", action="store_true",
help=_("Run the livemedia creation task at a lower priority")) help=_("Run the livemedia creation task at a lower priority"))
parser.add_option("--ksurl", metavar="SCMURL", parser.add_option("--ksurl", metavar="SCMURL",
help=_("The URL to the SCM containing the kickstart file")) help=_("The URL to the SCM containing the kickstart file"))
parser.add_option("--install-tree-url", metavar="URL", parser.add_option("--install-tree-url", metavar="URL",
help=_("Provide the URL for the install tree")) help=_("Provide the URL for the install tree"))
parser.add_option("--ksversion", metavar="VERSION", parser.add_option("--ksversion", metavar="VERSION",
help=_("The syntax version used in the kickstart file")) help=_("The syntax version used in the kickstart file"))
parser.add_option("--scratch", action="store_true", parser.add_option("--scratch", action="store_true",
help=_("Create a scratch LiveMedia image")) help=_("Create a scratch LiveMedia image"))
parser.add_option("--repo", action="append", parser.add_option("--repo", action="append",
help=_("Specify a repo that will override the repo used to install " + help=_("Specify a repo that will override the repo used to install " +
"RPMs in the LiveMedia. May be used multiple times. The " + "RPMs in the LiveMedia. May be used multiple times. The " +
"build tag repo associated with the target is the default.")) "build tag repo associated with the target is the default."))
parser.add_option("--release", help=_("Forcibly set the release field")) parser.add_option("--release", help=_("Forcibly set the release field"))
parser.add_option("--volid", help=_("Set the volume id")) parser.add_option("--volid", help=_("Set the volume id"))
parser.add_option("--specfile", metavar="URL", parser.add_option("--specfile", metavar="URL",
help=_("SCM URL to spec file fragment to use to generate wrapper RPMs")) help=_("SCM URL to spec file fragment to use to generate wrapper RPMs"))
parser.add_option("--skip-tag", action="store_true", parser.add_option("--skip-tag", action="store_true",
help=_("Do not attempt to tag package")) help=_("Do not attempt to tag package"))
parser.add_option("--can-fail", action="store", dest="optional_arches", parser.add_option("--can-fail", action="store", dest="optional_arches",
metavar="ARCH1,ARCH2,...", default="", metavar="ARCH1,ARCH2,...", default="",
help=_("List of archs which are not blocking for build (separated by commas.")) help=_("List of archs which are not blocking for build (separated by commas."))
parser.add_option('--lorax_dir', metavar='DIR', parser.add_option('--lorax_dir', metavar='DIR',
help=_('The relative path to the lorax templates ' help=_('The relative path to the lorax templates '
'directory within the checkout of "lorax_url".')) 'directory within the checkout of "lorax_url".'))
@ -5548,37 +5548,37 @@ def handle_spin_appliance(options, session, args):
"<target> <arch> <kickstart-file>") "<target> <arch> <kickstart-file>")
parser = OptionParser(usage=get_usage_str(usage)) parser = OptionParser(usage=get_usage_str(usage))
parser.add_option("--wait", action="store_true", parser.add_option("--wait", action="store_true",
help=_("Wait on the appliance creation, even if running in the background")) help=_("Wait on the appliance creation, even if running in the background"))
parser.add_option("--nowait", action="store_false", dest="wait", parser.add_option("--nowait", action="store_false", dest="wait",
help=_("Don't wait on appliance creation")) help=_("Don't wait on appliance creation"))
parser.add_option("--noprogress", action="store_true", parser.add_option("--noprogress", action="store_true",
help=_("Do not display progress of the upload")) help=_("Do not display progress of the upload"))
parser.add_option("--background", action="store_true", parser.add_option("--background", action="store_true",
help=_("Run the appliance creation task at a lower priority")) help=_("Run the appliance creation task at a lower priority"))
parser.add_option("--ksurl", metavar="SCMURL", parser.add_option("--ksurl", metavar="SCMURL",
help=_("The URL to the SCM containing the kickstart file")) help=_("The URL to the SCM containing the kickstart file"))
parser.add_option("--ksversion", metavar="VERSION", parser.add_option("--ksversion", metavar="VERSION",
help=_("The syntax version used in the kickstart file")) help=_("The syntax version used in the kickstart file"))
parser.add_option("--scratch", action="store_true", parser.add_option("--scratch", action="store_true",
help=_("Create a scratch appliance")) help=_("Create a scratch appliance"))
parser.add_option("--repo", action="append", parser.add_option("--repo", action="append",
help=_("Specify a repo that will override the repo used to install " + help=_("Specify a repo that will override the repo used to install " +
"RPMs in the appliance. May be used multiple times. The " + "RPMs in the appliance. May be used multiple times. The " +
"build tag repo associated with the target is the default.")) "build tag repo associated with the target is the default."))
parser.add_option("--release", help=_("Forcibly set the release field")) parser.add_option("--release", help=_("Forcibly set the release field"))
parser.add_option("--specfile", metavar="URL", parser.add_option("--specfile", metavar="URL",
help=_("SCM URL to spec file fragment to use to generate wrapper RPMs")) help=_("SCM URL to spec file fragment to use to generate wrapper RPMs"))
parser.add_option("--skip-tag", action="store_true", parser.add_option("--skip-tag", action="store_true",
help=_("Do not attempt to tag package")) help=_("Do not attempt to tag package"))
parser.add_option("--vmem", metavar="VMEM", default=None, parser.add_option("--vmem", metavar="VMEM", default=None,
help=_("Set the amount of virtual memory in the appliance in MB, " + help=_("Set the amount of virtual memory in the appliance in MB, " +
"default is 512")) "default is 512"))
parser.add_option("--vcpu", metavar="VCPU", default=None, parser.add_option("--vcpu", metavar="VCPU", default=None,
help=_("Set the number of virtual cpus in the appliance, " + help=_("Set the number of virtual cpus in the appliance, " +
"default is 1")) "default is 1"))
parser.add_option("--format", metavar="DISK_FORMAT", default='raw', parser.add_option("--format", metavar="DISK_FORMAT", default='raw',
help=_("Disk format, default is raw. Other options are qcow, " + help=_("Disk format, default is raw. Other options are qcow, " +
"qcow2, and vmx.")) "qcow2, and vmx."))
(task_options, args) = parser.parse_args(args) (task_options, args) = parser.parse_args(args)
@ -5598,42 +5598,42 @@ def handle_image_build_indirection(options, session, args):
usage += _("\n %prog image-build --config <FILE>\n") usage += _("\n %prog image-build --config <FILE>\n")
parser = OptionParser(usage=get_usage_str(usage)) parser = OptionParser(usage=get_usage_str(usage))
parser.add_option("--config", parser.add_option("--config",
help=_("Use a configuration file to define image-build options " + help=_("Use a configuration file to define image-build options " +
"instead of command line options (they will be ignored).")) "instead of command line options (they will be ignored)."))
parser.add_option("--background", action="store_true", parser.add_option("--background", action="store_true",
help=_("Run the image creation task at a lower priority")) help=_("Run the image creation task at a lower priority"))
parser.add_option("--name", parser.add_option("--name",
help=_("Name of the output image")) help=_("Name of the output image"))
parser.add_option("--version", parser.add_option("--version",
help=_("Version of the output image")) help=_("Version of the output image"))
parser.add_option("--release", parser.add_option("--release",
help=_("Release of the output image")) help=_("Release of the output image"))
parser.add_option("--arch", parser.add_option("--arch",
help=_("Architecture of the output image and input images")) help=_("Architecture of the output image and input images"))
parser.add_option("--target", parser.add_option("--target",
help=_("Build target to use for the indirection build")) help=_("Build target to use for the indirection build"))
parser.add_option("--skip-tag", action="store_true", parser.add_option("--skip-tag", action="store_true",
help=_("Do not tag the resulting build")) help=_("Do not tag the resulting build"))
parser.add_option("--base-image-task", parser.add_option("--base-image-task",
help=_("ID of the createImage task of the base image to be used")) help=_("ID of the createImage task of the base image to be used"))
parser.add_option("--base-image-build", parser.add_option("--base-image-build",
help=_("NVR or build ID of the base image to be used")) help=_("NVR or build ID of the base image to be used"))
parser.add_option("--utility-image-task", parser.add_option("--utility-image-task",
help=_("ID of the createImage task of the utility image to be used")) help=_("ID of the createImage task of the utility image to be used"))
parser.add_option("--utility-image-build", parser.add_option("--utility-image-build",
help=_("NVR or build ID of the utility image to be used")) help=_("NVR or build ID of the utility image to be used"))
parser.add_option("--indirection-template", parser.add_option("--indirection-template",
help=_("Name of the local file, or SCM file containing the template used to drive the indirection plugin")) help=_("Name of the local file, or SCM file containing the template used to drive the indirection plugin"))
parser.add_option("--indirection-template-url", parser.add_option("--indirection-template-url",
help=_("SCM URL containing the template used to drive the indirection plugin")) help=_("SCM URL containing the template used to drive the indirection plugin"))
parser.add_option("--results-loc", parser.add_option("--results-loc",
help=_("Relative path inside the working space image where the results should be extracted from")) help=_("Relative path inside the working space image where the results should be extracted from"))
parser.add_option("--scratch", action="store_true", parser.add_option("--scratch", action="store_true",
help=_("Create a scratch image")) help=_("Create a scratch image"))
parser.add_option("--wait", action="store_true", parser.add_option("--wait", action="store_true",
help=_("Wait on the image creation, even if running in the background")) help=_("Wait on the image creation, even if running in the background"))
parser.add_option("--noprogress", action="store_true", parser.add_option("--noprogress", action="store_true",
help=_("Do not display progress of the upload")) help=_("Do not display progress of the upload"))
(task_options, args) = parser.parse_args(args) (task_options, args) = parser.parse_args(args)
@ -5689,7 +5689,7 @@ def _build_image_indirection(options, task_opts, session, args):
dest_tag = session.getTag(tmp_target['dest_tag']) dest_tag = session.getTag(tmp_target['dest_tag'])
if not dest_tag: if not dest_tag:
raise koji.GenericError(_("Unknown destination tag: %s" % raise koji.GenericError(_("Unknown destination tag: %s" %
tmp_target['dest_tag_name'])) tmp_target['dest_tag_name']))
# Set the architecture # Set the architecture
task_opts.arch = koji.canonArch(task_opts.arch) task_opts.arch = koji.canonArch(task_opts.arch)
@ -5705,7 +5705,7 @@ def _build_image_indirection(options, task_opts, session, args):
serverdir = unique_path('cli-image-indirection') serverdir = unique_path('cli-image-indirection')
session.uploadWrapper(templatefile, serverdir, callback=callback) session.uploadWrapper(templatefile, serverdir, callback=callback)
task_opts.indirection_template = os.path.join('work', serverdir, task_opts.indirection_template = os.path.join('work', serverdir,
os.path.basename(templatefile)) os.path.basename(templatefile))
print('') print('')
hub_opts = { } hub_opts = { }
@ -5741,57 +5741,57 @@ def handle_image_build(options, session, args):
usage += _("\n %prog image-build --config <FILE>\n") usage += _("\n %prog image-build --config <FILE>\n")
parser = OptionParser(usage=get_usage_str(usage)) parser = OptionParser(usage=get_usage_str(usage))
parser.add_option("--background", action="store_true", parser.add_option("--background", action="store_true",
help=_("Run the image creation task at a lower priority")) help=_("Run the image creation task at a lower priority"))
parser.add_option("--config", parser.add_option("--config",
help=_("Use a configuration file to define image-build options " + help=_("Use a configuration file to define image-build options " +
"instead of command line options (they will be ignored).")) "instead of command line options (they will be ignored)."))
parser.add_option("--disk-size", default=10, parser.add_option("--disk-size", default=10,
help=_("Set the disk device size in gigabytes")) help=_("Set the disk device size in gigabytes"))
parser.add_option("--distro", parser.add_option("--distro",
help=_("specify the RPM based distribution the image will be based " + help=_("specify the RPM based distribution the image will be based " +
"on with the format RHEL-X.Y, CentOS-X.Y, SL-X.Y, or Fedora-NN. " + "on with the format RHEL-X.Y, CentOS-X.Y, SL-X.Y, or Fedora-NN. " +
"The packages for the Distro you choose must have been built " + "The packages for the Distro you choose must have been built " +
"in this system.")) "in this system."))
parser.add_option("--format", default=[], action="append", parser.add_option("--format", default=[], action="append",
help=_("Convert results to one or more formats " + help=_("Convert results to one or more formats " +
"(%s), this option may be used " % ', '.join(formats) + "(%s), this option may be used " % ', '.join(formats) +
"multiple times. By default, specifying this option will " + "multiple times. By default, specifying this option will " +
"omit the raw disk image (which is 10G in size) from the " + "omit the raw disk image (which is 10G in size) from the " +
"build results. If you really want it included with converted " + "build results. If you really want it included with converted " +
"images, pass in 'raw' as an option.")) "images, pass in 'raw' as an option."))
parser.add_option("--kickstart", help=_("Path to a local kickstart file")) parser.add_option("--kickstart", help=_("Path to a local kickstart file"))
parser.add_option("--ksurl", metavar="SCMURL", parser.add_option("--ksurl", metavar="SCMURL",
help=_("The URL to the SCM containing the kickstart file")) help=_("The URL to the SCM containing the kickstart file"))
parser.add_option("--ksversion", metavar="VERSION", parser.add_option("--ksversion", metavar="VERSION",
help=_("The syntax version used in the kickstart file")) help=_("The syntax version used in the kickstart file"))
parser.add_option("--noprogress", action="store_true", parser.add_option("--noprogress", action="store_true",
help=_("Do not display progress of the upload")) help=_("Do not display progress of the upload"))
parser.add_option("--nowait", action="store_false", dest="wait", parser.add_option("--nowait", action="store_false", dest="wait",
help=_("Don't wait on image creation")) help=_("Don't wait on image creation"))
parser.add_option("--ova-option", action="append", parser.add_option("--ova-option", action="append",
help=_("Override a value in the OVA description XML. Provide a value " + help=_("Override a value in the OVA description XML. Provide a value " +
"in a name=value format, such as 'ovf_memory_mb=6144'")) "in a name=value format, such as 'ovf_memory_mb=6144'"))
parser.add_option("--factory-parameter", nargs=2, action="append", parser.add_option("--factory-parameter", nargs=2, action="append",
help=_("Pass a parameter to Image Factory. The results are highly specific " + help=_("Pass a parameter to Image Factory. The results are highly specific " +
"to the image format being created. This is a two argument parameter " + "to the image format being created. This is a two argument parameter " +
"that can be specified an arbitrary number of times. For example: " "that can be specified an arbitrary number of times. For example: "
"--factory-parameter docker_cmd '[ \"/bin/echo Hello World\" ]'")) "--factory-parameter docker_cmd '[ \"/bin/echo Hello World\" ]'"))
parser.add_option("--release", help=_("Forcibly set the release field")) parser.add_option("--release", help=_("Forcibly set the release field"))
parser.add_option("--repo", action="append", parser.add_option("--repo", action="append",
help=_("Specify a repo that will override the repo used to install " + help=_("Specify a repo that will override the repo used to install " +
"RPMs in the image. May be used multiple times. The " + "RPMs in the image. May be used multiple times. The " +
"build tag repo associated with the target is the default.")) "build tag repo associated with the target is the default."))
parser.add_option("--scratch", action="store_true", parser.add_option("--scratch", action="store_true",
help=_("Create a scratch image")) help=_("Create a scratch image"))
parser.add_option("--skip-tag", action="store_true", parser.add_option("--skip-tag", action="store_true",
help=_("Do not attempt to tag package")) help=_("Do not attempt to tag package"))
parser.add_option("--can-fail", action="store", dest="optional_arches", parser.add_option("--can-fail", action="store", dest="optional_arches",
metavar="ARCH1,ARCH2,...", default="", metavar="ARCH1,ARCH2,...", default="",
help=_("List of archs which are not blocking for build (separated by commas.")) help=_("List of archs which are not blocking for build (separated by commas."))
parser.add_option("--specfile", metavar="URL", parser.add_option("--specfile", metavar="URL",
help=_("SCM URL to spec file fragment to use to generate wrapper RPMs")) help=_("SCM URL to spec file fragment to use to generate wrapper RPMs"))
parser.add_option("--wait", action="store_true", parser.add_option("--wait", action="store_true",
help=_("Wait on the image creation, even if running in the background")) help=_("Wait on the image creation, even if running in the background"))
(task_options, args) = parser.parse_args(args) (task_options, args) = parser.parse_args(args)
@ -5878,7 +5878,7 @@ def _build_image(options, task_opts, session, args, img_type):
dest_tag = session.getTag(tmp_target['dest_tag']) dest_tag = session.getTag(tmp_target['dest_tag'])
if not dest_tag: if not dest_tag:
raise koji.GenericError(_("Unknown destination tag: %s" % raise koji.GenericError(_("Unknown destination tag: %s" %
tmp_target['dest_tag_name'])) tmp_target['dest_tag_name']))
# Set the architecture # Set the architecture
if img_type == 'livemedia': if img_type == 'livemedia':
@ -5903,7 +5903,7 @@ def _build_image(options, task_opts, session, args, img_type):
'ksversion', 'release', 'repo', 'scratch', 'skip_tag', 'ksversion', 'release', 'repo', 'scratch', 'skip_tag',
'specfile', 'vcpu', 'vmem', 'volid', 'optional_arches', 'specfile', 'vcpu', 'vmem', 'volid', 'optional_arches',
'lorax_dir', 'lorax_url', 'lorax_dir', 'lorax_url',
] ]
for opt in passthru_opts: for opt in passthru_opts:
val = getattr(task_opts, opt, None) val = getattr(task_opts, opt, None)
if val is not None: if val is not None:
@ -5922,7 +5922,7 @@ def _build_image(options, task_opts, session, args, img_type):
if task_opts.wait or (task_opts.wait is None and not _running_in_bg()): if task_opts.wait or (task_opts.wait is None and not _running_in_bg()):
session.logout() session.logout()
return watch_tasks(session, [task_id], quiet=options.quiet, return watch_tasks(session, [task_id], quiet=options.quiet,
poll_interval=options.poll_interval) poll_interval=options.poll_interval)
else: else:
return return
@ -5954,7 +5954,7 @@ def _build_image_oz(options, task_opts, session, args):
dest_tag = session.getTag(tmp_target['dest_tag']) dest_tag = session.getTag(tmp_target['dest_tag'])
if not dest_tag: if not dest_tag:
raise koji.GenericError(_("Unknown destination tag: %s" % raise koji.GenericError(_("Unknown destination tag: %s" %
tmp_target['dest_tag_name'])) tmp_target['dest_tag_name']))
# Set the architectures # Set the architectures
arches = [] arches = []
@ -5971,7 +5971,7 @@ def _build_image_oz(options, task_opts, session, args):
serverdir = unique_path('cli-image') serverdir = unique_path('cli-image')
session.uploadWrapper(ksfile, serverdir, callback=callback) session.uploadWrapper(ksfile, serverdir, callback=callback)
task_opts.kickstart = os.path.join('work', serverdir, task_opts.kickstart = os.path.join('work', serverdir,
os.path.basename(ksfile)) os.path.basename(ksfile))
print('') print('')
hub_opts = {} hub_opts = {}
@ -5985,7 +5985,7 @@ def _build_image_oz(options, task_opts, session, args):
# finally, create the task. # finally, create the task.
task_id = session.buildImageOz(args[0], args[1], arches, target, args[3], task_id = session.buildImageOz(args[0], args[1], arches, target, args[3],
opts=hub_opts, priority=priority) opts=hub_opts, priority=priority)
if not options.quiet: if not options.quiet:
print("Created task: %d" % task_id) print("Created task: %d" % task_id)
@ -5993,7 +5993,7 @@ def _build_image_oz(options, task_opts, session, args):
if task_opts.wait or (task_opts.wait is None and not _running_in_bg()): if task_opts.wait or (task_opts.wait is None and not _running_in_bg()):
session.logout() session.logout()
return watch_tasks(session, [task_id], quiet=options.quiet, return watch_tasks(session, [task_id], quiet=options.quiet,
poll_interval=options.poll_interval) poll_interval=options.poll_interval)
else: else:
return return
@ -6069,7 +6069,7 @@ def handle_win_build(options, session, args):
if build_opts.wait or (build_opts.wait is None and not _running_in_bg()): if build_opts.wait or (build_opts.wait is None and not _running_in_bg()):
session.logout() session.logout()
return watch_tasks(session, [task_id], quiet=build_opts.quiet, return watch_tasks(session, [task_id], quiet=build_opts.quiet,
poll_interval=options.poll_interval) poll_interval=options.poll_interval)
else: else:
return return
@ -6166,7 +6166,7 @@ def handle_list_tasks(goptions, session, args):
parser.add_option("--channel", help=_("Only tasks in this channel")) parser.add_option("--channel", help=_("Only tasks in this channel"))
parser.add_option("--host", help=_("Only tasks for this host")) parser.add_option("--host", help=_("Only tasks for this host"))
parser.add_option("--quiet", action="store_true", default=goptions.quiet, parser.add_option("--quiet", action="store_true", default=goptions.quiet,
help=_("Do not display the column headers")) help=_("Do not display the column headers"))
(options, args) = parser.parse_args(args) (options, args) = parser.parse_args(args)
if len(args) != 0: if len(args) != 0:
parser.error(_("This command takes no arguments")) parser.error(_("This command takes no arguments"))
@ -6262,15 +6262,15 @@ def handle_set_pkg_owner_global(goptions, session, args):
if user['id'] == entry['owner_id']: if user['id'] == entry['owner_id']:
if options.verbose: if options.verbose:
print("Preserving owner=%s for package %s in tag %s" \ print("Preserving owner=%s for package %s in tag %s" \
% (user['name'], package, entry['tag_name'])) % (user['name'], package, entry['tag_name']))
else: else:
if options.test: if options.test:
print("Would have changed owner for %s in tag %s: %s -> %s" \ print("Would have changed owner for %s in tag %s: %s -> %s" \
% (entry['package_name'], entry['tag_name'], entry['owner_name'], user['name'])) % (entry['package_name'], entry['tag_name'], entry['owner_name'], user['name']))
continue continue
if options.verbose: if options.verbose:
print("Changing owner for %s in tag %s: %s -> %s" \ print("Changing owner for %s in tag %s: %s -> %s" \
% (entry['package_name'], entry['tag_name'], entry['owner_name'], user['name'])) % (entry['package_name'], entry['tag_name'], entry['owner_name'], user['name']))
session.packageListSetOwner(entry['tag_id'], entry['package_name'], user['id']) session.packageListSetOwner(entry['tag_id'], entry['package_name'], user['id'])
@ -6313,7 +6313,7 @@ def anon_handle_watch_task(goptions, session, args):
parser.error(_("at least one task id must be specified")) parser.error(_("at least one task id must be specified"))
return watch_tasks(session, tasks, quiet=options.quiet, return watch_tasks(session, tasks, quiet=options.quiet,
poll_interval=goptions.poll_interval) poll_interval=goptions.poll_interval)
def anon_handle_watch_logs(goptions, session, args): def anon_handle_watch_logs(goptions, session, args):
@ -6322,7 +6322,7 @@ def anon_handle_watch_logs(goptions, session, args):
parser = OptionParser(usage=get_usage_str(usage)) parser = OptionParser(usage=get_usage_str(usage))
parser.add_option("--log", help=_("Watch only a specific log")) parser.add_option("--log", help=_("Watch only a specific log"))
parser.add_option("--mine", action="store_true", help=_("Watch logs for " parser.add_option("--mine", action="store_true", help=_("Watch logs for "
"all your tasks, task_id arguments are forbidden in this case.")) "all your tasks, task_id arguments are forbidden in this case."))
parser.add_option("--follow", action="store_true", help=_("Follow spawned child tasks")) parser.add_option("--follow", action="store_true", help=_("Follow spawned child tasks"))
(options, args) = parser.parse_args(args) (options, args) = parser.parse_args(args)
activate_session(session, goptions) activate_session(session, goptions)
@ -6375,7 +6375,7 @@ def handle_make_task(goptions, session, args):
else: else:
session.logout() session.logout()
return watch_tasks(session, [task_id], quiet=goptions.quiet, return watch_tasks(session, [task_id], quiet=goptions.quiet,
poll_interval=goptions.poll_interval) poll_interval=goptions.poll_interval)
def handle_tag_build(opts, session, args): def handle_tag_build(opts, session, args):
@ -6399,7 +6399,7 @@ def handle_tag_build(opts, session, args):
else: else:
session.logout() session.logout()
return watch_tasks(session, tasks, quiet=opts.quiet, return watch_tasks(session, tasks, quiet=opts.quiet,
poll_interval=opts.poll_interval) poll_interval=opts.poll_interval)
def handle_move_build(opts, session, args): def handle_move_build(opts, session, args):
@ -6445,7 +6445,7 @@ def handle_move_build(opts, session, args):
else: else:
session.logout() session.logout()
return watch_tasks(session, tasks, quiet=opts.quiet, return watch_tasks(session, tasks, quiet=opts.quiet,
poll_interval=opts.poll_interval) poll_interval=opts.poll_interval)
def handle_untag_build(goptions, session, args): def handle_untag_build(goptions, session, args):
@ -6997,7 +6997,7 @@ def handle_regen_repo(options, session, args):
else: else:
session.logout() session.logout()
return watch_tasks(session, [task_id], quiet=options.quiet, return watch_tasks(session, [task_id], quiet=options.quiet,
poll_interval=options.poll_interval) poll_interval=options.poll_interval)
def handle_dist_repo(options, session, args): def handle_dist_repo(options, session, args):
@ -7011,59 +7011,59 @@ def handle_dist_repo(options, session, args):
usage += _("\n(Specify the --help option for a list of other options)") usage += _("\n(Specify the --help option for a list of other options)")
parser = OptionParser(usage=usage) parser = OptionParser(usage=usage)
parser.add_option('--allow-missing-signatures', action='store_true', parser.add_option('--allow-missing-signatures', action='store_true',
default=False, default=False,
help=_('For RPMs not signed with a desired key, fall back to the ' help=_('For RPMs not signed with a desired key, fall back to the '
'primary copy')) 'primary copy'))
parser.add_option("-a", "--arch", action='append', default=[], parser.add_option("-a", "--arch", action='append', default=[],
help=_("Indicate an architecture to consider. The default is all " + help=_("Indicate an architecture to consider. The default is all " +
"architectures associated with the given tag. This option may " + "architectures associated with the given tag. This option may " +
"be specified multiple times.")) "be specified multiple times."))
parser.add_option("--with-src", action='store_true', help='Also generate a src repo') parser.add_option("--with-src", action='store_true', help='Also generate a src repo')
parser.add_option("--split-debuginfo", action='store_true', default=False, parser.add_option("--split-debuginfo", action='store_true', default=False,
help='Split debuginfo info a separate repo for each arch') help='Split debuginfo info a separate repo for each arch')
parser.add_option('--comps', help='Include a comps file in the repodata') parser.add_option('--comps', help='Include a comps file in the repodata')
parser.add_option('--delta-rpms', metavar='REPO',default=[], parser.add_option('--delta-rpms', metavar='REPO',default=[],
action='append', action='append',
help=_('Create delta rpms. REPO can be the id of another dist repo ' help=_('Create delta rpms. REPO can be the id of another dist repo '
'or the name of a tag that has a dist repo. May be specified ' 'or the name of a tag that has a dist repo. May be specified '
'multiple times.')) 'multiple times.'))
parser.add_option('--event', type='int', parser.add_option('--event', type='int',
help=_('Use tag content at event')) help=_('Use tag content at event'))
parser.add_option("--volume", help=_("Generate repo on given volume")) parser.add_option("--volume", help=_("Generate repo on given volume"))
parser.add_option('--non-latest', dest='latest', default=True, parser.add_option('--non-latest', dest='latest', default=True,
action='store_false', help='Include older builds, not just the latest') action='store_false', help='Include older builds, not just the latest')
parser.add_option('--multilib', default=None, metavar="CONFIG", parser.add_option('--multilib', default=None, metavar="CONFIG",
help=_('Include multilib packages in the repository using the given ' help=_('Include multilib packages in the repository using the given '
'config file')) 'config file'))
parser.add_option("--noinherit", action='store_true', default=False, parser.add_option("--noinherit", action='store_true', default=False,
help=_('Do not consider tag inheritance')) help=_('Do not consider tag inheritance'))
parser.add_option("--nowait", action='store_true', default=False, parser.add_option("--nowait", action='store_true', default=False,
help=_('Do not wait for the task to complete')) help=_('Do not wait for the task to complete'))
parser.add_option('--skip-missing-signatures', action='store_true', default=False, parser.add_option('--skip-missing-signatures', action='store_true', default=False,
help=_('Skip RPMs not signed with the desired key(s)')) help=_('Skip RPMs not signed with the desired key(s)'))
parser.add_option('--zck', action='store_true', default=False, parser.add_option('--zck', action='store_true', default=False,
help=_('Generate zchunk files as well as the standard repodata')) help=_('Generate zchunk files as well as the standard repodata'))
parser.add_option('--zck-dict-dir', action='store', default=None, parser.add_option('--zck-dict-dir', action='store', default=None,
help=_('Directory containing compression dictionaries for use by zchunk (on builder)')) help=_('Directory containing compression dictionaries for use by zchunk (on builder)'))
task_opts, args = parser.parse_args(args) task_opts, args = parser.parse_args(args)
if len(args) < 1: if len(args) < 1:
parser.error(_('You must provide a tag to generate the repo from')) parser.error(_('You must provide a tag to generate the repo from'))
if len(args) < 2 and not task_opts.allow_missing_signatures: if len(args) < 2 and not task_opts.allow_missing_signatures:
parser.error(_('Please specify one or more GPG key IDs (or ' parser.error(_('Please specify one or more GPG key IDs (or '
'--allow-missing-signatures)')) '--allow-missing-signatures)'))
if task_opts.allow_missing_signatures and task_opts.skip_missing_signatures: if task_opts.allow_missing_signatures and task_opts.skip_missing_signatures:
parser.error(_('allow_missing_signatures and skip_missing_signatures ' parser.error(_('allow_missing_signatures and skip_missing_signatures '
'are mutually exclusive')) 'are mutually exclusive'))
activate_session(session, options) activate_session(session, options)
stuffdir = unique_path('cli-dist-repo') stuffdir = unique_path('cli-dist-repo')
if task_opts.comps: if task_opts.comps:
if not os.path.exists(task_opts.comps): if not os.path.exists(task_opts.comps):
parser.error(_('could not find %s') % task_opts.comps) parser.error(_('could not find %s') % task_opts.comps)
session.uploadWrapper(task_opts.comps, stuffdir, session.uploadWrapper(task_opts.comps, stuffdir,
callback=_progress_callback) callback=_progress_callback)
print('') print('')
task_opts.comps = os.path.join(stuffdir, task_opts.comps = os.path.join(stuffdir,
os.path.basename(task_opts.comps)) os.path.basename(task_opts.comps))
old_repos = [] old_repos = []
if len(task_opts.delta_rpms) > 0: if len(task_opts.delta_rpms) > 0:
for repo in task_opts.delta_rpms: for repo in task_opts.delta_rpms:
@ -7075,7 +7075,7 @@ def handle_dist_repo(options, session, args):
if not rinfo: if not rinfo:
# maybe there is an expired one # maybe there is an expired one
rinfo = session.getRepo(repo, rinfo = session.getRepo(repo,
state=koji.REPO_STATES['EXPIRED'], dist=True) state=koji.REPO_STATES['EXPIRED'], dist=True)
if not rinfo: if not rinfo:
parser.error(_("Can't find repo for tag: %s") % repo) parser.error(_("Can't find repo for tag: %s") % repo)
old_repos.append(rinfo['id']) old_repos.append(rinfo['id'])
@ -7103,9 +7103,9 @@ def handle_dist_repo(options, session, args):
if 'ppc64' in task_opts.arch and not 'ppc' in task_opts.arch: if 'ppc64' in task_opts.arch and not 'ppc' in task_opts.arch:
parser.error(_('The multilib arch (ppc) must be included')) parser.error(_('The multilib arch (ppc) must be included'))
session.uploadWrapper(task_opts.multilib, stuffdir, session.uploadWrapper(task_opts.multilib, stuffdir,
callback=_progress_callback) callback=_progress_callback)
task_opts.multilib = os.path.join(stuffdir, task_opts.multilib = os.path.join(stuffdir,
os.path.basename(task_opts.multilib)) os.path.basename(task_opts.multilib))
print('') print('')
if 'noarch' in task_opts.arch: if 'noarch' in task_opts.arch:
task_opts.arch.remove('noarch') task_opts.arch.remove('noarch')
@ -7135,7 +7135,7 @@ def handle_dist_repo(options, session, args):
else: else:
session.logout() session.logout()
return watch_tasks(session, [task_id], quiet=options.quiet, return watch_tasks(session, [task_id], quiet=options.quiet,
poll_interval=options.poll_interval) poll_interval=options.poll_interval)
_search_types = ('package', 'build', 'tag', 'target', 'user', 'host', 'rpm', _search_types = ('package', 'build', 'tag', 'target', 'user', 'host', 'rpm',
@ -7333,13 +7333,13 @@ def handle_edit_notification(goptions, session, args):
usage = _("usage: %prog edit-notification [options] <notification_id>") usage = _("usage: %prog edit-notification [options] <notification_id>")
parser = OptionParser(usage=get_usage_str(usage)) parser = OptionParser(usage=get_usage_str(usage))
parser.add_option("--package", parser.add_option("--package",
help=_("Notifications for this package, '*' for all")) help=_("Notifications for this package, '*' for all"))
parser.add_option("--tag", parser.add_option("--tag",
help=_("Notifications for this tag, '*' for all")) help=_("Notifications for this tag, '*' for all"))
parser.add_option("--success-only", action="store_true", default=None, parser.add_option("--success-only", action="store_true", default=None,
dest='success_only', help=_("Notify only on successful events")) dest='success_only', help=_("Notify only on successful events"))
parser.add_option("--no-success-only", action="store_false", parser.add_option("--no-success-only", action="store_false",
default=None, dest='success_only', help=_("Notify on all events")) default=None, dest='success_only', help=_("Notify on all events"))
(options, args) = parser.parse_args(args) (options, args) = parser.parse_args(args)
if len(args) != 1: if len(args) != 1:

View file

@ -34,22 +34,22 @@ greetings = ('hello', 'hi', 'yo', "what's up", "g'day", 'back to work',
'hallo', 'hallo',
'ciao', 'ciao',
'hola', 'hola',
u'olá', u'olá',
u'dobrý den', u'dobrý den',
u'zdravstvuite', u'zdravstvuite',
u'góðan daginn', u'góðan daginn',
'hej', 'hej',
'tervehdys', 'tervehdys',
u'grüezi', u'grüezi',
u'céad míle fáilte', u'céad míle fáilte',
u'hylô', u'hylô',
u'bună ziua', u'bună ziua',
u'jó napot', u'jó napot',
'dobre dan', 'dobre dan',
u'你好', u'你好',
u'こんにちは', u'こんにちは',
u'नमस्कार', u'नमस्कार',
u'안녕하세요') u'안녕하세요')
ARGMAP = {'None': None, ARGMAP = {'None': None,
'True': True, 'True': True,
@ -276,7 +276,7 @@ def watch_tasks(session, tasklist, quiet=False, poll_interval=60, ki_handler=Non
tlist = ['%s: %s' % (t.str(), t.display_state(t.info)) tlist = ['%s: %s' % (t.str(), t.display_state(t.info))
for t in tasks.values() if not t.is_done()] for t in tasks.values() if not t.is_done()]
print( print(
"""Tasks still running. You can continue to watch with the '%s watch-task' command. """Tasks still running. You can continue to watch with the '%s watch-task' command.
Running Tasks: Running Tasks:
%s""" % (progname, '\n'.join(tlist))) %s""" % (progname, '\n'.join(tlist)))
sys.stdout.flush() sys.stdout.flush()
@ -414,7 +414,7 @@ def unique_path(prefix):
# For some reason repr(time.time()) includes 4 or 5 # For some reason repr(time.time()) includes 4 or 5
# more digits of precision than str(time.time()) # more digits of precision than str(time.time())
return '%s/%r.%s' % (prefix, time.time(), return '%s/%r.%s' % (prefix, time.time(),
''.join([random.choice(string.ascii_letters) for i in range(8)])) ''.join([random.choice(string.ascii_letters) for i in range(8)]))
def _format_size(size): def _format_size(size):

File diff suppressed because it is too large Load diff

View file

@ -292,8 +292,8 @@ class ModXMLRPCRequestHandler(object):
def enforce_lockout(self): def enforce_lockout(self):
if context.opts.get('LockOut') and \ if context.opts.get('LockOut') and \
context.method not in ('login', 'krbLogin', 'sslLogin', 'logout') and \ context.method not in ('login', 'krbLogin', 'sslLogin', 'logout') and \
not context.session.hasPerm('admin'): not context.session.hasPerm('admin'):
raise koji.ServerOffline("Server disabled for maintenance") raise koji.ServerOffline("Server disabled for maintenance")
def _dispatch(self, method, params): def _dispatch(self, method, params):
@ -307,7 +307,7 @@ class ModXMLRPCRequestHandler(object):
if self.logger.isEnabledFor(logging.INFO): if self.logger.isEnabledFor(logging.INFO):
self.logger.info("Handling method %s for session %s (#%s)", self.logger.info("Handling method %s for session %s (#%s)",
method, context.session.id, context.session.callnum) method, context.session.id, context.session.callnum)
if method != 'uploadFile' and self.logger.isEnabledFor(logging.DEBUG): if method != 'uploadFile' and self.logger.isEnabledFor(logging.DEBUG):
self.logger.debug("Params: %s", pprint.pformat(params)) self.logger.debug("Params: %s", pprint.pformat(params))
self.logger.debug("Opts: %s", pprint.pformat(opts)) self.logger.debug("Opts: %s", pprint.pformat(opts))
@ -318,9 +318,9 @@ class ModXMLRPCRequestHandler(object):
if self.logger.isEnabledFor(logging.INFO): if self.logger.isEnabledFor(logging.INFO):
rusage = resource.getrusage(resource.RUSAGE_SELF) rusage = resource.getrusage(resource.RUSAGE_SELF)
self.logger.info("Completed method %s for session %s (#%s): %f seconds, rss %s, stime %f", self.logger.info("Completed method %s for session %s (#%s): %f seconds, rss %s, stime %f",
method, context.session.id, context.session.callnum, method, context.session.id, context.session.callnum,
time.time()-start, time.time()-start,
rusage.ru_maxrss, rusage.ru_stime) rusage.ru_maxrss, rusage.ru_stime)
return ret return ret
@ -682,7 +682,7 @@ def server_setup(environ):
opts = { opts = {
'ServerOffline': True, 'ServerOffline': True,
'OfflineMessage': 'server startup error', 'OfflineMessage': 'server startup error',
} }
# #
@ -762,7 +762,7 @@ def application(environ, start_response):
paramstr = paramstr[:117] + "..." paramstr = paramstr[:117] + "..."
h.logger.warning("Memory usage of process %d grew from %d KiB to %d KiB (+%d KiB) processing request %s with args %s" % (os.getpid(), memory_usage_at_start, memory_usage_at_end, memory_usage_at_end - memory_usage_at_start, context.method, paramstr)) h.logger.warning("Memory usage of process %d grew from %d KiB to %d KiB (+%d KiB) processing request %s with args %s" % (os.getpid(), memory_usage_at_start, memory_usage_at_end, memory_usage_at_end - memory_usage_at_start, context.method, paramstr))
h.logger.debug("Returning %d bytes after %f seconds", len(response), h.logger.debug("Returning %d bytes after %f seconds", len(response),
time.time() - start) time.time() - start)
finally: finally:
# make sure context gets cleaned up # make sure context gets cleaned up
if hasattr(context, 'cnx'): if hasattr(context, 'cnx'):

View file

@ -115,7 +115,7 @@ RPM_FILEDIGESTALGO_IDS = {
9: 'SHA384', 9: 'SHA384',
10: 'SHA512', 10: 'SHA512',
11: 'SHA224' 11: 'SHA224'
} }
# rpm 4.12 introduces optional deps, but they can also be backported in some # rpm 4.12 introduces optional deps, but they can also be backported in some
# rpm installations. So, we need to check their real support, not only rpm # rpm installations. So, we need to check their real support, not only rpm
@ -678,7 +678,7 @@ class RawHeader(object):
elif pos < next: elif pos < next:
print("** OVERLAPPING entries") print("** OVERLAPPING entries")
print("Tag: %d [%s], Type: %d, Offset: %x, Count: %d" \ print("Tag: %d [%s], Type: %d, Offset: %x, Count: %d" \
% (tag, tags.get(tag, '?'), dtype, offset, count)) % (tag, tags.get(tag, '?'), dtype, offset, count))
if dtype == 0: if dtype == 0:
# null # null
print("[NULL entry]") print("[NULL entry]")
@ -942,10 +942,10 @@ def get_header_field(hdr, name, src_arch=False):
return [] return []
if (src_arch and name == "ARCH" if (src_arch and name == "ARCH"
and get_header_field(hdr, "sourcepackage")): and get_header_field(hdr, "sourcepackage")):
# return "src" or "nosrc" arch instead of build arch for src packages # return "src" or "nosrc" arch instead of build arch for src packages
if (get_header_field(hdr, "nosource") if (get_header_field(hdr, "nosource")
or get_header_field(hdr, "nopatch")): or get_header_field(hdr, "nopatch")):
return "nosrc" return "nosrc"
return "src" return "src"
@ -1092,7 +1092,7 @@ def check_NVRA(nvra, strict=False):
def _check_NVRA(nvra): def _check_NVRA(nvra):
if isinstance(nvra, six.string_types): if isinstance(nvra, six.string_types):
nvra = parse_NVRA(nvra) nvra = parse_NVRA(nvra)
if '-' in nvra['version']: if '-' in nvra['version']:
raise GenericError('The "-" character not allowed in version field') raise GenericError('The "-" character not allowed in version field')
if '-' in nvra['release']: if '-' in nvra['release']:
@ -1281,13 +1281,13 @@ def make_groups_spec(grplist, name='buildsys-build', buildgroup=None):
if buildgroup is None: if buildgroup is None:
buildgroup = name buildgroup = name
data = [ data = [
"""# """#
# This specfile represents buildgroups for mock # This specfile represents buildgroups for mock
# Autogenerated by the build system # Autogenerated by the build system
# #
Summary: The base set of packages for a mock chroot\n""", Summary: The base set of packages for a mock chroot\n""",
"""Name: %s\n""" % name, """Name: %s\n""" % name,
"""Version: 1 """Version: 1
Release: 1 Release: 1
License: GPL License: GPL
Group: Development/Build Tools Group: Development/Build Tools
@ -1347,7 +1347,7 @@ def generate_comps(groups, expand_groups=False):
else: else:
return "false" return "false"
data = [ data = [
"""<?xml version="1.0"?> """<?xml version="1.0"?>
<!DOCTYPE comps PUBLIC "-//Red Hat, Inc.//DTD Comps info//EN" "comps.dtd"> <!DOCTYPE comps PUBLIC "-//Red Hat, Inc.//DTD Comps info//EN" "comps.dtd">
<!-- Auto-generated by the build system --> <!-- Auto-generated by the build system -->
@ -1364,7 +1364,7 @@ def generate_comps(groups, expand_groups=False):
default = boolean_text(g['is_default']) default = boolean_text(g['is_default'])
uservisible = boolean_text(g['uservisible']) uservisible = boolean_text(g['uservisible'])
data.append( data.append(
""" <group> """ <group>
<id>%(group_id)s</id> <id>%(group_id)s</id>
<name>%(name)s</name> <name>%(name)s</name>
<description>%(description)s</description> <description>%(description)s</description>
@ -1373,13 +1373,13 @@ def generate_comps(groups, expand_groups=False):
""" % locals()) """ % locals())
if g['biarchonly']: if g['biarchonly']:
data.append( data.append(
""" <biarchonly>%s</biarchonly> """ <biarchonly>%s</biarchonly>
""" % boolean_text(True)) """ % boolean_text(True))
# print grouplist, if any # print grouplist, if any
if g['grouplist'] and not expand_groups: if g['grouplist'] and not expand_groups:
data.append( data.append(
""" <grouplist> """ <grouplist>
""") """)
grouplist = list(g['grouplist']) grouplist = list(g['grouplist'])
grouplist.sort(key=lambda x: x['name']) grouplist.sort(key=lambda x: x['name'])
@ -1392,14 +1392,14 @@ def generate_comps(groups, expand_groups=False):
tag = "metapkg" tag = "metapkg"
if thetype: if thetype:
data.append( data.append(
""" <%(tag)s type="%(thetype)s">%(name)s</%(tag)s> """ <%(tag)s type="%(thetype)s">%(name)s</%(tag)s>
""" % locals()) """ % locals())
else: else:
data.append( data.append(
""" <%(tag)s>%(name)s</%(tag)s> """ <%(tag)s>%(name)s</%(tag)s>
""" % locals()) """ % locals())
data.append( data.append(
""" </grouplist> """ </grouplist>
""") """)
# print packagelist, if any # print packagelist, if any
@ -1414,14 +1414,14 @@ def generate_comps(groups, expand_groups=False):
return "<packagereq %(opts)s>%(name)s</packagereq>" % locals() return "<packagereq %(opts)s>%(name)s</packagereq>" % locals()
data.append( data.append(
""" <packagelist> """ <packagelist>
""") """)
if g['packagelist']: if g['packagelist']:
packagelist = list(g['packagelist']) packagelist = list(g['packagelist'])
packagelist.sort(key=lambda x: x['package']) packagelist.sort(key=lambda x: x['package'])
for p in packagelist: for p in packagelist:
data.append( data.append(
""" %s """ %s
""" % package_entry(p)) """ % package_entry(p))
# also include expanded list, if needed # also include expanded list, if needed
if expand_groups and g['grouplist']: if expand_groups and g['grouplist']:
@ -1438,11 +1438,11 @@ def generate_comps(groups, expand_groups=False):
group = group_idx.get(group_name) group = group_idx.get(group_name)
if group is None: if group is None:
data.append( data.append(
""" <!-- MISSING GROUP: %s --> """ <!-- MISSING GROUP: %s -->
""" % group_name) """ % group_name)
continue continue
data.append( data.append(
""" <!-- Expanding Group: %s --> """ <!-- Expanding Group: %s -->
""" % group_name) """ % group_name)
pkglist = list(group['packagelist']) pkglist = list(group['packagelist'])
pkglist.sort(key=lambda x: x['package']) pkglist.sort(key=lambda x: x['package'])
@ -1451,7 +1451,7 @@ def generate_comps(groups, expand_groups=False):
if pkg_name in seen_pkg: if pkg_name in seen_pkg:
continue continue
data.append( data.append(
""" %s """ %s
""" % package_entry(pkg)) """ % package_entry(pkg))
for req in group['grouplist']: for req in group['grouplist']:
req_name = req['name'] req_name = req['name']
@ -1459,13 +1459,13 @@ def generate_comps(groups, expand_groups=False):
continue continue
need.append(req_name) need.append(req_name)
data.append( data.append(
""" </packagelist> """ </packagelist>
""") """)
data.append( data.append(
""" </group> """ </group>
""") """)
data.append( data.append(
"""</comps> """</comps>
""") """)
return ''.join(data) return ''.join(data)
@ -1836,7 +1836,7 @@ def read_config(profile_name, user_config=None):
cert_defaults = { cert_defaults = {
'cert': '~/.koji/client.crt', 'cert': '~/.koji/client.crt',
'serverca': '~/.koji/serverca.crt', 'serverca': '~/.koji/serverca.crt',
} }
for name in cert_defaults: for name in cert_defaults:
if result.get(name) is None: if result.get(name) is None:
fn = os.path.expanduser(cert_defaults[name]) fn = os.path.expanduser(cert_defaults[name])
@ -2100,7 +2100,7 @@ def is_requests_cert_error(e):
if ('Permission denied' in errstr or # certificate not readable if ('Permission denied' in errstr or # certificate not readable
'certificate revoked' in errstr or 'certificate revoked' in errstr or
'certificate expired' in errstr or 'certificate expired' in errstr or
'certificate verify failed' in errstr): 'certificate verify failed' in errstr):
return True return True
return False return False
@ -2473,8 +2473,8 @@ class ClientSession(object):
if principal: if principal:
if re.match(r'0[.][1-8]\b', requests_kerberos.__version__): if re.match(r'0[.][1-8]\b', requests_kerberos.__version__):
raise PythonImportError( raise PythonImportError(
'python-requests-kerberos >= 0.9.0 required for ' 'python-requests-kerberos >= 0.9.0 required for '
'keytab auth' 'keytab auth'
) )
else: else:
kwargs['principal'] = principal kwargs['principal'] = principal
@ -2869,7 +2869,7 @@ class ClientSession(object):
raise GenericError("server returned wrong chunk size: %s != %s" % (result['size'], len(chunk))) raise GenericError("server returned wrong chunk size: %s != %s" % (result['size'], len(chunk)))
if result['hexdigest'] != hexdigest: if result['hexdigest'] != hexdigest:
raise GenericError('upload checksum failed: %s != %s' \ raise GenericError('upload checksum failed: %s != %s' \
% (result['hexdigest'], hexdigest)) % (result['hexdigest'], hexdigest))
ofs += len(chunk) ofs += len(chunk)
now = time.time() now = time.time()
t1 = max(now - lap, 0.00001) t1 = max(now - lap, 0.00001)
@ -2889,10 +2889,10 @@ class ClientSession(object):
raise GenericError("File upload failed: %s/%s" % (path, name)) raise GenericError("File upload failed: %s/%s" % (path, name))
if int(result['size']) != ofs: if int(result['size']) != ofs:
raise GenericError("Uploaded file is wrong length: %s/%s, %s != %s" \ raise GenericError("Uploaded file is wrong length: %s/%s, %s != %s" \
% (path, name, result['size'], ofs)) % (path, name, result['size'], ofs))
if problems and result['hexdigest'] != full_chksum.hexdigest(): if problems and result['hexdigest'] != full_chksum.hexdigest():
raise GenericError("Uploaded file has wrong checksum: %s/%s, %s != %s" \ raise GenericError("Uploaded file has wrong checksum: %s/%s, %s != %s" \
% (path, name, result['hexdigest'], full_chksum.hexdigest())) % (path, name, result['hexdigest'], full_chksum.hexdigest()))
self.logger.debug("Fast upload: %s complete. %i bytes in %.1f seconds", localfile, size, t2) self.logger.debug("Fast upload: %s complete. %i bytes in %.1f seconds", localfile, size, t2)
def _prepUpload(self, chunk, offset, path, name, verify="adler32", overwrite=False, volume=None): def _prepUpload(self, chunk, offset, path, name, verify="adler32", overwrite=False, volume=None):
@ -3125,8 +3125,8 @@ class MultiCallSession(object):
self._calls = [] self._calls = []
if batch: if batch:
self._session.logger.debug( self._session.logger.debug(
"MultiCall with batch size %i, calls/groups(%i/%i)", "MultiCall with batch size %i, calls/groups(%i/%i)",
batch, len(calls), round(len(calls) // batch)) batch, len(calls), round(len(calls) // batch))
batches = [calls[i:i+batch] for i in range(0, len(calls), batch)] batches = [calls[i:i+batch] for i in range(0, len(calls), batch)]
else: else:
batches = [calls] batches = [calls]
@ -3390,7 +3390,7 @@ def _taskLabel(taskInfo):
else: else:
kickstart = os.path.basename(stuff[7]) kickstart = os.path.basename(stuff[7])
extra = '%s, %s-%s-%s, %s, %s' % (stuff[4]['name'], stuff[0], extra = '%s, %s-%s-%s, %s, %s' % (stuff[4]['name'], stuff[0],
stuff[1], stuff[2], kickstart, stuff[3]) stuff[1], stuff[2], kickstart, stuff[3])
elif method == 'restart': elif method == 'restart':
if 'request' in taskInfo: if 'request' in taskInfo:
host = taskInfo['request'][0] host = taskInfo['request'][0]

View file

@ -88,14 +88,14 @@ arches = {
# itanium # itanium
"ia64": "noarch", "ia64": "noarch",
} }
# Will contain information parsed from /proc/self/auxv via _parse_auxv(). # Will contain information parsed from /proc/self/auxv via _parse_auxv().
# Should move into rpm really. # Should move into rpm really.
_aux_vector = { _aux_vector = {
"platform": "", "platform": "",
"hwcap": 0, "hwcap": 0,
} }
def legitMultiArchesInSameLib(arch=None): def legitMultiArchesInSameLib(arch=None):
# this is completely crackrock - if anyone has a better way I # this is completely crackrock - if anyone has a better way I

View file

@ -110,7 +110,7 @@ class Session(object):
'EXTRACT(EPOCH FROM start_time)': 'start_ts', 'EXTRACT(EPOCH FROM start_time)': 'start_ts',
'EXTRACT(EPOCH FROM update_time)': 'update_ts', 'EXTRACT(EPOCH FROM update_time)': 'update_ts',
'user_id': 'user_id', 'user_id': 'user_id',
} }
# sort for stability (unittests) # sort for stability (unittests)
fields, aliases = zip(*sorted(fields.items(), key=lambda x: x[1])) fields, aliases = zip(*sorted(fields.items(), key=lambda x: x[1]))
q = """ q = """
@ -138,7 +138,7 @@ class Session(object):
if lastcall is not None: if lastcall is not None:
if lastcall > callnum: if lastcall > callnum:
raise koji.SequenceError("%d > %d (session %d)" \ raise koji.SequenceError("%d > %d (session %d)" \
% (lastcall, callnum, id)) % (lastcall, callnum, id))
elif lastcall == callnum: elif lastcall == callnum:
# Some explanation: # Some explanation:
# This function is one of the few that performs its own commit. # This function is one of the few that performs its own commit.
@ -339,7 +339,7 @@ class Session(object):
login_principal = proxyuser login_principal = proxyuser
else: else:
raise koji.AuthError( raise koji.AuthError(
'Kerberos principal %s is not authorized to log in other users' % cprinc.name) 'Kerberos principal %s is not authorized to log in other users' % cprinc.name)
else: else:
login_principal = cprinc.name login_principal = cprinc.name
@ -538,7 +538,7 @@ class Session(object):
# generate a random key # generate a random key
alnum = string.ascii_letters + string.digits alnum = string.ascii_letters + string.digits
key = "%s-%s" %(user_id, key = "%s-%s" %(user_id,
''.join([random.choice(alnum) for x in range(1, 20)])) ''.join([random.choice(alnum) for x in range(1, 20)]))
# use sha? sha.new(phrase).hexdigest() # use sha? sha.new(phrase).hexdigest()
# get a session id # get a session id
@ -566,7 +566,7 @@ class Session(object):
if master is None: if master is None:
master = self.id master = self.id
return self.createSession(self.user_id, self.hostip, self.authtype, return self.createSession(self.user_id, self.hostip, self.authtype,
master=master) master=master)
def getPerms(self): def getPerms(self):
if not self.logged_in: if not self.logged_in:

View file

@ -200,7 +200,7 @@ class SCM(object):
# otherwise not valid # otherwise not valid
if strict: if strict:
raise koji.GenericError('Invalid scheme in scm url. Valid schemes ' raise koji.GenericError('Invalid scheme in scm url. Valid schemes '
'are: %s' % ' '.join(sorted(schemes))) 'are: %s' % ' '.join(sorted(schemes)))
else: else:
return False return False
@ -410,7 +410,7 @@ class SCM(object):
if log_output(session, cmd[0], cmd, logfile, uploadpath, if log_output(session, cmd[0], cmd, logfile, uploadpath,
cwd=chdir, logerror=1, append=append, env=env): cwd=chdir, logerror=1, append=append, env=env):
raise koji.BuildError('Error running %s command "%s", see %s for details' % \ raise koji.BuildError('Error running %s command "%s", see %s for details' % \
(self.scmtype, ' '.join(cmd), os.path.basename(logfile))) (self.scmtype, ' '.join(cmd), os.path.basename(logfile)))
if self.scmtype == 'CVS': if self.scmtype == 'CVS':
pserver = ':pserver:%s@%s:%s' % ((self.user or 'anonymous'), self.host, self.repository) pserver = ':pserver:%s@%s:%s' % ((self.user or 'anonymous'), self.host, self.repository)
@ -945,7 +945,7 @@ class TaskManager(object):
# return True if we should delay # return True if we should delay
if now - ts < delay: if now - ts < delay:
self.logger.debug("skipping task %i, age=%s rank=%s" self.logger.debug("skipping task %i, age=%s rank=%s"
% (task['id'], int(now - ts), rank)) % (task['id'], int(now - ts), rank))
return True return True
# otherwise # otherwise
del self.skipped_tasks[task['id']] del self.skipped_tasks[task['id']]

View file

@ -56,7 +56,7 @@ callbacks = {
'postCommit': [], 'postCommit': [],
'preSCMCheckout': [], 'preSCMCheckout': [],
'postSCMCheckout': [], 'postSCMCheckout': [],
} }
class PluginTracker(object): class PluginTracker(object):

View file

@ -171,7 +171,7 @@ class CompareTest(BaseSimpleTest):
'>=': lambda a, b: a >= b, '>=': lambda a, b: a >= b,
'=': lambda a, b: a == b, '=': lambda a, b: a == b,
'!=': lambda a, b: a != b, '!=': lambda a, b: a != b,
} }
def __init__(self, str): def __init__(self, str):
"""Read the test parameters from string""" """Read the test parameters from string"""

View file

@ -116,7 +116,7 @@ def parse_task_params(method, params):
# check for new style # check for new style
if (len(params) == 1 and isinstance(params[0], dict) if (len(params) == 1 and isinstance(params[0], dict)
and '__method__' in params[0]): and '__method__' in params[0]):
ret = params[0].copy() ret = params[0].copy()
del ret['__method__'] del ret['__method__']
return ret return ret
@ -343,7 +343,7 @@ class BaseTaskHandler(object):
# os.spawnvp(os.P_WAIT, 'rm', ['rm', '-rf', self.workdir]) # os.spawnvp(os.P_WAIT, 'rm', ['rm', '-rf', self.workdir])
def wait(self, subtasks=None, all=False, failany=False, canfail=None, def wait(self, subtasks=None, all=False, failany=False, canfail=None,
timeout=None): timeout=None):
"""Wait on subtasks """Wait on subtasks
subtasks is a list of integers (or an integer). If more than one subtask subtasks is a list of integers (or an integer). If more than one subtask
@ -417,7 +417,7 @@ class BaseTaskHandler(object):
self.logger.info('Subtasks timed out') self.logger.info('Subtasks timed out')
self.session.cancelTaskChildren(self.id) self.session.cancelTaskChildren(self.id)
raise koji.GenericError('Subtasks timed out after %.1f ' raise koji.GenericError('Subtasks timed out after %.1f '
'seconds' % duration) 'seconds' % duration)
else: else:
# signal handler set by TaskManager.forkTask # signal handler set by TaskManager.forkTask
self.logger.debug("Pausing...") self.logger.debug("Pausing...")
@ -429,7 +429,7 @@ class BaseTaskHandler(object):
if all: if all:
finished = subtasks finished = subtasks
return dict(self.session.host.taskWaitResults(self.id, finished, return dict(self.session.host.taskWaitResults(self.id, finished,
canfail=canfail)) canfail=canfail))
def getUploadDir(self): def getUploadDir(self):

View file

@ -65,8 +65,8 @@ def formatChangelog(entries):
%s %s
""" % (_changelogDate(entry['date']), """ % (_changelogDate(entry['date']),
koji._fix_print(entry['author']), koji._fix_print(entry['author']),
koji._fix_print(entry['text'])) koji._fix_print(entry['text']))
return result return result
DATE_RE = re.compile(r'(\d+)-(\d+)-(\d+)') DATE_RE = re.compile(r'(\d+)-(\d+)-(\d+)')
@ -92,7 +92,7 @@ def parseTime(val):
if result: if result:
time = [int(r) for r in result.groups()] time = [int(r) for r in result.groups()]
return calendar.timegm( return calendar.timegm(
datetime.datetime(*(date + time)).timetuple()) datetime.datetime(*(date + time)).timetuple())
def checkForBuilds(session, tag, builds, event, latest=False): def checkForBuilds(session, tag, builds, event, latest=False):
@ -291,7 +291,7 @@ def apply_argspec(argspec, args, kwargs=None):
for n, arg in enumerate(f_args): for n, arg in enumerate(f_args):
if arg not in data: if arg not in data:
raise koji.ParameterError('missing required argument %r (#%i)' raise koji.ParameterError('missing required argument %r (#%i)'
% (arg, n)) % (arg, n))
return data return data
@ -696,7 +696,7 @@ class MavenConfigOptAdapter(object):
""" """
MULTILINE = ['properties', 'envs'] MULTILINE = ['properties', 'envs']
MULTIVALUE = ['goals', 'profiles', 'packages', MULTIVALUE = ['goals', 'profiles', 'packages',
'jvm_options', 'maven_options', 'buildrequires'] 'jvm_options', 'maven_options', 'buildrequires']
def __init__(self, conf, section): def __init__(self, conf, section):
self._conf = conf self._conf = conf

View file

@ -100,7 +100,7 @@ def dumps(params, methodname=None, methodresponse=None, encoding=None,
"<methodName>", methodname, "</methodName>\n", "<methodName>", methodname, "</methodName>\n",
data, data,
"</methodCall>\n" "</methodCall>\n"
) )
elif methodresponse: elif methodresponse:
# a method response, or a fault structure # a method response, or a fault structure
parts = ( parts = (
@ -108,7 +108,7 @@ def dumps(params, methodname=None, methodresponse=None, encoding=None,
"<methodResponse>\n", "<methodResponse>\n",
data, data,
"</methodResponse>\n" "</methodResponse>\n"
) )
else: else:
return data # return as is return data # return as is
return ''.join(parts) return ''.join(parts)

View file

@ -53,11 +53,11 @@ class RunRootTask(koji.tasks.BaseTaskHandler):
def _read_config(self): def _read_config(self):
cp = koji.read_config_files(CONFIG_FILE) cp = koji.read_config_files(CONFIG_FILE)
self.config = { self.config = {
'default_mounts': [], 'default_mounts': [],
'safe_roots': [], 'safe_roots': [],
'path_subs': [], 'path_subs': [],
'paths': [], 'paths': [],
'internal_dev_setup': None, 'internal_dev_setup': None,
} }
# main options # main options
@ -155,12 +155,12 @@ class RunRootTask(koji.tasks.BaseTaskHandler):
if not repo_info: if not repo_info:
# wait for it # wait for it
task_id = self.session.host.subtask(method='waitrepo', task_id = self.session.host.subtask(method='waitrepo',
arglist=[root, None, None], arglist=[root, None, None],
parent=self.id) parent=self.id)
repo_info = self.wait(task_id)[task_id] repo_info = self.wait(task_id)[task_id]
broot = BuildRoot(self.session, self.options, root, br_arch, self.id, broot = BuildRoot(self.session, self.options, root, br_arch, self.id,
repo_id=repo_info['id'], setup_dns=True, repo_id=repo_info['id'], setup_dns=True,
internal_dev_setup=self.config['internal_dev_setup']) internal_dev_setup=self.config['internal_dev_setup'])
broot.workdir = self.workdir broot.workdir = self.workdir
broot.init() broot.init()
rootdir = broot.rootdir() rootdir = broot.rootdir()
@ -282,7 +282,7 @@ class RunRootTask(koji.tasks.BaseTaskHandler):
status = log_output(self.session, cmd[0], cmd, logfile, uploadpath, logerror=True, append=True) status = log_output(self.session, cmd[0], cmd, logfile, uploadpath, logerror=True, append=True)
if not isSuccess(status): if not isSuccess(status):
error = koji.GenericError("Unable to mount %s: %s" \ error = koji.GenericError("Unable to mount %s: %s" \
% (mpoint, parseStatus(status, cmd))) % (mpoint, parseStatus(status, cmd)))
break break
fslog.write("%s\n" % mpoint) fslog.write("%s\n" % mpoint)
fslog.flush() fslog.flush()

View file

@ -25,20 +25,20 @@ def handle_runroot(options, session, args):
parser.add_option("-p", "--package", action="append", default=[], help=_("make sure this package is in the chroot")) parser.add_option("-p", "--package", action="append", default=[], help=_("make sure this package is in the chroot"))
parser.add_option("-m", "--mount", action="append", default=[], help=_("mount this directory read-write in the chroot")) parser.add_option("-m", "--mount", action="append", default=[], help=_("mount this directory read-write in the chroot"))
parser.add_option("--skip-setarch", action="store_true", default=False, parser.add_option("--skip-setarch", action="store_true", default=False,
help=_("bypass normal setarch in the chroot")) help=_("bypass normal setarch in the chroot"))
parser.add_option("-w", "--weight", type='int', help=_("set task weight")) parser.add_option("-w", "--weight", type='int', help=_("set task weight"))
parser.add_option("--channel-override", help=_("use a non-standard channel")) parser.add_option("--channel-override", help=_("use a non-standard channel"))
parser.add_option("--task-id", action="store_true", default=False, parser.add_option("--task-id", action="store_true", default=False,
help=_("Print the ID of the runroot task")) help=_("Print the ID of the runroot task"))
parser.add_option("--use-shell", action="store_true", default=False, parser.add_option("--use-shell", action="store_true", default=False,
help=_("Run command through a shell, otherwise uses exec")) help=_("Run command through a shell, otherwise uses exec"))
parser.add_option("--new-chroot", action="store_true", default=None, parser.add_option("--new-chroot", action="store_true", default=None,
help=_("Run command with the --new-chroot (systemd-nspawn) option to mock")) help=_("Run command with the --new-chroot (systemd-nspawn) option to mock"))
parser.add_option("--old-chroot", action="store_false", default=None, dest='new_chroot', parser.add_option("--old-chroot", action="store_false", default=None, dest='new_chroot',
help=_("Run command with the --old-chroot (systemd-nspawn) option to mock")) help=_("Run command with the --old-chroot (systemd-nspawn) option to mock"))
parser.add_option("--repo-id", type="int", help=_("ID of the repo to use")) parser.add_option("--repo-id", type="int", help=_("ID of the repo to use"))
parser.add_option("--nowait", action="store_false", dest="wait", parser.add_option("--nowait", action="store_false", dest="wait",
default=True, help=_("Do not wait on task")) default=True, help=_("Do not wait on task"))
parser.add_option("--watch", action="store_true", help=_("Watch task instead of printing runroot.log")) parser.add_option("--watch", action="store_true", help=_("Watch task instead of printing runroot.log"))
parser.add_option("--quiet", action="store_true", default=options.quiet, parser.add_option("--quiet", action="store_true", default=options.quiet,
help=_("Do not print the task information")) help=_("Do not print the task information"))

View file

@ -14,13 +14,13 @@ def handle_save_failed_tree(options, session, args):
usage += _("\n(Specify the --help global option for a list of other help options)") usage += _("\n(Specify the --help global option for a list of other help options)")
parser = OptionParser(usage=usage) parser = OptionParser(usage=usage)
parser.add_option("-f", "--full", action="store_true", default=False, parser.add_option("-f", "--full", action="store_true", default=False,
help=_("Download whole tree, if not specified, only builddir will be downloaded")) help=_("Download whole tree, if not specified, only builddir will be downloaded"))
parser.add_option("-t", "--task", action="store_const", dest="mode", parser.add_option("-t", "--task", action="store_const", dest="mode",
const="task", default="task", const="task", default="task",
help=_("Treat ID as a task ID (the default)")) help=_("Treat ID as a task ID (the default)"))
parser.add_option("-r", "--buildroot", action="store_const", dest="mode", parser.add_option("-r", "--buildroot", action="store_const", dest="mode",
const="buildroot", const="buildroot",
help=_("Treat ID as a buildroot ID")) help=_("Treat ID as a buildroot ID"))
parser.add_option("--quiet", action="store_true", default=options.quiet, parser.add_option("--quiet", action="store_true", default=options.quiet,
help=_("Do not print the task information")) help=_("Do not print the task information"))
parser.add_option("--nowait", action="store_true", parser.add_option("--nowait", action="store_true",
@ -63,7 +63,7 @@ def handle_save_failed_tree(options, session, args):
if not opts.quiet: if not opts.quiet:
print(_("Created task %s for buildroot %s") % (task_id, br_id)) print(_("Created task %s for buildroot %s") % (task_id, br_id))
print("Task info: %s/taskinfo?taskID=%s" print("Task info: %s/taskinfo?taskID=%s"
% (options.weburl, task_id)) % (options.weburl, task_id))
if opts.nowait: if opts.nowait:
return return

View file

@ -66,8 +66,8 @@ def expand_rpm(filepath, tmpdir):
close_fds=True) close_fds=True)
if rpm2cpio.wait() != 0 or cpio.wait() != 0: if rpm2cpio.wait() != 0 or cpio.wait() != 0:
raise koji.CallbackError('error extracting files from %s, ' \ raise koji.CallbackError('error extracting files from %s, ' \
'rpm2cpio returned %s, cpio returned %s' % \ 'rpm2cpio returned %s, cpio returned %s' % \
(filepath, rpm2cpio.wait(), cpio.wait())) (filepath, rpm2cpio.wait(), cpio.wait()))
devnull.close() devnull.close()

View file

@ -56,7 +56,7 @@ def runroot(tagInfo, arch, command, channel=None, **opts):
choices = [x for x in tagarches if x in chanarches] choices = [x for x in tagarches if x in chanarches]
if not choices: if not choices:
raise koji.GenericError('no common arches for tag/channel: %s/%s' \ raise koji.GenericError('no common arches for tag/channel: %s/%s' \
% (tagInfo, taskopts['channel'])) % (tagInfo, taskopts['channel']))
taskopts['arch'] = koji.canonArch(random.choice(choices)) taskopts['arch'] = koji.canonArch(random.choice(choices))
args = koji.encode_args(tagInfo, arch, command, **opts) args = koji.encode_args(tagInfo, arch, command, **opts)

View file

@ -43,7 +43,7 @@ def saveFailedTree(buildrootID, full=False, **opts):
raise koji.PreBuildError("Task %s has not failed. Only failed tasks can upload their buildroots." % taskID) raise koji.PreBuildError("Task %s has not failed. Only failed tasks can upload their buildroots." % taskID)
elif allowed_methods != '*' and task_info['method'] not in allowed_methods: elif allowed_methods != '*' and task_info['method'] not in allowed_methods:
raise koji.PreBuildError("Only %s tasks can upload their buildroots (Task %s is %s)." % \ raise koji.PreBuildError("Only %s tasks can upload their buildroots (Task %s is %s)." % \
(', '.join(allowed_methods), task_info['id'], task_info['method'])) (', '.join(allowed_methods), task_info['id'], task_info['method']))
elif task_info["owner"] != context.session.user_id and not context.session.hasPerm('admin'): elif task_info["owner"] != context.session.user_id and not context.session.hasPerm('admin'):
raise koji.ActionNotAllowed("Only owner of failed task or 'admin' can run this task.") raise koji.ActionNotAllowed("Only owner of failed task or 'admin' can run this task.")
elif not kojihub.get_host(task_info['host_id'])['enabled']: elif not kojihub.get_host(task_info['host_id'])['enabled']:

View file

@ -139,7 +139,7 @@ def get_options():
['krbservice', None, 'string'], ['krbservice', None, 'string'],
['krb_rdns', None, 'boolean'], ['krb_rdns', None, 'boolean'],
['krb_canon_host', None, 'boolean'], ['krb_canon_host', None, 'boolean'],
['krb_server_realm', None, 'string'], ['krb_server_realm', None, 'string'],
['runas', None, 'string'], ['runas', None, 'string'],
['user', None, 'string'], ['user', None, 'string'],
['password', None, 'string'], ['password', None, 'string'],
@ -150,8 +150,8 @@ def get_options():
['server', None, 'string'], ['server', None, 'string'],
['weburl', None, 'string'], ['weburl', None, 'string'],
['smtp_host', None, 'string'], ['smtp_host', None, 'string'],
['smtp_user', None, 'string'], ['smtp_user', None, 'string'],
['smtp_pass', None, 'string'], ['smtp_pass', None, 'string'],
['from_addr', None, 'string'], ['from_addr', None, 'string'],
['email_template', None, 'string'], ['email_template', None, 'string'],
['email_domain', None, 'string'], ['email_domain', None, 'string'],
@ -162,9 +162,9 @@ def get_options():
['trashcan_tag', None, 'string'], ['trashcan_tag', None, 'string'],
['no_ssl_verify', None, 'boolean'], ['no_ssl_verify', None, 'boolean'],
['timeout', None, 'integer'], ['timeout', None, 'integer'],
['lock_file', None, 'string'], ['lock_file', None, 'string'],
['exit_on_lock', None, 'boolean'], ['exit_on_lock', None, 'boolean'],
] ]
for name, alias, type in cfgmap: for name, alias, type in cfgmap:
if alias is None: if alias is None:
alias = ('main', name) alias = ('main', name)
@ -903,7 +903,7 @@ def handle_prune():
'order': order - skipped, 'order': order - skipped,
'ts' : entry['create_ts'], 'ts' : entry['create_ts'],
'nvr' : nvr, 'nvr' : nvr,
} }
data = LazyDict(data) data = LazyDict(data)
data['keys'] = LazyValue(get_build_sigs, (entry['build_id'],), {'cache':True}) data['keys'] = LazyValue(get_build_sigs, (entry['build_id'],), {'cache':True})
data['volname'] = LazyValue(lambda x: session.getBuild(x).get('volume_name'), data['volname'] = LazyValue(lambda x: session.getBuild(x).get('volume_name'),

View file

@ -82,7 +82,7 @@ def get_options():
parser.add_option("--krbservice", help=_("the service name of the" parser.add_option("--krbservice", help=_("the service name of the"
" principal being used by the hub")) " principal being used by the hub"))
parser.add_option("--runas", metavar="USER", parser.add_option("--runas", metavar="USER",
help=_("run as the specified user (requires special privileges)")) help=_("run as the specified user (requires special privileges)"))
parser.add_option("--user", help=_("specify user")) parser.add_option("--user", help=_("specify user"))
parser.add_option("--password", help=_("specify password")) parser.add_option("--password", help=_("specify password"))
parser.add_option("--krb-rdns", action="store_true", default=False, parser.add_option("--krb-rdns", action="store_true", default=False,
@ -316,7 +316,7 @@ def _unique_path(prefix):
# For some reason repr(time.time()) includes 4 or 5 # For some reason repr(time.time()) includes 4 or 5
# more digits of precision than str(time.time()) # more digits of precision than str(time.time())
return '%s/%r.%s' % (prefix, time.time(), return '%s/%r.%s' % (prefix, time.time(),
''.join([random.choice(string.ascii_letters) for i in range(8)])) ''.join([random.choice(string.ascii_letters) for i in range(8)]))
class LocalBuild(object): class LocalBuild(object):
@ -547,7 +547,7 @@ class BuildTracker(object):
self.state_idx = {} self.state_idx = {}
self.nvr_idx = {} self.nvr_idx = {}
for state in ('common', 'pending', 'missing', 'broken', 'brokendeps', for state in ('common', 'pending', 'missing', 'broken', 'brokendeps',
'noroot', 'blocked', 'grey'): 'noroot', 'blocked', 'grey'):
self.state_idx.setdefault(state, {}) self.state_idx.setdefault(state, {})
self.scanRules() self.scanRules()
@ -1164,7 +1164,7 @@ class BuildTracker(object):
ret = True ret = True
if build.state != 'common': if build.state != 'common':
log ("Task %i finished, but %s still missing" \ log ("Task %i finished, but %s still missing" \
% (build.task_id, build.nvr)) % (build.task_id, build.nvr))
return ret return ret
def checkBuildDeps(self, build): def checkBuildDeps(self, build):
@ -1173,14 +1173,14 @@ class BuildTracker(object):
# log("No revised deplist yet for %s" % build.nvr) # log("No revised deplist yet for %s" % build.nvr)
return False return False
problem = [x for x in build.revised_deps problem = [x for x in build.revised_deps
if x.state in ('broken', 'brokendeps', 'noroot', 'blocked')] if x.state in ('broken', 'brokendeps', 'noroot', 'blocked')]
if problem: if problem:
log ("Can't rebuild %s, missing %i deps" % (build.nvr, len(problem))) log ("Can't rebuild %s, missing %i deps" % (build.nvr, len(problem)))
build.setState('brokendeps') build.setState('brokendeps')
self._print_builds(problem) self._print_builds(problem)
return False return False
not_common = [x for x in build.revised_deps not_common = [x for x in build.revised_deps
if x.state not in ('common', 'local')] if x.state not in ('common', 'local')]
if not_common: if not_common:
# could be missing or still building or whatever # could be missing or still building or whatever
# log("Still missing %i revised deps for %s" % (len(not_common), build.nvr)) # log("Still missing %i revised deps for %s" % (len(not_common), build.nvr))

View file

@ -348,11 +348,11 @@ class RepoManager(object):
# we're already tracking it # we're already tracking it
if repo.state != data['state']: if repo.state != data['state']:
self.logger.info('State changed for repo %s: %s -> %s' self.logger.info('State changed for repo %s: %s -> %s'
%(repo_id, koji.REPO_STATES[repo.state], koji.REPO_STATES[data['state']])) %(repo_id, koji.REPO_STATES[repo.state], koji.REPO_STATES[data['state']]))
repo.state = data['state'] repo.state = data['state']
else: else:
self.logger.info('Found repo %s, state=%s' self.logger.info('Found repo %s, state=%s'
%(repo_id, koji.REPO_STATES[data['state']])) %(repo_id, koji.REPO_STATES[data['state']]))
repo = ManagedRepo(self, data) repo = ManagedRepo(self, data)
self.repos[repo_id] = repo self.repos[repo_id] = repo
if not getTag(self.session, repo.tag_id) and not repo.expired(): if not getTag(self.session, repo.tag_id) and not repo.expired():
@ -488,7 +488,7 @@ class RepoManager(object):
if not self.options.ignore_stray_repos: if not self.options.ignore_stray_repos:
age = time.time() - dir_ts age = time.time() - dir_ts
self.logger.debug("did not expect %s; age: %s", self.logger.debug("did not expect %s; age: %s",
repodir, age) repodir, age)
if age > max_age: if age > max_age:
self.logger.info("Removing unexpected directory (no such repo): %s", repodir) self.logger.info("Removing unexpected directory (no such repo): %s", repodir)
if symlink: if symlink:
@ -545,7 +545,7 @@ class RepoManager(object):
stats = self.tagUseStats(entry['taginfo']['id']) stats = self.tagUseStats(entry['taginfo']['id'])
# normalize use count # normalize use count
max_n = max([t.get('n_recent', 0) for t in self.needed_tags.values()] max_n = max([t.get('n_recent', 0) for t in self.needed_tags.values()]
or [1]) or [1])
if max_n == 0: if max_n == 0:
# no recent use or missing data # no recent use or missing data
max_n = 1 max_n = 1
@ -559,7 +559,7 @@ class RepoManager(object):
age = 0 age = 0
entry['score'] = age * adj entry['score'] = age * adj
self.logger.debug("Needed tag %s got score %.2f", self.logger.debug("Needed tag %s got score %.2f",
entry['taginfo']['name'], entry['score']) entry['taginfo']['name'], entry['score'])
# so a day old unused repo gets about the regen same score as a # so a day old unused repo gets about the regen same score as a
# 2.4-hour-old, very popular repo # 2.4-hour-old, very popular repo
@ -572,7 +572,7 @@ class RepoManager(object):
self.logger.debug("Current tasks: %r" % self.tasks) self.logger.debug("Current tasks: %r" % self.tasks)
if self.other_tasks: if self.other_tasks:
self.logger.debug("Found %i untracked newRepo tasks", self.logger.debug("Found %i untracked newRepo tasks",
len(self.other_tasks)) len(self.other_tasks))
self.logger.debug("Updating repos") self.logger.debug("Updating repos")
self.readCurrentRepos() self.readCurrentRepos()
@ -634,7 +634,7 @@ class RepoManager(object):
# also check other newRepo tasks # also check other newRepo tasks
repo_tasks = self.session.listTasks(opts={'method':'newRepo', repo_tasks = self.session.listTasks(opts={'method':'newRepo',
'state':([koji.TASK_STATES[s] for s in ('FREE', 'OPEN')])}) 'state':([koji.TASK_STATES[s] for s in ('FREE', 'OPEN')])})
others = [t for t in repo_tasks if t['id'] not in self.tasks] others = [t for t in repo_tasks if t['id'] not in self.tasks]
for tinfo in others: for tinfo in others:
if tinfo['id'] not in self.other_tasks: if tinfo['id'] not in self.other_tasks:
@ -651,7 +651,7 @@ class RepoManager(object):
self.build_tags = set([ self.build_tags = set([
t['build_tag'] for t in self.session.getBuildTargets() t['build_tag'] for t in self.session.getBuildTargets()
if not koji.util.multi_fnmatch(t['build_tag_name'], ignore) if not koji.util.multi_fnmatch(t['build_tag_name'], ignore)
]) ])
# index repos by tag # index repos by tag
tag_repos = {} tag_repos = {}
for repo in to_list(self.repos.values()): for repo in to_list(self.repos.values()):
@ -672,7 +672,7 @@ class RepoManager(object):
if covered: if covered:
# no longer needed # no longer needed
self.logger.info("Tag %(name)s has a current or in " self.logger.info("Tag %(name)s has a current or in "
"progress repo", entry['taginfo']) "progress repo", entry['taginfo'])
del self.needed_tags[tag_id] del self.needed_tags[tag_id]
# if not covered, we already know # if not covered, we already know
continue continue
@ -699,10 +699,10 @@ class RepoManager(object):
ts = time.time() ts = time.time()
entry = { entry = {
'taginfo': taginfo, 'taginfo': taginfo,
'expire_ts': ts, 'expire_ts': ts,
'needed_since' : time.time(), 'needed_since' : time.time(),
} }
self.setTagScore(entry) self.setTagScore(entry)
self.needed_tags[tag_id] = entry self.needed_tags[tag_id] = entry
@ -711,7 +711,7 @@ class RepoManager(object):
entry = self.needed_tags.get(tag_id) entry = self.needed_tags.get(tag_id)
if tag_id not in self.build_tags: if tag_id not in self.build_tags:
self.logger.info("Tag %(name)s is no longer a build tag", self.logger.info("Tag %(name)s is no longer a build tag",
entry['taginfo']) entry['taginfo'])
del self.needed_tags[tag_id] del self.needed_tags[tag_id]
for tag_id, repolist in tag_repos.items(): for tag_id, repolist in tag_repos.items():
if tag_id not in self.build_tags: if tag_id not in self.build_tags:
@ -750,7 +750,7 @@ class RepoManager(object):
self.logger.info("Maximum number of repo tasks reached") self.logger.info("Maximum number of repo tasks reached")
return return
elif (len(self.tasks) + len(self.other_tasks) elif (len(self.tasks) + len(self.other_tasks)
>= self.options.repo_tasks_limit): >= self.options.repo_tasks_limit):
self.logger.info("Repo task limit reached") self.logger.info("Repo task limit reached")
return return
tagname = tag['taginfo']['name'] tagname = tag['taginfo']['name']
@ -765,7 +765,7 @@ class RepoManager(object):
else: else:
# should not happen # should not happen
logger.warning('Needed tag refers to unknown task. ' logger.warning('Needed tag refers to unknown task. '
'%s -> %i', tagname, task_id) '%s -> %i', tagname, task_id)
# we'll advance and create a new task # we'll advance and create a new task
taskopts = {} taskopts = {}
if koji.util.multi_fnmatch(tagname, debuginfo_pat): if koji.util.multi_fnmatch(tagname, debuginfo_pat):
@ -788,14 +788,14 @@ class RepoManager(object):
else: else:
time_expired = "%.1f" % (time.time() - expire_ts) time_expired = "%.1f" % (time.time() - expire_ts)
self.logger.info("Created newRepo task %s for tag %s (%s), " self.logger.info("Created newRepo task %s for tag %s (%s), "
"expired for %s sec", task_id, tag['taginfo']['id'], "expired for %s sec", task_id, tag['taginfo']['id'],
tag['taginfo']['name'], time_expired) tag['taginfo']['name'], time_expired)
self.tasks[task_id] = { self.tasks[task_id] = {
'id': task_id, 'id': task_id,
'taskinfo': self.session.getTaskInfo(task_id), 'taskinfo': self.session.getTaskInfo(task_id),
'tag_id': tag['taginfo']['id'], 'tag_id': tag['taginfo']['id'],
'maven': maven, 'maven': maven,
} }
tag['task_id'] = task_id tag['task_id'] = task_id
if running_tasks_maven >= self.options.max_repo_tasks_maven: if running_tasks_maven >= self.options.max_repo_tasks_maven:
self.logger.info("Maximum number of maven repo tasks reached") self.logger.info("Maximum number of maven repo tasks reached")
@ -804,7 +804,7 @@ class RepoManager(object):
def start_currency_checker(session, repomgr): def start_currency_checker(session, repomgr):
subsession = session.subsession() subsession = session.subsession()
thread = threading.Thread(name='currencyChecker', thread = threading.Thread(name='currencyChecker',
target=repomgr.currencyChecker, args=(subsession,)) target=repomgr.currencyChecker, args=(subsession,))
thread.setDaemon(True) thread.setDaemon(True)
thread.start() thread.start()
return thread return thread
@ -813,7 +813,7 @@ def start_currency_checker(session, repomgr):
def start_regen_loop(session, repomgr): def start_regen_loop(session, repomgr):
subsession = session.subsession() subsession = session.subsession()
thread = threading.Thread(name='regenLoop', thread = threading.Thread(name='regenLoop',
target=repomgr.regenLoop, args=(subsession,)) target=repomgr.regenLoop, args=(subsession,))
thread.setDaemon(True) thread.setDaemon(True)
thread.start() thread.start()
return thread return thread

View file

@ -617,7 +617,7 @@ def get_mgmt_server():
logger.debug('found MAC address %s, connecting to %s:%s', logger.debug('found MAC address %s, connecting to %s:%s',
macaddr, gateway, MANAGER_PORT) macaddr, gateway, MANAGER_PORT)
server = six.moves.xmlrpc_client.ServerProxy('http://%s:%s/' % server = six.moves.xmlrpc_client.ServerProxy('http://%s:%s/' %
(gateway, MANAGER_PORT), allow_none=True) (gateway, MANAGER_PORT), allow_none=True)
# we would set a timeout on the socket here, but that is apparently not # we would set a timeout on the socket here, but that is apparently not
# supported by python/cygwin/Windows # supported by python/cygwin/Windows
task_port = server.getPort(macaddr) task_port = server.getPort(macaddr)

View file

@ -98,7 +98,7 @@ def get_options():
parser.add_option("--maxjobs", type='int', help="Specify maxjobs") parser.add_option("--maxjobs", type='int', help="Specify maxjobs")
parser.add_option("--sleeptime", type='int', help="Specify the polling interval") parser.add_option("--sleeptime", type='int', help="Specify the polling interval")
parser.add_option("--admin-emails", type='str', action="store", metavar="EMAILS", parser.add_option("--admin-emails", type='str', action="store", metavar="EMAILS",
help="Comma-separated addresses to send error notices to.") help="Comma-separated addresses to send error notices to.")
parser.add_option("--workdir", help="Specify workdir") parser.add_option("--workdir", help="Specify workdir")
parser.add_option("--pluginpath", help="Specify plugin search path") parser.add_option("--pluginpath", help="Specify plugin search path")
parser.add_option("--plugin", action="append", help="Load specified plugin") parser.add_option("--plugin", action="append", help="Load specified plugin")
@ -266,7 +266,7 @@ class DaemonXMLRPCServer(six.moves.xmlrpc_server.SimpleXMLRPCServer):
six.moves.xmlrpc_server.SimpleXMLRPCServer.__init__(self, (addr, port), logRequests=False) six.moves.xmlrpc_server.SimpleXMLRPCServer.__init__(self, (addr, port), logRequests=False)
else: else:
six.moves.xmlrpc_server.SimpleXMLRPCServer.__init__(self, (addr, port), logRequests=False, six.moves.xmlrpc_server.SimpleXMLRPCServer.__init__(self, (addr, port), logRequests=False,
allow_none=True) allow_none=True)
self.logger = logging.getLogger('koji.vm.DaemonXMLRPCServer') self.logger = logging.getLogger('koji.vm.DaemonXMLRPCServer')
self.socket.settimeout(5) self.socket.settimeout(5)
self.active = True self.active = True
@ -308,7 +308,7 @@ class DaemonXMLRPCServer(six.moves.xmlrpc_server.SimpleXMLRPCServer):
# report exception back to server # report exception back to server
response = six.moves.xmlrpc_client.dumps( response = six.moves.xmlrpc_client.dumps(
six.moves.xmlrpc_client.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value)) six.moves.xmlrpc_client.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value))
) )
return response return response
@ -350,7 +350,7 @@ class WinBuildTask(MultiPlatformTask):
'build_tag' : build_tag['id'], 'build_tag' : build_tag['id'],
'skip_tag' : bool(opts.get('skip_tag')), 'skip_tag' : bool(opts.get('skip_tag')),
'target': target_info['id'] 'target': target_info['id']
} }
if not opts.get('skip_tag'): if not opts.get('skip_tag'):
policy_data['tag'] = dest_tag['id'] policy_data['tag'] = dest_tag['id']
self.session.host.assertPolicy('build_from_repo_id', policy_data) self.session.host.assertPolicy('build_from_repo_id', policy_data)
@ -378,10 +378,10 @@ class WinBuildTask(MultiPlatformTask):
# Make sure package is on the list for this tag # Make sure package is on the list for this tag
if pkg_cfg is None: if pkg_cfg is None:
raise koji.BuildError("package %s not in list for tag %s" \ raise koji.BuildError("package %s not in list for tag %s" \
% (build_info['name'], dest_tag['name'])) % (build_info['name'], dest_tag['name']))
elif pkg_cfg['blocked']: elif pkg_cfg['blocked']:
raise koji.BuildError("package %s is blocked for tag %s" \ raise koji.BuildError("package %s is blocked for tag %s" \
% (build_info['name'], dest_tag['name'])) % (build_info['name'], dest_tag['name']))
build_info = self.session.host.initWinBuild(self.id, build_info, build_info = self.session.host.initWinBuild(self.id, build_info,
koji.util.dslice(results, ['platform'])) koji.util.dslice(results, ['platform']))
@ -430,7 +430,7 @@ class VMExecTask(BaseTaskHandler):
def __init__(self, *args, **kw): def __init__(self, *args, **kw):
super(VMExecTask, self).__init__(*args, **kw) super(VMExecTask, self).__init__(*args, **kw)
self.task_manager = six.moves.xmlrpc_client.ServerProxy('http://%s:%s/' % (self.options.privaddr, self.options.portbase), self.task_manager = six.moves.xmlrpc_client.ServerProxy('http://%s:%s/' % (self.options.privaddr, self.options.portbase),
allow_none=True) allow_none=True)
self.port = None self.port = None
self.server = None self.server = None
self.task_info = None self.task_info = None
@ -450,7 +450,7 @@ class VMExecTask(BaseTaskHandler):
ret = proc.wait() ret = proc.wait()
if ret: if ret:
raise koji.BuildError('unable to create qcow2 image, "%s" returned %s; output was: %s' % \ raise koji.BuildError('unable to create qcow2 image, "%s" returned %s; output was: %s' % \
(' '.join(cmd), ret, output)) (' '.join(cmd), ret, output))
vm_user = pwd.getpwnam(self.options.vmuser) vm_user = pwd.getpwnam(self.options.vmuser)
os.chown(new_path, vm_user.pw_uid, vm_user.pw_gid) os.chown(new_path, vm_user.pw_uid, vm_user.pw_gid)
return new_path return new_path
@ -680,13 +680,13 @@ class VMExecTask(BaseTaskHandler):
remote_pi = koji.PathInfo(self.options.topurl) remote_pi = koji.PathInfo(self.options.topurl)
if type == 'rpm': if type == 'rpm':
remote_url = remote_pi.build(buildinfo) + '/' + \ remote_url = remote_pi.build(buildinfo) + '/' + \
fileinfo['localpath'] fileinfo['localpath']
elif type == 'maven': elif type == 'maven':
remote_url = remote_pi.mavenbuild(buildinfo) + '/' + \ remote_url = remote_pi.mavenbuild(buildinfo) + '/' + \
fileinfo['localpath'] fileinfo['localpath']
elif type == 'win': elif type == 'win':
remote_url = remote_pi.winbuild(buildinfo) + '/' + \ remote_url = remote_pi.winbuild(buildinfo) + '/' + \
fileinfo['localpath'] fileinfo['localpath']
else: else:
raise koji.BuildError('unsupported file type: %s' % type) raise koji.BuildError('unsupported file type: %s' % type)
koji.ensuredir(os.path.dirname(localpath)) koji.ensuredir(os.path.dirname(localpath))
@ -706,7 +706,7 @@ class VMExecTask(BaseTaskHandler):
fileinfo['payloadhash'], payloadhash)) fileinfo['payloadhash'], payloadhash))
if not koji.util.check_sigmd5(localpath): if not koji.util.check_sigmd5(localpath):
raise koji.BuildError("Downloaded rpm %s doesn't match sigmd5" % \ raise koji.BuildError("Downloaded rpm %s doesn't match sigmd5" % \
os.path.basename(fileinfo['localpath'])) os.path.basename(fileinfo['localpath']))
else: else:
self.verifyChecksum(localpath, fileinfo['checksum'], koji.CHECKSUM_TYPES[fileinfo['checksum_type']]) self.verifyChecksum(localpath, fileinfo['checksum'], koji.CHECKSUM_TYPES[fileinfo['checksum_type']])
@ -746,7 +746,7 @@ class VMExecTask(BaseTaskHandler):
size = os.path.getsize(local_path) size = os.path.getsize(local_path)
if offset != size: if offset != size:
raise koji.BuildError('cannot write to %s at offset %s, size is %s' % \ raise koji.BuildError('cannot write to %s at offset %s, size is %s' % \
(local_path, offset, size)) (local_path, offset, size))
fobj = open(local_path, 'r+') fobj = open(local_path, 'r+')
fobj.seek(offset) fobj.seek(offset)
data = base64.b64decode(contents) data = base64.b64decode(contents)
@ -790,7 +790,7 @@ class VMExecTask(BaseTaskHandler):
return True return True
else: else:
raise koji.BuildError('%s checksum validation failed for %s, %s (computed) != %s (provided)' % \ raise koji.BuildError('%s checksum validation failed for %s, %s (computed) != %s (provided)' % \
(algo, local_path, sum.hexdigest(), checksum)) (algo, local_path, sum.hexdigest(), checksum))
def closeTask(self, output): def closeTask(self, output):
self.output = output self.output = output
@ -855,7 +855,7 @@ class VMExecTask(BaseTaskHandler):
except libvirt.libvirtError as e: except libvirt.libvirtError as e:
self.logger.error('error starting VM %s', clone_name, exc_info=True) self.logger.error('error starting VM %s', clone_name, exc_info=True)
raise koji.PreBuildError('error starting VM %s, error was: %s' % \ raise koji.PreBuildError('error starting VM %s, error was: %s' % \
(clone_name, e)) (clone_name, e))
start = time.time() start = time.time()
while True: while True:
@ -873,7 +873,7 @@ class VMExecTask(BaseTaskHandler):
vm.destroy() vm.destroy()
self.server.server_close() self.server.server_close()
raise koji.BuildError('Task did not complete after %.2f minutes, VM %s has been destroyed' % \ raise koji.BuildError('Task did not complete after %.2f minutes, VM %s has been destroyed' % \
(mins, clone_name)) (mins, clone_name))
else: else:
vm.destroy() vm.destroy()
self.server.server_close() self.server.server_close()
@ -941,7 +941,7 @@ class VMTaskManager(TaskManager):
for node in nodelist: for node in nodelist:
disk = node.prop('file') disk = node.prop('file')
if os.path.basename(disk).startswith(VMExecTask.CLONE_PREFIX) and \ if os.path.basename(disk).startswith(VMExecTask.CLONE_PREFIX) and \
disk.endswith(VMExecTask.QCOW2_EXT): disk.endswith(VMExecTask.QCOW2_EXT):
disks.append(disk) disks.append(disk)
ctx.xpathFreeContext() ctx.xpathFreeContext()
doc.freeDoc() doc.freeDoc()

View file

@ -191,7 +191,7 @@ def _construct_url(environ, page):
host = environ['SERVER_NAME'] host = environ['SERVER_NAME']
url_scheme = environ['wsgi.url_scheme'] url_scheme = environ['wsgi.url_scheme']
if (url_scheme == 'https' and port == '443') or \ if (url_scheme == 'https' and port == '443') or \
(url_scheme == 'http' and port == '80'): (url_scheme == 'http' and port == '80'):
return "%s://%s%s" % (url_scheme, host, page) return "%s://%s%s" % (url_scheme, host, page)
return "%s://%s:%s%s" % (url_scheme, host, port, page) return "%s://%s:%s%s" % (url_scheme, host, port, page)
@ -683,7 +683,7 @@ def taskinfo(environ, taskID):
values['excClass'] = None values['excClass'] = None
if task['method'] == 'buildContainer' and 'koji_builds' in result: if task['method'] == 'buildContainer' and 'koji_builds' in result:
values['taskBuilds'] = [ values['taskBuilds'] = [
server.getBuild(int(buildID)) for buildID in result['koji_builds']] server.getBuild(int(buildID)) for buildID in result['koji_builds']]
else: else:
values['result'] = None values['result'] = None
values['excClass'] = None values['excClass'] = None
@ -819,7 +819,7 @@ def tags(environ, start=None, order=None, childID=None):
values['order'] = order values['order'] = order
kojiweb.util.paginateMethod(server, values, 'listTags', kw=None, kojiweb.util.paginateMethod(server, values, 'listTags', kw=None,
start=start, dataName='tags', prefix='tag', order=order) start=start, dataName='tags', prefix='tag', order=order)
if environ['koji.currentUser']: if environ['koji.currentUser']:
values['perms'] = server.getUserPerms(environ['koji.currentUser']['id']) values['perms'] = server.getUserPerms(environ['koji.currentUser']['id'])
@ -859,8 +859,8 @@ def packages(environ, tagID=None, userID=None, order='package_name', start=None,
values['inherited'] = inherited values['inherited'] = inherited
kojiweb.util.paginateMethod(server, values, 'listPackages', kojiweb.util.paginateMethod(server, values, 'listPackages',
kw={'tagID': tagID, 'userID': userID, 'prefix': prefix, 'inherited': bool(inherited)}, kw={'tagID': tagID, 'userID': userID, 'prefix': prefix, 'inherited': bool(inherited)},
start=start, dataName='packages', prefix='package', order=order) start=start, dataName='packages', prefix='package', order=order)
values['chars'] = _PREFIX_CHARS values['chars'] = _PREFIX_CHARS
@ -1652,8 +1652,8 @@ def channelinfo(environ, channelID):
states = [koji.TASK_STATES[s] for s in ('FREE', 'OPEN', 'ASSIGNED')] states = [koji.TASK_STATES[s] for s in ('FREE', 'OPEN', 'ASSIGNED')]
values['taskCount'] = \ values['taskCount'] = \
server.listTasks(opts={'channel_id': channelID, 'state': states}, server.listTasks(opts={'channel_id': channelID, 'state': states},
queryOpts={'countOnly': True}) queryOpts={'countOnly': True})
hosts = server.listHosts(channelID=channelID) hosts = server.listHosts(channelID=channelID)
hosts.sort(key=_sortbyname) hosts.sort(key=_sortbyname)
@ -1756,7 +1756,7 @@ def archivelist(environ, type, buildrootID=None, imageID=None, start=None, order
start=start, dataName='archives', prefix='archive', order=order) start=start, dataName='archives', prefix='archive', order=order)
elif type == 'built': elif type == 'built':
kojiweb.util.paginateMethod(server, values, 'listArchives', kw={'buildrootID': buildroot['id']}, kojiweb.util.paginateMethod(server, values, 'listArchives', kw={'buildrootID': buildroot['id']},
start=start, dataName='archives', prefix='archive', order=order) start=start, dataName='archives', prefix='archive', order=order)
else: else:
raise koji.GenericError('unrecognized type of archivelist') raise koji.GenericError('unrecognized type of archivelist')
elif imageID is not None: elif imageID is not None:

View file

@ -551,8 +551,8 @@ def escapeHTML(value):
value = koji.fixEncoding(value) value = koji.fixEncoding(value)
return value.replace('&', '&amp;').\ return value.replace('&', '&amp;').\
replace('<', '&lt;').\ replace('<', '&lt;').\
replace('>', '&gt;') replace('>', '&gt;')
def authToken(template, first=False, form=False): def authToken(template, first=False, form=False):
"""Return the current authToken if it exists. """Return the current authToken if it exists.
@ -644,7 +644,7 @@ class TaskResultFragment(object):
- empty_str_placeholder - empty_str_placeholder
""" """
def __init__(self, text='', size=None, need_escape=None, begin_tag='', def __init__(self, text='', size=None, need_escape=None, begin_tag='',
end_tag='', composer=None, empty_str_placeholder=None): end_tag='', composer=None, empty_str_placeholder=None):
self.text = text self.text = text
if size is None: if size is None:
self.size = len(text) self.size = len(text)
@ -689,7 +689,7 @@ class TaskResultLine(object):
- composer - composer
""" """
def __init__(self, fragments=None, need_escape=None, begin_tag='', def __init__(self, fragments=None, need_escape=None, begin_tag='',
end_tag='<br />', composer=None): end_tag='<br />', composer=None):
if fragments is None: if fragments is None:
self.fragments = [] self.fragments = []
else: else:
@ -746,18 +746,18 @@ def _parse_value(key, value, sep=', '):
_str = sep.join([str(val) for val in value]) _str = sep.join([str(val) for val in value])
elif isinstance(value, dict): elif isinstance(value, dict):
_str = sep.join(['%s=%s' % ((n == '' and "''" or n), v) _str = sep.join(['%s=%s' % ((n == '' and "''" or n), v)
for n, v in value.items()]) for n, v in value.items()])
else: else:
_str = str(value) _str = str(value)
if _str is None: if _str is None:
_str = '' _str = ''
return TaskResultFragment(text=_str, need_escape=need_escape, return TaskResultFragment(text=_str, need_escape=need_escape,
begin_tag=begin_tag, end_tag=end_tag) begin_tag=begin_tag, end_tag=end_tag)
def task_result_to_html(result=None, exc_class=None, def task_result_to_html(result=None, exc_class=None,
max_abbr_lines=None, max_abbr_len=None, max_abbr_lines=None, max_abbr_len=None,
abbr_postscript=None): abbr_postscript=None):
"""convert the result to a mutiple lines HTML fragment """convert the result to a mutiple lines HTML fragment
Args: Args:
@ -801,7 +801,7 @@ def task_result_to_html(result=None, exc_class=None,
def _parse_properties(props): def _parse_properties(props):
return ', '.join([v is not None and '%s=%s' % (n, v) or str(n) return ', '.join([v is not None and '%s=%s' % (n, v) or str(n)
for n, v in props.items()]) for n, v in props.items()])
if exc_class: if exc_class:
if hasattr(result, 'faultString'): if hasattr(result, 'faultString'):
@ -810,7 +810,7 @@ def task_result_to_html(result=None, exc_class=None,
_str = "%s: %s" % (exc_class.__name__, str(result)) _str = "%s: %s" % (exc_class.__name__, str(result))
fragment = TaskResultFragment(text=_str, need_escape=True) fragment = TaskResultFragment(text=_str, need_escape=True)
line = TaskResultLine(fragments=[fragment], line = TaskResultLine(fragments=[fragment],
begin_tag='<pre>', end_tag='</pre>') begin_tag='<pre>', end_tag='</pre>')
lines.append(line) lines.append(line)
elif isinstance(result, dict): elif isinstance(result, dict):
@ -821,8 +821,8 @@ def task_result_to_html(result=None, exc_class=None,
val_fragment = line.fragments[1] val_fragment = line.fragments[1]
if length is None: if length is None:
return '%s%s = %s%s%s' % (line.begin_tag, key_fragment.composer(), return '%s%s = %s%s%s' % (line.begin_tag, key_fragment.composer(),
val_fragment.composer(), postscript, val_fragment.composer(), postscript,
line.end_tag) line.end_tag)
first_part_len = len('%s = ') + key_fragment.size first_part_len = len('%s = ') + key_fragment.size
remainder_len = length - first_part_len remainder_len = length - first_part_len
if remainder_len < 0: remainder_len = 0 if remainder_len < 0: remainder_len = 0
@ -840,7 +840,7 @@ def task_result_to_html(result=None, exc_class=None,
val_fragment = _parse_value(k, v) val_fragment = _parse_value(k, v)
key_fragment = TaskResultFragment(text=k, need_escape=True) key_fragment = TaskResultFragment(text=k, need_escape=True)
line = TaskResultLine(fragments=[key_fragment, val_fragment], line = TaskResultLine(fragments=[key_fragment, val_fragment],
need_escape=False, composer=composer) need_escape=False, composer=composer)
lines.append(line) lines.append(line)
else: else:
if result is not None: if result is not None: