#include <userver/storages/postgres/dist_lock_component_base.hpp>
Base class for postgres-based distlock worker components.
A component that implements a distlock with lock in Postgres. Inherit from DistLockComponentBase and implement DoWork(). Lock options are configured in static config. To customize a distlock for testsuite override DoWorkTestsuite().
By default the distlock is started and stopped automatically by the framework in all environments except testsuite. If manual control over the distlock startup and shutdown is needed pass DisableAutostartAtBase{} to the DistLockComponentBase .ctor.
The class must be used for infinite loop jobs. If you want a distributed periodic, you should look at locked_periodiccomponents::PgLockedPeriodic.
See config POSTGRES_DISTLOCK_SETTINGS, some of parameters can be dynamically overridden.
A nonempty run_on_hosts gives priority to the listed hosts. All other hosts automatically act as fallback hosts and may run the task when the lock stays idle. An explicitly empty run_on_hosts disables all hosts; omitting it allows every host to acquire the lock immediately. A fallback host must observe fallback_heartbeat_checks consecutive successful checks with no live lock. Acquisition additionally requires the lock row to record no activity for fallback_heartbeat_checks * acquire_interval. If the checks finish before that shared idle interval has elapsed, the host starts another sequence. With regular successful checks, failover can therefore take nearly twice this interval; errors and scheduling delays can extend it. The host may then run for fallback_duration (10 minutes by default); expiry is advisory, so storages::postgres::DistLockComponentBase::DoWork must check storages::postgres::DistLockComponentBase::IsCancelAdvised and finish its current iteration.
Idle checks share the lock row's history, so a successful lock acquisition by any host restarts the waiting period for all fallback hosts, including short payload invocations. With fallback enabled, all participants, including preferred hosts, retain one expired row per lock key on release. With fallback disabled, release keeps the original behavior and deletes the row. Both release operations check the key and the owner, whose ID identifies an individual locker instance. A delayed release cannot change another owner's lock. However, an older strategy can delete its own row and lose the shared history. To enable fallback safely, first deploy support for conditional history retention to all participants while fallback is disabled (run_on_hosts is omitted). After that rollout completes, enable the same nonempty run_on_hosts policy for all participants of the lock. History retention must not depend on whether a participant is a preferred or a fallback host.
| Name | Description | Default value |
|---|---|---|
| cluster | Postgres cluster name. | – |
| shard-number | Postgres shard number. | – |
| table | Table name to store distlocks. | – |
| lockname | Name of the lock. | – |
| lock-ttl | TTL of the lock; must be at least as long as the duration between subsequent cancellation checks, otherwise brain split is possible. | – |
| pg-timeout | Timeout, must be less than lock-ttl/2. | – |
| restart-delay | How much time to wait after failed task restart. | 100ms |
| autostart | If true, start automatically after component load. | true |
| task-processor | The name of the TaskProcessor for running DoWork. | main-task-processor |
| testsuite-support | Enable testsuite support. | true if autostart_at_base_component parameter passed to the .ctor is kYes, false otherwise |
| locker-log-level | Base logging level for locker logs (default is info). | – |
Options inherited from components::ComponentBase :
| Name | Description | Default value |
|---|---|---|
| load-enabled | Set to false to disable loading of the component. | true |
You have to create a SQL table for distlocks. An example of the migration script is as following:
Definition at line 98 of file dist_lock_component_base.hpp.
Classes | |
| struct | DisableAutostartAtBase |
Public Member Functions | |
| DistLockComponentBase (const components::ComponentConfig &component_config, const components::ComponentContext &component_context) | |
| Constructs the distlock base and enables automatic startup and shutdown of the distlock. | |
| DistLockComponentBase (const components::ComponentConfig &component_config, const components::ComponentContext &component_context, DisableAutostartAtBase) | |
| Constructs the distlock base and disables automatic startup and shutdown of the distlock. The dislock should be started and stopped manually via AutostartDistlock() and StopDistLock() calls. | |
| dist_lock::DistLockedWorker & | GetWorker () |
| bool | OwnsLock () const noexcept |
| ComponentHealth | GetComponentHealth () const override |
| void | OnLoadingCancelled () override |
| void | OnAllComponentsLoaded () override |
| void | OnGracefulShutdown (engine::Deadline serving_shutdown_deadline) override |
| void | OnAllComponentsAreStopping () override |
Static Public Member Functions | |
| static yaml_config::Schema | GetStaticConfigSchema () |
Protected Types | |
| using | LoggableComponentBase = ComponentBase |
Protected Member Functions | |
| virtual void | DoWork ()=0 |
| virtual void | DoWorkTestsuite () |
| Override this function to provide custom testsuite handler. | |
| void | AutostartDistLock () |
| void | StopDistLock () |
| bool | IsCancelAdvised () const |
|
protectedinherited |
Definition at line 79 of file component_base.hpp.
|
protected |
Should be called in a .ctor of a derived class iff DisableAutostartAtBase{} has been passed to the DistLockComponentBase .ctor.
|
protectedpure virtual |
Override this function with anything that must be done under the pg lock.
|
inlineprotectedvirtual |
Override this function to provide custom testsuite handler.
Definition at line 162 of file dist_lock_component_base.hpp.
|
inlineoverridevirtualinherited |
Override this function to inform the world of the state of your component.
Reimplemented from components::RawComponentBase.
Reimplemented in components::Redis, and server::handlers::Restart.
Definition at line 35 of file component_base.hpp.
|
protected |
Check this method when going for the next independent processing iteration. Whereas engine::current_task::ShouldCancel() checks as frequently, as you can to honor low-level task cancellation.
|
inlineoverridevirtualinherited |
Component may use this function to stop doing work before the stop of the components that depend on it.
Base components may override it and make final to do some work before the derived object constructor is called. Don't use it otherwise.
Reimplemented from components::RawComponentBase.
Reimplemented in components::Server, and urabbitmq::ConsumerComponentBase.
Definition at line 70 of file component_base.hpp.
|
inlineoverridevirtualinherited |
Component may use this function to finalize registration of other components that depend on it (for example, handler components register in server component, and the latter uses OnAllComponentsLoaded() to start processing requests).
Base components may override it and make final to do some work after the derived object constructor is called. Don't use it otherwise.
Reimplemented from components::RawComponentBase.
Reimplemented in components::Server, server::handlers::Ping, and urabbitmq::ConsumerComponentBase.
Definition at line 51 of file component_base.hpp.
|
overridevirtualinherited |
Serving components like HTTP and gRPC servers may use this function to stop accepting new requests and shutdown serving in the given time interval. Application components likely do not need to override it.
| [in] | serving_shutdown_deadline | The deadline until already running requests should be allowed to complete. The component is supposed to stop accepting new requests and continue processing of already active requests until this deadline (unless those requests finish earlier). And it might completely shutdown requests processing when the deadline is reached (or when no active requests left). |
Reimplemented from components::RawComponentBase.
Reimplemented in components::Server.
|
inlineoverridevirtualinherited |
Called once if the creation of any other component failed. If the current component expects some other component to take any action with the current component, this call is a signal that such action may never happen due to components loading was cancelled. Application components might not want to override it.
Reimplemented from components::RawComponentBase.
Definition at line 42 of file component_base.hpp.
|
noexcept |
|
protected |
Should be called in a .dtor of a derived class iff DisableAutostartAtBase{} has been passed to the DistLockComponentBase .ctor.