service

package
v0.19.1 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2024 License: Apache-2.0 Imports: 54 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AuthorizationHeader = "Authorization"
	BearerPrefix        = "bearer "
)
View Source
const (
	UpgradeEntryTypeAgent       = "agent"
	UpgradeEntryTypeDBServer    = "dbserver"
	UpgradeEntryTypeCoordinator = "coordinator"
	UpgradeEntryTypeSingle      = "single"
)
View Source
const (
	DefaultMasterPort = 8528
)

Variables

View Source
var (
	JobStateToDo     = JobState("ToDo")
	JobStatePending  = JobState("Pending")
	JobStateFinished = JobState("Finished")
	JobStateFailed   = JobState("Failed")

	ErrJobNotFound = errors.New("job not found")
	ErrJobFailed   = errors.New("job failed")
)

Functions

func CreateCertificate

func CreateCertificate(options CreateCertificateOptions, folder string) (string, error)

CreateCertificate creates a self-signed certificate according to the given configuration. The resulting certificate + private key will be written into a single file in the given folder. The path of that single file is returned.

func CreateJwtToken

func CreateJwtToken(jwtSecret, user string, serverId string, paths []string, exp time.Duration, fieldsOverride jwt.MapClaims) (string, error)

CreateJwtToken calculates a JWT authorization token based on the given secret. If the secret is empty, an empty token is returned.

func DatabaseVersion added in v0.18.0

func DatabaseVersion(ctx context.Context, log zerolog.Logger, arangodPath string, runner Runner) (driver.Version, bool, error)

DatabaseVersion returns the version of the `arangod` binary

func FilterFiles

func FilterFiles(f []os.FileInfo, filter func(f os.FileInfo) bool) []os.FileInfo

func FilterOnlyFiles

func FilterOnlyFiles(f os.FileInfo) bool

func GuessOwnAddress

func GuessOwnAddress() (string, error)

GuessOwnAddress takes a "best guess" approach to find the IP address used to reach the host PC.

func IsArangoErrorWithCodeAndNum

func IsArangoErrorWithCodeAndNum(aerr driver.ArangoError, code, errorNum int) bool

IsArangoErrorWithCodeAndNum returns true when the given raw content contains a valid arangodb error encoded as json with the given code and errorNum values.

func IsLeadershipChallengeOngoingError

func IsLeadershipChallengeOngoingError(d driver.ArangoError) bool

IsLeadershipChallengeOngoingError returns true when given response content contains an arango error indicating an ongoing leadership challenge.

func IsNoLeaderError

func IsNoLeaderError(d driver.ArangoError) bool

IsNoLeaderError returns true when given response content contains an arango error indicating an "I'm not the leader" error.

func IsPortOpen

func IsPortOpen(host string, port int) bool

IsPortOpen checks if a TCP port is free to listen on.

func IsRedirect

func IsRedirect(err error) (string, bool)

func IsSpecialUpgradeFrom3614 added in v0.17.1

func IsSpecialUpgradeFrom3614(v driver.Version) bool

IsSpecialUpgradeFrom3614 determines if special case for upgrade is required

func LoadKeyFile

func LoadKeyFile(keyFile string) (tls.Certificate, error)

LoadKeyFile loads a SSL keyfile formatted for the arangod server.

func RemoveSetupConfig

func RemoveSetupConfig(log zerolog.Logger, dataDir string) error

RemoveSetupConfig tries to remove a setup.json config file.

func Sha256sum

func Sha256sum(d []byte) string

func WaitForFinishedJob

func WaitForFinishedJob(progress actions.Progressor, ctx context.Context, jobID string, agencyClient agency.Agency) error

WaitForFinishedJob waits for the job to be finished until context is canceled. If the job fails the error ErrJobFailed is returned.

func WaitUntilPortAvailable

func WaitUntilPortAvailable(host string, port int, timeout time.Duration) bool

WaitUntilPortAvailable waits until a TCP port is free to listen on or a timeout occurs. Returns true when port is free to listen on.

Types

type ActionResignLeadership

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

ActionResignLeadership describes action for the leadership resignation.

func (*ActionResignLeadership) Condition

func (a *ActionResignLeadership) Condition(serverType definitions.ServerType) bool

Condition returns true if this action should be launched.

func (*ActionResignLeadership) Name

func (a *ActionResignLeadership) Name() string

Name returns name of the action.

func (*ActionResignLeadership) PreStop

func (a *ActionResignLeadership) PreStop(ctx context.Context, progress actions.Progressor) error

PreStop runs action before server is stopped.

func (*ActionResignLeadership) Timeout

func (a *ActionResignLeadership) Timeout() time.Duration

Timeout returns how long it should wait for the action to be finished.

type BootstrapConfig

type BootstrapConfig struct {
	ID                            string      // Unique identifier of this peer
	Mode                          ServiceMode // Service mode cluster|single
	DataDir                       string
	AgencySize                    int    // Number of agents in the agency
	StartLocalSlaves              bool   // If set, start sufficient slave (Service's) locally.
	StartAgent                    *bool  // If not nil, sets if starter starts a agent, otherwise default handling applies
	StartDBserver                 *bool  // If not nil, sets if starter starts a dbserver, otherwise default handling applies
	StartCoordinator              *bool  // If not nil, sets if starter starts a coordinator, otherwise default handling applies
	ServerStorageEngine           string // mmfiles | rocksdb
	JwtSecret                     string // JWT secret used for arangod communication
	ArangosyncMonitoringToken     string // Bearer token used for arangosync authentication
	SslKeyFile                    string // Path containing an x509 certificate + private key to be used by the servers.
	SslCAFile                     string // Path containing an x509 CA certificate used to authenticate clients.
	RocksDBEncryptionKeyFile      string // Path containing encryption key for RocksDB encryption.
	RocksDBEncryptionKeyGenerator string // Path to program. The output of this program will be used as key for RocksDB encryption.
	DisableIPv6                   bool   // If set, no IPv6 notation will be used
	RecoveryAgentID               string `json:"-"` // ID of the agent. Only set during recovery
}

BootstrapConfig holds all configuration for a service that will not change through the lifetime of a cluster.

func (*BootstrapConfig) CreateTLSConfig

func (bsCfg *BootstrapConfig) CreateTLSConfig() (*tls.Config, error)

CreateTLSConfig creates a TLS config based on given bootstrap config

func (*BootstrapConfig) Initialize

func (bsCfg *BootstrapConfig) Initialize() error

Initialize auto-configures some optional values

func (*BootstrapConfig) JWTFolderDir

func (bsCfg *BootstrapConfig) JWTFolderDir() string

func (*BootstrapConfig) JWTFolderDirFile

func (bsCfg *BootstrapConfig) JWTFolderDirFile(f string) string

func (*BootstrapConfig) LoadFromSetupConfig added in v0.17.1

func (bsCfg *BootstrapConfig) LoadFromSetupConfig(cfg SetupConfigFile)

LoadFromSetupConfig loads important values from setup config file

func (*BootstrapConfig) PeersNeeded

func (bsCfg *BootstrapConfig) PeersNeeded() int

PeersNeeded returns the minimum number of peers needed for the given config.

type ClientBuilder

type ClientBuilder interface {
	// ClientBuilder creates authenticated go-driver clients with or without follow-redirect.
	CreateClient(endpoints []string, connectionType ConnectionType, serverType definitions.ServerType) (driver.Client, error)
}

ClientBuilder describes how to create connections to the specific instance of the cluster.

type ClusterConfig

type ClusterConfig struct {
	AllPeers            []Peer                    `json:"Peers"` // All peers
	AgencySize          int                       // Number of agents
	LastModified        *time.Time                `json:"LastModified,omitempty"`        // Time of last modification
	PortOffsetIncrement int                       `json:"PortOffsetIncrement,omitempty"` // Increment of port offsets for peers on same address
	ServerStorageEngine string                    `json:"ServerStorageEngine,omitempty"` // Storage engine being used
	PersistentOptions   options.PersistentOptions `json:"PersistentOptions,omitempty"`   // Options which were used during first start of DB and can't be changed anymore
}

ClusterConfig contains all the information of a cluster from a starter's point of view. When this type (or any of the types used in here) is changed, increase `SetupConfigVersion`.

func (*ClusterConfig) AddPeer

func (p *ClusterConfig) AddPeer(newPeer Peer) bool

AddPeer adds the given peer to the list of all peers, only if the id is not yet one of the peers. Returns true of success, false otherwise

func (ClusterConfig) AllAgents

func (p ClusterConfig) AllAgents() []Peer

AllAgents returns a list of all peers that have an agent.

func (ClusterConfig) CreateAgencyAPI

func (p ClusterConfig) CreateAgencyAPI(clientBuilder ClientBuilder) (agency.Agency, error)

CreateAgencyAPI creates a client for the agency

func (ClusterConfig) CreateClusterAPI

func (p ClusterConfig) CreateClusterAPI(ctx context.Context, clientBuilder ClientBuilder) (driver.Cluster, error)

CreateClusterAPI creates a client for the cluster

func (ClusterConfig) CreateCoordinatorsClient

func (p ClusterConfig) CreateCoordinatorsClient(jwtSecret string) (driver.Client, error)

CreateCoordinatorsClient creates go-driver client targeting the coordinators.

func (*ClusterConfig) ForEachPeer added in v0.17.1

func (p *ClusterConfig) ForEachPeer(updateFunc func(p Peer) Peer)

ForEachPeer updates all peers using predicate

func (ClusterConfig) GetAgentEndpoints

func (p ClusterConfig) GetAgentEndpoints() ([]string, error)

GetAgentEndpoints creates a list of URL's for all agents.

func (ClusterConfig) GetCoordinatorEndpoints

func (p ClusterConfig) GetCoordinatorEndpoints() ([]string, error)

GetCoordinatorEndpoints creates a list of URL's for all coordinators.

func (ClusterConfig) GetDBServerEndpoints

func (p ClusterConfig) GetDBServerEndpoints() ([]string, error)

GetDBServerEndpoints creates a list of URL's for all dbservers.

func (ClusterConfig) GetFreePortOffset

func (p ClusterConfig) GetFreePortOffset(peerAddress string, basePort int, allPortOffsetsUnique bool) int

GetFreePortOffset returns the first unallocated port offset.

func (ClusterConfig) GetPeerEndpoints

func (p ClusterConfig) GetPeerEndpoints() ([]string, error)

GetPeerEndpoints creates a list of URL's for all peer.

func (ClusterConfig) GetSingleEndpoints

func (p ClusterConfig) GetSingleEndpoints() ([]string, error)

GetSingleEndpoints creates a list of URL's for all single servers.

func (ClusterConfig) HaveEnoughAgents

func (p ClusterConfig) HaveEnoughAgents() bool

HaveEnoughAgents returns true when the number of peers that have an agent is greater or equal to AgencySize.

func (ClusterConfig) IDs

func (p ClusterConfig) IDs() []string

IDs returns the IDs of all peers.

func (*ClusterConfig) Initialize

func (p *ClusterConfig) Initialize(initialPeer Peer, agencySize int, storageEngine string, persistentOptions options.PersistentOptions)

Initialize a new cluster configuration

func (ClusterConfig) IsSecure

func (p ClusterConfig) IsSecure() bool

IsSecure returns true if any of the peers is secure.

func (ClusterConfig) NextPortOffset

func (p ClusterConfig) NextPortOffset(portOffset int) int

NextPortOffset returns the next port offset (from given offset)

func (ClusterConfig) PeerByAddressAndPort

func (p ClusterConfig) PeerByAddressAndPort(address string, port int) (Peer, bool)

PeerByAddressAndPort returns a peer with given address, port & true, or false if not found.

func (ClusterConfig) PeerByID

func (p ClusterConfig) PeerByID(id string) (Peer, bool)

PeerByID returns a peer with given id & true, or false if not found.

func (*ClusterConfig) RemovePeerByID

func (p *ClusterConfig) RemovePeerByID(id string) bool

RemovePeerByID removes the peer with given ID.

func (*ClusterConfig) UpdatePeerByID

func (p *ClusterConfig) UpdatePeerByID(update Peer) bool

UpdatePeerByID updates the peer with given id & true, or false if not found.

type Config

type Config struct {
	ArangodPath          string
	ArangodJSPath        string
	AdvertisedEndpoint   string
	MasterPort           int
	RrPath               string
	DataDir              string
	LogDir               string // Custom directory to which log files are written (default "")
	OwnAddress           string // IP address of used to reach this process
	BindAddress          string // IP address the HTTP server binds to (typically '0.0.0.0')
	MasterAddresses      []string
	Verbose              bool
	ServerThreads        int  // If set to something other than 0, this will be added to the commandline of each server with `--server.threads`...
	AllPortOffsetsUnique bool // If set, all peers will get a unique port offset. If false (default) only portOffset+peerAddress pairs will be unique.
	Configuration        *options.Configuration
	DebugCluster         bool
	LogRotateFilesToKeep int
	LogRotateInterval    time.Duration
	InstanceUpTimeout    time.Duration

	DockerConfig       DockerConfig
	DockerStarterImage string
	RunningInDocker    bool

	ProjectVersion string
	ProjectBuild   string
}

Config holds all configuration for a single service.

func (Config) CreateRunner

func (c Config) CreateRunner(log zerolog.Logger) (Runner, Config, bool)

CreateRunner creates a process runner based on given configuration. Returns: Runner, updated configuration, allowSameDataDir

func (Config) GetNetworkEnvironment

func (c Config) GetNetworkEnvironment(log zerolog.Logger) (Config, int, bool)

GetNetworkEnvironment loads information about the network environment based on the given config and returns an updated config, the announce port and isNetHost.

func (Config) GuessOwnAddress

func (c Config) GuessOwnAddress(log zerolog.Logger, bsCfg BootstrapConfig) Config

GuessOwnAddress fills in the OwnAddress field if needed and returns an update config.

func (Config) UseDockerRunner

func (c Config) UseDockerRunner() bool

UseDockerRunner returns true if the docker runner should be used. (instead of the local process runner).

type ConnectionType

type ConnectionType int
const (
	ConnectionTypeDatabase ConnectionType = iota
	ConnectionTypeAgency
)

type CreateCertificateOptions

type CreateCertificateOptions struct {
	Hosts        []string // Host names and/or IP addresses
	ValidFor     time.Duration
	Organization string
}

CreateCertificateOptions configures how to create a certificate.

type DatabaseFeatures

type DatabaseFeatures struct {
	Version    driver.Version
	Enterprise bool
}

DatabaseFeatures provides information about the features provided by the database in a given version.

func NewDatabaseFeatures

func NewDatabaseFeatures(version driver.Version, enterprise bool) DatabaseFeatures

NewDatabaseFeatures returns a new DatabaseFeatures based on the given version.

func (DatabaseFeatures) DefaultStorageEngine

func (v DatabaseFeatures) DefaultStorageEngine() string

DefaultStorageEngine returns the default storage engine (mmfiles|rocksdb).

func (DatabaseFeatures) GetJWTFolderOption

func (v DatabaseFeatures) GetJWTFolderOption() bool

func (DatabaseFeatures) HasCopyInstallationFiles

func (v DatabaseFeatures) HasCopyInstallationFiles() bool

HasCopyInstallationFiles does server support copying installation files

func (DatabaseFeatures) HasJWTSecretFileOption

func (v DatabaseFeatures) HasJWTSecretFileOption() bool

HasJWTSecretFileOption does the server support passing jwt secret by file

func (DatabaseFeatures) HasStorageEngineOption

func (v DatabaseFeatures) HasStorageEngineOption() bool

HasStorageEngineOption returns true when `server.storage-engine` option is supported.

func (DatabaseFeatures) SupportsActiveFailover added in v0.18.0

func (v DatabaseFeatures) SupportsActiveFailover() bool

SupportsActiveFailover returns true if Active-Failover (resilient-single) mode is supported

func (DatabaseFeatures) SupportsArangoSync added in v0.18.3

func (v DatabaseFeatures) SupportsArangoSync() bool

SupportsArangoSync returns true if ArangoSync is supported

type DockerConfig added in v0.18.0

type DockerConfig struct {
	Endpoint          string
	User              string
	HostContainerName string
	GCDelay           time.Duration
	NetworkMode       string
	Privileged        bool
	TTY               bool
	ImagePullPolicy   ImagePullPolicy

	ImageArangoD string
}

type HelloRequest

type HelloRequest struct {
	SlaveID      string // Unique ID of the slave
	SlaveAddress string // IP address used to reach the slave (if empty, this will be derived from the request)
	SlavePort    int    // Port used to reach the slave
	DataDir      string // Directory used for data by this slave
	IsSecure     bool   // If set, servers started by this peer are using an SSL connection
	Agent        *bool  `json:",omitempty"` // If not nil, sets if server gets an agent or not. If nil, default handling applies
	DBServer     *bool  `json:",omitempty"` // If not nil, sets if server gets an dbserver or not. If nil, default handling applies
	Coordinator  *bool  `json:",omitempty"` // If not nil, sets if server gets an coordinator or not. If nil, default handling applies
}

HelloRequest is the data structure send of the wire in a `/hello` POST request.

type ImagePullPolicy

type ImagePullPolicy string
const (
	// ImagePullPolicyAlways is a policy to always pull the image
	ImagePullPolicyAlways ImagePullPolicy = "Always"
	// ImagePullPolicyIfNotPresent is a policy to only pull the image when it does not exist locally
	ImagePullPolicyIfNotPresent ImagePullPolicy = "IfNotPresent"
	// ImagePullPolicyNever is a policy to never pull the image
	ImagePullPolicyNever ImagePullPolicy = "Never"
)

func ParseImagePullPolicy

func ParseImagePullPolicy(s, image string) (ImagePullPolicy, error)

ParseImagePullPolicy parses a string into an image pull policy

type JobState

type JobState string

type JobStatus

type JobStatus struct {
	Reason string `json:"reason,omitempty"`
	Server string `json:"server,omitempty"`
	JobID  string `json:"jobId,omitempty"`
	Type   string `json:"type,omitempty"`
	// contains filtered or unexported fields
}

type Peer

type Peer struct {
	ID         string // Unique ID of the peer
	Address    string // IP address of arangodb peer server
	Port       int    // Port number of arangodb peer server
	PortOffset int    // Offset to add to base ports for the various servers (agent, coordinator, dbserver)
	DataDir    string // Directory holding my data

	IsSecure bool // If set, servers started by this peer are using an SSL connection
	// contains filtered or unexported fields
}

Peer contains all persistent settings of a starter.

func (Peer) CreateAgentAPI

func (p Peer) CreateAgentAPI(clientBuilder ClientBuilder) (driver.Client, error)

CreateAgentAPI creates a client for the agent of the peer

func (Peer) CreateClient

func (p Peer) CreateClient(clientBuilder ClientBuilder, t definitions.ServerType) (driver.Client, error)

func (Peer) CreateCoordinatorAPI

func (p Peer) CreateCoordinatorAPI(clientBuilder ClientBuilder) (driver.Client, error)

CreateCoordinatorAPI creates a client for the coordinator of the peer

func (Peer) CreateDBServerAPI

func (p Peer) CreateDBServerAPI(clientBuilder ClientBuilder) (driver.Client, error)

CreateDBServerAPI creates a client for the dbserver of the peer

func (Peer) CreateStarterURL

func (p Peer) CreateStarterURL(relPath string) string

CreateStarterURL creates a URL to the relative path to the starter on this peer.

func (Peer) HasAgent

func (p Peer) HasAgent() bool

HasAgent returns true if this peer is running an agent

func (Peer) HasCoordinator

func (p Peer) HasCoordinator() bool

HasCoordinator returns true if this peer is running a coordinator

func (Peer) HasDBServer

func (p Peer) HasDBServer() bool

HasDBServer returns true if this peer is running a dbserver

func (Peer) PortRangeOverlaps

func (p Peer) PortRangeOverlaps(otherPort int, clusterConfig ClusterConfig) bool

PortRangeOverlaps returns true if the port range of this peer overlaps with a port range starting at given port.

type PermanentError

type PermanentError struct {
	Err error
}

func (*PermanentError) Error

func (e *PermanentError) Error() string

type Process

type Process interface {
	// ProcessID returns the pid of the process (if not running in docker)
	ProcessID() int
	// ContainerID returns the ID of the docker container that runs the process.
	ContainerID() string
	// ContainerIP returns the IP address of the docker container that runs the process.
	ContainerIP() string
	// HostPort returns the port on the host that is used to access the given port of the process.
	HostPort(containerPort int) (int, error)

	// Wait until the process has terminated and return exit code
	Wait() int
	// WaitCh returns unbuffered channel which will send exit code when process is terminated
	WaitCh() <-chan int
	// Terminate performs a graceful termination of the process
	Terminate() error
	// Kill performs a hard termination of the process
	Kill() error
	// Hup sends a SIGHUP to the process
	Hup() error

	// Cleanup removes all traces of this process
	Cleanup() error

	// GetLogger creates a new logger for the process.
	GetLogger(logger zerolog.Logger) zerolog.Logger
}

type ProcessWrapper

type ProcessWrapper interface {
	// Wait blocks until process terminates
	// Returns true if process was already terminated or it has terminated in time
	Wait(timeout time.Duration) bool

	Process() Process
}

func NewProcessWrapper

func NewProcessWrapper(s *runtimeServerManager, ctx context.Context, log zerolog.Logger, runtimeContext runtimeServerManagerContext, runner Runner,
	config Config, bsCfg BootstrapConfig, myPeer Peer, serverType definitions.ServerType, gracePeriod time.Duration) ProcessWrapper

type RedirectError

type RedirectError struct {
	Location string
}

func (RedirectError) Error

func (e RedirectError) Error() string

type Runner

type Runner interface {
	// Map the given host directory to a container directory
	GetContainerDir(hostDir, defaultContainerDir string) string

	// GetRunningServer checks if there is already a server process running in the given server directory.
	// If that is the case, its process is returned.
	// Otherwise nil is returned.
	GetRunningServer(serverDir string) (Process, error)

	// Start a server with given arguments
	Start(ctx context.Context, processType definitions.ProcessType, command string, args []string, envs map[string]string, volumes []Volume, ports []int, containerName, serverDir string, output io.Writer) (Process, error)

	// Create a command that a user should use to start a slave arangodb instance.
	CreateStartArangodbCommand(myDataDir string, index int, masterIP, masterPort, starterImageName string, clusterConfig ClusterConfig) string

	// Cleanup after all processes are dead and have been cleaned themselves
	Cleanup() error
}

func NewDockerRunner

func NewDockerRunner(log zerolog.Logger, d DockerConfig) (Runner, error)

NewDockerRunner creates a runner that starts processes in a docker container.

func NewProcessRunner

func NewProcessRunner(log zerolog.Logger) Runner

NewProcessRunner creates a runner that starts processes on the local OS.

type Service

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

Service implements the actual starter behavior of the ArangoDB starter.

func NewService

func NewService(ctx context.Context, log zerolog.Logger, logService logging.Service, config Config, bsCfg BootstrapConfig, isLocalSlave bool) *Service

NewService creates a new Service instance from the given config.

func (*Service) ChangeState

func (s *Service) ChangeState(newState State)

ChangeState alters the current state of the service

func (*Service) ClusterConfig

func (s *Service) ClusterConfig() (ClusterConfig, *Peer, ServiceMode)

ClusterConfig returns the current cluster configuration and the current peer

func (*Service) CreateClient

func (s *Service) CreateClient(endpoints []string, connectionType ConnectionType, serverType definitions.ServerType) (driver.Client, error)

CreateClient creates a go-driver client with authentication for the given endpoints.

func (*Service) DatabaseFeatures

func (s *Service) DatabaseFeatures() DatabaseFeatures

DatabaseFeatures returns the detected database features.

func (*Service) DatabaseVersion

func (s *Service) DatabaseVersion(ctx context.Context) (driver.Version, bool, error)

DatabaseVersion returns the version of the `arangod` binary that is being used by this starter.

func (*Service) GetLocalFolder

func (s *Service) GetLocalFolder() string

func (*Service) HandleGoodbye

func (s *Service) HandleGoodbye(id string, force bool) (peerRemoved bool, err error)

HandleGoodbye removes the database servers started by the peer with given id from the cluster and alters the cluster configuration, removing the peer.

func (*Service) HandleHello

func (s *Service) HandleHello(ownAddress, remoteAddress string, req *HelloRequest, isUpdateRequest bool) (ClusterConfig, error)

HandleHello handles a hello request. If req==nil, this is a GET request, otherwise it is a POST request.

func (*Service) IsLocalSlave

func (s *Service) IsLocalSlave() bool

IsLocalSlave returns true if this peer is running as a local slave

func (*Service) IsRunningMaster

func (s *Service) IsRunningMaster() (isRunningMaster, isRunning bool, masterURL string)

IsRunningMaster returns if the starter is the running master.

func (*Service) IsSecure

func (s *Service) IsSecure() bool

IsSecure returns true when the cluster is using SSL for connections, false otherwise.

func (*Service) PerformRecovery

func (s *Service) PerformRecovery(ctx context.Context, bsCfg BootstrapConfig) (BootstrapConfig, error)

PerformRecovery looks for a RECOVERY file in the data directory and performs a recovery of such a file exists.

func (*Service) PrepareDatabaseServerRequestFunc

func (s *Service) PrepareDatabaseServerRequestFunc() func(*http.Request) error

PrepareDatabaseServerRequestFunc returns a function that is used to prepare a request to a database server (including authentication).

func (*Service) RestartServer

func (s *Service) RestartServer(serverType definitions.ServerType) error

RestartServer triggers a restart of the server of the given type.

func (*Service) RotateLogFiles

func (s *Service) RotateLogFiles(ctx context.Context)

RotateLogFiles rotates the log files of all servers

func (*Service) Run

func (s *Service) Run(rootCtx context.Context, bsCfg BootstrapConfig, clusterConfig ClusterConfig, shouldRelaunch bool) error

Run runs the service in either master or slave mode.

func (*Service) Stop

func (s *Service) Stop()

Stop the peer

func (*Service) TestInstance

func (s *Service) TestInstance(ctx context.Context, serverType definitions.ServerType, address string, port int,
	statusChanged chan StatusItem) (up, correctRole bool, version, role, mode string, statusTrail []int, cancelled bool)

TestInstance checks the `up` status of an arangod server instance.

func (*Service) UpdateClusterConfig

func (s *Service) UpdateClusterConfig(newConfig ClusterConfig)

UpdateClusterConfig updates the current cluster configuration.

func (*Service) UpgradeManager

func (s *Service) UpgradeManager() UpgradeManager

UpgradeManager returns the upgrade manager service.

type ServiceMode

type ServiceMode string
const (
	ServiceModeCluster ServiceMode = "cluster"
	ServiceModeSingle  ServiceMode = "single"
)

func (ServiceMode) HasAgency

func (m ServiceMode) HasAgency() bool

HasAgency returns true when the given mode involves an agency.

func (ServiceMode) IsClusterMode

func (m ServiceMode) IsClusterMode() bool

IsClusterMode returns true when the service is running in cluster mode.

func (ServiceMode) IsSingleMode

func (m ServiceMode) IsSingleMode() bool

IsSingleMode returns true when the service is running in single server mode.

func (ServiceMode) SupportsRecovery

func (m ServiceMode) SupportsRecovery() bool

SupportsRecovery returns true when the given mode support recovering from permanent failed machines.

type SetupConfigFile

type SetupConfigFile struct {
	Version          string        `json:"version"` // Version of the process that created this. If the structure or semantics changed, you must increase this version.
	ID               string        `json:"id"`      // My unique peer ID
	Peers            ClusterConfig `json:"peers"`
	StartLocalSlaves bool          `json:"start-local-slaves,omitempty"`
	Mode             ServiceMode   `json:"mode,omitempty"` // Starter mode (cluster|single)
	SslKeyFile       string        `json:"ssl-keyfile,omitempty"`
	JwtSecret        string        `json:"jwt-secret,omitempty"`
}

SetupConfigFile is the JSON structure stored in the setup file of this process.

func ReadSetupConfig

func ReadSetupConfig(log zerolog.Logger, dataDir string) (SetupConfigFile, bool, error)

ReadSetupConfig tries to read a setup.json config file and relaunch when that file exists and is valid. Returns true on relaunch or false to continue with a fresh start.

func VerifySetupConfig added in v0.18.5

func VerifySetupConfig(log zerolog.Logger, setupContent []byte) (SetupConfigFile, bool, error)

type State

type State int

State of the service.

func (State) IsBootstrap

func (s State) IsBootstrap() bool

IsBootstrap returns true if given state is bootstrap master/slave

func (State) IsRunning

func (s State) IsRunning() bool

IsRunning returns true if given state is running master/slave

type StatusItem

type StatusItem struct {
	PrevStatusCode int
	StatusCode     int
	Duration       time.Duration
}

StatusItem contain a single point in time for a status feedback channel.

type URLSchemes

type URLSchemes struct {
	Browser  string // Scheme for use in a webbrowser
	Arangod  string // URL Scheme for use in Arangod[.conf]
	ArangoSH string // URL Scheme for use in ArangoSH
}

URLSchemes contains URL schemes for browser & Arango Shell.

func NewURLSchemes

func NewURLSchemes(isSecure bool) URLSchemes

NewURLSchemes creates initialized schemes depending on isSecure flag.

type UpgradeEntryType

type UpgradeEntryType string

UpgradeEntryType is a strongly typed upgrade plan item

type UpgradeManager

type UpgradeManager interface {
	// StartDatabaseUpgrade is called to start the upgrade process
	StartDatabaseUpgrade(ctx context.Context, forceMinorUpgrade bool) error

	// RetryDatabaseUpgrade resets a failure mark in the existing upgrade plan
	// such that the starters will retry the upgrade once more.
	RetryDatabaseUpgrade(ctx context.Context) error

	// AbortDatabaseUpgrade removes the existing upgrade plan.
	// Note that Starters working on an entry of the upgrade
	// will finish that entry.
	// If there is no plan, a NotFoundError will be returned.
	AbortDatabaseUpgrade(ctx context.Context) error

	// Status returns the status of any upgrade plan
	Status(context.Context) (client.UpgradeStatus, error)

	// IsServerUpgradeInProgress returns true when the upgrade manager is busy upgrading the server of given type.
	IsServerUpgradeInProgress(serverType definitions.ServerType) bool

	// ServerDatabaseAutoUpgrade returns true if the server of given type must be started with --database.auto-upgrade
	ServerDatabaseAutoUpgrade(serverType definitions.ServerType, lastExitCode int) bool

	// ServerDatabaseAutoUpgradeStarter is called when a server of given type has been started with --database.auto-upgrade
	ServerDatabaseAutoUpgradeStarter(serverType definitions.ServerType)

	// RunWatchUpgradePlan keeps watching the upgrade plan until the given context is canceled.
	RunWatchUpgradePlan(context.Context)
}

UpgradeManager is the API of a service used to control the upgrade process from 1 database version to the next.

func NewUpgradeManager

func NewUpgradeManager(log zerolog.Logger, upgradeManagerContext UpgradeManagerContext) UpgradeManager

NewUpgradeManager creates a new upgrade manager.

type UpgradeManagerContext

type UpgradeManagerContext interface {
	ClientBuilder
	// ClusterConfig returns the current cluster configuration and the current peer
	ClusterConfig() (ClusterConfig, *Peer, ServiceMode)
	// RestartServer triggers a restart of the server of the given type.
	RestartServer(serverType definitions.ServerType) error
	// IsRunningMaster returns if the starter is the running master.
	IsRunningMaster() (isRunningMaster, isRunning bool, masterURL string)
	// TestInstance checks the `up` status of an arangod server instance.
	TestInstance(ctx context.Context, serverType definitions.ServerType, address string, port int,
		statusChanged chan StatusItem) (up, correctRole bool, version, role, mode string, statusTrail []int, cancelled bool)
}

UpgradeManagerContext holds methods used by the upgrade manager to control its context.

type UpgradePlan

type UpgradePlan struct {
	Revision        int                `json:"revision"` // Must match with upgradePlanRevisionKey
	CreatedAt       time.Time          `json:"created_at"`
	LastModifiedAt  time.Time          `json:"last_modified_at"`
	Entries         []UpgradePlanEntry `json:"entries"`
	FinishedEntries []UpgradePlanEntry `json:"finished_entries"`
	Finished        bool               `json:"finished"`
	FromVersions    []driver.Version   `json:"from_versions"`
	ToVersion       driver.Version     `json:"to_version"`
}

UpgradePlan is the JSON structure that describes a plan to upgrade a deployment to a new version.

func (UpgradePlan) Equals added in v0.17.1

func (p UpgradePlan) Equals(other UpgradePlan) bool

Equals returns true if other plan is the same

func (UpgradePlan) IsEmpty

func (p UpgradePlan) IsEmpty() bool

IsEmpty returns true when the given plan has not been initialized.

func (UpgradePlan) IsFailed

func (p UpgradePlan) IsFailed() bool

IsFailed returns true when one of the entries has failures.

func (UpgradePlan) IsReady

func (p UpgradePlan) IsReady() bool

IsReady returns true when all entries have finished.

func (*UpgradePlan) ResetFailures

func (p *UpgradePlan) ResetFailures()

ResetFailures resets all Failures field to 0.

type UpgradePlanEntry

type UpgradePlanEntry struct {
	PeerID        string           `json:"peer_id"`
	Type          UpgradeEntryType `json:"type"`
	Failures      int              `json:"failures,omitempty"`
	Reason        string           `json:"reason,omitempty"`
	WithoutResign bool             `json:"withoutResign,omitempty"`
}

UpgradePlanEntry is the JSON structure that describes a single entry in an upgrade plan.

func (UpgradePlanEntry) CreateStatusServer

func (e UpgradePlanEntry) CreateStatusServer(upgradeManagerContext UpgradeManagerContext) (*client.UpgradeStatusServer, error)

CreateStatusServer creates a UpgradeStatusServer for the given entry. When the entry does not involve a specific server, nil is returned.

type Volume

type Volume struct {
	HostPath      string
	ContainerPath string
	ReadOnly      bool
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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