daemon

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2021 License: MIT Imports: 12 Imported by: 13

Documentation

Overview

Package daemon aims to make it easier to write simple network daemons for process supervised deployment like "systemd".

https://www.freedesktop.org/software/systemd/man/daemon.html

Specifically it supports the following:

  • Be able to implement graceful config reload without changing daemon PID. (A requirement for many other daemon supervisors, like "runit")
  • To not use the fork()/setsid()/fork() ritual to daemonize and not use "Type=forking" in the systemd unit file. (although you can)
  • Notify the init system about startup completion or status updates via the sd_notify(3) interface.
  • Socket activation for standard standard net package Listeners and Packetconns, with minimal code changes.
  • Using systemd FDSTORE to hold open filedescriptors during restart.

Package gone/daemon provides a master server manager for one or more services so they can be taken down and restarted while keeping any network connection or other file descriptors open. Several different reload/restart schemes are possible - see the examples.

Library layers

At the lower level the "gone/daemon/srv" package provides a "Server" interface and functions Serve(), Shutdown(). You can use this interface directly, implementing your own reload policy or use the higherlevel Run() function of the "gone/daemon" package.

At the higher level package "gone/daemon" provide the Run() function which takes a set of RunOptions, one of which must be a function to instantiate a slice of srv.Server objects (and possible define cleanup function) and serve these servers until Exit() is called while obeying Reload().

Index

Constants

View Source
const (
	LvlEMERG int = iota // Not to be used by applications.
	LvlALERT
	LvlCRIT
	LvlERROR
	LvlWARN
	LvlNOTICE
	LvlINFO
	LvlDEBUG
)

Syslog priority levels

Variables

View Source
var ErrNoListener = errors.New("No Matching Listener")

ErrNoListener is returned from Listen() when a specified required inherited socket to listen on is not found.

Functions

func Exit

func Exit(graceful bool)

Exit tells Run() to exit. If graceful is true, Run() will wait for all servers to nicely cleanup.

func ExitGracefulWithTimeout

func ExitGracefulWithTimeout(to time.Duration)

ExitGracefulWithTimeout is like Exit(true), but has a timeout to fall back to the effect of Exit(false)

func Log

func Log(level int, msg string)

Log is used to log internal events if a LoggerFunc is set with SetLogger() You can call this your self if you need to. It's go-routine safe if the provided Log function is. However, it's not fast. Don't use this for logging not related to daemon.Run()

func Reload

func Reload()

Reload tells Run() to instatiate new servers and continue serving with them.

func ReplaceProcess

func ReplaceProcess(sig syscall.Signal) (int, error)

ReplaceProcess spawns a new version of the program. sig is the UNIX signal to send to terminate the parent once we're up and running

func Run

func Run(opts ...RunOption) (err error)

Run takes a set of RunOptions. The only mandatory option is InstantiateServers. The servers will be managed and via Serve() and can be controlled with various functions, like Reload() and Exit() On Reload() Run() will try to instantiate a new set of servers and if successful will replace the current running servers with the new set, using the gone/sd package to re-create sockets without closing TCP connections.

func SetLogger

func SetLogger(f LoggerFunc)

SetLogger sets a custom log function.

Types

type CleanupFunc

type CleanupFunc func() error

CleanupFunc is a function to call after a srv.Server is fully exited. A slice of CleanupFunc will be called after all servers are completely done. These can be used to - say - close files.

type ConfigFunc

type ConfigFunc func() ([]Server, []CleanupFunc, error)

ConfigFunc is a function returning Servers and Cleanups for Run() to run. Run() will call this every time it needs to configure it self on start and on reload. Run() will need either a ConfigFunc or the (deprecated) ConfigureFunc.

type ConfigureFunc

type ConfigureFunc func() ([]srv.Server, []CleanupFunc, error)

ConfigureFunc is a function returning srv.Server to run and the CleanupFuncs to call when they have completely shut down. This function is deprecated. Use ConfigFunc instead and implement your servers as daemon.Server instead of srv.Server - if possible. The Run() function needs a ConfigureFunc to instantiate the Servers to serve.

type LingeringServer

type LingeringServer interface {
	Server
	// Shutdown will wait for all activity to stop until the context
	// is canceled at which point it will exit with an error if activity has
	// not stopped.
	Shutdown(context.Context) error
	// Close() will force all activity to stop.
	Close() error
}

LingeringServer is a Server which potentially has background activity even after Serve() has exited. This could be connections still open and processing request, even though the listeners have closed.

type ListenerGroup

type ListenerGroup []ListenerSpec

ListenerGroup implement a gone/daemon/listen interface using the gone/sd library.

func (ListenerGroup) Listen

func (lg ListenerGroup) Listen() (listeners []net.Listener, err error)

Listen will create new listeners based on ListenerSpec, first trying to inherit a listener socket from the gone/sd library, and possibly, - if that fails, create a new listener via the stdlib net package. All listerners are Exported by the sd lib.

type ListenerSpec

type ListenerSpec struct {
	Net string

	Addr string
	// ListenerFdName can be set to pick a named file descriptor as
	// Listener via LISTEN_FDNAMES
	// It is updated to contain the name of the chosen file descriptor
	// - if any
	ListenerFdName string

	// Extra sd.FileTest to apply to the listener inherited.
	ExtraFileTests []sd.FileTest

	// InheritOnly set to true requires the Listener to be inherited via
	// the environment and there will not be created a fresh Listener.
	InheritOnly bool

	// PrepareListener provides a callback to do last minute modifications of
	// the chosen listener. (like wrapping it in something else)
	// It will be called as a callback with the listener chosen before it's set.
	// The returned listener is set instead - wrapped in any TLS if
	// there's a TLSConfig set.
	PrepareListener func(net.Listener) net.Listener

	TLSConfig *tls.Config
}

ListenerSpec describes the properties of a listener so it can be instantiated either via the "sd" library or directly from stdlib package "net"

type ListeningServer

type ListeningServer interface {
	Server
	// Listen will be called before Serve() is called to allow the server
	// to prepare for serving. It doesn't need to actually do network listening.
	// it's just an opportunity to get a pre-serve call.
	Listen() error
}

ListeningServer is a Server which wished to have its Listen() method called before Serve()

type LoggerFunc

type LoggerFunc func(level int, message string)

A LoggerFunc can be set to make the daemon internal events log to a custom log library

type RunOption

type RunOption func(*runcfg)

RunOption change the behaviour of Run()

func Configurator

func Configurator(f ConfigFunc) RunOption

Configurator gives Run() a ConfigFunc. This is the only mandatory RunOption (except you when you use the legacy InstantiateServers() option and supply a deprecated "ConfigureFunc" instead)

func ControlSocket

func ControlSocket(name, path string) RunOption

ControlSocket is an option to provude a systemd socket name and/or a path for the daemon control socket. Providing "","" disables the control socket.

func InstantiateServers

func InstantiateServers(f ConfigureFunc) RunOption

InstantiateServers gives Run() a ConfigureFunc. This is the only mandatory RunOption

func ReadyCallback

func ReadyCallback(f func() error) RunOption

ReadyCallback sets a function to be called when all servers have started without error

func SdNotifyOnReady

func SdNotifyOnReady(mainpid bool, status string) RunOption

SdNotifyOnReady makes Run() notify systemd with STATUS=READY when all servers have started. If mainpid is true, the MAINPID of the current process is also notified.

func ShutdownTimeout

func ShutdownTimeout(to time.Duration) RunOption

ShutdownTimeout is an option to Run() to control the default timeout value for graceful shutdowns. This is used when OS signals or similar crude interface triggers a graceful shutdown. Using a control socket you can provide the timeout duration at shutdown time.

func SignalParentOnReady

func SignalParentOnReady() RunOption

SignalParentOnReady sets a ReadyCallback which signals the parent process to terminate.

func SyncReload

func SyncReload() RunOption

SyncReload makes Run() Wait() for all servers before starting the next generation om Reload()

type Server

type Server interface {
	// Serve will start serving until the context is canceled at which
	// point it will stop generating new activity and exit.
	Serve(context.Context) error
}

Server is the interface of objects daemon.Run() will manage. These objects will be single-use only with a lifetime: Listen, Serve, Shutdown, - and possibly Close() if Shutdown exits non-nil

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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