supervisor

package module
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 24, 2022 License: MIT Imports: 17 Imported by: 0

README

Caddy Supervisor

Build Status

A module to run and supervise background processes from Caddy

How it works

For every process in the supervisor caddyfile directive a command is executed in background and killed when caddy stops.

Full HTTP Cadyfile example

{
  # Must be in global options
  supervisor {
    php-fpm --no-daemonize {
      dir /path/to/desired/working-dir # default to current dir
      
      env APP_ENV production
      env DEBUG false
      
      user www-data
      
      restart_policy always # default to 'always', other values allowed: 'never', 'on_failure'
      
      redirect_stdout file /var/log/fpm.log       # redirect command stdout to a file. Default to caddy `stdout`
      redirect_stderr file /var/log/fpm-error.log # redirect command stderr to a file. Default to caddy `stderr`
      
      termination_grace_period 30s # default to '10s', amount of time to wait for application graceful termination before killing it
      
      replicas 3 # default to 1, number of instances that should be executed
    }
    
    # block configuration is optional    
    node worker.js
  }
}

mysite.com

Options description

  • command: the command to be executed. Supports template.
  • dir: the working directory the command should be executed in. Supports template.
  • env: declare environment variable that should be passed to command. This property can be repeated. Supports template.
  • redirect_stdout: redirect command stdout. Default: stdout, Possible values:
    • null: discard output
    • stdout: redirect to the caddy process stdout
    • stderr: redirect to the caddy process stderr
    • file /path/to/file: redirect output to a file
  • redirect_stderr: redirect command stderr. Default: stderr, See above for possible values.
  • restart_policy: define under which conditions the command should be restarted after exit. Default: always Valid values:
    • never: do not restart the command
    • on_failure: restart if exit code is not 0
    • always: always restart
  • termination_grace_period: amount of time to wait for application graceful termination before killing it. Ex: 10s
  • replicas: number of instances that should be executed. Default: 1.
  • user: the user that runs the command. Ignored on windows systems

On windows termination_grace_period is ignored and the command is killed immediatelly due to lack of signals support.

Templates

To enable different configuration per replica, you can use go templates on the fields marked with Supports template".

The following information are available to templates:

  • Replica: the index of the current replica, starting from 0

Templates also supports all functions from http://masterminds.github.io/sprig/

Example:

{
  supervisor {
    myapp --port "{{add 8000 .Replica}}" {
      replicas 5
    }
  }
}

reverse_proxy * localhost:8000-8004

Exponential backoff

To avoid spending too many resources on a crashing application, this plugin makes use of exponential backoff.

That means that when the command fail, it will be restarted with a delay of 0 seconds. If it fails again it will be restarted with a delay of 1 seconds, then on every sucessive failure the delay time doubles, with a max limit of 5 minutes.

If the command runs stable for at least 10 minutes, the restart delay is reset to 0 seconds.

Examples

PHP server (useful if you want a single container PHP application with php-fpm):

{
  supervisor {
    php-fpm
  }
}

example.com

php_fastcgi 127.0.0.1:9000
root * .
encode gzip
file_server

AspNet Core application on windows:

{
  supervisor {
    dotnet ./MyApplication.dll {
      env ASPNETCORE_URLS http://localhost:5000
      dir "C:\MyApplicationFolder"
      redirect_stdout stdout
      redirect_stderr stderr
      restart_policy always
    }
  }
}

example.com

reverse_proxy localhost:5000

Building it

Use the xcaddy tool to build a version of caddy with this module:

xcaddy build \
    --with github.com/baldinof/caddy-supervisor

Todo

  • Dedicated Caddyfile support (Supervisorfile)
  • Send processes outputs to Caddy logs

Credits

This package is continuation of https://github.com/lucaslorentz/caddy-supervisor which only supports Caddy v1.

Thank you @lucaslorentz for the original work ❤️

Documentation

Index

Constants

View Source
const (
	OutputTypeStdout = "stdout"
	OutputTypeStderr = "stderr"
	OutputTypeNull   = "null"
	OutputTypeFile   = "file"
)
View Source
const (
	// RestartNever indicates to never restart the process
	RestartNever = RestartPolicy("never")
	// RestartOnFailure indicates to only restart the process after failures
	RestartOnFailure = RestartPolicy("on_failure")
	// RestartAlways indicates to always restart the process
	RestartAlways = RestartPolicy("always")
)

Variables

This section is empty.

Functions

This section is empty.

Types

type App

type App struct {
	Supervise []Definition `json:"supervise,omitempty"`
	// contains filtered or unexported fields
}

func (App) CaddyModule

func (a App) CaddyModule() caddy.ModuleInfo

CaddyModule implements caddy.Module

func (*App) Provision

func (a *App) Provision(context caddy.Context) error

Provision implements caddy.Provisioner

func (*App) Start

func (a *App) Start() error

Start implements caddy.App

func (*App) Stop

func (a *App) Stop() error

Stop implements caddy.App

type Definition

type Definition struct {
	// Command to start and supervise. First item is the program to start, others are arguments.
	// Supports template.
	Command []string `json:"command"`
	// Replicas control how many instances of Command should run.
	Replicas *int `json:"replicas,omitempty"`
	// Dir defines the working directory the command should be executed in.
	// Supports template.
	// Default: current working dir
	Dir string `json:"dir,omitempty"`
	// Env declares environment variables that should be passed to command.
	// Supports template.
	Env map[string]string `json:"env,omitempty"`
	// RedirectStdout is the file where Command stdout is written. Use "stdout" to redirect to caddy stdout.
	RedirectStdout *OutputTarget `json:"redirect_stdout,omitempty"`
	// RedirectStderr is the file where Command stderr is written. Use "stderr" to redirect to caddy stderr.
	RedirectStderr *OutputTarget `json:"redirect_stderr,omitempty"`
	// RestartPolicy define under which conditions the command should be restarted after exit.
	// Valid values:
	//  - **never**: do not restart the command
	//  - **on_failure**: restart if exit code is not 0
	//  - **always**: always restart
	RestartPolicy RestartPolicy `json:"restart_policy,omitempty"`
	// TerminationGracePeriod defines the amount of time to wait for Command graceful termination before killing it. Ex: 10s
	TerminationGracePeriod string `json:"termination_grace_period,omitempty"`
	// User defines the user which executes the Command.
	// Default: current user
	User string `json:"user,omitempty"`
}

Definition is the configuration for process to supervise

func (Definition) ToSupervisors

func (d Definition) ToSupervisors(logger *zap.Logger) ([]*Supervisor, error)

ToSupervisors creates supervisors from the Definition (one per replica) and applies templates where needed

type Options

type Options struct {
	Command                string
	Replica                int
	Args                   []string
	Dir                    string
	Env                    []string
	RedirectStdout         OutputTarget
	RedirectStderr         OutputTarget
	RestartPolicy          RestartPolicy
	TerminationGracePeriod time.Duration
	User                   string
}

Options exposes settings to create a process supervisor

type OutputTarget

type OutputTarget struct {
	// Type is how the output should be redirected
	// Valid values:
	//   - **null**: discard outputs
	//   - **stdout**: redirect output to caddy process stdout
	//   - **stderr**: redirect output to caddy process stderr
	//   - **file**: redirect output to a file, if selected File field is required
	Type string `json:"type,omitempty"`
	// File is the file where outputs should be written. This is used only when Type is "file".
	File string `json:"file,omitempty"`
}

type RestartPolicy

type RestartPolicy string

RestartPolicy determines when a supervised process should be restarted

type Supervisor

type Supervisor struct {
	Options Options
	// contains filtered or unexported fields
}

Supervisor provides functionality to start and supervise a background process

func (*Supervisor) Run

func (s *Supervisor) Run()

Run a process and supervise

func (*Supervisor) Stop

func (s *Supervisor) Stop()

Stop the supervised process

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL