Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions docs/efficient_run_on_multi_workers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,6 @@ The lock is extended while the task is running, and expires after `timeout` seco
url=redis://localhost:6379
timeout=180

`redis_host`, `redis_port` and `redis_timeout` of `gokart.TaskOnKart` still work, but they are deprecated: when set, they take precedence over `[gokart_lock]` and emit a `FutureWarning`. They will be removed in gokart 2.0.0 (`#685 <https://github.com/m3dev/gokart/issues/685>`_).

Object storage (GCS / S3) backend
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If your pipeline already stores its outputs on GCS or S3, the run lock can live there too, so you do not have to operate Redis just for it.
Expand Down
12 changes: 4 additions & 8 deletions docs/using_task_task_conflict_prevention_lock.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Requires
--------

You need to install the ``redis`` client with ``pip install gokart[redis]``, and set up a `redis <https://redis.io/topics/quickstart>`_ server, for using this advanced feature.
When a Redis lock backend is configured (``url`` of ``[gokart_lock]``, or the deprecated ``redis_host`` and ``redis_port``), a task with ``should_lock_run=True`` raises ``ImportError`` at construction if the ``redis`` client is not installed.
When a Redis lock backend is configured (``url`` of ``[gokart_lock]``), a task with ``should_lock_run=True`` raises ``ImportError`` at construction if the ``redis`` client is not installed.
The run lock can also be stored on GCS or S3 instead of Redis (see :doc:`efficient_run_on_multi_workers`).


Expand Down Expand Up @@ -41,7 +41,6 @@ How to use

The URL has the form ``redis://host[:port][/db]``. The port defaults to 6379 and the db number to 0. Use ``rediss://`` to connect over TLS.
Do not put a password in the URL: gokart reads it from the environment variable ``GOKART_REDIS_PASSWORD`` (no password is sent when it is unset or empty).
The password, db number and TLS setting apply only to the server given by ``url``, not to a host set with the deprecated ``redis_host``.

.. code::

Expand All @@ -54,12 +53,9 @@ How to use

``timeout`` is the number of seconds after which a lock is released without extension (180 by default).

The deprecated ``redis_host``, ``redis_port`` and ``redis_timeout`` parameters of gokart.TaskOnKart (e.g. ``--redis-host=localhost --redis-port=6379``) still work.
When they are set, they take precedence over ``[gokart_lock]`` and emit a ``FutureWarning``. They will be removed in gokart 2.0.0 (`#685 <https://github.com/m3dev/gokart/issues/685>`_).
``redis_host`` and ``redis_port`` replace the whole endpoint (both are required, and the db number, TLS and password of ``url`` are not used), while ``redis_timeout`` falls back to ``timeout``.
The replacement of ``--redis-host`` / ``--redis-port`` on the command line is ``--gokart-lock-url=redis://localhost:6379``.
If only one of ``redis_host`` and ``redis_port`` is set, a ``FutureWarning`` says that ``url`` is ignored and no Redis lock is taken.
``TaskOnKart.redis_timeout`` is ``None`` unless it is set explicitly (it used to default to 180), so code that reads it should use ``timeout`` of ``[gokart_lock]`` instead.
The ``redis_host``, ``redis_port`` and ``redis_timeout`` parameters of gokart.TaskOnKart were removed in gokart 2.0.0 (`#685 <https://github.com/m3dev/gokart/issues/685>`_).
Use ``url`` and ``timeout`` of ``[gokart_lock]`` instead; on the command line, ``--redis-host=localhost --redis-port=6379`` becomes ``--gokart-lock-url=redis://localhost:6379``.
These options left in the ``[TaskOnKart]`` section of a config file are ignored.

3. Set ``should_lock_run`` of the tasks that should not run on several nodes at once.

Expand Down
41 changes: 6 additions & 35 deletions gokart/conflict_prevention_lock/lock_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import os
import re
import warnings
from typing import Any, NamedTuple, cast
from urllib.parse import urlsplit

Expand Down Expand Up @@ -44,8 +43,6 @@ class RedisLockSettings(NamedTuple):
timeout: int
db: int = 0
ssl: bool = False
# The password is only meant for the server that `url` points at, so it is not sent to a host given by the deprecated task-level redis_host.
use_password: bool = False


class RedisUrl(NamedTuple):
Expand Down Expand Up @@ -78,15 +75,15 @@ def parse_lock_url(url: str) -> RedisUrl:
return RedisUrl(parts.hostname, DEFAULT_REDIS_PORT if port is None else port, int(db_match.group(1) or 0), parts.scheme == 'rediss')


def redis_connection_kwargs(host: str | None, port: int | None, db: int, ssl: bool, use_password: bool = False) -> dict[str, Any]:
def redis_connection_kwargs(host: str | None, port: int | None, db: int, ssl: bool) -> dict[str, Any]:
"""Keyword arguments for ``redis.Redis``; options at their default are left out."""
kwargs: dict[str, Any] = {'host': host or 'localhost', 'port': DEFAULT_REDIS_PORT if port is None else port}
if db:
kwargs['db'] = db
if ssl:
kwargs['ssl'] = True
# An unset variable simply means that the server has no password.
password = os.environ.get(REDIS_PASSWORD_ENV) if use_password else None
password = os.environ.get(REDIS_PASSWORD_ENV)
if password:
kwargs['password'] = password
return kwargs
Expand Down Expand Up @@ -131,12 +128,8 @@ def check_object_storage_lock_settings(timeout: int) -> None:
raise ValueError(f'`[gokart_lock] skew_margin` must not be negative, not {skew_margin}.')


def resolve_redis_lock_settings(redis_host: str | None, redis_port: int | None, redis_timeout: int | None, warn: bool = True) -> RedisLockSettings:
"""Merge the deprecated task-level ``redis_*`` parameters with ``[gokart_lock]``.

The deprecated ``redis_host`` / ``redis_port`` replace the whole Redis endpoint as one unit, as they did before ``[gokart_lock]`` existed,
so that an endpoint is never assembled from two sources. Only the timeout falls back to the config field by field.
"""
def resolve_redis_lock_settings() -> RedisLockSettings:
"""Resolve the Redis lock settings from ``[gokart_lock]``."""
config = gokart_lock()
scheme = lock_url_scheme(config.url)
if scheme in OBJECT_STORAGE_SCHEMES:
Expand All @@ -145,29 +138,7 @@ def resolve_redis_lock_settings(redis_host: str | None, redis_port: int | None,
raise ValueError(
f'Unsupported lock backend URL: {config.url!r}. Only redis[s]://host[:port][/db], gs://bucket[/prefix] and s3://bucket[/prefix] are supported.'
)
explicit = [name for name, value in (('redis_host', redis_host), ('redis_port', redis_port), ('redis_timeout', redis_timeout)) if value is not None]
if explicit and warn:
# FutureWarning, because DeprecationWarning is hidden by default outside __main__ and the setting usually comes from a config file.
warnings.warn(
f'{", ".join(explicit)} of TaskOnKart is deprecated and will be removed in gokart 2.0.0. Use `url` and `timeout` of the [gokart_lock] section instead.',
FutureWarning,
stacklevel=2,
)
timeout = redis_timeout if redis_timeout is not None else config.timeout
if redis_host is not None or redis_port is not None:
if scheme in OBJECT_STORAGE_SCHEMES and (redis_host is None or redis_port is None):
# Without a port the task would silently fall through to the object storage lock, contradicting "task-level redis_* take precedence".
raise ValueError('redis_host and redis_port of TaskOnKart must be set together.')
if (redis_host is None or redis_port is None) and config.url:
# A leftover half of the old setting would otherwise switch the lock off without any hint.
warnings.warn(
'Only one of redis_host and redis_port of TaskOnKart is set, so `url` of the [gokart_lock] section is ignored and no Redis lock is taken. '
'Set both, or remove them to use `url`.',
FutureWarning,
stacklevel=2,
)
return RedisLockSettings(host=redis_host, port=redis_port, timeout=timeout)
if scheme in ('redis', 'rediss'):
redis_url = parse_lock_url(cast(str, config.url))
return RedisLockSettings(host=redis_url.host, port=redis_url.port, timeout=timeout, db=redis_url.db, ssl=redis_url.ssl, use_password=True)
return RedisLockSettings(host=None, port=None, timeout=timeout)
return RedisLockSettings(host=redis_url.host, port=redis_url.port, timeout=config.timeout, db=redis_url.db, ssl=redis_url.ssl)
return RedisLockSettings(host=None, port=None, timeout=config.timeout)
3 changes: 1 addition & 2 deletions gokart/conflict_prevention_lock/run_lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ def __init__(self, task_lock_params: TaskLockParams) -> None:
task_lock_params.redis_port,
task_lock_params.redis_db,
task_lock_params.redis_ssl,
task_lock_params.redis_use_password,
)
)
self._lock = redis.lock.Lock(redis=self._client, name=task_lock_params.redis_key, timeout=task_lock_params.redis_timeout, thread_local=False)
Expand Down Expand Up @@ -73,7 +72,7 @@ def make_run_lock(task: Any) -> RunLock | None:
return None
params = make_task_lock_params_for_run(task_self=task)
config = gokart_lock()
# Task-level redis_* settings are deprecated but still take precedence over [gokart_lock].
# Follow the backend resolved when the task was constructed, so that a Redis lock is not swapped for another backend afterwards.
if not params.should_task_lock and uses_object_storage_lock():
return _make_object_storage_run_lock(cast(str, config.url), cast(str, lock_url_scheme(config.url)), params, config.skew_margin)
return RedisRunLock(params)
Expand Down
2 changes: 0 additions & 2 deletions gokart/conflict_prevention_lock/task_lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ class TaskLockParams(NamedTuple):
should_task_lock: bool
redis_db: int = 0
redis_ssl: bool = False
redis_use_password: bool = False


class TaskLockException(Exception):
Expand All @@ -41,5 +40,4 @@ def make_task_lock_params_for_run(task_self: Any) -> TaskLockParams:
redis_timeout=settings.timeout,
redis_db=settings.db,
redis_ssl=settings.ssl,
redis_use_password=settings.use_password,
)
23 changes: 3 additions & 20 deletions gokart/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,22 +139,6 @@ class TaskOnKart(luigi.Task, Generic[T]):
default=FIX_RANDOM_SEED_VALUE_NONE_MAGIC_NUMBER, description='Fix random seed method value.', significant=False
) # FIXME: should fix with OptionalIntParameter after newer luigi (https://github.com/spotify/luigi/pull/3079) will be released

redis_host: luigi.Parameter[str | None] = luigi.OptionalParameter(
default=None,
description='Deprecated, and will be removed in gokart 2.0.0: use `url` of the [gokart_lock] section. Only used by the run lock of tasks with should_lock_run=True.',
significant=False,
)
redis_port: luigi.OptionalIntParameter = luigi.OptionalIntParameter(
default=None,
description='Deprecated, and will be removed in gokart 2.0.0: use `url` of the [gokart_lock] section. Only used by the run lock of tasks with should_lock_run=True.',
significant=False,
)
redis_timeout: luigi.OptionalIntParameter = luigi.OptionalIntParameter(
default=None,
description='Deprecated, and will be removed in gokart 2.0.0: use `timeout` of the [gokart_lock] section (180 seconds by default).',
significant=False,
)

fail_on_empty_dump: luigi.Parameter[bool] = ExplicitBoolParameter(default=False, description='Fail when task dumps empty DF', significant=False)
store_index_in_feather: luigi.Parameter[bool] = ExplicitBoolParameter(
default=True, description='Wether to store index when using feather as a output object.', significant=False
Expand Down Expand Up @@ -196,12 +180,11 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
# However, @lru_cache cannot be used as a decorator because luigi.Task employs metaclass tricks.
self._cache_to_str_params()

# Resolved once here, so that the deprecated task-level redis_* warn once per task; the run lock reads the result.
self._lock_settings = resolve_redis_lock_settings(self.redis_host, self.redis_port, self.redis_timeout)
# Resolved here, so that an unsupported `url` fails at construction; the run lock reads the result.
self._lock_settings = resolve_redis_lock_settings()
if self.should_lock_run:
assert self._has_redis_lock() or uses_object_storage_lock(), (
'A lock backend must be set when should_lock_run is True. Set `url` in the [gokart_lock] section. '
'If `url` is set, a leftover redis_host or redis_port of the task overrides it; redis_host and redis_port are both required, or remove them.'
'A lock backend must be set when should_lock_run is True. Set `url` in the [gokart_lock] section.'
)
# Fail at construction rather than when the worker takes the run lock, possibly after its upstream tasks have run.
if self._has_redis_lock():
Expand Down
Loading
Loading