service

package
v0.14.15-2 Latest Latest
Warning

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

Go to latest
Published: Dec 17, 2020 License: Apache-2.0 Imports: 43 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AuthorizationHeader = "Authorization"
	BearerPrefix        = "bearer "
)
View Source
const (
	ServerTypeCoordinator     = "coordinator"
	ServerTypeDBServer        = "dbserver"
	ServerTypeAgent           = "agent"
	ServerTypeSingle          = "single"
	ServerTypeResilientSingle = "resilientsingle"
	ServerTypeSyncMaster      = "syncmaster"
	ServerTypeSyncWorker      = "syncworker"
)
View Source
const (
	UpgradeEntryTypeAgent       = "agent"
	UpgradeEntryTypeDBServer    = "dbserver"
	UpgradeEntryTypeCoordinator = "coordinator"
	UpgradeEntryTypeSingle      = "single"
	UpgradeEntryTypeSyncMaster  = "syncmaster"
	UpgradeEntryTypeSyncWorker  = "syncworker"
)
View Source
const (
	DefaultMasterPort = 8528
)

Variables

This section is empty.

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) (string, error)

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

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(rawJSON []byte, 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(rawJSON []byte) bool

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

func IsNoLeaderError

func IsNoLeaderError(rawJSON []byte) 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 LoadKeyFile

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

LoadKeyFile loads a SSL keyfile formatted for the arangod server.

func ReadSetupConfig

func ReadSetupConfig(log zerolog.Logger, dataDir string, bsCfg BootstrapConfig) (BootstrapConfig, ClusterConfig, 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 RemoveSetupConfig

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

RemoveSetupConfig tries to remove a setup.json config file.

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 BootstrapConfig

type BootstrapConfig struct {
	ID                        string      // Unique identifier of this peer
	Mode                      ServiceMode // Service mode cluster|single
	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
	StartResilientSingle      *bool       // If not nil, sets if starter starts a resilient single, otherwise default handling applies
	StartSyncMaster           *bool       // If not nil, sets if the starter starts a sync master, otherwise default handling applies
	StartSyncWorker           *bool       // If not nil, sets if the starter starts a sync worker, 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.
	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) PeersNeeded

func (bsCfg BootstrapConfig) PeersNeeded() int

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

type ClientBuilder

type ClientBuilder func(endpoints []string, connectionType ConnectionType) (driver.Client, error)

ClientBuilder is a callback used to create authenticated go-driver clients with or without follow-redirect.

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
}

ClusterConfig contains all the informtion 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(ctx context.Context, jwtSecret string) (driver.Client, error)

CreateCoordinatorsClient creates go-driver client targeting the coordinators.

func (ClusterConfig) GetAgentEndpoints

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

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

func (ClusterConfig) GetAllSingleEndpoints

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

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

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) GetResilientSingleEndpoints

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

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

func (ClusterConfig) GetSingleEndpoints

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

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

func (ClusterConfig) GetSyncMasterEndpoints

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

GetSyncMasterEndpoints creates a list of URL's for all sync masters.

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)

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
	ArangoSyncPath       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.
	PassthroughOptions   []PassthroughOption
	DebugCluster         bool
	LogRotateFilesToKeep int
	LogRotateInterval    time.Duration
	InstanceUpTimeout    time.Duration

	DockerContainerName   string // Name of the container running this process
	DockerEndpoint        string // Where to reach the docker daemon
	DockerArangodImage    string // Name of Arangodb docker image
	DockerArangoSyncImage string // Name of Arangodb docker image
	DockerImagePullPolicy ImagePullPolicy
	DockerStarterImage    string
	DockerUser            string
	DockerGCDelay         time.Duration
	DockerNetworkMode     string
	DockerPrivileged      bool
	DockerTTY             bool
	RunningInDocker       bool

	SyncEnabled             bool   // If set, arangosync servers are activated
	SyncMasterKeyFile       string // TLS keyfile of local sync master
	SyncMasterClientCAFile  string // CA Certificate used for client certificate verification
	SyncMasterJWTSecretFile string // File containing JWT secret used to access the Sync Master (from Sync Worker)
	SyncMonitoringToken     string // Bearer token used for arangosync --monitoring.token
	SyncMQType              string // MQType used by sync master

	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 driver.Version

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

func NewDatabaseFeatures

func NewDatabaseFeatures(version driver.Version) 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) 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.

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
	ResilientSingle *bool  `json:",omitempty"` // If not nil, sets if server gets an resilient single or not. If nil, default handling applies
	SyncMaster      *bool  `json:",omitempty"` // If not nil, sets if server gets an sync master or not. If nil, default handling applies
	SyncWorker      *bool  `json:",omitempty"` // If not nil, sets if server gets an sync master 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 PassthroughOption

type PassthroughOption struct {
	Name   string
	Values struct {
		All          []string
		Coordinators []string
		DBServers    []string
		Agents       []string
		AllSync      []string
		SyncMasters  []string
		SyncWorkers  []string
	}
}

func (*PassthroughOption) FormattedOptionName

func (o *PassthroughOption) FormattedOptionName() string

FormattedOptionName returns the option ready to be used in a command line argument, prefixed with `--`.

func (*PassthroughOption) IsForbidden

func (o *PassthroughOption) IsForbidden() bool

IsForbidden returns true if the option cannot be overwritten.

type Peer

type Peer struct {
	ID                     string // Unique of 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
	HasAgentFlag           bool   `json:"HasAgent"`                     // If set, this peer is running an agent
	HasDBServerFlag        *bool  `json:"HasDBServer,omitempty"`        // If set or is nil, this peer is running a dbserver
	HasCoordinatorFlag     *bool  `json:"HasCoordinator,omitempty"`     // If set or is nil, this peer is running a coordinator
	HasResilientSingleFlag bool   `json:"HasResilientSingle,omitempty"` // If set, this peer is running a resilient single server
	HasSyncMasterFlag      bool   `json:"HasSyncMaster,omitempty"`      // If set, this peer is running a sync master
	HasSyncWorkerFlag      bool   `json:"HasSyncWorker,omitempty"`      // If set, this peer is running a sync worker
	IsSecure               bool   // If set, servers started by this peer are using an SSL connection
}

Peer contains all persistent settings of a starter.

func NewPeer

func NewPeer(id, address string, port, portOffset int, dataDir string, hasAgent, hasDBServer, hasCoordinator, hasResilientSingle, hasSyncMaster, hasSyncWorker, isSecure bool) Peer

NewPeer initializes a new Peer instance with given values.

func (Peer) CreateAgentAPI

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

CreateAgentAPI creates a client for the agent of the peer

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) HasResilientSingle

func (p Peer) HasResilientSingle() bool

HasResilientSingle returns true if this peer is running an resilient single server

func (Peer) HasSyncMaster

func (p Peer) HasSyncMaster() bool

HasSyncMaster returns true if this peer is running an arangosync master server

func (Peer) HasSyncWorker

func (p Peer) HasSyncWorker() bool

HasSyncWorker returns true if this peer is running an arangosync worker server

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
	Wait() int
	// WaitCh returns channel when process is terminated
	WaitCh() <-chan struct{}
	// 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

	// Remove all traces of this process
	Cleanup() error
}

type ProcessType

type ProcessType string

ProcessType specifies the types of process (the starter can work with).

const (
	ProcessTypeArangod    ProcessType = "arangod"
	ProcessTypeArangoSync ProcessType = "arangosync"
)

func (ProcessType) CommandFileName

func (s ProcessType) CommandFileName() string

CommandFileName returns the name of a file containing the full command for processes of this type.

func (ProcessType) LogFileName

func (s ProcessType) LogFileName(suffix string) string

LogFileName returns the name of the log file used by this process

func (ProcessType) String

func (s ProcessType) String() string

String returns a string representation of the given ProcessType.

type ProcessWrapper

type ProcessWrapper interface {
	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 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 ProcessType, command string, args []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, endpoint, arangodImage, arangoSyncImage string, imagePullPolicy ImagePullPolicy, user, volumesFrom string, gcDelay time.Duration,
	networkMode string, privileged, tty bool) (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 ServerType

type ServerType string

ServerType specifies the types of database servers.

func (ServerType) ExpectedServerRole

func (s ServerType) ExpectedServerRole() (string, string)

ExpectedServerRole returns the expected `role` & `mode` value resulting from a request to `_admin/server/role`.

func (ServerType) PortOffset

func (s ServerType) PortOffset() int

PortOffset returns the offset from a peer base port for the given type of server.

func (ServerType) ProcessType

func (s ServerType) ProcessType() ProcessType

ProcessType returns the type of process needed to run a server of given type.

func (ServerType) String

func (s ServerType) String() string

String returns a string representation of the given ServerType.

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, 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) (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, error)

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) MasterChangedCallback

func (s *Service) MasterChangedCallback()

MasterChangedCallback interrupts the runtime cluster manager

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 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, myPeers 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 ServerType, address string, port int,
	statusChanged chan StatusItem) (up, correctRole bool, version, role, mode string, isLeader bool, 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

func (ServiceMode) HasAgency

func (m ServiceMode) HasAgency() bool

HasAgency returns true when the given mode involves an agency.

func (ServiceMode) IsActiveFailoverMode

func (m ServiceMode) IsActiveFailoverMode() bool

IsActiveFailoverMode returns true when the service is running in activefailover server mode.

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) SupportsArangoSync

func (m ServiceMode) SupportsArangoSync() bool

SupportsArangoSync returns true when the given mode support running arangosync on it.

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.

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 ServerType) bool

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

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

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

	// UpgradePlanChangedCallback is an agency callback to notify about changes in the upgrade plan
	UpgradePlanChangedCallback()
}

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 {
	// ClusterConfig returns the current cluster configuration and the current peer
	ClusterConfig() (ClusterConfig, *Peer, ServiceMode)
	// CreateClient creates a go-driver client with authentication for the given endpoints.
	CreateClient(endpoints []string, connectionType ConnectionType) (driver.Client, error)
	// RestartServer triggers a restart of the server of the given type.
	RestartServer(serverType 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 ServerType, address string, port int,
		statusChanged chan StatusItem) (up, correctRole bool, version, role, mode string, isLeader bool, 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) 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"`
}

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
}

Jump to

Keyboard shortcuts

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