Commit 61f27220 authored by segfault's avatar segfault

Clean up code

parent 3299fbb3
......@@ -121,7 +121,8 @@ class ContainerManager(object):
return
time.sleep(0.2)
logger.warning("Failed to stop %r gracefully (timeout %s). Sending SIGKILL to all container processes.", self.name, STOP_TIMEOUT)
logger.warning("Failed to stop %r gracefully (timeout %s). Sending SIGKILL to all container processes.",
self.name, STOP_TIMEOUT)
sh.machinectl("kill", "--signal=SIGKILL", self.name)
start_time = time.perf_counter()
......
......@@ -63,7 +63,8 @@ class DBusObject(object):
def emit_signal(self, interface_name, signal_name, parameters=None, signature=None):
if not self.registered:
logger.debug("Could not emit signal %r: Object %r not registered with DBus", signal_name, self.__class__.__name__)
logger.debug("Could not emit signal %r: Object %r not registered with DBus",
signal_name, self.__class__.__name__)
return
if parameters:
parameters = GLib.Variant("(%s)" % signature, (parameters,))
......@@ -74,14 +75,14 @@ class DBusObject(object):
thread.start()
def do_handle_method_call(self,
connection: Gio.DBusConnection,
sender: str,
object_path: str,
interface_name: str,
method_name: str,
parameters: GLib.Variant,
invocation: Gio.DBusMethodInvocation,
user_data: Union[object, None] = None) -> None:
connection: Gio.DBusConnection,
sender: str,
object_path: str,
interface_name: str,
method_name: str,
parameters: GLib.Variant,
invocation: Gio.DBusMethodInvocation,
user_data: Union[object, None] = None) -> None:
try:
logger.debug("Handling method call %s.%s%s", self.__class__.__name__, method_name, parameters)
method_info = self.node_info.lookup_interface(interface_name).lookup_method(method_name)
......
class Signal(object):
def __init__(self, obj, name):
self.object = obj
self.name = name
self.dbus_signal = None
self.dbus_connection = None
def __call__(self, *args, **kwargs):
self.dbus_connection.emit_signal(None, path, interface_name, self.dbus_signal.name, parameters)
from typing import Any
from gi.repository import Gio, GLib
from gi.repository import GLib
class InvalidOptionTypeError(Exception):
......
......@@ -230,7 +230,7 @@ class OnionService(DBusObject, metaclass=abc.ABCMeta):
self.Status = Status.STOPPED
except ServiceAlreadyStoppedError:
raise
except:
except Exception:
logger.warning("Handling error in service.Stop")
self.Status = Status.ERROR
raise
......@@ -552,7 +552,8 @@ class OnionService(DBusObject, metaclass=abc.ABCMeta):
def set_initial_status(self):
if self.state_dir.exists() and not self.is_installed_file.exists():
logger.warning("Directory '%s' exists but installation was not completed. Removing directory.", self.state_dir)
logger.warning("Directory '%s' exists but installation was not completed. Removing directory.",
self.state_dir)
self.remove_state_dir()
if not self.IsInstalled:
......
......@@ -66,7 +66,8 @@ class TorManager(object):
if response.service_id:
response_address = response.service_id + ".onion"
if address != response_address:
raise TorException("Onion address %r does not match precalculated address %r" % (response_address, address))
raise TorException("Onion address %r does not match precalculated address %r" %
(response_address, address))
self._wait_for_publication(response)
......@@ -74,7 +75,7 @@ class TorManager(object):
self.controller.remove_ephemeral_hidden_service(address.replace(".onion", ""))
def _wait_for_publication(self, response):
directories_uploaded_to = list()
dirs_uploaded_to = list()
failures = list()
start_time = loop_time = time.perf_counter()
......@@ -89,13 +90,13 @@ class TorManager(object):
# This code is from stem.control (v1.5.4)
if event.action == stem.HSDescAction.UPLOAD and event.address == response.service_id:
directories_uploaded_to.append(event.directory_fingerprint)
elif event.action == stem.HSDescAction.UPLOADED and event.directory_fingerprint in directories_uploaded_to:
dirs_uploaded_to.append(event.directory_fingerprint)
elif event.action == stem.HSDescAction.UPLOADED and event.directory_fingerprint in dirs_uploaded_to:
return # successfully uploaded to a HS authority... maybe
elif event.action == stem.HSDescAction.FAILED and event.directory_fingerprint in directories_uploaded_to:
elif event.action == stem.HSDescAction.FAILED and event.directory_fingerprint in dirs_uploaded_to:
failures.append('%s (%s)' % (event.directory_fingerprint, event.reason))
if len(directories_uploaded_to) == len(failures):
if len(dirs_uploaded_to) == len(failures):
raise TorException('Failed to upload our hidden service descriptor to %s' % ', '.join(failures))
except queue.Empty:
for i in range(100):
......
......@@ -11,8 +11,8 @@ from gi.repository import GLib
logger = getLogger(__name__)
def run_threaded(function, *args):
thread = threading.Thread(target=function, args=args)
def run_threaded(func, *args):
thread = threading.Thread(target=func, args=args)
thread.start()
......
......@@ -2,7 +2,6 @@
import logging
import logging.handlers
import sys
from collections import OrderedDict
from os import path
......@@ -13,7 +12,6 @@ from pydbus import SystemBus
from onionkit.onionkitctl import argument_parser
from onionkit import logger
from onionkit.dbus.util import option_to_variant
from onionkit.util import run_threaded
from onionkit import BUS_NAME, SERVICES_PATH
......@@ -96,28 +94,6 @@ def print_yaml(*args, **kwargs):
print(yaml.dump(*args, Dumper=OrderedDictDumper, default_flow_style=False, **kwargs), end="")
def restore_services():
"""Install packages and restore files of services which have the 'persistence' option set to
True"""
persistent_services = list()
for service in services.objects:
if "persistence" in service.options_dict and service.options_dict["persistence"].Value:
persistent_services.append(service)
for service in persistent_services:
service.restore()
def autostart_services():
"""Start services with the autostart option set to True"""
services_to_autostart = [
s for s in services.objects if "autostart" in s.options_dict and s.options_dict["autostart"].Value
]
for service in services_to_autostart:
logging.info("Starting service %r", service.Name)
run_threaded(service.enable)
def execute_command(args, parser):
if args.command == "list":
list_services()
......@@ -127,10 +103,6 @@ def execute_command(args, parser):
list_running()
elif args.command == "list-published":
list_published()
elif args.command == "restore":
restore_services()
elif args.command == "autostart":
autostart_services()
else:
execute_service_command(args, parser)
......@@ -167,11 +139,11 @@ def execute_option_command(args, parser):
raise OptionNotFoundError("Could not find option %r for service %r" % (option_name, args.service))
if args.command == "get-option":
for option_name in args.options:
print(get_dbus_object(option_name).Value)
for name in args.options:
print(get_dbus_object(name).Value)
elif args.command == "set-option":
for option_name, value in args.assignments:
option = get_dbus_object(option_name)
for name, value in args.assignments:
option = get_dbus_object(name)
option.Value = option_to_variant(value)
else:
parser.error("Unknown command %r" % args.command)
......
......@@ -47,7 +47,8 @@ class OnionKit(DBusObject):
temp_state_dir = Path(TEMP_STATE_DIR)
temp_state_dir.mkdir(mode=0o700, exist_ok=True)
def GetServices(self):
@staticmethod
def GetServices():
"""Get list of DBus service object paths"""
connection = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
ret = connection.call_sync(BUS_NAME,
......@@ -94,7 +95,8 @@ class TorManager(object):
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", "-v", action="count")
parser.add_argument("--debug", action="store_true", help="Pause the execution in some error cases to allow debugging")
parser.add_argument("--debug", action="store_true",
help="Pause the execution in some error cases to allow debugging")
parser.add_argument("--log-file", "-l")
return parser.parse_args()
......
......@@ -46,13 +46,6 @@ setup(
description='Allows installing and managing onion services over a D-Bus interface.',
long_description=long_description,
#XXX: The project's main homepage.
#url='https://github.com/pypa/sampleproject',
#XXX: Author details
#author='The Python Packaging Authority',
#author_email='[email protected]',
# Choose your license
license='GPLv3',
......@@ -77,34 +70,14 @@ setup(
'Programming Language :: Python :: 3.5',
],
#XXX: What does your project relate to?
#keywords='sample setuptools development',
# You can just specify the packages manually here if your project is
# simple. Or you can use find_packages().
packages=['onionkit', 'onionkit.options', 'onionkit.data_files', 'onionkit.dbus', 'onionkit.onionkitctl'],
#XXX: List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=[],
# List additional groups of dependencies here (e.g. development
# dependencies). You can install these using the following syntax,
# for example:
# $ pip install -e .[dev,test]
#extras_require={
# 'dev': ['check-manifest'],
# 'test': ['coverage'],
#},
# If there are data files included in your packages that need to be
# installed, specify them here. If using Python 2.6 or less, then these
# have to be included in MANIFEST.in as well.
#package_data={
# 'onionkit': ['client-launchers/*', 'icons', 'gui', 'helper-scripts', 'services'],
#},
# package_data={}
# Although 'package_data' is the preferred approach, in some case you may
# need to place data files outside of your packages. See:
......@@ -119,15 +92,6 @@ setup(
(str(config_dir), ['onionkit.conf']),
],
# To provide executable scripts, use entry points in preference to the
# "scripts" keyword. Entry points provide cross-platform support and allow
# pip to create the appropriate form of executable for the target platform.
#entry_points={
# 'console_scripts': [
# 'sample=sample:main',
# ],
#},
scripts=['scripts/onionkitctl']
)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment