Skip to content

redis

redis

DEFAULT_DATA_ROOT = '/io/data' module-attribute

DEFAULT_PROCESS_ALLOWLIST = ','.join(['native:buffer', 'native:centroids']) module-attribute

DEFAULT_PROCESS_MAX_FEATURES = 1000000 module-attribute

DEFAULT_PROCESS_MAX_OUTPUT_SIZE = 1024 module-attribute

DEFAULT_PROCESS_OUTPUT_DIR = '/io/process_output' module-attribute

DEFAULT_PROCESS_TIMEOUT = 3600 module-attribute

DEFAULT_RUNNER_PLUGINS = ':'.join(['qgis_server_light.worker.runner.render.RenderRunner', 'qgis_server_light.worker.runner.legend.GetLegendRunner', 'qgis_server_light.worker.runner.feature.GetFeatureRunner', 'qgis_server_light.worker.runner.crs.CrsRunner']) module-attribute

DEFAULT_SVG_PATH = '/io/svg' module-attribute

engine_classes: dict[str, type[RedisEngine]] = {'publish': RedisPublishEngine, 'state': RedisStateEngine} module-attribute

JobProgress

Writes the progress a running job reports into its job hash. QGIS reports the progress per feature as float, so only a change of the full percentage is written, that's at most 101 writes per job.

Source code in src/qgis_server_light/worker/redis.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class JobProgress:
    """Writes the progress a running job reports into its job hash. QGIS
    reports the progress per feature as float, so only a change of the full
    percentage is written, that's at most 101 writes per job.
    """

    def __init__(self, client: Redis, job_key: str, progress_key: str):
        self.client = client
        self.job_key = job_key
        self.progress_key = progress_key
        self.percent: int | None = None

    def __call__(self, progress: float):
        percent = min(max(int(progress), 0), 100)
        if percent == self.percent:
            return
        self.percent = percent
        # written right away and not with the pipeline of the job, which is only
        # executed when the job is finished
        self.client.hset(self.job_key, self.progress_key, percent)

client = client instance-attribute

job_key = job_key instance-attribute

percent: int | None = None instance-attribute

progress_key = progress_key instance-attribute

__call__(progress: float)

Source code in src/qgis_server_light/worker/redis.py
73
74
75
76
77
78
79
80
def __call__(self, progress: float):
    percent = min(max(int(progress), 0), 100)
    if percent == self.percent:
        return
    self.percent = percent
    # written right away and not with the pipeline of the job, which is only
    # executed when the job is finished
    self.client.hset(self.job_key, self.progress_key, percent)

__init__(client: Redis, job_key: str, progress_key: str)

Source code in src/qgis_server_light/worker/redis.py
67
68
69
70
71
def __init__(self, client: Redis, job_key: str, progress_key: str):
    self.client = client
    self.job_key = job_key
    self.progress_key = progress_key
    self.percent: int | None = None

RedisEngine

Bases: Engine

The common part of the redis workers: connecting, registering, the heartbeat and the loop taking jobs from the queue. How a finished job is delivered is decided by the subclasses, so the loop does not need to know about it.

Attributes:

  • protocol (type[RedisProtocol]) –

    The protocol the engine is built on, it defines the queue the engine listens on.

Source code in src/qgis_server_light/worker/redis.py
 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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
class RedisEngine(Engine):
    """The common part of the redis workers: connecting, registering, the
    heartbeat and the loop taking jobs from the queue. How a finished job is
    delivered is decided by the subclasses, so the loop does not need to know
    about it.

    Attributes:
        protocol: The protocol the engine is built on, it defines the queue the
            engine listens on.
    """

    protocol: type[RedisProtocol]

    def __init__(
        self,
        context: EngineContext,
        runner_plugins: list[str],
        svg_paths: list | None = None,
        once: bool = False,
    ) -> None:
        self.boot_start = time.time()
        super().__init__(context, runner_plugins, svg_paths)
        # the worker exits after one job, so every job runs in a fresh process
        self.once = once
        # the worker only listens on the queue of its protocol
        self.queue_name = self.protocol.queue_name()
        self.shutdown = False
        self.retry_wait = 0.01
        self.max_retries = 11
        self.info_expire: int = 300
        self.heartbeat_interval = RedisProtocol.worker_heartbeat_interval
        self.heartbeat_thread = None
        self.redis_client: Redis | None = None
        self.processes_json: str | None = None

    def retry_handling_with_jitter(self, count: int):
        if count <= self.max_retries:
            sleep = math.pow(2, count) * self.retry_wait
            logging.warning(f"Retrying in {sleep} seconds...")
            time.sleep(sleep)
        else:
            self.exit_connection_error()

    @staticmethod
    def exit_connection_error():
        logging.error("Shutting down => now connection to Redis")
        exit(404)

    def exit_gracefully(self, signum, frame):
        logging.error(f"Received: {signum}")
        self.shutdown = True
        if self.redis_client is not None:
            self.unregister_worker(self.redis_client)
        exit(0)

    @staticmethod
    def set_job_runtime_status(
        job_id: str,
        pipeline: Pipeline,
        status: str,
        start_time: float,
    ):
        duration = time.time() - start_time
        ts = datetime.datetime.now().isoformat()
        pipeline.hset(RedisProtocol.job_key(job_id), RedisProtocol.job_status_key, status)
        pipeline.hset(
            RedisProtocol.job_key(job_id),
            f"{RedisProtocol.job_timestamp_key}.{status}",
            ts,
        )
        pipeline.hset(RedisProtocol.job_key(job_id), RedisProtocol.job_last_update_key, ts)
        pipeline.hset(RedisProtocol.job_key(job_id), RedisProtocol.job_duration_key, str(duration))
        pipeline.execute()

    def heartbeat(self, client: Redis) -> datetime.datetime:
        """Tells redis that this worker is still alive. Each beat is the full
        advertisement: the worker info with its current status, the last seen
        timestamp, the renewed expiry and the id in the list of workers. The beat
        does not ask redis what it still knows, it simply writes everything again. So
        when redis lost its keys (restart, flush, eviction) the worker is back within
        one heartbeat interval, without anybody having to notice the loss. Only the
        process descriptions are too big for that, the beat asks for them and writes
        them when they are missing.

        Args:
            client: The redis client.

        Returns:
            The UTC timestamp which was written as last seen.
        """
        now = datetime.datetime.now(datetime.UTC)
        pipeline = client.pipeline()
        # writing the full worker info with every beat, so it is back after redis lost
        # its keys (restart, flush, eviction) and it carries the current status
        pipeline.hset(
            RedisProtocol.worker_key(self.info.id),
            mapping={
                RedisProtocol.worker_info_key: JsonSerializer().render(self.info),
                RedisProtocol.worker_last_seen_key: now.isoformat(),
            },
        )
        # renewing the timer, otherwise the worker info expires while the worker is alive
        pipeline.expire(RedisProtocol.worker_key(self.info.id), self.info_expire)
        pipeline.sadd(RedisProtocol.worker_list_name, self.info.id)
        pipeline.execute()
        self.write_missing_processes(client)
        return now

    def register_worker(self, client: Redis):
        """Makes this worker known in redis and cleans up behind workers which vanished
        without unregistering. This way the list of workers heals itself with every
        worker start. The advertising itself is left to the first beat, there is only
        one place which knows what a worker writes.

        Args:
            client: The redis client.
        """
        self.prune_vanished_workers(client)
        # the first beat writes the worker info and adds the worker to the list
        self.heartbeat(client)
        logging.info("Worker was registered in Redis")

    @staticmethod
    def prune_vanished_workers(client: Redis):
        """Removes the ids of workers from the list whose hash expired already. Such a
        worker was killed or lost its container and could not say goodbye, so a
        starting colleague tidies up behind it.

        Args:
            client: The redis client.
        """
        # removing workers from the list which vanished without unregistering (e.g. killed),
        # their info expired already
        for worker_id in client.smembers(RedisProtocol.worker_list_name):
            if not client.exists(RedisProtocol.worker_key(worker_id)):
                client.srem(RedisProtocol.worker_list_name, worker_id)

    def unregister_worker(self, client: Redis):
        """Removes this worker from redis on a graceful shutdown. If redis is gone
        already, the worker does not insist: its info expires and the next registering
        worker cleans the list.

        Args:
            client: The redis client.
        """
        try:
            client.srem(RedisProtocol.worker_list_name, self.info.id)
            client.delete(RedisProtocol.worker_key(self.info.id))
        except RedisError as e:
            # the info expires on its own, the next registering worker cleans the list
            logging.warning(f"Worker could not be unregistered from Redis: {e}")
        else:
            logging.info("Worker was unregistered from Redis")

    def describe_processes(self):
        """Describes the processes the worker serves once on boot, the beats only pass
        the result on. Workers without the process runner don't serve processes and
        describe nothing."""
        process_runner_class = self.available_runner_classes_by_job_info.get(
            QslJobInfoExecuteProcess.__name__
        )
        if process_runner_class is None:
            return
        process_descriptions = process_runner_class.info(self.qgis, self.context)
        self.processes_json = JsonSerializer(dict_factory=DictFactory.FILTER_NONE).render(
            process_descriptions
        )

    def write_missing_processes(self, client: Redis):
        """Writes the process descriptions into the hash of the worker when they are not
        there. The descriptions are too big to be written with every beat, so the beat
        only asks whether redis still knows them. After redis lost its keys they are
        back within one heartbeat interval like the rest of the worker.

        Args:
            client: The redis client.
        """
        if self.processes_json is None:
            return
        worker_key = RedisProtocol.worker_key(self.info.id)
        if not client.hexists(worker_key, RedisProtocol.worker_processes_key):
            client.hset(worker_key, RedisProtocol.worker_processes_key, self.processes_json)
            logging.info(f"Processes {self.context.served_process_ids} were registered in Redis")

    def retry_connection(self, redis_url: str, count: int):
        logging.warning(f"Could not connect to redis on `{redis_url}`.")
        self.retry_handling_with_jitter(count)

    def start(self, redis_url) -> Redis:
        signal.signal(signal.SIGINT, self.exit_gracefully)
        signal.signal(signal.SIGTERM, self.exit_gracefully)
        r = Redis.from_url(redis_url, decode_responses=True, retry=Retry(ExponentialBackoff(), 0))
        self.wait_for_connection(r, redis_url)
        return r

    def wait_for_connection(self, client: Redis, redis_url: str):
        """Pings redis until it answers, waiting a bit longer after each refused ping.
        It is used on start and whenever the job loop lost the connection. Each outage
        gets the full number of retries, a worker which survived many short hiccups
        should not give up on the next one just because it used them up already.

        Args:
            client: The redis client.
            redis_url: The url of redis, only used to tell in the logs where the
                worker is knocking.
        """
        # the retries are counted per outage, so only one long outage makes the worker
        # give up and not the sum of all short ones
        retry_count = 0
        while True:
            try:
                retry_count += 1
                logging.debug(f"Looking up redis: {redis_url}")
                client.ping()
            except (RedisConnectionError, TimeoutError) as e:
                logging.debug(f"Connection on Redis not successful => {e}")
                self.retry_connection(redis_url, retry_count)
            else:
                break
        logging.info(f"Connection to redis on `{redis_url}`successful.")

    def start_heartbeat_worker(self, client: Redis):
        """Creates an own thread which is responsible for renewing the heartbeat info
        of the worker in redis"""

        def heartbeat_loop():
            while not self.shutdown:
                try:
                    self.heartbeat(client)
                except Exception as e:
                    logging.warning(f"Heartbeat failed: {e}")
                time.sleep(self.heartbeat_interval)

        self.heartbeat_thread = threading.Thread(target=heartbeat_loop, daemon=True)
        self.heartbeat_thread.start()
        logging.info("Heartbeat worker started")

    def run(self, redis_url):
        """Connects to redis, registers the worker, starts the heartbeat and serves jobs
        until the worker is told to stop, or with `once` until it served one. If
        something unexpected breaks the job loop, the worker reports its crash to redis
        before it goes down with the very same error, so the logs still show what
        happened. Exiting on purpose (a signal or giving up on redis) is not a crash.

        Args:
            redis_url: The url of redis, e.g. `redis://qsl-redis:6379`.
        """
        # described before registering, so the first beat writes them along
        self.describe_processes()
        r = self.start(redis_url)
        p = r.pipeline()
        # known before registering, so a signal during the registration still
        # gets unregistered
        self.redis_client = r
        self.register_worker(r)
        # Starte Heartbeat-Worker
        self.start_heartbeat_worker(r)
        try:
            self.serve_jobs(r, p, redis_url)
        except Exception:
            self.report_crash(r)
            raise
        # the loop only ends on its own with `once`. The worker doesn't unregister on
        # purpose, its last beat keeps its processes advertised until the next worker
        # booted, otherwise the consumer would see them vanish between two jobs
        exit(0)

    def report_crash(self, client: Redis):
        """Sets the status to crashed and tells redis right away. When redis is part of
        the trouble, the worker only logs that it couldn't report, the original error
        is the one which matters and must not be covered by a redis one.

        Args:
            client: The redis client.
        """
        self.set_crashed()
        try:
            # beating once more right away, the process might be gone before the
            # heartbeat thread gets its next turn
            self.heartbeat(client)
        except RedisError as e:
            logging.warning(f"Crash could not be reported to Redis: {e}")

    def serve_jobs(self, r: Redis, p: Pipeline, redis_url: str):
        """The job loop: takes the next job from the queue, processes it and publishes
        the result. A failing job is published as an error result, the loop goes on. A
        dismissed job is delivered the same way, but only noted in the log, somebody
        asked for it. With `once` the loop ends after the first job. When the connection
        to redis is lost, the loop waits for it to come back and carries on, the
        heartbeat thread takes care of advertising the worker again.

        Args:
            r: The redis client.
            p: The pipeline the job status and the result are written with.
            redis_url: The url of redis, used when waiting for the connection.
        """
        while not self.shutdown:
            try:
                logging.debug(f"Waiting for jobs on {self.queue_name}")
                self.set_waiting()
                # this is blocking the loop until a job is found in the redis
                # list/queue, if there is one we take it
                result = r.blpop(self.queue_name, timeout=0)
                if result is not None:
                    _, job_id = result
                    self.set_processing()
                    start_time = time.time()
                    job_info = None
                    try:
                        # we inform, that the job is running.
                        self.set_job_runtime_status(job_id, p, Status.RUNNING.value, start_time)

                        job_info_json = r.hget(
                            RedisProtocol.job_key(job_id), RedisProtocol.job_info_key
                        )
                        job_info_class_name = r.hget(
                            RedisProtocol.job_key(job_id), RedisProtocol.job_info_type_key
                        )
                        job_info_class = self.available_job_info_classes[job_info_class_name]
                        job_info = JsonParser().from_string(job_info_json, job_info_class)
                        with self.job_guard(r, job_id, job_info, start_time) as feedback:
                            result: JobResult = self.process(job_info, feedback)
                        self.succeed_job(job_id, job_info, result, p, start_time)
                    except JobDismissedError as e:
                        self.fail_job(job_id, job_info, e, p, start_time)
                        # somebody asked for it, nothing went wrong
                        logging.info(f"{job_id} {e}")
                    except Exception as e:
                        self.fail_job(job_id, job_info, e, p, start_time)

                        # we provide error information to the logs
                        logging.error(e, exc_info=True)
                    finally:
                        p.execute()
                    logging.debug(f"Job duration: {time.time() - start_time}")
                    if self.once:
                        self.shutdown = True
            except (RedisConnectionError, TimeoutError) as _:
                self.wait_for_connection(r, redis_url)
                continue

    def job_guard(
        self, client: Redis, job_id: str, job_info: QslJobInfoParameter, start_time: float
    ) -> AbstractContextManager[QgsProcessingFeedback | None]:
        """What watches the job while it runs, it hands out the feedback the job
        reports its progress to and is canceled through.

        Args:
            client: The redis client.
            job_id: The unique identifier of the job.
            job_info: The job info of the job.
            start_time: The time the job was taken from the queue.

        Returns:
            The context manager around the job, giving the feedback, `None` if nobody
            listens.
        """
        # map related jobs are short and their result is waited for anyway,
        # nobody asks for their progress or stops them
        return nullcontext()

    @abstractmethod
    def succeed_job(
        self,
        job_id: str,
        job_info: QslJobInfoParameter,
        result: JobResult,
        pipeline: Pipeline,
        start_time: float,
    ):
        """Delivers the result of a job which was solved.

        Args:
            job_id: The unique identifier of the job.
            job_info: The job info of the job.
            result: The result the runner returned.
            pipeline: The pipeline holding the transaction.
            start_time: The time the job was taken from the queue.
        """
        pass

    @abstractmethod
    def fail_job(
        self,
        job_id: str,
        job_info: QslJobInfoParameter | None,
        error: Exception,
        pipeline: Pipeline,
        start_time: float,
    ):
        """Delivers the error of a job which failed, or was dismissed while it ran.

        Args:
            job_id: The unique identifier of the job.
            job_info: The job info of the job, `None` if it failed before the
                job info could be read.
            error: The error the job failed with.
            pipeline: The pipeline holding the transaction.
            start_time: The time the job was taken from the queue.
        """
        pass

boot_start = time.time() instance-attribute

heartbeat_interval = RedisProtocol.worker_heartbeat_interval instance-attribute

heartbeat_thread = None instance-attribute

info_expire: int = 300 instance-attribute

max_retries = 11 instance-attribute

once = once instance-attribute

processes_json: str | None = None instance-attribute

protocol: type[RedisProtocol] instance-attribute

queue_name = self.protocol.queue_name() instance-attribute

redis_client: Redis | None = None instance-attribute

retry_wait = 0.01 instance-attribute

shutdown = False instance-attribute

__init__(context: EngineContext, runner_plugins: list[str], svg_paths: list | None = None, once: bool = False) -> None

Source code in src/qgis_server_light/worker/redis.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def __init__(
    self,
    context: EngineContext,
    runner_plugins: list[str],
    svg_paths: list | None = None,
    once: bool = False,
) -> None:
    self.boot_start = time.time()
    super().__init__(context, runner_plugins, svg_paths)
    # the worker exits after one job, so every job runs in a fresh process
    self.once = once
    # the worker only listens on the queue of its protocol
    self.queue_name = self.protocol.queue_name()
    self.shutdown = False
    self.retry_wait = 0.01
    self.max_retries = 11
    self.info_expire: int = 300
    self.heartbeat_interval = RedisProtocol.worker_heartbeat_interval
    self.heartbeat_thread = None
    self.redis_client: Redis | None = None
    self.processes_json: str | None = None

describe_processes()

Describes the processes the worker serves once on boot, the beats only pass the result on. Workers without the process runner don't serve processes and describe nothing.

Source code in src/qgis_server_light/worker/redis.py
237
238
239
240
241
242
243
244
245
246
247
248
249
def describe_processes(self):
    """Describes the processes the worker serves once on boot, the beats only pass
    the result on. Workers without the process runner don't serve processes and
    describe nothing."""
    process_runner_class = self.available_runner_classes_by_job_info.get(
        QslJobInfoExecuteProcess.__name__
    )
    if process_runner_class is None:
        return
    process_descriptions = process_runner_class.info(self.qgis, self.context)
    self.processes_json = JsonSerializer(dict_factory=DictFactory.FILTER_NONE).render(
        process_descriptions
    )

exit_connection_error() staticmethod

Source code in src/qgis_server_light/worker/redis.py
126
127
128
129
@staticmethod
def exit_connection_error():
    logging.error("Shutting down => now connection to Redis")
    exit(404)

exit_gracefully(signum, frame)

Source code in src/qgis_server_light/worker/redis.py
131
132
133
134
135
136
def exit_gracefully(self, signum, frame):
    logging.error(f"Received: {signum}")
    self.shutdown = True
    if self.redis_client is not None:
        self.unregister_worker(self.redis_client)
    exit(0)

fail_job(job_id: str, job_info: QslJobInfoParameter | None, error: Exception, pipeline: Pipeline, start_time: float) abstractmethod

Delivers the error of a job which failed, or was dismissed while it ran.

Parameters:

  • job_id (str) –

    The unique identifier of the job.

  • job_info (QslJobInfoParameter | None) –

    The job info of the job, None if it failed before the job info could be read.

  • error (Exception) –

    The error the job failed with.

  • pipeline (Pipeline) –

    The pipeline holding the transaction.

  • start_time (float) –

    The time the job was taken from the queue.

Source code in src/qgis_server_light/worker/redis.py
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
@abstractmethod
def fail_job(
    self,
    job_id: str,
    job_info: QslJobInfoParameter | None,
    error: Exception,
    pipeline: Pipeline,
    start_time: float,
):
    """Delivers the error of a job which failed, or was dismissed while it ran.

    Args:
        job_id: The unique identifier of the job.
        job_info: The job info of the job, `None` if it failed before the
            job info could be read.
        error: The error the job failed with.
        pipeline: The pipeline holding the transaction.
        start_time: The time the job was taken from the queue.
    """
    pass

heartbeat(client: Redis) -> datetime.datetime

Tells redis that this worker is still alive. Each beat is the full advertisement: the worker info with its current status, the last seen timestamp, the renewed expiry and the id in the list of workers. The beat does not ask redis what it still knows, it simply writes everything again. So when redis lost its keys (restart, flush, eviction) the worker is back within one heartbeat interval, without anybody having to notice the loss. Only the process descriptions are too big for that, the beat asks for them and writes them when they are missing.

Parameters:

  • client (Redis) –

    The redis client.

Returns:

  • datetime –

    The UTC timestamp which was written as last seen.

Source code in src/qgis_server_light/worker/redis.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
def heartbeat(self, client: Redis) -> datetime.datetime:
    """Tells redis that this worker is still alive. Each beat is the full
    advertisement: the worker info with its current status, the last seen
    timestamp, the renewed expiry and the id in the list of workers. The beat
    does not ask redis what it still knows, it simply writes everything again. So
    when redis lost its keys (restart, flush, eviction) the worker is back within
    one heartbeat interval, without anybody having to notice the loss. Only the
    process descriptions are too big for that, the beat asks for them and writes
    them when they are missing.

    Args:
        client: The redis client.

    Returns:
        The UTC timestamp which was written as last seen.
    """
    now = datetime.datetime.now(datetime.UTC)
    pipeline = client.pipeline()
    # writing the full worker info with every beat, so it is back after redis lost
    # its keys (restart, flush, eviction) and it carries the current status
    pipeline.hset(
        RedisProtocol.worker_key(self.info.id),
        mapping={
            RedisProtocol.worker_info_key: JsonSerializer().render(self.info),
            RedisProtocol.worker_last_seen_key: now.isoformat(),
        },
    )
    # renewing the timer, otherwise the worker info expires while the worker is alive
    pipeline.expire(RedisProtocol.worker_key(self.info.id), self.info_expire)
    pipeline.sadd(RedisProtocol.worker_list_name, self.info.id)
    pipeline.execute()
    self.write_missing_processes(client)
    return now

job_guard(client: Redis, job_id: str, job_info: QslJobInfoParameter, start_time: float) -> AbstractContextManager[QgsProcessingFeedback | None]

What watches the job while it runs, it hands out the feedback the job reports its progress to and is canceled through.

Parameters:

  • client (Redis) –

    The redis client.

  • job_id (str) –

    The unique identifier of the job.

  • job_info (QslJobInfoParameter) –

    The job info of the job.

  • start_time (float) –

    The time the job was taken from the queue.

Returns:

  • AbstractContextManager[QgsProcessingFeedback | None] –

    The context manager around the job, giving the feedback, None if nobody

  • AbstractContextManager[QgsProcessingFeedback | None] –

    listens.

Source code in src/qgis_server_light/worker/redis.py
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
def job_guard(
    self, client: Redis, job_id: str, job_info: QslJobInfoParameter, start_time: float
) -> AbstractContextManager[QgsProcessingFeedback | None]:
    """What watches the job while it runs, it hands out the feedback the job
    reports its progress to and is canceled through.

    Args:
        client: The redis client.
        job_id: The unique identifier of the job.
        job_info: The job info of the job.
        start_time: The time the job was taken from the queue.

    Returns:
        The context manager around the job, giving the feedback, `None` if nobody
        listens.
    """
    # map related jobs are short and their result is waited for anyway,
    # nobody asks for their progress or stops them
    return nullcontext()

prune_vanished_workers(client: Redis) staticmethod

Removes the ids of workers from the list whose hash expired already. Such a worker was killed or lost its container and could not say goodbye, so a starting colleague tidies up behind it.

Parameters:

  • client (Redis) –

    The redis client.

Source code in src/qgis_server_light/worker/redis.py
205
206
207
208
209
210
211
212
213
214
215
216
217
218
@staticmethod
def prune_vanished_workers(client: Redis):
    """Removes the ids of workers from the list whose hash expired already. Such a
    worker was killed or lost its container and could not say goodbye, so a
    starting colleague tidies up behind it.

    Args:
        client: The redis client.
    """
    # removing workers from the list which vanished without unregistering (e.g. killed),
    # their info expired already
    for worker_id in client.smembers(RedisProtocol.worker_list_name):
        if not client.exists(RedisProtocol.worker_key(worker_id)):
            client.srem(RedisProtocol.worker_list_name, worker_id)

register_worker(client: Redis)

Makes this worker known in redis and cleans up behind workers which vanished without unregistering. This way the list of workers heals itself with every worker start. The advertising itself is left to the first beat, there is only one place which knows what a worker writes.

Parameters:

  • client (Redis) –

    The redis client.

Source code in src/qgis_server_light/worker/redis.py
191
192
193
194
195
196
197
198
199
200
201
202
203
def register_worker(self, client: Redis):
    """Makes this worker known in redis and cleans up behind workers which vanished
    without unregistering. This way the list of workers heals itself with every
    worker start. The advertising itself is left to the first beat, there is only
    one place which knows what a worker writes.

    Args:
        client: The redis client.
    """
    self.prune_vanished_workers(client)
    # the first beat writes the worker info and adds the worker to the list
    self.heartbeat(client)
    logging.info("Worker was registered in Redis")

report_crash(client: Redis)

Sets the status to crashed and tells redis right away. When redis is part of the trouble, the worker only logs that it couldn't report, the original error is the one which matters and must not be covered by a redis one.

Parameters:

  • client (Redis) –

    The redis client.

Source code in src/qgis_server_light/worker/redis.py
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
def report_crash(self, client: Redis):
    """Sets the status to crashed and tells redis right away. When redis is part of
    the trouble, the worker only logs that it couldn't report, the original error
    is the one which matters and must not be covered by a redis one.

    Args:
        client: The redis client.
    """
    self.set_crashed()
    try:
        # beating once more right away, the process might be gone before the
        # heartbeat thread gets its next turn
        self.heartbeat(client)
    except RedisError as e:
        logging.warning(f"Crash could not be reported to Redis: {e}")

retry_connection(redis_url: str, count: int)

Source code in src/qgis_server_light/worker/redis.py
267
268
269
def retry_connection(self, redis_url: str, count: int):
    logging.warning(f"Could not connect to redis on `{redis_url}`.")
    self.retry_handling_with_jitter(count)

retry_handling_with_jitter(count: int)

Source code in src/qgis_server_light/worker/redis.py
118
119
120
121
122
123
124
def retry_handling_with_jitter(self, count: int):
    if count <= self.max_retries:
        sleep = math.pow(2, count) * self.retry_wait
        logging.warning(f"Retrying in {sleep} seconds...")
        time.sleep(sleep)
    else:
        self.exit_connection_error()

run(redis_url)

Connects to redis, registers the worker, starts the heartbeat and serves jobs until the worker is told to stop, or with once until it served one. If something unexpected breaks the job loop, the worker reports its crash to redis before it goes down with the very same error, so the logs still show what happened. Exiting on purpose (a signal or giving up on redis) is not a crash.

Parameters:

  • redis_url –

    The url of redis, e.g. redis://qsl-redis:6379.

Source code in src/qgis_server_light/worker/redis.py
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
def run(self, redis_url):
    """Connects to redis, registers the worker, starts the heartbeat and serves jobs
    until the worker is told to stop, or with `once` until it served one. If
    something unexpected breaks the job loop, the worker reports its crash to redis
    before it goes down with the very same error, so the logs still show what
    happened. Exiting on purpose (a signal or giving up on redis) is not a crash.

    Args:
        redis_url: The url of redis, e.g. `redis://qsl-redis:6379`.
    """
    # described before registering, so the first beat writes them along
    self.describe_processes()
    r = self.start(redis_url)
    p = r.pipeline()
    # known before registering, so a signal during the registration still
    # gets unregistered
    self.redis_client = r
    self.register_worker(r)
    # Starte Heartbeat-Worker
    self.start_heartbeat_worker(r)
    try:
        self.serve_jobs(r, p, redis_url)
    except Exception:
        self.report_crash(r)
        raise
    # the loop only ends on its own with `once`. The worker doesn't unregister on
    # purpose, its last beat keeps its processes advertised until the next worker
    # booted, otherwise the consumer would see them vanish between two jobs
    exit(0)

serve_jobs(r: Redis, p: Pipeline, redis_url: str)

The job loop: takes the next job from the queue, processes it and publishes the result. A failing job is published as an error result, the loop goes on. A dismissed job is delivered the same way, but only noted in the log, somebody asked for it. With once the loop ends after the first job. When the connection to redis is lost, the loop waits for it to come back and carries on, the heartbeat thread takes care of advertising the worker again.

Parameters:

  • r (Redis) –

    The redis client.

  • p (Pipeline) –

    The pipeline the job status and the result are written with.

  • redis_url (str) –

    The url of redis, used when waiting for the connection.

Source code in src/qgis_server_light/worker/redis.py
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
def serve_jobs(self, r: Redis, p: Pipeline, redis_url: str):
    """The job loop: takes the next job from the queue, processes it and publishes
    the result. A failing job is published as an error result, the loop goes on. A
    dismissed job is delivered the same way, but only noted in the log, somebody
    asked for it. With `once` the loop ends after the first job. When the connection
    to redis is lost, the loop waits for it to come back and carries on, the
    heartbeat thread takes care of advertising the worker again.

    Args:
        r: The redis client.
        p: The pipeline the job status and the result are written with.
        redis_url: The url of redis, used when waiting for the connection.
    """
    while not self.shutdown:
        try:
            logging.debug(f"Waiting for jobs on {self.queue_name}")
            self.set_waiting()
            # this is blocking the loop until a job is found in the redis
            # list/queue, if there is one we take it
            result = r.blpop(self.queue_name, timeout=0)
            if result is not None:
                _, job_id = result
                self.set_processing()
                start_time = time.time()
                job_info = None
                try:
                    # we inform, that the job is running.
                    self.set_job_runtime_status(job_id, p, Status.RUNNING.value, start_time)

                    job_info_json = r.hget(
                        RedisProtocol.job_key(job_id), RedisProtocol.job_info_key
                    )
                    job_info_class_name = r.hget(
                        RedisProtocol.job_key(job_id), RedisProtocol.job_info_type_key
                    )
                    job_info_class = self.available_job_info_classes[job_info_class_name]
                    job_info = JsonParser().from_string(job_info_json, job_info_class)
                    with self.job_guard(r, job_id, job_info, start_time) as feedback:
                        result: JobResult = self.process(job_info, feedback)
                    self.succeed_job(job_id, job_info, result, p, start_time)
                except JobDismissedError as e:
                    self.fail_job(job_id, job_info, e, p, start_time)
                    # somebody asked for it, nothing went wrong
                    logging.info(f"{job_id} {e}")
                except Exception as e:
                    self.fail_job(job_id, job_info, e, p, start_time)

                    # we provide error information to the logs
                    logging.error(e, exc_info=True)
                finally:
                    p.execute()
                logging.debug(f"Job duration: {time.time() - start_time}")
                if self.once:
                    self.shutdown = True
        except (RedisConnectionError, TimeoutError) as _:
            self.wait_for_connection(r, redis_url)
            continue

set_job_runtime_status(job_id: str, pipeline: Pipeline, status: str, start_time: float) staticmethod

Source code in src/qgis_server_light/worker/redis.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
@staticmethod
def set_job_runtime_status(
    job_id: str,
    pipeline: Pipeline,
    status: str,
    start_time: float,
):
    duration = time.time() - start_time
    ts = datetime.datetime.now().isoformat()
    pipeline.hset(RedisProtocol.job_key(job_id), RedisProtocol.job_status_key, status)
    pipeline.hset(
        RedisProtocol.job_key(job_id),
        f"{RedisProtocol.job_timestamp_key}.{status}",
        ts,
    )
    pipeline.hset(RedisProtocol.job_key(job_id), RedisProtocol.job_last_update_key, ts)
    pipeline.hset(RedisProtocol.job_key(job_id), RedisProtocol.job_duration_key, str(duration))
    pipeline.execute()

start(redis_url) -> Redis

Source code in src/qgis_server_light/worker/redis.py
271
272
273
274
275
276
def start(self, redis_url) -> Redis:
    signal.signal(signal.SIGINT, self.exit_gracefully)
    signal.signal(signal.SIGTERM, self.exit_gracefully)
    r = Redis.from_url(redis_url, decode_responses=True, retry=Retry(ExponentialBackoff(), 0))
    self.wait_for_connection(r, redis_url)
    return r

start_heartbeat_worker(client: Redis)

Creates an own thread which is responsible for renewing the heartbeat info of the worker in redis

Source code in src/qgis_server_light/worker/redis.py
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
def start_heartbeat_worker(self, client: Redis):
    """Creates an own thread which is responsible for renewing the heartbeat info
    of the worker in redis"""

    def heartbeat_loop():
        while not self.shutdown:
            try:
                self.heartbeat(client)
            except Exception as e:
                logging.warning(f"Heartbeat failed: {e}")
            time.sleep(self.heartbeat_interval)

    self.heartbeat_thread = threading.Thread(target=heartbeat_loop, daemon=True)
    self.heartbeat_thread.start()
    logging.info("Heartbeat worker started")

succeed_job(job_id: str, job_info: QslJobInfoParameter, result: JobResult, pipeline: Pipeline, start_time: float) abstractmethod

Delivers the result of a job which was solved.

Parameters:

  • job_id (str) –

    The unique identifier of the job.

  • job_info (QslJobInfoParameter) –

    The job info of the job.

  • result (JobResult) –

    The result the runner returned.

  • pipeline (Pipeline) –

    The pipeline holding the transaction.

  • start_time (float) –

    The time the job was taken from the queue.

Source code in src/qgis_server_light/worker/redis.py
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
@abstractmethod
def succeed_job(
    self,
    job_id: str,
    job_info: QslJobInfoParameter,
    result: JobResult,
    pipeline: Pipeline,
    start_time: float,
):
    """Delivers the result of a job which was solved.

    Args:
        job_id: The unique identifier of the job.
        job_info: The job info of the job.
        result: The result the runner returned.
        pipeline: The pipeline holding the transaction.
        start_time: The time the job was taken from the queue.
    """
    pass

unregister_worker(client: Redis)

Removes this worker from redis on a graceful shutdown. If redis is gone already, the worker does not insist: its info expires and the next registering worker cleans the list.

Parameters:

  • client (Redis) –

    The redis client.

Source code in src/qgis_server_light/worker/redis.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def unregister_worker(self, client: Redis):
    """Removes this worker from redis on a graceful shutdown. If redis is gone
    already, the worker does not insist: its info expires and the next registering
    worker cleans the list.

    Args:
        client: The redis client.
    """
    try:
        client.srem(RedisProtocol.worker_list_name, self.info.id)
        client.delete(RedisProtocol.worker_key(self.info.id))
    except RedisError as e:
        # the info expires on its own, the next registering worker cleans the list
        logging.warning(f"Worker could not be unregistered from Redis: {e}")
    else:
        logging.info("Worker was unregistered from Redis")

wait_for_connection(client: Redis, redis_url: str)

Pings redis until it answers, waiting a bit longer after each refused ping. It is used on start and whenever the job loop lost the connection. Each outage gets the full number of retries, a worker which survived many short hiccups should not give up on the next one just because it used them up already.

Parameters:

  • client (Redis) –

    The redis client.

  • redis_url (str) –

    The url of redis, only used to tell in the logs where the worker is knocking.

Source code in src/qgis_server_light/worker/redis.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
def wait_for_connection(self, client: Redis, redis_url: str):
    """Pings redis until it answers, waiting a bit longer after each refused ping.
    It is used on start and whenever the job loop lost the connection. Each outage
    gets the full number of retries, a worker which survived many short hiccups
    should not give up on the next one just because it used them up already.

    Args:
        client: The redis client.
        redis_url: The url of redis, only used to tell in the logs where the
            worker is knocking.
    """
    # the retries are counted per outage, so only one long outage makes the worker
    # give up and not the sum of all short ones
    retry_count = 0
    while True:
        try:
            retry_count += 1
            logging.debug(f"Looking up redis: {redis_url}")
            client.ping()
        except (RedisConnectionError, TimeoutError) as e:
            logging.debug(f"Connection on Redis not successful => {e}")
            self.retry_connection(redis_url, retry_count)
        else:
            break
    logging.info(f"Connection to redis on `{redis_url}`successful.")

write_missing_processes(client: Redis)

Writes the process descriptions into the hash of the worker when they are not there. The descriptions are too big to be written with every beat, so the beat only asks whether redis still knows them. After redis lost its keys they are back within one heartbeat interval like the rest of the worker.

Parameters:

  • client (Redis) –

    The redis client.

Source code in src/qgis_server_light/worker/redis.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def write_missing_processes(self, client: Redis):
    """Writes the process descriptions into the hash of the worker when they are not
    there. The descriptions are too big to be written with every beat, so the beat
    only asks whether redis still knows them. After redis lost its keys they are
    back within one heartbeat interval like the rest of the worker.

    Args:
        client: The redis client.
    """
    if self.processes_json is None:
        return
    worker_key = RedisProtocol.worker_key(self.info.id)
    if not client.hexists(worker_key, RedisProtocol.worker_processes_key):
        client.hset(worker_key, RedisProtocol.worker_processes_key, self.processes_json)
        logging.info(f"Processes {self.context.served_process_ids} were registered in Redis")

RedisPublishEngine

Bases: RedisEngine

The engine publishing the result to the waiting dispatcher (see RedisPublishProtocol). This is the default, map related jobs are served by it.

Source code in src/qgis_server_light/worker/redis.py
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
class RedisPublishEngine(RedisEngine):
    """The engine publishing the result to the waiting dispatcher (see
    `RedisPublishProtocol`). This is the default, map related jobs are served
    by it.
    """

    protocol = RedisPublishProtocol

    def publish_result(
        self, job_id: str, result: JobResult, pipeline: Pipeline, status: str, start_time: float
    ):
        """Sets the final status and publishes the pickled result. Success and
        failure only differ in the result and the status, so both end here.

        Args:
            job_id: The unique identifier of the job.
            result: The result to publish, the worker information is added.
            pipeline: The pipeline holding the transaction.
            status: The final status of the job.
            start_time: The time the job was taken from the queue.
        """
        result.worker_id = self.info.id
        result.worker_host_name = socket.gethostname()
        data = pickle.dumps(result)

        # we inform, that the job was finished
        self.set_job_runtime_status(job_id, pipeline, status, start_time)

        # we publish the result to any subscribers
        pipeline.publish(self.protocol.channel(job_id), data)

    def succeed_job(
        self,
        job_id: str,
        job_info: QslJobInfoParameter,
        result: JobResult,
        pipeline: Pipeline,
        start_time: float,
    ):
        self.publish_result(job_id, result, pipeline, Status.SUCCESS.value, start_time)

    def fail_job(
        self,
        job_id: str,
        job_info: QslJobInfoParameter | None,
        error: Exception,
        pipeline: Pipeline,
        start_time: float,
    ):
        # preparation of the result, containing error information
        result = JobResult(id=job_id, data=str(error), content_type="text")
        self.publish_result(job_id, result, pipeline, Status.FAILURE.value, start_time)

protocol = RedisPublishProtocol class-attribute instance-attribute

fail_job(job_id: str, job_info: QslJobInfoParameter | None, error: Exception, pipeline: Pipeline, start_time: float)

Source code in src/qgis_server_light/worker/redis.py
527
528
529
530
531
532
533
534
535
536
537
def fail_job(
    self,
    job_id: str,
    job_info: QslJobInfoParameter | None,
    error: Exception,
    pipeline: Pipeline,
    start_time: float,
):
    # preparation of the result, containing error information
    result = JobResult(id=job_id, data=str(error), content_type="text")
    self.publish_result(job_id, result, pipeline, Status.FAILURE.value, start_time)

publish_result(job_id: str, result: JobResult, pipeline: Pipeline, status: str, start_time: float)

Sets the final status and publishes the pickled result. Success and failure only differ in the result and the status, so both end here.

Parameters:

  • job_id (str) –

    The unique identifier of the job.

  • result (JobResult) –

    The result to publish, the worker information is added.

  • pipeline (Pipeline) –

    The pipeline holding the transaction.

  • status (str) –

    The final status of the job.

  • start_time (float) –

    The time the job was taken from the queue.

Source code in src/qgis_server_light/worker/redis.py
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
def publish_result(
    self, job_id: str, result: JobResult, pipeline: Pipeline, status: str, start_time: float
):
    """Sets the final status and publishes the pickled result. Success and
    failure only differ in the result and the status, so both end here.

    Args:
        job_id: The unique identifier of the job.
        result: The result to publish, the worker information is added.
        pipeline: The pipeline holding the transaction.
        status: The final status of the job.
        start_time: The time the job was taken from the queue.
    """
    result.worker_id = self.info.id
    result.worker_host_name = socket.gethostname()
    data = pickle.dumps(result)

    # we inform, that the job was finished
    self.set_job_runtime_status(job_id, pipeline, status, start_time)

    # we publish the result to any subscribers
    pipeline.publish(self.protocol.channel(job_id), data)

succeed_job(job_id: str, job_info: QslJobInfoParameter, result: JobResult, pipeline: Pipeline, start_time: float)

Source code in src/qgis_server_light/worker/redis.py
517
518
519
520
521
522
523
524
525
def succeed_job(
    self,
    job_id: str,
    job_info: QslJobInfoParameter,
    result: JobResult,
    pipeline: Pipeline,
    start_time: float,
):
    self.publish_result(job_id, result, pipeline, Status.SUCCESS.value, start_time)

RedisStateEngine

Bases: RedisEngine

The engine keeping the result in the job hash (see RedisStateProtocol). Process-workers are started with it.

Source code in src/qgis_server_light/worker/redis.py
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
class RedisStateEngine(RedisEngine):
    """The engine keeping the result in the job hash (see `RedisStateProtocol`).
    Process-workers are started with it.
    """

    protocol = RedisStateProtocol

    def finish_job(
        self,
        job_id: str,
        job_info: QslJobInfoParameter | None,
        pipeline: Pipeline,
        status: str,
        start_time: float,
    ):
        """Renews the expiry, sets the final status and notifies a waiting
        dispatcher. Success and failure only differ in the fields written
        before, so both end here.

        Args:
            job_id: The unique identifier of the job.
            job_info: The job info of the job, `None` if it could not be read. A
                waiting dispatcher can not be ruled out then, so it is notified.
            pipeline: The pipeline holding the transaction.
            status: The final status of the job.
            start_time: The time the job was taken from the queue.
        """
        # the fields written before are executed in the same transaction as the
        # final status
        pipeline.expire(self.protocol.job_key(job_id), self.protocol.job_expire)
        self.set_job_runtime_status(job_id, pipeline, status, start_time)
        # the notification only wakes a waiting dispatcher, the job hash is
        # written already
        if job_info is None or job_info.execution_mode == ExecutionMode.SYNC:
            pipeline.publish(self.protocol.channel(job_id), status)

    def job_guard(
        self, client: Redis, job_id: str, job_info: QslJobInfoParameter, start_time: float
    ) -> JobGuard:
        job_key = self.protocol.job_key(job_id)
        feedback = QgsProcessingFeedback()
        # the algorithm runs in this thread, so the signal calls it directly
        feedback.progressChanged.connect(
            JobProgress(client, job_key, self.protocol.job_progress_key)
        )
        output_dir = self.context.process_output_dir
        return JobGuard(
            feedback,
            dismissed=lambda: bool(client.hexists(job_key, self.protocol.job_cancel_key)),
            abandon=lambda reason: self.abandon_job(client, job_id, job_info, reason, start_time),
            timeout=self.context.process_timeout,
            output_dir=Path(output_dir, job_id) if output_dir is not None else None,
            max_output_size=self.context.process_max_output_size,
        )

    def abandon_job(
        self,
        client: Redis,
        job_id: str,
        job_info: QslJobInfoParameter,
        reason: Exception,
        start_time: float,
    ):
        """Finishes a job which didn't stop after it was canceled, right before the
        worker exits. It runs in the thread of the guard, the thread of the worker is
        still stuck in the algorithm, so it has its own pipeline.

        Args:
            client: The redis client.
            job_id: The unique identifier of the job.
            job_info: The job info of the job.
            reason: Why the job was canceled.
            start_time: The time the job was taken from the queue.
        """
        pipeline = client.pipeline()
        self.fail_job(job_id, job_info, reason, pipeline, start_time)
        pipeline.execute()
        if self.context.process_output_dir is not None:
            shutil.rmtree(Path(self.context.process_output_dir, job_id), ignore_errors=True)
        self.unregister_worker(client)

    def succeed_job(
        self,
        job_id: str,
        job_info: QslJobInfoParameter,
        result: JobResult,
        pipeline: Pipeline,
        start_time: float,
    ):
        pipeline.hset(self.protocol.job_key(job_id), self.protocol.job_result_key, result.data)
        pipeline.hset(
            self.protocol.job_key(job_id),
            self.protocol.job_result_content_type_key,
            result.content_type,
        )
        self.finish_job(job_id, job_info, pipeline, Status.SUCCESS.value, start_time)

    def fail_job(
        self,
        job_id: str,
        job_info: QslJobInfoParameter | None,
        error: Exception,
        pipeline: Pipeline,
        start_time: float,
    ):
        pipeline.hset(self.protocol.job_key(job_id), self.protocol.job_message_key, str(error))
        status = Status.DISMISSED if isinstance(error, JobDismissedError) else Status.FAILURE
        self.finish_job(job_id, job_info, pipeline, status.value, start_time)

protocol = RedisStateProtocol class-attribute instance-attribute

abandon_job(client: Redis, job_id: str, job_info: QslJobInfoParameter, reason: Exception, start_time: float)

Finishes a job which didn't stop after it was canceled, right before the worker exits. It runs in the thread of the guard, the thread of the worker is still stuck in the algorithm, so it has its own pipeline.

Parameters:

  • client (Redis) –

    The redis client.

  • job_id (str) –

    The unique identifier of the job.

  • job_info (QslJobInfoParameter) –

    The job info of the job.

  • reason (Exception) –

    Why the job was canceled.

  • start_time (float) –

    The time the job was taken from the queue.

Source code in src/qgis_server_light/worker/redis.py
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
def abandon_job(
    self,
    client: Redis,
    job_id: str,
    job_info: QslJobInfoParameter,
    reason: Exception,
    start_time: float,
):
    """Finishes a job which didn't stop after it was canceled, right before the
    worker exits. It runs in the thread of the guard, the thread of the worker is
    still stuck in the algorithm, so it has its own pipeline.

    Args:
        client: The redis client.
        job_id: The unique identifier of the job.
        job_info: The job info of the job.
        reason: Why the job was canceled.
        start_time: The time the job was taken from the queue.
    """
    pipeline = client.pipeline()
    self.fail_job(job_id, job_info, reason, pipeline, start_time)
    pipeline.execute()
    if self.context.process_output_dir is not None:
        shutil.rmtree(Path(self.context.process_output_dir, job_id), ignore_errors=True)
    self.unregister_worker(client)

fail_job(job_id: str, job_info: QslJobInfoParameter | None, error: Exception, pipeline: Pipeline, start_time: float)

Source code in src/qgis_server_light/worker/redis.py
637
638
639
640
641
642
643
644
645
646
647
def fail_job(
    self,
    job_id: str,
    job_info: QslJobInfoParameter | None,
    error: Exception,
    pipeline: Pipeline,
    start_time: float,
):
    pipeline.hset(self.protocol.job_key(job_id), self.protocol.job_message_key, str(error))
    status = Status.DISMISSED if isinstance(error, JobDismissedError) else Status.FAILURE
    self.finish_job(job_id, job_info, pipeline, status.value, start_time)

finish_job(job_id: str, job_info: QslJobInfoParameter | None, pipeline: Pipeline, status: str, start_time: float)

Renews the expiry, sets the final status and notifies a waiting dispatcher. Success and failure only differ in the fields written before, so both end here.

Parameters:

  • job_id (str) –

    The unique identifier of the job.

  • job_info (QslJobInfoParameter | None) –

    The job info of the job, None if it could not be read. A waiting dispatcher can not be ruled out then, so it is notified.

  • pipeline (Pipeline) –

    The pipeline holding the transaction.

  • status (str) –

    The final status of the job.

  • start_time (float) –

    The time the job was taken from the queue.

Source code in src/qgis_server_light/worker/redis.py
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
def finish_job(
    self,
    job_id: str,
    job_info: QslJobInfoParameter | None,
    pipeline: Pipeline,
    status: str,
    start_time: float,
):
    """Renews the expiry, sets the final status and notifies a waiting
    dispatcher. Success and failure only differ in the fields written
    before, so both end here.

    Args:
        job_id: The unique identifier of the job.
        job_info: The job info of the job, `None` if it could not be read. A
            waiting dispatcher can not be ruled out then, so it is notified.
        pipeline: The pipeline holding the transaction.
        status: The final status of the job.
        start_time: The time the job was taken from the queue.
    """
    # the fields written before are executed in the same transaction as the
    # final status
    pipeline.expire(self.protocol.job_key(job_id), self.protocol.job_expire)
    self.set_job_runtime_status(job_id, pipeline, status, start_time)
    # the notification only wakes a waiting dispatcher, the job hash is
    # written already
    if job_info is None or job_info.execution_mode == ExecutionMode.SYNC:
        pipeline.publish(self.protocol.channel(job_id), status)

job_guard(client: Redis, job_id: str, job_info: QslJobInfoParameter, start_time: float) -> JobGuard

Source code in src/qgis_server_light/worker/redis.py
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
def job_guard(
    self, client: Redis, job_id: str, job_info: QslJobInfoParameter, start_time: float
) -> JobGuard:
    job_key = self.protocol.job_key(job_id)
    feedback = QgsProcessingFeedback()
    # the algorithm runs in this thread, so the signal calls it directly
    feedback.progressChanged.connect(
        JobProgress(client, job_key, self.protocol.job_progress_key)
    )
    output_dir = self.context.process_output_dir
    return JobGuard(
        feedback,
        dismissed=lambda: bool(client.hexists(job_key, self.protocol.job_cancel_key)),
        abandon=lambda reason: self.abandon_job(client, job_id, job_info, reason, start_time),
        timeout=self.context.process_timeout,
        output_dir=Path(output_dir, job_id) if output_dir is not None else None,
        max_output_size=self.context.process_max_output_size,
    )

succeed_job(job_id: str, job_info: QslJobInfoParameter, result: JobResult, pipeline: Pipeline, start_time: float)

Source code in src/qgis_server_light/worker/redis.py
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
def succeed_job(
    self,
    job_id: str,
    job_info: QslJobInfoParameter,
    result: JobResult,
    pipeline: Pipeline,
    start_time: float,
):
    pipeline.hset(self.protocol.job_key(job_id), self.protocol.job_result_key, result.data)
    pipeline.hset(
        self.protocol.job_key(job_id),
        self.protocol.job_result_content_type_key,
        result.content_type,
    )
    self.finish_job(job_id, job_info, pipeline, Status.SUCCESS.value, start_time)

main() -> None

Source code in src/qgis_server_light/worker/redis.py
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
def main() -> None:
    parser = argparse.ArgumentParser()

    parser.add_argument("--redis-url", type=str, help="redis url")

    parser.add_argument(
        "--log-level",
        type=str,
        help="log level (debug, info, warning or error)",
        default="info",
    )

    parser.add_argument(
        "--data-root",
        type=str,
        help=f"Absolute path to the data dir. Defaults to {DEFAULT_DATA_ROOT}",
        default=DEFAULT_DATA_ROOT,
    )

    parser.add_argument(
        "--svg-path",
        type=str,
        help=f"Absolute path to additional svg files. Multiple paths "
        f"can be separated by `:`. Defaults to {DEFAULT_SVG_PATH}",
        default=DEFAULT_SVG_PATH,
    )

    parser.add_argument(
        "--runner-plugins",
        type=str,
        help="Runner classes the worker boots with, as dotted paths. Multiple plugins "
        "can be separated by `:`. The worker listens on the queues of their jobs only, "
        "e.g. `qgis_server_light.worker.runner.process.ProcessRunner` for a worker "
        "serving processes. Defaults to the map related runners.",
        default=DEFAULT_RUNNER_PLUGINS,
    )

    parser.add_argument(
        "--process-allowlist",
        type=str,
        help="Ids of the QGIS algorithms the worker serves as processes, separated by `,`. "
        "Only used when the worker boots with the process runner. "
        f"Defaults to {DEFAULT_PROCESS_ALLOWLIST}",
        default=DEFAULT_PROCESS_ALLOWLIST,
    )

    parser.add_argument(
        "--process-internal-allowlist",
        type=str,
        help="Ids of the QGIS algorithms the worker serves as processes for internal use of "
        "the consumer only, separated by `,`. Their descriptions are marked `internal`, the "
        "consumer must not publish them. Only used when the worker boots with the process "
        "runner. Defaults to none",
        default="",
    )

    parser.add_argument(
        "--process-output-dir",
        type=str,
        help="Absolute path to the dir the processes write their outputs to, each job "
        "into its own sub dir. Only used when the worker boots with the process runner. "
        f"Defaults to {DEFAULT_PROCESS_OUTPUT_DIR}",
        default=DEFAULT_PROCESS_OUTPUT_DIR,
    )

    parser.add_argument(
        "--process-timeout",
        type=float,
        help="Seconds a process job may run before it is canceled, 0 for no limit. Only "
        f"used when the worker boots with the process runner. Defaults to "
        f"{DEFAULT_PROCESS_TIMEOUT}",
        default=DEFAULT_PROCESS_TIMEOUT,
    )

    parser.add_argument(
        "--process-max-output-size",
        type=int,
        help="Megabytes a process job may write before it is canceled, 0 for no limit. "
        "Only used when the worker boots with the process runner. Defaults to "
        f"{DEFAULT_PROCESS_MAX_OUTPUT_SIZE}",
        default=DEFAULT_PROCESS_MAX_OUTPUT_SIZE,
    )

    parser.add_argument(
        "--process-max-features",
        type=int,
        help="Features a vector layer input of a process job may have, 0 for no limit. "
        "Only used when the worker boots with the process runner. Defaults to "
        f"{DEFAULT_PROCESS_MAX_FEATURES}",
        default=DEFAULT_PROCESS_MAX_FEATURES,
    )

    parser.add_argument(
        "--once",
        action="store_true",
        help="Exit after one job, so every job runs in a fresh process. The worker has "
        "to be started again for the next job, e.g. by a loop around it.",
    )

    parser.add_argument(
        "--engine",
        type=str,
        choices=list(engine_classes),
        help="How the worker delivers job results: `publish` publishes the result to the "
        "waiting dispatcher, `state` keeps it in the job hash. Defaults to publish",
        default="publish",
    )

    args = parser.parse_args()

    logging.basicConfig(
        level=args.log_level.upper(), format="%(asctime)s [%(levelname)s] %(message)s"
    )

    if not args.redis_url:
        raise AssertionError(
            "no redis host specified: start qgis-server-light with '--redis-url <QSL_REDIS_URL>'"
        )

    svg_paths = args.svg_path.split(":")
    runner_plugins = args.runner_plugins.split(":")
    process_allowlist = args.process_allowlist.split(",")
    process_internal_allowlist = [
        process_id for process_id in args.process_internal_allowlist.split(",") if process_id
    ]
    engine = engine_classes[args.engine](
        EngineContext(
            args.data_root,
            process_allowlist,
            args.process_output_dir,
            process_internal_allowlist,
            # 0 means no limit, the context knows no limit as `None`
            process_timeout=args.process_timeout or None,
            process_max_output_size=args.process_max_output_size * 1024 * 1024 or None,
            process_max_features=args.process_max_features or None,
        ),
        runner_plugins,
        svg_paths=svg_paths,
        once=args.once,
    )
    engine.run(
        args.redis_url,
    )