Skip to content

job_guard

job_guard

JobDismissedError

Bases: Exception

The job was dismissed while it ran.

Source code in src/qgis_server_light/worker/job_guard.py
11
12
class JobDismissedError(Exception):
    """The job was dismissed while it ran."""

JobGuard

Watches a running process job from its own thread, the algorithm blocks the thread of the worker. Once the job is dismissed, runs longer than timeout or its outputs grow beyond max_output_size, the guard cancels the feedback of the job. QGIS algorithms check it and stop. Native code which doesn't check it would keep the worker busy forever, so if the job doesn't stop within cancel_grace the guard abandons it and ends the worker process the hard way, its restart brings it back.

Used as context manager around the job, it hands out the feedback the job runs with and turns the error of a job it canceled into the reason it canceled it.

Attributes:

  • check_interval (float) –

    Seconds between two looks at the job.

  • cancel_grace (float) –

    Seconds a canceled job has to stop before the worker exits.

Source code in src/qgis_server_light/worker/job_guard.py
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
class JobGuard:
    """Watches a running process job from its own thread, the algorithm blocks the
    thread of the worker. Once the job is dismissed, runs longer than `timeout` or its
    outputs grow beyond `max_output_size`, the guard cancels the feedback of the job.
    QGIS algorithms check it and stop. Native code which doesn't check it would keep the
    worker busy forever, so if the job doesn't stop within `cancel_grace` the guard
    abandons it and ends the worker process the hard way, its restart brings it back.

    Used as context manager around the job, it hands out the feedback the job runs with
    and turns the error of a job it canceled into the reason it canceled it.

    Attributes:
        check_interval: Seconds between two looks at the job.
        cancel_grace: Seconds a canceled job has to stop before the worker exits.
    """

    check_interval: float = 1.0
    cancel_grace: float = 30.0

    def __init__(
        self,
        feedback: QgsProcessingFeedback,
        dismissed: Callable[[], bool],
        abandon: Callable[[Exception], None],
        timeout: float | None = None,
        output_dir: Path | None = None,
        max_output_size: int | None = None,
    ):
        """
        Args:
            feedback: The feedback the job runs with.
            dismissed: Tells if somebody dismissed the job.
            abandon: Finishes the job for good before the worker exits, it gets the
                reason the job was canceled for.
            timeout: Seconds the job may run, `None` for no limit.
            output_dir: The dir the job writes its outputs to.
            max_output_size: Bytes the job may write into `output_dir`, `None` for no
                limit.
        """
        self.feedback = feedback
        self.dismissed = dismissed
        self.abandon = abandon
        self.timeout = timeout
        self.output_dir = output_dir
        self.max_output_size = max_output_size
        self.reason: Exception | None = None
        self.finished = threading.Event()
        self.thread = threading.Thread(target=self.watch, name="job-guard", daemon=True)

    def __enter__(self) -> QgsProcessingFeedback:
        """Starts the clock of the timeout and the watch.

        Returns:
            The feedback the job has to run with, it is the line the guard pulls on.
        """
        self.started = time.monotonic()
        self.thread.start()
        return self.feedback

    def __exit__(self, exc_type, exc, traceback):
        """Stops the watch once the job is over, however it ended. The error of a job the
        guard canceled tells little more than "canceled", so it is replaced by the reason,
        the original stays attached as cause.

        Raises:
            JobDismissedError: If the guard canceled the job because it was dismissed.
            JobLimitExceededError: If the guard canceled the job because of a limit.
        """
        self.finished.set()
        self.thread.join()
        # a job which finished before it noticed the cancel keeps its result
        if exc is not None and self.reason is not None:
            raise self.reason from exc
        return False

    def watch(self):
        """The loop of the guard thread: it looks at the job every `check_interval`
        seconds until the job is over or there is a reason to cancel it. After the cancel
        it gives the job `cancel_grace` seconds to stop, a job ignoring it is abandoned
        together with the worker process.
        """
        while (reason := self.check()) is None:
            if self.finished.wait(self.check_interval):
                return
        self.reason = reason
        logging.warning(f"Canceling the job: {reason}")
        self.feedback.cancel()
        if self.finished.wait(self.cancel_grace):
            return
        logging.error(
            f"The job did not stop {self.cancel_grace} seconds after it was canceled, "
            "the worker exits"
        )
        self.abandon(reason)
        logging.shutdown()
        # the algorithm holds the main thread, only leaving the process stops it
        os._exit(1)

    def check(self) -> Exception | None:
        """Looks at the job once.

        Returns:
            The reason to cancel the job, `None` if it may go on.
        """
        try:
            if self.dismissed():
                return JobDismissedError("The job was dismissed.")
        except Exception as e:
            # a hiccup of redis must not end the guard, the next look asks again
            logging.warning(f"Could not check if the job was dismissed: {e}")
        if self.timeout and time.monotonic() - self.started > self.timeout:
            return JobLimitExceededError(f"The job ran longer than {self.timeout} seconds.")
        if self.max_output_size and self.output_size() > self.max_output_size:
            return JobLimitExceededError(
                f"The outputs of the job grew beyond {self.max_output_size} bytes."
            )
        return None

    def output_size(self) -> int:
        """The bytes the job has written so far."""
        if self.output_dir is None or not self.output_dir.is_dir():
            return 0
        size = 0
        for path in self.output_dir.rglob("*"):
            # the algorithm may remove a temporary file while we count
            try:
                if path.is_file():
                    size += path.stat().st_size
            except OSError:
                continue
        return size

abandon = abandon instance-attribute

cancel_grace: float = 30.0 class-attribute instance-attribute

check_interval: float = 1.0 class-attribute instance-attribute

dismissed = dismissed instance-attribute

feedback = feedback instance-attribute

finished = threading.Event() instance-attribute

max_output_size = max_output_size instance-attribute

output_dir = output_dir instance-attribute

reason: Exception | None = None instance-attribute

thread = threading.Thread(target=(self.watch), name='job-guard', daemon=True) instance-attribute

timeout = timeout instance-attribute

__enter__() -> QgsProcessingFeedback

Starts the clock of the timeout and the watch.

Returns:

  • QgsProcessingFeedback –

    The feedback the job has to run with, it is the line the guard pulls on.

Source code in src/qgis_server_light/worker/job_guard.py
68
69
70
71
72
73
74
75
76
def __enter__(self) -> QgsProcessingFeedback:
    """Starts the clock of the timeout and the watch.

    Returns:
        The feedback the job has to run with, it is the line the guard pulls on.
    """
    self.started = time.monotonic()
    self.thread.start()
    return self.feedback

__exit__(exc_type, exc, traceback)

Stops the watch once the job is over, however it ended. The error of a job the guard canceled tells little more than "canceled", so it is replaced by the reason, the original stays attached as cause.

Raises:

Source code in src/qgis_server_light/worker/job_guard.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def __exit__(self, exc_type, exc, traceback):
    """Stops the watch once the job is over, however it ended. The error of a job the
    guard canceled tells little more than "canceled", so it is replaced by the reason,
    the original stays attached as cause.

    Raises:
        JobDismissedError: If the guard canceled the job because it was dismissed.
        JobLimitExceededError: If the guard canceled the job because of a limit.
    """
    self.finished.set()
    self.thread.join()
    # a job which finished before it noticed the cancel keeps its result
    if exc is not None and self.reason is not None:
        raise self.reason from exc
    return False

__init__(feedback: QgsProcessingFeedback, dismissed: Callable[[], bool], abandon: Callable[[Exception], None], timeout: float | None = None, output_dir: Path | None = None, max_output_size: int | None = None)

Parameters:

  • feedback (QgsProcessingFeedback) –

    The feedback the job runs with.

  • dismissed (Callable[[], bool]) –

    Tells if somebody dismissed the job.

  • abandon (Callable[[Exception], None]) –

    Finishes the job for good before the worker exits, it gets the reason the job was canceled for.

  • timeout (float | None, default: None ) –

    Seconds the job may run, None for no limit.

  • output_dir (Path | None, default: None ) –

    The dir the job writes its outputs to.

  • max_output_size (int | None, default: None ) –

    Bytes the job may write into output_dir, None for no limit.

Source code in src/qgis_server_light/worker/job_guard.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def __init__(
    self,
    feedback: QgsProcessingFeedback,
    dismissed: Callable[[], bool],
    abandon: Callable[[Exception], None],
    timeout: float | None = None,
    output_dir: Path | None = None,
    max_output_size: int | None = None,
):
    """
    Args:
        feedback: The feedback the job runs with.
        dismissed: Tells if somebody dismissed the job.
        abandon: Finishes the job for good before the worker exits, it gets the
            reason the job was canceled for.
        timeout: Seconds the job may run, `None` for no limit.
        output_dir: The dir the job writes its outputs to.
        max_output_size: Bytes the job may write into `output_dir`, `None` for no
            limit.
    """
    self.feedback = feedback
    self.dismissed = dismissed
    self.abandon = abandon
    self.timeout = timeout
    self.output_dir = output_dir
    self.max_output_size = max_output_size
    self.reason: Exception | None = None
    self.finished = threading.Event()
    self.thread = threading.Thread(target=self.watch, name="job-guard", daemon=True)

check() -> Exception | None

Looks at the job once.

Returns:

  • Exception | None –

    The reason to cancel the job, None if it may go on.

Source code in src/qgis_server_light/worker/job_guard.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def check(self) -> Exception | None:
    """Looks at the job once.

    Returns:
        The reason to cancel the job, `None` if it may go on.
    """
    try:
        if self.dismissed():
            return JobDismissedError("The job was dismissed.")
    except Exception as e:
        # a hiccup of redis must not end the guard, the next look asks again
        logging.warning(f"Could not check if the job was dismissed: {e}")
    if self.timeout and time.monotonic() - self.started > self.timeout:
        return JobLimitExceededError(f"The job ran longer than {self.timeout} seconds.")
    if self.max_output_size and self.output_size() > self.max_output_size:
        return JobLimitExceededError(
            f"The outputs of the job grew beyond {self.max_output_size} bytes."
        )
    return None

output_size() -> int

The bytes the job has written so far.

Source code in src/qgis_server_light/worker/job_guard.py
137
138
139
140
141
142
143
144
145
146
147
148
149
def output_size(self) -> int:
    """The bytes the job has written so far."""
    if self.output_dir is None or not self.output_dir.is_dir():
        return 0
    size = 0
    for path in self.output_dir.rglob("*"):
        # the algorithm may remove a temporary file while we count
        try:
            if path.is_file():
                size += path.stat().st_size
        except OSError:
            continue
    return size

watch()

The loop of the guard thread: it looks at the job every check_interval seconds until the job is over or there is a reason to cancel it. After the cancel it gives the job cancel_grace seconds to stop, a job ignoring it is abandoned together with the worker process.

Source code in src/qgis_server_light/worker/job_guard.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def watch(self):
    """The loop of the guard thread: it looks at the job every `check_interval`
    seconds until the job is over or there is a reason to cancel it. After the cancel
    it gives the job `cancel_grace` seconds to stop, a job ignoring it is abandoned
    together with the worker process.
    """
    while (reason := self.check()) is None:
        if self.finished.wait(self.check_interval):
            return
    self.reason = reason
    logging.warning(f"Canceling the job: {reason}")
    self.feedback.cancel()
    if self.finished.wait(self.cancel_grace):
        return
    logging.error(
        f"The job did not stop {self.cancel_grace} seconds after it was canceled, "
        "the worker exits"
    )
    self.abandon(reason)
    logging.shutdown()
    # the algorithm holds the main thread, only leaving the process stops it
    os._exit(1)

JobLimitExceededError

Bases: Exception

The job ran too long or wrote too much.

Source code in src/qgis_server_light/worker/job_guard.py
15
16
class JobLimitExceededError(Exception):
    """The job ran too long or wrote too much."""