GenesisCoreLibs Looper Documentation
Overview
GCL Looper is a Python library designed to create daemon-like services that can run indefinitely, performing tasks at regular intervals or on demand.
Usage Examples
Basic Service
- Iterate infinitely
- There should be at least 5 seconds between start of previous and next iteration (
iter_min_period) - pause for 1 second between iterations (
iter_pause)
from gcl_looper.services import basic
class MyService(basic.BasicService):
def __init__(self, iter_min_period=5, iter_pause=1):
super(MyService, self).__init__(iter_min_period, iter_pause)
def _iteration(self):
print("Iteration", self._iteration_number)
service = MyService()
service.start()
Finite Service without any pauses in-between
from gcl_looper.services import basic
class MyFiniteService(basic.BasicService):
def __init__(self, iter_min_period=0, iter_pause=0):
super(MyFiniteService, self).__init__(iter_min_period, iter_pause)
self.countdown = 3
def _iteration(self):
if self.countdown > 1:
self.countdown -= 1
else:
self.stop()
service = MyFiniteService()
service.start()
API service with database (restalchemy)
from gcl_looper.services import bjoern_service
from gcl_looper.services import hub
from oslo_config import cfg
from restalchemy.storage.sql import engines
from restalchemy.common import config_opts as db_config_opts
from MY_PACKAGE.user_api import app
api_cli_opts = [
cfg.StrOpt(
"bind-host", default="127.0.0.1", help="The host IP to bind to"
),
cfg.IntOpt("bind-port", default=8080, help="The port to bind to"),
cfg.IntOpt(
"workers", default=1, help="How many http servers should be started"
),
]
DOMAIN = "user_api"
CONF = cfg.CONF
CONF.register_cli_opts(api_cli_opts, DOMAIN)
db_config_opts.register_posgresql_db_opts(conf=CONF)
def main():
serv_hub = hub.ProcessHubService()
for _ in range(CONF[DOMAIN].workers):
service = bjoern_service.BjoernService(
wsgi_app=app.build_wsgi_application(),
host=CONF[DOMAIN].bind_host,
port=CONF[DOMAIN].bind_port,
bjoern_kwargs=dict(reuse_port=True),
)
service.add_setup(
lambda: engines.engine_factory.configure_postgresql_factory(
conf=CONF
)
)
serv_hub.add_service(service)
serv_hub.start()
if __name__ == "__main__":
main()
Public interface:
start(): Starts the service.stop(): Stop the service._loop_iteration(): Performs one iteration of the service loop.- Boost mode:
boost(),reset_boost()— see the Boost mode section below.
Implement these methods to get usable service:
_iteration(): This method must be implemented by subclasses to perform the actual work at each iteration.
Boost mode (dynamic iteration pace)
By default the iteration pace (iter_min_period/iter_pause) is static.
The boost mode allows the business logic to change the pace dynamically,
for instance, to react on events faster for a while and then return to the
default pace:
service = MyService(iter_min_period=3, iter_pause=0.1)
# Run the next 5 iterations as fast as possible (the default)
service.boost()
# Or iterate each 0.5 second for 5 iterations
service.boost(0.5)
# Or boost until explicitly reset (pass iterations=None)
service.boost(0.5, iterations=None)
# Or boost only the next 10 iterations
service.boost(0.5, iterations=10)
# Reapply the boost and wake the loop even if the pacing is unchanged
service.boost(0.5, force=True)
# Return to the default pace
service.reset_boost()
Boost interface:
boost(iter_min_period=0, iter_pause=0, iterations=5, force=False): Switch the service into boost mode. With no arguments, the next 5 iterations run without a minimum period or pause. A repeated call replaces the previous boost;force=Truealso wakes the loop when the pacing is unchanged.iterations=Nonemeans the boost never expires by itself, but is only allowed when at least one ofiter_min_periodoriter_pauseis greater than zero — otherwise the loop would spin without any delay. ReturnsFalseif the boost is refused during the overheat cooldown (own or an ancestor's).reset_boost(): Return to the default iteration pace.is_boosted,boost_remaining_iterations,effective_iter_min_period,effective_iter_pause: Inspect the current pace.
A buggy business logic can enable the boost on every iteration and keep the service in the boost mode forever, starving the other services which share its loop. The overheat protection limits that:
# No more than 100 boosted iterations in a row, then force 200
# iterations in the default pace during which boost is refused
service.configure_boost_protection(
max_boost_iterations=100,
cooldown_iterations=200,
)
The counter of consecutive boosted iterations is reset as soon as the
service performs an iteration in the default pace. When the service
overheats, the boost is dropped and boost() returns False and has no
effect until the cooldown iterations are done.
configure_boost_protection(max_boost_iterations, cooldown_iterations): Configure the protection (None, Nonedisables it).is_cooling_down,boost_cooldown_remaining,boost_overheat_count: Inspect the cooldown state.
Boost mode works inside the LaunchpadService as well: since the inner
services are iterated by the launchpad itself, boosting any of the inner
services boosts the whole launchpad and, thus, all of its services. The
launchpad uses the minimum iteration period between its own pace and the
pace of all boosted inner services. A boost is applied to the launchpad
until all inner boosts are reset or expired.
Process Hub service
Process Hub allows running multiple services in separate processes. It's useful when you want to run multiple instances of a service (e.g., multiple API workers) or different services that should be isolated.
Security Feature: Privilege Downgrade
When using ProcessHubService, you can set __mp_downgrade_user__ on a child service to automatically downgrade process privileges after the fork. This is a security best practice to minimize attack surface - start as root (if needed to bind to privileged ports), then downgrade to an unprivileged user.
__mp_downgrade_user__: Class attribute set to a username (e.g.,"nobody"). When set, the child process will downgrade to this user after forking. Default isNone(no downgrade).
from gcl_looper.services import hub
from gcl_looper.services import bjoern_service
serv_hub = hub.ProcessHubService()
# BjoernService has __mp_downgrade_user__ = "nobody" by default
for _ in range(4): # 4 workers
service = bjoern_service.BjoernService(
wsgi_app=my_app,
host="0.0.0.0",
port=80, # Privileged port, needs root to bind
bjoern_kwargs=dict(reuse_port=True),
)
serv_hub.add_service(service)
serv_hub.start()
# Each worker starts as root to bind port 80, then downgrades to 'nobody'
Note: This feature only works on Linux and requires the process to start as root. The target user must exist on the system.
Manual Privilege Downgrade
You can also manually downgrade privileges using the utility function:
from gcl_looper import utils
# Downgrade to 'nobody' user
utils.downgrade_user_group_privileges("nobody")
Reloadable Process Hub service
ReloadableProcessHubService supervises service generations. Each generation
starts in a fresh interpreter via subprocess/exec, preloads its factory-built
services and forks workers to share application memory through copy-on-write.
Identical serialized factories share a master; different factories use separate
interpreters so their workers do not inherit each other's application state.
Replicas sharing a master must use the same __mp_downgrade_user__.
With one worker the service runs directly, without an intermediate master.
Readiness uses a pipe; the hub starts no multiprocessing resource tracker.
Factory payloads travel through a separate stdin pipe, closed before application
code runs. Child interpreters preserve the supervisor's Python isolation flags
and import paths. Payload transfer and worker readiness share ready_timeout;
stop() interrupts a blocked transfer.
On SIGHUP or reload(), a new generation starts beside the old one. Only after
all new workers finish setup does the old master receive SIGTERM. If startup
fails or exceeds ready_timeout, the old generation keeps serving. After
drain_timeout, remaining processes in the old generation's group are killed.
reload() returns a concurrent.futures.Future that resolves to True after a
successful replacement or False on failure or shutdown. Requests queued before
the same replacement share its result. A request arriving during replacement
gets the result of a later generation.
Register singleton services with add_background_service_factory(factory).
Each factory starts once in its own interpreter and is supervised alongside
the worker generation. If a child exits unexpectedly or initial readiness
fails, start() raises after cleaning up the children. Workers that finish
normally after readiness can stop the hub successfully. Set
allow_clean_worker_exit=False for long-running servers that must treat any
worker exit as a failure. Background services must run until shutdown.
- Factories are picklable module-level callables or
functools.partialobjects. They run in the generation master and must remain single-threaded and fork-safe. Parse config and configure logging there; open connections and start background threads in worker setup callbacks. - Both generations must share the listening address: TCP
BjoernServiceworkers needreuse_port=True. - Set
net.ipv4.tcp_migrate_req=1(Linux 5.14+) to migrate connections queued on a closing listener to a live one. - Bjoern keeps serving open keep-alive connections while draining. Such a worker
may be killed at
drain_timeout, potentially resetting an in-flight request. BjoernServicebinds before setup callbacks and listens only after they succeed. Filesystem Unix socket cleanup uses pinned directory descriptors and removes only the socket created by that service; overlapping generations on the same filesystem Unix socket path are not supported.
import functools
import sys
from gcl_looper.services import bjoern_service, hub
def build_worker(argv):
parse_config(argv)
app = build_app()
service = bjoern_service.BjoernService(
wsgi_app=app,
host="0.0.0.0",
port=8080,
bjoern_kwargs=dict(reuse_port=True),
)
# Open database connections in this callback, after fork and before readiness.
service.add_setup(app.open_connections)
return service
def main():
serv_hub = hub.ReloadableProcessHubService()
for _ in range(4):
serv_hub.add_service_factory(functools.partial(build_worker, sys.argv[1:]))
serv_hub.start()
if __name__ == "__main__":
main()
Use the same hub in dev and production. Set autoreload=True for development;
no paths are required. The supervisor discovers local imported source directories
and installed editable projects, including SDKs and plugins imported only on a
request. System Python directories are excluded. Use reload_dirs only to add
other source directories. Hidden directories, virtual environments, build outputs
and bytecode caches are skipped.
The supervisor polls .py timestamps with nanosecond precision once per hub
iteration (one second by default), replacing generations on edits, additions or
deletions. Development generations compile Python source directly, bypassing
bytecode caches (including PYTHONPYCACHEPREFIX); cached files are left untouched.
A filesystem scan error disables autoreload and keeps the current services running;
manual reload remains available and continues compiling source directly.
Autoreload uses only the standard library and starts no threads or processes;
autoreload=False (the default) disables discovery and scanning in production.
With systemd, ExecReload=/bin/kill -HUP $MAINPID requests reload asynchronously.
For a synchronous result, pass reload_socket=reload_control.systemd_socket_path()
to the hub, importing reload_control from gcl_looper.services. Configure one
private runtime directory for the unit and point ExecReload at the same Python
environment as the service.
[Service]
RuntimeDirectory=my-service
RuntimeDirectoryMode=0700
TimeoutStartSec=130
ExecReload=/path/to/venv/bin/python -m gcl_looper.services.reload_control
The command waits for up to 125 seconds and exits unsuccessfully if the hub
cannot complete the replacement. request_reload(path, timeout=...) offers the
same result to Python callers. The socket uses mode 0600 and its parent
directory must be writable only by trusted users. The hub uses an adjacent
reload.sock.lock file to coordinate ownership and reclaim stale sockets after
an unclean shutdown.
Launchpad Service
Launchpad service is a service that can run multiple services and execute them sequentially. It's convenient when you have multiple services that need to be run in a specific order or the services aren't heavy and you don't want to use multiprocessing. Also it simplifies the configuration of the services.
Basic usage:
from gcl_looper.services.oslo import launchpad
services = [
MyService(),
MyFiniteService(),
]
service = launchpad.LaunchpadService(services)
service.start()
The most important part in the launchpad service is its configuration. In the configuration you specify how to run inner services, how to configure them and how to initialize them.
Configuration options:
services: List of services to run. Each service can be specified as a string in the formatmodule.path:ServiceName::countwherecountis optional and defaults to 1.common_registrator_opts: Common options for all services. These options are passed to the service constructor.common_initializer: Common initializer for all services. This initializer is called after the service is created and before it is started.iter_min_period: Minimum period between iterations of the service loop.iter_pause: Pause between iterations of the service loop.
Example:
[DEFAULT]
verbose = True
debug = True
[launchpad]
services =
my_package.service_foo:FooService,
my_package.service_bar:BarService,
my_package.service_baz:BazService
common_registrator_opts = my_package.service_common:common_opts
common_initializer = my_package.service_common:common_init
[my_package.service_foo:FooService]
name = foo
[my_package.service_bar:BarService]
name = bar
project_id = 123
[my_package.service_baz:BazService]
param1 = value1
param2 = value2
Example with multiple instances of the same service:
[DEFAULT]
verbose = True
debug = True
[launchpad]
services =
my_package.service_foo:FooService,
my_package.service_bar:BarService::2
[my_package.service_foo:FooService]
name = foo
[my_package.service_bar:BarService::0]
name = bar0
project_id = 123
[my_package.service_bar:BarService::1]
name = bar1
project_id = 456
Metadata
Release files for gcl-looper 1.3.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| gcl_looper-1.3.2.tar.gz | 177.7 kB | With provenance | Details for gcl_looper-1.3.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| gcl_looper-1.3.2-py3-none-any.whl | Python 3 | none | any | Details for gcl_looper-1.3.2-py3-none-any.whl |
Total release size: 251.0 kB
Release files / gcl_looper-1.3.2.tar.gz
| Download URL | gcl_looper-1.3.2.tar.gz |
|---|---|
| Size | 177.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a0b4fcc57e3ee04baa99f201bdd0fe2d4df4b9426ec005e3a5ca50698aae03b7
|
|
BLAKE2b-256 checksum How to use checksums |
5fa6256bf39b80cf2fab72fa3b1c7f6bf0176410fd6b86e9d1e9147d45e5afdd
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.
Transparency logRelease files / gcl_looper-1.3.2-py3-none-any.whl
| Download URL | gcl_looper-1.3.2-py3-none-any.whl |
|---|---|
| Size | 73.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
a33891194703d2da1849b60956a50bc6e4b3378f20691eff802a9308297a4c0e
|
|
BLAKE2b-256 checksum How to use checksums |
a4cf74865e625da90d3a116cdbf2dce902b3b5091f6a7e8f4dfc565cb5fdc07d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.
Transparency logSecurity for gcl-looper 1.3.2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for gcl_looper-1.3.2.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.