Documentation
¶
Overview ¶
Package service provides a simple way to create a system service. Currently supports Windows, Linux/(systemd | Upstart | SysV | OpenRC), and OSX/Launchd.
Windows controls services by setting up callbacks that is non-trivial. This is very different then other systems. This package provides the same API despite the substantial differences. It also can be used to detect how a program is called, from an interactive terminal or from a service manager.
Examples in the example/ folder.
package main
import (
"log"
"github.com/admpub/service"
)
var logger service.Logger
type program struct{}
func (p *program) Start(s service.Service) error {
// Start should not block. Do the actual work async.
go p.run()
return nil
}
func (p *program) run() {
// Do work here
}
func (p *program) Stop(s service.Service) error {
// Stop should not block. Return with a few seconds.
return nil
}
func main() {
svcConfig := &service.Config{
Name: "GoServiceTest",
DisplayName: "Go Service Test",
Description: "This is a test Go service.",
}
prg := &program{}
s, err := service.New(prg, svcConfig)
if err != nil {
log.Fatal(err)
}
logger, err = s.Logger(nil)
if err != nil {
log.Fatal(err)
}
err = s.Run()
if err != nil {
logger.Error(err)
}
}
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNameFieldRequired is returned when Config.Name is empty. ErrNameFieldRequired = errors.New("Config.Name field is required.") // ErrNoServiceSystemDetected is returned when no system was detected. ErrNoServiceSystemDetected = errors.New("No service system detected.") // ErrNotInstalled is returned when the service is not installed. ErrNotInstalled = errors.New("the service is not installed") )
var ConsoleLogger = consoleLogger{}
ConsoleLogger logs to the std err.
var ControlAction = [5]string{"start", "stop", "restart", "install", "uninstall"}
ControlAction list valid string texts to use in Control.
Functions ¶
func ChooseSystem ¶
func ChooseSystem(a ...System)
ChooseSystem chooses a system from the given system services. SystemServices are considered in the order they are suggested. Calling this may change what Interactive and Platform return.
func Interactive ¶
func Interactive() bool
Interactive returns false if running under the OS service manager and true otherwise.
Types ¶
type Config ¶
type Config struct {
Name string // Required name of the service. No spaces suggested.
DisplayName string // Display name, spaces allowed.
Description string // Long description of service.
UserName string // Run as username.
Arguments []string // Run with arguments.
// Optional field to specify the executable for service.
// If empty the current executable is used.
Executable string
// Array of service dependencies.
// Not yet fully implemented on Linux or OS X:
// 1. Support linux-systemd dependencies, just put each full line as the
// element of the string array, such as
// "After=network.target syslog.target"
// "Requires=syslog.target"
// Note, such lines will be directly appended into the [Unit] of
// the generated service config file, will not check their correctness.
Dependencies []string
// The following fields are not supported on Windows.
WorkingDirectory string // Initial working directory.
ChRoot string
// System specific options.
Option KeyValue
EnvVars map[string]string
}
Config provides the setup for a Service. The Name field is required.
type Interface ¶
type Interface interface {
// Start provides a place to initiate the service. The service doesn't
// signal a completed start until after this function returns, so the
// Start function must not take more then a few seconds at most.
Start(s Service) error
// Stop provides a place to clean up program execution before it is terminated.
// It should not take more then a few seconds to execute.
// Stop should not call os.Exit directly in the function.
Stop(s Service) error
}
Interface represents the service interface for a program. Start runs before the hosting process is granted control and Stop runs when control is returned.
- OS service manager executes user program.
- User program sees it is executed from a service manager (IsInteractive is false).
- User program calls Service.Run() which blocks.
- Interface.Start() is called and quickly returns.
- User program runs.
- OS service manager signals the user program to stop.
- Interface.Stop() is called and quickly returns. - For a successful exit, os.Exit should not be called in Interface.Stop().
- Service.Run returns.
- User program should quickly exit.
type KeyValue ¶
type KeyValue map[string]interface{}
KeyValue provides a list of system specific options.
OS X
LaunchdConfig string () - Use custom launchd config.
KeepAlive bool (true) - Prevent the system from stopping the service automatically.
RunAtLoad bool (false) - Run the service after its job has been loaded.
SessionCreate bool (false) - Create a full user session.
Solaris
Prefix string ("application") - Service FMRI prefix.
POSIX
UserService bool (false) - Install as a current user service.
SystemdScript string () - Use custom systemd script.
UpstartScript string () - Use custom upstart script.
SysvScript string () - Use custom sysv script.
OpenRCScript string () - Use custom OpenRC script.
RunWait func() (wait for SIGNAL) - Do not install signal but wait for this function to return.
ReloadSignal string () [USR1, ...] - Signal to send on reload.
PIDFile string () [/run/prog.pid] - Location of the PID file.
LogOutput bool (false) - Redirect StdErr & StandardOutPath to files.
Restart string (always) - How shall service be restarted.
RestartSec int (120) - Delay seconds before restarting the service.
SuccessExitStatus string () - The list of exit status that shall be considered as successful, in addition to the default ones.
LogDirectory string(/var/log) - The path to the log files directory
Linux (systemd)
LimitNOFILE int (-1) - Maximum open files (ulimit -n) (https://serverfault.com/questions/628610/increasing-nproc-for-processes-launched-by-systemd-on-centos-7)
Windows
DelayedAutoStart bool (false) - After booting, start this service after some delay.
Password string () - Password to use when interfacing with the system service manager.
Interactive bool (false) - The service can interact with the desktop. (more information https://docs.microsoft.com/en-us/windows/win32/services/interactive-services)
DelayedAutoStart bool (false) - after booting start this service after some delay.
StartType string ("automatic") - Start service type. (automatic | manual | disabled)
OnFailure string ("restart" ) - Action to perform on service failure. (restart | reboot | noaction)
OnFailureDelayDuration string ( "1s" ) - Delay before restarting the service, time.Duration string.
OnFailureResetPeriod int ( 10 ) - Reset period for errors, seconds.
type Logger ¶
type Logger interface {
Error(v ...interface{}) error
Warning(v ...interface{}) error
Info(v ...interface{}) error
Errorf(format string, a ...interface{}) error
Warningf(format string, a ...interface{}) error
Infof(format string, a ...interface{}) error
}
Logger writes to the system log.
type Service ¶
type Service interface {
// Run should be called shortly after the program entry point.
// After Interface.Stop has finished running, Run will stop blocking.
// After Run stops blocking, the program must exit shortly after.
Run() error
// Start signals to the OS service manager the given service should start.
Start() error
// Stop signals to the OS service manager the given service should stop.
Stop() error
// Restart signals to the OS service manager the given service should stop then start.
Restart() error
// Install setups up the given service in the OS service manager. This may require
// greater rights. Will return an error if it is already installed.
Install() error
// Uninstall removes the given service from the OS service manager. This may require
// greater rights. Will return an error if the service is not present.
Uninstall() error
// Opens and returns a system logger. If the user program is running
// interactively rather then as a service, the returned logger will write to
// os.Stderr. If errs is non-nil errors will be sent on errs as well as
// returned from Logger's functions.
Logger(errs chan<- error) (Logger, error)
// SystemLogger opens and returns a system logger. If errs is non-nil errors
// will be sent on errs as well as returned from Logger's functions.
SystemLogger(errs chan<- error) (Logger, error)
// String displays the name of the service. The display name if present,
// otherwise the name.
String() string
// Platform displays the name of the system that manages the service.
// In most cases this will be the same as service.Platform().
Platform() string
// Status returns the current service status.
Status() (Status, error)
}
Service represents a service that can be run or controlled.
type Shutdowner ¶
type Shutdowner interface {
Interface
// Shutdown provides a place to clean up program execution when the system is being shutdown.
// It is essentially the same as Stop but for the case where machine is being shutdown/restarted
// instead of just normally stopping the service. Stop won't be called when Shutdown is.
Shutdown(s Service) error
}
Shutdowner represents a service interface for a program that differentiates between "stop" and "shutdown". A shutdown is triggered when the whole box (not just the service) is stopped.
type System ¶
type System interface {
// String returns a description of the system.
String() string
// Detect returns true if the system is available to use.
Detect() bool
// Interactive returns false if running under the system service manager
// and true otherwise.
Interactive() bool
// New creates a new service for this system.
New(i Interface, c *Config) (Service, error)
}
System represents the service manager that is available.
func AvailableSystems ¶
func AvailableSystems() []System
AvailableSystems returns the list of system services considered when choosing the system service.
func ChosenSystem ¶
func ChosenSystem() System
ChosenSystem returns the system that service will use.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
example
|
|
|
logging
command
Simple service that only works by printing a log message every few seconds.
|
Simple service that only works by printing a log message every few seconds. |
|
runner
command
Simple service that only works by printing a log message every few seconds.
|
Simple service that only works by printing a log message every few seconds. |
|
simple
command
simple does nothing except block while running the service.
|
simple does nothing except block while running the service. |
|
stopPause
command
simple does nothing except block while running the service.
|
simple does nothing except block while running the service. |