API

class cotyledon.Service(worker_id)

Base class for a service

This class will be executed in a new child process of a ServiceRunner. It registers signals to manager the reloading and the ending of the process.

Methods run(), terminate() and reload() are optional.

__init__(worker_id)

Create a new Service

Parameters:worker_id (int) – the identifier of this service instance
name = None

Service name used in the process title and the log messages in additionnal of the worker_id.

reload()

Reloading of the service

This method will be executed when the Service receives a SIGHUP.

If not implemented the process will just end with status 0 and ServiceRunner will start a new fresh process for this service with the same worker_id.

run()

Method representing the service activity

If not implemented the process will just wait to receive an ending signal.

terminate()

Gracefully shutdown the service

This method will be executed when the Service has to shutdown cleanly.

If not implemented the process will just end with status 0.

To customize the exit code, the SystemExit exception can be used.

class cotyledon.ServiceManager(wait_interval=0.01)

Manage lifetimes of services

ServiceManager acts as a master process that controls the lifetime of children processes and restart them if they die unexpectedly. It also propagate some signals (SIGTERM, SIGALRM, SIGINT and SIGHUP) to them.

Each child process runs an instance of a Service.

An application must create only one ServiceManager class and use ServiceManager.run() as main loop of the application.

Usage:

class MyService(Service):
    def __init__(self, worker_id, myconf):
        super(MyService, self).__init__(worker_id)
        preparing_my_job(myconf)
        self.running = True

    def run(self):
        while self.running:
            do_my_job()

    def terminate(self):
        self.running = False
        gracefully_stop_my_jobs()

    def reload(self):
        restart_my_job()

conf = {'foobar': 2}
sr = ServiceManager()
sr.add(MyService, 5, conf)
sr.run()

This will create 5 children processes running the service MyService.

__init__(wait_interval=0.01)

Creates the ServiceManager object

Parameters:wait_interval (float) – time between each new process spawn
add(service, workers=1, args=None, kwargs=None)

Add a new service to the ServiceManager

Parameters:
  • service (callable) – callable that return an instance of Service
  • workers (int) – number of processes/workers for this service
  • args (tuple) – additional positional arguments for this service
  • kwargs (dict) – additional keywoard arguments for this service
run()

Start and supervise services

This method will start and supervise all children processes until the master process asked to shutdown by a SIGTERM.

All spawned processes are part of the same unix process group.

Previous topic

Installation

Next topic

Examples

This Page