api

package module
v1.2.7 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2022 License: MPL-2.0 Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AllocDesiredStatusRun   = "run"   // Allocation should run
	AllocDesiredStatusStop  = "stop"  // Allocation should stop
	AllocDesiredStatusEvict = "evict" // Allocation should stop, and was evicted
)
View Source
const (
	AllocClientStatusPending  = "pending"
	AllocClientStatusRunning  = "running"
	AllocClientStatusComplete = "complete"
	AllocClientStatusFailed   = "failed"
	AllocClientStatusLost     = "lost"
)
View Source
const (
	ConstraintDistinctProperty  = "distinct_property"
	ConstraintDistinctHosts     = "distinct_hosts"
	ConstraintRegex             = "regexp"
	ConstraintVersion           = "version"
	ConstraintSemver            = "semver"
	ConstraintSetContains       = "set_contains"
	ConstraintSetContainsAll    = "set_contains_all"
	ConstraintSetContainsAny    = "set_contains_any"
	ConstraintAttributeIsSet    = "is_set"
	ConstraintAttributeIsNotSet = "is_not_set"
)
View Source
const (
	// OriginStart and OriginEnd are the available parameters for the origin
	// argument when streaming a file. They respectively offset from the start
	// and end of a file.
	OriginStart = "start"
	OriginEnd   = "end"
)
View Source
const (
	// JobTypeService indicates a long-running processes
	JobTypeService = "service"

	// JobTypeBatch indicates a short-lived process
	JobTypeBatch = "batch"

	// JobTypeSystem indicates a system process that should run on all clients
	JobTypeSystem = "system"

	// PeriodicSpecCron is used for a cron spec.
	PeriodicSpecCron = "cron"

	// DefaultNamespace is the default namespace.
	DefaultNamespace = "default"

	// For Job configuration, GlobalRegion is a sentinel region value
	// that users may specify to indicate the job should be run on
	// the region of the node that the job was submitted to.
	// For Client configuration, if no region information is given,
	// the client node will default to be part of the GlobalRegion.
	GlobalRegion = "global"
)
View Source
const (
	NodeStatusInit  = "initializing"
	NodeStatusReady = "ready"
	NodeStatusDown  = "down"

	// NodeSchedulingEligible and Ineligible marks the node as eligible or not,
	// respectively, for receiving allocations. This is orthogonal to the node
	// status being ready.
	NodeSchedulingEligible   = "eligible"
	NodeSchedulingIneligible = "ineligible"

	DrainStatusDraining DrainStatus = "draining"
	DrainStatusComplete DrainStatus = "complete"
	DrainStatusCanceled DrainStatus = "canceled"
)
View Source
const (
	NodeEventSubsystemDrain     = "Drain"
	NodeEventSubsystemDriver    = "Driver"
	NodeEventSubsystemHeartbeat = "Heartbeat"
	NodeEventSubsystemCluster   = "Cluster"
)
View Source
const (
	OnUpdateRequireHealthy = "require_healthy"
	OnUpdateIgnoreWarn     = "ignore_warnings"
	OnUpdateIgnore         = "ignore"
)
View Source
const (
	// RestartPolicyModeDelay causes an artificial delay till the next interval is
	// reached when the specified attempts have been reached in the interval.
	RestartPolicyModeDelay = "delay"

	// RestartPolicyModeFail causes a job to fail if the specified number of
	// attempts are reached within an interval.
	RestartPolicyModeFail = "fail"
)
View Source
const (
	VolumeMountPropagationPrivate       = "private"
	VolumeMountPropagationHostToTask    = "host-to-task"
	VolumeMountPropagationBidirectional = "bidirectional"
)
View Source
const (
	TaskLifecycleHookPrestart  = "prestart"
	TaskLifecycleHookPoststart = "poststart"
	TaskLifecycleHookPoststop  = "poststop"
)
View Source
const (
	TaskSetup                  = "Task Setup"
	TaskSetupFailure           = "Setup Failure"
	TaskDriverFailure          = "Driver Failure"
	TaskDriverMessage          = "Driver"
	TaskReceived               = "Received"
	TaskFailedValidation       = "Failed Validation"
	TaskStarted                = "Started"
	TaskTerminated             = "Terminated"
	TaskKilling                = "Killing"
	TaskKilled                 = "Killed"
	TaskRestarting             = "Restarting"
	TaskNotRestarting          = "Not Restarting"
	TaskDownloadingArtifacts   = "Downloading Artifacts"
	TaskArtifactDownloadFailed = "Failed Artifact Download"
	TaskSiblingFailed          = "Sibling Task Failed"
	TaskSignaling              = "Signaling"
	TaskRestartSignal          = "Restart Signaled"
	TaskLeaderDead             = "Leader Task Dead"
	TaskBuildingTaskDir        = "Building Task Directory"
)
View Source
const (
	// AllNamespacesNamespace is a sentinel Namespace value to indicate that api should search for
	// jobs and allocations in all the namespaces the requester can access.
	AllNamespacesNamespace = "*"
)
View Source
const (
	// RegisterEnforceIndexErrPrefix is the prefix to use in errors caused by
	// enforcing the job modify index during registers.
	RegisterEnforceIndexErrPrefix = "Enforcing job modify index"
)
View Source
const (
	// ScalingPolicyTypeHorizontal indicates a policy that does horizontal scaling.
	ScalingPolicyTypeHorizontal = "horizontal"
)

Variables

View Source
var (
	// ClientConnTimeout is the timeout applied when attempting to contact a
	// client directly before switching to a connection through the Nomad
	// server.
	ClientConnTimeout = 1 * time.Second
)
View Source
var (
	// NodeDownErr marks an operation as not able to complete since the node is
	// down.
	NodeDownErr = fmt.Errorf("node down")
)

Functions

func ConfigureTLS

func ConfigureTLS(httpClient *http.Client, tlsConfig *TLSConfig) error

ConfigureTLS applies a set of TLS configurations to the the HTTP client.

Types

type ACLPolicies

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

ACLPolicies is used to query the ACL Policy endpoints.

func (*ACLPolicies) Delete

func (a *ACLPolicies) Delete(policyName string, q *WriteOptions) (*WriteMeta, error)

Delete is used to delete a policy

func (*ACLPolicies) Info

func (a *ACLPolicies) Info(policyName string, q *QueryOptions) (*ACLPolicy, *QueryMeta, error)

Info is used to query a specific policy

func (*ACLPolicies) List

List is used to dump all of the policies.

func (*ACLPolicies) Upsert

func (a *ACLPolicies) Upsert(policy *ACLPolicy, q *WriteOptions) (*WriteMeta, error)

Upsert is used to create or update a policy

type ACLPolicy

type ACLPolicy struct {
	Name        string
	Description string
	Rules       string
	CreateIndex uint64
	ModifyIndex uint64
}

ACLPolicy is used to represent an ACL policy

type ACLPolicyListStub

type ACLPolicyListStub struct {
	Name        string
	Description string
	CreateIndex uint64
	ModifyIndex uint64
}

ACLPolicyListStub is used to for listing ACL policies

type ACLToken

type ACLToken struct {
	AccessorID  string
	SecretID    string
	Name        string
	Type        string
	Policies    []string
	Global      bool
	CreateTime  time.Time
	CreateIndex uint64
	ModifyIndex uint64
}

ACLToken represents a client token which is used to Authenticate

type ACLTokenListStub

type ACLTokenListStub struct {
	AccessorID  string
	Name        string
	Type        string
	Policies    []string
	Global      bool
	CreateTime  time.Time
	CreateIndex uint64
	ModifyIndex uint64
}

type ACLTokens

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

ACLTokens is used to query the ACL token endpoints.

func (*ACLTokens) Bootstrap

func (a *ACLTokens) Bootstrap(q *WriteOptions) (*ACLToken, *WriteMeta, error)

Bootstrap is used to get the initial bootstrap token

func (*ACLTokens) Create

func (a *ACLTokens) Create(token *ACLToken, q *WriteOptions) (*ACLToken, *WriteMeta, error)

Create is used to create a token

func (*ACLTokens) Delete

func (a *ACLTokens) Delete(accessorID string, q *WriteOptions) (*WriteMeta, error)

Delete is used to delete a token

func (*ACLTokens) ExchangeOneTimeToken

func (a *ACLTokens) ExchangeOneTimeToken(secret string, q *WriteOptions) (*ACLToken, *WriteMeta, error)

ExchangeOneTimeToken is used to create a one-time token

func (*ACLTokens) Info

func (a *ACLTokens) Info(accessorID string, q *QueryOptions) (*ACLToken, *QueryMeta, error)

Info is used to query a token

func (*ACLTokens) List

List is used to dump all of the tokens.

func (*ACLTokens) Self

func (a *ACLTokens) Self(q *QueryOptions) (*ACLToken, *QueryMeta, error)

Self is used to query our own token

func (*ACLTokens) Update

func (a *ACLTokens) Update(token *ACLToken, q *WriteOptions) (*ACLToken, *WriteMeta, error)

Update is used to update an existing token

func (*ACLTokens) UpsertOneTimeToken

func (a *ACLTokens) UpsertOneTimeToken(q *WriteOptions) (*OneTimeToken, *WriteMeta, error)

UpsertOneTimeToken is used to create a one-time token

type Affinity

type Affinity struct {
	LTarget string `hcl:"attribute,optional"` // Left-hand target
	RTarget string `hcl:"value,optional"`     // Right-hand target
	Operand string `hcl:"operator,optional"`  // Constraint operand (<=, <, =, !=, >, >=), set_contains_all, set_contains_any
	Weight  *int8  `hcl:"weight,optional"`    // Weight applied to nodes that match the affinity. Can be negative
}

Affinity is used to serialize task group affinities

func NewAffinity

func NewAffinity(lTarget string, operand string, rTarget string, weight int8) *Affinity

func (*Affinity) Canonicalize

func (a *Affinity) Canonicalize()

type Agent

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

Agent encapsulates an API client which talks to Nomad's agent endpoints for a specific node.

func (*Agent) CPUProfile

func (a *Agent) CPUProfile(opts PprofOptions, q *QueryOptions) ([]byte, error)

CPUProfile returns a runtime/pprof cpu profile for a given server or node. The profile will run for the amount of seconds passed in or default to 1. If no serverID or nodeID are provided the current Agents server will be used.

The call blocks until the profile finishes, and returns the raw bytes of the profile.

func (*Agent) Datacenter

func (a *Agent) Datacenter() (string, error)

Datacenter is used to return the name of the datacenter which the agent is a member of.

func (*Agent) ForceLeave

func (a *Agent) ForceLeave(node string) error

ForceLeave is used to eject an existing node from the cluster.

func (*Agent) GetSchedulerWorkerConfig

func (a *Agent) GetSchedulerWorkerConfig(q *QueryOptions) (*SchedulerWorkerPoolArgs, error)

GetSchedulerWorkerConfig returns the targeted agent's worker pool configuration

func (*Agent) GetSchedulerWorkersInfo

func (a *Agent) GetSchedulerWorkersInfo(q *QueryOptions) (*AgentSchedulerWorkersInfo, error)

GetSchedulerWorkersInfo returns the current status of all of the scheduler workers on a Nomad server.

func (*Agent) Health

func (a *Agent) Health() (*AgentHealthResponse, error)

Health queries the agent's health

func (*Agent) Host

func (a *Agent) Host(serverID, nodeID string, q *QueryOptions) (*HostDataResponse, error)

Host returns debugging context about the agent's host operating system

func (*Agent) InstallKey

func (a *Agent) InstallKey(key string) (*KeyringResponse, error)

InstallKey installs a key in the keyrings of all the serf members

func (*Agent) Join

func (a *Agent) Join(addrs ...string) (int, error)

Join is used to instruct a server node to join another server via the gossip protocol. Multiple addresses may be specified. We attempt to join all of the hosts in the list. Returns the number of nodes successfully joined and any error. If one or more nodes have a successful result, no error is returned.

func (*Agent) ListKeys

func (a *Agent) ListKeys() (*KeyringResponse, error)

ListKeys returns the list of installed keys

func (*Agent) Lookup

func (a *Agent) Lookup(profile string, opts PprofOptions, q *QueryOptions) ([]byte, error)

Lookup returns a runtime/pprof profile using pprof.Lookup to determine which profile to run. Accepts a client or server ID but not both simultaneously.

The call blocks until the profile finishes, and returns the raw bytes of the profile unless debug is set.

func (*Agent) Members

func (a *Agent) Members() (*ServerMembers, error)

Members is used to query all of the known server members

func (*Agent) MembersOpts

func (a *Agent) MembersOpts(opts *QueryOptions) (*ServerMembers, error)

Members is used to query all of the known server members with the ability to set QueryOptions

func (*Agent) Monitor

func (a *Agent) Monitor(stopCh <-chan struct{}, q *QueryOptions) (<-chan *StreamFrame, <-chan error)

Monitor returns a channel which will receive streaming logs from the agent Providing a non-nil stopCh can be used to close the connection and stop log streaming

func (*Agent) NodeName

func (a *Agent) NodeName() (string, error)

NodeName is used to query the Nomad agent for its node name.

func (*Agent) Region

func (a *Agent) Region() (string, error)

Region is used to look up the region the agent is in.

func (*Agent) RemoveKey

func (a *Agent) RemoveKey(key string) (*KeyringResponse, error)

RemoveKey removes a particular key from keyrings of serf members

func (*Agent) Self

func (a *Agent) Self() (*AgentSelf, error)

Self is used to query the /v1/agent/self endpoint and returns information specific to the running agent.

func (*Agent) Servers

func (a *Agent) Servers() ([]string, error)

Servers is used to query the list of servers on a client node.

func (*Agent) SetSchedulerWorkerConfig

func (a *Agent) SetSchedulerWorkerConfig(args SchedulerWorkerPoolArgs, q *WriteOptions) (*SchedulerWorkerPoolArgs, error)

SetSchedulerWorkerConfig attempts to update the targeted agent's worker pool configuration

func (*Agent) SetServers

func (a *Agent) SetServers(addrs []string) error

SetServers is used to update the list of servers on a client node.

func (*Agent) Trace

func (a *Agent) Trace(opts PprofOptions, q *QueryOptions) ([]byte, error)

Trace returns a runtime/pprof trace for a given server or node. The trace will run for the amount of seconds passed in or default to 1. If no serverID or nodeID are provided the current Agents server will be used.

The call blocks until the profile finishes, and returns the raw bytes of the profile.

func (*Agent) UseKey

func (a *Agent) UseKey(key string) (*KeyringResponse, error)

UseKey uses a key from the keyring of serf members

type AgentHealth

type AgentHealth struct {
	// Ok is false if the agent is unhealthy
	Ok bool `json:"ok"`

	// Message describes why the agent is unhealthy
	Message string `json:"message"`
}

AgentHealth describes the Client or Server's health in a Health request.

type AgentHealthResponse

type AgentHealthResponse struct {
	Client *AgentHealth `json:"client,omitempty"`
	Server *AgentHealth `json:"server,omitempty"`
}

AgentHealthResponse is the response from the Health endpoint describing an agent's health.

type AgentMember

type AgentMember struct {
	Name        string
	Addr        string
	Port        uint16
	Tags        map[string]string
	Status      string
	ProtocolMin uint8
	ProtocolMax uint8
	ProtocolCur uint8
	DelegateMin uint8
	DelegateMax uint8
	DelegateCur uint8
}

AgentMember represents a cluster member known to the agent

type AgentMembersNameSort

type AgentMembersNameSort []*AgentMember

AgentMembersNameSort implements sort.Interface for []*AgentMembersNameSort based on the Name, DC and Region

func (AgentMembersNameSort) Len

func (a AgentMembersNameSort) Len() int

func (AgentMembersNameSort) Less

func (a AgentMembersNameSort) Less(i, j int) bool

func (AgentMembersNameSort) Swap

func (a AgentMembersNameSort) Swap(i, j int)

type AgentSchedulerWorkerConfigRequest

type AgentSchedulerWorkerConfigRequest struct {
	NumSchedulers     int      `json:"num_schedulers"`
	EnabledSchedulers []string `json:"enabled_schedulers"`
}

AgentSchedulerWorkerConfigRequest is used to provide new scheduler worker configuration to a specific Nomad server. EnabledSchedulers must contain at least the `_core` scheduler to be valid.

type AgentSchedulerWorkerConfigResponse

type AgentSchedulerWorkerConfigResponse struct {
	ServerID          string   `json:"server_id"`
	NumSchedulers     int      `json:"num_schedulers"`
	EnabledSchedulers []string `json:"enabled_schedulers"`
}

AgentSchedulerWorkerConfigResponse contains the Nomad server's current running configuration as well as the server's id as a convenience. This can be used to provide starting values for creating an AgentSchedulerWorkerConfigRequest to make changes to the running configuration.

type AgentSchedulerWorkerInfo

type AgentSchedulerWorkerInfo struct {
	ID                string   `json:"id"`
	EnabledSchedulers []string `json:"enabled_schedulers"`
	Started           string   `json:"started"`
	Status            string   `json:"status"`
	WorkloadStatus    string   `json:"workload_status"`
}

AgentSchedulerWorkerInfo holds the detailed status information for a single scheduler worker.

type AgentSchedulerWorkersInfo

type AgentSchedulerWorkersInfo struct {
	ServerID   string                     `json:"server_id"`
	Schedulers []AgentSchedulerWorkerInfo `json:"schedulers"`
}

AgentSchedulerWorkersInfo is the response from the scheduler information endpoint containing a detailed status of each scheduler worker running on the server.

type AgentSelf

type AgentSelf struct {
	Config map[string]interface{}       `json:"config"`
	Member AgentMember                  `json:"member"`
	Stats  map[string]map[string]string `json:"stats"`
}

type AggregateSample

type AggregateSample struct {
	Count       int       // The count of emitted pairs
	Rate        float64   // The values rate per time unit (usually 1 second)
	Sum         float64   // The sum of values
	SumSq       float64   `json:"-"` // The sum of squared values
	Min         float64   // Minimum value
	Max         float64   // Maximum value
	LastUpdated time.Time `json:"-"` // When value was last updated
}

AggregateSample is used to hold aggregate metrics about a sample

type AllocDeploymentStatus

type AllocDeploymentStatus struct {
	Healthy     *bool
	Timestamp   time.Time
	Canary      bool
	ModifyIndex uint64
}

AllocDeploymentStatus captures the status of the allocation as part of the deployment. This can include things like if the allocation has been marked as healthy.

type AllocFS

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

AllocFS is used to introspect an allocation directory on a Nomad client

func (*AllocFS) Cat

func (a *AllocFS) Cat(alloc *Allocation, path string, q *QueryOptions) (io.ReadCloser, error)

Cat is used to read contents of a file at the given path in an allocation directory

func (*AllocFS) List

func (a *AllocFS) List(alloc *Allocation, path string, q *QueryOptions) ([]*AllocFileInfo, *QueryMeta, error)

List is used to list the files at a given path of an allocation directory

func (*AllocFS) Logs

func (a *AllocFS) Logs(alloc *Allocation, follow bool, task, logType, origin string,
	offset int64, cancel <-chan struct{}, q *QueryOptions) (<-chan *StreamFrame, <-chan error)

Logs streams the content of a tasks logs blocking on EOF. The parameters are: * allocation: the allocation to stream from. * follow: Whether the logs should be followed. * task: the tasks name to stream logs for. * logType: Either "stdout" or "stderr" * origin: Either "start" or "end" and defines from where the offset is applied. * offset: The offset to start streaming data at. * cancel: A channel that when closed, streaming will end.

The return value is a channel that will emit StreamFrames as they are read. The chan will be closed when follow=false and the end of the file is reached.

Unexpected (non-EOF) errors will be sent on the error chan.

func (*AllocFS) ReadAt

func (a *AllocFS) ReadAt(alloc *Allocation, path string, offset int64, limit int64, q *QueryOptions) (io.ReadCloser, error)

ReadAt is used to read bytes at a given offset until limit at the given path in an allocation directory. If limit is <= 0, there is no limit.

func (*AllocFS) Stat

func (a *AllocFS) Stat(alloc *Allocation, path string, q *QueryOptions) (*AllocFileInfo, *QueryMeta, error)

Stat is used to stat a file at a given path of an allocation directory

func (*AllocFS) Stream

func (a *AllocFS) Stream(alloc *Allocation, path, origin string, offset int64,
	cancel <-chan struct{}, q *QueryOptions) (<-chan *StreamFrame, <-chan error)

Stream streams the content of a file blocking on EOF. The parameters are: * path: path to file to stream. * offset: The offset to start streaming data at. * origin: Either "start" or "end" and defines from where the offset is applied. * cancel: A channel that when closed, streaming will end.

The return value is a channel that will emit StreamFrames as they are read.

type AllocFileInfo

type AllocFileInfo struct {
	Name        string
	IsDir       bool
	Size        int64
	FileMode    string
	ModTime     time.Time
	ContentType string
}

AllocFileInfo holds information about a file inside the AllocDir

type AllocIndexSort

type AllocIndexSort []*AllocationListStub

AllocIndexSort reverse sorts allocs by CreateIndex.

func (AllocIndexSort) Len

func (a AllocIndexSort) Len() int

func (AllocIndexSort) Less

func (a AllocIndexSort) Less(i, j int) bool

func (AllocIndexSort) Swap

func (a AllocIndexSort) Swap(i, j int)

type AllocResourceUsage

type AllocResourceUsage struct {
	ResourceUsage *ResourceUsage
	Tasks         map[string]*TaskResourceUsage
	Timestamp     int64
}

AllocResourceUsage holds the aggregated task resource usage of the allocation.

type AllocSignalRequest

type AllocSignalRequest struct {
	Task   string
	Signal string
}

type AllocStopResponse

type AllocStopResponse struct {
	// EvalID is the id of the follow up evalution for the rescheduled alloc.
	EvalID string

	WriteMeta
}

AllocStopResponse is the response to an `AllocStopRequest`

type AllocatedCpuResources

type AllocatedCpuResources struct {
	CpuShares int64
}

type AllocatedDeviceResource

type AllocatedDeviceResource struct {
	Vendor    string
	Type      string
	Name      string
	DeviceIDs []string
}

type AllocatedMemoryResources

type AllocatedMemoryResources struct {
	MemoryMB    int64
	MemoryMaxMB int64
}

type AllocatedResources

type AllocatedResources struct {
	Tasks  map[string]*AllocatedTaskResources
	Shared AllocatedSharedResources
}

type AllocatedSharedResources

type AllocatedSharedResources struct {
	DiskMB   int64
	Networks []*NetworkResource
	Ports    []PortMapping
}

type AllocatedTaskResources

type AllocatedTaskResources struct {
	Cpu      AllocatedCpuResources
	Memory   AllocatedMemoryResources
	Networks []*NetworkResource
	Devices  []*AllocatedDeviceResource
}

type Allocation

type Allocation struct {
	ID                    string
	Namespace             string
	EvalID                string
	Name                  string
	NodeID                string
	NodeName              string
	JobID                 string
	Job                   *Job
	TaskGroup             string
	Resources             *Resources
	TaskResources         map[string]*Resources
	AllocatedResources    *AllocatedResources
	Services              map[string]string
	Metrics               *AllocationMetric
	DesiredStatus         string
	DesiredDescription    string
	DesiredTransition     DesiredTransition
	ClientStatus          string
	ClientDescription     string
	TaskStates            map[string]*TaskState
	DeploymentID          string
	DeploymentStatus      *AllocDeploymentStatus
	FollowupEvalID        string
	PreviousAllocation    string
	NextAllocation        string
	RescheduleTracker     *RescheduleTracker
	PreemptedAllocations  []string
	PreemptedByAllocation string
	CreateIndex           uint64
	ModifyIndex           uint64
	AllocModifyIndex      uint64
	CreateTime            int64
	ModifyTime            int64
}

Allocation is used for serialization of allocations.

func (*Allocation) ClientTerminalStatus

func (a *Allocation) ClientTerminalStatus() bool

ClientTerminalStatus returns true if the client status is terminal and will therefore no longer transition.

func (Allocation) GetTaskGroup

func (a Allocation) GetTaskGroup() *TaskGroup

func (Allocation) RescheduleInfo

func (a Allocation) RescheduleInfo(t time.Time) (int, int)

RescheduleInfo is used to calculate remaining reschedule attempts according to the given time and the task groups reschedule policy

func (*Allocation) ServerTerminalStatus

func (a *Allocation) ServerTerminalStatus() bool

ServerTerminalStatus returns true if the desired state of the allocation is terminal.

func (*Allocation) Stub

func (a *Allocation) Stub() *AllocationListStub

Stub returns a list stub for the allocation

type AllocationListStub

type AllocationListStub struct {
	ID                    string
	EvalID                string
	Name                  string
	Namespace             string
	NodeID                string
	NodeName              string
	JobID                 string
	JobType               string
	JobVersion            uint64
	TaskGroup             string
	AllocatedResources    *AllocatedResources `json:",omitempty"`
	DesiredStatus         string
	DesiredDescription    string
	ClientStatus          string
	ClientDescription     string
	TaskStates            map[string]*TaskState
	DeploymentStatus      *AllocDeploymentStatus
	FollowupEvalID        string
	RescheduleTracker     *RescheduleTracker
	PreemptedAllocations  []string
	PreemptedByAllocation string
	CreateIndex           uint64
	ModifyIndex           uint64
	CreateTime            int64
	ModifyTime            int64
}

AllocationListStub is used to return a subset of an allocation during list operations.

type AllocationMetric

type AllocationMetric struct {
	NodesEvaluated     int
	NodesFiltered      int
	NodesAvailable     map[string]int
	ClassFiltered      map[string]int
	ConstraintFiltered map[string]int
	NodesExhausted     int
	ClassExhausted     map[string]int
	DimensionExhausted map[string]int
	QuotaExhausted     []string
	ResourcesExhausted map[string]*Resources
	// Deprecated, replaced with ScoreMetaData
	Scores            map[string]float64
	AllocationTime    time.Duration
	CoalescedFailures int
	ScoreMetaData     []*NodeScoreMeta
}

AllocationMetric is used to deserialize allocation metrics.

type AllocationRestartRequest

type AllocationRestartRequest struct {
	TaskName string
}

type AllocationSort

type AllocationSort []*Allocation

AllocationSort reverse sorts allocs by CreateIndex.

func (AllocationSort) Len

func (a AllocationSort) Len() int

func (AllocationSort) Less

func (a AllocationSort) Less(i, j int) bool

func (AllocationSort) Swap

func (a AllocationSort) Swap(i, j int)

type Allocations

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

Allocations is used to query the alloc-related endpoints.

func (*Allocations) Exec

func (a *Allocations) Exec(ctx context.Context,
	alloc *Allocation, task string, tty bool, command []string,
	stdin io.Reader, stdout, stderr io.Writer,
	terminalSizeCh <-chan TerminalSize, q *QueryOptions) (exitCode int, err error)

Exec is used to execute a command inside a running task. The command is to run inside the task environment.

The parameters are:

  • ctx: context to set deadlines or timeout
  • allocation: the allocation to execute command inside
  • task: the task's name to execute command in
  • tty: indicates whether to start a pseudo-tty for the command
  • stdin, stdout, stderr: the std io to pass to command. If tty is true, then streams need to point to a tty that's alive for the whole process
  • terminalSizeCh: A channel to send new tty terminal sizes

The call blocks until command terminates (or an error occurs), and returns the exit code.

func (*Allocations) GC

func (a *Allocations) GC(alloc *Allocation, q *QueryOptions) error

func (*Allocations) Info

func (a *Allocations) Info(allocID string, q *QueryOptions) (*Allocation, *QueryMeta, error)

Info is used to retrieve a single allocation.

func (*Allocations) List

List returns a list of all of the allocations.

func (*Allocations) PrefixList

func (a *Allocations) PrefixList(prefix string) ([]*AllocationListStub, *QueryMeta, error)

func (*Allocations) Restart

func (a *Allocations) Restart(alloc *Allocation, taskName string, q *QueryOptions) error

func (*Allocations) Signal

func (a *Allocations) Signal(alloc *Allocation, q *QueryOptions, task, signal string) error

func (*Allocations) Stats

func (a *Allocations) Stats(alloc *Allocation, q *QueryOptions) (*AllocResourceUsage, error)

func (*Allocations) Stop

func (a *Allocations) Stop(alloc *Allocation, q *QueryOptions) (*AllocStopResponse, error)

type ApplyLicenseOptions

type ApplyLicenseOptions struct {
	Force bool
}

type Attribute

type Attribute struct {
	// Float is the float value for the attribute
	FloatVal *float64 `json:"Float,omitempty"`

	// Int is the int value for the attribute
	IntVal *int64 `json:"Int,omitempty"`

	// String is the string value for the attribute
	StringVal *string `json:"String,omitempty"`

	// Bool is the bool value for the attribute
	BoolVal *bool `json:"Bool,omitempty"`

	// Unit is the optional unit for the set int or float value
	Unit string
}

Attribute is used to describe the value of an attribute, optionally specifying units

func (Attribute) String

func (a Attribute) String() string

type AutopilotConfiguration

type AutopilotConfiguration struct {
	// CleanupDeadServers controls whether to remove dead servers from the Raft
	// peer list when a new server joins
	CleanupDeadServers bool

	// LastContactThreshold is the limit on the amount of time a server can go
	// without leader contact before being considered unhealthy.
	LastContactThreshold time.Duration

	// MaxTrailingLogs is the amount of entries in the Raft Log that a server can
	// be behind before being considered unhealthy.
	MaxTrailingLogs uint64

	// MinQuorum sets the minimum number of servers allowed in a cluster before
	// autopilot can prune dead servers.
	MinQuorum uint

	// ServerStabilizationTime is the minimum amount of time a server must be
	// in a stable, healthy state before it can be added to the cluster. Only
	// applicable with Raft protocol version 3 or higher.
	ServerStabilizationTime time.Duration

	// (Enterprise-only) EnableRedundancyZones specifies whether to enable redundancy zones.
	EnableRedundancyZones bool

	// (Enterprise-only) DisableUpgradeMigration will disable Autopilot's upgrade migration
	// strategy of waiting until enough newer-versioned servers have been added to the
	// cluster before promoting them to voters.
	DisableUpgradeMigration bool

	// (Enterprise-only) EnableCustomUpgrades specifies whether to enable using custom
	// upgrade versions when performing migrations.
	EnableCustomUpgrades bool

	// CreateIndex holds the index corresponding the creation of this configuration.
	// This is a read-only field.
	CreateIndex uint64

	// ModifyIndex will be set to the index of the last update when retrieving the
	// Autopilot configuration. Resubmitting a configuration with
	// AutopilotCASConfiguration will perform a check-and-set operation which ensures
	// there hasn't been a subsequent update since the configuration was retrieved.
	ModifyIndex uint64
}

AutopilotConfiguration is used for querying/setting the Autopilot configuration. Autopilot helps manage operator tasks related to Nomad servers like removing failed servers from the Raft quorum.

func (*AutopilotConfiguration) MarshalJSON

func (u *AutopilotConfiguration) MarshalJSON() ([]byte, error)

func (*AutopilotConfiguration) UnmarshalJSON

func (u *AutopilotConfiguration) UnmarshalJSON(data []byte) error

type CSIControllerInfo

type CSIControllerInfo struct {
	// SupportsCreateDelete indicates plugin support for CREATE_DELETE_VOLUME
	SupportsCreateDelete bool

	// SupportsPublishVolume is true when the controller implements the
	// methods required to attach and detach volumes. If this is false Nomad
	// should skip the controller attachment flow.
	SupportsAttachDetach bool

	// SupportsListVolumes is true when the controller implements the
	// ListVolumes RPC. NOTE: This does not guarantee that attached nodes will
	// be returned unless SupportsListVolumesAttachedNodes is also true.
	SupportsListVolumes bool

	// SupportsGetCapacity indicates plugin support for GET_CAPACITY
	SupportsGetCapacity bool

	// SupportsCreateDeleteSnapshot indicates plugin support for
	// CREATE_DELETE_SNAPSHOT
	SupportsCreateDeleteSnapshot bool

	// SupportsListSnapshots indicates plugin support for LIST_SNAPSHOTS
	SupportsListSnapshots bool

	// SupportsClone indicates plugin support for CLONE_VOLUME
	SupportsClone bool

	// SupportsReadOnlyAttach is set to true when the controller returns the
	// ATTACH_READONLY capability.
	SupportsReadOnlyAttach bool

	// SupportsExpand indicates plugin support for EXPAND_VOLUME
	SupportsExpand bool

	// SupportsListVolumesAttachedNodes indicates whether the plugin will
	// return attached nodes data when making ListVolume RPCs (plugin support
	// for LIST_VOLUMES_PUBLISHED_NODES)
	SupportsListVolumesAttachedNodes bool

	// SupportsCondition indicates plugin support for VOLUME_CONDITION
	SupportsCondition bool

	// SupportsGet indicates plugin support for GET_VOLUME
	SupportsGet bool
}

CSIControllerInfo is the fingerprinted data from a CSI Plugin that is specific to the Controller API.

type CSIInfo

type CSIInfo struct {
	PluginID                 string
	AllocID                  string
	Healthy                  bool
	HealthDescription        string
	UpdateTime               time.Time
	RequiresControllerPlugin bool
	RequiresTopologies       bool
	ControllerInfo           *CSIControllerInfo `json:",omitempty"`
	NodeInfo                 *CSINodeInfo       `json:",omitempty"`
}

CSIInfo is the current state of a single CSI Plugin. This is updated regularly as plugin health changes on the node.

type CSIMountOptions

type CSIMountOptions struct {
	// FSType is an optional field that allows an operator to specify the type
	// of the filesystem.
	FSType string `hcl:"fs_type,optional"`

	// MountFlags contains additional options that may be used when mounting the
	// volume by the plugin. This may contain sensitive data and should not be
	// leaked.
	MountFlags []string `hcl:"mount_flags,optional"`

	ExtraKeysHCL []string `hcl1:",unusedKeys" json:"-"` // report unexpected keys
}

CSIMountOptions contain optional additional configuration that can be used when specifying that a Volume should be used with VolumeAccessTypeMount.

type CSINodeInfo

type CSINodeInfo struct {
	ID                 string
	MaxVolumes         int64
	AccessibleTopology *CSITopology

	// RequiresNodeStageVolume indicates whether the client should Stage/Unstage
	// volumes on this node.
	RequiresNodeStageVolume bool

	// SupportsStats indicates plugin support for GET_VOLUME_STATS
	SupportsStats bool

	// SupportsExpand indicates plugin support for EXPAND_VOLUME
	SupportsExpand bool

	// SupportsCondition indicates plugin support for VOLUME_CONDITION
	SupportsCondition bool
}

CSINodeInfo is the fingerprinted data from a CSI Plugin that is specific to the Node API.

type CSIPlugin

type CSIPlugin struct {
	ID                 string
	Provider           string
	Version            string
	ControllerRequired bool
	// Map Node.ID to CSIInfo fingerprint results
	Controllers         map[string]*CSIInfo
	Nodes               map[string]*CSIInfo
	Allocations         []*AllocationListStub
	ControllersHealthy  int
	ControllersExpected int
	NodesHealthy        int
	NodesExpected       int
	CreateIndex         uint64
	ModifyIndex         uint64
}

CSIPlugin is used for serialization, see also nomad/structs/csi.go

type CSIPluginIndexSort

type CSIPluginIndexSort []*CSIPluginListStub

CSIPluginIndexSort is a helper used for sorting plugin stubs by creation time.

func (CSIPluginIndexSort) Len

func (v CSIPluginIndexSort) Len() int

func (CSIPluginIndexSort) Less

func (v CSIPluginIndexSort) Less(i, j int) bool

func (CSIPluginIndexSort) Swap

func (v CSIPluginIndexSort) Swap(i, j int)

type CSIPluginListStub

type CSIPluginListStub struct {
	ID                  string
	Provider            string
	ControllerRequired  bool
	ControllersHealthy  int
	ControllersExpected int
	NodesHealthy        int
	NodesExpected       int
	CreateIndex         uint64
	ModifyIndex         uint64
}

type CSIPluginType

type CSIPluginType string

CSIPluginType is an enum string that encapsulates the valid options for a CSIPlugin stanza's Type. These modes will allow the plugin to be used in different ways by the client.

const (
	// CSIPluginTypeNode indicates that Nomad should only use the plugin for
	// performing Node RPCs against the provided plugin.
	CSIPluginTypeNode CSIPluginType = "node"

	// CSIPluginTypeController indicates that Nomad should only use the plugin for
	// performing Controller RPCs against the provided plugin.
	CSIPluginTypeController CSIPluginType = "controller"

	// CSIPluginTypeMonolith indicates that Nomad can use the provided plugin for
	// both controller and node rpcs.
	CSIPluginTypeMonolith CSIPluginType = "monolith"
)

type CSIPlugins

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

CSI Plugins are jobs with plugin specific data

func (*CSIPlugins) Info

func (v *CSIPlugins) Info(id string, q *QueryOptions) (*CSIPlugin, *QueryMeta, error)

Info is used to retrieve a single CSI Plugin Job

func (*CSIPlugins) List

List returns all CSI plugins

type CSISecrets

type CSISecrets map[string]string

CSISecrets contain optional additional credentials that may be needed by the storage provider. These values will be redacted when reported in the API or in Nomad's logs.

type CSISnapshot

type CSISnapshot struct {
	ID                     string // storage provider's ID
	ExternalSourceVolumeID string // storage provider's ID for volume
	SizeBytes              int64  // value from storage provider
	CreateTime             int64  // value from storage provider
	IsReady                bool   // value from storage provider
	SourceVolumeID         string // Nomad volume ID
	PluginID               string // CSI plugin ID

	// These field are only used during snapshot creation and will not be
	// populated when the snapshot is returned
	Name       string            // suggested name of the snapshot, used for creation
	Secrets    CSISecrets        // secrets needed to create snapshot
	Parameters map[string]string // secrets needed to create snapshot
}

CSISnapshot is the storage provider's view of a volume snapshot

type CSISnapshotCreateRequest

type CSISnapshotCreateRequest struct {
	Snapshots []*CSISnapshot
	WriteRequest
}

type CSISnapshotCreateResponse

type CSISnapshotCreateResponse struct {
	Snapshots []*CSISnapshot
	QueryMeta
}

type CSISnapshotListRequest

type CSISnapshotListRequest struct {
	PluginID string
	Secrets  CSISecrets
	QueryOptions
}

CSISnapshotListRequest is a request to a controller plugin to list all the snapshot known to the the storage provider. This request is paginated by the plugin and accepts the QueryOptions.PerPage and QueryOptions.NextToken fields

type CSISnapshotListResponse

type CSISnapshotListResponse struct {
	Snapshots []*CSISnapshot
	NextToken string
	QueryMeta
}

type CSISnapshotSort

type CSISnapshotSort []*CSISnapshot

CSISnapshotSort is a helper used for sorting snapshots by creation time.

func (CSISnapshotSort) Len

func (v CSISnapshotSort) Len() int

func (CSISnapshotSort) Less

func (v CSISnapshotSort) Less(i, j int) bool

func (CSISnapshotSort) Swap

func (v CSISnapshotSort) Swap(i, j int)

type CSITopology

type CSITopology struct {
	Segments map[string]string `hcl:"segments"`
}

type CSITopologyRequest

type CSITopologyRequest struct {
	Required  []*CSITopology `hcl:"required"`
	Preferred []*CSITopology `hcl:"preferred"`
}

type CSIVolume

type CSIVolume struct {
	ID         string
	Name       string
	ExternalID string `mapstructure:"external_id" hcl:"external_id"`
	Namespace  string

	// RequestedTopologies are the topologies submitted as options to
	// the storage provider at the time the volume was created. After
	// volumes are created, this field is ignored.
	RequestedTopologies *CSITopologyRequest `hcl:"topology_request"`

	// Topologies are the topologies returned by the storage provider,
	// based on the RequestedTopologies and what the storage provider
	// could support. This value cannot be set by the user.
	Topologies []*CSITopology

	AccessMode     CSIVolumeAccessMode     `hcl:"access_mode"`
	AttachmentMode CSIVolumeAttachmentMode `hcl:"attachment_mode"`
	MountOptions   *CSIMountOptions        `hcl:"mount_options"`
	Secrets        CSISecrets              `mapstructure:"secrets" hcl:"secrets"`
	Parameters     map[string]string       `mapstructure:"parameters" hcl:"parameters"`
	Context        map[string]string       `mapstructure:"context" hcl:"context"`
	Capacity       int64                   `hcl:"-"`

	// These fields are used as part of the volume creation request
	RequestedCapacityMin  int64                  `hcl:"capacity_min"`
	RequestedCapacityMax  int64                  `hcl:"capacity_max"`
	RequestedCapabilities []*CSIVolumeCapability `hcl:"capability"`
	CloneID               string                 `mapstructure:"clone_id" hcl:"clone_id"`
	SnapshotID            string                 `mapstructure:"snapshot_id" hcl:"snapshot_id"`

	// ReadAllocs is a map of allocation IDs for tracking reader claim status.
	// The Allocation value will always be nil; clients can populate this data
	// by iterating over the Allocations field.
	ReadAllocs map[string]*Allocation

	// WriteAllocs is a map of allocation IDs for tracking writer claim
	// status. The Allocation value will always be nil; clients can populate
	// this data by iterating over the Allocations field.
	WriteAllocs map[string]*Allocation

	// Allocations is a combined list of readers and writers
	Allocations []*AllocationListStub

	// Schedulable is true if all the denormalized plugin health fields are true
	Schedulable         bool
	PluginID            string `mapstructure:"plugin_id" hcl:"plugin_id"`
	Provider            string
	ProviderVersion     string
	ControllerRequired  bool
	ControllersHealthy  int
	ControllersExpected int
	NodesHealthy        int
	NodesExpected       int
	ResourceExhausted   time.Time

	CreateIndex uint64
	ModifyIndex uint64

	// ExtraKeysHCL is used by the hcl parser to report unexpected keys
	ExtraKeysHCL []string `hcl1:",unusedKeys" json:"-"`
}

CSIVolume is used for serialization, see also nomad/structs/csi.go

type CSIVolumeAccessMode

type CSIVolumeAccessMode string

CSIVolumeAccessMode indicates how a volume should be used in a storage topology e.g whether the provider should make the volume available concurrently. (Duplicated in nomad/structs/csi.go)

const (
	CSIVolumeAccessModeUnknown               CSIVolumeAccessMode = ""
	CSIVolumeAccessModeSingleNodeReader      CSIVolumeAccessMode = "single-node-reader-only"
	CSIVolumeAccessModeSingleNodeWriter      CSIVolumeAccessMode = "single-node-writer"
	CSIVolumeAccessModeMultiNodeReader       CSIVolumeAccessMode = "multi-node-reader-only"
	CSIVolumeAccessModeMultiNodeSingleWriter CSIVolumeAccessMode = "multi-node-single-writer"
	CSIVolumeAccessModeMultiNodeMultiWriter  CSIVolumeAccessMode = "multi-node-multi-writer"
)

type CSIVolumeAttachmentMode

type CSIVolumeAttachmentMode string

CSIVolumeAttachmentMode chooses the type of storage api that will be used to interact with the device. (Duplicated in nomad/structs/csi.go)

const (
	CSIVolumeAttachmentModeUnknown     CSIVolumeAttachmentMode = ""
	CSIVolumeAttachmentModeBlockDevice CSIVolumeAttachmentMode = "block-device"
	CSIVolumeAttachmentModeFilesystem  CSIVolumeAttachmentMode = "file-system"
)

type CSIVolumeCapability

type CSIVolumeCapability struct {
	AccessMode     CSIVolumeAccessMode     `mapstructure:"access_mode" hcl:"access_mode"`
	AttachmentMode CSIVolumeAttachmentMode `mapstructure:"attachment_mode" hcl:"attachment_mode"`
}

CSIVolumeCapability is a requested attachment and access mode for a volume

type CSIVolumeCreateRequest

type CSIVolumeCreateRequest struct {
	Volumes []*CSIVolume
	WriteRequest
}

type CSIVolumeCreateResponse

type CSIVolumeCreateResponse struct {
	Volumes []*CSIVolume
	QueryMeta
}

type CSIVolumeDeregisterRequest

type CSIVolumeDeregisterRequest struct {
	VolumeIDs []string
	WriteRequest
}

type CSIVolumeExternalStub

type CSIVolumeExternalStub struct {
	ExternalID               string
	CapacityBytes            int64
	VolumeContext            map[string]string
	CloneID                  string
	SnapshotID               string
	PublishedExternalNodeIDs []string
	IsAbnormal               bool
	Status                   string
}

CSIVolumeExternalStub is the storage provider's view of a volume, as returned from the controller plugin; all IDs are for external resources

type CSIVolumeExternalStubSort

type CSIVolumeExternalStubSort []*CSIVolumeExternalStub

CSIVolumeExternalStubSort is a sorting helper for external volumes. We can't sort these by creation time because we don't get that data back from the storage provider. Sort by External ID within this page.

func (CSIVolumeExternalStubSort) Len

func (CSIVolumeExternalStubSort) Less

func (v CSIVolumeExternalStubSort) Less(i, j int) bool

func (CSIVolumeExternalStubSort) Swap

func (v CSIVolumeExternalStubSort) Swap(i, j int)

type CSIVolumeIndexSort

type CSIVolumeIndexSort []*CSIVolumeListStub

CSIVolumeIndexSort is a helper used for sorting volume stubs by creation time.

func (CSIVolumeIndexSort) Len

func (v CSIVolumeIndexSort) Len() int

func (CSIVolumeIndexSort) Less

func (v CSIVolumeIndexSort) Less(i, j int) bool

func (CSIVolumeIndexSort) Swap

func (v CSIVolumeIndexSort) Swap(i, j int)

type CSIVolumeListExternalResponse

type CSIVolumeListExternalResponse struct {
	Volumes   []*CSIVolumeExternalStub
	NextToken string
}

type CSIVolumeListStub

type CSIVolumeListStub struct {
	ID                  string
	Namespace           string
	Name                string
	ExternalID          string
	Topologies          []*CSITopology
	AccessMode          CSIVolumeAccessMode
	AttachmentMode      CSIVolumeAttachmentMode
	Schedulable         bool
	PluginID            string
	Provider            string
	ControllerRequired  bool
	ControllersHealthy  int
	ControllersExpected int
	NodesHealthy        int
	NodesExpected       int
	ResourceExhausted   time.Time

	CreateIndex uint64
	ModifyIndex uint64
}

CSIVolumeListStub omits allocations. See also nomad/structs/csi.go

type CSIVolumeRegisterRequest

type CSIVolumeRegisterRequest struct {
	Volumes []*CSIVolume
	WriteRequest
}

type CSIVolumes

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

CSIVolumes is used to access Container Storage Interface (CSI) endpoints.

func (*CSIVolumes) Create

func (v *CSIVolumes) Create(vol *CSIVolume, w *WriteOptions) ([]*CSIVolume, *WriteMeta, error)

Create creates a single CSIVolume in an external storage provider and registers it with Nomad. You do not need to call Register if this call is successful.

func (*CSIVolumes) CreateSnapshot

func (v *CSIVolumes) CreateSnapshot(snap *CSISnapshot, w *WriteOptions) (*CSISnapshotCreateResponse, *WriteMeta, error)

CreateSnapshot snapshots an external storage volume.

func (*CSIVolumes) Delete

func (v *CSIVolumes) Delete(externalVolID string, w *WriteOptions) error

Delete deletes a CSI volume from an external storage provider. The ID passed as an argument here is for the storage provider's ID, so a volume that's already been deregistered can be deleted.

func (*CSIVolumes) DeleteSnapshot

func (v *CSIVolumes) DeleteSnapshot(snap *CSISnapshot, w *WriteOptions) error

DeleteSnapshot deletes an external storage volume snapshot.

func (*CSIVolumes) Deregister

func (v *CSIVolumes) Deregister(id string, force bool, w *WriteOptions) error

Deregister deregisters a single CSIVolume from Nomad. The volume will not be deleted from the external storage provider.

func (*CSIVolumes) Detach

func (v *CSIVolumes) Detach(volID, nodeID string, w *WriteOptions) error

Detach causes Nomad to attempt to detach a CSI volume from a client node. This is used in the case that the node is temporarily lost and the allocations are unable to drop their claims automatically.

func (*CSIVolumes) Info

func (v *CSIVolumes) Info(id string, q *QueryOptions) (*CSIVolume, *QueryMeta, error)

Info is used to retrieve a single CSIVolume

func (*CSIVolumes) List

List returns all CSI volumes.

func (*CSIVolumes) ListExternal

func (v *CSIVolumes) ListExternal(pluginID string, q *QueryOptions) (*CSIVolumeListExternalResponse, *QueryMeta, error)

ListExternal returns all CSI volumes, as understood by the external storage provider. These volumes may or may not be currently registered with Nomad. The response is paginated by the plugin and accepts the QueryOptions.PerPage and QueryOptions.NextToken fields.

func (*CSIVolumes) ListSnapshots

func (v *CSIVolumes) ListSnapshots(pluginID string, secrets string, q *QueryOptions) (*CSISnapshotListResponse, *QueryMeta, error)

DEPRECATED: will be removed in Nomad 1.4.0 ListSnapshots lists external storage volume snapshots.

func (*CSIVolumes) ListSnapshotsOpts

func (v *CSIVolumes) ListSnapshotsOpts(req *CSISnapshotListRequest) (*CSISnapshotListResponse, *QueryMeta, error)

ListSnapshotsOpts lists external storage volume snapshots.

func (*CSIVolumes) PluginList

func (v *CSIVolumes) PluginList(pluginID string) ([]*CSIVolumeListStub, *QueryMeta, error)

PluginList returns all CSI volumes for the specified plugin id

func (*CSIVolumes) Register

func (v *CSIVolumes) Register(vol *CSIVolume, w *WriteOptions) (*WriteMeta, error)

Register registers a single CSIVolume with Nomad. The volume must already exist in the external storage provider.

type CheckRestart

type CheckRestart struct {
	Limit          int            `mapstructure:"limit" hcl:"limit,optional"`
	Grace          *time.Duration `mapstructure:"grace" hcl:"grace,optional"`
	IgnoreWarnings bool           `mapstructure:"ignore_warnings" hcl:"ignore_warnings,optional"`
}

CheckRestart describes if and when a task should be restarted based on failing health checks.

func (*CheckRestart) Canonicalize

func (c *CheckRestart) Canonicalize()

Canonicalize CheckRestart fields if not nil.

func (*CheckRestart) Copy

func (c *CheckRestart) Copy() *CheckRestart

Copy returns a copy of CheckRestart or nil if unset.

func (*CheckRestart) Merge

func (c *CheckRestart) Merge(o *CheckRestart) *CheckRestart

Merge values from other CheckRestart over default values on this CheckRestart and return merged copy.

type Client

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

Client provides a client to the Nomad API

func NewClient

func NewClient(config *Config) (*Client, error)

NewClient returns a new client

func (*Client) ACLPolicies

func (c *Client) ACLPolicies() *ACLPolicies

ACLPolicies returns a new handle on the ACL policies.

func (*Client) ACLTokens

func (c *Client) ACLTokens() *ACLTokens

ACLTokens returns a new handle on the ACL tokens.

func (*Client) Address

func (c *Client) Address() string

Address return the address of the Nomad agent

func (*Client) Agent

func (c *Client) Agent() *Agent

Agent returns a new agent which can be used to query the agent-specific endpoints.

func (*Client) AllocFS

func (c *Client) AllocFS() *AllocFS

AllocFS returns an handle to the AllocFS endpoints

func (*Client) Allocations

func (c *Client) Allocations() *Allocations

Allocations returns a handle on the allocs endpoints.

func (*Client) CSIPlugins

func (c *Client) CSIPlugins() *CSIPlugins

CSIPlugins returns a handle on the CSIPlugins endpoint

func (*Client) CSIVolumes

func (c *Client) CSIVolumes() *CSIVolumes

CSIVolumes returns a handle on the CSIVolumes endpoint.

func (*Client) Deployments

func (c *Client) Deployments() *Deployments

Deployments returns a new handle on the deployments.

func (*Client) Evaluations

func (c *Client) Evaluations() *Evaluations

Evaluations returns a new handle on the evaluations.

func (*Client) EventStream

func (c *Client) EventStream() *EventStream

EventStream returns a handle to the Events endpoint

func (*Client) GetNodeClient

func (c *Client) GetNodeClient(nodeID string, q *QueryOptions) (*Client, error)

GetNodeClient returns a new Client that will dial the specified node. If the QueryOptions is set, its region will be used.

func (*Client) GetNodeClientWithTimeout

func (c *Client) GetNodeClientWithTimeout(
	nodeID string, timeout time.Duration, q *QueryOptions) (*Client, error)

GetNodeClientWithTimeout returns a new Client that will dial the specified node using the specified timeout. If the QueryOptions is set, its region will be used.

func (*Client) Jobs

func (c *Client) Jobs() *Jobs

Jobs returns a handle on the jobs endpoints.

func (*Client) Namespaces

func (c *Client) Namespaces() *Namespaces

Namespaces returns a new handle on the namespaces.

func (*Client) Nodes

func (c *Client) Nodes() *Nodes

Nodes returns a handle on the node endpoints.

func (*Client) Operator

func (c *Client) Operator() *Operator

Operator returns a handle to the operator endpoints.

func (*Client) Quotas

func (c *Client) Quotas() *Quotas

Quotas returns a new handle on the quotas.

func (*Client) Raw

func (c *Client) Raw() *Raw

Raw returns a handle to query endpoints

func (*Client) Recommendations

func (c *Client) Recommendations() *Recommendations

Recommendations returns a new handle on the recommendations endpoints.

func (*Client) Regions

func (c *Client) Regions() *Regions

Regions returns a handle on the regions endpoints.

func (*Client) Scaling

func (c *Client) Scaling() *Scaling

Scaling returns a handle on the scaling endpoints.

func (*Client) Search

func (c *Client) Search() *Search

Search returns a handle on the Search endpoints

func (*Client) SentinelPolicies

func (c *Client) SentinelPolicies() *SentinelPolicies

SentinelPolicies returns a new handle on the Sentinel policies.

func (*Client) SetNamespace

func (c *Client) SetNamespace(namespace string)

SetNamespace sets the namespace to forward API requests to.

func (*Client) SetRegion

func (c *Client) SetRegion(region string)

SetRegion sets the region to forward API requests to.

func (*Client) SetSecretID

func (c *Client) SetSecretID(secretID string)

SetSecretID sets the ACL token secret for API requests.

func (*Client) Status

func (c *Client) Status() *Status

Status returns a handle on the status endpoints.

func (*Client) System

func (c *Client) System() *System

System returns a handle on the system endpoints.

type Config

type Config struct {
	// Address is the address of the Nomad agent
	Address string

	// Region to use. If not provided, the default agent region is used.
	Region string

	// SecretID to use. This can be overwritten per request.
	SecretID string

	// Namespace to use. If not provided the default namespace is used.
	Namespace string

	// HttpClient is the client to use. Default will be used if not provided.
	//
	// If set, it expected to be configured for tls already, and TLSConfig is ignored.
	// You may use ConfigureTLS() function to aid with initialization.
	HttpClient *http.Client

	// HttpAuth is the auth info to use for http access.
	HttpAuth *HttpBasicAuth

	// WaitTime limits how long a Watch will block. If not provided,
	// the agent default values will be used.
	WaitTime time.Duration

	// TLSConfig provides the various TLS related configurations for the http
	// client.
	//
	// TLSConfig is ignored if HttpClient is set.
	TLSConfig *TLSConfig

	Headers http.Header
}

Config is used to configure the creation of a client

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a default configuration for the client

func (*Config) ClientConfig

func (c *Config) ClientConfig(region, address string, tlsEnabled bool) *Config

ClientConfig copies the configuration with a new client address, region, and whether the client has TLS enabled.

type Constraint

type Constraint struct {
	LTarget string `hcl:"attribute,optional"`
	RTarget string `hcl:"value,optional"`
	Operand string `hcl:"operator,optional"`
}

Constraint is used to serialize a job placement constraint.

func NewConstraint

func NewConstraint(left, operand, right string) *Constraint

NewConstraint generates a new job placement constraint.

type Consul

type Consul struct {
	// (Enterprise-only) Namespace represents a Consul namespace.
	Namespace string `mapstructure:"namespace" hcl:"namespace,optional"`
}

Consul represents configuration related to consul.

func (*Consul) Canonicalize

func (c *Consul) Canonicalize()

Canonicalize Consul into a canonical form. The Canonicalize structs containing a Consul should ensure it is not nil.

func (*Consul) Copy

func (c *Consul) Copy() *Consul

Copy creates a deep copy of c.

func (*Consul) MergeNamespace

func (c *Consul) MergeNamespace(namespace *string)

MergeNamespace sets Namespace to namespace if not already configured. This is used to inherit the job-level consul_namespace if the group-level namespace is not explicitly configured.

type ConsulConnect

type ConsulConnect struct {
	Native         bool                  `hcl:"native,optional"`
	Gateway        *ConsulGateway        `hcl:"gateway,block"`
	SidecarService *ConsulSidecarService `mapstructure:"sidecar_service" hcl:"sidecar_service,block"`
	SidecarTask    *SidecarTask          `mapstructure:"sidecar_task" hcl:"sidecar_task,block"`
}

ConsulConnect represents a Consul Connect jobspec stanza.

func (*ConsulConnect) Canonicalize

func (cc *ConsulConnect) Canonicalize()

type ConsulExposeConfig

type ConsulExposeConfig struct {
	Path []*ConsulExposePath `mapstructure:"path" hcl:"path,block"`
}

func (*ConsulExposeConfig) Canonicalize

func (cec *ConsulExposeConfig) Canonicalize()

type ConsulExposePath

type ConsulExposePath struct {
	Path          string `hcl:"path,optional"`
	Protocol      string `hcl:"protocol,optional"`
	LocalPathPort int    `mapstructure:"local_path_port" hcl:"local_path_port,optional"`
	ListenerPort  string `mapstructure:"listener_port" hcl:"listener_port,optional"`
}

type ConsulGateway

type ConsulGateway struct {
	// Proxy is used to configure the Envoy instance acting as the gateway.
	Proxy *ConsulGatewayProxy `hcl:"proxy,block"`

	// Ingress represents the Consul Configuration Entry for an Ingress Gateway.
	Ingress *ConsulIngressConfigEntry `hcl:"ingress,block"`

	// Terminating represents the Consul Configuration Entry for a Terminating Gateway.
	Terminating *ConsulTerminatingConfigEntry `hcl:"terminating,block"`

	// Mesh indicates the Consul service should be a Mesh Gateway.
	Mesh *ConsulMeshConfigEntry `hcl:"mesh,block"`
}

ConsulGateway is used to configure one of the Consul Connect Gateway types.

func (*ConsulGateway) Canonicalize

func (g *ConsulGateway) Canonicalize()

func (*ConsulGateway) Copy

func (g *ConsulGateway) Copy() *ConsulGateway

type ConsulGatewayBindAddress

type ConsulGatewayBindAddress struct {
	Name    string `hcl:",label"`
	Address string `mapstructure:"address" hcl:"address,optional"`
	Port    int    `mapstructure:"port" hcl:"port,optional"`
}

type ConsulGatewayProxy

type ConsulGatewayProxy struct {
	ConnectTimeout                  *time.Duration                       `mapstructure:"connect_timeout" hcl:"connect_timeout,optional"`
	EnvoyGatewayBindTaggedAddresses bool                                 `mapstructure:"envoy_gateway_bind_tagged_addresses" hcl:"envoy_gateway_bind_tagged_addresses,optional"`
	EnvoyGatewayBindAddresses       map[string]*ConsulGatewayBindAddress `mapstructure:"envoy_gateway_bind_addresses" hcl:"envoy_gateway_bind_addresses,block"`
	EnvoyGatewayNoDefaultBind       bool                                 `mapstructure:"envoy_gateway_no_default_bind" hcl:"envoy_gateway_no_default_bind,optional"`
	EnvoyDNSDiscoveryType           string                               `mapstructure:"envoy_dns_discovery_type" hcl:"envoy_dns_discovery_type,optional"`
	Config                          map[string]interface{}               `hcl:"config,block"` // escape hatch envoy config
}

ConsulGatewayProxy is used to tune parameters of the proxy instance acting as one of the forms of Connect gateways that Consul supports.

https://www.consul.io/docs/connect/proxies/envoy#gateway-options

func (*ConsulGatewayProxy) Canonicalize

func (p *ConsulGatewayProxy) Canonicalize()

func (*ConsulGatewayProxy) Copy

type ConsulGatewayTLSConfig

type ConsulGatewayTLSConfig struct {
	Enabled bool `hcl:"enabled,optional"`
}

ConsulGatewayTLSConfig is used to configure TLS for a gateway.

func (*ConsulGatewayTLSConfig) Canonicalize

func (tc *ConsulGatewayTLSConfig) Canonicalize()

func (*ConsulGatewayTLSConfig) Copy

type ConsulIngressConfigEntry

type ConsulIngressConfigEntry struct {
	TLS       *ConsulGatewayTLSConfig  `hcl:"tls,block"`
	Listeners []*ConsulIngressListener `hcl:"listener,block"`
}

ConsulIngressConfigEntry represents the Consul Configuration Entry type for an Ingress Gateway.

https://www.consul.io/docs/agent/config-entries/ingress-gateway#available-fields

func (*ConsulIngressConfigEntry) Canonicalize

func (e *ConsulIngressConfigEntry) Canonicalize()

func (*ConsulIngressConfigEntry) Copy

type ConsulIngressListener

type ConsulIngressListener struct {
	Port     int                     `hcl:"port,optional"`
	Protocol string                  `hcl:"protocol,optional"`
	Services []*ConsulIngressService `hcl:"service,block"`
}

ConsulIngressListener is used to configure a listener on a Consul Ingress Gateway.

func (*ConsulIngressListener) Canonicalize

func (l *ConsulIngressListener) Canonicalize()

func (*ConsulIngressListener) Copy

type ConsulIngressService

type ConsulIngressService struct {
	// Namespace is not yet supported.
	// Namespace string
	Name string `hcl:"name,optional"`

	Hosts []string `hcl:"hosts,optional"`
}

ConsulIngressService is used to configure a service fronted by the ingress gateway.

func (*ConsulIngressService) Canonicalize

func (s *ConsulIngressService) Canonicalize()

func (*ConsulIngressService) Copy

type ConsulLinkedService

type ConsulLinkedService struct {
	Name     string `hcl:"name,optional"`
	CAFile   string `hcl:"ca_file,optional" mapstructure:"ca_file"`
	CertFile string `hcl:"cert_file,optional" mapstructure:"cert_file"`
	KeyFile  string `hcl:"key_file,optional" mapstructure:"key_file"`
	SNI      string `hcl:"sni,optional"`
}

func (*ConsulLinkedService) Canonicalize

func (s *ConsulLinkedService) Canonicalize()

func (*ConsulLinkedService) Copy

type ConsulMeshConfigEntry

type ConsulMeshConfigEntry struct {
}

ConsulMeshConfigEntry is a stub used to represent that the gateway service type should be for a Mesh Gateway. Unlike Ingress and Terminating, there is no actual Consul Config Entry type for mesh-gateway, at least for now. We still create a type for future proofing, instead just using a bool for example.

func (*ConsulMeshConfigEntry) Canonicalize

func (e *ConsulMeshConfigEntry) Canonicalize()

func (*ConsulMeshConfigEntry) Copy

type ConsulMeshGateway

type ConsulMeshGateway struct {
	// Mode configures how an upstream should be accessed with regard to using
	// mesh gateways.
	//
	// local - the connect proxy makes outbound connections through mesh gateway
	// originating in the same datacenter.
	//
	// remote - the connect proxy makes outbound connections to a mesh gateway
	// in the destination datacenter.
	//
	// none (default) - no mesh gateway is used, the proxy makes outbound connections
	// directly to destination services.
	//
	// https://www.consul.io/docs/connect/gateways/mesh-gateway#modes-of-operation
	Mode string `mapstructure:"mode" hcl:"mode,optional"`
}

ConsulMeshGateway is used to configure mesh gateway usage when connecting to a connect upstream in another datacenter.

func (*ConsulMeshGateway) Canonicalize

func (c *ConsulMeshGateway) Canonicalize()

func (*ConsulMeshGateway) Copy

type ConsulProxy

type ConsulProxy struct {
	LocalServiceAddress string                 `mapstructure:"local_service_address" hcl:"local_service_address,optional"`
	LocalServicePort    int                    `mapstructure:"local_service_port" hcl:"local_service_port,optional"`
	ExposeConfig        *ConsulExposeConfig    `mapstructure:"expose" hcl:"expose,block"`
	Upstreams           []*ConsulUpstream      `hcl:"upstreams,block"`
	Config              map[string]interface{} `hcl:"config,block"`
}

ConsulProxy represents a Consul Connect sidecar proxy jobspec stanza.

func (*ConsulProxy) Canonicalize

func (cp *ConsulProxy) Canonicalize()

type ConsulSidecarService

type ConsulSidecarService struct {
	Tags                   []string     `hcl:"tags,optional"`
	Port                   string       `hcl:"port,optional"`
	Proxy                  *ConsulProxy `hcl:"proxy,block"`
	DisableDefaultTCPCheck bool         `mapstructure:"disable_default_tcp_check" hcl:"disable_default_tcp_check,optional"`
}

ConsulSidecarService represents a Consul Connect SidecarService jobspec stanza.

func (*ConsulSidecarService) Canonicalize

func (css *ConsulSidecarService) Canonicalize()

type ConsulTerminatingConfigEntry

type ConsulTerminatingConfigEntry struct {
	Services []*ConsulLinkedService `hcl:"service,block"`
}

ConsulTerminatingConfigEntry represents the Consul Configuration Entry type for a Terminating Gateway.

https://www.consul.io/docs/agent/config-entries/terminating-gateway#available-fields

func (*ConsulTerminatingConfigEntry) Canonicalize

func (e *ConsulTerminatingConfigEntry) Canonicalize()

func (*ConsulTerminatingConfigEntry) Copy

type ConsulUpstream

type ConsulUpstream struct {
	DestinationName  string             `mapstructure:"destination_name" hcl:"destination_name,optional"`
	LocalBindPort    int                `mapstructure:"local_bind_port" hcl:"local_bind_port,optional"`
	Datacenter       string             `mapstructure:"datacenter" hcl:"datacenter,optional"`
	LocalBindAddress string             `mapstructure:"local_bind_address" hcl:"local_bind_address,optional"`
	MeshGateway      *ConsulMeshGateway `mapstructure:"mesh_gateway" hcl:"mesh_gateway,block"`
}

ConsulUpstream represents a Consul Connect upstream jobspec stanza.

func (*ConsulUpstream) Canonicalize

func (cu *ConsulUpstream) Canonicalize()

func (*ConsulUpstream) Copy

func (cu *ConsulUpstream) Copy() *ConsulUpstream

type CpuStats

type CpuStats struct {
	SystemMode       float64
	UserMode         float64
	TotalTicks       float64
	ThrottledPeriods uint64
	ThrottledTime    uint64
	Percent          float64
	Measured         []string
}

CpuStats holds cpu usage related stats

type DNSConfig

type DNSConfig struct {
	Servers  []string `mapstructure:"servers" hcl:"servers,optional"`
	Searches []string `mapstructure:"searches" hcl:"searches,optional"`
	Options  []string `mapstructure:"options" hcl:"options,optional"`
}

type Deployment

type Deployment struct {
	// ID is a generated UUID for the deployment
	ID string

	// Namespace is the namespace the deployment is created in
	Namespace string

	// JobID is the job the deployment is created for
	JobID string

	// JobVersion is the version of the job at which the deployment is tracking
	JobVersion uint64

	// JobModifyIndex is the ModifyIndex of the job which the deployment is
	// tracking.
	JobModifyIndex uint64

	// JobSpecModifyIndex is the JobModifyIndex of the job which the
	// deployment is tracking.
	JobSpecModifyIndex uint64

	// JobCreateIndex is the create index of the job which the deployment is
	// tracking. It is needed so that if the job gets stopped and reran we can
	// present the correct list of deployments for the job and not old ones.
	JobCreateIndex uint64

	// IsMultiregion specifies if this deployment is part of a multi-region deployment
	IsMultiregion bool

	// TaskGroups is the set of task groups effected by the deployment and their
	// current deployment status.
	TaskGroups map[string]*DeploymentState

	// The status of the deployment
	Status string

	// StatusDescription allows a human readable description of the deployment
	// status.
	StatusDescription string

	CreateIndex uint64
	ModifyIndex uint64
}

Deployment is used to serialize an deployment.

type DeploymentAllocHealthRequest

type DeploymentAllocHealthRequest struct {
	DeploymentID string

	// Marks these allocations as healthy, allow further allocations
	// to be rolled.
	HealthyAllocationIDs []string

	// Any unhealthy allocations fail the deployment
	UnhealthyAllocationIDs []string

	WriteRequest
}

DeploymentAllocHealthRequest is used to set the health of a set of allocations as part of a deployment.

type DeploymentFailRequest

type DeploymentFailRequest struct {
	DeploymentID string
	WriteRequest
}

DeploymentFailRequest is used to fail a particular deployment

type DeploymentIndexSort

type DeploymentIndexSort []*Deployment

DeploymentIndexSort is a wrapper to sort deployments by CreateIndex. We reverse the test so that we get the highest index first.

func (DeploymentIndexSort) Len

func (d DeploymentIndexSort) Len() int

func (DeploymentIndexSort) Less

func (d DeploymentIndexSort) Less(i, j int) bool

func (DeploymentIndexSort) Swap

func (d DeploymentIndexSort) Swap(i, j int)

type DeploymentPauseRequest

type DeploymentPauseRequest struct {
	DeploymentID string

	// Pause sets the pause status
	Pause bool

	WriteRequest
}

DeploymentPauseRequest is used to pause a deployment

type DeploymentPromoteRequest

type DeploymentPromoteRequest struct {
	DeploymentID string

	// All is to promote all task groups
	All bool

	// Groups is used to set the promotion status per task group
	Groups []string

	WriteRequest
}

DeploymentPromoteRequest is used to promote task groups in a deployment

type DeploymentSpecificRequest

type DeploymentSpecificRequest struct {
	DeploymentID string
	QueryOptions
}

DeploymentSpecificRequest is used to make a request specific to a particular deployment

type DeploymentState

type DeploymentState struct {
	PlacedCanaries    []string
	AutoRevert        bool
	ProgressDeadline  time.Duration
	RequireProgressBy time.Time
	Promoted          bool
	DesiredCanaries   int
	DesiredTotal      int
	PlacedAllocs      int
	HealthyAllocs     int
	UnhealthyAllocs   int
}

DeploymentState tracks the state of a deployment for a given task group.

type DeploymentUnblockRequest

type DeploymentUnblockRequest struct {
	DeploymentID string
	WriteRequest
}

DeploymentUnblockRequest is used to unblock a particular deployment

type DeploymentUpdateResponse

type DeploymentUpdateResponse struct {
	EvalID                string
	EvalCreateIndex       uint64
	DeploymentModifyIndex uint64
	RevertedJobVersion    *uint64
	WriteMeta
}

DeploymentUpdateResponse is used to respond to a deployment change. The response will include the modify index of the deployment as well as details of any triggered evaluation.

type Deployments

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

Deployments is used to query the deployments endpoints.

func (*Deployments) Allocations

func (d *Deployments) Allocations(deploymentID string, q *QueryOptions) ([]*AllocationListStub, *QueryMeta, error)

Allocations is used to retrieve a set of allocations that are part of the deployment

func (*Deployments) Fail

func (d *Deployments) Fail(deploymentID string, q *WriteOptions) (*DeploymentUpdateResponse, *WriteMeta, error)

Fail is used to fail the given deployment.

func (*Deployments) Info

func (d *Deployments) Info(deploymentID string, q *QueryOptions) (*Deployment, *QueryMeta, error)

Info is used to query a single deployment by its ID.

func (*Deployments) List

func (d *Deployments) List(q *QueryOptions) ([]*Deployment, *QueryMeta, error)

List is used to dump all of the deployments.

func (*Deployments) Pause

func (d *Deployments) Pause(deploymentID string, pause bool, q *WriteOptions) (*DeploymentUpdateResponse, *WriteMeta, error)

Pause is used to pause or unpause the given deployment.

func (*Deployments) PrefixList

func (d *Deployments) PrefixList(prefix string) ([]*Deployment, *QueryMeta, error)

func (*Deployments) PromoteAll

func (d *Deployments) PromoteAll(deploymentID string, q *WriteOptions) (*DeploymentUpdateResponse, *WriteMeta, error)

PromoteAll is used to promote all canaries in the given deployment

func (*Deployments) PromoteGroups

func (d *Deployments) PromoteGroups(deploymentID string, groups []string, q *WriteOptions) (*DeploymentUpdateResponse, *WriteMeta, error)

PromoteGroups is used to promote canaries in the passed groups in the given deployment

func (*Deployments) SetAllocHealth

func (d *Deployments) SetAllocHealth(deploymentID string, healthy, unhealthy []string, q *WriteOptions) (*DeploymentUpdateResponse, *WriteMeta, error)

SetAllocHealth is used to set allocation health for allocs that are part of the given deployment

func (*Deployments) Unblock

func (d *Deployments) Unblock(deploymentID string, q *WriteOptions) (*DeploymentUpdateResponse, *WriteMeta, error)

Unblock is used to unblock the given deployment.

type DeregisterOptions

type DeregisterOptions struct {
	// If Purge is set to true, the job is deregistered and purged from the
	// system versus still being queryable and eventually GC'ed from the
	// system. Most callers should not specify purge.
	Purge bool

	// If Global is set to true, all regions of a multiregion job will be
	// stopped.
	Global bool

	// EvalPriority is an optional priority to use on any evaluation created as
	// a result on this job deregistration. This value must be between 1-100
	// inclusively, where a larger value corresponds to a higher priority. This
	// is useful when an operator wishes to push through a job deregistration
	// in busy clusters with a large evaluation backlog.
	EvalPriority int

	// NoShutdownDelay, if set to true, will override the group and
	// task shutdown_delay configuration and ignore the delay for any
	// allocations stopped as a result of this Deregister call.
	NoShutdownDelay bool
}

DeregisterOptions is used to pass through job deregistration parameters

type DesiredTransition

type DesiredTransition struct {
	// Migrate is used to indicate that this allocation should be stopped and
	// migrated to another node.
	Migrate *bool

	// Reschedule is used to indicate that this allocation is eligible to be
	// rescheduled.
	Reschedule *bool
}

DesiredTransition is used to mark an allocation as having a desired state transition. This information can be used by the scheduler to make the correct decision.

func (DesiredTransition) ShouldMigrate

func (d DesiredTransition) ShouldMigrate() bool

ShouldMigrate returns whether the transition object dictates a migration.

type DesiredUpdates

type DesiredUpdates struct {
	Ignore            uint64
	Place             uint64
	Migrate           uint64
	Stop              uint64
	InPlaceUpdate     uint64
	DestructiveUpdate uint64
	Canary            uint64
	Preemptions       uint64
}

type DeviceGroupStats

type DeviceGroupStats struct {
	Vendor string
	Type   string
	Name   string

	// InstanceStats is a mapping of each device ID to its statistics.
	InstanceStats map[string]*DeviceStats
}

DeviceGroupStats contains statistics for each device of a particular device group, identified by the vendor, type and name of the device.

type DeviceStats

type DeviceStats struct {
	// Summary exposes a single summary metric that should be the most
	// informative to users.
	Summary *StatValue

	// Stats contains the verbose statistics for the device.
	Stats *StatObject

	// Timestamp is the time the statistics were collected.
	Timestamp time.Time
}

DeviceStats is the statistics for an individual device

type DiskUsage

type DiskUsage struct {
	DiskMB int64
	UsedMB int64
}

type DispatchPayloadConfig

type DispatchPayloadConfig struct {
	File string `hcl:"file,optional"`
}

DispatchPayloadConfig configures how a task gets its input from a job dispatch

type DrainMetadata

type DrainMetadata struct {
	StartedAt  time.Time
	UpdatedAt  time.Time
	Status     DrainStatus
	AccessorID string
	Meta       map[string]string
}

DrainMetadata contains information about the most recent drain operation for a given Node.

type DrainOptions

type DrainOptions struct {
	// DrainSpec contains the drain specification for the node. If non-nil,
	// the node will be marked ineligible and begin/continue draining according
	// to the provided drain spec.
	// If nil, any existing drain operation will be canceled.
	DrainSpec *DrainSpec

	// MarkEligible indicates whether the node should be marked as eligible when
	// canceling a drain operation.
	MarkEligible bool

	// Meta is metadata that is persisted in Node.LastDrain about this
	// drain update.
	Meta map[string]string
}

DrainOptions is used to pass through node drain parameters

type DrainSpec

type DrainSpec struct {
	// Deadline is the duration after StartTime when the remaining
	// allocations on a draining Node should be told to stop.
	Deadline time.Duration

	// IgnoreSystemJobs allows systems jobs to remain on the node even though it
	// has been marked for draining.
	IgnoreSystemJobs bool
}

DrainSpec describes a Node's drain behavior.

type DrainStatus

type DrainStatus string

type DrainStrategy

type DrainStrategy struct {
	// DrainSpec is the user declared drain specification
	DrainSpec

	// ForceDeadline is the deadline time for the drain after which drains will
	// be forced
	ForceDeadline time.Time

	// StartedAt is the time the drain process started
	StartedAt time.Time
}

DrainStrategy describes a Node's drain behavior.

func (*DrainStrategy) Equal

func (d *DrainStrategy) Equal(o *DrainStrategy) bool

func (*DrainStrategy) String

func (d *DrainStrategy) String() string

String returns a human readable version of the drain strategy.

type DriverInfo

type DriverInfo struct {
	Attributes        map[string]string
	Detected          bool
	Healthy           bool
	HealthDescription string
	UpdateTime        time.Time
}

DriverInfo is used to deserialize a DriverInfo entry

type EphemeralDisk

type EphemeralDisk struct {
	Sticky  *bool `hcl:"sticky,optional"`
	Migrate *bool `hcl:"migrate,optional"`
	SizeMB  *int  `mapstructure:"size" hcl:"size,optional"`
}

EphemeralDisk is an ephemeral disk object

func DefaultEphemeralDisk

func DefaultEphemeralDisk() *EphemeralDisk

func (*EphemeralDisk) Canonicalize

func (e *EphemeralDisk) Canonicalize()

type EvalIndexSort

type EvalIndexSort []*Evaluation

EvalIndexSort is a wrapper to sort evaluations by CreateIndex. We reverse the test so that we get the highest index first.

func (EvalIndexSort) Len

func (e EvalIndexSort) Len() int

func (EvalIndexSort) Less

func (e EvalIndexSort) Less(i, j int) bool

func (EvalIndexSort) Swap

func (e EvalIndexSort) Swap(i, j int)

type EvalOptions

type EvalOptions struct {
	ForceReschedule bool
}

EvalOptions is used to encapsulate options when forcing a job evaluation

type Evaluation

type Evaluation struct {
	ID                   string
	Priority             int
	Type                 string
	TriggeredBy          string
	Namespace            string
	JobID                string
	JobModifyIndex       uint64
	NodeID               string
	NodeModifyIndex      uint64
	DeploymentID         string
	Status               string
	StatusDescription    string
	Wait                 time.Duration
	WaitUntil            time.Time
	NextEval             string
	PreviousEval         string
	BlockedEval          string
	FailedTGAllocs       map[string]*AllocationMetric
	ClassEligibility     map[string]bool
	EscapedComputedClass bool
	QuotaLimitReached    string
	AnnotatePlan         bool
	QueuedAllocations    map[string]int
	SnapshotIndex        uint64
	CreateIndex          uint64
	ModifyIndex          uint64
	CreateTime           int64
	ModifyTime           int64
}

Evaluation is used to serialize an evaluation.

type Evaluations

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

Evaluations is used to query the evaluation endpoints.

func (*Evaluations) Allocations

func (e *Evaluations) Allocations(evalID string, q *QueryOptions) ([]*AllocationListStub, *QueryMeta, error)

Allocations is used to retrieve a set of allocations given an evaluation ID.

func (*Evaluations) Info

func (e *Evaluations) Info(evalID string, q *QueryOptions) (*Evaluation, *QueryMeta, error)

Info is used to query a single evaluation by its ID.

func (*Evaluations) List

func (e *Evaluations) List(q *QueryOptions) ([]*Evaluation, *QueryMeta, error)

List is used to dump all of the evaluations.

func (*Evaluations) PrefixList

func (e *Evaluations) PrefixList(prefix string) ([]*Evaluation, *QueryMeta, error)

type Event

type Event struct {
	Topic      Topic
	Type       string
	Key        string
	FilterKeys []string
	Index      uint64
	Payload    map[string]interface{}
}

Event holds information related to an event that occurred in Nomad. The Payload is a hydrated object related to the Topic

func (*Event) Allocation

func (e *Event) Allocation() (*Allocation, error)

Allocation returns a Allocation struct from a given event payload. If the Event Topic is Allocation this will return a valid Allocation.

func (*Event) Deployment

func (e *Event) Deployment() (*Deployment, error)

Deployment returns a Deployment struct from a given event payload. If the Event Topic is Deployment this will return a valid Deployment

func (*Event) Evaluation

func (e *Event) Evaluation() (*Evaluation, error)

Evaluation returns a Evaluation struct from a given event payload. If the Event Topic is Evaluation this will return a valid Evaluation

func (*Event) Job

func (e *Event) Job() (*Job, error)

Job returns a Job struct from a given event payload. If the Event Topic is Job this will return a valid Job.

func (*Event) Node

func (e *Event) Node() (*Node, error)

Node returns a Node struct from a given event payload. If the Event Topic is Node this will return a valid Node.

type EventStream

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

EventStream is used to stream events from Nomad

func (*EventStream) Stream

func (e *EventStream) Stream(ctx context.Context, topics map[Topic][]string, index uint64, q *QueryOptions) (<-chan *Events, error)

Stream establishes a new subscription to Nomad's event stream and streams results back to the returned channel.

type Events

type Events struct {
	Index  uint64
	Events []Event
	Err    error
}

Events is a set of events for a corresponding index. Events returned for the index depend on which topics are subscribed to when a request is made.

func (*Events) IsHeartbeat

func (e *Events) IsHeartbeat() bool

IsHeartbeat specifies if the event is an empty heartbeat used to keep a connection alive.

type ExecStreamingExitResult

type ExecStreamingExitResult struct {
	ExitCode int `json:"exit_code"`
}

ExecStreamingExitResults captures the exit code of just completed nomad exec command

type ExecStreamingIOOperation

type ExecStreamingIOOperation struct {
	Data  []byte `json:"data,omitempty"`
	Close bool   `json:"close,omitempty"`
}

ExecStreamingIOOperation represents a stream write operation: either appending data or close (exclusively)

type ExecStreamingInput

type ExecStreamingInput struct {
	Stdin   *ExecStreamingIOOperation `json:"stdin,omitempty"`
	TTYSize *TerminalSize             `json:"tty_size,omitempty"`
}

ExecStreamingInput represents user input to be sent to nomad exec handler.

At most one field should be set.

type ExecStreamingOutput

type ExecStreamingOutput struct {
	Stdout *ExecStreamingIOOperation `json:"stdout,omitempty"`
	Stderr *ExecStreamingIOOperation `json:"stderr,omitempty"`

	Exited bool                     `json:"exited,omitempty"`
	Result *ExecStreamingExitResult `json:"result,omitempty"`
}

ExecStreamingInput represents an output streaming entity, e.g. stdout/stderr update or termination

At most one of these fields should be set: `Stdout`, `Stderr`, or `Result`. If `Exited` is true, then `Result` is non-nil, and other fields are nil.

type FieldDiff

type FieldDiff struct {
	Type        string
	Name        string
	Old, New    string
	Annotations []string
}

type FrameReader

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

FrameReader is used to convert a stream of frames into a read closer.

func NewFrameReader

func NewFrameReader(frames <-chan *StreamFrame, errCh <-chan error, cancelCh chan struct{}) *FrameReader

NewFrameReader takes a channel of frames and returns a FrameReader which implements io.ReadCloser

func (*FrameReader) Close

func (f *FrameReader) Close() error

Close cancels the stream of frames

func (*FrameReader) Offset

func (f *FrameReader) Offset() int

Offset returns the offset into the stream.

func (*FrameReader) Read

func (f *FrameReader) Read(p []byte) (n int, err error)

Read reads the data of the incoming frames into the bytes buffer. Returns EOF when there are no more frames.

func (*FrameReader) SetUnblockTime

func (f *FrameReader) SetUnblockTime(d time.Duration)

SetUnblockTime sets the time to unblock and return zero bytes read. If the duration is unset or is zero or less, the read will block until data is read.

type FuzzyMatch

type FuzzyMatch struct {
	ID    string   // ID is UUID or Name of object
	Scope []string `json:",omitempty"` // IDs of parent objects
}

FuzzyMatch is used to describe the ID of an object which may be a machine readable UUID or a human readable Name. If the object is a component of a Job, the Scope is a list of IDs starting from Namespace down to the parent object of ID.

e.g. A Task-level service would have scope like,

["<namespace>", "<job>", "<group>", "<task>"]

type FuzzySearchRequest

type FuzzySearchRequest struct {
	// Text is what names are fuzzy-matched to. E.g. if the given text were
	// "py", potential matches might be "python", "mypy", etc. of jobs, nodes,
	// allocs, groups, services, commands, images, classes.
	Text string

	// Context is the type that can be matched against. A Context of "all" indicates
	// all Contexts types are queried for matching.
	Context contexts.Context

	QueryOptions
}

FuzzySearchRequest is used to parameterize a fuzzy search request, and returns a list of matches made up of jobs, allocations, evaluations, and/or nodes, along with whether or not the information returned is truncated.

type FuzzySearchResponse

type FuzzySearchResponse struct {
	// Matches is a map of Context types to IDs which fuzzy match a specified query.
	Matches map[contexts.Context][]FuzzyMatch

	// Truncations indicates whether the matches for a particular Context have
	// been truncated.
	Truncations map[contexts.Context]bool

	QueryMeta
}

FuzzySearchResponse is used to return fuzzy matches and information about whether the match list is truncated specific to each type of searchable Context.

type GaugeValue

type GaugeValue struct {
	Name  string
	Hash  string `json:"-"`
	Value float32

	Labels        []Label           `json:"-"`
	DisplayLabels map[string]string `json:"Labels"`
}

type GenericResponse

type GenericResponse struct {
	WriteMeta
}

GenericResponse is used to respond to a request where no specific response information is needed.

type HostCPUStats

type HostCPUStats struct {
	CPU    string
	User   float64
	System float64
	Idle   float64
}

type HostData

type HostData struct {
	OS          string
	Network     []map[string]string
	ResolvConf  string
	Hosts       string
	Environment map[string]string
	Disk        map[string]DiskUsage
}

type HostDataResponse

type HostDataResponse struct {
	AgentID  string
	HostData *HostData `json:",omitempty"`
}

type HostDiskStats

type HostDiskStats struct {
	Device            string
	Mountpoint        string
	Size              uint64
	Used              uint64
	Available         uint64
	UsedPercent       float64
	InodesUsedPercent float64
}

type HostMemoryStats

type HostMemoryStats struct {
	Total     uint64
	Available uint64
	Used      uint64
	Free      uint64
}

type HostNetworkInfo

type HostNetworkInfo struct {
	Name          string
	CIDR          string
	Interface     string
	ReservedPorts string
}

HostNetworkInfo is used to return metadata about a given HostNetwork

type HostStats

type HostStats struct {
	Memory           *HostMemoryStats
	CPU              []*HostCPUStats
	DiskStats        []*HostDiskStats
	DeviceStats      []*DeviceGroupStats
	Uptime           uint64
	CPUTicksConsumed float64
}

HostStats represents resource usage stats of the host running a Nomad client

type HostVolumeInfo

type HostVolumeInfo struct {
	Path     string
	ReadOnly bool
}

HostVolumeInfo is used to return metadata about a given HostVolume.

type HttpBasicAuth

type HttpBasicAuth struct {
	// Username to use for HTTP Basic Authentication
	Username string

	// Password to use for HTTP Basic Authentication
	Password string
}

HttpBasicAuth is used to authenticate http client with HTTP Basic Authentication

type Job

type Job struct {
	Region           *string                 `hcl:"region,optional"`
	Namespace        *string                 `hcl:"namespace,optional"`
	ID               *string                 `hcl:"id,optional"`
	Name             *string                 `hcl:"name,optional"`
	Type             *string                 `hcl:"type,optional"`
	Priority         *int                    `hcl:"priority,optional"`
	AllAtOnce        *bool                   `mapstructure:"all_at_once" hcl:"all_at_once,optional"`
	Datacenters      []string                `hcl:"datacenters,optional"`
	Constraints      []*Constraint           `hcl:"constraint,block"`
	Affinities       []*Affinity             `hcl:"affinity,block"`
	TaskGroups       []*TaskGroup            `hcl:"group,block"`
	Update           *UpdateStrategy         `hcl:"update,block"`
	Multiregion      *Multiregion            `hcl:"multiregion,block"`
	Spreads          []*Spread               `hcl:"spread,block"`
	Periodic         *PeriodicConfig         `hcl:"periodic,block"`
	ParameterizedJob *ParameterizedJobConfig `hcl:"parameterized,block"`
	Reschedule       *ReschedulePolicy       `hcl:"reschedule,block"`
	Migrate          *MigrateStrategy        `hcl:"migrate,block"`
	Meta             map[string]string       `hcl:"meta,block"`
	ConsulToken      *string                 `mapstructure:"consul_token" hcl:"consul_token,optional"`
	VaultToken       *string                 `mapstructure:"vault_token" hcl:"vault_token,optional"`

	Stop                     *bool
	ParentID                 *string
	Dispatched               bool
	DispatchIdempotencyToken *string
	Payload                  []byte
	ConsulNamespace          *string `mapstructure:"consul_namespace"`
	VaultNamespace           *string `mapstructure:"vault_namespace"`
	NomadTokenID             *string `mapstructure:"nomad_token_id"`
	Status                   *string
	StatusDescription        *string
	Stable                   *bool
	Version                  *uint64
	SubmitTime               *int64
	CreateIndex              *uint64
	ModifyIndex              *uint64
	JobModifyIndex           *uint64
}

Job is used to serialize a job.

func NewBatchJob

func NewBatchJob(id, name, region string, pri int) *Job

NewBatchJob creates and returns a new batch-style job for short-lived processes using the provided name and ID along with the relative job priority.

func NewServiceJob

func NewServiceJob(id, name, region string, pri int) *Job

NewServiceJob creates and returns a new service-style job for long-lived processes using the provided name, ID, and relative job priority.

func NewSystemJob

func NewSystemJob(id, name, region string, pri int) *Job

NewSystemJob creates and returns a new system-style job for processes designed to run on all clients, using the provided name and ID along with the relative job priority.

func (*Job) AddAffinity

func (j *Job) AddAffinity(a *Affinity) *Job

AddAffinity is used to add an affinity to a job.

func (*Job) AddDatacenter

func (j *Job) AddDatacenter(dc string) *Job

AddDatacenter is used to add a datacenter to a job.

func (*Job) AddPeriodicConfig

func (j *Job) AddPeriodicConfig(cfg *PeriodicConfig) *Job

AddPeriodicConfig adds a periodic config to an existing job.

func (*Job) AddSpread

func (j *Job) AddSpread(s *Spread) *Job

func (*Job) AddTaskGroup

func (j *Job) AddTaskGroup(grp *TaskGroup) *Job

AddTaskGroup adds a task group to an existing job.

func (*Job) Canonicalize

func (j *Job) Canonicalize()

func (*Job) Constrain

func (j *Job) Constrain(c *Constraint) *Job

Constrain is used to add a constraint to a job.

func (*Job) IsMultiregion

func (j *Job) IsMultiregion() bool

IsMultiregion returns whether a job is a multiregion job

func (*Job) IsParameterized

func (j *Job) IsParameterized() bool

IsParameterized returns whether a job is parameterized job.

func (*Job) IsPeriodic

func (j *Job) IsPeriodic() bool

IsPeriodic returns whether a job is periodic.

func (*Job) LookupTaskGroup

func (j *Job) LookupTaskGroup(name string) *TaskGroup

LookupTaskGroup finds a task group by name

func (*Job) SetMeta

func (j *Job) SetMeta(key, val string) *Job

SetMeta is used to set arbitrary k/v pairs of metadata on a job.

type JobChildrenSummary

type JobChildrenSummary struct {
	Pending int64
	Running int64
	Dead    int64
}

JobChildrenSummary contains the summary of children job status

func (*JobChildrenSummary) Sum

func (jc *JobChildrenSummary) Sum() int

type JobDeregisterResponse

type JobDeregisterResponse struct {
	EvalID          string
	EvalCreateIndex uint64
	JobModifyIndex  uint64
	QueryMeta
}

JobDeregisterResponse is used to respond to a job deregistration

type JobDiff

type JobDiff struct {
	Type       string
	ID         string
	Fields     []*FieldDiff
	Objects    []*ObjectDiff
	TaskGroups []*TaskGroupDiff
}

type JobDispatchRequest

type JobDispatchRequest struct {
	JobID   string
	Payload []byte
	Meta    map[string]string
}

type JobDispatchResponse

type JobDispatchResponse struct {
	DispatchedJobID string
	EvalID          string
	EvalCreateIndex uint64
	JobCreateIndex  uint64
	WriteMeta
}

type JobEvaluateRequest

type JobEvaluateRequest struct {
	JobID       string
	EvalOptions EvalOptions
	WriteRequest
}

JobEvaluateRequest is used when we just need to re-evaluate a target job

type JobIDSort

type JobIDSort []*JobListStub

JobIDSort is used to sort jobs by their job ID's.

func (JobIDSort) Len

func (j JobIDSort) Len() int

func (JobIDSort) Less

func (j JobIDSort) Less(a, b int) bool

func (JobIDSort) Swap

func (j JobIDSort) Swap(a, b int)

type JobListStub

type JobListStub struct {
	ID                string
	ParentID          string
	Name              string
	Namespace         string `json:",omitempty"`
	Datacenters       []string
	Type              string
	Priority          int
	Periodic          bool
	ParameterizedJob  bool
	Stop              bool
	Status            string
	StatusDescription string
	JobSummary        *JobSummary
	CreateIndex       uint64
	ModifyIndex       uint64
	JobModifyIndex    uint64
	SubmitTime        int64
}

JobListStub is used to return a subset of information about jobs during list operations.

type JobPlanRequest

type JobPlanRequest struct {
	Job            *Job
	Diff           bool
	PolicyOverride bool
	WriteRequest
}

type JobPlanResponse

type JobPlanResponse struct {
	JobModifyIndex     uint64
	CreatedEvals       []*Evaluation
	Diff               *JobDiff
	Annotations        *PlanAnnotations
	FailedTGAllocs     map[string]*AllocationMetric
	NextPeriodicLaunch time.Time

	// Warnings contains any warnings about the given job. These may include
	// deprecation warnings.
	Warnings string
}

type JobRegisterRequest

type JobRegisterRequest struct {
	Job *Job
	// If EnforceIndex is set then the job will only be registered if the passed
	// JobModifyIndex matches the current Jobs index. If the index is zero, the
	// register only occurs if the job is new.
	EnforceIndex   bool   `json:",omitempty"`
	JobModifyIndex uint64 `json:",omitempty"`
	PolicyOverride bool   `json:",omitempty"`
	PreserveCounts bool   `json:",omitempty"`

	// EvalPriority is an optional priority to use on any evaluation created as
	// a result on this job registration. This value must be between 1-100
	// inclusively, where a larger value corresponds to a higher priority. This
	// is useful when an operator wishes to push through a job registration in
	// busy clusters with a large evaluation backlog. This avoids needing to
	// change the job priority which also impacts preemption.
	EvalPriority int `json:",omitempty"`

	WriteRequest
}

JobRegisterRequest is used to update a job

type JobRegisterResponse

type JobRegisterResponse struct {
	EvalID          string
	EvalCreateIndex uint64
	JobModifyIndex  uint64

	// Warnings contains any warnings about the given job. These may include
	// deprecation warnings.
	Warnings string

	QueryMeta
}

JobRegisterResponse is used to respond to a job registration

type JobRevertRequest

type JobRevertRequest struct {
	// JobID is the ID of the job  being reverted
	JobID string

	// JobVersion the version to revert to.
	JobVersion uint64

	// EnforcePriorVersion if set will enforce that the job is at the given
	// version before reverting.
	EnforcePriorVersion *uint64

	// ConsulToken is the Consul token that proves the submitter of the job revert
	// has access to the Service Identity policies associated with the job's
	// Consul Connect enabled services. This field is only used to transfer the
	// token and is not stored after the Job revert.
	ConsulToken string `json:",omitempty"`

	// VaultToken is the Vault token that proves the submitter of the job revert
	// has access to any Vault policies specified in the targeted job version. This
	// field is only used to authorize the revert and is not stored after the Job
	// revert.
	VaultToken string `json:",omitempty"`

	WriteRequest
}

JobRevertRequest is used to revert a job to a prior version.

type JobScaleStatusResponse

type JobScaleStatusResponse struct {
	JobID          string
	Namespace      string
	JobCreateIndex uint64
	JobModifyIndex uint64
	JobStopped     bool
	TaskGroups     map[string]TaskGroupScaleStatus
}

JobScaleStatusResponse is used to return information about job scaling status

type JobStabilityRequest

type JobStabilityRequest struct {
	// Job to set the stability on
	JobID      string
	JobVersion uint64

	// Set the stability
	Stable bool
	WriteRequest
}

JobStabilityRequest is used to marked a job as stable.

type JobStabilityResponse

type JobStabilityResponse struct {
	JobModifyIndex uint64
	WriteMeta
}

JobStabilityResponse is the response when marking a job as stable.

type JobSummary

type JobSummary struct {
	JobID     string
	Namespace string
	Summary   map[string]TaskGroupSummary
	Children  *JobChildrenSummary

	// Raft Indexes
	CreateIndex uint64
	ModifyIndex uint64
}

JobSummary summarizes the state of the allocations of a job

type JobValidateRequest

type JobValidateRequest struct {
	Job *Job
	WriteRequest
}

JobValidateRequest is used to validate a job

type JobValidateResponse

type JobValidateResponse struct {
	// DriverConfigValidated indicates whether the agent validated the driver
	// config
	DriverConfigValidated bool

	// ValidationErrors is a list of validation errors
	ValidationErrors []string

	// Error is a string version of any error that may have occurred
	Error string

	// Warnings contains any warnings about the given job. These may include
	// deprecation warnings.
	Warnings string
}

JobValidateResponse is the response from validate request

type JobVersionsResponse

type JobVersionsResponse struct {
	Versions []*Job
	Diffs    []*JobDiff
	QueryMeta
}

JobVersionsResponse is used for a job get versions request

type Jobs

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

Jobs is used to access the job-specific endpoints.

func (*Jobs) Allocations

func (j *Jobs) Allocations(jobID string, allAllocs bool, q *QueryOptions) ([]*AllocationListStub, *QueryMeta, error)

Allocations is used to return the allocs for a given job ID.

func (*Jobs) Deployments

func (j *Jobs) Deployments(jobID string, all bool, q *QueryOptions) ([]*Deployment, *QueryMeta, error)

Deployments is used to query the deployments associated with the given job ID.

func (*Jobs) Deregister

func (j *Jobs) Deregister(jobID string, purge bool, q *WriteOptions) (string, *WriteMeta, error)

Deregister is used to remove an existing job. If purge is set to true, the job is deregistered and purged from the system versus still being queryable and eventually GC'ed from the system. Most callers should not specify purge.

func (*Jobs) DeregisterOpts

func (j *Jobs) DeregisterOpts(jobID string, opts *DeregisterOptions, q *WriteOptions) (string, *WriteMeta, error)

DeregisterOpts is used to remove an existing job. See DeregisterOptions for parameters.

func (*Jobs) Dispatch

func (j *Jobs) Dispatch(jobID string, meta map[string]string,
	payload []byte, q *WriteOptions) (*JobDispatchResponse, *WriteMeta, error)

func (*Jobs) EnforceRegister

func (j *Jobs) EnforceRegister(job *Job, modifyIndex uint64, q *WriteOptions) (*JobRegisterResponse, *WriteMeta, error)

EnforceRegister is used to register a job enforcing its job modify index.

func (*Jobs) EvaluateWithOpts

func (j *Jobs) EvaluateWithOpts(jobID string, opts EvalOptions, q *WriteOptions) (string, *WriteMeta, error)

EvaluateWithOpts is used to force-evaluate an existing job and takes additional options for whether to force reschedule failed allocations

func (*Jobs) Evaluations

func (j *Jobs) Evaluations(jobID string, q *QueryOptions) ([]*Evaluation, *QueryMeta, error)

Evaluations is used to query the evaluations associated with the given job ID.

func (*Jobs) ForceEvaluate

func (j *Jobs) ForceEvaluate(jobID string, q *WriteOptions) (string, *WriteMeta, error)

ForceEvaluate is used to force-evaluate an existing job.

func (*Jobs) Info

func (j *Jobs) Info(jobID string, q *QueryOptions) (*Job, *QueryMeta, error)

Info is used to retrieve information about a particular job given its unique ID.

func (*Jobs) LatestDeployment

func (j *Jobs) LatestDeployment(jobID string, q *QueryOptions) (*Deployment, *QueryMeta, error)

LatestDeployment is used to query for the latest deployment associated with the given job ID.

func (*Jobs) List

func (j *Jobs) List(q *QueryOptions) ([]*JobListStub, *QueryMeta, error)

List is used to list all of the existing jobs.

func (*Jobs) ParseHCL

func (j *Jobs) ParseHCL(jobHCL string, canonicalize bool) (*Job, error)

ParseHCL is used to convert the HCL repesentation of a Job to JSON server side. To parse the HCL client side see package github.com/hashicorp/nomad/jobspec

func (*Jobs) PeriodicForce

func (j *Jobs) PeriodicForce(jobID string, q *WriteOptions) (string, *WriteMeta, error)

PeriodicForce spawns a new instance of the periodic job and returns the eval ID

func (*Jobs) Plan

func (j *Jobs) Plan(job *Job, diff bool, q *WriteOptions) (*JobPlanResponse, *WriteMeta, error)

func (*Jobs) PlanOpts

func (j *Jobs) PlanOpts(job *Job, opts *PlanOptions, q *WriteOptions) (*JobPlanResponse, *WriteMeta, error)

func (*Jobs) PrefixList

func (j *Jobs) PrefixList(prefix string) ([]*JobListStub, *QueryMeta, error)

PrefixList is used to list all existing jobs that match the prefix.

func (*Jobs) Register

func (j *Jobs) Register(job *Job, q *WriteOptions) (*JobRegisterResponse, *WriteMeta, error)

Register is used to register a new job. It returns the ID of the evaluation, along with any errors encountered.

func (*Jobs) RegisterOpts

func (j *Jobs) RegisterOpts(job *Job, opts *RegisterOptions, q *WriteOptions) (*JobRegisterResponse, *WriteMeta, error)

RegisterOpts is used to register a new job with the passed RegisterOpts. It returns the ID of the evaluation, along with any errors encountered.

func (*Jobs) Revert

func (j *Jobs) Revert(jobID string, version uint64, enforcePriorVersion *uint64,
	q *WriteOptions, consulToken, vaultToken string) (*JobRegisterResponse, *WriteMeta, error)

Revert is used to revert the given job to the passed version. If enforceVersion is set, the job is only reverted if the current version is at the passed version.

func (*Jobs) Scale

func (j *Jobs) Scale(jobID, group string, count *int, message string, error bool, meta map[string]interface{},
	q *WriteOptions) (*JobRegisterResponse, *WriteMeta, error)

Scale is used to retrieve information about a particular job given its unique ID.

func (*Jobs) ScaleStatus

func (j *Jobs) ScaleStatus(jobID string, q *QueryOptions) (*JobScaleStatusResponse, *QueryMeta, error)

ScaleStatus is used to retrieve information about a particular job given its unique ID.

func (*Jobs) Stable

func (j *Jobs) Stable(jobID string, version uint64, stable bool,
	q *WriteOptions) (*JobStabilityResponse, *WriteMeta, error)

Stable is used to mark a job version's stability.

func (*Jobs) Summary

func (j *Jobs) Summary(jobID string, q *QueryOptions) (*JobSummary, *QueryMeta, error)

func (*Jobs) Validate

func (j *Jobs) Validate(job *Job, q *WriteOptions) (*JobValidateResponse, *WriteMeta, error)

func (*Jobs) Versions

func (j *Jobs) Versions(jobID string, diffs bool, q *QueryOptions) ([]*Job, []*JobDiff, *QueryMeta, error)

Versions is used to retrieve all versions of a particular job given its unique ID.

type JobsParseRequest

type JobsParseRequest struct {
	// JobHCL is an hcl jobspec
	JobHCL string

	// HCLv1 indicates whether the JobHCL should be parsed with the hcl v1 parser
	HCLv1 bool `json:"hclv1,omitempty"`

	// Canonicalize is a flag as to if the server should return default values
	// for unset fields
	Canonicalize bool
}

JobsParseRequest is used for arguments of the /v1/jobs/parse endpoint

type KeyringRequest

type KeyringRequest struct {
	Key string
}

KeyringRequest is request objects for serf key operations.

type KeyringResponse

type KeyringResponse struct {
	Messages map[string]string
	Keys     map[string]int
	NumNodes int
}

KeyringResponse is a unified key response and can be used for install, remove, use, as well as listing key queries.

type Label

type Label struct {
	Name  string
	Value string
}

type License

type License struct {
	// The unique identifier of the license
	LicenseID string

	// The customer ID associated with the license
	CustomerID string

	// If set, an identifier that should be used to lock the license to a
	// particular site, cluster, etc.
	InstallationID string

	// The time at which the license was issued
	IssueTime time.Time

	// The time at which the license starts being valid
	StartTime time.Time

	// The time after which the license expires
	ExpirationTime time.Time

	// The time at which the license ceases to function and can
	// no longer be used in any capacity
	TerminationTime time.Time

	// The product the license is valid for
	Product string

	// License Specific Flags
	Flags map[string]interface{}

	// Modules is a list of the licensed enterprise modules
	Modules []string

	// List of features enabled by the license
	Features []string
}

type LicenseReply

type LicenseReply struct {
	License        *License
	ConfigOutdated bool
	QueryMeta
}

type LogConfig

type LogConfig struct {
	MaxFiles      *int `mapstructure:"max_files" hcl:"max_files,optional"`
	MaxFileSizeMB *int `mapstructure:"max_file_size" hcl:"max_file_size,optional"`
}

LogConfig provides configuration for log rotation

func DefaultLogConfig

func DefaultLogConfig() *LogConfig

func (*LogConfig) Canonicalize

func (l *LogConfig) Canonicalize()

type MemoryStats

type MemoryStats struct {
	RSS            uint64
	Cache          uint64
	Swap           uint64
	Usage          uint64
	MaxUsage       uint64
	KernelUsage    uint64
	KernelMaxUsage uint64
	Measured       []string
}

MemoryStats holds memory usage related stats

type MetricsSummary

type MetricsSummary struct {
	Timestamp string
	Gauges    []GaugeValue
	Points    []PointValue
	Counters  []SampledValue
	Samples   []SampledValue
}

MetricsSummary holds a roll-up of metrics info for a given interval

type MigrateStrategy

type MigrateStrategy struct {
	MaxParallel     *int           `mapstructure:"max_parallel" hcl:"max_parallel,optional"`
	HealthCheck     *string        `mapstructure:"health_check" hcl:"health_check,optional"`
	MinHealthyTime  *time.Duration `mapstructure:"min_healthy_time" hcl:"min_healthy_time,optional"`
	HealthyDeadline *time.Duration `mapstructure:"healthy_deadline" hcl:"healthy_deadline,optional"`
}

MigrateStrategy describes how allocations for a task group should be migrated between nodes (eg when draining).

func DefaultMigrateStrategy

func DefaultMigrateStrategy() *MigrateStrategy

func (*MigrateStrategy) Canonicalize

func (m *MigrateStrategy) Canonicalize()

func (*MigrateStrategy) Copy

func (m *MigrateStrategy) Copy() *MigrateStrategy

func (*MigrateStrategy) Merge

func (m *MigrateStrategy) Merge(o *MigrateStrategy)

type MonitorMessage

type MonitorMessage struct {
	Level   MonitorMsgLevel
	Message string
}

MonitorMessage contains a message and log level.

func Messagef

func Messagef(lvl MonitorMsgLevel, msg string, args ...interface{}) *MonitorMessage

Messagef formats a new MonitorMessage.

func (*MonitorMessage) String

func (m *MonitorMessage) String() string

type MonitorMsgLevel

type MonitorMsgLevel int

MonitorMsgLevels represents the severity log level of a MonitorMessage.

const (
	MonitorMsgLevelNormal MonitorMsgLevel = 0
	MonitorMsgLevelInfo   MonitorMsgLevel = 1
	MonitorMsgLevelWarn   MonitorMsgLevel = 2
	MonitorMsgLevelError  MonitorMsgLevel = 3
)

type Multiregion

type Multiregion struct {
	Strategy *MultiregionStrategy `hcl:"strategy,block"`
	Regions  []*MultiregionRegion `hcl:"region,block"`
}

func (*Multiregion) Canonicalize

func (m *Multiregion) Canonicalize()

func (*Multiregion) Copy

func (m *Multiregion) Copy() *Multiregion

type MultiregionRegion

type MultiregionRegion struct {
	Name        string            `hcl:",label"`
	Count       *int              `hcl:"count,optional"`
	Datacenters []string          `hcl:"datacenters,optional"`
	Meta        map[string]string `hcl:"meta,block"`
}

type MultiregionStrategy

type MultiregionStrategy struct {
	MaxParallel *int    `mapstructure:"max_parallel" hcl:"max_parallel,optional"`
	OnFailure   *string `mapstructure:"on_failure" hcl:"on_failure,optional"`
}

type Namespace

type Namespace struct {
	Name         string
	Description  string
	Quota        string
	Capabilities *NamespaceCapabilities `hcl:"capabilities,block"`
	Meta         map[string]string
	CreateIndex  uint64
	ModifyIndex  uint64
}

Namespace is used to serialize a namespace.

type NamespaceCapabilities

type NamespaceCapabilities struct {
	EnabledTaskDrivers  []string `hcl:"enabled_task_drivers"`
	DisabledTaskDrivers []string `hcl:"disabled_task_drivers"`
}

type NamespaceIndexSort

type NamespaceIndexSort []*Namespace

NamespaceIndexSort is a wrapper to sort Namespaces by CreateIndex. We reverse the test so that we get the highest index first.

func (NamespaceIndexSort) Len

func (n NamespaceIndexSort) Len() int

func (NamespaceIndexSort) Less

func (n NamespaceIndexSort) Less(i, j int) bool

func (NamespaceIndexSort) Swap

func (n NamespaceIndexSort) Swap(i, j int)

type Namespaces

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

Namespaces is used to query the namespace endpoints.

func (*Namespaces) Delete

func (n *Namespaces) Delete(namespace string, q *WriteOptions) (*WriteMeta, error)

Delete is used to delete a namespace

func (*Namespaces) Info

func (n *Namespaces) Info(name string, q *QueryOptions) (*Namespace, *QueryMeta, error)

Info is used to query a single namespace by its name.

func (*Namespaces) List

func (n *Namespaces) List(q *QueryOptions) ([]*Namespace, *QueryMeta, error)

List is used to dump all of the namespaces.

func (*Namespaces) PrefixList

func (n *Namespaces) PrefixList(prefix string, q *QueryOptions) ([]*Namespace, *QueryMeta, error)

PrefixList is used to do a PrefixList search over namespaces

func (*Namespaces) Register

func (n *Namespaces) Register(namespace *Namespace, q *WriteOptions) (*WriteMeta, error)

Register is used to register a namespace.

type NetworkResource

type NetworkResource struct {
	Mode          string     `hcl:"mode,optional"`
	Device        string     `hcl:"device,optional"`
	CIDR          string     `hcl:"cidr,optional"`
	IP            string     `hcl:"ip,optional"`
	DNS           *DNSConfig `hcl:"dns,block"`
	ReservedPorts []Port     `hcl:"reserved_ports,block"`
	DynamicPorts  []Port     `hcl:"port,block"`
	Hostname      string     `hcl:"hostname,optional"`

	// COMPAT(0.13)
	// XXX Deprecated. Please do not use. The field will be removed in Nomad
	// 0.13 and is only being kept to allow any references to be removed before
	// then.
	MBits *int `hcl:"mbits,optional"`
}

NetworkResource is used to describe required network resources of a given task.

func (*NetworkResource) Canonicalize

func (n *NetworkResource) Canonicalize()

func (*NetworkResource) HasPorts

func (n *NetworkResource) HasPorts() bool

func (*NetworkResource) Megabits

func (n *NetworkResource) Megabits() int

COMPAT(0.13) XXX Deprecated. Please do not use. The method will be removed in Nomad 0.13 and is only being kept to allow any references to be removed before then.

type Node

type Node struct {
	ID                    string
	Datacenter            string
	Name                  string
	HTTPAddr              string
	TLSEnabled            bool
	Attributes            map[string]string
	Resources             *Resources
	Reserved              *Resources
	NodeResources         *NodeResources
	ReservedResources     *NodeReservedResources
	Links                 map[string]string
	Meta                  map[string]string
	NodeClass             string
	Drain                 bool
	DrainStrategy         *DrainStrategy
	SchedulingEligibility string
	Status                string
	StatusDescription     string
	StatusUpdatedAt       int64
	Events                []*NodeEvent
	Drivers               map[string]*DriverInfo
	HostVolumes           map[string]*HostVolumeInfo
	HostNetworks          map[string]*HostNetworkInfo
	CSIControllerPlugins  map[string]*CSIInfo
	CSINodePlugins        map[string]*CSIInfo
	LastDrain             *DrainMetadata
	CreateIndex           uint64
	ModifyIndex           uint64
}

Node is used to deserialize a node entry.

type NodeCpuResources

type NodeCpuResources struct {
	CpuShares          int64
	TotalCpuCores      uint16
	ReservableCpuCores []uint16
}

type NodeDevice

type NodeDevice struct {
	// ID is the ID of the device.
	ID string

	// Healthy captures whether the device is healthy.
	Healthy bool

	// HealthDescription is used to provide a human readable description of why
	// the device may be unhealthy.
	HealthDescription string

	// Locality stores HW locality information for the node to optionally be
	// used when making placement decisions.
	Locality *NodeDeviceLocality
}

NodeDevice is an instance of a particular device.

type NodeDeviceLocality

type NodeDeviceLocality struct {
	// PciBusID is the PCI Bus ID for the device.
	PciBusID string
}

NodeDeviceLocality stores information about the devices hardware locality on the node.

type NodeDeviceResource

type NodeDeviceResource struct {

	// Vendor specifies the vendor of device
	Vendor string

	// Type specifies the type of the device
	Type string

	// Name specifies the specific model of the device
	Name string

	// Instances are list of the devices matching the vendor/type/name
	Instances []*NodeDevice

	Attributes map[string]*Attribute
}

NodeDeviceResource captures a set of devices sharing a common vendor/type/device_name tuple.

func (NodeDeviceResource) ID

func (r NodeDeviceResource) ID() string

type NodeDiskResources

type NodeDiskResources struct {
	DiskMB int64
}

type NodeDrainUpdateResponse

type NodeDrainUpdateResponse struct {
	NodeModifyIndex uint64
	EvalIDs         []string
	EvalCreateIndex uint64
	WriteMeta
}

NodeDrainUpdateResponse is used to respond to a node drain update

type NodeEligibilityUpdateResponse

type NodeEligibilityUpdateResponse struct {
	NodeModifyIndex uint64
	EvalIDs         []string
	EvalCreateIndex uint64
	WriteMeta
}

NodeEligibilityUpdateResponse is used to respond to a node eligibility update

type NodeEvent

type NodeEvent struct {
	Message     string
	Subsystem   string
	Details     map[string]string
	Timestamp   time.Time
	CreateIndex uint64
}

NodeEvent is a single unit representing a node’s state change

type NodeIndexSort

type NodeIndexSort []*NodeListStub

NodeIndexSort reverse sorts nodes by CreateIndex

func (NodeIndexSort) Len

func (n NodeIndexSort) Len() int

func (NodeIndexSort) Less

func (n NodeIndexSort) Less(i, j int) bool

func (NodeIndexSort) Swap

func (n NodeIndexSort) Swap(i, j int)

type NodeListStub

type NodeListStub struct {
	Address               string
	ID                    string
	Datacenter            string
	Name                  string
	NodeClass             string
	Version               string
	Drain                 bool
	SchedulingEligibility string
	Status                string
	StatusDescription     string
	Drivers               map[string]*DriverInfo
	NodeResources         *NodeResources         `json:",omitempty"`
	ReservedResources     *NodeReservedResources `json:",omitempty"`
	LastDrain             *DrainMetadata
	CreateIndex           uint64
	ModifyIndex           uint64
}

NodeListStub is a subset of information returned during node list operations.

type NodeMemoryResources

type NodeMemoryResources struct {
	MemoryMB int64
}

type NodePurgeResponse

type NodePurgeResponse struct {
	EvalIDs         []string
	EvalCreateIndex uint64
	NodeModifyIndex uint64
}

NodePurgeResponse is used to deserialize a Purge response.

type NodeReservedCpuResources

type NodeReservedCpuResources struct {
	CpuShares uint64
}

type NodeReservedDiskResources

type NodeReservedDiskResources struct {
	DiskMB uint64
}

type NodeReservedMemoryResources

type NodeReservedMemoryResources struct {
	MemoryMB uint64
}

type NodeReservedNetworkResources

type NodeReservedNetworkResources struct {
	ReservedHostPorts string
}

type NodeResources

type NodeResources struct {
	Cpu      NodeCpuResources
	Memory   NodeMemoryResources
	Disk     NodeDiskResources
	Networks []*NetworkResource
	Devices  []*NodeDeviceResource

	MinDynamicPort int
	MaxDynamicPort int
}

type NodeScoreMeta

type NodeScoreMeta struct {
	NodeID    string
	Scores    map[string]float64
	NormScore float64
}

NodeScoreMeta is used to serialize node scoring metadata displayed in the CLI during verbose mode

type NodeUpdateDrainRequest

type NodeUpdateDrainRequest struct {
	// NodeID is the node to update the drain specification for.
	NodeID string

	// DrainSpec is the drain specification to set for the node. A nil DrainSpec
	// will disable draining.
	DrainSpec *DrainSpec

	// MarkEligible marks the node as eligible for scheduling if removing
	// the drain strategy.
	MarkEligible bool

	// Meta allows operators to specify metadata related to the drain operation
	Meta map[string]string
}

NodeUpdateDrainRequest is used to update the drain specification for a node.

type NodeUpdateEligibilityRequest

type NodeUpdateEligibilityRequest struct {
	// NodeID is the node to update the drain specification for.
	NodeID      string
	Eligibility string
}

NodeUpdateEligibilityRequest is used to update the drain specification for a node.

type Nodes

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

Nodes is used to query node-related API endpoints

func (*Nodes) Allocations

func (n *Nodes) Allocations(nodeID string, q *QueryOptions) ([]*Allocation, *QueryMeta, error)

Allocations is used to return the allocations associated with a node.

func (*Nodes) CSIVolumes

func (n *Nodes) CSIVolumes(nodeID string, q *QueryOptions) ([]*CSIVolumeListStub, error)

func (*Nodes) ForceEvaluate

func (n *Nodes) ForceEvaluate(nodeID string, q *WriteOptions) (string, *WriteMeta, error)

ForceEvaluate is used to force-evaluate an existing node.

func (*Nodes) GC

func (n *Nodes) GC(nodeID string, q *QueryOptions) error

func (*Nodes) GcAlloc

func (n *Nodes) GcAlloc(allocID string, q *QueryOptions) error

TODO Add tests

func (*Nodes) Info

func (n *Nodes) Info(nodeID string, q *QueryOptions) (*Node, *QueryMeta, error)

Info is used to query a specific node by its ID.

func (*Nodes) List

func (n *Nodes) List(q *QueryOptions) ([]*NodeListStub, *QueryMeta, error)

List is used to list out all of the nodes

func (*Nodes) MonitorDrain

func (n *Nodes) MonitorDrain(ctx context.Context, nodeID string, index uint64, ignoreSys bool) <-chan *MonitorMessage

MonitorDrain emits drain related events on the returned string channel. The channel will be closed when all allocations on the draining node have stopped, when an error occurs, or if the context is canceled.

func (*Nodes) PrefixList

func (n *Nodes) PrefixList(prefix string) ([]*NodeListStub, *QueryMeta, error)

func (*Nodes) PrefixListOpts

func (n *Nodes) PrefixListOpts(prefix string, opts *QueryOptions) ([]*NodeListStub, *QueryMeta, error)

func (*Nodes) Purge

func (n *Nodes) Purge(nodeID string, q *QueryOptions) (*NodePurgeResponse, *QueryMeta, error)

Purge removes a node from the system. Nodes can still re-join the cluster if they are alive.

func (*Nodes) Stats

func (n *Nodes) Stats(nodeID string, q *QueryOptions) (*HostStats, error)

func (*Nodes) ToggleEligibility

func (n *Nodes) ToggleEligibility(nodeID string, eligible bool, q *WriteOptions) (*NodeEligibilityUpdateResponse, error)

ToggleEligibility is used to update the scheduling eligibility of the node

func (*Nodes) UpdateDrain

func (n *Nodes) UpdateDrain(nodeID string, spec *DrainSpec, markEligible bool, q *WriteOptions) (*NodeDrainUpdateResponse, error)

UpdateDrain is used to update the drain strategy for a given node. If markEligible is true and the drain is being removed, the node will be marked as having its scheduling being eligible

func (*Nodes) UpdateDrainOpts

func (n *Nodes) UpdateDrainOpts(nodeID string, opts *DrainOptions, q *WriteOptions) (*NodeDrainUpdateResponse,
	error)

UpdateDrainWithMeta is used to update the drain strategy for a given node. If markEligible is true and the drain is being removed, the node will be marked as having its scheduling being eligible

type ObjectDiff

type ObjectDiff struct {
	Type    string
	Name    string
	Fields  []*FieldDiff
	Objects []*ObjectDiff
}

type OneTimeToken

type OneTimeToken struct {
	OneTimeSecretID string
	AccessorID      string
	ExpiresAt       time.Time
	CreateIndex     uint64
	ModifyIndex     uint64
}

type OneTimeTokenExchangeRequest

type OneTimeTokenExchangeRequest struct {
	OneTimeSecretID string
}

type OneTimeTokenExchangeResponse

type OneTimeTokenExchangeResponse struct {
	Token *ACLToken
}

type OneTimeTokenUpsertResponse

type OneTimeTokenUpsertResponse struct {
	OneTimeToken *OneTimeToken
}

type Operator

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

Operator can be used to perform low-level operator tasks for Nomad.

func (*Operator) ApplyLicense

func (op *Operator) ApplyLicense(license string, opts *ApplyLicenseOptions, q *WriteOptions) (*WriteMeta, error)

func (*Operator) AutopilotCASConfiguration

func (op *Operator) AutopilotCASConfiguration(conf *AutopilotConfiguration, q *WriteOptions) (bool, *WriteMeta, error)

AutopilotCASConfiguration is used to perform a Check-And-Set update on the Autopilot configuration. The ModifyIndex value will be respected. Returns true on success or false on failures.

func (*Operator) AutopilotGetConfiguration

func (op *Operator) AutopilotGetConfiguration(q *QueryOptions) (*AutopilotConfiguration, *QueryMeta, error)

AutopilotGetConfiguration is used to query the current Autopilot configuration.

func (*Operator) AutopilotServerHealth

func (op *Operator) AutopilotServerHealth(q *QueryOptions) (*OperatorHealthReply, *QueryMeta, error)

AutopilotServerHealth is used to query Autopilot's top-level view of the health of each Nomad server.

func (*Operator) AutopilotSetConfiguration

func (op *Operator) AutopilotSetConfiguration(conf *AutopilotConfiguration, q *WriteOptions) (*WriteMeta, error)

AutopilotSetConfiguration is used to set the current Autopilot configuration.

func (*Operator) LicenseGet

func (op *Operator) LicenseGet(q *QueryOptions) (*LicenseReply, *QueryMeta, error)

func (*Operator) LicensePut

func (op *Operator) LicensePut(license string, q *WriteOptions) (*WriteMeta, error)

func (*Operator) Metrics

func (op *Operator) Metrics(q *QueryOptions) ([]byte, error)

Metrics returns a slice of bytes containing metrics, optionally formatted as either json or prometheus

func (*Operator) MetricsSummary

func (op *Operator) MetricsSummary(q *QueryOptions) (*MetricsSummary, *QueryMeta, error)

MetricsSummary returns a MetricsSummary struct and query metadata

func (*Operator) RaftGetConfiguration

func (op *Operator) RaftGetConfiguration(q *QueryOptions) (*RaftConfiguration, error)

RaftGetConfiguration is used to query the current Raft peer set.

func (*Operator) RaftRemovePeerByAddress

func (op *Operator) RaftRemovePeerByAddress(address string, q *WriteOptions) error

RaftRemovePeerByAddress is used to kick a stale peer (one that it in the Raft quorum but no longer known to Serf or the catalog) by address in the form of "IP:port".

func (*Operator) RaftRemovePeerByID

func (op *Operator) RaftRemovePeerByID(id string, q *WriteOptions) error

RaftRemovePeerByID is used to kick a stale peer (one that is in the Raft quorum but no longer known to Serf or the catalog) by ID.

func (*Operator) SchedulerCASConfiguration

func (op *Operator) SchedulerCASConfiguration(conf *SchedulerConfiguration, q *WriteOptions) (*SchedulerSetConfigurationResponse, *WriteMeta, error)

SchedulerCASConfiguration is used to perform a Check-And-Set update on the Scheduler configuration. The ModifyIndex value will be respected. Returns true on success or false on failures.

func (*Operator) SchedulerGetConfiguration

func (op *Operator) SchedulerGetConfiguration(q *QueryOptions) (*SchedulerConfigurationResponse, *QueryMeta, error)

SchedulerGetConfiguration is used to query the current Scheduler configuration.

func (*Operator) SchedulerSetConfiguration

func (op *Operator) SchedulerSetConfiguration(conf *SchedulerConfiguration, q *WriteOptions) (*SchedulerSetConfigurationResponse, *WriteMeta, error)

SchedulerSetConfiguration is used to set the current Scheduler configuration.

func (*Operator) Snapshot

func (op *Operator) Snapshot(q *QueryOptions) (io.ReadCloser, error)

Snapshot is used to capture a snapshot state of a running cluster. The returned reader that must be consumed fully

func (*Operator) SnapshotRestore

func (op *Operator) SnapshotRestore(in io.Reader, q *WriteOptions) (*WriteMeta, error)

SnapshotRestore is used to restore a running nomad cluster to an original state.

type OperatorHealthReply

type OperatorHealthReply struct {
	// Healthy is true if all the servers in the cluster are healthy.
	Healthy bool

	// FailureTolerance is the number of healthy servers that could be lost without
	// an outage occurring.
	FailureTolerance int

	// Servers holds the health of each server.
	Servers []ServerHealth
}

OperatorHealthReply is a representation of the overall health of the cluster

type ParameterizedJobConfig

type ParameterizedJobConfig struct {
	Payload      string   `hcl:"payload,optional"`
	MetaRequired []string `mapstructure:"meta_required" hcl:"meta_required,optional"`
	MetaOptional []string `mapstructure:"meta_optional" hcl:"meta_optional,optional"`
}

ParameterizedJobConfig is used to configure the parameterized job.

type PeriodicConfig

type PeriodicConfig struct {
	Enabled         *bool   `hcl:"enabled,optional"`
	Spec            *string `hcl:"cron,optional"`
	SpecType        *string
	ProhibitOverlap *bool   `mapstructure:"prohibit_overlap" hcl:"prohibit_overlap,optional"`
	TimeZone        *string `mapstructure:"time_zone" hcl:"time_zone,optional"`
}

PeriodicConfig is for serializing periodic config for a job.

func (*PeriodicConfig) Canonicalize

func (p *PeriodicConfig) Canonicalize()

func (*PeriodicConfig) GetLocation

func (p *PeriodicConfig) GetLocation() (*time.Location, error)

func (*PeriodicConfig) Next

func (p *PeriodicConfig) Next(fromTime time.Time) (time.Time, error)

Next returns the closest time instant matching the spec that is after the passed time. If no matching instance exists, the zero value of time.Time is returned. The `time.Location` of the returned value matches that of the passed time.

type PlanAnnotations

type PlanAnnotations struct {
	DesiredTGUpdates map[string]*DesiredUpdates
	PreemptedAllocs  []*AllocationListStub
}

type PlanOptions

type PlanOptions struct {
	Diff           bool
	PolicyOverride bool
}

PlanOptions is used to pass through job planning parameters

type PointValue

type PointValue struct {
	Name   string
	Points []float32
}

type Port

type Port struct {
	Label       string `hcl:",label"`
	Value       int    `mapstructure:"static" hcl:"static,optional"`
	To          int    `mapstructure:"to" hcl:"to,optional"`
	HostNetwork string `mapstructure:"host_network" hcl:"host_network,optional"`
}

type PortMapping

type PortMapping struct {
	Label  string
	Value  int
	To     int
	HostIP string
}

type PprofOptions

type PprofOptions struct {
	// ServerID is the server ID, name, or special value "leader" to
	// specify the server that a given profile should be run on.
	ServerID string

	// NodeID is the node ID that a given profile should be run on.
	NodeID string

	// Seconds specifies the amount of time a profile should be run for.
	// Seconds only applies for certain runtime profiles like CPU and Trace.
	Seconds int

	// GC determines if a runtime.GC() should be called before a heap
	// profile.
	GC int

	// Debug specifies if the output of a lookup profile should be returned
	// in human readable format instead of binary.
	Debug int
}

PprofOptions contain a set of parameters for profiling a node or server.

type PreemptionConfig

type PreemptionConfig struct {
	SystemSchedulerEnabled   bool
	SysBatchSchedulerEnabled bool
	BatchSchedulerEnabled    bool
	ServiceSchedulerEnabled  bool
}

PreemptionConfig specifies whether preemption is enabled based on scheduler type

type QueryMeta

type QueryMeta struct {
	// LastIndex. This can be used as a WaitIndex to perform
	// a blocking query
	LastIndex uint64

	// Time of last contact from the leader for the
	// server servicing the request
	LastContact time.Duration

	// Is there a known leader
	KnownLeader bool

	// How long did the request take
	RequestTime time.Duration

	// NextToken is the token used to indicate where to start paging
	// for queries that support paginated lists. To resume paging from
	// this point, pass this token in the next request's QueryOptions
	NextToken string
}

QueryMeta is used to return meta data about a query

type QueryOptions

type QueryOptions struct {
	// Providing a datacenter overwrites the region provided
	// by the Config
	Region string

	// Namespace is the target namespace for the query.
	Namespace string

	// AllowStale allows any Nomad server (non-leader) to service
	// a read. This allows for lower latency and higher throughput
	AllowStale bool

	// WaitIndex is used to enable a blocking query. Waits
	// until the timeout or the next index is reached
	WaitIndex uint64

	// WaitTime is used to bound the duration of a wait.
	// Defaults to that of the Config, but can be overridden.
	WaitTime time.Duration

	// If set, used as prefix for resource list searches
	Prefix string

	// Set HTTP parameters on the query.
	Params map[string]string

	// Set HTTP headers on the query.
	Headers map[string]string

	// AuthToken is the secret ID of an ACL token
	AuthToken string

	// Filter specifies the go-bexpr filter expression to be used for
	// filtering the data prior to returning a response
	Filter string

	// PerPage is the number of entries to be returned in queries that support
	// paginated lists.
	PerPage int32

	// NextToken is the token used to indicate where to start paging
	// for queries that support paginated lists. This token should be
	// the ID of the next object after the last one seen in the
	// previous response.
	NextToken string

	// Reverse is used to reverse the default order of list results.
	//
	// Currently only supported by specific endpoints.
	Reverse bool
	// contains filtered or unexported fields
}

QueryOptions are used to parametrize a query

func (*QueryOptions) Context

func (o *QueryOptions) Context() context.Context

Context returns the context used for canceling HTTP requests related to this query

func (*QueryOptions) SetHeadersFromCSISecrets

func (q *QueryOptions) SetHeadersFromCSISecrets(secrets CSISecrets)

func (*QueryOptions) WithContext

func (o *QueryOptions) WithContext(ctx context.Context) *QueryOptions

WithContext creates a copy of the query options using the provided context to cancel related HTTP requests

type QuotaLimit

type QuotaLimit struct {
	// Region is the region in which this limit has affect
	Region string

	// RegionLimit is the quota limit that applies to any allocation within a
	// referencing namespace in the region. A value of zero is treated as
	// unlimited and a negative value is treated as fully disallowed. This is
	// useful for once we support GPUs
	RegionLimit *Resources

	// Hash is the hash of the object and is used to make replication efficient.
	Hash []byte
}

QuotaLimit describes the resource limit in a particular region.

type QuotaLimitSort

type QuotaLimitSort []*QuotaLimit

QuotaLimitSort is a wrapper to sort QuotaLimits

func (QuotaLimitSort) Len

func (q QuotaLimitSort) Len() int

func (QuotaLimitSort) Less

func (q QuotaLimitSort) Less(i, j int) bool

func (QuotaLimitSort) Swap

func (q QuotaLimitSort) Swap(i, j int)

type QuotaSpec

type QuotaSpec struct {
	// Name is the name for the quota object
	Name string

	// Description is an optional description for the quota object
	Description string

	// Limits is the set of quota limits encapsulated by this quota object. Each
	// limit applies quota in a particular region and in the future over a
	// particular priority range and datacenter set.
	Limits []*QuotaLimit

	// Raft indexes to track creation and modification
	CreateIndex uint64
	ModifyIndex uint64
}

QuotaSpec specifies the allowed resource usage across regions.

type QuotaSpecIndexSort

type QuotaSpecIndexSort []*QuotaSpec

QuotaSpecIndexSort is a wrapper to sort QuotaSpecs by CreateIndex. We reverse the test so that we get the highest index first.

func (QuotaSpecIndexSort) Len

func (q QuotaSpecIndexSort) Len() int

func (QuotaSpecIndexSort) Less

func (q QuotaSpecIndexSort) Less(i, j int) bool

func (QuotaSpecIndexSort) Swap

func (q QuotaSpecIndexSort) Swap(i, j int)

type QuotaUsage

type QuotaUsage struct {
	Name        string
	Used        map[string]*QuotaLimit
	CreateIndex uint64
	ModifyIndex uint64
}

QuotaUsage is the resource usage of a Quota

type QuotaUsageIndexSort

type QuotaUsageIndexSort []*QuotaUsage

QuotaUsageIndexSort is a wrapper to sort QuotaUsages by CreateIndex. We reverse the test so that we get the highest index first.

func (QuotaUsageIndexSort) Len

func (q QuotaUsageIndexSort) Len() int

func (QuotaUsageIndexSort) Less

func (q QuotaUsageIndexSort) Less(i, j int) bool

func (QuotaUsageIndexSort) Swap

func (q QuotaUsageIndexSort) Swap(i, j int)

type Quotas

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

Quotas is used to query the quotas endpoints.

func (*Quotas) Delete

func (q *Quotas) Delete(quota string, qo *WriteOptions) (*WriteMeta, error)

Delete is used to delete a quota spec

func (*Quotas) Info

func (q *Quotas) Info(name string, qo *QueryOptions) (*QuotaSpec, *QueryMeta, error)

Info is used to query a single quota spec by its name.

func (*Quotas) List

func (q *Quotas) List(qo *QueryOptions) ([]*QuotaSpec, *QueryMeta, error)

List is used to dump all of the quota specs

func (*Quotas) ListUsage

func (q *Quotas) ListUsage(qo *QueryOptions) ([]*QuotaUsage, *QueryMeta, error)

ListUsage is used to dump all of the quota usages

func (*Quotas) PrefixList

func (q *Quotas) PrefixList(prefix string, qo *QueryOptions) ([]*QuotaSpec, *QueryMeta, error)

PrefixList is used to do a PrefixList search over quota specs

func (*Quotas) PrefixListUsage

func (q *Quotas) PrefixListUsage(prefix string, qo *QueryOptions) ([]*QuotaUsage, *QueryMeta, error)

PrefixList is used to do a PrefixList search over quota usages

func (*Quotas) Register

func (q *Quotas) Register(spec *QuotaSpec, qo *WriteOptions) (*WriteMeta, error)

Register is used to register a quota spec.

func (*Quotas) Usage

func (q *Quotas) Usage(name string, qo *QueryOptions) (*QuotaUsage, *QueryMeta, error)

Usage is used to query a single quota usage by its name.

type RaftConfiguration

type RaftConfiguration struct {
	// Servers has the list of servers in the Raft configuration.
	Servers []*RaftServer

	// Index has the Raft index of this configuration.
	Index uint64
}

RaftConfiguration is returned when querying for the current Raft configuration.

type RaftServer

type RaftServer struct {
	// ID is the unique ID for the server. These are currently the same
	// as the address, but they will be changed to a real GUID in a future
	// release of Nomad.
	ID string

	// Node is the node name of the server, as known by Nomad, or this
	// will be set to "(unknown)" otherwise.
	Node string

	// Address is the IP:port of the server, used for Raft communications.
	Address string

	// Leader is true if this server is the current cluster leader.
	Leader bool

	// Voter is true if this server has a vote in the cluster. This might
	// be false if the server is staging and still coming online, or if
	// it's a non-voting server, which will be added in a future release of
	// Nomad.
	Voter bool

	// RaftProtocol is the version of the Raft protocol spoken by this server.
	RaftProtocol string
}

RaftServer has information about a server in the Raft configuration.

type Raw

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

Raw can be used to do raw queries against custom endpoints

func (*Raw) Delete

func (raw *Raw) Delete(endpoint string, out interface{}, q *WriteOptions) (*WriteMeta, error)

Delete is used to do a DELETE request against an endpoint and serialize/deserialized using the standard Nomad conventions.

func (*Raw) Query

func (raw *Raw) Query(endpoint string, out interface{}, q *QueryOptions) (*QueryMeta, error)

Query is used to do a GET request against an endpoint and deserialize the response into an interface using standard Nomad conventions.

func (*Raw) Response

func (raw *Raw) Response(endpoint string, q *QueryOptions) (io.ReadCloser, error)

Response is used to make a GET request against an endpoint and returns the response body

func (*Raw) Write

func (raw *Raw) Write(endpoint string, in, out interface{}, q *WriteOptions) (*WriteMeta, error)

Write is used to do a PUT request against an endpoint and serialize/deserialized using the standard Nomad conventions.

type Recommendation

type Recommendation struct {
	ID             string
	Region         string
	Namespace      string
	JobID          string
	JobVersion     uint64
	Group          string
	Task           string
	Resource       string
	Value          int
	Current        int
	Meta           map[string]interface{}
	Stats          map[string]float64
	EnforceVersion bool

	SubmitTime int64

	CreateIndex uint64
	ModifyIndex uint64
}

Recommendation is used to serialize a recommendation.

type RecommendationApplyRequest

type RecommendationApplyRequest struct {
	Apply          []string
	Dismiss        []string
	PolicyOverride bool
}

RecommendationApplyRequest is used to apply and/or dismiss a set of recommendations

type RecommendationApplyResponse

type RecommendationApplyResponse struct {
	UpdatedJobs []*SingleRecommendationApplyResult
	Errors      []*SingleRecommendationApplyError
	WriteMeta
}

RecommendationApplyResponse is used to apply a set of recommendations

type Recommendations

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

Recommendations is used to query the recommendations endpoints.

func (*Recommendations) Apply

func (r *Recommendations) Apply(ids []string, policyOverride bool) (
	*RecommendationApplyResponse, *WriteMeta, error)

Apply is used to apply a set of recommendations

func (*Recommendations) Delete

func (r *Recommendations) Delete(ids []string, q *WriteOptions) (*WriteMeta, error)

Delete is used to delete a list of recommendations

func (*Recommendations) Info

Info is used to return information on a single recommendation

func (*Recommendations) List

List is used to dump all of the recommendations in the cluster

func (*Recommendations) Upsert

Upsert is used to create or update a recommendation

type Regions

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

Regions is used to query the regions in the cluster.

func (*Regions) List

func (r *Regions) List() ([]string, error)

List returns a list of all of the regions from the server that serves the request. It is never forwarded to a leader.

type RegisterOptions

type RegisterOptions struct {
	EnforceIndex   bool
	ModifyIndex    uint64
	PolicyOverride bool
	PreserveCounts bool
	EvalPriority   int
}

RegisterOptions is used to pass through job registration parameters

type RequestedDevice

type RequestedDevice struct {
	// Name is the request name. The possible values are as follows:
	// * <type>: A single value only specifies the type of request.
	// * <vendor>/<type>: A single slash delimiter assumes the vendor and type of device is specified.
	// * <vendor>/<type>/<name>: Two slash delimiters assume vendor, type and specific model are specified.
	//
	// Examples are as follows:
	// * "gpu"
	// * "nvidia/gpu"
	// * "nvidia/gpu/GTX2080Ti"
	Name string `hcl:",label"`

	// Count is the number of requested devices
	Count *uint64 `hcl:"count,optional"`

	// Constraints are a set of constraints to apply when selecting the device
	// to use.
	Constraints []*Constraint `hcl:"constraint,block"`

	// Affinities are a set of affinites to apply when selecting the device
	// to use.
	Affinities []*Affinity `hcl:"affinity,block"`
}

RequestedDevice is used to request a device for a task.

func (*RequestedDevice) Canonicalize

func (d *RequestedDevice) Canonicalize()

type RescheduleEvent

type RescheduleEvent struct {
	// RescheduleTime is the timestamp of a reschedule attempt
	RescheduleTime int64

	// PrevAllocID is the ID of the previous allocation being restarted
	PrevAllocID string

	// PrevNodeID is the node ID of the previous allocation
	PrevNodeID string
}

RescheduleEvent is used to keep track of previous attempts at rescheduling an allocation

type ReschedulePolicy

type ReschedulePolicy struct {
	// Attempts limits the number of rescheduling attempts that can occur in an interval.
	Attempts *int `mapstructure:"attempts" hcl:"attempts,optional"`

	// Interval is a duration in which we can limit the number of reschedule attempts.
	Interval *time.Duration `mapstructure:"interval" hcl:"interval,optional"`

	// Delay is a minimum duration to wait between reschedule attempts.
	// The delay function determines how much subsequent reschedule attempts are delayed by.
	Delay *time.Duration `mapstructure:"delay" hcl:"delay,optional"`

	// DelayFunction determines how the delay progressively changes on subsequent reschedule
	// attempts. Valid values are "exponential", "constant", and "fibonacci".
	DelayFunction *string `mapstructure:"delay_function" hcl:"delay_function,optional"`

	// MaxDelay is an upper bound on the delay.
	MaxDelay *time.Duration `mapstructure:"max_delay" hcl:"max_delay,optional"`

	// Unlimited allows rescheduling attempts until they succeed
	Unlimited *bool `mapstructure:"unlimited" hcl:"unlimited,optional"`
}

Reschedule configures how Tasks are rescheduled when they crash or fail.

func NewDefaultReschedulePolicy

func NewDefaultReschedulePolicy(jobType string) *ReschedulePolicy

func (*ReschedulePolicy) Canonicalize

func (r *ReschedulePolicy) Canonicalize(jobType string)

func (*ReschedulePolicy) Copy

func (*ReschedulePolicy) Merge

func (r *ReschedulePolicy) Merge(rp *ReschedulePolicy)

func (*ReschedulePolicy) String

func (p *ReschedulePolicy) String() string

type RescheduleTracker

type RescheduleTracker struct {
	Events []*RescheduleEvent
}

RescheduleTracker encapsulates previous reschedule events

type ResourceUsage

type ResourceUsage struct {
	MemoryStats *MemoryStats
	CpuStats    *CpuStats
	DeviceStats []*DeviceGroupStats
}

ResourceUsage holds information related to cpu and memory stats

type Resources

type Resources struct {
	CPU         *int               `hcl:"cpu,optional"`
	Cores       *int               `hcl:"cores,optional"`
	MemoryMB    *int               `mapstructure:"memory" hcl:"memory,optional"`
	MemoryMaxMB *int               `mapstructure:"memory_max" hcl:"memory_max,optional"`
	DiskMB      *int               `mapstructure:"disk" hcl:"disk,optional"`
	Networks    []*NetworkResource `hcl:"network,block"`
	Devices     []*RequestedDevice `hcl:"device,block"`

	// COMPAT(0.10)
	// XXX Deprecated. Please do not use. The field will be removed in Nomad
	// 0.10 and is only being kept to allow any references to be removed before
	// then.
	IOPS *int `hcl:"iops,optional"`
}

Resources encapsulates the required resources of a given task or task group.

func DefaultResources

func DefaultResources() *Resources

DefaultResources is a small resources object that contains the default resources requests that we will provide to an object. --- THIS FUNCTION IS REPLICATED IN nomad/structs/structs.go and should be kept in sync.

func MinResources

func MinResources() *Resources

MinResources is a small resources object that contains the absolute minimum resources that we will provide to an object. This should not be confused with the defaults which are provided in DefaultResources() --- THIS LOGIC IS REPLICATED IN nomad/structs/structs.go and should be kept in sync.

func (*Resources) Canonicalize

func (r *Resources) Canonicalize()

Canonicalize will supply missing values in the cases where they are not provided.

func (*Resources) Merge

func (r *Resources) Merge(other *Resources)

Merge merges this resource with another resource.

type RestartPolicy

type RestartPolicy struct {
	Interval *time.Duration `hcl:"interval,optional"`
	Attempts *int           `hcl:"attempts,optional"`
	Delay    *time.Duration `hcl:"delay,optional"`
	Mode     *string        `hcl:"mode,optional"`
}

RestartPolicy defines how the Nomad client restarts tasks in a taskgroup when they fail

func (*RestartPolicy) Merge

func (r *RestartPolicy) Merge(rp *RestartPolicy)

type SampledValue

type SampledValue struct {
	Name string
	Hash string `json:"-"`
	*AggregateSample
	Mean   float64
	Stddev float64

	Labels        []Label           `json:"-"`
	DisplayLabels map[string]string `json:"Labels"`
}

type Scaling

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

Scaling is used to query scaling-related API endpoints

func (*Scaling) GetPolicy

func (s *Scaling) GetPolicy(id string, q *QueryOptions) (*ScalingPolicy, *QueryMeta, error)

func (*Scaling) ListPolicies

func (s *Scaling) ListPolicies(q *QueryOptions) ([]*ScalingPolicyListStub, *QueryMeta, error)

type ScalingEvent

type ScalingEvent struct {
	Count         *int64
	PreviousCount int64
	Error         bool
	Message       string
	Meta          map[string]interface{}
	EvalID        *string
	Time          uint64
	CreateIndex   uint64
}

type ScalingPolicy

type ScalingPolicy struct {
	Min     *int64                 `hcl:"min,optional"`
	Max     *int64                 `hcl:"max,optional"`
	Policy  map[string]interface{} `hcl:"policy,block"`
	Enabled *bool                  `hcl:"enabled,optional"`
	Type    string                 `hcl:"type,optional"`

	ID          string
	Namespace   string
	Target      map[string]string
	CreateIndex uint64
	ModifyIndex uint64
}

ScalingPolicy is the user-specified API object for an autoscaling policy

func (*ScalingPolicy) Canonicalize

func (p *ScalingPolicy) Canonicalize(taskGroupCount int)

type ScalingPolicyListStub

type ScalingPolicyListStub struct {
	ID          string
	Enabled     bool
	Type        string
	Target      map[string]string
	CreateIndex uint64
	ModifyIndex uint64
}

ScalingPolicyListStub is used to return a subset of scaling policy information for the scaling policy list

type ScalingRequest

type ScalingRequest struct {
	Count   *int64
	Target  map[string]string
	Message string
	Error   bool
	Meta    map[string]interface{}
	WriteRequest
	// this is effectively a job update, so we need the ability to override policy.
	PolicyOverride bool
}

ScalingRequest is the payload for a generic scaling action

type SchedulerAlgorithm

type SchedulerAlgorithm string

SchedulerAlgorithm is an enum string that encapsulates the valid options for a SchedulerConfiguration stanza's SchedulerAlgorithm. These modes will allow the scheduler to be user-selectable.

const (
	SchedulerAlgorithmBinpack SchedulerAlgorithm = "binpack"
	SchedulerAlgorithmSpread  SchedulerAlgorithm = "spread"
)

type SchedulerConfiguration

type SchedulerConfiguration struct {
	// SchedulerAlgorithm lets you select between available scheduling algorithms.
	SchedulerAlgorithm SchedulerAlgorithm

	// PreemptionConfig specifies whether to enable eviction of lower
	// priority jobs to place higher priority jobs.
	PreemptionConfig PreemptionConfig

	// MemoryOversubscriptionEnabled specifies whether memory oversubscription is enabled
	MemoryOversubscriptionEnabled bool

	// RejectJobRegistration disables new job registrations except with a
	// management ACL token
	RejectJobRegistration bool

	// CreateIndex/ModifyIndex store the create/modify indexes of this configuration.
	CreateIndex uint64
	ModifyIndex uint64
}

SchedulerConfiguration is the config for controlling scheduler behavior

type SchedulerConfigurationResponse

type SchedulerConfigurationResponse struct {
	// SchedulerConfig contains scheduler config options
	SchedulerConfig *SchedulerConfiguration

	QueryMeta
}

SchedulerConfigurationResponse is the response object that wraps SchedulerConfiguration

type SchedulerSetConfigurationResponse

type SchedulerSetConfigurationResponse struct {
	// Updated returns whether the config was actually updated
	// Only set when the request uses CAS
	Updated bool

	WriteMeta
}

SchedulerSetConfigurationResponse is the response object used when updating scheduler configuration

type SchedulerWorkerPoolArgs

type SchedulerWorkerPoolArgs struct {
	NumSchedulers     int
	EnabledSchedulers []string
}
type Search struct {
	// contains filtered or unexported fields
}

func (*Search) FuzzySearch

func (s *Search) FuzzySearch(text string, context contexts.Context, q *QueryOptions) (*FuzzySearchResponse, *QueryMeta, error)

FuzzySearch returns a set of matches for a given context and string.

func (*Search) PrefixSearch

func (s *Search) PrefixSearch(prefix string, context contexts.Context, q *QueryOptions) (*SearchResponse, *QueryMeta, error)

PrefixSearch returns a set of matches for a particular context and prefix.

type SearchRequest

type SearchRequest struct {
	Prefix  string
	Context contexts.Context
	QueryOptions
}

type SearchResponse

type SearchResponse struct {
	Matches     map[contexts.Context][]string
	Truncations map[contexts.Context]bool
	QueryMeta
}

type SentinelPolicies

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

SentinelPolicies is used to query the Sentinel Policy endpoints.

func (*SentinelPolicies) Delete

func (a *SentinelPolicies) Delete(policyName string, q *WriteOptions) (*WriteMeta, error)

Delete is used to delete a policy

func (*SentinelPolicies) Info

func (a *SentinelPolicies) Info(policyName string, q *QueryOptions) (*SentinelPolicy, *QueryMeta, error)

Info is used to query a specific policy

func (*SentinelPolicies) List

List is used to dump all of the policies.

func (*SentinelPolicies) Upsert

func (a *SentinelPolicies) Upsert(policy *SentinelPolicy, q *WriteOptions) (*WriteMeta, error)

Upsert is used to create or update a policy

type SentinelPolicy

type SentinelPolicy struct {
	Name             string
	Description      string
	Scope            string
	EnforcementLevel string
	Policy           string
	CreateIndex      uint64
	ModifyIndex      uint64
}

type SentinelPolicyListStub

type SentinelPolicyListStub struct {
	Name             string
	Description      string
	Scope            string
	EnforcementLevel string
	CreateIndex      uint64
	ModifyIndex      uint64
}

type ServerHealth

type ServerHealth struct {
	// ID is the raft ID of the server.
	ID string

	// Name is the node name of the server.
	Name string

	// Address is the address of the server.
	Address string

	// The status of the SerfHealth check for the server.
	SerfStatus string

	// Version is the Nomad version of the server.
	Version string

	// Leader is whether this server is currently the leader.
	Leader bool

	// LastContact is the time since this node's last contact with the leader.
	LastContact time.Duration

	// LastTerm is the highest leader term this server has a record of in its Raft log.
	LastTerm uint64

	// LastIndex is the last log index this server has a record of in its Raft log.
	LastIndex uint64

	// Healthy is whether or not the server is healthy according to the current
	// Autopilot config.
	Healthy bool

	// Voter is whether this is a voting server.
	Voter bool

	// StableSince is the last time this server's Healthy value changed.
	StableSince time.Time
}

ServerHealth is the health (from the leader's point of view) of a server.

func (*ServerHealth) MarshalJSON

func (u *ServerHealth) MarshalJSON() ([]byte, error)

func (*ServerHealth) UnmarshalJSON

func (u *ServerHealth) UnmarshalJSON(data []byte) error

type ServerMembers

type ServerMembers struct {
	ServerName   string
	ServerRegion string
	ServerDC     string
	Members      []*AgentMember
}

type Service

type Service struct {
	//FIXME Id is unused. Remove?
	Id                string            `hcl:"id,optional"`
	Name              string            `hcl:"name,optional"`
	Tags              []string          `hcl:"tags,optional"`
	CanaryTags        []string          `mapstructure:"canary_tags" hcl:"canary_tags,optional"`
	EnableTagOverride bool              `mapstructure:"enable_tag_override" hcl:"enable_tag_override,optional"`
	PortLabel         string            `mapstructure:"port" hcl:"port,optional"`
	AddressMode       string            `mapstructure:"address_mode" hcl:"address_mode,optional"`
	Checks            []ServiceCheck    `hcl:"check,block"`
	CheckRestart      *CheckRestart     `mapstructure:"check_restart" hcl:"check_restart,block"`
	Connect           *ConsulConnect    `hcl:"connect,block"`
	Meta              map[string]string `hcl:"meta,block"`
	CanaryMeta        map[string]string `hcl:"canary_meta,block"`
	TaskName          string            `mapstructure:"task" hcl:"task,optional"`
	OnUpdate          string            `mapstructure:"on_update" hcl:"on_update,optional"`
}

Service represents a Consul service definition.

func (*Service) Canonicalize

func (s *Service) Canonicalize(t *Task, tg *TaskGroup, job *Job)

Canonicalize the Service by ensuring its name and address mode are set. Task will be nil for group services.

type ServiceCheck

type ServiceCheck struct {
	//FIXME Id is unused. Remove?
	Id                     string              `hcl:"id,optional"`
	Name                   string              `hcl:"name,optional"`
	Type                   string              `hcl:"type,optional"`
	Command                string              `hcl:"command,optional"`
	Args                   []string            `hcl:"args,optional"`
	Path                   string              `hcl:"path,optional"`
	Protocol               string              `hcl:"protocol,optional"`
	PortLabel              string              `mapstructure:"port" hcl:"port,optional"`
	Expose                 bool                `hcl:"expose,optional"`
	AddressMode            string              `mapstructure:"address_mode" hcl:"address_mode,optional"`
	Interval               time.Duration       `hcl:"interval,optional"`
	Timeout                time.Duration       `hcl:"timeout,optional"`
	InitialStatus          string              `mapstructure:"initial_status" hcl:"initial_status,optional"`
	TLSSkipVerify          bool                `mapstructure:"tls_skip_verify" hcl:"tls_skip_verify,optional"`
	Header                 map[string][]string `hcl:"header,block"`
	Method                 string              `hcl:"method,optional"`
	CheckRestart           *CheckRestart       `mapstructure:"check_restart" hcl:"check_restart,block"`
	GRPCService            string              `mapstructure:"grpc_service" hcl:"grpc_service,optional"`
	GRPCUseTLS             bool                `mapstructure:"grpc_use_tls" hcl:"grpc_use_tls,optional"`
	TaskName               string              `mapstructure:"task" hcl:"task,optional"`
	SuccessBeforePassing   int                 `mapstructure:"success_before_passing" hcl:"success_before_passing,optional"`
	FailuresBeforeCritical int                 `mapstructure:"failures_before_critical" hcl:"failures_before_critical,optional"`
	Body                   string              `hcl:"body,optional"`
	OnUpdate               string              `mapstructure:"on_update" hcl:"on_update,optional"`
}

ServiceCheck represents the consul health check that Nomad registers.

type SidecarTask

type SidecarTask struct {
	Name          string                 `hcl:"name,optional"`
	Driver        string                 `hcl:"driver,optional"`
	User          string                 `hcl:"user,optional"`
	Config        map[string]interface{} `hcl:"config,block"`
	Env           map[string]string      `hcl:"env,block"`
	Resources     *Resources             `hcl:"resources,block"`
	Meta          map[string]string      `hcl:"meta,block"`
	KillTimeout   *time.Duration         `mapstructure:"kill_timeout" hcl:"kill_timeout,optional"`
	LogConfig     *LogConfig             `mapstructure:"logs" hcl:"logs,block"`
	ShutdownDelay *time.Duration         `mapstructure:"shutdown_delay" hcl:"shutdown_delay,optional"`
	KillSignal    string                 `mapstructure:"kill_signal" hcl:"kill_signal,optional"`
}

SidecarTask represents a subset of Task fields that can be set to override the fields of the Task generated for the sidecar

func (*SidecarTask) Canonicalize

func (st *SidecarTask) Canonicalize()

type SingleDeploymentResponse

type SingleDeploymentResponse struct {
	Deployment *Deployment
	QueryMeta
}

SingleDeploymentResponse is used to respond with a single deployment

type SingleRecommendationApplyError

type SingleRecommendationApplyError struct {
	Namespace       string
	JobID           string
	Recommendations []string
	Error           string
}

type SingleRecommendationApplyResult

type SingleRecommendationApplyResult struct {
	Namespace       string
	JobID           string
	JobModifyIndex  uint64
	EvalID          string
	EvalCreateIndex uint64
	Warnings        string
	Recommendations []string
}

type Spread

type Spread struct {
	Attribute    string          `hcl:"attribute,optional"`
	Weight       *int8           `hcl:"weight,optional"`
	SpreadTarget []*SpreadTarget `hcl:"target,block"`
}

Spread is used to serialize task group allocation spread preferences

func NewSpread

func NewSpread(attribute string, weight int8, spreadTargets []*SpreadTarget) *Spread

func (*Spread) Canonicalize

func (s *Spread) Canonicalize()

type SpreadTarget

type SpreadTarget struct {
	Value   string `hcl:",label"`
	Percent uint8  `hcl:"percent,optional"`
}

SpreadTarget is used to serialize target allocation spread percentages

func NewSpreadTarget

func NewSpreadTarget(value string, percent uint8) *SpreadTarget

type StatObject

type StatObject struct {
	// Nested is a mapping of object name to a nested stats object.
	Nested map[string]*StatObject

	// Attributes is a mapping of statistic name to its value.
	Attributes map[string]*StatValue
}

StatObject is a collection of statistics either exposed at the top level or via nested StatObjects.

type StatValue

type StatValue struct {
	// FloatNumeratorVal exposes a floating point value. If denominator is set
	// it is assumed to be a fractional value, otherwise it is a scalar.
	FloatNumeratorVal   *float64 `json:",omitempty"`
	FloatDenominatorVal *float64 `json:",omitempty"`

	// IntNumeratorVal exposes a int value. If denominator is set it is assumed
	// to be a fractional value, otherwise it is a scalar.
	IntNumeratorVal   *int64 `json:",omitempty"`
	IntDenominatorVal *int64 `json:",omitempty"`

	// StringVal exposes a string value. These are likely annotations.
	StringVal *string `json:",omitempty"`

	// BoolVal exposes a boolean statistic.
	BoolVal *bool `json:",omitempty"`

	// Unit gives the unit type: °F, %, MHz, MB, etc.
	Unit string `json:",omitempty"`

	// Desc provides a human readable description of the statistic.
	Desc string `json:",omitempty"`
}

StatValue exposes the values of a particular statistic. The value may be of type float, integer, string or boolean. Numeric types can be exposed as a single value or as a fraction.

func (*StatValue) String

func (v *StatValue) String() string

type Status

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

Status is used to query the status-related endpoints.

func (*Status) Leader

func (s *Status) Leader() (string, error)

Leader is used to query for the current cluster leader.

func (*Status) Peers

func (s *Status) Peers() ([]string, error)

Peers is used to query the addresses of the server peers in the cluster.

func (*Status) RegionLeader

func (s *Status) RegionLeader(region string) (string, error)

RegionLeader is used to query for the leader in the passed region.

type StreamFrame

type StreamFrame struct {
	Offset    int64  `json:",omitempty"`
	Data      []byte `json:",omitempty"`
	File      string `json:",omitempty"`
	FileEvent string `json:",omitempty"`
}

StreamFrame is used to frame data of a file when streaming

func (*StreamFrame) IsHeartbeat

func (s *StreamFrame) IsHeartbeat() bool

IsHeartbeat returns if the frame is a heartbeat frame

type System

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

Status is used to query the status-related endpoints.

func (*System) GarbageCollect

func (s *System) GarbageCollect() error

func (*System) ReconcileSummaries

func (s *System) ReconcileSummaries() error

type TLSConfig

type TLSConfig struct {
	// CACert is the path to a PEM-encoded CA cert file to use to verify the
	// Nomad server SSL certificate.
	CACert string

	// CAPath is the path to a directory of PEM-encoded CA cert files to verify
	// the Nomad server SSL certificate.
	CAPath string

	// CACertPem is the PEM-encoded CA cert to use to verify the Nomad server
	// SSL certificate.
	CACertPEM []byte

	// ClientCert is the path to the certificate for Nomad communication
	ClientCert string

	// ClientCertPEM is the PEM-encoded certificate for Nomad communication
	ClientCertPEM []byte

	// ClientKey is the path to the private key for Nomad communication
	ClientKey string

	// ClientKeyPEM is the PEM-encoded private key for Nomad communication
	ClientKeyPEM []byte

	// TLSServerName, if set, is used to set the SNI host when connecting via
	// TLS.
	TLSServerName string

	// Insecure enables or disables SSL verification
	Insecure bool
}

TLSConfig contains the parameters needed to configure TLS on the HTTP client used to communicate with Nomad.

func (*TLSConfig) Copy

func (t *TLSConfig) Copy() *TLSConfig

type Task

type Task struct {
	Name            string                 `hcl:"name,label"`
	Driver          string                 `hcl:"driver,optional"`
	User            string                 `hcl:"user,optional"`
	Lifecycle       *TaskLifecycle         `hcl:"lifecycle,block"`
	Config          map[string]interface{} `hcl:"config,block"`
	Constraints     []*Constraint          `hcl:"constraint,block"`
	Affinities      []*Affinity            `hcl:"affinity,block"`
	Env             map[string]string      `hcl:"env,block"`
	Services        []*Service             `hcl:"service,block"`
	Resources       *Resources             `hcl:"resources,block"`
	RestartPolicy   *RestartPolicy         `hcl:"restart,block"`
	Meta            map[string]string      `hcl:"meta,block"`
	KillTimeout     *time.Duration         `mapstructure:"kill_timeout" hcl:"kill_timeout,optional"`
	LogConfig       *LogConfig             `mapstructure:"logs" hcl:"logs,block"`
	Artifacts       []*TaskArtifact        `hcl:"artifact,block"`
	Vault           *Vault                 `hcl:"vault,block"`
	Templates       []*Template            `hcl:"template,block"`
	DispatchPayload *DispatchPayloadConfig `hcl:"dispatch_payload,block"`
	VolumeMounts    []*VolumeMount         `hcl:"volume_mount,block"`
	CSIPluginConfig *TaskCSIPluginConfig   `mapstructure:"csi_plugin" json:",omitempty" hcl:"csi_plugin,block"`
	Leader          bool                   `hcl:"leader,optional"`
	ShutdownDelay   time.Duration          `mapstructure:"shutdown_delay" hcl:"shutdown_delay,optional"`
	KillSignal      string                 `mapstructure:"kill_signal" hcl:"kill_signal,optional"`
	Kind            string                 `hcl:"kind,optional"`
	ScalingPolicies []*ScalingPolicy       `hcl:"scaling,block"`
}

Task is a single process in a task group.

func NewTask

func NewTask(name, driver string) *Task

NewTask creates and initializes a new Task.

func (*Task) AddAffinity

func (t *Task) AddAffinity(a *Affinity) *Task

AddAffinity adds a new affinity to a single task.

func (*Task) Canonicalize

func (t *Task) Canonicalize(tg *TaskGroup, job *Job)

func (*Task) Constrain

func (t *Task) Constrain(c *Constraint) *Task

Constraint adds a new constraints to a single task.

func (*Task) Require

func (t *Task) Require(r *Resources) *Task

Require is used to add resource requirements to a task.

func (*Task) SetConfig

func (t *Task) SetConfig(key string, val interface{}) *Task

Configure is used to configure a single k/v pair on the task.

func (*Task) SetLogConfig

func (t *Task) SetLogConfig(l *LogConfig) *Task

SetLogConfig sets a log config to a task

func (*Task) SetMeta

func (t *Task) SetMeta(key, val string) *Task

SetMeta is used to add metadata k/v pairs to the task.

type TaskArtifact

type TaskArtifact struct {
	GetterSource  *string           `mapstructure:"source" hcl:"source,optional"`
	GetterOptions map[string]string `mapstructure:"options" hcl:"options,block"`
	GetterHeaders map[string]string `mapstructure:"headers" hcl:"headers,block"`
	GetterMode    *string           `mapstructure:"mode" hcl:"mode,optional"`
	RelativeDest  *string           `mapstructure:"destination" hcl:"destination,optional"`
}

TaskArtifact is used to download artifacts before running a task.

func (*TaskArtifact) Canonicalize

func (a *TaskArtifact) Canonicalize()

type TaskCSIPluginConfig

type TaskCSIPluginConfig struct {
	// ID is the identifier of the plugin.
	// Ideally this should be the FQDN of the plugin.
	ID string `mapstructure:"id" hcl:"id,optional"`

	// CSIPluginType instructs Nomad on how to handle processing a plugin
	Type CSIPluginType `mapstructure:"type" hcl:"type,optional"`

	// MountDir is the destination that nomad should mount in its CSI
	// directory for the plugin. It will then expect a file called CSISocketName
	// to be created by the plugin, and will provide references into
	// "MountDir/CSIIntermediaryDirname/VolumeName/AllocID for mounts.
	//
	// Default is /csi.
	MountDir string `mapstructure:"mount_dir" hcl:"mount_dir,optional"`
}

TaskCSIPluginConfig contains the data that is required to setup a task as a CSI plugin. This will be used by the csi_plugin_supervisor_hook to configure mounts for the plugin and initiate the connection to the plugin catalog.

func (*TaskCSIPluginConfig) Canonicalize

func (t *TaskCSIPluginConfig) Canonicalize()

type TaskDiff

type TaskDiff struct {
	Type        string
	Name        string
	Fields      []*FieldDiff
	Objects     []*ObjectDiff
	Annotations []string
}

type TaskEvent

type TaskEvent struct {
	Type           string
	Time           int64
	DisplayMessage string
	Details        map[string]string
	Message        string
	// DEPRECATION NOTICE: The following fields are all deprecated. see TaskEvent struct in structs.go for details.
	FailsTask        bool
	RestartReason    string
	SetupError       string
	DriverError      string
	DriverMessage    string
	ExitCode         int
	Signal           int
	KillReason       string
	KillTimeout      time.Duration
	KillError        string
	StartDelay       int64
	DownloadError    string
	ValidationError  string
	DiskLimit        int64
	DiskSize         int64
	FailedSibling    string
	VaultError       string
	TaskSignalReason string
	TaskSignal       string
	GenericSource    string
}

TaskEvent is an event that effects the state of a task and contains meta-data appropriate to the events type.

type TaskGroup

type TaskGroup struct {
	Name                      *string                   `hcl:"name,label"`
	Count                     *int                      `hcl:"count,optional"`
	Constraints               []*Constraint             `hcl:"constraint,block"`
	Affinities                []*Affinity               `hcl:"affinity,block"`
	Tasks                     []*Task                   `hcl:"task,block"`
	Spreads                   []*Spread                 `hcl:"spread,block"`
	Volumes                   map[string]*VolumeRequest `hcl:"volume,block"`
	RestartPolicy             *RestartPolicy            `hcl:"restart,block"`
	ReschedulePolicy          *ReschedulePolicy         `hcl:"reschedule,block"`
	EphemeralDisk             *EphemeralDisk            `hcl:"ephemeral_disk,block"`
	Update                    *UpdateStrategy           `hcl:"update,block"`
	Migrate                   *MigrateStrategy          `hcl:"migrate,block"`
	Networks                  []*NetworkResource        `hcl:"network,block"`
	Meta                      map[string]string         `hcl:"meta,block"`
	Services                  []*Service                `hcl:"service,block"`
	ShutdownDelay             *time.Duration            `mapstructure:"shutdown_delay" hcl:"shutdown_delay,optional"`
	StopAfterClientDisconnect *time.Duration            `mapstructure:"stop_after_client_disconnect" hcl:"stop_after_client_disconnect,optional"`
	Scaling                   *ScalingPolicy            `hcl:"scaling,block"`
	Consul                    *Consul                   `hcl:"consul,block"`
}

TaskGroup is the unit of scheduling.

func NewTaskGroup

func NewTaskGroup(name string, count int) *TaskGroup

NewTaskGroup creates a new TaskGroup.

func (*TaskGroup) AddAffinity

func (g *TaskGroup) AddAffinity(a *Affinity) *TaskGroup

AddAffinity is used to add a new affinity to a task group.

func (*TaskGroup) AddSpread

func (g *TaskGroup) AddSpread(s *Spread) *TaskGroup

AddSpread is used to add a new spread preference to a task group.

func (*TaskGroup) AddTask

func (g *TaskGroup) AddTask(t *Task) *TaskGroup

AddTask is used to add a new task to a task group.

func (*TaskGroup) Canonicalize

func (g *TaskGroup) Canonicalize(job *Job)

Canonicalize sets defaults and merges settings that should be inherited from the job

func (*TaskGroup) Constrain

func (g *TaskGroup) Constrain(c *Constraint) *TaskGroup

Constrain is used to add a constraint to a task group.

func (*TaskGroup) RequireDisk

func (g *TaskGroup) RequireDisk(disk *EphemeralDisk) *TaskGroup

RequireDisk adds a ephemeral disk to the task group

func (*TaskGroup) SetMeta

func (g *TaskGroup) SetMeta(key, val string) *TaskGroup

AddMeta is used to add a meta k/v pair to a task group

type TaskGroupDiff

type TaskGroupDiff struct {
	Type    string
	Name    string
	Fields  []*FieldDiff
	Objects []*ObjectDiff
	Tasks   []*TaskDiff
	Updates map[string]uint64
}

type TaskGroupScaleStatus

type TaskGroupScaleStatus struct {
	Desired   int
	Placed    int
	Running   int
	Healthy   int
	Unhealthy int
	Events    []ScalingEvent
}

type TaskGroupSummary

type TaskGroupSummary struct {
	Queued   int
	Complete int
	Failed   int
	Running  int
	Starting int
	Lost     int
}

TaskGroup summarizes the state of all the allocations of a particular TaskGroup

type TaskHandle

type TaskHandle struct {
	Version     int
	DriverState []byte
}

Experimental - TaskHandle is based on drivers.TaskHandle and used by remote task drivers to migrate task handles between allocations.

type TaskLifecycle

type TaskLifecycle struct {
	Hook    string `mapstructure:"hook" hcl:"hook,optional"`
	Sidecar bool   `mapstructure:"sidecar" hcl:"sidecar,optional"`
}

func (*TaskLifecycle) Empty

func (l *TaskLifecycle) Empty() bool

Determine if lifecycle has user-input values

type TaskResourceUsage

type TaskResourceUsage struct {
	ResourceUsage *ResourceUsage
	Timestamp     int64
	Pids          map[string]*ResourceUsage
}

TaskResourceUsage holds aggregated resource usage of all processes in a Task and the resource usage of the individual pids

type TaskState

type TaskState struct {
	State       string
	Failed      bool
	Restarts    uint64
	LastRestart time.Time
	StartedAt   time.Time
	FinishedAt  time.Time
	Events      []*TaskEvent

	// Experimental -  TaskHandle is based on drivers.TaskHandle and used
	// by remote task drivers to migrate task handles between allocations.
	TaskHandle *TaskHandle
}

TaskState tracks the current state of a task and events that caused state transitions.

type Template

type Template struct {
	SourcePath   *string        `mapstructure:"source" hcl:"source,optional"`
	DestPath     *string        `mapstructure:"destination" hcl:"destination,optional"`
	EmbeddedTmpl *string        `mapstructure:"data" hcl:"data,optional"`
	ChangeMode   *string        `mapstructure:"change_mode" hcl:"change_mode,optional"`
	ChangeSignal *string        `mapstructure:"change_signal" hcl:"change_signal,optional"`
	Splay        *time.Duration `mapstructure:"splay" hcl:"splay,optional"`
	Perms        *string        `mapstructure:"perms" hcl:"perms,optional"`
	LeftDelim    *string        `mapstructure:"left_delimiter" hcl:"left_delimiter,optional"`
	RightDelim   *string        `mapstructure:"right_delimiter" hcl:"right_delimiter,optional"`
	Envvars      *bool          `mapstructure:"env" hcl:"env,optional"`
	VaultGrace   *time.Duration `mapstructure:"vault_grace" hcl:"vault_grace,optional"`
	Wait         *WaitConfig    `mapstructure:"wait" hcl:"wait,block"`
}

func (*Template) Canonicalize

func (tmpl *Template) Canonicalize()

type TerminalSize

type TerminalSize struct {
	Height int `json:"height,omitempty"`
	Width  int `json:"width,omitempty"`
}

TerminalSize represents the size of the terminal

type Topic

type Topic string

Topic is an event Topic

const (
	TopicDeployment Topic = "Deployment"
	TopicEvaluation Topic = "Evaluation"
	TopicAllocation Topic = "Allocation"
	TopicJob        Topic = "Job"
	TopicNode       Topic = "Node"
	TopicAll        Topic = "*"
)

type UpdateStrategy

type UpdateStrategy struct {
	Stagger          *time.Duration `mapstructure:"stagger" hcl:"stagger,optional"`
	MaxParallel      *int           `mapstructure:"max_parallel" hcl:"max_parallel,optional"`
	HealthCheck      *string        `mapstructure:"health_check" hcl:"health_check,optional"`
	MinHealthyTime   *time.Duration `mapstructure:"min_healthy_time" hcl:"min_healthy_time,optional"`
	HealthyDeadline  *time.Duration `mapstructure:"healthy_deadline" hcl:"healthy_deadline,optional"`
	ProgressDeadline *time.Duration `mapstructure:"progress_deadline" hcl:"progress_deadline,optional"`
	Canary           *int           `mapstructure:"canary" hcl:"canary,optional"`
	AutoRevert       *bool          `mapstructure:"auto_revert" hcl:"auto_revert,optional"`
	AutoPromote      *bool          `mapstructure:"auto_promote" hcl:"auto_promote,optional"`
}

UpdateStrategy defines a task groups update strategy.

func DefaultUpdateStrategy

func DefaultUpdateStrategy() *UpdateStrategy

DefaultUpdateStrategy provides a baseline that can be used to upgrade jobs with the old policy or for populating field defaults.

func (*UpdateStrategy) Canonicalize

func (u *UpdateStrategy) Canonicalize()

func (*UpdateStrategy) Copy

func (u *UpdateStrategy) Copy() *UpdateStrategy

func (*UpdateStrategy) Empty

func (u *UpdateStrategy) Empty() bool

Empty returns whether the UpdateStrategy is empty or has user defined values.

func (*UpdateStrategy) Merge

func (u *UpdateStrategy) Merge(o *UpdateStrategy)

type Vault

type Vault struct {
	Policies     []string `hcl:"policies,optional"`
	Namespace    *string  `mapstructure:"namespace" hcl:"namespace,optional"`
	Env          *bool    `hcl:"env,optional"`
	ChangeMode   *string  `mapstructure:"change_mode" hcl:"change_mode,optional"`
	ChangeSignal *string  `mapstructure:"change_signal" hcl:"change_signal,optional"`
}

func (*Vault) Canonicalize

func (v *Vault) Canonicalize()

type VolumeMount

type VolumeMount struct {
	Volume          *string `hcl:"volume,optional"`
	Destination     *string `hcl:"destination,optional"`
	ReadOnly        *bool   `mapstructure:"read_only" hcl:"read_only,optional"`
	PropagationMode *string `mapstructure:"propagation_mode" hcl:"propagation_mode,optional"`
}

VolumeMount represents the relationship between a destination path in a task and the task group volume that should be mounted there.

func (*VolumeMount) Canonicalize

func (vm *VolumeMount) Canonicalize()

type VolumeRequest

type VolumeRequest struct {
	Name           string           `hcl:"name,label"`
	Type           string           `hcl:"type,optional"`
	Source         string           `hcl:"source,optional"`
	ReadOnly       bool             `hcl:"read_only,optional"`
	AccessMode     string           `hcl:"access_mode,optional"`
	AttachmentMode string           `hcl:"attachment_mode,optional"`
	MountOptions   *CSIMountOptions `hcl:"mount_options,block"`
	PerAlloc       bool             `hcl:"per_alloc,optional"`
	ExtraKeysHCL   []string         `hcl1:",unusedKeys,optional" json:"-"`
}

VolumeRequest is a representation of a storage volume that a TaskGroup wishes to use.

type WaitConfig

type WaitConfig struct {
	Min *time.Duration `mapstructure:"min" hcl:"min"`
	Max *time.Duration `mapstructure:"max" hcl:"max"`
}

WaitConfig is the Min/Max duration to wait for the Consul cluster to reach a consistent state before attempting to render Templates.

func (*WaitConfig) Copy

func (wc *WaitConfig) Copy() *WaitConfig

type WriteMeta

type WriteMeta struct {
	// LastIndex. This can be used as a WaitIndex to perform
	// a blocking query
	LastIndex uint64

	// How long did the request take
	RequestTime time.Duration
}

WriteMeta is used to return meta data about a write

type WriteOptions

type WriteOptions struct {
	// Providing a datacenter overwrites the region provided
	// by the Config
	Region string

	// Namespace is the target namespace for the write.
	Namespace string

	// AuthToken is the secret ID of an ACL token
	AuthToken string

	// Set HTTP headers on the query.
	Headers map[string]string

	// IdempotencyToken can be used to ensure the write is idempotent.
	IdempotencyToken string
	// contains filtered or unexported fields
}

WriteOptions are used to parametrize a write

func (*WriteOptions) Context

func (o *WriteOptions) Context() context.Context

Context returns the context used for canceling HTTP requests related to this write

func (*WriteOptions) SetHeadersFromCSISecrets

func (w *WriteOptions) SetHeadersFromCSISecrets(secrets CSISecrets)

func (*WriteOptions) WithContext

func (o *WriteOptions) WithContext(ctx context.Context) *WriteOptions

WithContext creates a copy of the write options using the provided context to cancel related HTTP requests

type WriteRequest

type WriteRequest struct {
	// The target region for this write
	Region string

	// Namespace is the target namespace for this write
	Namespace string

	// SecretID is the secret ID of an ACL token
	SecretID string
}

Directories

Path Synopsis
Package contexts provides constants used with the Nomad Search API.
Package contexts provides constants used with the Nomad Search API.
internal
testutil/freeport
Package freeport provides a helper for allocating free ports across multiple processes on the same machine.
Package freeport provides a helper for allocating free ports across multiple processes on the same machine.

Jump to

Keyboard shortcuts

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