2020-07-08 20:23:19 +02:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
'''Tool for managing VM templates.'''
|
|
|
|
|
2020-07-08 20:23:19 +02:00
|
|
|
import argparse
|
2020-07-21 13:34:16 +02:00
|
|
|
import collections
|
2020-07-08 20:23:19 +02:00
|
|
|
import datetime
|
2020-07-09 20:43:03 +02:00
|
|
|
import enum
|
2020-07-19 19:08:40 +02:00
|
|
|
import fnmatch
|
2020-07-21 13:34:16 +02:00
|
|
|
import functools
|
2020-07-20 20:04:55 +02:00
|
|
|
import itertools
|
2020-08-18 19:59:51 +02:00
|
|
|
import json
|
2020-08-07 08:48:08 +02:00
|
|
|
import operator
|
2020-07-08 20:23:19 +02:00
|
|
|
import os
|
2020-07-29 12:36:02 +02:00
|
|
|
import re
|
2020-07-08 20:23:19 +02:00
|
|
|
import shutil
|
|
|
|
import subprocess
|
|
|
|
import sys
|
|
|
|
import tempfile
|
|
|
|
import time
|
2020-08-03 20:51:36 +02:00
|
|
|
import typing
|
2020-07-08 20:23:19 +02:00
|
|
|
|
2020-08-30 20:08:44 +02:00
|
|
|
import rpm
|
|
|
|
import tqdm
|
|
|
|
import xdg.BaseDirectory
|
|
|
|
|
2020-07-08 20:23:19 +02:00
|
|
|
import qubesadmin
|
2020-07-09 20:43:03 +02:00
|
|
|
import qubesadmin.tools
|
2020-08-14 05:38:30 +02:00
|
|
|
import qubesadmin.tools.qvm_kill
|
|
|
|
import qubesadmin.tools.qvm_remove
|
2020-07-08 20:23:19 +02:00
|
|
|
|
|
|
|
PATH_PREFIX = '/var/lib/qubes/vm-templates'
|
|
|
|
TEMP_DIR = '/var/tmp'
|
|
|
|
PACKAGE_NAME_PREFIX = 'qubes-template-'
|
|
|
|
CACHE_DIR = os.path.join(xdg.BaseDirectory.xdg_cache_home, 'qvm-template')
|
2020-07-11 16:31:38 +02:00
|
|
|
UNVERIFIED_SUFFIX = '.unverified'
|
2020-07-25 20:08:46 +02:00
|
|
|
LOCK_FILE = '/var/tmp/qvm-template.lck'
|
2020-09-06 17:57:42 +02:00
|
|
|
DATE_FMT = '%Y-%m-%d %H:%M:%S'
|
2020-07-08 20:23:19 +02:00
|
|
|
|
2020-08-03 20:51:36 +02:00
|
|
|
def qubes_release() -> str:
|
|
|
|
"""Return the Qubes release."""
|
2020-07-08 20:38:36 +02:00
|
|
|
if os.path.exists('/usr/share/qubes/marker-vm'):
|
2020-07-11 17:12:57 +02:00
|
|
|
with open('/usr/share/qubes/marker-vm', 'r') as fd:
|
2020-07-08 20:38:36 +02:00
|
|
|
# Get last line (in the format `x.x`)
|
2020-07-11 17:12:57 +02:00
|
|
|
return fd.readlines()[-1].strip()
|
2020-08-29 19:58:25 +02:00
|
|
|
with open('/etc/os-release', 'r') as fd:
|
|
|
|
for line in fd:
|
|
|
|
line = line.strip()
|
|
|
|
if not line or line[0] == '#':
|
|
|
|
continue
|
|
|
|
key, val = line.split('=', 1)
|
|
|
|
if key != 'VERSION_ID':
|
|
|
|
continue
|
|
|
|
val = val.strip('\'"') # strip possible quotes
|
|
|
|
return val
|
2020-07-08 20:23:19 +02:00
|
|
|
|
2020-08-03 20:51:36 +02:00
|
|
|
def parser_gen() -> argparse.ArgumentParser:
|
|
|
|
"""Generate argument parser for the application."""
|
2020-08-03 19:34:14 +02:00
|
|
|
formatter = argparse.ArgumentDefaultsHelpFormatter
|
|
|
|
parser_main = argparse.ArgumentParser(description='Qubes Template Manager',
|
|
|
|
formatter_class=formatter)
|
2020-09-04 20:06:53 +02:00
|
|
|
subparsers = parser_main.add_subparsers(dest='operation',
|
2020-08-03 19:34:14 +02:00
|
|
|
description='Command to run.')
|
|
|
|
|
2020-08-14 05:38:30 +02:00
|
|
|
def parser_add_command(cmd, help_str):
|
|
|
|
return subparsers.add_parser(
|
|
|
|
cmd,
|
|
|
|
formatter_class=formatter,
|
|
|
|
help=help_str,
|
|
|
|
description=help_str)
|
2020-08-03 19:34:14 +02:00
|
|
|
|
|
|
|
parser_main.add_argument('--repo-files', action='append',
|
2020-08-03 19:35:14 +02:00
|
|
|
default=['/usr/share/qubes/repo-templates/qubes-templates.repo'],
|
2020-08-25 17:00:08 +02:00
|
|
|
help=('Specify files containing DNF repository configuration.'
|
|
|
|
' Can be used more than once.'))
|
2020-08-14 08:27:36 +02:00
|
|
|
parser_main.add_argument('--keyring',
|
|
|
|
default='/usr/share/qubes/repo-templates/keys',
|
|
|
|
help='Specify directory containing RPM public keys.')
|
2020-08-03 19:34:14 +02:00
|
|
|
parser_main.add_argument('--updatevm', default='sys-firewall',
|
2020-09-03 19:59:28 +02:00
|
|
|
help=('Specify VM to download updates from.'
|
|
|
|
' (Set to empty string to specify the current VM.)'))
|
2020-08-03 19:34:14 +02:00
|
|
|
parser_main.add_argument('--enablerepo', action='append', default=[],
|
2020-08-25 17:00:08 +02:00
|
|
|
metavar='REPOID',
|
|
|
|
help=('Enable additional repositories by an id or a glob.'
|
|
|
|
' Can be used more than once.'))
|
2020-08-03 19:34:14 +02:00
|
|
|
parser_main.add_argument('--disablerepo', action='append', default=[],
|
2020-08-25 17:00:08 +02:00
|
|
|
metavar='REPOID',
|
|
|
|
help=('Disable certain repositories by an id or a glob.'
|
|
|
|
' Can be used more than once.'))
|
2020-08-03 19:34:14 +02:00
|
|
|
parser_main.add_argument('--repoid', action='append', default=[],
|
2020-08-25 17:00:08 +02:00
|
|
|
help=('Enable just specific repositories by an id or a glob.'
|
|
|
|
' Can be used more than once.'))
|
2020-08-03 19:34:14 +02:00
|
|
|
parser_main.add_argument('--releasever', default=qubes_release(),
|
2020-08-25 17:00:08 +02:00
|
|
|
help='Override Qubes release version.')
|
2020-08-03 19:34:14 +02:00
|
|
|
parser_main.add_argument('--refresh', action='store_true',
|
|
|
|
help='Set repository metadata as expired before running the command.')
|
|
|
|
parser_main.add_argument('--cachedir', default=CACHE_DIR,
|
|
|
|
help='Specify cache directory.')
|
2020-08-08 08:39:29 +02:00
|
|
|
parser_main.add_argument('--yes', action='store_true',
|
|
|
|
help='Assume "yes" to questions.')
|
2020-08-18 20:00:19 +02:00
|
|
|
parser_main.add_argument('--quiet', action='store_true',
|
2020-08-25 17:00:08 +02:00
|
|
|
help='Decrease verbosity.')
|
2020-08-03 19:34:14 +02:00
|
|
|
# qvm-template {install,reinstall,downgrade,upgrade}
|
|
|
|
parser_install = parser_add_command('install',
|
|
|
|
help_str='Install template packages.')
|
|
|
|
parser_install.add_argument('--pool',
|
|
|
|
help='Specify pool to store created VMs in.')
|
|
|
|
parser_reinstall = parser_add_command('reinstall',
|
|
|
|
help_str='Reinstall template packages.')
|
|
|
|
parser_downgrade = parser_add_command('downgrade',
|
|
|
|
help_str='Downgrade template packages.')
|
|
|
|
parser_upgrade = parser_add_command('upgrade',
|
|
|
|
help_str='Upgrade template packages.')
|
|
|
|
for parser_x in [parser_install, parser_reinstall,
|
|
|
|
parser_downgrade, parser_upgrade]:
|
|
|
|
parser_x.add_argument('--nogpgcheck', action='store_true',
|
|
|
|
help='Disable signature checks.')
|
|
|
|
parser_x.add_argument('--allow-pv', action='store_true',
|
2020-08-25 17:00:08 +02:00
|
|
|
help='Allow templates that set virt_mode to pv.')
|
|
|
|
parser_x.add_argument('templates', nargs='*', metavar='TEMPLATESPEC')
|
2020-08-07 16:58:17 +02:00
|
|
|
# qvm-template download
|
|
|
|
parser_download = parser_add_command('download',
|
2020-08-25 17:00:08 +02:00
|
|
|
help_str='Download template packages.')
|
2020-08-07 16:58:17 +02:00
|
|
|
for parser_x in [parser_install, parser_reinstall,
|
|
|
|
parser_downgrade, parser_upgrade, parser_download]:
|
|
|
|
parser_x.add_argument('--downloaddir', default='.',
|
|
|
|
help='Specify download directory.')
|
|
|
|
parser_x.add_argument('--retries', default=5, type=int,
|
2020-08-25 17:00:08 +02:00
|
|
|
help='Specify maximum number of retries for downloads.')
|
|
|
|
parser_download.add_argument('templates', nargs='*',
|
|
|
|
metavar='TEMPLATESPEC')
|
2020-08-03 19:34:14 +02:00
|
|
|
# qvm-template {list,info}
|
|
|
|
parser_list = parser_add_command('list',
|
|
|
|
help_str='List templates.')
|
|
|
|
parser_info = parser_add_command('info',
|
|
|
|
help_str='Display details about templates.')
|
|
|
|
for parser_x in [parser_list, parser_info]:
|
|
|
|
parser_x.add_argument('--all', action='store_true',
|
|
|
|
help='Show all templates (default).')
|
|
|
|
parser_x.add_argument('--installed', action='store_true',
|
|
|
|
help='Show installed templates.')
|
|
|
|
parser_x.add_argument('--available', action='store_true',
|
|
|
|
help='Show available templates.')
|
|
|
|
parser_x.add_argument('--extras', action='store_true',
|
2020-08-25 17:00:08 +02:00
|
|
|
help=('Show extras (e.g., ones that exist'
|
2020-08-03 19:34:14 +02:00
|
|
|
' locally but not in repos) templates.'))
|
|
|
|
parser_x.add_argument('--upgrades', action='store_true',
|
2020-08-29 20:54:43 +02:00
|
|
|
help='Show available upgrades.')
|
2020-08-18 19:59:51 +02:00
|
|
|
readable = parser_x.add_mutually_exclusive_group()
|
|
|
|
readable.add_argument('--machine-readable', action='store_true',
|
2020-08-05 20:42:05 +02:00
|
|
|
help='Enable machine-readable output.')
|
2020-08-18 19:59:51 +02:00
|
|
|
readable.add_argument('--machine-readable-json', action='store_true',
|
|
|
|
help='Enable machine-readable output (JSON).')
|
2020-08-25 17:00:08 +02:00
|
|
|
parser_x.add_argument('templates', nargs='*', metavar='TEMPLATESPEC')
|
2020-08-03 19:34:14 +02:00
|
|
|
# qvm-template search
|
|
|
|
parser_search = parser_add_command('search',
|
|
|
|
help_str='Search template details for the given string.')
|
|
|
|
parser_search.add_argument('--all', action='store_true',
|
2020-08-25 17:00:08 +02:00
|
|
|
help=('Search also in the template description and URL. In addition,'
|
2020-08-03 19:34:14 +02:00
|
|
|
' the criterion are evaluated with OR instead of AND.'))
|
|
|
|
parser_search.add_argument('templates', nargs='*', metavar='PATTERN')
|
|
|
|
# qvm-template remove
|
|
|
|
parser_remove = parser_add_command('remove',
|
2020-08-14 05:38:30 +02:00
|
|
|
help_str='Remove installed templates.')
|
|
|
|
parser_remove.add_argument('--disassoc', action='store_true',
|
2020-08-25 17:00:08 +02:00
|
|
|
help=('Also disassociate VMs from the templates to be removed.'
|
|
|
|
' This creates a dummy template for the VMs to link with.'))
|
2020-08-14 05:38:30 +02:00
|
|
|
parser_remove.add_argument('templates', nargs='*', metavar='TEMPLATE')
|
|
|
|
# qvm-template purge
|
|
|
|
parser_purge = parser_add_command('purge',
|
|
|
|
help_str='Remove installed templates and associated VMs.')
|
|
|
|
parser_purge.add_argument('templates', nargs='*', metavar='TEMPLATE')
|
2020-08-03 19:34:14 +02:00
|
|
|
# qvm-template clean
|
|
|
|
parser_clean = parser_add_command('clean',
|
2020-08-25 17:00:08 +02:00
|
|
|
help_str='Remove locally cached packages.')
|
2020-08-03 19:34:14 +02:00
|
|
|
_ = parser_clean # unused
|
2020-08-07 08:48:08 +02:00
|
|
|
# qvm-template repolist
|
|
|
|
parser_repolist = parser_add_command('repolist',
|
|
|
|
help_str='Show configured repositories.')
|
|
|
|
repolim = parser_repolist.add_mutually_exclusive_group()
|
|
|
|
repolim.add_argument('--all', action='store_true',
|
|
|
|
help='Show all repos.')
|
|
|
|
repolim.add_argument('--enabled', action='store_true',
|
2020-08-25 17:00:08 +02:00
|
|
|
help='Show only enabled repos (default).')
|
2020-08-07 08:48:08 +02:00
|
|
|
repolim.add_argument('--disabled', action='store_true',
|
2020-08-25 17:00:08 +02:00
|
|
|
help='Show only disabled repos.')
|
2020-08-07 08:48:08 +02:00
|
|
|
parser_repolist.add_argument('repos', nargs='*', metavar='REPOS')
|
2020-08-03 19:34:14 +02:00
|
|
|
|
|
|
|
return parser_main
|
|
|
|
|
|
|
|
parser = parser_gen()
|
2020-07-08 20:23:19 +02:00
|
|
|
|
2020-07-09 20:43:03 +02:00
|
|
|
class TemplateState(enum.Enum):
|
2020-08-03 20:51:36 +02:00
|
|
|
"""Enum representing the state of a template."""
|
2020-07-09 20:43:03 +02:00
|
|
|
INSTALLED = 'installed'
|
|
|
|
AVAILABLE = 'available'
|
|
|
|
EXTRA = 'extra'
|
|
|
|
UPGRADABLE = 'upgradable'
|
|
|
|
|
2020-08-03 20:51:36 +02:00
|
|
|
def title(self) -> str:
|
|
|
|
"""Return a long description of the state. Can be used as headings."""
|
2020-07-21 13:34:16 +02:00
|
|
|
#pylint: disable=invalid-name
|
2020-07-20 20:04:55 +02:00
|
|
|
TEMPLATE_TITLES = {
|
|
|
|
TemplateState.INSTALLED: 'Installed Templates',
|
|
|
|
TemplateState.AVAILABLE: 'Available Templates',
|
|
|
|
TemplateState.EXTRA: 'Extra Templates',
|
|
|
|
TemplateState.UPGRADABLE: 'Available Upgrades'
|
|
|
|
}
|
|
|
|
return TEMPLATE_TITLES[self]
|
|
|
|
|
2020-07-12 17:02:07 +02:00
|
|
|
class VersionSelector(enum.Enum):
|
2020-08-03 20:51:36 +02:00
|
|
|
"""Enum representing how the candidate template version is chosen."""
|
2020-07-12 17:02:07 +02:00
|
|
|
LATEST = enum.auto()
|
2020-08-05 20:05:57 +02:00
|
|
|
"""Install latest version."""
|
2020-07-12 17:02:07 +02:00
|
|
|
REINSTALL = enum.auto()
|
2020-08-05 20:05:57 +02:00
|
|
|
"""Reinstall current version."""
|
2020-07-12 17:02:07 +02:00
|
|
|
LATEST_LOWER = enum.auto()
|
2020-08-05 20:05:57 +02:00
|
|
|
"""Downgrade to the highest version that is lower than the current one."""
|
2020-07-12 17:02:07 +02:00
|
|
|
LATEST_HIGHER = enum.auto()
|
2020-08-05 20:05:57 +02:00
|
|
|
"""Upgrade to the highest version that is higher than the current one."""
|
|
|
|
|
|
|
|
class Template(typing.NamedTuple):
|
|
|
|
"""Details of a template."""
|
|
|
|
name: str
|
|
|
|
epoch: str
|
|
|
|
version: str
|
|
|
|
release: str
|
|
|
|
reponame: str
|
|
|
|
dlsize: int
|
|
|
|
buildtime: datetime.datetime
|
|
|
|
licence: str
|
|
|
|
url: str
|
|
|
|
summary: str
|
|
|
|
description: str
|
|
|
|
|
|
|
|
class DlEntry(typing.NamedTuple):
|
|
|
|
"""Information about a template to be downloaded."""
|
|
|
|
evr: typing.Tuple[str, str, str]
|
|
|
|
reponame: str
|
|
|
|
dlsize: int
|
2020-07-31 20:24:29 +02:00
|
|
|
|
2020-08-03 20:51:36 +02:00
|
|
|
def build_version_str(evr: typing.Tuple[str, str, str]) -> str:
|
2020-08-05 20:05:57 +02:00
|
|
|
"""Return version string described by ``evr``, which is in (epoch, version,
|
|
|
|
release) format."""
|
2020-07-31 20:40:27 +02:00
|
|
|
return '%s:%s-%s' % evr
|
|
|
|
|
2020-08-03 20:51:36 +02:00
|
|
|
def is_match_spec(name: str, epoch: str, version: str, release: str, spec: str
|
|
|
|
) -> typing.Tuple[bool, float]:
|
|
|
|
"""Check whether (name, epoch, version, release) matches the spec string.
|
|
|
|
|
|
|
|
For the algorithm, refer to section "NEVRA Matching" in the DNF
|
|
|
|
documentation.
|
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
Note that currently ``arch`` is ignored as the templates should be of
|
2020-08-03 20:51:36 +02:00
|
|
|
``noarch``.
|
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
:return: A tuple. The first element indicates whether there is a match; the
|
|
|
|
second element represents the priority of the match (lower is better)
|
2020-08-03 20:51:36 +02:00
|
|
|
"""
|
2020-07-31 20:40:27 +02:00
|
|
|
if epoch != 0:
|
|
|
|
targets = [
|
|
|
|
f'{name}-{epoch}:{version}-{release}',
|
|
|
|
f'{name}',
|
|
|
|
f'{name}-{epoch}:{version}'
|
|
|
|
]
|
|
|
|
else:
|
|
|
|
targets = [
|
|
|
|
f'{name}-{epoch}:{version}-{release}',
|
|
|
|
f'{name}-{version}-{release}',
|
|
|
|
f'{name}',
|
|
|
|
f'{name}-{epoch}:{version}',
|
|
|
|
f'{name}-{version}'
|
|
|
|
]
|
|
|
|
for prio, target in enumerate(targets):
|
|
|
|
if fnmatch.fnmatch(target, spec):
|
|
|
|
return True, prio
|
|
|
|
return False, float('inf')
|
|
|
|
|
2020-08-03 20:51:36 +02:00
|
|
|
def query_local(vm: qubesadmin.vm.QubesVM) -> Template:
|
|
|
|
"""Return Template object associated with ``vm``.
|
|
|
|
|
|
|
|
Requires the VM to be managed by qvm-template.
|
|
|
|
"""
|
2020-07-31 20:24:29 +02:00
|
|
|
return Template(
|
|
|
|
vm.features['template-name'],
|
|
|
|
vm.features['template-epoch'],
|
|
|
|
vm.features['template-version'],
|
|
|
|
vm.features['template-release'],
|
|
|
|
vm.features['template-reponame'],
|
|
|
|
vm.get_disk_utilization(),
|
2020-09-06 17:57:42 +02:00
|
|
|
datetime.datetime.strptime(vm.features['template-buildtime'], DATE_FMT),
|
2020-07-31 20:24:29 +02:00
|
|
|
vm.features['template-license'],
|
|
|
|
vm.features['template-url'],
|
|
|
|
vm.features['template-summary'],
|
|
|
|
vm.features['template-description'].replace('|', '\n'))
|
|
|
|
|
2020-08-03 20:51:36 +02:00
|
|
|
def query_local_evr(vm: qubesadmin.vm.QubesVM) -> typing.Tuple[str, str, str]:
|
|
|
|
"""Return the (epoch, version, release) of ``vm``.
|
|
|
|
|
|
|
|
Requires the VM to be managed by qvm-template.
|
|
|
|
"""
|
2020-07-31 20:24:29 +02:00
|
|
|
return (
|
|
|
|
vm.features['template-epoch'],
|
|
|
|
vm.features['template-version'],
|
|
|
|
vm.features['template-release'])
|
|
|
|
|
2020-08-03 20:51:36 +02:00
|
|
|
def is_managed_template(vm: qubesadmin.vm.QubesVM) -> bool:
|
|
|
|
"""Return whether the VM is managed by qvm-template."""
|
2020-08-03 19:38:52 +02:00
|
|
|
return vm.features.get('template-name', None) == vm.name
|
2020-07-31 20:24:29 +02:00
|
|
|
|
2020-08-03 20:51:36 +02:00
|
|
|
def get_managed_template_vm(app: qubesadmin.app.QubesBase, name: str
|
|
|
|
) -> qubesadmin.vm.QubesVM:
|
|
|
|
"""Return the QubesVM object associated with the given name if it exists
|
|
|
|
and is managed by qvm-template, otherwise raise a parser error."""
|
2020-07-31 21:21:31 +02:00
|
|
|
if name not in app.domains:
|
|
|
|
parser.error("Template '%s' not already installed." % name)
|
|
|
|
vm = app.domains[name]
|
|
|
|
if not is_managed_template(vm):
|
|
|
|
parser.error("Template '%s' is not managed by qvm-template." % name)
|
|
|
|
return vm
|
|
|
|
|
2020-08-14 05:38:30 +02:00
|
|
|
def confirm_action(msg: str, affected: typing.List[str]) -> None:
|
|
|
|
"""Confirm user action."""
|
|
|
|
print(msg)
|
|
|
|
for name in affected:
|
|
|
|
print(' ' + name)
|
|
|
|
|
|
|
|
confirm = ''
|
|
|
|
while confirm != 'y':
|
|
|
|
confirm = input('Are you sure? [y/N] ').lower()
|
|
|
|
if confirm == 'n':
|
|
|
|
print('Operation cancelled.')
|
|
|
|
sys.exit(1)
|
|
|
|
|
2020-08-03 20:51:36 +02:00
|
|
|
def qrexec_popen(
|
|
|
|
args: argparse.Namespace,
|
|
|
|
app: qubesadmin.app.QubesBase,
|
|
|
|
service: str,
|
2020-08-05 20:05:57 +02:00
|
|
|
stdout: typing.Union[int, typing.IO] = subprocess.PIPE,
|
2020-08-03 20:51:36 +02:00
|
|
|
filter_esc: bool = True) -> subprocess.Popen:
|
2020-08-05 20:05:57 +02:00
|
|
|
"""Return ``Popen`` object that communicates with the given qrexec call in
|
|
|
|
``args.updatevm``.
|
2020-08-03 20:51:36 +02:00
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
Note that this falls back to invoking ``/etc/qubes-rpc/*`` directly if
|
2020-09-03 19:59:28 +02:00
|
|
|
``args.updatevm`` is empty string.
|
2020-08-03 20:51:36 +02:00
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
:param args: Arguments received by the application. ``args.updatevm`` is
|
|
|
|
used
|
2020-08-03 20:51:36 +02:00
|
|
|
:param app: Qubes application object
|
2020-08-05 20:05:57 +02:00
|
|
|
:param service: The qrexec call to invoke
|
2020-08-03 20:51:36 +02:00
|
|
|
:param stdout: Where the process stdout points to. This is passed directly
|
2020-08-05 20:05:57 +02:00
|
|
|
to ``subprocess.Popen``. Defaults to ``subprocess.PIPE``
|
2020-08-03 20:51:36 +02:00
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
Note that stderr is always set to ``subprocess.PIPE``
|
|
|
|
:param filter_esc: Whether to filter out escape sequences from
|
|
|
|
stdout/stderr. Defaults to True
|
2020-08-03 20:51:36 +02:00
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
:returns: ``Popen`` object that communicates with the given qrexec call
|
2020-08-03 20:51:36 +02:00
|
|
|
"""
|
2020-07-08 20:23:19 +02:00
|
|
|
if args.updatevm:
|
2020-07-09 20:43:03 +02:00
|
|
|
return app.domains[args.updatevm].run_service(
|
|
|
|
service,
|
|
|
|
filter_esc=filter_esc,
|
|
|
|
stdout=stdout)
|
2020-07-11 17:12:57 +02:00
|
|
|
return subprocess.Popen([
|
|
|
|
'/etc/qubes-rpc/%s' % service,
|
|
|
|
],
|
|
|
|
stdin=subprocess.PIPE,
|
|
|
|
stdout=stdout,
|
|
|
|
stderr=subprocess.PIPE)
|
2020-07-08 20:23:19 +02:00
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
def qrexec_payload(args: argparse.Namespace, app: qubesadmin.app.QubesBase,
|
|
|
|
spec: str, refresh: bool) -> str:
|
|
|
|
"""Return payload string for the ``qubes.Template*`` qrexec calls.
|
|
|
|
|
|
|
|
:param args: Arguments received by the application. Specifically,
|
|
|
|
``args.{enablerepo,disablerepo,repoid,releasever,repo_files}`` are used
|
|
|
|
:param app: Qubes application object
|
|
|
|
:param spec: Package spec to query (refer to ``<package-name-spec>`` in the
|
|
|
|
DNF documentation)
|
|
|
|
:param refresh: Whether to force refresh repo metadata
|
|
|
|
|
|
|
|
:return: Payload string
|
|
|
|
|
|
|
|
:raises: Parser error if spec equals ``---`` or input contains ``\\n``
|
|
|
|
"""
|
2020-07-11 17:12:57 +02:00
|
|
|
_ = app # unused
|
|
|
|
|
2020-07-31 21:05:21 +02:00
|
|
|
if spec == '---':
|
|
|
|
parser.error("Malformed template name: argument should not be '---'.")
|
2020-07-31 20:24:29 +02:00
|
|
|
|
2020-07-11 16:08:16 +02:00
|
|
|
def check_newline(string, name):
|
|
|
|
if '\n' in string:
|
|
|
|
parser.error(f"Malformed {name}:" +
|
|
|
|
" argument should not contain '\\n'.")
|
|
|
|
|
2020-07-08 20:23:19 +02:00
|
|
|
payload = ''
|
2020-08-03 19:34:14 +02:00
|
|
|
for repo in args.enablerepo:
|
2020-07-11 17:12:57 +02:00
|
|
|
check_newline(repo, '--enablerepo')
|
|
|
|
payload += '--enablerepo=%s\n' % repo
|
2020-08-03 19:34:14 +02:00
|
|
|
for repo in args.disablerepo:
|
2020-07-11 17:12:57 +02:00
|
|
|
check_newline(repo, '--disablerepo')
|
|
|
|
payload += '--disablerepo=%s\n' % repo
|
2020-08-03 19:34:14 +02:00
|
|
|
for repo in args.repoid:
|
2020-07-11 17:12:57 +02:00
|
|
|
check_newline(repo, '--repoid')
|
|
|
|
payload += '--repoid=%s\n' % repo
|
2020-07-29 13:47:48 +02:00
|
|
|
if refresh:
|
|
|
|
payload += '--refresh\n'
|
2020-07-11 16:08:16 +02:00
|
|
|
check_newline(args.releasever, '--releasever')
|
2020-07-08 20:23:19 +02:00
|
|
|
payload += '--releasever=%s\n' % args.releasever
|
2020-07-11 16:08:16 +02:00
|
|
|
check_newline(spec, 'template name')
|
2020-07-08 20:23:19 +02:00
|
|
|
payload += spec + '\n'
|
|
|
|
payload += '---\n'
|
2020-07-11 17:12:57 +02:00
|
|
|
for path in args.repo_files:
|
|
|
|
with open(path, 'r') as fd:
|
|
|
|
payload += fd.read() + '\n'
|
2020-07-08 20:23:19 +02:00
|
|
|
return payload
|
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
def qrexec_repoquery(
|
|
|
|
args: argparse.Namespace,
|
|
|
|
app: qubesadmin.app.QubesBase,
|
|
|
|
spec: str = '*',
|
|
|
|
refresh: bool = False) -> typing.List[Template]:
|
|
|
|
"""Query template information from repositories.
|
|
|
|
|
|
|
|
:param args: Arguments received by the application. Specifically,
|
|
|
|
``args.{enablerepo,disablerepo,repoid,releasever,repo_files,updatevm}``
|
|
|
|
are used
|
|
|
|
:param app: Qubes application object
|
|
|
|
:param spec: Package spec to query (refer to ``<package-name-spec>`` in the
|
|
|
|
DNF documentation). Defaults to ``*``
|
|
|
|
:param refresh: Whether to force refresh repo metadata. Defaults to False
|
|
|
|
|
|
|
|
:raises ConnectionError: if the qrexec call fails
|
|
|
|
|
|
|
|
:return: List of ``Template`` objects representing the result of the query
|
|
|
|
"""
|
2020-07-29 13:47:48 +02:00
|
|
|
payload = qrexec_payload(args, app, spec, refresh)
|
2020-08-03 19:40:59 +02:00
|
|
|
proc = qrexec_popen(args, app, 'qubes.TemplateSearch')
|
2020-07-25 20:11:03 +02:00
|
|
|
stdout, stderr = proc.communicate(payload.encode('UTF-8'))
|
2020-07-09 20:43:03 +02:00
|
|
|
stdout = stdout.decode('ASCII')
|
2020-07-08 20:23:19 +02:00
|
|
|
if proc.wait() != 0:
|
2020-07-25 20:11:03 +02:00
|
|
|
for line in stderr.decode('ASCII').rstrip().split('\n'):
|
|
|
|
print('[Qrexec] %s' % line, file=sys.stderr)
|
2020-07-11 16:08:16 +02:00
|
|
|
raise ConnectionError("qrexec call 'qubes.TemplateSearch' failed.")
|
2020-07-29 12:36:02 +02:00
|
|
|
name_re = re.compile(r'^[A-Za-z0-9._+\-]*$')
|
|
|
|
evr_re = re.compile(r'^[A-Za-z0-9._+~]*$')
|
|
|
|
date_re = re.compile(r'^\d+-\d+-\d+ \d+:\d+$')
|
2020-07-29 13:58:19 +02:00
|
|
|
licence_re = re.compile(r'^[A-Za-z0-9._+\-()]*$')
|
2020-07-08 20:23:19 +02:00
|
|
|
result = []
|
2020-07-29 12:36:02 +02:00
|
|
|
for line in stdout.split('|\n'):
|
|
|
|
# Note that there's an empty entry at the end as .strip() is not used.
|
|
|
|
# This is because if .strip() is used, the .split() will not work.
|
|
|
|
if line == '':
|
2020-07-08 20:23:19 +02:00
|
|
|
continue
|
2020-07-29 12:36:02 +02:00
|
|
|
entry = line.split('|')
|
|
|
|
try:
|
|
|
|
# If there is an incorrect number of entries, raise an error
|
2020-07-31 20:24:29 +02:00
|
|
|
# Unpack manually instead of stuffing into `Template` right away
|
|
|
|
# so that it's easier to mutate stuff.
|
2020-07-29 12:36:02 +02:00
|
|
|
name, epoch, version, release, reponame, dlsize, \
|
2020-07-29 13:58:19 +02:00
|
|
|
buildtime, licence, url, summary, description = entry
|
2020-07-29 12:36:02 +02:00
|
|
|
|
|
|
|
# Ignore packages that are not templates
|
|
|
|
if not name.startswith(PACKAGE_NAME_PREFIX):
|
|
|
|
continue
|
|
|
|
name = name[len(PACKAGE_NAME_PREFIX):]
|
|
|
|
|
|
|
|
# Check that the values make sense
|
|
|
|
if not re.fullmatch(name_re, name):
|
|
|
|
raise ValueError
|
|
|
|
for val in [epoch, version, release]:
|
|
|
|
if not re.fullmatch(evr_re, val):
|
|
|
|
raise ValueError
|
|
|
|
if not re.fullmatch(name_re, reponame):
|
|
|
|
raise ValueError
|
|
|
|
dlsize = int(dlsize)
|
|
|
|
# First verify that the date does not look weird, then parse it
|
|
|
|
if not re.fullmatch(date_re, buildtime):
|
|
|
|
raise ValueError
|
|
|
|
buildtime = datetime.datetime.strptime(buildtime, '%Y-%m-%d %H:%M')
|
|
|
|
# XXX: Perhaps whitelist licenses directly?
|
2020-07-29 13:58:19 +02:00
|
|
|
if not re.fullmatch(licence_re, licence):
|
2020-07-29 12:36:02 +02:00
|
|
|
raise ValueError
|
|
|
|
# Check name actually matches spec
|
2020-09-06 19:52:56 +02:00
|
|
|
if not is_match_spec(PACKAGE_NAME_PREFIX + name,
|
|
|
|
epoch, version, release, spec)[0]:
|
2020-07-29 12:36:02 +02:00
|
|
|
continue
|
|
|
|
|
2020-07-31 20:40:27 +02:00
|
|
|
result.append(Template(name, epoch, version, release, reponame,
|
|
|
|
dlsize, buildtime, licence, url, summary, description))
|
|
|
|
except (TypeError, ValueError):
|
|
|
|
raise ConnectionError(("qrexec call 'qubes.TemplateSearch' failed:"
|
|
|
|
" unexpected data format."))
|
|
|
|
return result
|
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
def qrexec_download(
|
|
|
|
args: argparse.Namespace,
|
|
|
|
app: qubesadmin.app.QubesBase,
|
|
|
|
spec: str,
|
|
|
|
path: str,
|
|
|
|
dlsize: typing.Optional[int] = None,
|
|
|
|
refresh: bool = False) -> None:
|
|
|
|
"""Download a template from repositories.
|
|
|
|
|
|
|
|
:param args: Arguments received by the application. Specifically,
|
2020-08-18 20:00:19 +02:00
|
|
|
``args.{enablerepo,disablerepo,repoid,releasever,repo_files,updatevm,
|
|
|
|
quiet}`` are used
|
2020-08-05 20:05:57 +02:00
|
|
|
:param app: Qubes application object
|
|
|
|
:param spec: Package spec to query (refer to ``<package-name-spec>`` in the
|
|
|
|
DNF documentation)
|
|
|
|
:param path: Path to place the downloaded template
|
|
|
|
:param dlsize: Size of template to be downloaded. Used for the progress
|
|
|
|
bar. Optional
|
|
|
|
:param refresh: Whether to force refresh repo metadata. Defaults to False
|
|
|
|
|
|
|
|
:raises ConnectionError: if the qrexec call fails
|
|
|
|
"""
|
2020-07-31 20:40:27 +02:00
|
|
|
with open(path, 'wb') as fd:
|
2020-08-03 19:40:59 +02:00
|
|
|
payload = qrexec_payload(args, app, spec, refresh)
|
2020-07-31 20:40:27 +02:00
|
|
|
# Don't filter ESCs for binary files
|
|
|
|
proc = qrexec_popen(args, app, 'qubes.TemplateDownload',
|
|
|
|
stdout=fd, filter_esc=False)
|
|
|
|
proc.stdin.write(payload.encode('UTF-8'))
|
|
|
|
proc.stdin.close()
|
|
|
|
with tqdm.tqdm(desc=spec, total=dlsize, unit_scale=True,
|
2020-08-18 20:00:19 +02:00
|
|
|
unit_divisor=1000, unit='B', disable=args.quiet) as pbar:
|
2020-07-31 20:40:27 +02:00
|
|
|
last = 0
|
|
|
|
while proc.poll() is None:
|
|
|
|
cur = fd.tell()
|
|
|
|
pbar.update(cur - last)
|
|
|
|
last = cur
|
|
|
|
time.sleep(0.1)
|
|
|
|
if proc.wait() != 0:
|
|
|
|
raise ConnectionError(
|
|
|
|
"qrexec call 'qubes.TemplateDownload' failed.")
|
|
|
|
|
2020-08-14 08:27:36 +02:00
|
|
|
def rpm_transactionset(key_dir: str) -> rpm.transaction.TransactionSet:
|
|
|
|
"""Create RPM TransactionSet using the keys in the given directory."""
|
|
|
|
tset = rpm.TransactionSet()
|
|
|
|
kring = rpm.keyring()
|
|
|
|
for name in os.listdir(key_dir):
|
|
|
|
path = os.path.join(key_dir, name)
|
|
|
|
if os.path.isfile(path):
|
|
|
|
with open(path, 'rb') as fd:
|
|
|
|
kring.addKey(rpm.pubkey(fd.read()))
|
|
|
|
tset.setKeyring(kring)
|
|
|
|
return tset
|
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
def verify_rpm(
|
|
|
|
path: str,
|
2020-08-14 08:27:36 +02:00
|
|
|
transaction_set: rpm.transaction.TransactionSet,
|
|
|
|
nogpgcheck: bool = False
|
2020-08-08 08:39:29 +02:00
|
|
|
) -> rpm.hdr:
|
|
|
|
"""Verify the digest and signature of a RPM package and return the package
|
|
|
|
header.
|
2020-08-05 20:05:57 +02:00
|
|
|
|
|
|
|
Note that verifying RPMs this way is prone to TOCTOU. This is okay for
|
|
|
|
local files, but may create problems if multiple instances of
|
|
|
|
**qvm-template** are downloading the same file, so a lock is needed in that
|
|
|
|
case.
|
|
|
|
|
|
|
|
:param path: Location of the RPM package
|
2020-08-14 08:27:36 +02:00
|
|
|
:param transaction_set: RPM ``TransactionSet``
|
2020-08-05 20:05:57 +02:00
|
|
|
:param nogpgcheck: Whether to allow invalid GPG signatures
|
|
|
|
|
2020-08-08 08:39:29 +02:00
|
|
|
:return: RPM package header. If verification fails, ``None`` is returned.
|
2020-08-05 20:05:57 +02:00
|
|
|
"""
|
2020-07-31 20:40:27 +02:00
|
|
|
with open(path, 'rb') as fd:
|
|
|
|
try:
|
|
|
|
hdr = transaction_set.hdrFromFdno(fd)
|
2020-08-08 08:39:29 +02:00
|
|
|
if hdr[rpm.RPMTAG_SIGPGP] is None \
|
2020-07-31 20:40:27 +02:00
|
|
|
and hdr[rpm.RPMTAG_SIGGPG] is None:
|
2020-08-08 08:39:29 +02:00
|
|
|
return hdr if nogpgcheck else None
|
2020-07-31 20:40:27 +02:00
|
|
|
except rpm.error as e:
|
|
|
|
if str(e) == 'public key not trusted' \
|
|
|
|
or str(e) == 'public key not available':
|
2020-09-03 19:56:15 +02:00
|
|
|
# TODO: This does not work
|
|
|
|
# Should just tell TransactionSet not to verify sigs
|
2020-08-08 08:39:29 +02:00
|
|
|
return hdr if nogpgcheck else None
|
|
|
|
return None
|
|
|
|
return hdr
|
2020-07-31 20:40:27 +02:00
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
def extract_rpm(name: str, path: str, target: str) -> bool:
|
|
|
|
"""Extract a template RPM package.
|
|
|
|
|
|
|
|
:param name: Name of the template
|
|
|
|
:param path: Location of the RPM package
|
|
|
|
:param target: Target path to extract to
|
|
|
|
|
|
|
|
:return: Whether the extraction succeeded
|
|
|
|
"""
|
2020-07-31 20:40:27 +02:00
|
|
|
rpm2cpio = subprocess.Popen(['rpm2cpio', path], stdout=subprocess.PIPE)
|
|
|
|
# `-D` is GNUism
|
|
|
|
cpio = subprocess.Popen([
|
|
|
|
'cpio',
|
|
|
|
'-idm',
|
|
|
|
'-D',
|
|
|
|
target,
|
|
|
|
'.%s/%s/*' % (PATH_PREFIX, name)
|
|
|
|
], stdin=rpm2cpio.stdout, stdout=subprocess.DEVNULL)
|
|
|
|
return rpm2cpio.wait() == 0 and cpio.wait() == 0
|
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
def get_dl_list(
|
|
|
|
args: argparse.Namespace,
|
|
|
|
app: qubesadmin.app.QubesBase,
|
|
|
|
version_selector: VersionSelector = VersionSelector.LATEST
|
|
|
|
) -> typing.Dict[str, DlEntry]:
|
|
|
|
"""Return list of templates that needs to be downloaded.
|
|
|
|
|
|
|
|
:param args: Arguments received by the application.
|
|
|
|
:param app: Qubes application object
|
|
|
|
:param version_selector: Specify algorithm to select the candidate version
|
|
|
|
of a package. Defaults to ``VersionSelector.LATEST``
|
|
|
|
|
|
|
|
:return: Dictionary that maps to ``DlEntry`` the names of templates that
|
|
|
|
needs to be downloaded
|
|
|
|
"""
|
|
|
|
full_candid: typing.Dict[str, DlEntry] = {}
|
2020-07-31 20:40:27 +02:00
|
|
|
for template in args.templates:
|
|
|
|
# This will be merged into `full_candid` later.
|
|
|
|
# It is separated so that we can check whether it is empty.
|
2020-08-05 20:05:57 +02:00
|
|
|
candid: typing.Dict[str, DlEntry] = {}
|
2020-07-31 20:40:27 +02:00
|
|
|
|
|
|
|
# Skip local RPMs
|
|
|
|
if template.endswith('.rpm'):
|
|
|
|
continue
|
|
|
|
|
|
|
|
query_res = qrexec_repoquery(args, app, PACKAGE_NAME_PREFIX + template)
|
|
|
|
|
|
|
|
# We only select one package for each distinct package name
|
|
|
|
for entry in query_res:
|
|
|
|
ver = (entry.epoch, entry.version, entry.release)
|
|
|
|
insert = False
|
|
|
|
if version_selector == VersionSelector.LATEST:
|
|
|
|
if entry.name not in candid \
|
|
|
|
or rpm.labelCompare(candid[entry.name][0], ver) < 0:
|
|
|
|
insert = True
|
|
|
|
elif version_selector == VersionSelector.REINSTALL:
|
2020-07-31 21:21:31 +02:00
|
|
|
vm = get_managed_template_vm(app, entry.name)
|
2020-07-31 20:40:27 +02:00
|
|
|
cur_ver = query_local_evr(vm)
|
|
|
|
if rpm.labelCompare(ver, cur_ver) == 0:
|
|
|
|
insert = True
|
|
|
|
elif version_selector in [VersionSelector.LATEST_LOWER,
|
|
|
|
VersionSelector.LATEST_HIGHER]:
|
2020-07-31 21:21:31 +02:00
|
|
|
vm = get_managed_template_vm(app, entry.name)
|
2020-07-31 20:40:27 +02:00
|
|
|
cur_ver = query_local_evr(vm)
|
|
|
|
cmp_res = -1 \
|
|
|
|
if version_selector == VersionSelector.LATEST_LOWER \
|
|
|
|
else 1
|
|
|
|
if rpm.labelCompare(ver, cur_ver) == cmp_res:
|
|
|
|
if entry.name not in candid \
|
|
|
|
or rpm.labelCompare(candid[entry.name][0], ver) < 0:
|
|
|
|
insert = True
|
|
|
|
if insert:
|
|
|
|
candid[entry.name] = DlEntry(ver, entry.reponame, entry.dlsize)
|
|
|
|
|
2020-07-31 21:21:31 +02:00
|
|
|
# XXX: As it's possible to include version information in `template`,
|
|
|
|
# perhaps the messages can be improved
|
2020-07-31 20:40:27 +02:00
|
|
|
if len(candid) == 0:
|
|
|
|
if version_selector == VersionSelector.LATEST:
|
|
|
|
parser.error('Template \'%s\' not found.' % template)
|
|
|
|
elif version_selector == VersionSelector.REINSTALL:
|
|
|
|
parser.error('Same version of template \'%s\' not found.' \
|
|
|
|
% template)
|
|
|
|
# Copy behavior of DNF and do nothing if version not found
|
|
|
|
elif version_selector == VersionSelector.LATEST_LOWER:
|
|
|
|
print(("Template '%s' of lowest version"
|
|
|
|
" already installed, skipping..." % template),
|
|
|
|
file=sys.stderr)
|
|
|
|
elif version_selector == VersionSelector.LATEST_HIGHER:
|
|
|
|
print(("Template '%s' of highest version"
|
|
|
|
" already installed, skipping..." % template),
|
|
|
|
file=sys.stderr)
|
|
|
|
|
|
|
|
# Merge & choose the template with the highest version
|
2020-08-05 20:05:57 +02:00
|
|
|
for name, dlentry in candid.items():
|
2020-07-31 20:40:27 +02:00
|
|
|
if name not in full_candid \
|
2020-08-05 20:05:57 +02:00
|
|
|
or rpm.labelCompare(full_candid[name].evr, dlentry.evr) < 0:
|
|
|
|
full_candid[name] = dlentry
|
2020-07-31 20:40:27 +02:00
|
|
|
|
2020-07-31 21:06:04 +02:00
|
|
|
return full_candid
|
2020-07-31 20:40:27 +02:00
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
def download(
|
|
|
|
args: argparse.Namespace,
|
|
|
|
app: qubesadmin.app.QubesBase,
|
|
|
|
path_override: typing.Optional[str] = None,
|
|
|
|
dl_list: typing.Optional[typing.Dict[str, DlEntry]] = None,
|
|
|
|
suffix: str = '',
|
|
|
|
version_selector: VersionSelector = VersionSelector.LATEST) -> None:
|
|
|
|
"""Command that downloads template packages.
|
|
|
|
|
|
|
|
:param args: Arguments received by the application.
|
|
|
|
:param app: Qubes application object
|
|
|
|
:param path_override: Override path to store downloads. If not set or set
|
|
|
|
to None, ``args.downloaddir`` is used. Optional
|
|
|
|
:param dl_list: Override list of templates to download. If not set or set
|
|
|
|
to None, ``get_dl_list`` is called, which generates the list from
|
|
|
|
``args``. Optional
|
|
|
|
:param suffix: Suffix to add to the file name of downloaded packages. This
|
|
|
|
is useful if you want to distinguish between verified and unverified
|
|
|
|
packages. Defaults to an empty string
|
|
|
|
:param version_selector: Specify algorithm to select the candidate version
|
|
|
|
of a package. Defaults to ``VersionSelector.LATEST``
|
|
|
|
"""
|
2020-07-31 20:40:27 +02:00
|
|
|
if dl_list is None:
|
|
|
|
dl_list = get_dl_list(args, app, version_selector=version_selector)
|
|
|
|
|
|
|
|
path = path_override if path_override is not None else args.downloaddir
|
|
|
|
for name, entry in dl_list.items():
|
|
|
|
version_str = build_version_str(entry.evr)
|
|
|
|
spec = PACKAGE_NAME_PREFIX + name + '-' + version_str
|
|
|
|
target = os.path.join(path, '%s.rpm' % spec)
|
|
|
|
target_suffix = target + suffix
|
|
|
|
if suffix != '' and os.path.exists(target_suffix):
|
|
|
|
print('\'%s\' already exists, skipping...' % target,
|
|
|
|
file=sys.stderr)
|
|
|
|
if os.path.exists(target):
|
|
|
|
print('\'%s\' already exists, skipping...' % target,
|
|
|
|
file=sys.stderr)
|
|
|
|
if suffix != '':
|
|
|
|
os.rename(target, target_suffix)
|
|
|
|
else:
|
|
|
|
print('Downloading \'%s\'...' % spec, file=sys.stderr)
|
|
|
|
done = False
|
|
|
|
for attempt in range(args.retries):
|
|
|
|
try:
|
|
|
|
qrexec_download(args, app, spec, target_suffix,
|
|
|
|
entry.dlsize)
|
|
|
|
done = True
|
|
|
|
break
|
|
|
|
except ConnectionError:
|
|
|
|
os.remove(target_suffix)
|
|
|
|
if attempt + 1 < args.retries:
|
|
|
|
print('\'%s\' download failed, retrying...' % spec,
|
|
|
|
file=sys.stderr)
|
|
|
|
except:
|
|
|
|
# Also remove file if interrupted by other means
|
|
|
|
os.remove(target_suffix)
|
|
|
|
raise
|
|
|
|
if not done:
|
2020-08-07 08:48:08 +02:00
|
|
|
print('Error: \'%s\' download failed.' % spec, file=sys.stderr)
|
2020-07-31 20:40:27 +02:00
|
|
|
sys.exit(1)
|
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
def install(
|
|
|
|
args: argparse.Namespace,
|
|
|
|
app: qubesadmin.app.QubesBase,
|
|
|
|
version_selector: VersionSelector = VersionSelector.LATEST,
|
|
|
|
override_existing: bool = False) -> None:
|
|
|
|
"""Command that installs template packages.
|
|
|
|
|
|
|
|
This command creates a lock file to ensure that two instances are not
|
|
|
|
running at the same time.
|
|
|
|
|
|
|
|
:param args: Arguments received by the application.
|
|
|
|
:param app: Qubes application object
|
|
|
|
:param version_selector: Specify algorithm to select the candidate version
|
|
|
|
of a package. Defaults to ``VersionSelector.LATEST``
|
|
|
|
:param override_existing: Whether to override existing packages. Used for
|
|
|
|
reinstall, upgrade, and downgrade operations
|
|
|
|
"""
|
2020-07-31 20:40:27 +02:00
|
|
|
try:
|
|
|
|
with open(LOCK_FILE, 'x') as _:
|
|
|
|
pass
|
|
|
|
except FileExistsError:
|
|
|
|
parser.error(('%s already exists.'
|
|
|
|
' Perhaps another instance of qvm-template is running?')
|
|
|
|
% LOCK_FILE)
|
|
|
|
|
|
|
|
try:
|
2020-08-14 08:27:36 +02:00
|
|
|
transaction_set = rpm_transactionset(args.keyring)
|
2020-07-31 20:40:27 +02:00
|
|
|
|
2020-08-08 08:39:29 +02:00
|
|
|
unverified_rpm_list = [] # rpmfile, reponame
|
|
|
|
verified_rpm_list = []
|
|
|
|
def verify(rpmfile, reponame):
|
|
|
|
"""Verify package signature and version, remove "unverified"
|
|
|
|
suffix, and parse package header."""
|
|
|
|
if reponame != '@commandline':
|
|
|
|
path = rpmfile + UNVERIFIED_SUFFIX
|
|
|
|
else:
|
|
|
|
path = rpmfile
|
|
|
|
|
2020-08-14 08:27:36 +02:00
|
|
|
package_hdr = verify_rpm(path, transaction_set, args.nogpgcheck)
|
2020-08-08 08:39:29 +02:00
|
|
|
if not package_hdr:
|
|
|
|
parser.error('Package \'%s\' verification failed.' % rpmfile)
|
|
|
|
|
|
|
|
package_name = package_hdr[rpm.RPMTAG_NAME]
|
|
|
|
if not package_name.startswith(PACKAGE_NAME_PREFIX):
|
|
|
|
parser.error(
|
|
|
|
'Illegal package name for package \'%s\'.' % rpmfile)
|
|
|
|
# Remove prefix to get the real template name
|
|
|
|
name = package_name[len(PACKAGE_NAME_PREFIX):]
|
|
|
|
|
2020-08-09 19:30:31 +02:00
|
|
|
if path != rpmfile:
|
|
|
|
os.rename(path, rpmfile)
|
|
|
|
|
2020-08-08 08:39:29 +02:00
|
|
|
# Check if already installed
|
|
|
|
if not override_existing and name in app.domains:
|
|
|
|
print(('Template \'%s\' already installed, skipping...'
|
|
|
|
' (You may want to use the'
|
|
|
|
' {reinstall,upgrade,downgrade}'
|
|
|
|
' operations.)') % name, file=sys.stderr)
|
|
|
|
return
|
|
|
|
|
|
|
|
# Check if version is really what we want
|
|
|
|
if override_existing:
|
|
|
|
vm = get_managed_template_vm(app, name)
|
|
|
|
pkg_evr = (
|
|
|
|
str(package_hdr[rpm.RPMTAG_EPOCHNUM]),
|
|
|
|
package_hdr[rpm.RPMTAG_VERSION],
|
|
|
|
package_hdr[rpm.RPMTAG_RELEASE])
|
|
|
|
vm_evr = query_local_evr(vm)
|
|
|
|
cmp_res = rpm.labelCompare(pkg_evr, vm_evr)
|
|
|
|
if version_selector == VersionSelector.REINSTALL \
|
|
|
|
and cmp_res != 0:
|
|
|
|
parser.error(
|
|
|
|
'Same version of template \'%s\' not found.' \
|
|
|
|
% name)
|
|
|
|
elif version_selector == VersionSelector.LATEST_LOWER \
|
|
|
|
and cmp_res != -1:
|
|
|
|
print(("Template '%s' of lower version"
|
|
|
|
" already installed, skipping..." % name),
|
|
|
|
file=sys.stderr)
|
|
|
|
return
|
|
|
|
elif version_selector == VersionSelector.LATEST_HIGHER \
|
|
|
|
and cmp_res != 1:
|
|
|
|
print(("Template '%s' of higher version"
|
|
|
|
" already installed, skipping..." % name),
|
|
|
|
file=sys.stderr)
|
|
|
|
return
|
|
|
|
|
|
|
|
verified_rpm_list.append((rpmfile, reponame, name, package_hdr))
|
|
|
|
|
|
|
|
# Process local templates
|
2020-07-31 20:40:27 +02:00
|
|
|
for template in args.templates:
|
|
|
|
if template.endswith('.rpm'):
|
|
|
|
if not os.path.exists(template):
|
|
|
|
parser.error('RPM file \'%s\' not found.' % template)
|
2020-08-08 08:39:29 +02:00
|
|
|
unverified_rpm_list.append((template, '@commandline'))
|
|
|
|
|
|
|
|
# First verify local RPMs and extract header
|
|
|
|
for rpmfile, reponame in unverified_rpm_list:
|
|
|
|
verify(rpmfile, reponame)
|
|
|
|
unverified_rpm_list = []
|
2020-07-31 20:40:27 +02:00
|
|
|
|
|
|
|
os.makedirs(args.cachedir, exist_ok=True)
|
|
|
|
|
2020-08-08 08:39:29 +02:00
|
|
|
# Get list of templates to download
|
2020-07-31 20:40:27 +02:00
|
|
|
dl_list = get_dl_list(args, app, version_selector=version_selector)
|
|
|
|
dl_list_copy = dl_list.copy()
|
|
|
|
for name, entry in dl_list.items():
|
|
|
|
# Should be ensured by checks in repoquery
|
|
|
|
assert entry.reponame != '@commandline'
|
2020-08-08 08:39:29 +02:00
|
|
|
# Verify that the templates to be downloaded are not yet installed
|
|
|
|
# Note that we *still* have to do this again in verify() for
|
|
|
|
# already-downloaded templates
|
2020-07-31 20:40:27 +02:00
|
|
|
if not override_existing and name in app.domains:
|
|
|
|
print(('Template \'%s\' already installed, skipping...'
|
2020-07-31 21:21:31 +02:00
|
|
|
' (You may want to use the'
|
|
|
|
' {reinstall,upgrade,downgrade}'
|
2020-07-31 20:40:27 +02:00
|
|
|
' operations.)') % name, file=sys.stderr)
|
|
|
|
del dl_list_copy[name]
|
|
|
|
else:
|
2020-08-08 08:39:29 +02:00
|
|
|
# XXX: Perhaps this is better returned by download()
|
2020-07-31 20:40:27 +02:00
|
|
|
version_str = build_version_str(entry.evr)
|
|
|
|
target_file = \
|
|
|
|
'%s%s-%s.rpm' % (PACKAGE_NAME_PREFIX, name, version_str)
|
2020-08-08 08:39:29 +02:00
|
|
|
unverified_rpm_list.append(
|
2020-07-31 20:56:59 +02:00
|
|
|
(os.path.join(args.cachedir, target_file), entry.reponame))
|
2020-07-31 20:40:27 +02:00
|
|
|
dl_list = dl_list_copy
|
|
|
|
|
2020-08-08 08:39:29 +02:00
|
|
|
# Ask the user for confirmation before we actually download stuff
|
|
|
|
if override_existing and not args.yes:
|
|
|
|
override_tpls = []
|
|
|
|
# Local templates, already verified
|
|
|
|
for _, _, name, _ in verified_rpm_list:
|
|
|
|
override_tpls.append(name)
|
|
|
|
# Templates not yet downloaded
|
|
|
|
for name in dl_list:
|
|
|
|
override_tpls.append(name)
|
|
|
|
|
2020-08-14 05:38:30 +02:00
|
|
|
confirm_action(
|
|
|
|
'This will override changes made in the following VMs:',
|
|
|
|
override_tpls)
|
2020-08-08 08:39:29 +02:00
|
|
|
|
2020-07-31 20:40:27 +02:00
|
|
|
download(args, app, path_override=args.cachedir,
|
|
|
|
dl_list=dl_list, suffix=UNVERIFIED_SUFFIX,
|
|
|
|
version_selector=version_selector)
|
|
|
|
|
2020-08-08 08:39:29 +02:00
|
|
|
# Verify downloaded templates
|
|
|
|
for rpmfile, reponame in unverified_rpm_list:
|
|
|
|
verify(rpmfile, reponame)
|
|
|
|
unverified_rpm_list = []
|
2020-07-31 20:40:27 +02:00
|
|
|
|
|
|
|
# Unpack and install
|
2020-08-08 08:39:29 +02:00
|
|
|
for rpmfile, reponame, name, package_hdr in verified_rpm_list:
|
2020-07-31 20:40:27 +02:00
|
|
|
with tempfile.TemporaryDirectory(dir=TEMP_DIR) as target:
|
|
|
|
print('Installing template \'%s\'...' % name, file=sys.stderr)
|
2020-09-03 19:56:15 +02:00
|
|
|
# TODO: Handle return value
|
2020-07-31 20:40:27 +02:00
|
|
|
extract_rpm(name, rpmfile, target)
|
|
|
|
cmdline = [
|
|
|
|
'qvm-template-postprocess',
|
|
|
|
'--really',
|
|
|
|
'--no-installed-by-rpm',
|
|
|
|
]
|
|
|
|
if args.allow_pv:
|
|
|
|
cmdline.append('--allow-pv')
|
2020-08-08 08:39:29 +02:00
|
|
|
if not override_existing and args.pool:
|
2020-07-31 20:40:27 +02:00
|
|
|
cmdline += ['--pool', args.pool]
|
|
|
|
subprocess.check_call(cmdline + [
|
|
|
|
'post-install',
|
|
|
|
name,
|
|
|
|
target + PATH_PREFIX + '/' + name])
|
2020-07-08 20:23:19 +02:00
|
|
|
|
2020-07-31 20:40:27 +02:00
|
|
|
app.domains.refresh_cache(force=True)
|
|
|
|
tpl = app.domains[name]
|
|
|
|
|
|
|
|
tpl.features['template-name'] = name
|
|
|
|
tpl.features['template-epoch'] = \
|
|
|
|
package_hdr[rpm.RPMTAG_EPOCHNUM]
|
|
|
|
tpl.features['template-version'] = \
|
|
|
|
package_hdr[rpm.RPMTAG_VERSION]
|
|
|
|
tpl.features['template-release'] = \
|
|
|
|
package_hdr[rpm.RPMTAG_RELEASE]
|
|
|
|
tpl.features['template-reponame'] = reponame
|
|
|
|
tpl.features['template-buildtime'] = \
|
2020-09-06 17:57:42 +02:00
|
|
|
datetime.datetime.fromtimestamp(
|
|
|
|
int(package_hdr[rpm.RPMTAG_BUILDTIME]),
|
|
|
|
tz=datetime.timezone.utc) \
|
|
|
|
.strftime(DATE_FMT)
|
2020-08-29 20:01:19 +02:00
|
|
|
tpl.features['template-installtime'] = \
|
2020-09-06 17:57:42 +02:00
|
|
|
datetime.datetime.today(
|
|
|
|
tz=datetime.timezone.utc).strftime(DATE_FMT)
|
2020-07-31 20:40:27 +02:00
|
|
|
tpl.features['template-license'] = \
|
|
|
|
package_hdr[rpm.RPMTAG_LICENSE]
|
|
|
|
tpl.features['template-url'] = \
|
|
|
|
package_hdr[rpm.RPMTAG_URL]
|
|
|
|
tpl.features['template-summary'] = \
|
|
|
|
package_hdr[rpm.RPMTAG_SUMMARY]
|
|
|
|
tpl.features['template-description'] = \
|
|
|
|
package_hdr[rpm.RPMTAG_DESCRIPTION].replace('\n', '|')
|
|
|
|
finally:
|
|
|
|
os.remove(LOCK_FILE)
|
2020-07-19 19:08:40 +02:00
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
def list_templates(args: argparse.Namespace,
|
|
|
|
app: qubesadmin.app.QubesBase, operation: str) -> None:
|
|
|
|
"""Command that lists templates.
|
|
|
|
|
|
|
|
:param args: Arguments received by the application.
|
|
|
|
:param app: Qubes application object
|
|
|
|
:param operation: If set to ``list``, display a listing similar to ``dnf
|
|
|
|
list``. If set to ``info``, display detailed template information
|
|
|
|
similar to ``dnf info``. Otherwise, an ``AssertionError`` is raised.
|
|
|
|
"""
|
2020-07-08 20:23:19 +02:00
|
|
|
tpl_list = []
|
|
|
|
|
2020-07-29 12:36:02 +02:00
|
|
|
def append_list(data, status, install_time=None):
|
|
|
|
_ = install_time # unused
|
2020-07-31 20:24:29 +02:00
|
|
|
version_str = build_version_str(
|
|
|
|
(data.epoch, data.version, data.release))
|
|
|
|
tpl_list.append((status, data.name, version_str, data.reponame))
|
2020-07-20 20:04:55 +02:00
|
|
|
|
2020-07-29 12:36:02 +02:00
|
|
|
def append_info(data, status, install_time=None):
|
2020-08-05 20:42:05 +02:00
|
|
|
tpl_list.append((status, data, install_time))
|
|
|
|
|
2020-08-18 19:59:51 +02:00
|
|
|
def list_to_human_output(tpls):
|
2020-08-06 20:10:57 +02:00
|
|
|
outputs = []
|
|
|
|
for status, grp in itertools.groupby(tpls, lambda x: x[0]):
|
2020-08-18 19:59:51 +02:00
|
|
|
def convert(row):
|
|
|
|
return row[1:]
|
|
|
|
outputs.append((status, list(map(convert, grp))))
|
|
|
|
return outputs
|
|
|
|
|
|
|
|
def list_to_machine_output(tpls):
|
|
|
|
outputs = {}
|
|
|
|
for status, grp in itertools.groupby(tpls, lambda x: x[0]):
|
|
|
|
def convert(row):
|
|
|
|
_, name, evr, reponame = row
|
|
|
|
return {'name': name, 'evr': evr, 'reponame': reponame}
|
|
|
|
outputs[status.value] = list(map(convert, grp))
|
2020-08-06 20:10:57 +02:00
|
|
|
return outputs
|
|
|
|
|
2020-08-05 20:42:05 +02:00
|
|
|
def info_to_human_output(tpls):
|
2020-08-06 20:10:57 +02:00
|
|
|
outputs = []
|
|
|
|
for status, grp in itertools.groupby(tpls, lambda x: x[0]):
|
|
|
|
output = []
|
|
|
|
for _, data, install_time in grp:
|
|
|
|
output.append(('Name', ':', data.name))
|
|
|
|
output.append(('Epoch', ':', data.epoch))
|
|
|
|
output.append(('Version', ':', data.version))
|
|
|
|
output.append(('Release', ':', data.release))
|
|
|
|
output.append(('Size', ':',
|
|
|
|
qubesadmin.utils.size_to_human(data.dlsize)))
|
|
|
|
output.append(('Repository', ':', data.reponame))
|
|
|
|
output.append(('Buildtime', ':', str(data.buildtime)))
|
|
|
|
if install_time:
|
|
|
|
output.append(('Install time', ':', str(install_time)))
|
|
|
|
output.append(('URL', ':', data.url))
|
|
|
|
output.append(('License', ':', data.licence))
|
|
|
|
output.append(('Summary', ':', data.summary))
|
|
|
|
# Only show "Description" for the first line
|
|
|
|
title = 'Description'
|
|
|
|
for line in data.description.splitlines():
|
|
|
|
output.append((title, ':', line))
|
|
|
|
title = ''
|
|
|
|
output.append((' ', ' ', ' ')) # empty line
|
|
|
|
outputs.append((status, output))
|
|
|
|
return outputs
|
2020-08-05 20:42:05 +02:00
|
|
|
|
2020-08-06 20:14:37 +02:00
|
|
|
def info_to_machine_output(tpls, replace_newline=True):
|
2020-08-18 19:59:51 +02:00
|
|
|
outputs = {}
|
2020-08-06 20:10:57 +02:00
|
|
|
for status, grp in itertools.groupby(tpls, lambda x: x[0]):
|
|
|
|
output = []
|
|
|
|
for _, data, install_time in grp:
|
|
|
|
name, epoch, version, release, reponame, dlsize, \
|
|
|
|
buildtime, licence, url, summary, description = data
|
|
|
|
dlsize = str(dlsize)
|
2020-09-06 17:57:42 +02:00
|
|
|
buildtime = buildtime.strftime(DATE_FMT)
|
2020-09-06 20:12:22 +02:00
|
|
|
install_time = install_time.strftime(DATE_FMT) \
|
|
|
|
if install_time else ''
|
2020-08-06 20:14:37 +02:00
|
|
|
if replace_newline:
|
|
|
|
description = description.replace('\n', '|')
|
2020-08-18 19:59:51 +02:00
|
|
|
output.append({
|
|
|
|
'name': name,
|
|
|
|
'epoch': epoch,
|
|
|
|
'version': version,
|
|
|
|
'release': release,
|
|
|
|
'reponame': reponame,
|
|
|
|
'size': dlsize,
|
|
|
|
'buildtime': buildtime,
|
|
|
|
'installtime': install_time,
|
|
|
|
'license': licence,
|
|
|
|
'url': url,
|
|
|
|
'summary': summary,
|
|
|
|
'description': description})
|
|
|
|
outputs[status.value] = output
|
2020-08-06 20:10:57 +02:00
|
|
|
return outputs
|
2020-07-20 20:04:55 +02:00
|
|
|
|
|
|
|
if operation == 'list':
|
|
|
|
append = append_list
|
|
|
|
elif operation == 'info':
|
|
|
|
append = append_info
|
|
|
|
else:
|
|
|
|
assert False and 'Unknown operation'
|
|
|
|
|
|
|
|
def append_vm(vm, status):
|
2020-08-29 20:01:19 +02:00
|
|
|
append(query_local(vm), status, vm.features['template-installtime'])
|
2020-07-20 20:04:55 +02:00
|
|
|
|
2020-07-08 20:23:19 +02:00
|
|
|
if not (args.installed or args.available or args.extras or args.upgrades):
|
|
|
|
args.all = True
|
|
|
|
|
2020-07-09 20:43:03 +02:00
|
|
|
if args.all or args.available or args.extras or args.upgrades:
|
2020-07-19 19:08:40 +02:00
|
|
|
if args.templates:
|
2020-08-05 20:05:57 +02:00
|
|
|
query_res_set: typing.Set[Template] = set()
|
2020-07-19 19:08:40 +02:00
|
|
|
for spec in args.templates:
|
2020-08-05 20:05:57 +02:00
|
|
|
query_res_set |= set(qrexec_repoquery(args, app, spec))
|
|
|
|
query_res = list(query_res_set)
|
2020-07-19 19:08:40 +02:00
|
|
|
else:
|
|
|
|
query_res = qrexec_repoquery(args, app)
|
2020-07-09 20:43:03 +02:00
|
|
|
|
2020-07-08 20:23:19 +02:00
|
|
|
if args.installed or args.all:
|
|
|
|
for vm in app.domains:
|
2020-07-31 20:24:29 +02:00
|
|
|
if is_managed_template(vm):
|
2020-07-19 19:08:40 +02:00
|
|
|
if not args.templates or \
|
|
|
|
any(is_match_spec(
|
2020-07-31 21:21:31 +02:00
|
|
|
vm.name,
|
2020-07-31 20:24:29 +02:00
|
|
|
*query_local_evr(vm),
|
|
|
|
spec)[0]
|
|
|
|
for spec in args.templates):
|
2020-07-20 20:04:55 +02:00
|
|
|
append_vm(vm, TemplateState.INSTALLED)
|
2020-07-08 20:23:19 +02:00
|
|
|
|
|
|
|
if args.available or args.all:
|
2020-07-20 20:04:55 +02:00
|
|
|
for data in query_res:
|
|
|
|
append(data, TemplateState.AVAILABLE)
|
2020-07-08 20:23:19 +02:00
|
|
|
|
|
|
|
if args.extras:
|
|
|
|
remote = set()
|
2020-07-31 20:24:29 +02:00
|
|
|
for data in query_res:
|
|
|
|
remote.add(data.name)
|
2020-07-08 20:23:19 +02:00
|
|
|
for vm in app.domains:
|
2020-07-31 21:21:31 +02:00
|
|
|
if is_managed_template(vm) and vm.name not in remote:
|
2020-07-20 20:04:55 +02:00
|
|
|
append_vm(vm, TemplateState.EXTRA)
|
2020-07-08 20:23:19 +02:00
|
|
|
|
|
|
|
if args.upgrades:
|
|
|
|
local = {}
|
|
|
|
for vm in app.domains:
|
2020-07-31 20:24:29 +02:00
|
|
|
if is_managed_template(vm):
|
2020-07-31 21:21:31 +02:00
|
|
|
local[vm.name] = query_local_evr(vm)
|
2020-07-31 20:24:29 +02:00
|
|
|
for entry in query_res:
|
|
|
|
if entry.name in local:
|
|
|
|
if rpm.labelCompare(local[entry.name],
|
|
|
|
(entry.epoch, entry.version, entry.release)) < 0:
|
|
|
|
append(entry, TemplateState.UPGRADABLE)
|
2020-07-20 20:04:55 +02:00
|
|
|
|
|
|
|
if len(tpl_list) == 0:
|
|
|
|
parser.error('No matching templates to list')
|
2020-07-08 20:23:19 +02:00
|
|
|
|
2020-08-18 19:59:51 +02:00
|
|
|
if args.machine_readable:
|
2020-08-05 20:42:05 +02:00
|
|
|
if operation == 'info':
|
2020-08-18 19:59:51 +02:00
|
|
|
tpl_list = info_to_machine_output(tpl_list)
|
2020-08-06 20:10:57 +02:00
|
|
|
elif operation == 'list':
|
2020-08-18 19:59:51 +02:00
|
|
|
tpl_list = list_to_machine_output(tpl_list)
|
|
|
|
for status, grp in tpl_list.items():
|
|
|
|
for line in grp:
|
2020-08-25 19:31:33 +02:00
|
|
|
print('|'.join([status] + list(line.values())))
|
2020-08-18 19:59:51 +02:00
|
|
|
elif args.machine_readable_json:
|
|
|
|
if operation == 'info':
|
|
|
|
tpl_list = info_to_machine_output(tpl_list, replace_newline=False)
|
|
|
|
elif operation == 'list':
|
|
|
|
tpl_list = list_to_machine_output(tpl_list)
|
|
|
|
print(json.dumps(tpl_list))
|
2020-08-05 20:42:05 +02:00
|
|
|
else:
|
|
|
|
if operation == 'info':
|
2020-08-18 19:59:51 +02:00
|
|
|
tpl_list = info_to_human_output(tpl_list)
|
2020-08-06 20:10:57 +02:00
|
|
|
elif operation == 'list':
|
2020-08-18 19:59:51 +02:00
|
|
|
tpl_list = list_to_human_output(tpl_list)
|
2020-08-06 20:10:57 +02:00
|
|
|
for status, grp in tpl_list:
|
2020-08-18 19:59:51 +02:00
|
|
|
print(status.title())
|
|
|
|
qubesadmin.tools.print_table(grp)
|
2020-07-20 20:04:55 +02:00
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
def search(args: argparse.Namespace, app: qubesadmin.app.QubesBase) -> None:
|
|
|
|
"""Command that searches template details for given patterns.
|
|
|
|
|
|
|
|
:param args: Arguments received by the application.
|
|
|
|
:param app: Qubes application object
|
|
|
|
"""
|
2020-07-21 13:34:16 +02:00
|
|
|
# Search in both installed and available templates
|
|
|
|
query_res = qrexec_repoquery(args, app)
|
|
|
|
for vm in app.domains:
|
2020-07-31 20:24:29 +02:00
|
|
|
if is_managed_template(vm):
|
|
|
|
query_res.append(query_local(vm))
|
2020-07-21 13:34:16 +02:00
|
|
|
|
|
|
|
# Get latest version for each template
|
|
|
|
query_res_tmp = []
|
2020-07-31 20:56:59 +02:00
|
|
|
for _, grp in itertools.groupby(sorted(query_res), lambda x: x[0]):
|
2020-07-21 13:34:16 +02:00
|
|
|
def compare(lhs, rhs):
|
|
|
|
return lhs if rpm.labelCompare(lhs[1:4], rhs[1:4]) < 0 else rhs
|
|
|
|
query_res_tmp.append(functools.reduce(compare, grp))
|
|
|
|
query_res = query_res_tmp
|
|
|
|
|
|
|
|
#pylint: disable=invalid-name
|
2020-07-29 12:36:02 +02:00
|
|
|
WEIGHT_NAME_EXACT = 1 << 4
|
|
|
|
WEIGHT_NAME = 1 << 3
|
|
|
|
WEIGHT_SUMMARY = 1 << 2
|
|
|
|
WEIGHT_DESCRIPTION = 1 << 1
|
|
|
|
WEIGHT_URL = 1 << 0
|
|
|
|
|
|
|
|
WEIGHT_TO_FIELD = [
|
|
|
|
(WEIGHT_NAME_EXACT, 'Name'),
|
|
|
|
(WEIGHT_NAME, 'Name'),
|
|
|
|
(WEIGHT_SUMMARY, 'Summary'),
|
|
|
|
(WEIGHT_DESCRIPTION, 'Description'),
|
|
|
|
(WEIGHT_URL, 'URL')]
|
2020-07-21 13:34:16 +02:00
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
search_res_by_idx: \
|
|
|
|
typing.Dict[int, typing.List[typing.Tuple[int, str, bool]]] = \
|
|
|
|
collections.defaultdict(list)
|
2020-07-21 13:34:16 +02:00
|
|
|
for keyword in args.templates:
|
2020-07-31 20:24:29 +02:00
|
|
|
for idx, entry in enumerate(query_res):
|
2020-08-05 20:05:57 +02:00
|
|
|
needle_types = \
|
2020-07-31 20:24:29 +02:00
|
|
|
[(entry.name, WEIGHT_NAME), (entry.summary, WEIGHT_SUMMARY)]
|
2020-07-29 12:36:02 +02:00
|
|
|
if args.all:
|
2020-08-05 20:05:57 +02:00
|
|
|
needle_types += [(entry.description, WEIGHT_DESCRIPTION),
|
2020-07-31 20:24:29 +02:00
|
|
|
(entry.url, WEIGHT_URL)]
|
2020-08-05 20:05:57 +02:00
|
|
|
for key, weight in needle_types:
|
2020-07-29 12:36:02 +02:00
|
|
|
if fnmatch.fnmatch(key, '*' + keyword + '*'):
|
|
|
|
exact = keyword == key
|
|
|
|
if exact and weight == WEIGHT_NAME:
|
|
|
|
weight = WEIGHT_NAME_EXACT
|
2020-08-05 20:05:57 +02:00
|
|
|
search_res_by_idx[idx].append((weight, keyword, exact))
|
2020-07-29 12:36:02 +02:00
|
|
|
|
2020-07-25 20:11:57 +02:00
|
|
|
if not args.all:
|
|
|
|
keywords = set(args.templates)
|
2020-08-05 20:05:57 +02:00
|
|
|
idxs = list(search_res_by_idx.keys())
|
2020-07-25 20:11:57 +02:00
|
|
|
for idx in idxs:
|
2020-08-05 20:05:57 +02:00
|
|
|
if keywords != set(x[1] for x in search_res_by_idx[idx]):
|
|
|
|
del search_res_by_idx[idx]
|
2020-07-21 13:34:16 +02:00
|
|
|
|
|
|
|
def key_func(x):
|
2020-07-25 20:11:57 +02:00
|
|
|
# ORDER BY weight DESC, list_of_needles ASC, name ASC
|
|
|
|
idx, needles = x
|
|
|
|
weight = sum(t[0] for t in needles)
|
|
|
|
name = query_res[idx][0]
|
|
|
|
return (-weight, needles, name)
|
2020-07-21 13:34:16 +02:00
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
search_res = sorted(search_res_by_idx.items(), key=key_func)
|
2020-07-21 13:34:16 +02:00
|
|
|
|
2020-07-31 20:56:59 +02:00
|
|
|
def gen_header(needles):
|
2020-07-25 20:11:57 +02:00
|
|
|
fields = []
|
|
|
|
weight_types = set(x[0] for x in needles)
|
2020-07-29 12:36:02 +02:00
|
|
|
for weight, field in WEIGHT_TO_FIELD:
|
|
|
|
if weight in weight_types:
|
|
|
|
fields.append(field)
|
2020-07-25 20:11:57 +02:00
|
|
|
exact = all(x[-1] for x in needles)
|
|
|
|
match = 'Exactly Matched' if exact else 'Matched'
|
|
|
|
keywords = sorted(list(set(x[1] for x in needles)))
|
|
|
|
return ' & '.join(fields) + ' ' + match + ': ' + ', '.join(keywords)
|
|
|
|
|
|
|
|
last_header = ''
|
|
|
|
for idx, needles in search_res:
|
|
|
|
# Print headers
|
2020-07-31 20:56:59 +02:00
|
|
|
cur_header = gen_header(needles)
|
2020-07-25 20:11:57 +02:00
|
|
|
if last_header != cur_header:
|
|
|
|
last_header = cur_header
|
2020-07-21 13:34:16 +02:00
|
|
|
# XXX: The style is different from that of DNF
|
2020-07-25 20:11:57 +02:00
|
|
|
print('===', cur_header, '===')
|
2020-07-31 20:24:29 +02:00
|
|
|
print(query_res[idx].name, ':', query_res[idx].summary)
|
2020-07-08 20:23:19 +02:00
|
|
|
|
2020-08-14 05:38:30 +02:00
|
|
|
def remove(
|
|
|
|
args: argparse.Namespace,
|
|
|
|
app: qubesadmin.app.QubesBase,
|
|
|
|
disassoc: bool = False,
|
|
|
|
purge: bool = False,
|
|
|
|
dummy: str = 'dummy'
|
|
|
|
) -> None:
|
2020-08-05 20:05:57 +02:00
|
|
|
"""Command that remove templates.
|
|
|
|
|
|
|
|
:param args: Arguments received by the application.
|
|
|
|
:param app: Qubes application object
|
2020-08-14 05:38:30 +02:00
|
|
|
:param disassoc: Whether to disassociate VMs from the templates
|
|
|
|
:param purge: Whether to remove VMs based on the templates
|
|
|
|
:param dummy: Name of dummy VM if disassoc is used
|
2020-08-05 20:05:57 +02:00
|
|
|
"""
|
2020-08-14 05:38:30 +02:00
|
|
|
# NOTE: While QubesArgumentParser provide similar functionality
|
|
|
|
# it does not seem to work as a parent parser
|
|
|
|
for tpl in args.templates:
|
|
|
|
if tpl not in app.domains:
|
|
|
|
parser.error("no such domain: '%s'" % tpl)
|
|
|
|
|
|
|
|
remove_list = args.templates
|
|
|
|
if purge:
|
|
|
|
# Not disassociating first may result in dependency ordering issues
|
|
|
|
disassoc = True
|
|
|
|
# Remove recursively via BFS
|
|
|
|
remove_set = set(remove_list) # visited
|
|
|
|
idx = 0
|
|
|
|
while idx < len(remove_list):
|
|
|
|
tpl = remove_list[idx]
|
|
|
|
idx += 1
|
|
|
|
vm = app.domains[tpl]
|
|
|
|
for holder, prop in qubesadmin.utils.vm_dependencies(app, vm):
|
|
|
|
if holder is not None and holder.name not in remove_set:
|
|
|
|
remove_list.append(holder.name)
|
|
|
|
remove_set.add(holder.name)
|
|
|
|
|
|
|
|
if not args.yes:
|
|
|
|
repeat = 3 if purge else 1
|
|
|
|
for _ in range(repeat):
|
|
|
|
confirm_action(
|
|
|
|
'This will completely remove the selected VM(s)...',
|
|
|
|
remove_list)
|
|
|
|
|
|
|
|
if disassoc:
|
|
|
|
# Remove the dummy afterwards if we're purging
|
|
|
|
remove_dummy = purge
|
|
|
|
# Create dummy template; handle name collisions
|
|
|
|
orig_dummy = dummy
|
|
|
|
cnt = 1
|
|
|
|
while dummy in app.domains \
|
2020-08-24 19:43:11 +02:00
|
|
|
and app.domains[dummy].features.get(
|
|
|
|
'template-dummy', '0') == '0':
|
2020-08-14 05:38:30 +02:00
|
|
|
dummy = '%s-%d' % (orig_dummy, cnt)
|
|
|
|
cnt += 1
|
|
|
|
if dummy not in app.domains:
|
|
|
|
dummy_vm = app.add_new_vm('TemplateVM', dummy, 'red')
|
2020-08-24 19:43:11 +02:00
|
|
|
dummy_vm.features['template-dummy'] = 1
|
2020-08-14 05:38:30 +02:00
|
|
|
else:
|
|
|
|
dummy_vm = app.domains[dummy]
|
|
|
|
|
|
|
|
for tpl in remove_list:
|
|
|
|
vm = app.domains[tpl]
|
|
|
|
for holder, prop in qubesadmin.utils.vm_dependencies(app, vm):
|
|
|
|
if holder:
|
|
|
|
setattr(holder, prop, dummy_vm)
|
|
|
|
holder.template = dummy_vm
|
|
|
|
print("Property '%s' of '%s' set to '%s'." % (
|
|
|
|
prop, holder.name, dummy), file=sys.stderr)
|
|
|
|
else:
|
|
|
|
print("Global property '%s' set to ''." % prop,
|
|
|
|
file=sys.stderr)
|
|
|
|
setattr(app, prop, '')
|
|
|
|
if remove_dummy:
|
|
|
|
remove_list.append(dummy)
|
2020-07-20 20:04:55 +02:00
|
|
|
|
2020-08-14 05:38:30 +02:00
|
|
|
if disassoc or purge:
|
|
|
|
qubesadmin.tools.qvm_kill.main(['--'] + remove_list, app)
|
|
|
|
qubesadmin.tools.qvm_remove.main(['--force', '--'] + remove_list, app)
|
2020-07-08 20:23:19 +02:00
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
def clean(args: argparse.Namespace, app: qubesadmin.app.QubesBase) -> None:
|
|
|
|
"""Command that cleans the local package cache.
|
|
|
|
|
|
|
|
:param args: Arguments received by the application.
|
|
|
|
:param app: Qubes application object
|
|
|
|
"""
|
2020-07-08 20:23:19 +02:00
|
|
|
# TODO: More fine-grained options
|
2020-07-11 17:12:57 +02:00
|
|
|
_ = app # unused
|
|
|
|
|
2020-07-08 20:23:19 +02:00
|
|
|
shutil.rmtree(args.cachedir)
|
|
|
|
|
2020-08-07 08:48:08 +02:00
|
|
|
def repolist(args: argparse.Namespace, app: qubesadmin.app.QubesBase) -> None:
|
|
|
|
"""Command that lists configured repositories.
|
|
|
|
|
|
|
|
:param args: Arguments received by the application.
|
|
|
|
:param app: Qubes application object
|
|
|
|
"""
|
|
|
|
_ = app # unused
|
|
|
|
|
|
|
|
# python-dnf is not packaged on Debian
|
|
|
|
# As this is not an "essential operation", the module is imported here
|
|
|
|
# instead of top-level so that other operations still work.
|
|
|
|
try:
|
|
|
|
import dnf
|
|
|
|
except ModuleNotFoundError:
|
|
|
|
print("Error: Python module 'dnf' not found.", file=sys.stderr)
|
|
|
|
sys.exit(1)
|
|
|
|
|
|
|
|
if not args.all and not args.disabled:
|
|
|
|
args.enabled = True
|
|
|
|
|
|
|
|
with tempfile.TemporaryDirectory(dir=TEMP_DIR) as reposdir:
|
|
|
|
for idx, path in enumerate(args.repo_files):
|
|
|
|
src = os.path.abspath(path)
|
|
|
|
# Use index as file name in case of collisions
|
|
|
|
dst = os.path.join(reposdir, '%d.repo' % idx)
|
|
|
|
os.symlink(src, dst)
|
|
|
|
conf = dnf.conf.Conf()
|
|
|
|
conf.substitutions['releasever'] = args.releasever
|
|
|
|
conf.reposdir = reposdir
|
|
|
|
base = dnf.Base(conf)
|
|
|
|
base.read_all_repos()
|
|
|
|
if args.repoid:
|
|
|
|
base.repos.get_matching('*').disable()
|
|
|
|
for repo in args.repoid:
|
|
|
|
base.repos.get_matching(repo).enable()
|
|
|
|
else:
|
|
|
|
for repo in args.enablerepo:
|
|
|
|
base.repos.get_matching(repo).enable()
|
|
|
|
for repo in args.disablerepo:
|
|
|
|
base.repos.get_matching(repo).disable()
|
|
|
|
|
2020-08-08 09:31:25 +02:00
|
|
|
repos: typing.List[dnf.repo.Repo]
|
2020-08-07 08:48:08 +02:00
|
|
|
if args.repos:
|
|
|
|
repos = []
|
|
|
|
for repo in args.repos:
|
|
|
|
repos += list(base.repos.get_matching(repo))
|
|
|
|
repos = list(set(repos))
|
|
|
|
repos.sort(key=operator.attrgetter('id'))
|
|
|
|
else:
|
|
|
|
repos = list(base.repos.values())
|
|
|
|
repos.sort(key=operator.attrgetter('id'))
|
|
|
|
|
|
|
|
table = []
|
|
|
|
for repo in repos:
|
|
|
|
if args.all or (args.enabled == repo.enabled):
|
|
|
|
state = 'enabled' if repo.enabled else 'disabled'
|
|
|
|
table.append((repo.id, repo.name, state))
|
|
|
|
|
|
|
|
qubesadmin.tools.print_table(table)
|
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
def main(args: typing.Optional[typing.Sequence[str]] = None,
|
|
|
|
app: typing.Optional[qubesadmin.app.QubesBase] = None) -> int:
|
|
|
|
"""Main routine of **qvm-template**.
|
|
|
|
|
|
|
|
:param args: Override arguments received by the application. Optional
|
|
|
|
:param app: Override Qubes application object. Optional
|
|
|
|
|
|
|
|
:return: Return code of the application
|
|
|
|
"""
|
2020-08-14 05:38:30 +02:00
|
|
|
p_args = parser.parse_args(args)
|
2020-07-08 20:23:19 +02:00
|
|
|
|
2020-09-04 20:06:53 +02:00
|
|
|
if not p_args.operation:
|
|
|
|
parser.error('An operation needs to be specified.')
|
|
|
|
|
2020-08-07 09:02:40 +02:00
|
|
|
# If the user specified other repo files...
|
|
|
|
if len(p_args.repo_files) > 1:
|
|
|
|
# ...remove the default entry
|
|
|
|
p_args.repo_files.pop(0)
|
|
|
|
|
2020-07-08 20:23:19 +02:00
|
|
|
if app is None:
|
|
|
|
app = qubesadmin.Qubes()
|
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
if p_args.refresh:
|
|
|
|
qrexec_repoquery(p_args, app, refresh=True)
|
2020-07-29 13:47:48 +02:00
|
|
|
|
2020-08-05 20:05:57 +02:00
|
|
|
if p_args.operation == 'download':
|
|
|
|
download(p_args, app)
|
|
|
|
elif p_args.operation == 'install':
|
|
|
|
install(p_args, app)
|
|
|
|
elif p_args.operation == 'reinstall':
|
|
|
|
install(p_args, app, version_selector=VersionSelector.REINSTALL,
|
2020-07-30 19:27:40 +02:00
|
|
|
override_existing=True)
|
2020-08-05 20:05:57 +02:00
|
|
|
elif p_args.operation == 'downgrade':
|
|
|
|
install(p_args, app, version_selector=VersionSelector.LATEST_LOWER,
|
2020-07-30 19:27:40 +02:00
|
|
|
override_existing=True)
|
2020-08-05 20:05:57 +02:00
|
|
|
elif p_args.operation == 'upgrade':
|
|
|
|
install(p_args, app, version_selector=VersionSelector.LATEST_HIGHER,
|
2020-07-30 19:27:40 +02:00
|
|
|
override_existing=True)
|
2020-08-05 20:05:57 +02:00
|
|
|
elif p_args.operation == 'list':
|
|
|
|
list_templates(p_args, app, 'list')
|
|
|
|
elif p_args.operation == 'info':
|
|
|
|
list_templates(p_args, app, 'info')
|
|
|
|
elif p_args.operation == 'search':
|
|
|
|
search(p_args, app)
|
|
|
|
elif p_args.operation == 'remove':
|
2020-08-14 05:38:30 +02:00
|
|
|
remove(p_args, app, disassoc=p_args.disassoc)
|
|
|
|
elif p_args.operation == 'purge':
|
|
|
|
remove(p_args, app, purge=True)
|
2020-08-05 20:05:57 +02:00
|
|
|
elif p_args.operation == 'clean':
|
|
|
|
clean(p_args, app)
|
2020-08-07 08:48:08 +02:00
|
|
|
elif p_args.operation == 'repolist':
|
|
|
|
repolist(p_args, app)
|
2020-07-08 20:23:19 +02:00
|
|
|
else:
|
2020-08-05 20:05:57 +02:00
|
|
|
parser.error('Operation \'%s\' not supported.' % p_args.operation)
|
2020-07-08 20:23:19 +02:00
|
|
|
|
|
|
|
return 0
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
sys.exit(main())
|