Skip to content

Commit

Permalink
Catch installation errors and display them.
Browse files Browse the repository at this point in the history
Fixes #193
  • Loading branch information
almet committed Oct 15, 2024
1 parent fd5aafd commit c84e269
Show file tree
Hide file tree
Showing 7 changed files with 191 additions and 32 deletions.
76 changes: 53 additions & 23 deletions dangerzone/gui/main_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,20 @@
from PySide6.QtWidgets import QTextEdit
except ImportError:
from PySide2 import QtCore, QtGui, QtSvg, QtWidgets
from PySide2.QtWidgets import QAction, QTextEdit
from PySide2.QtCore import Qt
from PySide2.QtWidgets import QAction, QTextEdit

from .. import errors
from ..document import SAFE_EXTENSION, Document
from ..isolation_provider.container import Container, NoContainerTechException
from ..isolation_provider.dummy import Dummy
from ..isolation_provider.qubes import Qubes, is_qubes_native_conversion
from ..util import get_resource_path, get_subprocess_startupinfo, get_version
from ..util import (
format_exception,
get_resource_path,
get_subprocess_startupinfo,
get_version,
)
from .logic import Alert, CollapsibleBox, DangerzoneGui, UpdateDialog
from .updater import UpdateReport

Expand Down Expand Up @@ -388,15 +393,24 @@ def closeEvent(self, e: QtGui.QCloseEvent) -> None:


class InstallContainerThread(QtCore.QThread):
finished = QtCore.Signal()
finished = QtCore.Signal(str)

def __init__(self, dangerzone: DangerzoneGui) -> None:
super(InstallContainerThread, self).__init__()
self.dangerzone = dangerzone

def run(self) -> None:
self.dangerzone.isolation_provider.install()
self.finished.emit()
error = None
try:
installed = self.dangerzone.isolation_provider.install()
except Exception as e:
log.error("Container installation problem")
error = format_exception(e)
else:
if not installed:
error = "The image cannot be found. This can be caused by a faulty container image."
finally:
self.finished.emit(error)


class WaitingWidget(QtWidgets.QWidget):
Expand All @@ -423,9 +437,10 @@ def __init__(self) -> None:
# Enable copying
self.setTextInteractionFlags(Qt.TextSelectableByMouse)

def set_content(self, error: str) -> None:
self.setPlainText(error)
self.setVisible(True)
def set_content(self, error: Optional[str] = None) -> None:
if error:
self.setPlainText(error)
self.setVisible(True)


class WaitingWidgetContainer(WaitingWidget):
Expand All @@ -438,7 +453,6 @@ class WaitingWidgetContainer(WaitingWidget):
#
# Linux states
# - "install_container"
finished = QtCore.Signal()

def __init__(self, dangerzone: DangerzoneGui) -> None:
super(WaitingWidgetContainer, self).__init__()
Expand Down Expand Up @@ -509,48 +523,64 @@ def check_state(self) -> None:
# Update the state
self.state_change(state, error)

def show_error(self, msg: str, details: Optional[str] = None) -> None:
self.label.setText(msg)
show_traceback = details is not None
if show_traceback:
self.traceback.set_content(details)
self.traceback.setVisible(show_traceback)
self.buttons.show()

def show_message(self, msg: str) -> None:
self.label.setText(msg)
self.traceback.setVisible(False)
self.buttons.hide()

def installation_finished(self, error: Optional[str] = None) -> None:
if error:
msg = (
"During installation of the dangerzone image, <br>"
"the following error occured:"
)
self.show_error(msg, error)
else:
self.finished.emit()

def state_change(self, state: str, error: Optional[str] = None) -> None:
if state == "not_installed":
if platform.system() == "Linux":
self.label.setText(
self.show_error(
"<strong>Dangerzone requires Podman</strong><br><br>"
"Install it and retry."
)
else:
self.label.setText(
self.show_error(
"<strong>Dangerzone requires Docker Desktop</strong><br><br>"
"<a href='https://www.docker.com/products/docker-desktop'>Download Docker Desktop</a>"
", install it, and open it."
)
self.buttons.show()

elif state == "not_running":
if platform.system() == "Linux":
# "not_running" here means that the `podman image ls` command failed.
message = (
"<strong>Dangerzone requires Podman</strong><br><br>"
"Podman is installed but cannot run properly. See errors below"
)
if error:
self.traceback.set_content(error)

self.label.setText(message)

else:
self.label.setText(
message = (
"<strong>Dangerzone requires Docker Desktop</strong><br><br>"
"Docker is installed but isn't running.<br><br>"
"Open Docker and make sure it's running in the background."
)
self.buttons.show()
self.show_error(message, error)
else:
self.label.setText(
self.show_message(
"Installing the Dangerzone container image.<br><br>"
"This might take a few minutes..."
)
self.buttons.hide()
self.traceback.setVisible(False)
self.install_container_t = InstallContainerThread(self.dangerzone)
self.install_container_t.finished.connect(self.finished)
self.install_container_t.finished.connect(self.installation_finished)
self.install_container_t.start()


Expand Down
20 changes: 14 additions & 6 deletions dangerzone/isolation_provider/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ def install() -> bool:
startupinfo=get_subprocess_startupinfo(),
)

chunk_size = 10240
chunk_size = 4 << 20
compressed_container_path = get_resource_path("container.tar.gz")
with gzip.open(compressed_container_path) as f:
while True:
Expand All @@ -175,19 +175,20 @@ def install() -> bool:
p.stdin.write(chunk)
else:
break
p.communicate()
_, err = p.communicate()
if p.returncode < 0:
raise RuntimeError(f"Could not install container image: {err.decode()}")

if not Container.is_container_installed():
log.error("Failed to install the container image")
if not Container.is_container_installed(raise_on_error=True):
return False

log.info("Container image installed")
return True

@staticmethod
def is_container_installed() -> bool:
def is_container_installed(raise_on_error: bool = False) -> bool:
"""
See if the podman container is installed. Linux only.
See if the container is installed.
"""
# Get the image id
with open(get_resource_path("image-id.txt")) as f:
Expand All @@ -214,6 +215,13 @@ def is_container_installed() -> bool:
elif found_image_id == "":
pass
else:
msg = (
f"{Container.CONTAINER_NAME} images found, but IDs do not match."
f"Found: {found_image_id}, Expected: {','.join(expected_image_ids)}"
)
if raise_on_error:
raise RuntimeError(msg)
log.info(msg)
log.info("Deleting old dangerzone container image")

try:
Expand Down
11 changes: 11 additions & 0 deletions dangerzone/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import platform
import subprocess
import sys
import traceback
import unicodedata
from typing import Optional

Expand Down Expand Up @@ -97,3 +98,13 @@ def is_safe(chr: str) -> bool:
else:
sanitized_str += "�"
return sanitized_str


def format_exception(e: Exception) -> str:
# The signature of traceback.format_exception has changed in python 3.10
if sys.version_info < (3, 10):
output = traceback.format_exception(*sys.exc_info())
else:
output = traceback.format_exception(e)

return "".join(output)
21 changes: 20 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ pytest-mock = "^3.10.0"
pytest-qt = "^4.2.0"
pytest-cov = "^5.0.0"
strip-ansi = "*"
pytest-subprocess = "^1.5.2"

[tool.poetry.group.qubes.dependencies]
pymupdf = "^1.23.6"
Expand Down
93 changes: 92 additions & 1 deletion tests/gui/test_main_window.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,31 @@
import os
import pathlib
import platform
import shutil
import time
from typing import List

from pytest import MonkeyPatch, fixture
from pytest_mock import MockerFixture
from pytest_subprocess import FakeProcess
from pytestqt.qtbot import QtBot

from dangerzone.document import Document
from dangerzone.gui import MainWindow
from dangerzone.gui import main_window as main_window_module
from dangerzone.gui import updater as updater_module
from dangerzone.gui.logic import DangerzoneGui
from dangerzone.gui.main_window import ( # import Pyside related objects from here to avoid duplicating import logic.

# import Pyside related objects from here to avoid duplicating import logic.
from dangerzone.gui.main_window import (
ContentWidget,
InstallContainerThread,
QtCore,
QtGui,
WaitingWidgetContainer,
)
from dangerzone.gui.updater import UpdateReport, UpdaterThread
from dangerzone.isolation_provider.container import Container

from .test_updater import assert_report_equal, default_updater_settings

Expand Down Expand Up @@ -492,3 +499,87 @@ def test_drop_1_invalid_2_valid_documents(
content_widget.doc_selection_wrapper.dropEvent(
drag_1_invalid_and_2_valid_files_event
)


def test_installation_image_ls_error(
qtbot: QtBot, mocker: MockerFixture, fp: FakeProcess
):
# Setup
mock_app = mocker.MagicMock()
dummy = mocker.MagicMock(spec=Container)
dummy.get_runtime.return_value = "podman"

# Make "podman image ls" return an error
fp.register_subprocess(
["podman", "image", "ls"], returncode=-1, stderr="podman image ls logs"
)
fp.pass_command(["xdg-mime", "query", "default", "application/pdf"])

dz = DangerzoneGui(mock_app, dummy)
widget = WaitingWidgetContainer(dz)
qtbot.addWidget(widget)

# Assert that the error is displayed in the GUI
if platform.system() in ["Darwin", "Windows"]:
assert "Dangerzone requires Docker Desktop" in widget.label.text()
else:
assert "Podman is installed but cannot run properly" in widget.label.text()

assert "podman image ls logs" in widget.traceback.toPlainText()


def test_installation_failure_exception(
qtbot: QtBot, mocker: MockerFixture, fp: FakeProcess
):
# Setup
mock_app = mocker.MagicMock()
dummy = mocker.MagicMock(spec=Container)
dummy.get_runtime.return_value = "podman"
dummy.install.side_effect = RuntimeError("Error during install")

# Make "podman image ls" return an error
fp.register_subprocess(["podman", "image", "ls"], returncode=0)
fp.pass_command(["xdg-mime", "query", "default", "application/pdf"])

dz = DangerzoneGui(mock_app, dummy)
widget = WaitingWidgetContainer(dz)
qtbot.addWidget(widget)

# Assert that the error is displayed in the GUI
assert "Installing the Dangerzone container image" in widget.label.text()
# Start the installation process
install_thread = InstallContainerThread(dz)
with qtbot.waitSignal(install_thread.finished, timeout=5000):
install_thread.start()

assert "the following error occured" in widget.label.text()
assert "Traceback" in widget.traceback.toPlainText()
assert "Error during install" in widget.traceback.toPlainText()


def test_installation_failure_return_false(
qtbot: QtBot, mocker: MockerFixture, fp: FakeProcess
):
# Setup
mock_app = mocker.MagicMock()
dummy = mocker.MagicMock(spec=Container)
dummy.get_runtime.return_value = "podman"
dummy.install.return_value = False

# Make "podman image ls" return an error
fp.register_subprocess(["podman", "image", "ls"], returncode=0)
fp.pass_command(["xdg-mime", "query", "default", "application/pdf"])

dz = DangerzoneGui(mock_app, dummy)
widget = WaitingWidgetContainer(dz)
qtbot.addWidget(widget)

# Assert that the error is displayed in the GUI
assert "Installing the Dangerzone container image" in widget.label.text()
# Start the installation process
install_thread = InstallContainerThread(dz)
with qtbot.waitSignal(install_thread.finished, timeout=5000):
install_thread.start()

assert "the following error occured" in widget.label.text()
assert "The image cannot be found" in widget.traceback.toPlainText()
1 change: 0 additions & 1 deletion tests/isolation_provider/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from dangerzone.conversion import errors
from dangerzone.document import Document
from dangerzone.isolation_provider import base
from dangerzone.isolation_provider.qubes import running_on_qubes

TIMEOUT_STARTUP = 60 # Timeout in seconds until the conversion sandbox starts.

Expand Down

0 comments on commit c84e269

Please sign in to comment.