api

package
v0.0.0-...-d2438c5 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2019 License: Apache-2.0 Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const Interval = 60

Interval represents the number of seconds to wait between to heartbeat rounds.

Variables

This section is empty.

Functions

func DiscoveryRestServer

func DiscoveryRestServer(
	d Discovery,
	config *clusterconfig.ReadOnlyConfig,
	services, internalServices []Service,
	options ...Option,
) (*http.Server, error)

DiscoveryRestServer creates an http.Server capable of handling requests against the REST API endpoint.

func IsClusterNotification

func IsClusterNotification(r *http.Request) bool

IsClusterNotification returns true if this an API request coming from a cluster node that is notifying us of some user-initiated API request that needs some action to be taken on this node as well.

Types

type Actor

type Actor interface {

	// ID returns the unique ID for the actor
	ID() string

	// Types returns the underlying types the actor subscribes to
	Types() []string

	// Write pushes information to the actor
	Write([]byte) error

	// Close the actor
	Close()

	// NoForward decides if messages should be forwarded to the actor
	NoForward() bool

	// Done returns if the actor is done messaging.
	Done() bool
}

Actor defines an broker between event messages and nodes

type ActorGroup

type ActorGroup interface {

	// Add an actor to a group
	Add(a Actor)

	// Prune removes any done actors
	Prune() bool

	// Walk over the actors with in the group one by one (order is not
	// guaranteed).
	Walk(func(Actor) error) error
}

ActorGroup holds a group of actors

type Cluster

type Cluster interface {
	database.DBAccessor
	db.ClusterOpener
	db.ClusterTransactioner
	db.ClusterExclusiveLocker

	// NodeID sets the the node NodeID associated with this cluster instance. It's used for
	// backward-compatibility of all db-related APIs that were written before
	// clustering and don't accept a node NodeID, so in those cases we automatically
	// use this value as implicit node NodeID.
	NodeID(int64)

	// SchemaVersion returns the underlying schema version for the cluster
	SchemaVersion() int

	// Close the database facade.
	Close() error
}

Cluster mediates access to data stored in the cluster dqlite database.

type ContextKey

type ContextKey string

ContextKey defines a key that can be used to identify values within a context value.

const (
	// DaemonKey represents a way to identify a daemon in a context
	DaemonKey ContextKey = "daemon"

	// DiscoveryKey represents a way to identify a service in a context
	DiscoveryKey ContextKey = "discovery"
)

type Daemon

type Daemon interface {
	Facade

	// Gateway returns the underlying Daemon Gateway
	Gateway() Gateway

	// Cluster returns the underlying Cluster
	Cluster() Cluster

	// Node returns the underlying Node associated with the daemon
	Node() Node

	// State creates a new State instance liked to our internal db and os.
	State() State

	// Operations return the underlying operational tasks associated with the
	// current daemon
	Operations() Operations

	// Schedules return the underlying schedule tasks associated with the
	// cluster
	Schedules() Schedules

	// ClusterConfigSchema returns the daemon schema for the Cluster
	ClusterConfigSchema() config.Schema

	// NodeConfigSchema returns the daemon schema for the local Node
	NodeConfigSchema() config.Schema

	// ActorGroup returns the actor group for event broadcast
	ActorGroup() ActorGroup

	// EventBroadcaster returns a event broadcaster for event processing
	EventBroadcaster() EventBroadcaster

	// Version returns the current version of the daemon
	Version() string

	// Nonce returns the current nonce of the daemon
	Nonce() string

	// Endpoints returns the underlying endpoints that the daemon controls.
	Endpoints() Endpoints

	// APIExtensions returns the extensions available to the current daemon
	APIExtensions() []string

	// UnsafeShutdown forces an automatic shutdown of the Daemon
	UnsafeShutdown()

	// UnsafeSetCluster forces a cluster onto the daemon.
	UnsafeSetCluster(Cluster)
}

Daemon can respond to requests from a shared client.

func GetDaemon

func GetDaemon(ctx context.Context) (Daemon, error)

GetDaemon returns the Daemon from the context or return an error

type DaemonServiceRouter

type DaemonServiceRouter struct {
	*ServiceRouter
	// contains filtered or unexported fields
}

DaemonServiceRouter creates a wrapper of a underlying router, then allows services to be added and handled.

func NewDaemonServiceRouter

func NewDaemonServiceRouter(
	d Daemon,
	mux *mux.Router,
	clientCerts, clusterCerts func() []x509.Certificate,
	logger log.Logger,
) *DaemonServiceRouter

NewDaemonServiceRouter creates a ServiceRouter with sane defaults

type DefaultService

type DefaultService struct{}

DefaultService creates a default service that just returns not implemented errors

func (DefaultService) Delete

Delete handles DELETE requests, but always returns NotImplemented

func (DefaultService) Get

Get handles GET requests, but always returns NotImplemented

func (DefaultService) Patch

Patch handles PATCH requests, but always returns NotImplemented

func (DefaultService) Post

Post handles POST requests, but always returns NotImplemented

func (DefaultService) Put

Put handles PUT requests, but always returns NotImplemented

type Discovery

type Discovery interface {
	Facade

	// Version returns the current version of the discovery
	Version() string

	// Endpoints returns the underlying endpoints that the discovery controls.
	Endpoints() Endpoints

	// UnsafeShutdown forces an automatic shutdown of the Discovery
	UnsafeShutdown()
}

Discovery can respond to requests from a shared client.

func GetDiscovery

func GetDiscovery(ctx context.Context) (Discovery, error)

GetDiscovery returns the Discovery from the context or return an error

type DiscoveryServiceRouter

type DiscoveryServiceRouter struct {
	*ServiceRouter
	// contains filtered or unexported fields
}

DiscoveryServiceRouter creates a wrapper of a underlying router, then allows services to be added and handled.

func NewDiscoveryServiceRouter

func NewDiscoveryServiceRouter(
	d Discovery,
	mux *mux.Router,
	clientCerts, clusterCerts func() []x509.Certificate,
	logger log.Logger,
) *DiscoveryServiceRouter

NewDiscoveryServiceRouter creates a ServiceRouter with sane defaults

type Endpoints

type Endpoints interface {

	// NetworkPublicKey returns the public key of the TLS certificate used by the
	// network endpoint.
	NetworkPublicKey() []byte

	// NetworkPrivateKey returns the private key of the TLS certificate used by the
	// network endpoint.
	NetworkPrivateKey() []byte

	// NetworkCert returns the full TLS certificate information for this endpoint.
	NetworkCert() *cert.Info

	// NetworkUpdateAddress updates the address for the network endpoint,
	// shutting it down and restarting it.
	NetworkUpdateAddress(string) error

	// PprofUpdateAddress updates the address for the pprof endpoint, shutting
	// it down and restarting it.
	PprofUpdateAddress(string) error

	// NetworkUpdateCert updates the cert for the network endpoint,
	// shutting it down and restarting it.
	NetworkUpdateCert(*cert.Info) error
}

Endpoints are in charge of bringing up and down the HTTP endpoints for serving the RESTful API.

type EventBroadcaster

type EventBroadcaster interface {

	// Dispatch an event to other parts of the underlying system
	Dispatch(map[string]interface{}) error
}

EventBroadcaster defines a way to broadcast events to other internal parts of the system.

type Facade

type Facade interface {
	// SetupChan returns a channel that blocks until setup has happened from
	// the Daemon
	SetupChan() <-chan struct{}

	// RegisterChan returns a channel that blocks until all the registered tasks
	// have happened for the Daemon
	RegisterChan() <-chan struct{}

	// ClientCerts returns the associated client certificates
	ClientCerts() []x509.Certificate

	// ClusterCerts returns the associated client certificates
	ClusterCerts() []x509.Certificate

	// APIMetrics returns a series of metrics, useful for diagnostics.
	APIMetrics() Metrics
}

Facade defines a facade to interact with the underlying controller.

type Gateway

type Gateway interface {

	// Init the gateway, creating a new raft factory and gRPC server (if this
	// node is a database node), and a gRPC dialer.
	Init(*cert.Info) error

	// Shutdown this gateway, stopping the gRPC server and possibly the raft
	// factory.
	Shutdown() error

	// WaitLeadership will wait for the raft node to become leader. Should only
	// be used by Bootstrap, since we know that we'll self elect.
	WaitLeadership() error

	// RaftNodes returns information about the nodes that a currently
	// part of the raft cluster, as configured in the raft log. It returns an
	// error if this node is not the leader.
	RaftNodes() ([]db.RaftNode, error)

	// Raft returns the raft instance
	Raft() RaftInstance

	// HandlerFuncs returns the HTTP handlers that should be added to the REST API
	// endpoint in order to handle database-related requests.
	HandlerFuncs() map[string]http.HandlerFunc

	// DB returns the the underlying db node
	DB() Node

	// IsDatabaseNode returns true if this gateway also run acts a raft database
	// node.
	IsDatabaseNode() bool

	// LeaderAddress returns the address of the current raft leader.
	LeaderAddress() (string, error)

	// Cert returns the currently available cert in the gateway
	Cert() *cert.Info

	// Reset the gateway, shutting it down and starting against from scratch
	// using the given certificate.
	//
	// This is used when disabling clustering on a node.
	Reset(cert *cert.Info) error

	// DialFunc returns a dial function that can be used to connect to one of
	// the dqlite nodes.
	DialFunc() dqlite.DialFunc

	// ServerStore returns a dqlite server store that can be used to lookup the
	// addresses of known database nodes.
	ServerStore() querycluster.ServerStore

	// Context returns a cancellation context to pass to dqlite.NewDriver as
	// option.
	//
	// This context gets cancelled by Gateway.Kill() and at that point any
	// connection failure won't be retried.
	Context() context.Context
}

Gateway mediates access to the dqlite cluster using a gRPC SQL client, and possibly runs a dqlite replica on this node (if we're configured to do so).

type Gauge

type Gauge interface {
	// Inc increments the Gauge by 1. Use Add to increment it by arbitrary
	// values.
	Inc()
}

Gauge is a Metric that represents a single numerical value that can arbitrarily go up and down.

type GaugeVec

type GaugeVec interface {
	// WithLabelValues works as GetMetricWithLabelValues, but panics where
	// GetMetricWithLabelValues would have returned an error. By not returning an
	// error, WithLabelValues allows shortcuts like
	//     myVec.WithLabelValues("404", "GET").Add(42)
	WithLabelValues(lvs ...string) Gauge
}

GaugeVec is a Collector that bundles a set of Gauges that all share the same Desc, but have different values for their variable labels.

type Histogram

type Histogram interface {
	// Observe adds a single observation to the histogram.
	Observe(float64)
}

A Histogram counts individual observations from an event or sample stream in configurable buckets. Similar to a summary, it also provides a sum of observations and an observation count.

type HistogramVec

type HistogramVec interface {
	// WithLabelValues works as GetMetricWithLabelValues, but panics where
	// GetMetricWithLabelValues would have returned an error. By not returning an
	// error, WithLabelValues allows shortcuts like
	//     myVec.WithLabelValues("404", "GET").Observe(42.21)
	WithLabelValues(lvs ...string) Histogram
}

HistogramVec is a Collector that bundles a set of Histograms that all share the same Desc, but have different values for their variable labels.

type Metrics

type Metrics interface {
	APIDuration() HistogramVec
	ConnectedClients() GaugeVec
}

Metrics is a collection metrics to use from the daemon

type Node

type Node interface {
	database.DBAccessor
	db.NodeOpener
	db.NodeTransactioner

	// Dir returns the directory of the underlying database file.
	Dir() string

	// Close the database facade.
	Close() error
}

Node mediates access to the data stored locally

type OS

type OS interface {

	// LocalDatabasePath returns the path of the local database file.
	LocalDatabasePath() string

	// GlobalDatabaseDir returns the path of the global database directory.
	GlobalDatabaseDir() string

	// GlobalDatabasePath returns the path of the global database SQLite file
	// managed by dqlite.
	GlobalDatabasePath() string

	// VarDir represents the Data directory (e.g. /var/lib/therm/).
	VarDir() string

	// Hostname returns the host name reported by the kernel.
	Hostname() (string, error)

	// HostNames will generate a list of names for which the certificate will be
	// valid.
	// This will include the hostname and ip address
	HostNames() ([]string, error)

	// User returns the current user.
	User() (*user.User, error)
}

OS is a high-level facade for accessing all operating-system level functionality that therm uses.

type Operations

type Operations interface {

	// Add an operation to the collection
	Add(*operations.Operation) error

	// GetOpByPartialID retrieves an op of the operation from the collection by a
	// partial id. As long as the prefix matches an id then it will return that
	// operation. If the id matches multiple ids then it will return an ambiguous
	// error.
	GetOpByPartialID(string) (operations.Op, error)

	// DeleteOp attempts to kill an operation by the id
	DeleteOp(string) error

	// WaitOp for an operation to be completed
	WaitOp(string, time.Duration) (bool, error)

	// Walk over a collection of operations
	Walk(func(operations.Op) error) error
}

Operations defines an interface for interacting with a series of operations

type Option

type Option func(*options)

Option to be passed to Connect to customize the resulting instance.

func WithLogger

func WithLogger(logger log.Logger) Option

WithLogger sets the logger on the option

type RaftInstance

type RaftInstance interface {

	// MembershipChanger returns the underlying rafthttp.Layer, which can be
	// used to change the membership of this node in the cluster.
	MembershipChanger() raftmembership.Changer
}

RaftInstance is a specific wrapper around raft.Raft, which also holds a reference to its network transport and dqlite FSM.

type Response

type Response interface {

	// Render the response with a response writer.
	Render(http.ResponseWriter) error
}

Response defines a return value from a http request. The response then can be rendered.

func BadRequest

func BadRequest(err error) Response

BadRequest takes an error and returns a Response of badrequest error.

func Conflict

func Conflict(err error) Response

Conflict takes an error and returns a Response of conflict error.

func EmptySyncResponse

func EmptySyncResponse() Response

EmptySyncResponse defines an empty successful response

func Forbidden

func Forbidden(err error) Response

Forbidden takes an error and returns a Response of forbidden error.

func InternalError

func InternalError(err error) Response

InternalError takes an error and returns a Response of internal server error.

func NotFound

func NotFound(err error) Response

NotFound takes an error and returns a Response of not found.

func NotImplemented

func NotImplemented(err error) Response

NotImplemented takes an error and returns a Response of not implemented.

func PreconditionFailed

func PreconditionFailed(err error) Response

PreconditionFailed takes an error and returns a Response of precondition failed error.

func SmartError

func SmartError(err error) Response

SmartError returns the right error message based on err.

func SyncResponse

func SyncResponse(success bool, metadata interface{}) Response

SyncResponse defines a response that is synchronous

func SyncResponseETag

func SyncResponseETag(success bool, metadata interface{}, eTag interface{}) Response

SyncResponseETag defines a response that can add ETag as additional information

func SyncResponseRedirect

func SyncResponseRedirect(address string) Response

SyncResponseRedirect defines a successful response that will aways perform a permanent redirect.

func Unavailable

func Unavailable(err error) Response

Unavailable takes an error and returns a Response of unavailable error.

type SchedulerTask

type SchedulerTask interface {

	// Run setups up the given schedule
	Run() (task.Func, task.Schedule)
}

SchedulerTask defines a task that can be run repeatedly

func DaemonRestServer

func DaemonRestServer(
	d Daemon,
	services, internalServices []Service,
	options ...Option,
) (*http.Server, SchedulerTask, error)

DaemonRestServer creates an http.Server capable of handling requests against the REST API endpoint.

type Schedules

type Schedules interface {

	// Add an task to the schedule
	Add(*schedules.Task) error

	// Remove a scheduled task
	Remove(string) error

	// GetTsk returns a scheduled task
	GetTsk(string) (schedules.Tsk, error)

	// Walk over a set of scheduled tasks
	Walk(func(schedules.Tsk) error) error
}

Schedules defines an interface for interacting with a set of scheduled tasks

type Service

type Service interface {

	// Get handles GET requests
	Get(context.Context, *http.Request) Response

	// Put handles PUT requests
	Put(context.Context, *http.Request) Response

	// Post handles POST requests
	Post(context.Context, *http.Request) Response

	// Delete handles DELETE requests
	Delete(context.Context, *http.Request) Response

	// Patch handles PATCH requests
	Patch(context.Context, *http.Request) Response

	// Name returns the serialisable service name.
	// The name has to conform to RFC 3986
	Name() string
}

Service represents a endpoint that can perform http actions upon

type ServiceRouter

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

ServiceRouter creates a wrapper of a underlying router, then allows services to be added and handled.

func (*ServiceRouter) Add

func (s *ServiceRouter) Add(prefix string, service Service)

Add a Service to the DaemonServiceRouter with a prefix (1.0/internal)

func (*ServiceRouter) ServeHTTP

func (s *ServiceRouter) ServeHTTP(w http.ResponseWriter, r *http.Request)

type State

type State interface {
	// Node returns the underlying Node
	Node() Node

	// Cluster returns the underlying Cluster
	Cluster() Cluster

	// OS returns the underlying OS values
	OS() OS
}

State is a gateway to the two main stateful components, the database and the operating system. It's typically used by model entities in order to perform changes.

Directories

Path Synopsis
daemon
discovery

Jump to

Keyboard shortcuts

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