service

package
v1.0.9 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2024 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// New indicates that the service execution was created but not yet started.
	New = Status(0)
	// Down indicates that the service execution was run and is now done.
	Down = Status(1)
	// Running indicates that the service execution is still running.
	Running = Status(2)
	// Stopped indicates that the service execution is still running but a stop was initiated.
	Stopped = Status(3)
	// Killed indicates that the service execution is still running but a kill was initiated.
	Killed = Status(4)
	// Unknown indicates a status that should never happen. Please consult the log for more information.
	Unknown = Status(5)
)

Variables

View Source
var AllStatus = []Status{
	New,
	Down,
	Running,
	Stopped,
	Killed,
	Unknown,
}

AllStatus contains all possible variants of Status.

View Source
var AllTypes = []Type{
	OnDemand,
	AutoStart,
	Master,
}

AllTypes contains all possible variants of Type.

Functions

This section is empty.

Types

type AlreadyRunningError added in v0.1.6

type AlreadyRunningError struct {
	Name string
}

AlreadyRunningError indicates that a service was up but was expected to be down.

func (AlreadyRunningError) Error added in v0.1.6

func (instance AlreadyRunningError) Error() string

type AlreadyStoppedError added in v0.1.6

type AlreadyStoppedError struct {
	Name string
}

AlreadyStoppedError indicates that a service was up but was expected to be down.

func (AlreadyStoppedError) Error added in v0.1.6

func (instance AlreadyStoppedError) Error() string

type Config

type Config struct {
	// @default autoStart
	//
	// Defines how this service will be run by caretakerd.
	//
	// For details of possible values see {@ref github.com/echocat/caretakerd/values.RestartType}.
	//
	// > **Important**: Exactly one of the services have to be configured as
	// > {@ref github.com/echocat/caretakerd/service.Type#Master master}.
	Type Type `json:"type" yaml:"type"`

	// @default []
	//
	// The command the service process has to start with. The called command has to be run in the foreground - or in other words: Should not daemonize.
	//
	// > **Hint**: If there is no command line provided, this service cannot be started and caretakerd will
	// > fail.
	//
	// # PATH expansion
	//
	// The provided commands are resolved from the “PATH“ environment provided to caretakerd.
	// This makes it possible to use the names of the binaries like “sleep“ instead of “/usr/bin/sleep“.
	//
	// # Parameter evaluation
	//
	// Environment variables could be included like:
	// “`yaml
	// command: ["echo", "${MESSAGE}"]
	// environment:
	//     MESSAGE: "Hello world!"
	// “`
	//
	// “`bash
	// $ caretakerd run
	// Hello world!
	// “`
	//
	// # Special master handling
	//
	// If the service is configured as {@ref #Type type} = {@ref github.com/echocat/caretakerd/service.Type#Master master}
	// every parameter which was passed to caretakerd itself will be enriched to the called command line of the service process.
	//
	// Config example:
	// “`yaml
	// command: ["echo", "Hello"]
	// “`
	//
	// Run examples:
	// “`bash
	// $ caretakerd run
	// Hello
	//
	// $ caretakerd run "world!"
	// Hello world!
	// “`
	Command []values.String `json:"command" yaml:"command,flow"`

	// @default []
	//
	// Commands to be executed before execution of the actual {@ref #Command command}.
	//
	// If one of these commands fails, the whole service will also marked as failed. The actual
	// {@ref #Command command} will not be invoked and the {@ref #AutoRestart autoRestart} handling will be initiated.
	//
	// Only exit codes of value “0“ will be accepted as success.
	//
	// If there is a minus (“-“) provided as first item of the command, every error of this command will be ignored.
	//
	// Example:
	// “`yaml
	// preCommands:
	// - ["-", "program.sh", "prepare"]        # Ignore if fails
	// - ["program.sh", "prepareAndDoNotFail"] # Do not ignore if fails
	// command: ["program.sh", "run"]
	// “`
	PreCommands [][]values.String `json:"preCommands" yaml:"preCommands,flow"`

	// @default []
	//
	// Commands to be executed after execution of the actual {@ref #Command command}.
	//
	// Every result of these commands are ignored and will not force another behaviour - Exception: an error is logged.
	//
	// Only exit codes of value “0“ will be accepted as success.
	//
	// If there is a minus (“-“) provided as first item of the command, every error of this command will be ignored.
	//
	// Example:
	// “`yaml
	// command: ["program.sh", "run"]
	// postCommands:
	// - ["-", "program.sh", "cleanUp"]        # Ignore if fails
	// - ["program.sh", "cleanUpAndDoNotFail"] # Log if fails
	// “`
	PostCommands [][]values.String `json:"postCommands" yaml:"postCommands,flow"`

	// @default ""
	//
	// If configured this will trigger the service at this specific times. If not the service will
	// run as a normal process just once (except of the {@ref #AutoRestart autoRestart} handling).
	//
	// For details of possible values see {@ref github.com/echocat/caretakerd/service.CronExpression}.
	CronExpression CronExpression `json:"cronExpression" yaml:"cronExpression"`

	// @default 0
	//
	// Wait before the service process will start the first time.
	//
	// > **Hint:** Every run triggered by {@ref #CronExpression cronExpression} will also wait for this delay.
	StartDelayInSeconds values.NonNegativeInteger `json:"startDelayInSeconds" yaml:"startDelayInSeconds"`

	// @default [0]
	//
	// Every of these values represents an expected success exit code.
	// If a service ends with one of these values, the service will not be restarted.
	// Other values will trigger a auto restart if configured.
	//
	// See: {@ref #AutoRestart autoRestart}
	SuccessExitCodes values.ExitCodes `json:"successExitCodes" yaml:"successExitCodes,flow"`

	// @default "TERM"
	//
	// Signal which will be send to the service when a stop is requested.
	// You can use the signal number here and also names like “"TERM"“ or “"KILL"“.
	StopSignal values.Signal `json:"stopSignal" yaml:"stopSignal"`

	// @default "processGroup"
	//
	// Defines who have to receive the stop signal.
	//
	// > **Hint:** If the service have to be killed, always “processGroup“ is used.
	StopSignalTarget values.SignalTarget `json:"stopSignalTarget" yaml:"stopSignalTarget"`

	// @default []
	//
	// Command to be executed to stop the service.
	//
	// From the moment on this command is called, the {@ref #StopWaitInSeconds stopWaitInSeconds} are running.
	// It is not important when this stopCommand ends or what is the exit code.
	// If this command is executed and the service does not end within the configured {@ref #StopWaitInSeconds stopWaitInSeconds},
	// the service will be killed.
	//
	// Only exit codes of value “0“ will be accepted as success. Other codes are logged as error.
	//
	// If there is a minus (“-“) provided as first item of the command, every error of this command will be ignored.
	//
	// > **Hint:** If this property is configured, {@ref #StopSignal stopSignal} will not be evaluated.
	StopCommand []values.String `json:"stopCommand" yaml:"stopCommand,flow"`

	// @default 30
	//
	// Timeout to wait before killing the service process after a stop is requested.
	StopWaitInSeconds values.NonNegativeInteger `json:"stopWaitInSeconds" yaml:"stopWaitInSeconds"`

	// @default ""
	//
	// User under which the service process will be started.
	User values.String `json:"user" yaml:"user"`

	// @default []
	//
	// Environment variables to pass to the process.
	Environment Environments `json:"environment" yaml:"environment"`

	// @default true
	//
	// Additionally pass the environment variables started with caretakerd to the service process.
	InheritEnvironment values.Boolean `json:"inheritEnvironment" yaml:"inheritEnvironment"`

	// @default ""
	//
	// Working directory to start the service process in.
	Directory values.String `json:"directory" yaml:"directory"`

	// @default onFailures
	//
	// Configure how caretakerd will handle the end of a process.
	// It depends mainly on the {@ref #SuccessExitCodes successExitCodes} property.
	//
	// For details of possible values see {@ref github.com/echocat/caretakerd/values.RestartType}.
	AutoRestart values.RestartType `json:"autoRestart" yaml:"autoRestart"`

	// @default 5
	//
	// Seconds to wait before restart of a process.
	//
	// If a process should be restarted (because of {@ref #AutoRestart autoRestart}), caretakerd will wait this seconds before restart is initiated.
	RestartDelayInSeconds values.NonNegativeInteger `json:"restartDelayInSeconds" yaml:"restartDelayInSeconds"`

	// Configures the permission of this service to control caretakerd remotely
	// and how to obtain the credentials for it.
	//
	// For details see {@ref github.com/echocat/caretakerd/access.Config}.
	Access access.Config `json:"access" yaml:"access,omitempty"`

	// Configures the logger for this specific service.
	//
	// For details see {@ref github.com/echocat/caretakerd/logger.Config}.
	Logger logger.Config `json:"logger" yaml:"logger,omitempty"`
}

Represents the configuration of a service in caretakerd.

func NewConfig

func NewConfig() Config

NewConfig creates a new instance of Config.

func (*Config) UnmarshalYAML added in v1.0.0

func (instance *Config) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML is used until yaml unmarshalling. Do not call this method directly.

func (Config) Validate

func (instance Config) Validate() error

Validate validates actions on this object and returns an error object if there are any.

func (Config) WithCommand

func (instance Config) WithCommand(command ...values.String) Config

WithCommand reconfigures the current config instance with the given command.

type Configs

type Configs map[string]Config

Configs represents a couple of named service configs. @inline

func NewConfigs

func NewConfigs() Configs

NewConfigs creates a new instance of Configs.

func (*Configs) Configure

func (s *Configs) Configure(serviceName string, value string, with func(conf *Config, value string) error) error

Configure executes a configuring action for a service with the given name.

func (*Configs) ConfigureSub

func (s *Configs) ConfigureSub(serviceName string, key string, value string, with func(conf *Config, key string, value string) error) error

ConfigureSub executes a configuring action for a service with the given name.

func (*Configs) GetMasterName

func (s *Configs) GetMasterName() (string, bool)

GetMasterName returns the name of the configured master. If there is no valid master configured false is returned.

func (Configs) Validate

func (instance Configs) Validate() error

Validate validates actions on this object and returns an error object if there are any.

func (Configs) ValidateMaster

func (instance Configs) ValidateMaster() error

ValidateMaster validates whether there is exactly one service defined as master. Returns an error object if there are more services defined as masters.

type CronExpression

type CronExpression struct {
	// contains filtered or unexported fields
}

@serializedAs string # Description

A cron expression represents a set of times, using 6 space-separated fields.

| Field name | Mandatory | Allowed values | Allowed special characters | | ------------ | --------- | ------------------- | ------------------------------ | | Seconds | No | “0-59“ | “* / , -“ | | Minutes | Yes | “0-59“ | “* / , -“ | | Hours | Yes | “0-23“ | “* / , -“ | | Day of month | Yes | “1-31“ | “* / , - ?“ | | Month | Yes | “1-12 or JAN-DEC“ | “* / , -“ | | Day of week | Yes | “0-6 or SUN-SAT“ | “* / , - ?“ |

> **Note:** Month and Day-of-week field values are case insensitive. “SUN“, “Sun“, and “sun“ are equally accepted.

Special Characters

* **Asterisk** (“*“) The asterisk indicates that the cron expression will match all values of the field; e.g., using an asterisk in the 5th field (month) would match every month. * **Slash** (“/“) Slashes are used to describe increments of ranges. For example “3-59/15“ in the 1st field (minutes) would match the 3rd minute of the hour and every 15 minutes thereafter. The form “*\/...“ is equivalent to the form “first-last/...“, that is, an increment over the largest possible range of the field. The form “N/...“ is accepted as meaning “N-MAX/...“, that is, starting at N, use the increment until the end of that specific range. It does not wrap around. * **Comma** (“,“) Commas are used to separate items of a list. For example, using “MON,WED,FRI“ in the 5th field (day of week) would match Mondays, Wednesdays and Fridays. * **Hyphen** (“-“) Hyphens are used to define ranges. For example, “9-17“ would match every hour between 9am and 5pm (inclusive). * **Question mark** (“?“) Question marks may be used instead of “*“ for leaving either day-of-month or day-of-week blank.

Predefined schedules

You may use one of several pre-defined schedules in place of a cron expression.

| Entry | Description | Equivalent To | | ------------------------------ | ------------------------------------------ | --------------- | | “@yearly“ (or “@annually)“ | Run once a year, midnight, Jan. 1st | “0 0 0 1 1 *“ | | “@monthly“ | Run once a month, midnight, first of month | “0 0 0 1 * *“ | | “@weekly“ | Run once a week, midnight on Sunday | “0 0 0 * * 0“ | | “@daily (or @midnight)“ | Run once a day, midnight | “0 0 0 * * *“ | | “@hourly“ | Run once an hour, beginning of hour | “0 0 * * * *“ |

Intervals

You may also schedule a job to be executed at fixed intervals. This is supported by formatting the cron spec as follows: ``` @every <duration> ``` where “duration“ is a string accepted by time.ParseDuration(http://golang.org/pkg/time/#ParseDuration).

For example, “@every 1h30m10s“ would indicate a schedule that activates every 1 hour, 30 minutes, 10 seconds.

> **Hint:** The interval does not take the job runtime into account. For example, if a job takes 3 minutes to run and it is scheduled to run every 5 minutes, it will have only 2 minutes of idle time between each run.

func NewCronExpression

func NewCronExpression() CronExpression

NewCronExpression creates a new instance of CronExpression

func (CronExpression) IsEnabled

func (instance CronExpression) IsEnabled() bool

IsEnabled returns "true" if this expression is valid and enabled.

func (CronExpression) MarshalYAML

func (instance CronExpression) MarshalYAML() (interface{}, error)

MarshalYAML is used until yaml marshalling. Do not call this method directly.

func (CronExpression) Next

func (instance CronExpression) Next(from time.Time) *time.Time

Next returns the next possible time matching to this cron expression based on the given time.

func (*CronExpression) Set

func (instance *CronExpression) Set(value string) error

Set sets the given string to current object from a string. Returns an error object if there are any problems while transforming the string.

func (CronExpression) String

func (instance CronExpression) String() string

func (*CronExpression) UnmarshalYAML

func (instance *CronExpression) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML is used until yaml unmarshalling. Do not call this method directly.

type Environments

type Environments map[string]string

Environments represents a couple of key value pair environment variables. @inline

func (Environments) Append

func (i Environments) Append(value string) error

Append appends a string with format key=value to this instance.

func (*Environments) Put

func (i *Environments) Put(key string, value string) error

Put appends a key value pair to this instance.

func (*Environments) Set

func (i *Environments) Set(value string) error

Set sets the given string to a current object from a string. Returns an error object if there are any problems while transforming the string.

func (Environments) String

func (i Environments) String() string

type Execution

type Execution struct {
	// contains filtered or unexported fields
}

Execution represents an execution of a service. An execution could only be used one times.

func (*Execution) Kill

func (instance *Execution) Kill() error

Kill kills this execution if it is running. This method blocks until the execution is done.

func (*Execution) Name

func (instance *Execution) Name() string

Name returns the name of the owning service.

func (*Execution) PID added in v0.1.6

func (instance *Execution) PID() int

PID returns the PID of this execution if it is running - otherwise, it returns "0".

func (*Execution) Run

func (instance *Execution) Run() (values.ExitCode, error)

Run runs this execution. This method is a blocking method and could only be executed at this instance once.

func (Execution) Service

func (instance Execution) Service() *Service

Service returns the service this execution belongs to.

func (*Execution) Signal

func (instance *Execution) Signal(what values.Signal) error

Signal sends the given signal to this execution if it is running. This method is not a blocking method.

func (*Execution) Status

func (instance *Execution) Status() Status

Status returns the status of this execution.

func (*Execution) Stop

func (instance *Execution) Stop()

Stop stops this execution instance if it is running. This method blocks until the execution is done.

func (Execution) String added in v0.1.3

func (instance Execution) String() string

func (*Execution) SyncGroup added in v0.1.3

func (instance *Execution) SyncGroup() *sync.Group

SyncGroup returns the syncGroup this execution is using.

type Information

type Information struct {
	Config Config         `json:"config"`
	Status Status         `json:"status"`
	PID    values.Integer `json:"pid"`
}

Information represents the current status of a running execution of a service.

func NewInformationForExecution

func NewInformationForExecution(e *Execution) Information

NewInformationForExecution creates a new information instance for the given execution.

func NewInformationForService

func NewInformationForService(s *Service) Information

NewInformationForService creates a new information instance for the given service. This always means that there is no execution and the service is currently down.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service represents a service instance in caretakerd that was created from a Config object.

func NewService

func NewService(conf Config, name string, syncGroup *usync.Group, sec *keyStore.KeyStore) (*Service, error)

NewService creates a new service instance from the given Config.

func (*Service) Access

func (instance *Service) Access() *access.Access

Access returns the access instance this service uses.

func (*Service) Close

func (instance *Service) Close()

Close closes all resources of this service.

func (Service) Config

func (instance Service) Config() Config

Config returns the config that was used to create this service.

func (Service) Logger

func (instance Service) Logger() *logger.Logger

Logger returns the logger this service uses.

func (Service) Name

func (instance Service) Name() string

Name returns the name of this service.

func (*Service) NewExecution

func (instance *Service) NewExecution(sec *keyStore.KeyStore) (*Execution, error)

NewExecution creates a new instance of Execution.

func (Service) String

func (instance Service) String() string

type Services

type Services map[string]*Service

Services is a couple of services with their names.

func NewServices

func NewServices(configs Configs, syncGroup *usync.Group, sec *keyStore.KeyStore) (*Services, error)

NewServices creates a new instance of Services from the given Configs.

func (Services) Close

func (instance Services) Close()

Close closes this instance and all of the services.

func (Services) Get

func (instance Services) Get(name string) *Service

Get returns a service for the given name if a service exists. If no service for the given name could be found, "nil" is returned.

func (Services) GetAllAutoStartable

func (instance Services) GetAllAutoStartable() Services

GetAllAutoStartable returns every service that is autostartable.

func (Services) GetAllButMaster

func (instance Services) GetAllButMaster() Services

GetAllButMaster returns every service but not the master.

func (Services) GetMaster

func (instance Services) GetMaster() *Service

GetMaster returns the master of this instance. If there is no master, "nil" is returned.

func (Services) GetMasterOrFail

func (instance Services) GetMasterOrFail() *Service

GetMasterOrFail returns the master, if a master exists. Otherwise it will fail with a panic.

type Status

type Status int

Status represents a status of a service execution.

func (Status) CheckedString added in v0.1.6

func (instance Status) CheckedString() (string, error)

CheckedString is like String but also returns an optional error if there are any validation errors.

func (Status) IsGoDownRequest

func (instance Status) IsGoDownRequest() bool

IsGoDownRequest returns "true" if the status indicates that the service must be stopped.

func (Status) MarshalJSON

func (instance Status) MarshalJSON() ([]byte, error)

MarshalJSON is used until json marshalling. Do not call this method directly.

func (*Status) Set

func (instance *Status) Set(value string) error

Set sets the given string to the current object from a string. Returns an error object if there are any problems while transforming the string.

func (Status) String

func (instance Status) String() string

func (*Status) UnmarshalJSON

func (instance *Status) UnmarshalJSON(b []byte) error

UnmarshalJSON is used until json unmarshalling. Do not call this method directly.

func (Status) Validate

func (instance Status) Validate() error

Validate validates actions on this object and returns an error object if there are any.

type StoppedOrKilledError

type StoppedOrKilledError struct {
	// contains filtered or unexported fields
}

StoppedOrKilledError indicates not a real problem. It means that the service was stopped or killed.

type Type

type Type int

Description

Identifies the different ways caretakerd handles services.

const (
	// @id onDemand
	//
	// The service is not automatically started by caretakerd.
	// You have to use [“caretakerctl“](#commands.caretakerctl) or execute an RPC call from another service
	// to start it.
	//
	// This service will be automatically stopped if the {@ref #Master master} was also stopped.
	OnDemand Type = 0
	// @id autoStart
	//
	// This services is automatically started by caretakerd.
	//
	// This service will be automatically stopped if the {@ref #Master master} was also stopped.
	AutoStart Type = 1
	// @id master
	//
	// This service is automatically started by caretakerd and influences all other services.
	//
	// > **Important:** One of all available services must be specified as “master“.
	//
	// Every other service lives and dies together with the “master“.
	Master Type = 2
)

func (Type) CheckedString

func (instance Type) CheckedString() (string, error)

CheckedString is like String but also returns an optional error if there are any validation errors.

func (Type) IsAutoStartable

func (instance Type) IsAutoStartable() bool

IsAutoStartable returns "true" if the given type indicates that the service have to be started automatically together with caretakerd.

func (Type) MarshalJSON

func (instance Type) MarshalJSON() ([]byte, error)

MarshalJSON is used until json marshalling. Do not call this method directly.

func (Type) MarshalYAML

func (instance Type) MarshalYAML() (interface{}, error)

MarshalYAML is used until yaml marshalling. Do not call this method directly.

func (*Type) Set

func (instance *Type) Set(value string) error

Set the given string to current object from a string. Returns an error object if there are any problems while transforming the string.

func (Type) String

func (instance Type) String() string

func (*Type) UnmarshalJSON

func (instance *Type) UnmarshalJSON(b []byte) error

UnmarshalJSON is used until json unmarshalling. Do not call this method directly.

func (*Type) UnmarshalYAML

func (instance *Type) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML is used until yaml unmarshalling. Do not call this method directly.

func (Type) Validate

func (instance Type) Validate() error

Validate validates actions on this object and returns an error object if there are any.

type UnrecoverableError

type UnrecoverableError struct {
	// contains filtered or unexported fields
}

UnrecoverableError indicates a problem that could not be recovered by a restart of a service.

Jump to

Keyboard shortcuts

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