Documentation

Index

Constants

const (

	// Prefix based errors that are used to check if the error is of a given
	// type. These errors should be created with the associated constructor.
	ErrUnknownAllocationPrefix = "Unknown allocation"
	ErrUnknownNodePrefix       = "Unknown node"
	ErrUnknownJobPrefix        = "Unknown job"
	ErrUnknownEvaluationPrefix = "Unknown evaluation"
	ErrUnknownDeploymentPrefix = "Unknown deployment"
)

const (
	// MinDynamicPort is the smallest dynamic port generated
	MinDynamicPort = 20000

	// MaxDynamicPort is the largest dynamic port generated
	MaxDynamicPort = 32000
)

const (
	EnvoyBootstrapPath = "${NOMAD_SECRETS_DIR}/envoy_bootstrap.json"

	ServiceCheckHTTP   = "http"
	ServiceCheckTCP    = "tcp"
	ServiceCheckScript = "script"
	ServiceCheckGRPC   = "grpc"
)

const (
	AddressModeAuto   = "auto"
	AddressModeHost   = "host"
	AddressModeDriver = "driver"
)

const (
	// IgnoreUnknownTypeFlag is set along with a MessageType
	// to indicate that the message type can be safely ignored
	// if it is not recognized. This is for future proofing, so
	// that new commands can be added in a way that won't cause
	// old servers to crash when the FSM attempts to process them.
	IgnoreUnknownTypeFlag MessageType = 128

	// ApiMajorVersion is returned as part of the Status.Version request.
	// It should be incremented anytime the APIs are changed in a way
	// that would break clients for sane client versioning.
	ApiMajorVersion = 1

	// ApiMinorVersion is returned as part of the Status.Version request.
	// It should be incremented anytime the APIs are changed to allow
	// for sane client versioning. Minor changes should be compatible
	// within the major version.
	ApiMinorVersion = 1

	ProtocolVersion = "protocol"
	APIMajorVersion = "api.major"
	APIMinorVersion = "api.minor"

	GetterModeAny  = "any"
	GetterModeFile = "file"
	GetterModeDir  = "dir"

	// ACLClientToken and ACLManagementToken are the only types of tokens
	ACLClientToken     = "client"
	ACLManagementToken = "management"

	// DefaultNamespace is the default namespace.
	DefaultNamespace            = "default"
	DefaultNamespaceDescription = "Default shared namespace"

	// AllNamespacesSentinel is the value used as a namespace RPC value
	// to indicate that endpoints must search in all namespaces
	AllNamespacesSentinel = "*"

	// JitterFraction is a the limit to the amount of jitter we apply
	// to a user specified MaxQueryTime. We divide the specified time by
	// the fraction. So 16 == 6.25% limit of jitter. This jitter is also
	// applied to RPCHoldTimeout.
	JitterFraction = 16

	// MaxRetainedNodeEvents is the maximum number of node events that will be
	// retained for a single node
	MaxRetainedNodeEvents = 10

	// MaxRetainedNodeScores is the number of top scoring nodes for which we
	// retain scoring metadata
	MaxRetainedNodeScores = 5

	// Normalized scorer name
	NormScorerName = "normalized-score"
)

const (
	NodeEventSubsystemDrain     = "Drain"
	NodeEventSubsystemDriver    = "Driver"
	NodeEventSubsystemHeartbeat = "Heartbeat"
	NodeEventSubsystemCluster   = "Cluster"
	NodeEventSubsystemStorage   = "Storage"
)

const (
	NodeStatusInit  = "initializing"
	NodeStatusReady = "ready"
	NodeStatusDown  = "down"
)

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

const (
	// JobTypeNomad is reserved for internal system tasks and is
	// always handled by the CoreScheduler.
	JobTypeCore    = "_core"
	JobTypeService = "service"
	JobTypeBatch   = "batch"
	JobTypeSystem  = "system"
)

const (
	JobStatusPending = "pending" // Pending means the job is waiting on scheduling
	JobStatusRunning = "running" // Running means the job has non-terminal allocations
	JobStatusDead    = "dead"    // Dead means all evaluation's and allocations are terminal
)

const (
	// JobMinPriority is the minimum allowed priority
	JobMinPriority = 1

	// JobDefaultPriority is the default priority if not
	// not specified.
	JobDefaultPriority = 50

	// JobMaxPriority is the maximum allowed priority
	JobMaxPriority = 100

	// Ensure CoreJobPriority is higher than any user
	// specified job so that it gets priority. This is important
	// for the system to remain healthy.
	CoreJobPriority = JobMaxPriority * 2

	// JobTrackedVersions is the number of historic job versions that are
	// kept.
	JobTrackedVersions = 6

	// JobTrackedScalingEvents is the number of scaling events that are
	// kept for a single task group.
	JobTrackedScalingEvents = 20
)

const (
	// Checks uses any registered health check state in combination with task
	// states to determine if a allocation is healthy.
	UpdateStrategyHealthCheck_Checks = "checks"

	// TaskStates uses the task states of an allocation to determine if the
	// allocation is healthy.
	UpdateStrategyHealthCheck_TaskStates = "task_states"

	// Manual allows the operator to manually signal to Nomad when an
	// allocations is healthy. This allows more advanced health checking that is
	// outside of the scope of Nomad.
	UpdateStrategyHealthCheck_Manual = "manual"
)

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

	// PeriodicSpecTest is only used by unit tests. It is a sorted, comma
	// separated list of unix timestamps at which to launch.
	PeriodicSpecTest = "_internal_test"
)

const (
	DispatchPayloadForbidden = "forbidden"
	DispatchPayloadOptional  = "optional"
	DispatchPayloadRequired  = "required"

	// DispatchLaunchSuffix is the string appended to the parameterized job's ID
	// when dispatching instances of it.
	DispatchLaunchSuffix = "/dispatch-"
)

const (
	TaskLifecycleHookPrestart  = "prestart"
	TaskLifecycleHookPoststart = "poststart"
)

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"

	// RestartPolicyMinInterval is the minimum interval that is accepted for a
	// restart policy.
	RestartPolicyMinInterval = 5 * time.Second

	// ReasonWithinPolicy describes restart events that are within policy
	ReasonWithinPolicy = "Restart within policy"
)

const (
	ScalingTargetNamespace = "Namespace"
	ScalingTargetJob       = "Job"
	ScalingTargetGroup     = "Group"
)

const (
	MigrateStrategyHealthChecks = "checks"
	MigrateStrategyHealthStates = "task_states"
)

const (
	// ConnectProxyPrefix is the prefix used for fields referencing a Consul Connect
	// Proxy
	ConnectProxyPrefix = "connect-proxy"

	// ConnectNativePrefix is the prefix used for fields referencing a Connect
	// Native Task
	ConnectNativePrefix = "connect-native"

	// ConnectIngressPrefix is the prefix used for fields referencing a Consul
	// Connect Ingress Gateway Proxy.
	ConnectIngressPrefix = "connect-ingress"
)

const (
	// TemplateChangeModeNoop marks that no action should be taken if the
	// template is re-rendered
	TemplateChangeModeNoop = "noop"

	// TemplateChangeModeSignal marks that the task should be signaled if the
	// template is re-rendered
	TemplateChangeModeSignal = "signal"

	// TemplateChangeModeRestart marks that the task should be restarted if the
	// template is re-rendered
	TemplateChangeModeRestart = "restart"
)

const (
	TaskStatePending = "pending" // The task is waiting to be run.
	TaskStateRunning = "running" // The task is currently running.
	TaskStateDead    = "dead"    // Terminal state of task.
)

Set of possible states for a task.


const (
	// TaskSetupFailure indicates that the task could not be started due to a
	// a setup failure.
	TaskSetupFailure = "Setup Failure"

	// TaskDriveFailure indicates that the task could not be started due to a
	// failure in the driver. TaskDriverFailure is considered Recoverable.
	TaskDriverFailure = "Driver Failure"

	// TaskReceived signals that the task has been pulled by the client at the
	// given timestamp.
	TaskReceived = "Received"

	// TaskFailedValidation indicates the task was invalid and as such was not run.
	// TaskFailedValidation is not considered Recoverable.
	TaskFailedValidation = "Failed Validation"

	// TaskStarted signals that the task was started and its timestamp can be
	// used to determine the running length of the task.
	TaskStarted = "Started"

	// TaskTerminated indicates that the task was started and exited.
	TaskTerminated = "Terminated"

	// TaskKilling indicates a kill signal has been sent to the task.
	TaskKilling = "Killing"

	// TaskKilled indicates a user has killed the task.
	TaskKilled = "Killed"

	// TaskRestarting indicates that task terminated and is being restarted.
	TaskRestarting = "Restarting"

	// TaskNotRestarting indicates that the task has failed and is not being
	// restarted because it has exceeded its restart policy.
	TaskNotRestarting = "Not Restarting"

	// TaskRestartSignal indicates that the task has been signalled to be
	// restarted
	TaskRestartSignal = "Restart Signaled"

	// TaskSignaling indicates that the task is being signalled.
	TaskSignaling = "Signaling"

	// TaskDownloadingArtifacts means the task is downloading the artifacts
	// specified in the task.
	TaskDownloadingArtifacts = "Downloading Artifacts"

	// TaskArtifactDownloadFailed indicates that downloading the artifacts
	// failed.
	TaskArtifactDownloadFailed = "Failed Artifact Download"

	// TaskBuildingTaskDir indicates that the task directory/chroot is being
	// built.
	TaskBuildingTaskDir = "Building Task Directory"

	// TaskSetup indicates the task runner is setting up the task environment
	TaskSetup = "Task Setup"

	// TaskDiskExceeded indicates that one of the tasks in a taskgroup has
	// exceeded the requested disk resources.
	TaskDiskExceeded = "Disk Resources Exceeded"

	// TaskSiblingFailed indicates that a sibling task in the task group has
	// failed.
	TaskSiblingFailed = "Sibling Task Failed"

	// TaskDriverMessage is an informational event message emitted by
	// drivers such as when they're performing a long running action like
	// downloading an image.
	TaskDriverMessage = "Driver"

	// TaskLeaderDead indicates that the leader task within the has finished.
	TaskLeaderDead = "Leader Task Dead"

	// TaskMainDead indicates that the main tasks have dead
	TaskMainDead = "Main Tasks Dead"

	// TaskHookFailed indicates that one of the hooks for a task failed.
	TaskHookFailed = "Task hook failed"

	// TaskRestoreFailed indicates Nomad was unable to reattach to a
	// restored task.
	TaskRestoreFailed = "Failed Restoring Task"

	// TaskPluginUnhealthy indicates that a plugin managed by Nomad became unhealthy
	TaskPluginUnhealthy = "Plugin became unhealthy"

	// TaskPluginHealthy indicates that a plugin managed by Nomad became healthy
	TaskPluginHealthy = "Plugin became healthy"
)

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

const (
	// VaultChangeModeNoop takes no action when a new token is retrieved.
	VaultChangeModeNoop = "noop"

	// VaultChangeModeSignal signals the task when a new token is retrieved.
	VaultChangeModeSignal = "signal"

	// VaultChangeModeRestart restarts the task when a new token is retrieved.
	VaultChangeModeRestart = "restart"
)

const (
	// DeploymentStatuses are the various states a deployment can be be in
	DeploymentStatusRunning    = "running"
	DeploymentStatusPaused     = "paused"
	DeploymentStatusFailed     = "failed"
	DeploymentStatusSuccessful = "successful"
	DeploymentStatusCancelled  = "cancelled"
	DeploymentStatusPending    = "pending"
	DeploymentStatusBlocked    = "blocked"
	DeploymentStatusUnblocking = "unblocking"

	// DeploymentStatusDescriptions are the various descriptions of the states a
	// deployment can be in.
	DeploymentStatusDescriptionRunning               = "Deployment is running"
	DeploymentStatusDescriptionRunningNeedsPromotion = "Deployment is running but requires manual promotion"
	DeploymentStatusDescriptionRunningAutoPromotion  = "Deployment is running pending automatic promotion"
	DeploymentStatusDescriptionPaused                = "Deployment is paused"
	DeploymentStatusDescriptionSuccessful            = "Deployment completed successfully"
	DeploymentStatusDescriptionStoppedJob            = "Cancelled because job is stopped"
	DeploymentStatusDescriptionNewerJob              = "Cancelled due to newer version of job"
	DeploymentStatusDescriptionFailedAllocations     = "Failed due to unhealthy allocations"
	DeploymentStatusDescriptionProgressDeadline      = "Failed due to progress deadline"
	DeploymentStatusDescriptionFailedByUser          = "Deployment marked as failed"

	// used only in multiregion deployments
	DeploymentStatusDescriptionFailedByPeer   = "Failed because of an error in peer region"
	DeploymentStatusDescriptionBlocked        = "Deployment is complete but waiting for peer region"
	DeploymentStatusDescriptionUnblocking     = "Deployment is unblocking remaining regions"
	DeploymentStatusDescriptionPendingForPeer = "Deployment is pending, waiting for peer region"
)

const (
	AllocDesiredStatusRun   = "run"   // Allocation should run
	AllocDesiredStatusStop  = "stop"  // Allocation should stop
	AllocDesiredStatusEvict = "evict" // Allocation should stop, and was evicted
)

const (
	AllocClientStatusPending  = "pending"
	AllocClientStatusRunning  = "running"
	AllocClientStatusComplete = "complete"
	AllocClientStatusFailed   = "failed"
	AllocClientStatusLost     = "lost"
)

const (
	EvalStatusBlocked   = "blocked"
	EvalStatusPending   = "pending"
	EvalStatusComplete  = "complete"
	EvalStatusFailed    = "failed"
	EvalStatusCancelled = "canceled"
)

const (
	EvalTriggerJobRegister       = "job-register"
	EvalTriggerJobDeregister     = "job-deregister"
	EvalTriggerPeriodicJob       = "periodic-job"
	EvalTriggerNodeDrain         = "node-drain"
	EvalTriggerNodeUpdate        = "node-update"
	EvalTriggerAllocStop         = "alloc-stop"
	EvalTriggerScheduled         = "scheduled"
	EvalTriggerRollingUpdate     = "rolling-update"
	EvalTriggerDeploymentWatcher = "deployment-watcher"
	EvalTriggerFailedFollowUp    = "failed-follow-up"
	EvalTriggerMaxPlans          = "max-plan-attempts"
	EvalTriggerRetryFailedAlloc  = "alloc-failure"
	EvalTriggerQueuedAllocs      = "queued-allocs"
	EvalTriggerPreemption        = "preemption"
	EvalTriggerScaling           = "job-scaling"
)

const (
	// CoreJobEvalGC is used for the garbage collection of evaluations
	// and allocations. We periodically scan evaluations in a terminal state,
	// in which all the corresponding allocations are also terminal. We
	// delete these out of the system to bound the state.
	CoreJobEvalGC = "eval-gc"

	// CoreJobNodeGC is used for the garbage collection of failed nodes.
	// We periodically scan nodes in a terminal state, and if they have no
	// corresponding allocations we delete these out of the system.
	CoreJobNodeGC = "node-gc"

	// CoreJobJobGC is used for the garbage collection of eligible jobs. We
	// periodically scan garbage collectible jobs and check if both their
	// evaluations and allocations are terminal. If so, we delete these out of
	// the system.
	CoreJobJobGC = "job-gc"

	// CoreJobDeploymentGC is used for the garbage collection of eligible
	// deployments. We periodically scan garbage collectible deployments and
	// check if they are terminal. If so, we delete these out of the system.
	CoreJobDeploymentGC = "deployment-gc"

	// CoreJobCSIVolumeClaimGC is use for the garbage collection of CSI
	// volume claims. We periodically scan volumes to see if no allocs are
	// claiming them. If so, we unclaim the volume.
	CoreJobCSIVolumeClaimGC = "csi-volume-claim-gc"

	// CoreJobCSIPluginGC is use for the garbage collection of CSI plugins.
	// We periodically scan plugins to see if they have no associated volumes
	// or allocs running them. If so, we delete the plugin.
	CoreJobCSIPluginGC = "csi-plugin-gc"

	// CoreJobForceGC is used to force garbage collection of all GCable objects.
	CoreJobForceGC = "force-gc"
)

const (
	VolumeMountPropagationPrivate       = "private"
	VolumeMountPropagationHostToTask    = "host-to-task"
	VolumeMountPropagationBidirectional = "bidirectional"
)

const (
	BytesInMegabyte = 1024 * 1024
)

const CSIIntermediaryDirname = "volumes"

CSIIntermediaryDirname is the name of the directory inside the PluginMountDir where Nomad will expect plugins to create intermediary mounts for volumes.


const CSISocketName = "csi.sock"

CSISocketName is the filename that Nomad expects plugins to create inside the PluginMountDir.


const (
	// DefaultKillTimeout is the default timeout between signaling a task it
	// will be killed and killing it.
	DefaultKillTimeout = 5 * time.Second
)

const (
	// NodeUniqueNamespace is a prefix that can be appended to node meta or
	// attribute keys to mark them for exclusion in computed node class.
	NodeUniqueNamespace = "unique."
)

const (
	// PeriodicLaunchSuffix is the string appended to the periodic jobs ID
	// when launching derived instances of it.
	PeriodicLaunchSuffix = "/periodic-"
)

const ReschedulePolicyMinDelay = 5 * time.Second

const ReschedulePolicyMinInterval = 15 * time.Second

const VolumeTypeCSI = "csi"

VolumeTypeCSI is the type in the volume stanza of a TaskGroup


const (
	VolumeTypeHost = "host"
)

Variables

var (
	ErrNoLeader                   = errors.New(errNoLeader)
	ErrNotReadyForConsistentReads = errors.New(errNotReadyForConsistentReads)
	ErrNoRegionPath               = errors.New(errNoRegionPath)
	ErrTokenNotFound              = errors.New(errTokenNotFound)
	ErrPermissionDenied           = errors.New(errPermissionDenied)
	ErrNoNodeConn                 = errors.New(errNoNodeConn)
	ErrUnknownMethod              = errors.New(errUnknownMethod)
	ErrUnknownNomadVersion        = errors.New(errUnknownNomadVersion)
	ErrNodeLacksRpc               = errors.New(errNodeLacksRpc)
	ErrMissingAllocID             = errors.New(errMissingAllocID)

	ErrUnknownNode = errors.New(ErrUnknownNodePrefix)

	ErrDeploymentTerminalNoCancel    = errors.New(errDeploymentTerminalNoCancel)
	ErrDeploymentTerminalNoFail      = errors.New(errDeploymentTerminalNoFail)
	ErrDeploymentTerminalNoPause     = errors.New(errDeploymentTerminalNoPause)
	ErrDeploymentTerminalNoPromote   = errors.New(errDeploymentTerminalNoPromote)
	ErrDeploymentTerminalNoResume    = errors.New(errDeploymentTerminalNoResume)
	ErrDeploymentTerminalNoUnblock   = errors.New(errDeploymentTerminalNoUnblock)
	ErrDeploymentTerminalNoRun       = errors.New(errDeploymentTerminalNoRun)
	ErrDeploymentTerminalNoSetHealth = errors.New(errDeploymentTerminalNoSetHealth)
	ErrDeploymentRunningNoUnblock    = errors.New(errDeploymentRunningNoUnblock)

	ErrCSIClientRPCIgnorable = errors.New("CSI client error (ignorable)")
	ErrCSIClientRPCRetryable = errors.New("CSI client error (retryable)")
)

var (
	DefaultServiceJobRestartPolicy = RestartPolicy{
		Delay:    15 * time.Second,
		Attempts: 2,
		Interval: 30 * time.Minute,
		Mode:     RestartPolicyModeFail,
	}
	DefaultBatchJobRestartPolicy = RestartPolicy{
		Delay:    15 * time.Second,
		Attempts: 3,
		Interval: 24 * time.Hour,
		Mode:     RestartPolicyModeFail,
	}
)

var (
	DefaultServiceJobReschedulePolicy = ReschedulePolicy{
		Delay:         30 * time.Second,
		DelayFunction: "exponential",
		MaxDelay:      1 * time.Hour,
		Unlimited:     true,
	}
	DefaultBatchJobReschedulePolicy = ReschedulePolicy{
		Attempts:      1,
		Interval:      24 * time.Hour,
		Delay:         5 * time.Second,
		DelayFunction: "constant",
	}
)

var (
	// JsonHandle and JsonHandlePretty are the codec handles to JSON encode
	// structs. The pretty handle will add indents for easier human consumption.
	JsonHandle = &codec.JsonHandle{
		HTMLCharsAsIs: true,
	}
	JsonHandlePretty = &codec.JsonHandle{
		HTMLCharsAsIs: true,
		Indent:        4,
	}
)

var (
	// AnonymousACLToken is used no SecretID is provided, and the
	// request is made anonymously.
	AnonymousACLToken = &ACLToken{
		AccessorID: "anonymous",
		Name:       "Anonymous Token",
		Type:       ACLClientToken,
		Policies:   []string{"anonymous"},
		Global:     false,
	}
)

var (
	// DefaultUpdateStrategy provides a baseline that can be used to upgrade
	// jobs with the old policy or for populating field defaults.
	DefaultUpdateStrategy = &UpdateStrategy{
		Stagger:          30 * time.Second,
		MaxParallel:      1,
		HealthCheck:      UpdateStrategyHealthCheck_Checks,
		MinHealthyTime:   10 * time.Second,
		HealthyDeadline:  5 * time.Minute,
		ProgressDeadline: 10 * time.Minute,
		AutoRevert:       false,
		AutoPromote:      false,
		Canary:           0,
	}
)

var MsgpackHandle = func() *codec.MsgpackHandle {
	h := &codec.MsgpackHandle{}
	h.RawToString = true

	h.BasicHandle.TimeNotBuiltin = true

	h.MapType = reflect.TypeOf(map[string]interface{}(nil))

	h.TypeInfos = codec.NewTypeInfos([]string{"codec"})

	return h
}()

msgpackHandle is a shared handle for encoding/decoding of structs


var RescheduleDelayFunctions = [...]string{"constant", "exponential", "fibonacci"}

var (
	// TemplateChangeModeInvalidError is the error for when an invalid change
	// mode is given
	TemplateChangeModeInvalidError = errors.New("Invalid change mode. Must be one of the following: noop, signal, restart")
)

var (
	// VaultUnrecoverableError matches unrecoverable errors returned by a Vault
	// server
	VaultUnrecoverableError = regexp.MustCompile(`Code:\s+40(0|3|4)`)
)

Functions

func ACLPolicyListHash

func ACLPolicyListHash(policies []*ACLPolicy) string

ACLPolicyListHash returns a consistent hash for a set of policies.

func AllocName

func AllocName(job, group string, idx uint) string

AllocName returns the name of the allocation given the input.

func Bridge

func Bridge(a, b io.ReadWriteCloser)

Bridge is used to just link two connections together and copy traffic

func CSIPluginTypeIsValid

func CSIPluginTypeIsValid(pt CSIPluginType) bool

CSIPluginTypeIsValid validates the given CSIPluginType string and returns true only when a correct plugin type is specified.

func CodeFromRPCCodedErr

func CodeFromRPCCodedErr(err error) (code int, msg string, ok bool)

CodeFromRPCCodedErr returns the code and message of error if it's an RPC error created through NewErrRPCCoded function. Returns `ok` false if error is not an rpc error

func CompareMigrateToken

func CompareMigrateToken(allocID, nodeSecretID, otherMigrateToken string) bool

CompareMigrateToken returns true if two migration tokens can be computed and are equal.

func CompileACLObject

func CompileACLObject(cache *lru.TwoQueueCache, policies []*ACLPolicy) (*acl.ACL, error)

CompileACLObject compiles a set of ACL policies into an ACL object with a cache

func CopyMapStringClientHostVolumeConfig

func CopyMapStringClientHostVolumeConfig(m map[string]*ClientHostVolumeConfig) map[string]*ClientHostVolumeConfig

func CopyMapVolumeRequest

func CopyMapVolumeRequest(s map[string]*VolumeRequest) map[string]*VolumeRequest

func CronParseNext

func CronParseNext(e *cronexpr.Expression, fromTime time.Time, spec string) (t time.Time, err error)

CronParseNext is a helper that parses the next time for the given expression but captures any panic that may occur in the underlying library.

func Decode

func Decode(buf []byte, out interface{}) error

Decode is used to decode a MsgPack encoded object

func DenormalizeAllocationJobs

func DenormalizeAllocationJobs(job *Job, allocs []*Allocation)

DenormalizeAllocationJobs is used to attach a job to all allocations that are non-terminal and do not have a job already. This is useful in cases where the job is normalized.

func DeploymentStatusDescriptionNoRollbackTarget

func DeploymentStatusDescriptionNoRollbackTarget(baseDescription string) string

DeploymentStatusDescriptionNoRollbackTarget is used to get the status description of a deployment when there is no target to rollback to but autorevert is desired.

func DeploymentStatusDescriptionRollback

func DeploymentStatusDescriptionRollback(baseDescription string, jobVersion uint64) string

DeploymentStatusDescriptionRollback is used to get the status description of a deployment when rolling back to an older job.

func DeploymentStatusDescriptionRollbackNoop

func DeploymentStatusDescriptionRollbackNoop(baseDescription string, jobVersion uint64) string

DeploymentStatusDescriptionRollbackNoop is used to get the status description of a deployment when rolling back is not possible because it has the same specification

func DevicesEquals

func DevicesEquals(d1, d2 []*NodeDeviceResource) bool

DevicesEquals returns true if the two device arrays are set equal

func DispatchedID

func DispatchedID(templateID string, t time.Time) string

DispatchedID returns an ID appropriate for a job dispatched against a particular parameterized job

func Encode

func Encode(t MessageType, msg interface{}) ([]byte, error)

Encode is used to encode a MsgPack object with type prefix

func GenerateMigrateToken

func GenerateMigrateToken(allocID, nodeSecretID string) (string, error)

GenerateMigrateToken will create a token for a client to access an authenticated volume of another client to migrate data for sticky volumes.

func IsErrNoLeader

func IsErrNoLeader(err error) bool

IsErrNoLeader returns whether the error is due to there being no leader.

func IsErrNoNodeConn

func IsErrNoNodeConn(err error) bool

IsErrNoNodeConn returns whether the error is due to there being no path to the given node.

func IsErrNoRegionPath

func IsErrNoRegionPath(err error) bool

IsErrNoRegionPath returns whether the error is due to there being no path to the given region.

func IsErrNodeLacksRpc

func IsErrNodeLacksRpc(err error) bool

IsErrNodeLacksRpc returns whether error is due to a Nomad server being unable to connect to a client node because the client is too old (pre-v0.8).

func IsErrPermissionDenied

func IsErrPermissionDenied(err error) bool

IsErrPermissionDenied returns whether the error is due to the operation not being allowed due to lack of permissions.

func IsErrRPCCoded

func IsErrRPCCoded(err error) bool

func IsErrTokenNotFound

func IsErrTokenNotFound(err error) bool

IsErrTokenNotFound returns whether the error is due to the passed token not being resolvable.

func IsErrUnknownAllocation

func IsErrUnknownAllocation(err error) bool

IsErrUnknownAllocation returns whether the error is due to an unknown allocation.

func IsErrUnknownDeployment

func IsErrUnknownDeployment(err error) bool

IsErrUnknownDeployment returns whether the error is due to an unknown deployment.

func IsErrUnknownEvaluation

func IsErrUnknownEvaluation(err error) bool

IsErrUnknownEvaluation returns whether the error is due to an unknown evaluation.

func IsErrUnknownJob

func IsErrUnknownJob(err error) bool

IsErrUnknownJob returns whether the error is due to an unknown job.

func IsErrUnknownMethod

func IsErrUnknownMethod(err error) bool

IsErrUnknownMethod returns whether the error is due to the operation not being allowed due to lack of permissions.

func IsErrUnknownNode

func IsErrUnknownNode(err error) bool

IsErrUnknownNode returns whether the error is due to an unknown node.

func IsErrUnknownNomadVersion

func IsErrUnknownNomadVersion(err error) bool

IsErrUnknownNomadVersion returns whether the error is due to Nomad being unable to determine the version of a node.

func IsRecoverable

func IsRecoverable(e error) bool

IsRecoverable returns true if error is a RecoverableError with Recoverable=true. Otherwise false is returned.

func IsServerSide

func IsServerSide(e error) bool

IsServerSide returns true if error is a wrapped server side error

func IsUniqueNamespace

func IsUniqueNamespace(key string) bool

IsUniqueNamespace returns whether the key is under the unique namespace.

func MergeMultierrorWarnings

func MergeMultierrorWarnings(warnings ...error) string

MergeMultierrorWarnings takes job warnings and canonicalize warnings and merges them into a returnable string. Both the errors may be nil.

func MountPropagationModeIsValid

func MountPropagationModeIsValid(propagationMode string) bool

func NewErrRPCCoded

func NewErrRPCCoded(code int, msg string) error

NewErrRPCCoded wraps an RPC error with a code to be converted to HTTP status code

func NewErrRPCCodedf

func NewErrRPCCodedf(code int, format string, args ...interface{}) error

NewErrRPCCoded wraps an RPC error with a code to be converted to HTTP status code

func NewErrUnknownAllocation

func NewErrUnknownAllocation(allocID string) error

NewErrUnknownAllocation returns a new error caused by the allocation being unknown.

func NewErrUnknownDeployment

func NewErrUnknownDeployment(deploymentID string) error

NewErrUnknownDeployment returns a new error caused by the deployment being unknown.

func NewErrUnknownEvaluation

func NewErrUnknownEvaluation(evaluationID string) error

NewErrUnknownEvaluation returns a new error caused by the evaluation being unknown.

func NewErrUnknownJob

func NewErrUnknownJob(jobID string) error

NewErrUnknownJob returns a new error caused by the job being unknown.

func NewErrUnknownNode

func NewErrUnknownNode(nodeID string) error

NewErrUnknownNode returns a new error caused by the node being unknown.

func NewRecoverableError

func NewRecoverableError(e error, recoverable bool) error

NewRecoverableError is used to wrap an error and mark it as recoverable or not.

func NewWrappedServerError

func NewWrappedServerError(e error) error

NewWrappedServerError is used to create a wrapped server side error

func NodeNetworksEquals

func NodeNetworksEquals(n1, n2 []*NodeNetworkResource) bool

func ParsePortRanges

func ParsePortRanges(spec string) ([]uint64, error)

ParsePortRanges parses the passed port range string and returns a list of the ports. The specification is a comma separated list of either port numbers or port ranges. A port number is a single integer and a port range is two integers separated by a hyphen. As an example the following spec would convert to: ParsePortRanges("10,12-14,16") -> []uint64{10, 12, 13, 14, 16}

func PathEscapesAllocDir

func PathEscapesAllocDir(prefix, path string) (bool, error)

PathEscapesAllocDir returns if the given path escapes the allocation directory.

The prefix is to joined to the path (e.g. "task/local"), and this function checks if path escapes the alloc dir, NOT the prefix directory within the alloc dir. With prefix="task/local", it will return false for "../secret", but true for "../../../../../../root" path; only the latter escapes the alloc dir

func ScoreFitBinPack

func ScoreFitBinPack(node *Node, util *ComparableResources) float64

ScoreFitBinPack computes a fit score to achieve pinbacking behavior. Score is in [0, 18]

It's the BestFit v3 on the Google work published here: http://www.columbia.edu/~cs2035/courses/ieor4405.S13/datacenter_scheduling.ppt

func ScoreFitSpread

func ScoreFitSpread(node *Node, util *ComparableResources) float64

ScoreFitBinSpread computes a fit score to achieve spread behavior. Score is in [0, 18]

This is equivalent to Worst Fit of http://www.columbia.edu/~cs2035/courses/ieor4405.S13/datacenter_scheduling.ppt

func ShouldDrainNode

func ShouldDrainNode(status string) bool

ShouldDrainNode checks if a given node status should trigger an evaluation. Some states don't require any further action.

func UniqueNamespace

func UniqueNamespace(key string) string

UniqueNamespace takes a key and returns the key marked under the unique namespace.

func ValidCSIVolumeAccessMode

func ValidCSIVolumeAccessMode(accessMode CSIVolumeAccessMode) bool

ValidCSIVolumeAccessMode checks to see that the provided access mode is a valid, non-empty access mode.

func ValidCSIVolumeAttachmentMode

func ValidCSIVolumeAttachmentMode(attachmentMode CSIVolumeAttachmentMode) bool

func ValidCSIVolumeWriteAccessMode

func ValidCSIVolumeWriteAccessMode(accessMode CSIVolumeAccessMode) bool

ValidCSIVolumeAccessMode checks for a writable access mode

func ValidNodeStatus

func ValidNodeStatus(status string) bool

ValidNodeStatus is used to check if a node status is valid

func ValidateConnectProxyService

func ValidateConnectProxyService(serviceName string, tgServices []*Service) error

ValidateConnectProxyService checks that the service that is being proxied by this task exists in the task group and contains valid Connect config.

func VaultNamespaceSet

func VaultNamespaceSet(policies map[string]map[string]*Vault) []string

VaultNaVaultNamespaceSet takes the structure returned by VaultPolicies and returns a set of required namespaces

func VaultPoliciesSet

func VaultPoliciesSet(policies map[string]map[string]*Vault) []string

VaultPoliciesSet takes the structure returned by VaultPolicies and returns the set of required policies

func WrapRecoverable

func WrapRecoverable(msg string, err error) error

WrapRecoverable wraps an existing error in a new RecoverableError with a new message. If the error was recoverable before the returned error is as well; otherwise it is unrecoverable.

Types

type ACLPolicy

type ACLPolicy struct {
	Name        string      // Unique name
	Description string      // Human readable
	Rules       string      // HCL or JSON format
	RulesJSON   *acl.Policy // Generated from Rules on read
	Hash        []byte
	CreateIndex uint64
	ModifyIndex uint64
}

ACLPolicy is used to represent an ACL policy

func (*ACLPolicy) SetHash

func (c *ACLPolicy) SetHash() []byte

SetHash is used to compute and set the hash of the ACL policy

func (*ACLPolicy) Stub

func (a *ACLPolicy) Stub() *ACLPolicyListStub

func (*ACLPolicy) Validate

func (a *ACLPolicy) Validate() error

type ACLPolicyDeleteRequest

type ACLPolicyDeleteRequest struct {
	Names []string
	WriteRequest
}

ACLPolicyDeleteRequest is used to delete a set of policies

type ACLPolicyListRequest

type ACLPolicyListRequest struct {
	QueryOptions
}

ACLPolicyListRequest is used to request a list of policies

type ACLPolicyListResponse

type ACLPolicyListResponse struct {
	Policies []*ACLPolicyListStub
	QueryMeta
}

ACLPolicyListResponse is used for a list request

type ACLPolicyListStub

type ACLPolicyListStub struct {
	Name        string
	Description string
	Hash        []byte
	CreateIndex uint64
	ModifyIndex uint64
}

ACLPolicyListStub is used to for listing ACL policies

type ACLPolicySetRequest

type ACLPolicySetRequest struct {
	Names []string
	QueryOptions
}

ACLPolicySetRequest is used to query a set of policies

type ACLPolicySetResponse

type ACLPolicySetResponse struct {
	Policies map[string]*ACLPolicy
	QueryMeta
}

ACLPolicySetResponse is used to return a set of policies

type ACLPolicySpecificRequest

type ACLPolicySpecificRequest struct {
	Name string
	QueryOptions
}

ACLPolicySpecificRequest is used to query a specific policy

type ACLPolicyUpsertRequest

type ACLPolicyUpsertRequest struct {
	Policies []*ACLPolicy
	WriteRequest
}

ACLPolicyUpsertRequest is used to upsert a set of policies

type ACLToken

type ACLToken struct {
	AccessorID  string   // Public Accessor ID (UUID)
	SecretID    string   // Secret ID, private (UUID)
	Name        string   // Human friendly name
	Type        string   // Client or Management
	Policies    []string // Policies this token ties to
	Global      bool     // Global or Region local
	Hash        []byte
	CreateTime  time.Time // Time of creation
	CreateIndex uint64
	ModifyIndex uint64
}

ACLToken represents a client token which is used to Authenticate

func (*ACLToken) PolicySubset

func (a *ACLToken) PolicySubset(policies []string) bool

PolicySubset checks if a given set of policies is a subset of the token

func (*ACLToken) SetHash

func (a *ACLToken) SetHash() []byte

SetHash is used to compute and set the hash of the ACL token

func (*ACLToken) Stub

func (a *ACLToken) Stub() *ACLTokenListStub

func (*ACLToken) Validate

func (a *ACLToken) Validate() error

Validate is used to sanity check a token

type ACLTokenBootstrapRequest

type ACLTokenBootstrapRequest struct {
	Token      *ACLToken // Not client specifiable
	ResetIndex uint64    // Reset index is used to clear the bootstrap token
	WriteRequest
}

ACLTokenBootstrapRequest is used to bootstrap ACLs

type ACLTokenDeleteRequest

type ACLTokenDeleteRequest struct {
	AccessorIDs []string
	WriteRequest
}

ACLTokenDeleteRequest is used to delete a set of tokens

type ACLTokenListRequest

type ACLTokenListRequest struct {
	GlobalOnly bool
	QueryOptions
}

ACLTokenListRequest is used to request a list of tokens

type ACLTokenListResponse

type ACLTokenListResponse struct {
	Tokens []*ACLTokenListStub
	QueryMeta
}

ACLTokenListResponse is used for a list request

type ACLTokenListStub

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

type ACLTokenSetRequest

type ACLTokenSetRequest struct {
	AccessorIDS []string
	QueryOptions
}

ACLTokenSetRequest is used to query a set of tokens

type ACLTokenSetResponse

type ACLTokenSetResponse struct {
	Tokens map[string]*ACLToken // Keyed by Accessor ID
	QueryMeta
}

ACLTokenSetResponse is used to return a set of token

type ACLTokenSpecificRequest

type ACLTokenSpecificRequest struct {
	AccessorID string
	QueryOptions
}

ACLTokenSpecificRequest is used to query a specific token

type ACLTokenUpsertRequest

type ACLTokenUpsertRequest struct {
	Tokens []*ACLToken
	WriteRequest
}

ACLTokenUpsertRequest is used to upsert a set of tokens

type ACLTokenUpsertResponse

type ACLTokenUpsertResponse struct {
	Tokens []*ACLToken
	WriteMeta
}

ACLTokenUpsertResponse is used to return from an ACLTokenUpsertRequest

type Affinities

type Affinities []*Affinity

func (*Affinities) Equals

func (xs *Affinities) Equals(ys *Affinities) bool

Equals compares Affinities as a set

type Affinity

type Affinity struct {
	LTarget string // Left-hand target
	RTarget string // Right-hand target
	Operand string // Affinity operand (<=, <, =, !=, >, >=), set_contains_all, set_contains_any
	Weight  int8   // Weight applied to nodes that match the affinity. Can be negative
	// contains filtered or unexported fields
}

Affinity is used to score placement options based on a weight

func CopySliceAffinities

func CopySliceAffinities(s []*Affinity) []*Affinity

func (*Affinity) Copy

func (a *Affinity) Copy() *Affinity

func (*Affinity) Equal

func (a *Affinity) Equal(o *Affinity) bool

func (*Affinity) Equals

func (a *Affinity) Equals(o *Affinity) bool

Equal checks if two affinities are equal

func (*Affinity) String

func (a *Affinity) String() string

func (*Affinity) Validate

func (a *Affinity) Validate() error

type AgentPprofRequest

type AgentPprofRequest struct {
	// ReqType specifies the profile to use
	ReqType pprof.ReqType

	// Profile specifies the runtime/pprof profile to lookup and generate.
	Profile string

	// Seconds is the number of seconds to capture a profile
	Seconds int

	// Debug specifies if pprof profile should inclue debug output
	Debug int

	// GC specifies if the profile should call runtime.GC() before
	// running its profile. This is only used for "heap" profiles
	GC int

	// NodeID is the node we want to track the logs of
	NodeID string

	// ServerID is the server we want to track the logs of
	ServerID string

	QueryOptions
}

AgentPprofRequest is used to request a pprof report for a given node.

type AgentPprofResponse

type AgentPprofResponse struct {
	// ID of the agent that fulfilled the request
	AgentID string

	// Payload is the generated pprof profile
	Payload []byte

	// HTTPHeaders are a set of key value pairs to be applied as
	// HTTP headers for a specific runtime profile
	HTTPHeaders map[string]string
}

AgentPprofResponse is used to return a generated pprof profile

type AllocDeploymentStatus

type AllocDeploymentStatus struct {
	// Healthy marks whether the allocation has been marked healthy or unhealthy
	// as part of a deployment. It can be unset if it has neither been marked
	// healthy or unhealthy.
	Healthy *bool

	// Timestamp is the time at which the health status was set.
	Timestamp time.Time

	// Canary marks whether the allocation is a canary or not. A canary that has
	// been promoted will have this field set to false.
	Canary bool

	// ModifyIndex is the raft index in which the deployment status was last
	// changed.
	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.

func (*AllocDeploymentStatus) Copy

func (a *AllocDeploymentStatus) Copy() *AllocDeploymentStatus

func (*AllocDeploymentStatus) HasHealth

func (a *AllocDeploymentStatus) HasHealth() bool

HasHealth returns true if the allocation has its health set.

func (*AllocDeploymentStatus) IsCanary

func (a *AllocDeploymentStatus) IsCanary() bool

IsCanary returns if the allocation is marked as a canary

func (*AllocDeploymentStatus) IsHealthy

func (a *AllocDeploymentStatus) IsHealthy() bool

IsHealthy returns if the allocation is marked as healthy as part of a deployment

func (*AllocDeploymentStatus) IsUnhealthy

func (a *AllocDeploymentStatus) IsUnhealthy() bool

IsUnhealthy returns if the allocation is marked as unhealthy as part of a deployment

type AllocListRequest

type AllocListRequest struct {
	QueryOptions
}

AllocListRequest is used to request a list of allocations

type AllocListResponse

type AllocListResponse struct {
	Allocations []*AllocListStub
	QueryMeta
}

AllocListResponse is used for a list request

type AllocListStub

type AllocListStub struct {
	ID                    string
	EvalID                string
	Name                  string
	Namespace             string
	NodeID                string
	NodeName              string
	JobID                 string
	JobType               string
	JobVersion            uint64
	TaskGroup             string
	DesiredStatus         string
	DesiredDescription    string
	ClientStatus          string
	ClientDescription     string
	DesiredTransition     DesiredTransition
	TaskStates            map[string]*TaskState
	DeploymentStatus      *AllocDeploymentStatus
	FollowupEvalID        string
	RescheduleTracker     *RescheduleTracker
	PreemptedAllocations  []string
	PreemptedByAllocation string
	CreateIndex           uint64
	ModifyIndex           uint64
	CreateTime            int64
	ModifyTime            int64
}

AllocListStub is used to return a subset of alloc information

func (*AllocListStub) SetEventDisplayMessages

func (a *AllocListStub) SetEventDisplayMessages()

SetEventDisplayMessage populates the display message if its not already set, a temporary fix to handle old allocations that don't have it. This method will be removed in a future release.

type AllocMetric

type AllocMetric struct {
	// NodesEvaluated is the number of nodes that were evaluated
	NodesEvaluated int

	// NodesFiltered is the number of nodes filtered due to a constraint
	NodesFiltered int

	// NodesAvailable is the number of nodes available for evaluation per DC.
	NodesAvailable map[string]int

	// ClassFiltered is the number of nodes filtered by class
	ClassFiltered map[string]int

	// ConstraintFiltered is the number of failures caused by constraint
	ConstraintFiltered map[string]int

	// NodesExhausted is the number of nodes skipped due to being
	// exhausted of at least one resource
	NodesExhausted int

	// ClassExhausted is the number of nodes exhausted by class
	ClassExhausted map[string]int

	// DimensionExhausted provides the count by dimension or reason
	DimensionExhausted map[string]int

	// QuotaExhausted provides the exhausted dimensions
	QuotaExhausted []string

	// Scores is the scores of the final few nodes remaining
	// for placement. The top score is typically selected.
	// Deprecated: Replaced by ScoreMetaData in Nomad 0.9
	Scores map[string]float64

	// ScoreMetaData is a slice of top scoring nodes displayed in the CLI
	ScoreMetaData []*NodeScoreMeta

	// AllocationTime is a measure of how long the allocation
	// attempt took. This can affect performance and SLAs.
	AllocationTime time.Duration

	// CoalescedFailures indicates the number of other
	// allocations that were coalesced into this failed allocation.
	// This is to prevent creating many failed allocations for a
	// single task group.
	CoalescedFailures int
	// contains filtered or unexported fields
}

AllocMetric is used to track various metrics while attempting to make an allocation. These are used to debug a job, or to better understand the pressure within the system.

func (*AllocMetric) Copy

func (a *AllocMetric) Copy() *AllocMetric

func (*AllocMetric) EvaluateNode

func (a *AllocMetric) EvaluateNode()

func (*AllocMetric) ExhaustQuota

func (a *AllocMetric) ExhaustQuota(dimensions []string)

func (*AllocMetric) ExhaustedNode

func (a *AllocMetric) ExhaustedNode(node *Node, dimension string)

func (*AllocMetric) FilterNode

func (a *AllocMetric) FilterNode(node *Node, constraint string)

func (*AllocMetric) PopulateScoreMetaData

func (a *AllocMetric) PopulateScoreMetaData()

PopulateScoreMetaData populates a map of scorer to scoring metadata The map is populated by popping elements from a heap of top K scores maintained per scorer

func (*AllocMetric) ScoreNode

func (a *AllocMetric) ScoreNode(node *Node, name string, score float64)

ScoreNode is used to gather top K scoring nodes in a heap

type AllocRestartRequest

type AllocRestartRequest struct {
	AllocID  string
	TaskName string

	QueryOptions
}

AllocRestartRequest is used to restart a specific allocations tasks.

type AllocSignalRequest

type AllocSignalRequest struct {
	AllocID string
	Task    string
	Signal  string
	QueryOptions
}

AllocSignalRequest is used to signal a specific allocation

type AllocSpecificRequest

type AllocSpecificRequest struct {
	AllocID string
	QueryOptions
}

AllocSpecificRequest is used to query a specific allocation

type AllocState

type AllocState struct {
	Field AllocStateField
	Value string
	Time  time.Time
}

type AllocStateField

type AllocStateField uint8

AllocState records a single event that changes the state of the whole allocation

const (
	AllocStateFieldClientStatus AllocStateField = iota
)

type AllocStopRequest

type AllocStopRequest struct {
	AllocID string

	WriteRequest
}

AllocStopRequest is used to stop and reschedule a running Allocation.

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 AllocUpdateDesiredTransitionRequest

type AllocUpdateDesiredTransitionRequest struct {
	// Allocs is the mapping of allocation ids to their desired state
	// transition
	Allocs map[string]*DesiredTransition

	// Evals is the set of evaluations to create
	Evals []*Evaluation

	WriteRequest
}

AllocUpdateDesiredTransitionRequest is used to submit changes to allocations desired transition state.

type AllocUpdateRequest

type AllocUpdateRequest struct {
	// COMPAT 0.11
	// Alloc is the list of new allocations to assign
	// Deprecated: Replaced with two separate slices, one containing stopped allocations
	// and another containing updated allocations
	Alloc []*Allocation

	// Allocations to stop. Contains only the diff, not the entire allocation
	AllocsStopped []*AllocationDiff

	// New or updated allocations
	AllocsUpdated []*Allocation

	// Evals is the list of new evaluations to create
	// Evals are valid only when used in the Raft RPC
	Evals []*Evaluation

	// Job is the shared parent job of the allocations.
	// It is pulled out since it is common to reduce payload size.
	Job *Job

	WriteRequest
}

AllocUpdateRequest is used to submit changes to allocations, either to cause evictions or to assign new allocations. Both can be done within a single transaction

type AllocatedCpuResources

type AllocatedCpuResources struct {
	CpuShares int64
}

AllocatedCpuResources captures the allocated CPU resources.

func (*AllocatedCpuResources) Add

func (a *AllocatedCpuResources) Add(delta *AllocatedCpuResources)

func (*AllocatedCpuResources) Max

func (a *AllocatedCpuResources) Max(other *AllocatedCpuResources)

func (*AllocatedCpuResources) Subtract

func (a *AllocatedCpuResources) Subtract(delta *AllocatedCpuResources)

type AllocatedDeviceResource

type AllocatedDeviceResource struct {
	// Vendor, Type, and Name are used to select the plugin to request the
	// device IDs from.
	Vendor string
	Type   string
	Name   string

	// DeviceIDs is the set of allocated devices
	DeviceIDs []string
}

AllocatedDeviceResource captures a set of allocated devices.

func (*AllocatedDeviceResource) Add

func (a *AllocatedDeviceResource) Add(delta *AllocatedDeviceResource)

func (*AllocatedDeviceResource) Copy

func (a *AllocatedDeviceResource) Copy() *AllocatedDeviceResource

func (*AllocatedDeviceResource) ID

func (a *AllocatedDeviceResource) ID() *DeviceIdTuple

type AllocatedDevices

type AllocatedDevices []*AllocatedDeviceResource

func (AllocatedDevices) Index

func (a AllocatedDevices) Index(d *AllocatedDeviceResource) int

Index finds the matching index using the passed device. If not found, -1 is returned.

type AllocatedMemoryResources

type AllocatedMemoryResources struct {
	MemoryMB int64
}

AllocatedMemoryResources captures the allocated memory resources.

func (*AllocatedMemoryResources) Add

func (a *AllocatedMemoryResources) Add(delta *AllocatedMemoryResources)

func (*AllocatedMemoryResources) Max

func (a *AllocatedMemoryResources) Max(other *AllocatedMemoryResources)

func (*AllocatedMemoryResources) Subtract

func (a *AllocatedMemoryResources) Subtract(delta *AllocatedMemoryResources)

type AllocatedPortMapping

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

type AllocatedPorts

type AllocatedPorts []AllocatedPortMapping

func (AllocatedPorts) Get

func (p AllocatedPorts) Get(label string) (AllocatedPortMapping, bool)

type AllocatedResources

type AllocatedResources struct {
	// Tasks is a mapping of task name to the resources for the task.
	Tasks          map[string]*AllocatedTaskResources
	TaskLifecycles map[string]*TaskLifecycleConfig

	// Shared is the set of resource that are shared by all tasks in the group.
	Shared AllocatedSharedResources
}

AllocatedResources is the set of resources to be used by an allocation.

func NodeResourcesToAllocatedResources

func NodeResourcesToAllocatedResources(n *NodeResources) *AllocatedResources

NodeResourcesToAllocatedResources converts a node resources to an allocated resources. The task name used is "web" and network is omitted. This is useful when trying to make an allocation fill an entire node.

func (*AllocatedResources) Comparable

func (a *AllocatedResources) Comparable() *ComparableResources

Comparable returns a comparable version of the allocations allocated resources. This conversion can be lossy so care must be taken when using it.

func (*AllocatedResources) Copy

func (a *AllocatedResources) Copy() *AllocatedResources

func (*AllocatedResources) OldTaskResources

func (a *AllocatedResources) OldTaskResources() map[string]*Resources

OldTaskResources returns the pre-0.9.0 map of task resources

type AllocatedSharedResources

type AllocatedSharedResources struct {
	Networks Networks
	DiskMB   int64
	Ports    AllocatedPorts
}

AllocatedSharedResources are the set of resources allocated to a task group.

func (*AllocatedSharedResources) Add

func (a *AllocatedSharedResources) Add(delta *AllocatedSharedResources)

func (*AllocatedSharedResources) Canonicalize

func (a *AllocatedSharedResources) Canonicalize()

func (AllocatedSharedResources) Copy

func (a AllocatedSharedResources) Copy() AllocatedSharedResources

func (*AllocatedSharedResources) Subtract

func (a *AllocatedSharedResources) Subtract(delta *AllocatedSharedResources)

type AllocatedTaskResources

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

AllocatedTaskResources are the set of resources allocated to a task.

func (*AllocatedTaskResources) Add

func (a *AllocatedTaskResources) Add(delta *AllocatedTaskResources)

func (*AllocatedTaskResources) Comparable

func (a *AllocatedTaskResources) Comparable() *ComparableResources

Comparable turns AllocatedTaskResources into ComparableResources as a helper step in preemption

func (*AllocatedTaskResources) Copy

func (a *AllocatedTaskResources) Copy() *AllocatedTaskResources

func (*AllocatedTaskResources) Max

func (a *AllocatedTaskResources) Max(other *AllocatedTaskResources)

func (*AllocatedTaskResources) NetIndex

func (a *AllocatedTaskResources) NetIndex(n *NetworkResource) int

NetIndex finds the matching net index using device name

func (*AllocatedTaskResources) Subtract

func (a *AllocatedTaskResources) Subtract(delta *AllocatedTaskResources)

Subtract only subtracts CPU and Memory resources. Network utilization is managed separately in NetworkIndex

type Allocation

type Allocation struct {

	// ID of the allocation (UUID)
	ID string

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

	// ID of the evaluation that generated this allocation
	EvalID string

	// Name is a logical name of the allocation.
	Name string

	// NodeID is the node this is being placed on
	NodeID string

	// NodeName is the name of the node this is being placed on.
	NodeName string

	// Job is the parent job of the task group being allocated.
	// This is copied at allocation time to avoid issues if the job
	// definition is updated.
	JobID string
	Job   *Job

	// TaskGroup is the name of the task group that should be run
	TaskGroup string

	// COMPAT(0.11): Remove in 0.11
	// Resources is the total set of resources allocated as part
	// of this allocation of the task group. Dynamic ports will be set by
	// the scheduler.
	Resources *Resources

	// SharedResources are the resources that are shared by all the tasks in an
	// allocation
	// Deprecated: use AllocatedResources.Shared instead.
	// Keep field to allow us to handle upgrade paths from old versions
	SharedResources *Resources

	// TaskResources is the set of resources allocated to each
	// task. These should sum to the total Resources. Dynamic ports will be
	// set by the scheduler.
	// Deprecated: use AllocatedResources.Tasks instead.
	// Keep field to allow us to handle upgrade paths from old versions
	TaskResources map[string]*Resources

	// AllocatedResources is the total resources allocated for the task group.
	AllocatedResources *AllocatedResources

	// Metrics associated with this allocation
	Metrics *AllocMetric

	// Desired Status of the allocation on the client
	DesiredStatus string

	// DesiredStatusDescription is meant to provide more human useful information
	DesiredDescription string

	// DesiredTransition is used to indicate that a state transition
	// is desired for a given reason.
	DesiredTransition DesiredTransition

	// Status of the allocation on the client
	ClientStatus string

	// ClientStatusDescription is meant to provide more human useful information
	ClientDescription string

	// TaskStates stores the state of each task,
	TaskStates map[string]*TaskState

	// AllocStates track meta data associated with changes to the state of the whole allocation, like becoming lost
	AllocStates []*AllocState

	// PreviousAllocation is the allocation that this allocation is replacing
	PreviousAllocation string

	// NextAllocation is the allocation that this allocation is being replaced by
	NextAllocation string

	// DeploymentID identifies an allocation as being created from a
	// particular deployment
	DeploymentID string

	// DeploymentStatus captures the status of the allocation as part of the
	// given deployment
	DeploymentStatus *AllocDeploymentStatus

	// RescheduleTrackers captures details of previous reschedule attempts of the allocation
	RescheduleTracker *RescheduleTracker

	// FollowupEvalID captures a follow up evaluation created to handle a failed allocation
	// that can be rescheduled in the future
	FollowupEvalID string

	// PreemptedAllocations captures IDs of any allocations that were preempted
	// in order to place this allocation
	PreemptedAllocations []string

	// PreemptedByAllocation tracks the alloc ID of the allocation that caused this allocation
	// to stop running because it got preempted
	PreemptedByAllocation string

	// Raft Indexes
	CreateIndex uint64
	ModifyIndex uint64

	// AllocModifyIndex is not updated when the client updates allocations. This
	// lets the client pull only the allocs updated by the server.
	AllocModifyIndex uint64

	// CreateTime is the time the allocation has finished scheduling and been
	// verified by the plan applier.
	CreateTime int64

	// ModifyTime is the time the allocation was last updated.
	ModifyTime int64
	// contains filtered or unexported fields
}

Allocation is used to allocate the placement of a task group to a node.

func FilterTerminalAllocs

func FilterTerminalAllocs(allocs []*Allocation) ([]*Allocation, map[string]*Allocation)

FilterTerminalAllocs filters out all allocations in a terminal state and returns the latest terminal allocations

func MockAlloc

func MockAlloc() *Allocation

func RemoveAllocs

func RemoveAllocs(alloc []*Allocation, remove []*Allocation) []*Allocation

RemoveAllocs is used to remove any allocs with the given IDs from the list of allocations

func (*Allocation) AllocationDiff

func (a *Allocation) AllocationDiff() *AllocationDiff

AllocationDiff converts an Allocation type to an AllocationDiff type If at any time, modification are made to AllocationDiff so that an Allocation can no longer be safely converted to AllocationDiff, this method should be changed accordingly.

func (*Allocation) AppendState

func (a *Allocation) AppendState(field AllocStateField, value string)

AppendState creates and appends an AllocState entry recording the time of the state transition. Used to mark the transition to lost

func (*Allocation) Canonicalize

func (a *Allocation) Canonicalize()

Canonicalize Allocation to ensure fields are initialized to the expectations of this version of Nomad. Should be called when restoring persisted Allocations or receiving Allocations from Nomad agents potentially on an older version of Nomad.

func (*Allocation) ClientTerminalStatus

func (a *Allocation) ClientTerminalStatus() bool

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

func (*Allocation) ComparableResources

func (a *Allocation) ComparableResources() *ComparableResources

COMPAT(0.11): Remove in 0.11 ComparableResources returns the resources on the allocation handling upgrade paths. After 0.11 calls to this should be replaced with: alloc.AllocatedResources.Comparable()

func (*Allocation) Copy

func (a *Allocation) Copy() *Allocation

Copy provides a copy of the allocation and deep copies the job

func (*Allocation) CopySkipJob

func (a *Allocation) CopySkipJob() *Allocation

CopySkipJob provides a copy of the allocation but doesn't deep copy the job

func (*Allocation) Index

func (a *Allocation) Index() uint

Index returns the index of the allocation. If the allocation is from a task group with count greater than 1, there will be multiple allocations for it.

func (*Allocation) LastEventTime

func (a *Allocation) LastEventTime() time.Time

LastEventTime is the time of the last task event in the allocation. It is used to determine allocation failure time. If the FinishedAt field is not set, the alloc's modify time is used

func (*Allocation) LookupTask

func (a *Allocation) LookupTask(name string) *Task

LookupTask by name from the Allocation. Returns nil if the Job is not set, the TaskGroup does not exist, or the task name cannot be found.

func (*Allocation) NextDelay

func (a *Allocation) NextDelay() time.Duration

NextDelay returns a duration after which the allocation can be rescheduled. It is calculated according to the delay function and previous reschedule attempts.

func (*Allocation) NextRescheduleTime

func (a *Allocation) NextRescheduleTime() (time.Time, bool)

NextRescheduleTime returns a time on or after which the allocation is eligible to be rescheduled, and whether the next reschedule time is within policy's interval if the policy doesn't allow unlimited reschedules

func (*Allocation) RanSuccessfully

func (a *Allocation) RanSuccessfully() bool

RanSuccessfully returns whether the client has ran the allocation and all tasks finished successfully. Critically this function returns whether the allocation has ran to completion and not just that the alloc has converged to its desired state. That is to say that a batch allocation must have finished with exit code 0 on all task groups. This doesn't really have meaning on a non-batch allocation because a service and system allocation should not finish.

func (*Allocation) RescheduleEligible

func (a *Allocation) RescheduleEligible(reschedulePolicy *ReschedulePolicy, failTime time.Time) bool

RescheduleEligible returns if the allocation is eligible to be rescheduled according to its ReschedulePolicy and the current state of its reschedule trackers

func (*Allocation) ReschedulePolicy

func (a *Allocation) ReschedulePolicy() *ReschedulePolicy

ReschedulePolicy returns the reschedule policy based on the task group

func (*Allocation) ServerTerminalStatus

func (a *Allocation) ServerTerminalStatus() bool

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

func (*Allocation) SetEventDisplayMessages

func (a *Allocation) SetEventDisplayMessages()

SetEventDisplayMessage populates the display message if its not already set, a temporary fix to handle old allocations that don't have it. This method will be removed in a future release.

func (*Allocation) SetStop

func (a *Allocation) SetStop(clientStatus, clientDesc string)

SetStopped updates the allocation in place to a DesiredStatus stop, with the ClientStatus

func (*Allocation) ShouldClientStop

func (a *Allocation) ShouldClientStop() bool

ShouldClientStop tests an alloc for StopAfterClientDisconnect configuration

func (*Allocation) ShouldMigrate

func (a *Allocation) ShouldMigrate() bool

ShouldMigrate returns if the allocation needs data migration

func (*Allocation) ShouldReschedule

func (a *Allocation) ShouldReschedule(reschedulePolicy *ReschedulePolicy, failTime time.Time) bool

ShouldReschedule returns if the allocation is eligible to be rescheduled according to its status and ReschedulePolicy given its failure time

func (*Allocation) Stub

func (a *Allocation) Stub() *AllocListStub

Stub returns a list stub for the allocation

func (*Allocation) TerminalStatus

func (a *Allocation) TerminalStatus() bool

TerminalStatus returns if the desired or actual status is terminal and will no longer transition.

func (*Allocation) Terminated

func (a *Allocation) Terminated() bool

Terminated returns if the allocation is in a terminal state on a client.

func (*Allocation) WaitClientStop

func (a *Allocation) WaitClientStop() time.Time

WaitClientStop uses the reschedule delay mechanism to block rescheduling until StopAfterClientDisconnect's block interval passes

type AllocationDiff

type AllocationDiff Allocation

AllocationDiff is another named type for Allocation (to use the same fields), which is used to represent the delta for an Allocation. If you need a method defined on the al

type AllocsGetRequest

type AllocsGetRequest struct {
	AllocIDs []string
	QueryOptions
}

AllocsGetRequest is used to query a set of allocations

type AllocsGetResponse

type AllocsGetResponse struct {
	Allocs []*Allocation
	QueryMeta
}

AllocsGetResponse is used to return a set of allocations

type ApplyDeploymentAllocHealthRequest

type ApplyDeploymentAllocHealthRequest struct {
	DeploymentAllocHealthRequest

	// Timestamp is the timestamp to use when setting the allocations health.
	Timestamp time.Time

	// An optional field to update the status of a deployment
	DeploymentUpdate *DeploymentStatusUpdate

	// Job is used to optionally upsert a job. This is used when setting the
	// allocation health results in a deployment failure and the deployment
	// auto-reverts to the latest stable job.
	Job *Job

	// An optional evaluation to create after promoting the canaries
	Eval *Evaluation
}

ApplyDeploymentAllocHealthRequest is used to apply an alloc health request via Raft

type ApplyDeploymentPromoteRequest

type ApplyDeploymentPromoteRequest struct {
	DeploymentPromoteRequest

	// An optional evaluation to create after promoting the canaries
	Eval *Evaluation
}

ApplyDeploymentPromoteRequest is used to apply a promotion request via Raft

type ApplyPlanResultsRequest

type ApplyPlanResultsRequest struct {
	// AllocUpdateRequest holds the allocation updates to be made by the
	// scheduler.
	AllocUpdateRequest

	// Deployment is the deployment created or updated as a result of a
	// scheduling event.
	Deployment *Deployment

	// DeploymentUpdates is a set of status updates to apply to the given
	// deployments. This allows the scheduler to cancel any unneeded deployment
	// because the job is stopped or the update block is removed.
	DeploymentUpdates []*DeploymentStatusUpdate

	// EvalID is the eval ID of the plan being applied. The modify index of the
	// evaluation is updated as part of applying the plan to ensure that subsequent
	// scheduling events for the same job will wait for the index that last produced
	// state changes. This is necessary for blocked evaluations since they can be
	// processed many times, potentially making state updates, without the state of
	// the evaluation itself being updated.
	EvalID string

	// COMPAT 0.11
	// NodePreemptions is a slice of allocations from other lower priority jobs
	// that are preempted. Preempted allocations are marked as evicted.
	// Deprecated: Replaced with AllocsPreempted which contains only the diff
	NodePreemptions []*Allocation

	// AllocsPreempted is a slice of allocation diffs from other lower priority jobs
	// that are preempted. Preempted allocations are marked as evicted.
	AllocsPreempted []*AllocationDiff

	// PreemptionEvals is a slice of follow up evals for jobs whose allocations
	// have been preempted to place allocs in this plan
	PreemptionEvals []*Evaluation
}

ApplyPlanResultsRequest is used by the planner to apply a Raft transaction committing the result of a plan.

type AutopilotConfig

type AutopilotConfig struct {
	// CleanupDeadServers controls whether to remove dead servers when a new
	// server is added to the Raft peers.
	CleanupDeadServers bool

	// 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

	// 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 required in a cluster
	// before autopilot can prune dead servers.
	MinQuorum uint

	// (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/ModifyIndex store the create/modify indexes of this configuration.
	CreateIndex uint64
	ModifyIndex uint64
}

AutopilotConfig is the internal config for the Autopilot mechanism.

type AutopilotSetConfigRequest

type AutopilotSetConfigRequest struct {
	// Datacenter is the target this request is intended for.
	Datacenter string

	// Config is the new Autopilot configuration to use.
	Config AutopilotConfig

	// CAS controls whether to use check-and-set semantics for this request.
	CAS bool

	// WriteRequest holds the ACL token to go along with this request.
	WriteRequest
}

AutopilotSetConfigRequest is used by the Operator endpoint to update the current Autopilot configuration of the cluster.

func (*AutopilotSetConfigRequest) RequestDatacenter

func (op *AutopilotSetConfigRequest) RequestDatacenter() string

RequestDatacenter returns the datacenter for a given request.

type BatchFuture

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

BatchFuture is used to wait on a batch update to complete

func NewBatchFuture

func NewBatchFuture() *BatchFuture

NewBatchFuture creates a new batch future

func (*BatchFuture) Error

func (b *BatchFuture) Error() error

Error is used to return the error of the batch, only after Wait()

func (*BatchFuture) Index

func (b *BatchFuture) Index() uint64

Index is used to return the index of the batch, only after Wait()

func (*BatchFuture) Respond

func (b *BatchFuture) Respond(index uint64, err error)

Respond is used to unblock the future

func (*BatchFuture) Wait

func (b *BatchFuture) Wait() error

Wait is used to block for the future to complete and returns the error

func (*BatchFuture) WaitCh

func (b *BatchFuture) WaitCh() <-chan struct{}

WaitCh is used to block for the future to complete

type BatchNodeUpdateDrainRequest

type BatchNodeUpdateDrainRequest struct {
	// Updates is a mapping of nodes to their updated drain strategy
	Updates map[string]*DrainUpdate

	// NodeEvents is a mapping of the node to the event to add to the node
	NodeEvents map[string]*NodeEvent

	// UpdatedAt represents server time of receiving request
	UpdatedAt int64

	WriteRequest
}

BatchNodeUpdateDrainRequest is used for updating the drain strategy for a batch of nodes

type Bitmap

type Bitmap []byte

Bitmap is a simple uncompressed bitmap

func NewBitmap

func NewBitmap(size uint) (Bitmap, error)

NewBitmap returns a bitmap with up to size indexes

func (Bitmap) Check

func (b Bitmap) Check(idx uint) bool

Check is used to check the given index of the bitmap

func (Bitmap) Clear

func (b Bitmap) Clear()

Clear is used to efficiently clear the bitmap

func (Bitmap) Copy

func (b Bitmap) Copy() (Bitmap, error)

Copy returns a copy of the Bitmap

func (Bitmap) IndexesInRange

func (b Bitmap) IndexesInRange(set bool, from, to uint) []int

IndexesInRange returns the indexes in which the values are either set or unset based on the passed parameter in the passed range

func (Bitmap) Set

func (b Bitmap) Set(idx uint)

Set is used to set the given index of the bitmap

func (Bitmap) Size

func (b Bitmap) Size() uint

Size returns the size of the bitmap

func (Bitmap) Unset

func (b Bitmap) Unset(idx uint)

Unset is used to unset the given index of the bitmap

type CSIControllerInfo

type CSIControllerInfo struct {
	// SupportsReadOnlyAttach is set to true when the controller returns the
	// ATTACH_READONLY capability.
	SupportsReadOnlyAttach 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 guaruntee that attached nodes will be returned
	// unless SupportsListVolumesAttachedNodes is also true.
	SupportsListVolumes bool

	// SupportsListVolumesAttachedNodes indicates whether the plugin will return
	// attached nodes data when making ListVolume RPCs
	SupportsListVolumesAttachedNodes bool
}

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

func (*CSIControllerInfo) Copy

func (c *CSIControllerInfo) Copy() *CSIControllerInfo

type CSIInfo

type CSIInfo struct {
	PluginID          string
	AllocID           string
	Healthy           bool
	HealthDescription string
	UpdateTime        time.Time

	Provider        string // vendor name from CSI GetPluginInfoResponse
	ProviderVersion string // vendor version from CSI GetPluginInfoResponse

	// RequiresControllerPlugin is set when the CSI Plugin returns the
	// CONTROLLER_SERVICE capability. When this is true, the volumes should not be
	// scheduled on this client until a matching controller plugin is available.
	RequiresControllerPlugin bool

	// RequiresTopologies is set when the CSI Plugin returns the
	// VOLUME_ACCESSIBLE_CONSTRAINTS capability. When this is true, we must
	// respect the Volume and Node Topology information.
	RequiresTopologies bool

	// CSI Specific metadata
	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.

func (*CSIInfo) Copy

func (c *CSIInfo) Copy() *CSIInfo

func (*CSIInfo) Equal

func (c *CSIInfo) Equal(o *CSIInfo) bool

func (*CSIInfo) IsController

func (c *CSIInfo) IsController() bool

func (*CSIInfo) IsNode

func (c *CSIInfo) IsNode() bool

func (*CSIInfo) SetHealthy

func (c *CSIInfo) SetHealthy(hs bool)

type CSIMountOptions

type CSIMountOptions struct {
	// FSType is an optional field that allows an operator to specify the type
	// of the filesystem.
	FSType string

	// 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
}

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

func (*CSIMountOptions) Copy

func (o *CSIMountOptions) Copy() *CSIMountOptions

func (*CSIMountOptions) GoString

func (v *CSIMountOptions) GoString() string

func (*CSIMountOptions) Merge

func (o *CSIMountOptions) Merge(p *CSIMountOptions)

func (*CSIMountOptions) String

func (v *CSIMountOptions) String() string

type CSINodeInfo

type CSINodeInfo struct {
	// ID is the identity of a given nomad client as observed by the storage
	// provider.
	ID string

	// MaxVolumes is the maximum number of volumes that can be attached to the
	// current host via this provider.
	// If 0 then unlimited volumes may be attached.
	MaxVolumes int64

	// AccessibleTopology specifies where (regions, zones, racks, etc.) the node is
	// accessible from within the storage provider.
	//
	// A plugin that returns this field MUST also set the `RequiresTopologies`
	// property.
	//
	// This field is OPTIONAL. If it is not specified, then we assume that the
	// the node is not subject to any topological constraint, and MAY
	// schedule workloads that reference any volume V, such that there are
	// no topological constraints declared for V.
	//
	// Example 1:
	//   accessible_topology =
	//     {"region": "R1", "zone": "Z2"}
	// Indicates the node exists within the "region" "R1" and the "zone"
	// "Z2" within the storage provider.
	AccessibleTopology *CSITopology

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

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

func (*CSINodeInfo) Copy

func (n *CSINodeInfo) Copy() *CSINodeInfo

type CSIPlugin

type CSIPlugin struct {
	ID                 string
	Provider           string // the vendor name from CSI GetPluginInfoResponse
	Version            string // the vendor verson from  CSI GetPluginInfoResponse
	ControllerRequired bool

	// Map Node.IDs to fingerprint results, split by type. Monolith type plugins have
	// both sets of fingerprinting results.
	Controllers map[string]*CSIInfo
	Nodes       map[string]*CSIInfo

	// Allocations are populated by denormalize to show running allocations
	Allocations []*AllocListStub

	// Jobs are populated to by job update to support expected counts and the UI
	ControllerJobs JobDescriptions
	NodeJobs       JobDescriptions

	// Cache the count of healthy plugins
	ControllersHealthy  int
	ControllersExpected int
	NodesHealthy        int
	NodesExpected       int

	CreateIndex uint64
	ModifyIndex uint64
}

CSIPlugin collects fingerprint info context for the plugin for clients

func NewCSIPlugin

func NewCSIPlugin(id string, index uint64) *CSIPlugin

NewCSIPlugin creates the plugin struct. No side-effects

func (*CSIPlugin) AddJob

func (p *CSIPlugin) AddJob(job *Job, summary *JobSummary)

AddJob adds a job to the plugin and increments expected

func (*CSIPlugin) AddPlugin

func (p *CSIPlugin) AddPlugin(nodeID string, info *CSIInfo) error

AddPlugin adds a single plugin running on the node. Called from state.NodeUpdate in a transaction

func (*CSIPlugin) Copy

func (p *CSIPlugin) Copy() *CSIPlugin

func (*CSIPlugin) DeleteAlloc

func (p *CSIPlugin) DeleteAlloc(allocID, nodeID string) error

DeleteAlloc removes the fingerprint info for the allocation

func (*CSIPlugin) DeleteJob

func (p *CSIPlugin) DeleteJob(job *Job, summary *JobSummary)

DeleteJob removes the job from the plugin and decrements expected

func (*CSIPlugin) DeleteNode

func (p *CSIPlugin) DeleteNode(nodeID string) error

DeleteNode removes all plugins from the node. Called from state.DeleteNode in a transaction

func (*CSIPlugin) DeleteNodeForType

func (p *CSIPlugin) DeleteNodeForType(nodeID string, pluginType CSIPluginType) error

DeleteNodeForType deletes a client node from the list of controllers or node instance of a plugin. Called from deleteJobFromPlugin during job deregistration, in a transaction

func (*CSIPlugin) IsEmpty

func (p *CSIPlugin) IsEmpty() bool

func (*CSIPlugin) Stub

func (p *CSIPlugin) Stub() *CSIPluginListStub

func (*CSIPlugin) UpdateExpectedWithJob

func (p *CSIPlugin) UpdateExpectedWithJob(job *Job, summary *JobSummary, terminal bool)

UpdateExpectedWithJob maintains the expected instance count we use the summary to add non-allocation expected counts

type CSIPluginDeleteRequest

type CSIPluginDeleteRequest struct {
	ID string
	QueryOptions
}

type CSIPluginDeleteResponse

type CSIPluginDeleteResponse struct {
	QueryMeta
}

type CSIPluginGetRequest

type CSIPluginGetRequest struct {
	ID string
	QueryOptions
}

type CSIPluginGetResponse

type CSIPluginGetResponse struct {
	Plugin *CSIPlugin
	QueryMeta
}

type CSIPluginListRequest

type CSIPluginListRequest struct {
	QueryOptions
}

type CSIPluginListResponse

type CSIPluginListResponse struct {
	Plugins []*CSIPluginListStub
	QueryMeta
}

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 CSISecrets

type CSISecrets map[string]string

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

func (*CSISecrets) GoString

func (s *CSISecrets) GoString() string

func (*CSISecrets) String

func (s *CSISecrets) String() string

type CSITopology

type CSITopology struct {
	Segments map[string]string
}

CSITopology is a map of topological domains to topological segments. A topological domain is a sub-division of a cluster, like "region", "zone", "rack", etc.

According to CSI, there are a few requirements for the keys within this map: - Valid keys have two segments: an OPTIONAL prefix and name, separated

by a slash (/), for example: "com.company.example/zone".

- The key name segment is REQUIRED. The prefix is OPTIONAL. - The key name MUST be 63 characters or less, begin and end with an

alphanumeric character ([a-z0-9A-Z]), and contain only dashes (-),
underscores (_), dots (.), or alphanumerics in between, for example
"zone".

- The key prefix MUST be 63 characters or less, begin and end with a

lower-case alphanumeric character ([a-z0-9]), contain only
dashes (-), dots (.), or lower-case alphanumerics in between, and
follow domain name notation format
(https://tools.ietf.org/html/rfc1035#section-2.3.1).

- The key prefix SHOULD include the plugin's host company name and/or

the plugin name, to minimize the possibility of collisions with keys
from other plugins.

- If a key prefix is specified, it MUST be identical across all

topology keys returned by the SP (across all RPCs).

- Keys MUST be case-insensitive. Meaning the keys "Zone" and "zone"

MUST not both exist.

- Each value (topological segment) MUST contain 1 or more strings. - Each string MUST be 63 characters or less and begin and end with an

alphanumeric character with '-', '_', '.', or alphanumerics in
between.

However, Nomad applies lighter restrictions to these, as they are already only referenced by plugin within the scheduler and as such collisions and related concerns are less of an issue. We may implement these restrictions in the future.

func (*CSITopology) Copy

func (t *CSITopology) Copy() *CSITopology

func (*CSITopology) Equal

func (t *CSITopology) Equal(o *CSITopology) bool

type CSIVolListStub

type CSIVolListStub struct {
	ID                  string
	Namespace           string
	Name                string
	ExternalID          string
	Topologies          []*CSITopology
	AccessMode          CSIVolumeAccessMode
	AttachmentMode      CSIVolumeAttachmentMode
	CurrentReaders      int
	CurrentWriters      int
	Schedulable         bool
	PluginID            string
	Provider            string
	ControllersHealthy  int
	ControllersExpected int
	NodesHealthy        int
	NodesExpected       int
	CreateIndex         uint64
	ModifyIndex         uint64
}

CSIVolListStub is partial representation of a CSI Volume for inclusion in lists

type CSIVolume

type CSIVolume struct {
	// ID is a namespace unique URL safe identifier for the volume
	ID string
	// Name is a display name for the volume, not required to be unique
	Name string
	// ExternalID identifies the volume for the CSI interface, may be URL unsafe
	ExternalID     string
	Namespace      string
	Topologies     []*CSITopology
	AccessMode     CSIVolumeAccessMode
	AttachmentMode CSIVolumeAttachmentMode
	MountOptions   *CSIMountOptions
	Secrets        CSISecrets
	Parameters     map[string]string
	Context        map[string]string

	// Allocations, tracking claim status
	ReadAllocs  map[string]*Allocation // AllocID -> Allocation
	WriteAllocs map[string]*Allocation // AllocID -> Allocation

	ReadClaims  map[string]*CSIVolumeClaim // AllocID -> claim
	WriteClaims map[string]*CSIVolumeClaim // AllocID -> claim
	PastClaims  map[string]*CSIVolumeClaim // AllocID -> claim

	// Schedulable is true if all the denormalized plugin health fields are true, and the
	// volume has not been marked for garbage collection
	Schedulable         bool
	PluginID            string
	Provider            string
	ProviderVersion     string
	ControllerRequired  bool
	ControllersHealthy  int
	ControllersExpected int
	NodesHealthy        int
	NodesExpected       int
	ResourceExhausted   time.Time

	CreateIndex uint64
	ModifyIndex uint64
}

CSIVolume is the full representation of a CSI Volume

func NewCSIVolume

func NewCSIVolume(volumeID string, index uint64) *CSIVolume

NewCSIVolume creates the volume struct. No side-effects

func (*CSIVolume) Claim

func (v *CSIVolume) Claim(claim *CSIVolumeClaim, alloc *Allocation) error

Claim updates the allocations and changes the volume state

func (*CSIVolume) ClaimRead

func (v *CSIVolume) ClaimRead(claim *CSIVolumeClaim, alloc *Allocation) error

ClaimRead marks an allocation as using a volume read-only

func (*CSIVolume) ClaimRelease

func (v *CSIVolume) ClaimRelease(claim *CSIVolumeClaim) error

ClaimRelease is called when the allocation has terminated and already stopped using the volume

func (*CSIVolume) ClaimWrite

func (v *CSIVolume) ClaimWrite(claim *CSIVolumeClaim, alloc *Allocation) error

ClaimWrite marks an allocation as using a volume as a writer

func (*CSIVolume) Copy

func (v *CSIVolume) Copy() *CSIVolume

Copy returns a copy of the volume, which shares only the Topologies slice

func (*CSIVolume) Equal

func (v *CSIVolume) Equal(o *CSIVolume) bool

Equality by value

func (*CSIVolume) InUse

func (v *CSIVolume) InUse() bool

InUse tests whether any allocations are actively using the volume

func (*CSIVolume) ReadSchedulable

func (v *CSIVolume) ReadSchedulable() bool

func (*CSIVolume) RemoteID

func (v *CSIVolume) RemoteID() string

func (*CSIVolume) Stub

func (v *CSIVolume) Stub() *CSIVolListStub

func (*CSIVolume) Validate

func (v *CSIVolume) Validate() error

Validate validates the volume struct, returning all validation errors at once

func (*CSIVolume) WriteFreeClaims

func (v *CSIVolume) WriteFreeClaims() bool

WriteFreeClaims determines if there are any free write claims available

func (*CSIVolume) WriteSchedulable

func (v *CSIVolume) WriteSchedulable() bool

WriteSchedulable determines if the volume is schedulable for writes, considering only volume health

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.

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.

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

type CSIVolumeClaim

type CSIVolumeClaim struct {
	AllocationID   string
	NodeID         string
	ExternalNodeID string
	Mode           CSIVolumeClaimMode
	State          CSIVolumeClaimState
}

type CSIVolumeClaimBatchRequest

type CSIVolumeClaimBatchRequest struct {
	Claims []CSIVolumeClaimRequest
}

type CSIVolumeClaimMode

type CSIVolumeClaimMode int
const (
	CSIVolumeClaimRead CSIVolumeClaimMode = iota
	CSIVolumeClaimWrite
	CSIVolumeClaimRelease
)

type CSIVolumeClaimRequest

type CSIVolumeClaimRequest struct {
	VolumeID       string
	AllocationID   string
	NodeID         string
	ExternalNodeID string
	Claim          CSIVolumeClaimMode
	State          CSIVolumeClaimState
	WriteRequest
}

func (*CSIVolumeClaimRequest) ToClaim

func (req *CSIVolumeClaimRequest) ToClaim() *CSIVolumeClaim

type CSIVolumeClaimResponse

type CSIVolumeClaimResponse struct {
	// Opaque static publish properties of the volume. SP MAY use this
	// field to ensure subsequent `NodeStageVolume` or `NodePublishVolume`
	// calls calls have contextual information.
	// The contents of this field SHALL be opaque to nomad.
	// The contents of this field SHALL NOT be mutable.
	// The contents of this field SHALL be safe for the nomad to cache.
	// The contents of this field SHOULD NOT contain sensitive
	// information.
	// The contents of this field SHOULD NOT be used for uniquely
	// identifying a volume. The `volume_id` alone SHOULD be sufficient to
	// identify the volume.
	// This field is OPTIONAL and when present MUST be passed to
	// `NodeStageVolume` or `NodePublishVolume` calls on the client
	PublishContext map[string]string

	// Volume contains the expanded CSIVolume for use on the client after a Claim
	// has completed.
	Volume *CSIVolume

	QueryMeta
}

type CSIVolumeClaimState

type CSIVolumeClaimState int
const (
	CSIVolumeClaimStateTaken CSIVolumeClaimState = iota
	CSIVolumeClaimStateNodeDetached
	CSIVolumeClaimStateControllerDetached
	CSIVolumeClaimStateReadyToFree
)

type CSIVolumeDeregisterRequest

type CSIVolumeDeregisterRequest struct {
	VolumeIDs []string
	Force     bool
	WriteRequest
}

type CSIVolumeDeregisterResponse

type CSIVolumeDeregisterResponse struct {
	QueryMeta
}

type CSIVolumeGetRequest

type CSIVolumeGetRequest struct {
	ID string
	QueryOptions
}

type CSIVolumeGetResponse

type CSIVolumeGetResponse struct {
	Volume *CSIVolume
	QueryMeta
}

type CSIVolumeListRequest

type CSIVolumeListRequest struct {
	PluginID string
	NodeID   string
	QueryOptions
}

type CSIVolumeListResponse

type CSIVolumeListResponse struct {
	Volumes []*CSIVolListStub
	QueryMeta
}

type CSIVolumeRegisterRequest

type CSIVolumeRegisterRequest struct {
	Volumes []*CSIVolume
	WriteRequest
}

Request and response wrappers

type CSIVolumeRegisterResponse

type CSIVolumeRegisterResponse struct {
	QueryMeta
}

type CSIVolumeUnpublishRequest

type CSIVolumeUnpublishRequest struct {
	VolumeID string
	Claim    *CSIVolumeClaim
	WriteRequest
}

type CSIVolumeUnpublishResponse

type CSIVolumeUnpublishResponse struct {
	QueryMeta
}

type CheckRestart

type CheckRestart struct {
	Limit          int           // Restart task after this many unhealthy intervals
	Grace          time.Duration // Grace time to give tasks after starting to get healthy
	IgnoreWarnings bool          // If true treat checks in `warning` as passing
}

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

func (*CheckRestart) Copy

func (c *CheckRestart) Copy() *CheckRestart

func (*CheckRestart) Equals

func (c *CheckRestart) Equals(o *CheckRestart) bool

func (*CheckRestart) Validate

func (c *CheckRestart) Validate() error

type ClientHostNetworkConfig

type ClientHostNetworkConfig struct {
	Name          string `hcl:",key"`
	CIDR          string `hcl:"cidr"`
	Interface     string `hcl:"interface"`
	ReservedPorts string `hcl:"reserved_ports"`
}

type ClientHostVolumeConfig

type ClientHostVolumeConfig struct {
	Name     string `hcl:",key"`
	Path     string `hcl:"path"`
	ReadOnly bool   `hcl:"read_only"`
}

ClientHostVolumeConfig is used to configure access to host paths on a Nomad Client

func CopySliceClientHostVolumeConfig

func CopySliceClientHostVolumeConfig(s []*ClientHostVolumeConfig) []*ClientHostVolumeConfig

func HostVolumeSliceMerge

func HostVolumeSliceMerge(a, b []*ClientHostVolumeConfig) []*ClientHostVolumeConfig

func (*ClientHostVolumeConfig) Copy

func (p *ClientHostVolumeConfig) Copy() *ClientHostVolumeConfig

type ClusterMetadata

type ClusterMetadata struct {
	ClusterID  string
	CreateTime int64
}

ClusterMetadata is used to store per-cluster metadata.

type ComparableResources

type ComparableResources struct {
	Flattened AllocatedTaskResources
	Shared    AllocatedSharedResources
}

ComparableResources is the set of resources allocated to a task group but not keyed by Task, making it easier to compare.

func AllocsFit

func AllocsFit(node *Node, allocs []*Allocation, netIdx *NetworkIndex, checkDevices bool) (bool, string, *ComparableResources, error)

AllocsFit checks if a given set of allocations will fit on a node. The netIdx can optionally be provided if its already been computed. If the netIdx is provided, it is assumed that the client has already ensured there are no collisions. If checkDevices is set to true, we check if there is a device oversubscription.

func (*ComparableResources) Add

func (c *ComparableResources) Add(delta *ComparableResources)

func (*ComparableResources) Copy

func (c *ComparableResources) Copy() *ComparableResources

func (*ComparableResources) NetIndex

func (c *ComparableResources) NetIndex(n *NetworkResource) int

allocated finds the matching net index using device name

func (*ComparableResources) Subtract

func (c *ComparableResources) Subtract(delta *ComparableResources)

func (*ComparableResources) Superset

func (c *ComparableResources) Superset(other *ComparableResources) (bool, string)

Superset checks if one set of resources is a superset of another. This ignores network resources, and the NetworkIndex should be used for that.

type Constraint

type Constraint struct {
	LTarget string // Left-hand target
	RTarget string // Right-hand target
	Operand string // Constraint operand (<=, <, =, !=, >, >=), contains, near
	// contains filtered or unexported fields
}

Constraints are used to restrict placement options.

func CopySliceConstraints

func CopySliceConstraints(s []*Constraint) []*Constraint

func EscapedConstraints

func EscapedConstraints(constraints []*Constraint) []*Constraint

EscapedConstraints takes a set of constraints and returns the set that escapes computed node classes.

func (*Constraint) Copy

func (c *Constraint) Copy() *Constraint

func (*Constraint) Equal

func (c *Constraint) Equal(o *Constraint) bool

func (*Constraint) Equals

func (c *Constraint) Equals(o *Constraint) bool

Equal checks if two constraints are equal

func (*Constraint) String

func (c *Constraint) String() string

func (*Constraint) Validate

func (c *Constraint) Validate() error

type Constraints

type Constraints []*Constraint

func (*Constraints) Equals

func (xs *Constraints) Equals(ys *Constraints) bool

Equals compares Constraints as a set

type ConsulConnect

type ConsulConnect struct {
	// Native indicates whether the service is Consul Connect Native enabled.
	Native bool

	// SidecarService is non-nil if a service requires a sidecar.
	SidecarService *ConsulSidecarService

	// SidecarTask is non-nil if sidecar overrides are set
	SidecarTask *SidecarTask

	// Gateway is a Consul Connect Gateway Proxy.
	Gateway *ConsulGateway
}

ConsulConnect represents a Consul Connect jobspec stanza.

func (*ConsulConnect) Copy

func (c *ConsulConnect) Copy() *ConsulConnect

Copy the stanza recursively. Returns nil if nil.

func (*ConsulConnect) Equals

func (c *ConsulConnect) Equals(o *ConsulConnect) bool

Equals returns true if the structs are recursively equal.

func (*ConsulConnect) HasSidecar

func (c *ConsulConnect) HasSidecar() bool

HasSidecar checks if a sidecar task is configured.

func (*ConsulConnect) IsGateway

func (c *ConsulConnect) IsGateway() bool

func (*ConsulConnect) IsNative

func (c *ConsulConnect) IsNative() bool

IsNative checks if the service is connect native.

func (*ConsulConnect) Validate

func (c *ConsulConnect) Validate() error

Validate that the Connect block represents exactly one of: - Connect non-native service sidecar proxy - Connect native service - Connect gateway (any type)

type ConsulExposeConfig

type ConsulExposeConfig struct {
	// Use json tag to match with field name in api/
	Paths []ConsulExposePath `json:"Path"`
}

ExposeConfig represents a Consul Connect expose jobspec stanza.

func (*ConsulExposeConfig) Copy

func (e *ConsulExposeConfig) Copy() *ConsulExposeConfig

Copy the stanza. Returns nil if e is nil.

func (*ConsulExposeConfig) Equals

func (e *ConsulExposeConfig) Equals(o *ConsulExposeConfig) bool

Equals returns true if the structs are recursively equal.

type ConsulExposePath

type ConsulExposePath struct {
	Path          string
	Protocol      string
	LocalPathPort int
	ListenerPort  string
}

type ConsulGateway

type ConsulGateway struct {
	// Proxy is used to configure the Envoy instance acting as the gateway.
	Proxy *ConsulGatewayProxy

	// Ingress represents the Consul Configuration Entry for an Ingress Gateway.
	Ingress *ConsulIngressConfigEntry
}

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

func (*ConsulGateway) Copy

func (g *ConsulGateway) Copy() *ConsulGateway

func (*ConsulGateway) Equals

func (g *ConsulGateway) Equals(o *ConsulGateway) bool

func (*ConsulGateway) Validate

func (g *ConsulGateway) Validate() error

type ConsulGatewayBindAddress

type ConsulGatewayBindAddress struct {
	Address string
	Port    int
}

ConsulGatewayBindAddress is equivalent to Consul's api/catalog.go ServiceAddress struct, as this is used to encode values to pass along to Envoy (i.e. via JSON encoding).

func (*ConsulGatewayBindAddress) Copy

func (a *ConsulGatewayBindAddress) Copy() *ConsulGatewayBindAddress

func (*ConsulGatewayBindAddress) Equals

func (a *ConsulGatewayBindAddress) Equals(o *ConsulGatewayBindAddress) bool

func (*ConsulGatewayBindAddress) Validate

func (a *ConsulGatewayBindAddress) Validate() error

type ConsulGatewayProxy

type ConsulGatewayProxy struct {
	ConnectTimeout                  *time.Duration
	EnvoyGatewayBindTaggedAddresses bool
	EnvoyGatewayBindAddresses       map[string]*ConsulGatewayBindAddress
	EnvoyGatewayNoDefaultBind       bool
	Config                          map[string]interface{}
}

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

func (p *ConsulGatewayProxy) Copy() *ConsulGatewayProxy

func (*ConsulGatewayProxy) Equals

func (p *ConsulGatewayProxy) Equals(o *ConsulGatewayProxy) bool

func (*ConsulGatewayProxy) Validate

func (p *ConsulGatewayProxy) Validate() error

type ConsulGatewayTLSConfig

type ConsulGatewayTLSConfig struct {
	Enabled bool
}

ConsulGatewayTLSConfig is used to configure TLS for a gateway.

func (*ConsulGatewayTLSConfig) Copy

func (c *ConsulGatewayTLSConfig) Copy() *ConsulGatewayTLSConfig

func (*ConsulGatewayTLSConfig) Equals

func (c *ConsulGatewayTLSConfig) Equals(o *ConsulGatewayTLSConfig) bool

type ConsulIngressConfigEntry

type ConsulIngressConfigEntry struct {
	TLS       *ConsulGatewayTLSConfig
	Listeners []*ConsulIngressListener
}

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

func (e *ConsulIngressConfigEntry) Copy() *ConsulIngressConfigEntry

func (*ConsulIngressConfigEntry) Equals

func (e *ConsulIngressConfigEntry) Equals(o *ConsulIngressConfigEntry) bool

func (*ConsulIngressConfigEntry) Validate

func (e *ConsulIngressConfigEntry) Validate() error

type ConsulIngressListener

type ConsulIngressListener struct {
	Port     int
	Protocol string
	Services []*ConsulIngressService
}

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

func (*ConsulIngressListener) Copy

func (l *ConsulIngressListener) Copy() *ConsulIngressListener

func (*ConsulIngressListener) Equals

func (l *ConsulIngressListener) Equals(o *ConsulIngressListener) bool

func (*ConsulIngressListener) Validate

func (l *ConsulIngressListener) Validate() error

type ConsulIngressService

type ConsulIngressService struct {
	Name string

	Hosts []string
}

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

func (*ConsulIngressService) Copy

func (s *ConsulIngressService) Copy() *ConsulIngressService

func (*ConsulIngressService) Equals

func (s *ConsulIngressService) Equals(o *ConsulIngressService) bool

func (*ConsulIngressService) Validate

func (s *ConsulIngressService) Validate(isHTTP bool) error

type ConsulProxy

type ConsulProxy struct {

	// LocalServiceAddress is the address the local service binds to.
	// Usually 127.0.0.1 it is useful to customize in clusters with mixed
	// Connect and non-Connect services.
	LocalServiceAddress string

	// LocalServicePort is the port the local service binds to. Usually
	// the same as the parent service's port, it is useful to customize
	// in clusters with mixed Connect and non-Connect services
	LocalServicePort int

	// Upstreams configures the upstream services this service intends to
	// connect to.
	Upstreams []ConsulUpstream

	// Expose configures the consul proxy.expose stanza to "open up" endpoints
	// used by task-group level service checks using HTTP or gRPC protocols.
	//
	// Use json tag to match with field name in api/
	Expose *ConsulExposeConfig `json:"ExposeConfig"`

	// Config is a proxy configuration. It is opaque to Nomad and passed
	// directly to Consul.
	Config map[string]interface{}
}

ConsulProxy represents a Consul Connect sidecar proxy jobspec stanza.

func (*ConsulProxy) Copy

func (p *ConsulProxy) Copy() *ConsulProxy

Copy the stanza recursively. Returns nil if nil.

func (*ConsulProxy) Equals

func (p *ConsulProxy) Equals(o *ConsulProxy) bool

Equals returns true if the structs are recursively equal.

type ConsulSidecarService

type ConsulSidecarService struct {
	// Tags are optional service tags that get registered with the sidecar service
	// in Consul. If unset, the sidecar service inherits the parent service tags.
	Tags []string

	// Port is the service's port that the sidecar will connect to. May be
	// a port label or a literal port number.
	Port string

	// Proxy stanza defining the sidecar proxy configuration.
	Proxy *ConsulProxy
}

ConsulSidecarService represents a Consul Connect SidecarService jobspec stanza.

func (*ConsulSidecarService) Copy

func (s *ConsulSidecarService) Copy() *ConsulSidecarService

Copy the stanza recursively. Returns nil if nil.

func (*ConsulSidecarService) Equals

func (s *ConsulSidecarService) Equals(o *ConsulSidecarService) bool

Equals returns true if the structs are recursively equal.

func (*ConsulSidecarService) HasUpstreams

func (s *ConsulSidecarService) HasUpstreams() bool

HasUpstreams checks if the sidecar service has any upstreams configured

type ConsulUpstream

type ConsulUpstream struct {
	// DestinationName is the name of the upstream service.
	DestinationName string

	// LocalBindPort is the port the proxy will receive connections for the
	// upstream on.
	LocalBindPort int
}

ConsulUpstream represents a Consul Connect upstream jobspec stanza.

func (*ConsulUpstream) Copy

func (u *ConsulUpstream) Copy() *ConsulUpstream

Copy the stanza recursively. Returns nil if u is nil.

func (*ConsulUpstream) Equals

func (u *ConsulUpstream) Equals(o *ConsulUpstream) bool

Equals returns true if the structs are recursively equal.

type Context

type Context string

Context defines the scope in which a search for Nomad object operates, and is also used to query the matching index value for this context

const (
	Allocs      Context = "allocs"
	Deployments Context = "deployment"
	Evals       Context = "evals"
	Jobs        Context = "jobs"
	Nodes       Context = "nodes"
	Namespaces  Context = "namespaces"
	Quotas      Context = "quotas"
	All         Context = "all"
	Plugins     Context = "plugins"
	Volumes     Context = "volumes"
)

type DNSConfig

type DNSConfig struct {
	Servers  []string
	Searches []string
	Options  []string
}

func (*DNSConfig) Diff

func (c *DNSConfig) Diff(other *DNSConfig, contextual bool) *ObjectDiff

Diff returns a diff of two DNSConfig structs

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

	// Multiregion specifies if deployment is part of multiregion 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 the object that represents a job deployment which is used to transition a job between versions.

func NewDeployment

func NewDeployment(job *Job) *Deployment

NewDeployment creates a new deployment given the job.

func (*Deployment) Active

func (d *Deployment) Active() bool

Active returns whether the deployment is active or terminal.

func (*Deployment) Copy

func (d *Deployment) Copy() *Deployment

func (*Deployment) GetID

func (d *Deployment) GetID() string

GetID is a helper for getting the ID when the object may be nil

func (*Deployment) GoString

func (d *Deployment) GoString() string

func (*Deployment) HasAutoPromote

func (d *Deployment) HasAutoPromote() bool

HasAutoPromote determines if all taskgroups are marked auto_promote

func (*Deployment) HasPlacedCanaries

func (d *Deployment) HasPlacedCanaries() bool

HasPlacedCanaries returns whether the deployment has placed canaries

func (*Deployment) RequiresPromotion

func (d *Deployment) RequiresPromotion() bool

RequiresPromotion returns whether the deployment requires promotion to continue

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 DeploymentCancelRequest

type DeploymentCancelRequest struct {
	DeploymentID string

	WriteRequest
}

DeploymentCancelRequest is used to remotely cancel a deployment. Used only for multiregion deployments.

type DeploymentDeleteRequest

type DeploymentDeleteRequest struct {
	Deployments []string
	WriteRequest
}

DeploymentDeleteRequest is used for deleting deployments.

type DeploymentFailRequest

type DeploymentFailRequest struct {
	DeploymentID string
	WriteRequest
}

DeploymentFailRequest is used to fail a particular deployment

type DeploymentListRequest

type DeploymentListRequest struct {
	QueryOptions
}

DeploymentListRequest is used to list the deployments

type DeploymentListResponse

type DeploymentListResponse struct {
	Deployments []*Deployment
	QueryMeta
}

DeploymentListResponse is used for a list request

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 DeploymentRunRequest

type DeploymentRunRequest struct {
	DeploymentID string

	WriteRequest
}

DeploymentRunRequest is used to remotely start a pending deployment. Used only for multiregion deployments.

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 {
	// AutoRevert marks whether the task group has indicated the job should be
	// reverted on failure
	AutoRevert bool

	// AutoPromote marks promotion triggered automatically by healthy canaries
	// copied from TaskGroup UpdateStrategy in scheduler.reconcile
	AutoPromote bool

	// ProgressDeadline is the deadline by which an allocation must transition
	// to healthy before the deployment is considered failed.
	ProgressDeadline time.Duration

	// RequireProgressBy is the time by which an allocation must transition
	// to healthy before the deployment is considered failed.
	RequireProgressBy time.Time

	// Promoted marks whether the canaries have been promoted
	Promoted bool

	// PlacedCanaries is the set of placed canary allocations
	PlacedCanaries []string

	// DesiredCanaries is the number of canaries that should be created.
	DesiredCanaries int

	// DesiredTotal is the total number of allocations that should be created as
	// part of the deployment.
	DesiredTotal int

	// PlacedAllocs is the number of allocations that have been placed
	PlacedAllocs int

	// HealthyAllocs is the number of allocations that have been marked healthy.
	HealthyAllocs int

	// UnhealthyAllocs are allocations that have been marked as unhealthy.
	UnhealthyAllocs int
}

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

func (*DeploymentState) Copy

func (d *DeploymentState) Copy() *DeploymentState

func (*DeploymentState) GoString

func (d *DeploymentState) GoString() string

type DeploymentStatusUpdate

type DeploymentStatusUpdate struct {
	// DeploymentID is the ID of the deployment to update
	DeploymentID string

	// Status is the new status of the deployment.
	Status string

	// StatusDescription is the new status description of the deployment.
	StatusDescription string
}

DeploymentStatusUpdate is used to update the status of a given deployment

type DeploymentStatusUpdateRequest

type DeploymentStatusUpdateRequest struct {
	// Eval, if set, is used to create an evaluation at the same time as
	// updating the status of a deployment.
	Eval *Evaluation

	// DeploymentUpdate is a status update to apply to the given
	// deployment.
	DeploymentUpdate *DeploymentStatusUpdate

	// Job is used to optionally upsert a job. This is used when setting the
	// allocation health results in a deployment failure and the deployment
	// auto-reverts to the latest stable job.
	Job *Job
}

DeploymentStatusUpdateRequest is used to update the status of a deployment as well as optionally creating an evaluation atomically.

type DeploymentUnblockRequest

type DeploymentUnblockRequest struct {
	DeploymentID string

	WriteRequest
}

DeploymentUnblockRequest is used to remotely unblock a deployment. Used only for multiregion deployments.

type DeploymentUpdateResponse

type DeploymentUpdateResponse struct {
	EvalID                string
	EvalCreateIndex       uint64
	DeploymentModifyIndex uint64

	// RevertedJobVersion is the version the job was reverted to. If unset, the
	// job wasn't reverted
	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 DeriveSITokenRequest

type DeriveSITokenRequest struct {
	NodeID   string
	SecretID string
	AllocID  string
	Tasks    []string
	QueryOptions
}

DeriveSITokenRequest is used to request Consul Service Identity tokens from the Nomad Server for the named tasks in the given allocation.

func (*DeriveSITokenRequest) Validate

func (r *DeriveSITokenRequest) Validate() error

type DeriveSITokenResponse

type DeriveSITokenResponse struct {
	// Tokens maps from Task Name to its associated SI token
	Tokens map[string]string

	// Error stores any error that occurred. Errors are stored here so we can
	// communicate whether it is retryable
	Error *RecoverableError

	QueryMeta
}

type DeriveVaultTokenRequest

type DeriveVaultTokenRequest struct {
	NodeID   string
	SecretID string
	AllocID  string
	Tasks    []string
	QueryOptions
}

DeriveVaultTokenRequest is used to request wrapped Vault tokens for the following tasks in the given allocation

type DeriveVaultTokenResponse

type DeriveVaultTokenResponse struct {
	// Tasks is a mapping between the task name and the wrapped token
	Tasks map[string]string

	// Error stores any error that occurred. Errors are stored here so we can
	// communicate whether it is retryable
	Error *RecoverableError

	QueryMeta
}

DeriveVaultTokenResponse returns the wrapped tokens for each requested task

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. Most allocations are automatically eligible for
	// rescheduling, so this field is only required when an allocation is not
	// automatically eligible. An example is an allocation that is part of a
	// deployment.
	Reschedule *bool

	// ForceReschedule is used to indicate that this allocation must be rescheduled.
	// This field is only used when operators want to force a placement even if
	// a failed allocation is not eligible to be rescheduled
	ForceReschedule *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) Merge

func (d *DesiredTransition) Merge(o *DesiredTransition)

Merge merges the two desired transitions, preferring the values from the passed in object.

func (*DesiredTransition) ShouldForceReschedule

func (d *DesiredTransition) ShouldForceReschedule() bool

ShouldForceReschedule returns whether the transition object dictates a forced rescheduling.

func (*DesiredTransition) ShouldMigrate

func (d *DesiredTransition) ShouldMigrate() bool

ShouldMigrate returns whether the transition object dictates a migration.

func (*DesiredTransition) ShouldReschedule

func (d *DesiredTransition) ShouldReschedule() bool

ShouldReschedule returns whether the transition object dictates a rescheduling.

type DesiredUpdates

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

DesiredUpdates is the set of changes the scheduler would like to make given sufficient resources and cluster capacity.

func (*DesiredUpdates) GoString

func (d *DesiredUpdates) GoString() string

type DeviceAccounter

type DeviceAccounter struct {
	// Devices maps a device group to its device accounter instance
	Devices map[DeviceIdTuple]*DeviceAccounterInstance
}

DeviceAccounter is used to account for device usage on a node. It can detect when a node is oversubscribed and can be used for deciding what devices are free

func NewDeviceAccounter

func NewDeviceAccounter(n *Node) *DeviceAccounter

NewDeviceAccounter returns a new device accounter. The node is used to populate the set of available devices based on what healthy device instances exist on the node.

func (*DeviceAccounter) AddAllocs

func (d *DeviceAccounter) AddAllocs(allocs []*Allocation) (collision bool)

AddAllocs takes a set of allocations and internally marks which devices are used. If a device is used more than once by the set of passed allocations, the collision will be returned as true.

func (*DeviceAccounter) AddReserved

func (d *DeviceAccounter) AddReserved(res *AllocatedDeviceResource) (collision bool)

AddReserved marks the device instances in the passed device reservation as used and returns if there is a collision.

type DeviceAccounterInstance

type DeviceAccounterInstance struct {
	// Device is the device being wrapped
	Device *NodeDeviceResource

	// Instances is a mapping of the device IDs to their usage.
	// Only a value of 0 indicates that the instance is unused.
	Instances map[string]int
}

DeviceAccounterInstance wraps a device and adds tracking to the instances of the device to determine if they are free or not.

func (*DeviceAccounterInstance) FreeCount

func (i *DeviceAccounterInstance) FreeCount() int

FreeCount returns the number of free device instances

type DeviceIdTuple

type DeviceIdTuple struct {
	Vendor string
	Type   string
	Name   string
}

DeviceIdTuple is the tuple that identifies a device

func (*DeviceIdTuple) Equals

func (id *DeviceIdTuple) Equals(o *DeviceIdTuple) bool

Equals returns if this Device ID is the same as the passed ID.

func (*DeviceIdTuple) Matches

func (id *DeviceIdTuple) Matches(other *DeviceIdTuple) bool

Matches returns if this Device ID is a superset of the passed ID.

func (*DeviceIdTuple) String

func (d *DeviceIdTuple) String() string

type DiffType

type DiffType string

DiffType denotes the type of a diff object.

var (
	DiffTypeNone    DiffType = "None"
	DiffTypeAdded   DiffType = "Added"
	DiffTypeDeleted DiffType = "Deleted"
	DiffTypeEdited  DiffType = "Edited"
)

func (DiffType) Less

func (d DiffType) Less(other DiffType) bool

type DispatchPayloadConfig

type DispatchPayloadConfig struct {
	// File specifies a relative path to where the input data should be written
	File string
}

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

func (*DispatchPayloadConfig) Copy

func (d *DispatchPayloadConfig) Copy() *DispatchPayloadConfig

func (*DispatchPayloadConfig) Validate

func (d *DispatchPayloadConfig) Validate() error

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 desired drain behavior.

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

func (d *DrainStrategy) Copy() *DrainStrategy

func (*DrainStrategy) DeadlineTime

func (d *DrainStrategy) DeadlineTime() (infinite bool, deadline time.Time)

DeadlineTime returns a boolean whether the drain strategy allows an infinite duration or otherwise the deadline time. The force drain is captured by the deadline time being in the past.

func (*DrainStrategy) Equal

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

type DrainUpdate

type DrainUpdate struct {
	// DrainStrategy is the new strategy for the node
	DrainStrategy *DrainStrategy

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

DrainUpdate is used to update the drain of a node

type DriverInfo

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

DriverInfo is the current state of a single driver. This is updated regularly as driver health changes on the node.

func (*DriverInfo) Copy

func (di *DriverInfo) Copy() *DriverInfo

func (*DriverInfo) HealthCheckEquals

func (di *DriverInfo) HealthCheckEquals(other *DriverInfo) bool

DriverInfo determines if two driver info objects are equal..As this is used in the process of health checking, we only check the fields that are computed by the health checker. In the future, this will be merged.

func (*DriverInfo) MergeFingerprintInfo

func (di *DriverInfo) MergeFingerprintInfo(other *DriverInfo)

MergeFingerprint merges information from fingerprinting a node for a driver into a node's driver info for that driver.

func (*DriverInfo) MergeHealthCheck

func (di *DriverInfo) MergeHealthCheck(other *DriverInfo)

MergeHealthCheck merges information from a health check for a drier into a node's driver info

type EmitNodeEventsRequest

type EmitNodeEventsRequest struct {
	// NodeEvents are a map where the key is a node id, and value is a list of
	// events for that node
	NodeEvents map[string][]*NodeEvent

	WriteRequest
}

EmitNodeEventsRequest is a request to update the node events source with a new client-side event

type EmitNodeEventsResponse

type EmitNodeEventsResponse struct {
	WriteMeta
}

EmitNodeEventsResponse is a response to the client about the status of the node event source update.

type EphemeralDisk

type EphemeralDisk struct {
	// Sticky indicates whether the allocation is sticky to a node
	Sticky bool

	// SizeMB is the size of the local disk
	SizeMB int

	// Migrate determines if Nomad client should migrate the allocation dir for
	// sticky allocations
	Migrate bool
}

EphemeralDisk is an ephemeral disk object

func DefaultEphemeralDisk

func DefaultEphemeralDisk() *EphemeralDisk

DefaultEphemeralDisk returns a EphemeralDisk with default configurations

func (*EphemeralDisk) Copy

func (d *EphemeralDisk) Copy() *EphemeralDisk

Copy copies the EphemeralDisk struct and returns a new one

func (*EphemeralDisk) Validate

func (d *EphemeralDisk) Validate() error

Validate validates EphemeralDisk

type EvalAckRequest

type EvalAckRequest struct {
	EvalID string
	Token  string
	WriteRequest
}

EvalAckRequest is used to Ack/Nack a specific evaluation

type EvalAllocationsResponse

type EvalAllocationsResponse struct {
	Allocations []*AllocListStub
	QueryMeta
}

EvalAllocationsResponse is used to return the allocations for an evaluation

type EvalDeleteRequest

type EvalDeleteRequest struct {
	Evals  []string
	Allocs []string
	WriteRequest
}

EvalDeleteRequest is used for deleting an evaluation.

type EvalDequeueRequest

type EvalDequeueRequest struct {
	Schedulers       []string
	Timeout          time.Duration
	SchedulerVersion uint16
	WriteRequest
}

EvalDequeueRequest is used when we want to dequeue an evaluation

type EvalDequeueResponse

type EvalDequeueResponse struct {
	Eval  *Evaluation
	Token string

	// WaitIndex is the Raft index the worker should wait until invoking the
	// scheduler.
	WaitIndex uint64

	QueryMeta
}

EvalDequeueResponse is used to return from a dequeue

func (*EvalDequeueResponse) GetWaitIndex

func (e *EvalDequeueResponse) GetWaitIndex() uint64

GetWaitIndex is used to retrieve the Raft index in which state should be at or beyond before invoking the scheduler.

type EvalListRequest

type EvalListRequest struct {
	QueryOptions
}

EvalListRequest is used to list the evaluations

type EvalListResponse

type EvalListResponse struct {
	Evaluations []*Evaluation
	QueryMeta
}

EvalListResponse is used for a list request

type EvalOptions

type EvalOptions struct {
	ForceReschedule bool
}

EvalOptions is used to encapsulate options when forcing a job evaluation

type EvalSpecificRequest

type EvalSpecificRequest struct {
	EvalID string
	QueryOptions
}

EvalSpecificRequest is used when we just need to specify a target evaluation

type EvalUpdateRequest

type EvalUpdateRequest struct {
	Evals     []*Evaluation
	EvalToken string
	WriteRequest
}

EvalUpdateRequest is used for upserting evaluations.

type Evaluation

type Evaluation struct {

	// ID is a randomly generated UUID used for this evaluation. This
	// is assigned upon the creation of the evaluation.
	ID string

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

	// Priority is used to control scheduling importance and if this job
	// can preempt other jobs.
	Priority int

	// Type is used to control which schedulers are available to handle
	// this evaluation.
	Type string

	// TriggeredBy is used to give some insight into why this Eval
	// was created. (Job change, node failure, alloc failure, etc).
	TriggeredBy string

	// JobID is the job this evaluation is scoped to. Evaluations cannot
	// be run in parallel for a given JobID, so we serialize on this.
	JobID string

	// JobModifyIndex is the modify index of the job at the time
	// the evaluation was created
	JobModifyIndex uint64

	// NodeID is the node that was affected triggering the evaluation.
	NodeID string

	// NodeModifyIndex is the modify index of the node at the time
	// the evaluation was created
	NodeModifyIndex uint64

	// DeploymentID is the ID of the deployment that triggered the evaluation.
	DeploymentID string

	// Status of the evaluation
	Status string

	// StatusDescription is meant to provide more human useful information
	StatusDescription string

	// Wait is a minimum wait time for running the eval. This is used to
	// support a rolling upgrade in versions prior to 0.7.0
	// Deprecated
	Wait time.Duration

	// WaitUntil is the time when this eval should be run. This is used to
	// supported delayed rescheduling of failed allocations
	WaitUntil time.Time

	// NextEval is the evaluation ID for the eval created to do a followup.
	// This is used to support rolling upgrades and failed-follow-up evals, where
	// we need a chain of evaluations.
	NextEval string

	// PreviousEval is the evaluation ID for the eval creating this one to do a followup.
	// This is used to support rolling upgrades and failed-follow-up evals, where
	// we need a chain of evaluations.
	PreviousEval string

	// BlockedEval is the evaluation ID for a created blocked eval. A
	// blocked eval will be created if all allocations could not be placed due
	// to constraints or lacking resources.
	BlockedEval string

	// FailedTGAllocs are task groups which have allocations that could not be
	// made, but the metrics are persisted so that the user can use the feedback
	// to determine the cause.
	FailedTGAllocs map[string]*AllocMetric

	// ClassEligibility tracks computed node classes that have been explicitly
	// marked as eligible or ineligible.
	ClassEligibility map[string]bool

	// QuotaLimitReached marks whether a quota limit was reached for the
	// evaluation.
	QuotaLimitReached string

	// EscapedComputedClass marks whether the job has constraints that are not
	// captured by computed node classes.
	EscapedComputedClass bool

	// AnnotatePlan triggers the scheduler to provide additional annotations
	// during the evaluation. This should not be set during normal operations.
	AnnotatePlan bool

	// QueuedAllocations is the number of unplaced allocations at the time the
	// evaluation was processed. The map is keyed by Task Group names.
	QueuedAllocations map[string]int

	// LeaderACL provides the ACL token to when issuing RPCs back to the
	// leader. This will be a valid management token as long as the leader is
	// active. This should not ever be exposed via the API.
	LeaderACL string

	// SnapshotIndex is the Raft index of the snapshot used to process the
	// evaluation. The index will either be set when it has gone through the
	// scheduler or if a blocked evaluation is being created. The index is set
	// in this case so we can determine if an early unblocking is required since
	// capacity has changed since the evaluation was created. This can result in
	// the SnapshotIndex being less than the CreateIndex.
	SnapshotIndex uint64

	// Raft Indexes
	CreateIndex uint64
	ModifyIndex uint64

	CreateTime int64
	ModifyTime int64
	// contains filtered or unexported fields
}

Evaluation is used anytime we need to apply business logic as a result of a change to our desired state (job specification) or the emergent state (registered nodes). When the inputs change, we need to "evaluate" them, potentially taking action (allocation of work) or doing nothing if the state of the world does not require it.

func (*Evaluation) Copy

func (e *Evaluation) Copy() *Evaluation

func (*Evaluation) CreateBlockedEval

func (e *Evaluation) CreateBlockedEval(classEligibility map[string]bool,
	escaped bool, quotaReached string) *Evaluation

CreateBlockedEval creates a blocked evaluation to followup this eval to place any failed allocations. It takes the classes marked explicitly eligible or ineligible, whether the job has escaped computed node classes and whether the quota limit was reached.

func (*Evaluation) CreateFailedFollowUpEval

func (e *Evaluation) CreateFailedFollowUpEval(wait time.Duration) *Evaluation

CreateFailedFollowUpEval creates a follow up evaluation when the current one has been marked as failed because it has hit the delivery limit and will not be retried by the eval_broker. Callers should copy the created eval's ID to into the old eval's NextEval field.

func (*Evaluation) GoString

func (e *Evaluation) GoString() string

func (*Evaluation) MakePlan

func (e *Evaluation) MakePlan(j *Job) *Plan

MakePlan is used to make a plan from the given evaluation for a given Job

func (*Evaluation) NextRollingEval

func (e *Evaluation) NextRollingEval(wait time.Duration) *Evaluation

NextRollingEval creates an evaluation to followup this eval for rolling updates

func (*Evaluation) ShouldBlock

func (e *Evaluation) ShouldBlock() bool

ShouldBlock checks if a given evaluation should be entered into the blocked eval tracker.

func (*Evaluation) ShouldEnqueue

func (e *Evaluation) ShouldEnqueue() bool

ShouldEnqueue checks if a given evaluation should be enqueued into the eval_broker

func (*Evaluation) TerminalStatus

func (e *Evaluation) TerminalStatus() bool

TerminalStatus returns if the current status is terminal and will no longer transition.

func (*Evaluation) UpdateModifyTime

func (e *Evaluation) UpdateModifyTime()

UpdateModifyTime takes into account that clocks on different servers may be slightly out of sync. Even in case of a leader change, this method will guarantee that ModifyTime will always be after CreateTime.

type FieldDiff

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

func (*FieldDiff) GoString

func (f *FieldDiff) GoString() string

func (*FieldDiff) Less

func (f *FieldDiff) Less(other *FieldDiff) bool

type FieldDiffs

type FieldDiffs []*FieldDiff

For sorting FieldDiffs

func (FieldDiffs) Len

func (f FieldDiffs) Len() int

func (FieldDiffs) Less

func (f FieldDiffs) Less(i, j int) bool

func (FieldDiffs) Swap

func (f FieldDiffs) Swap(i, j int)

type GenericRequest

type GenericRequest struct {
	QueryOptions
}

GenericRequest is used to request where no specific information is needed.

type GenericResponse

type GenericResponse struct {
	WriteMeta
}

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

type HostDataRequest

type HostDataRequest struct {
	ServerID string
	NodeID   string
	QueryOptions
}

HostDataRequest is used by /agent/host to retrieve data about the agent's host system. If ServerID or NodeID is specified, the request is forwarded to the remote agent

type HostDataResponse

type HostDataResponse struct {
	AgentID  string
	HostData *host.HostData
}

HostDataResponse contains the HostData content

type InternalRpcInfo

type InternalRpcInfo struct {
	// Forwarded marks whether the RPC has been forwarded.
	Forwarded bool
}

InternalRpcInfo allows adding internal RPC metadata to an RPC. This struct should NOT be replicated in the API package as it is internal only.

func (*InternalRpcInfo) IsForwarded

func (i *InternalRpcInfo) IsForwarded() bool

IsForwarded returns whether the RPC is forwarded from another server.

func (*InternalRpcInfo) SetForwarded

func (i *InternalRpcInfo) SetForwarded()

SetForwarded marks that the RPC is being forwarded from another server.

type Job

type Job struct {
	// Stop marks whether the user has stopped the job. A stopped job will
	// have all created allocations stopped and acts as a way to stop a job
	// without purging it from the system. This allows existing allocs to be
	// queried and the job to be inspected as it is being killed.
	Stop bool

	// Region is the Nomad region that handles scheduling this job
	Region string

	// Namespace is the namespace the job is submitted into.
	Namespace string

	// ID is a unique identifier for the job per region. It can be
	// specified hierarchically like LineOfBiz/OrgName/Team/Project
	ID string

	// ParentID is the unique identifier of the job that spawned this job.
	ParentID string

	// Name is the logical name of the job used to refer to it. This is unique
	// per region, but not unique globally.
	Name string

	// Type is used to control various behaviors about the job. Most jobs
	// are service jobs, meaning they are expected to be long lived.
	// Some jobs are batch oriented meaning they run and then terminate.
	// This can be extended in the future to support custom schedulers.
	Type string

	// Priority is used to control scheduling importance and if this job
	// can preempt other jobs.
	Priority int

	// AllAtOnce is used to control if incremental scheduling of task groups
	// is allowed or if we must do a gang scheduling of the entire job. This
	// can slow down larger jobs if resources are not available.
	AllAtOnce bool

	// Datacenters contains all the datacenters this job is allowed to span
	Datacenters []string

	// Constraints can be specified at a job level and apply to
	// all the task groups and tasks.
	Constraints []*Constraint

	// Affinities can be specified at the job level to express
	// scheduling preferences that apply to all groups and tasks
	Affinities []*Affinity

	// Spread can be specified at the job level to express spreading
	// allocations across a desired attribute, such as datacenter
	Spreads []*Spread

	// TaskGroups are the collections of task groups that this job needs
	// to run. Each task group is an atomic unit of scheduling and placement.
	TaskGroups []*TaskGroup

	// See agent.ApiJobToStructJob
	// Update provides defaults for the TaskGroup Update stanzas
	Update UpdateStrategy

	Multiregion *Multiregion

	// Periodic is used to define the interval the job is run at.
	Periodic *PeriodicConfig

	// ParameterizedJob is used to specify the job as a parameterized job
	// for dispatching.
	ParameterizedJob *ParameterizedJobConfig

	// Dispatched is used to identify if the Job has been dispatched from a
	// parameterized job.
	Dispatched bool

	// Payload is the payload supplied when the job was dispatched.
	Payload []byte

	// Meta is used to associate arbitrary metadata with this
	// job. This is opaque to Nomad.
	Meta map[string]string

	// ConsulToken is the Consul token that proves the submitter of the job 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 Job submission.
	ConsulToken string

	// VaultToken is the Vault token that proves the submitter of the job has
	// access to the specified Vault policies. This field is only used to
	// transfer the token and is not stored after Job submission.
	VaultToken string

	// VaultNamespace is the Vault namepace
	VaultNamespace string

	// NomadTokenID is the Accessor ID of the ACL token (if any)
	// used to register this version of the job. Used by deploymentwatcher.
	NomadTokenID string

	// Job status
	Status string

	// StatusDescription is meant to provide more human useful information
	StatusDescription string

	// Stable marks a job as stable. Stability is only defined on "service" and
	// "system" jobs. The stability of a job will be set automatically as part
	// of a deployment and can be manually set via APIs. This field is updated
	// when the status of a corresponding deployment transitions to Failed
	// or Successful. This field is not meaningful for jobs that don't have an
	// update stanza.
	Stable bool

	// Version is a monotonically increasing version number that is incremented
	// on each job register.
	Version uint64

	// SubmitTime is the time at which the job was submitted as a UnixNano in
	// UTC
	SubmitTime int64

	// Raft Indexes
	CreateIndex    uint64
	ModifyIndex    uint64
	JobModifyIndex uint64
}

Job is the scope of a scheduling request to Nomad. It is the largest scoped object, and is a named collection of task groups. Each task group is further composed of tasks. A task group (TG) is the unit of scheduling however.

func MockJob

func MockJob() *Job

func (*Job) Canonicalize

func (j *Job) Canonicalize() (warnings error)

Canonicalize is used to canonicalize fields in the Job. This should be called when registering a Job. A set of warnings are returned if the job was changed in anyway that the user should be made aware of.

func (*Job) CombinedTaskMeta

func (j *Job) CombinedTaskMeta(groupName, taskName string) map[string]string

CombinedTaskMeta takes a TaskGroup and Task name and returns the combined meta data for the task. When joining Job, Group and Task Meta, the precedence is by deepest scope (Task > Group > Job).

func (*Job) ConfigEntries

func (j *Job) ConfigEntries() map[string]*ConsulIngressConfigEntry

ConfigEntries accumulates the Consul Configuration Entries defined in task groups of j.

Currently Nomad only supports entries for connect ingress gateways.

func (*Job) ConnectTasks

func (j *Job) ConnectTasks() []TaskKind

ConnectTasks returns the set of Consul Connect enabled tasks defined on the job that will require a Service Identity token in the case that Consul ACLs are enabled. The TaskKind.Value is the name of the Consul service.

This method is meaningful only after the Job has passed through the job submission Mutator functions.

func (*Job) Copy

func (j *Job) Copy() *Job

Copy returns a deep copy of the Job. It is expected that callers use recover. This job can panic if the deep copy failed as it uses reflection.

func (*Job) Diff

func (j *Job) Diff(other *Job, contextual bool) (*JobDiff, error)

Diff returns a diff of two jobs and a potential error if the Jobs are not diffable. If contextual diff is enabled, objects within the job will contain field information even if unchanged.

func (*Job) GetScalingPolicies

func (j *Job) GetScalingPolicies() []*ScalingPolicy

GetScalingPolicies returns a slice of all scaling scaling policies for this job

func (*Job) HasUpdateStrategy

func (j *Job) HasUpdateStrategy() bool

HasUpdateStrategy returns if any task group in the job has an update strategy

func (*Job) IsMultiregion

func (j *Job) IsMultiregion() bool

IsMultiregion returns whether a job is multiregion

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

func (j *Job) IsPeriodicActive() bool

IsPeriodicActive returns whether the job is an active periodic job that will create child jobs

func (*Job) LookupTaskGroup

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

LookupTaskGroup finds a task group by name

func (*Job) NamespacedID

func (j *Job) NamespacedID() *NamespacedID

NamespacedID returns the namespaced id useful for logging

func (*Job) RequiredSignals

func (j *Job) RequiredSignals() map[string]map[string][]string

RequiredSignals returns a mapping of task groups to tasks to their required set of signals

func (*Job) SetSubmitTime

func (j *Job) SetSubmitTime()

func (*Job) SpecChanged

func (j *Job) SpecChanged(new *Job) bool

SpecChanged determines if the functional specification has changed between two job versions.

func (*Job) Stopped

func (j *Job) Stopped() bool

Stopped returns if a job is stopped.

func (*Job) Stub

func (j *Job) Stub(summary *JobSummary) *JobListStub

Stub is used to return a summary of the job

func (*Job) Validate

func (j *Job) Validate() error

Validate is used to sanity check a job input

func (*Job) VaultPolicies

func (j *Job) VaultPolicies() map[string]map[string]*Vault

VaultPolicies returns the set of Vault policies per task group, per task

func (*Job) Warnings

func (j *Job) Warnings() error

Warnings returns a list of warnings that may be from dubious settings or deprecation warnings.

type JobAllocationsResponse

type JobAllocationsResponse struct {
	Allocations []*AllocListStub
	QueryMeta
}

JobAllocationsResponse is used to return the allocations for a job

type JobBatchDeregisterRequest

type JobBatchDeregisterRequest struct {
	// Jobs is the set of jobs to deregister
	Jobs map[NamespacedID]*JobDeregisterOptions

	// Evals is the set of evaluations to create.
	Evals []*Evaluation

	WriteRequest
}

JobBatchDeregisterRequest is used to batch deregister jobs and upsert evaluations.

type JobBatchDeregisterResponse

type JobBatchDeregisterResponse struct {
	// JobEvals maps the job to its created evaluation
	JobEvals map[NamespacedID]string
	QueryMeta
}

JobBatchDeregisterResponse is used to respond to a batch job deregistration

type JobChildrenSummary

type JobChildrenSummary struct {
	Pending int64
	Running int64
	Dead    int64
}

JobChildrenSummary contains the summary of children job statuses

func (*JobChildrenSummary) Copy

func (jc *JobChildrenSummary) Copy() *JobChildrenSummary

Copy returns a new copy of a JobChildrenSummary

type JobDeregisterOptions

type JobDeregisterOptions struct {
	// Purge controls whether the deregister purges the job from the system or
	// whether the job is just marked as stopped and will be removed by the
	// garbage collector
	Purge bool
}

JobDeregisterOptions configures how a job is deregistered.

type JobDeregisterRequest

type JobDeregisterRequest struct {
	JobID string

	// Purge controls whether the deregister purges the job from the system or
	// whether the job is just marked as stopped and will be removed by the
	// garbage collector
	Purge bool

	// Global controls whether all regions of a multi-region job are
	// deregistered. It is ignored for single-region jobs.
	Global bool

	// Eval is the evaluation to create that's associated with job deregister
	Eval *Evaluation

	WriteRequest
}

JobDeregisterRequest is used for Job.Deregister endpoint to deregister a job as being a schedulable entity.

type JobDeregisterResponse

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

JobDeregisterResponse is used to respond to a job deregistration

type JobDescription

type JobDescription struct {
	Namespace string
	ID        string
	Expected  int
}

JobDescription records Job identification and the count of expected plugin instances

type JobDescriptions

type JobDescriptions map[string]JobNamespacedDescriptions

JobDescriptions maps Namespace to a mapping of Job.ID to JobDescription

func (JobDescriptions) Add

func (j JobDescriptions) Add(job *Job, expected int)

Add the Job to the JobDescriptions, creating maps as necessary

func (JobDescriptions) Count

func (j JobDescriptions) Count() int

Count the Expected instances for all JobDescriptions

func (JobDescriptions) Delete

func (j JobDescriptions) Delete(job *Job)

Delete the Job from the JobDescriptions

type JobDiff

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

JobDiff contains the diff of two jobs.

func (*JobDiff) GoString

func (j *JobDiff) GoString() string

type JobDispatchRequest

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

JobDispatchRequest is used to dispatch a job based on a parameterized job

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 JobEvaluationsResponse

type JobEvaluationsResponse struct {
	Evaluations []*Evaluation
	QueryMeta
}

JobEvaluationsResponse is used to return the evaluations for a job

type JobListRequest

type JobListRequest struct {
	QueryOptions
}

JobListRequest is used to parameterize a list request

type JobListResponse

type JobListResponse struct {
	Jobs []*JobListStub
	QueryMeta
}

JobListResponse is used for a list request

type JobListStub

type JobListStub struct {
	ID                string
	ParentID          string
	Name              string
	Namespace         string `json:",omitempty"`
	Datacenters       []string
	Multiregion       *Multiregion
	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 job information for the job list

type JobNamespacedDescriptions

type JobNamespacedDescriptions map[string]JobDescription

JobNamespacedDescriptions maps Job.ID to JobDescription

type JobPlanRequest

type JobPlanRequest struct {
	Job  *Job
	Diff bool // Toggles an annotated diff
	// PolicyOverride is set when the user is attempting to override any policies
	PolicyOverride bool
	WriteRequest
}

JobPlanRequest is used for the Job.Plan endpoint to trigger a dry-run evaluation of the Job.

type JobPlanResponse

type JobPlanResponse struct {
	// Annotations stores annotations explaining decisions the scheduler made.
	Annotations *PlanAnnotations

	// FailedTGAllocs is the placement failures per task group.
	FailedTGAllocs map[string]*AllocMetric

	// JobModifyIndex is the modification index of the job. The value can be
	// used when running `nomad run` to ensure that the Job wasn’t modified
	// since the last plan. If the job is being created, the value is zero.
	JobModifyIndex uint64

	// CreatedEvals is the set of evaluations created by the scheduler. The
	// reasons for this can be rolling-updates or blocked evals.
	CreatedEvals []*Evaluation

	// Diff contains the diff of the job and annotations on whether the change
	// causes an in-place update or create/destroy
	Diff *JobDiff

	// NextPeriodicLaunch is the time duration till the job would be launched if
	// submitted.
	NextPeriodicLaunch time.Time

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

	WriteMeta
}

JobPlanResponse is used to respond to a job plan request

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
	JobModifyIndex uint64

	// PreserveCounts indicates that during job update, existing task group
	// counts should be preserved, over those specified in the new job spec
	// PreserveCounts is ignored for newly created jobs.
	PreserveCounts bool

	// PolicyOverride is set when the user is attempting to override any policies
	PolicyOverride bool

	// Eval is the evaluation that is associated with the job registration
	Eval *Evaluation

	WriteRequest
}

JobRegisterRequest is used for Job.Register endpoint to register a job as being a schedulable entity.

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

	// 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 transfer the token and is not stored after the Job
	// revert.
	VaultToken string

	WriteRequest
}

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

type JobScaleRequest

type JobScaleRequest struct {
	Namespace string
	JobID     string
	Target    map[string]string
	Count     *int64
	Message   string
	Error     bool
	Meta      map[string]interface{}
	// PolicyOverride is set when the user is attempting to override any policies
	PolicyOverride bool
	WriteRequest
}

JobScaleRequest is used for the Job.Scale endpoint to scale one of the scaling targets in a job

type JobScaleStatus

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

type JobScaleStatusRequest

type JobScaleStatusRequest struct {
	JobID string
	QueryOptions
}

JobScaleStatusRequest is used to get the scale status for a job

type JobScaleStatusResponse

type JobScaleStatusResponse struct {
	JobScaleStatus *JobScaleStatus
	QueryMeta
}

JobScaleStatusResponse is used to return the scale status for a job

type JobScalingEvents

type JobScalingEvents struct {
	Namespace string
	JobID     string

	// This map is indexed by target; currently, this is just task group
	// the indexed array is sorted from newest to oldest event
	// the array should have less than JobTrackedScalingEvents entries
	ScalingEvents map[string][]*ScalingEvent

	// Raft index
	ModifyIndex uint64
}

JobScalingEvents contains the scaling events for a given job

type JobSpecificRequest

type JobSpecificRequest struct {
	JobID string
	All   bool
	QueryOptions
}

JobSpecificRequest is used when we just need to specify a target job

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 {
	WriteMeta
}

JobStabilityResponse is the response when marking a job as stable.

type JobSummary

type JobSummary struct {
	// JobID is the ID of the job the summary is for
	JobID string

	// Namespace is the namespace of the job and its summary
	Namespace string

	// Summary contains the summary per task group for the Job
	Summary map[string]TaskGroupSummary

	// Children contains a summary for the children of this job.
	Children *JobChildrenSummary

	// Raft Indexes
	CreateIndex uint64
	ModifyIndex uint64
}

JobSummary summarizes the state of the allocations of a job

func (*JobSummary) Copy

func (js *JobSummary) Copy() *JobSummary

Copy returns a new copy of JobSummary

type JobSummaryRequest

type JobSummaryRequest struct {
	JobID string
	QueryOptions
}

JobSummaryRequest is used when we just need to get a specific job summary

type JobSummaryResponse

type JobSummaryResponse struct {
	JobSummary *JobSummary
	QueryMeta
}

JobSummaryResponse is used to return a single job summary

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 JobVersionsRequest

type JobVersionsRequest struct {
	JobID string
	Diffs bool
	QueryOptions
}

JobVersionsRequest is used to get a jobs versions

type JobVersionsResponse

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

JobVersionsResponse is used for a job get versions request

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 LogConfig

type LogConfig struct {
	MaxFiles      int
	MaxFileSizeMB int
}

LogConfig provides configuration for log rotation

func DefaultLogConfig

func DefaultLogConfig() *LogConfig

DefaultLogConfig returns the default LogConfig values.

func (*LogConfig) Copy

func (l *LogConfig) Copy() *LogConfig

func (*LogConfig) Validate

func (l *LogConfig) Validate() error

Validate returns an error if the log config specified are less than the minimum allowed.

type MessageType

type MessageType uint8
const (
	NodeRegisterRequestType MessageType = iota
	NodeDeregisterRequestType
	NodeUpdateStatusRequestType
	NodeUpdateDrainRequestType
	JobRegisterRequestType
	JobDeregisterRequestType
	EvalUpdateRequestType
	EvalDeleteRequestType
	AllocUpdateRequestType
	AllocClientUpdateRequestType
	ReconcileJobSummariesRequestType
	VaultAccessorRegisterRequestType
	VaultAccessorDeregisterRequestType
	ApplyPlanResultsRequestType
	DeploymentStatusUpdateRequestType
	DeploymentPromoteRequestType
	DeploymentAllocHealthRequestType
	DeploymentDeleteRequestType
	JobStabilityRequestType
	ACLPolicyUpsertRequestType
	ACLPolicyDeleteRequestType
	ACLTokenUpsertRequestType
	ACLTokenDeleteRequestType
	ACLTokenBootstrapRequestType
	AutopilotRequestType
	UpsertNodeEventsType
	JobBatchDeregisterRequestType
	AllocUpdateDesiredTransitionRequestType
	NodeUpdateEligibilityRequestType
	BatchNodeUpdateDrainRequestType
	SchedulerConfigRequestType
	NodeBatchDeregisterRequestType
	ClusterMetadataRequestType
	ServiceIdentityAccessorRegisterRequestType
	ServiceIdentityAccessorDeregisterRequestType
	CSIVolumeRegisterRequestType
	CSIVolumeDeregisterRequestType
	CSIVolumeClaimRequestType
	ScalingEventRegisterRequestType
	CSIVolumeClaimBatchRequestType
	CSIPluginDeleteRequestType
)

note: new raft message types need to be added to the end of this list of contents

type MigrateStrategy

type MigrateStrategy struct {
	MaxParallel     int
	HealthCheck     string
	MinHealthyTime  time.Duration
	HealthyDeadline time.Duration
}

func DefaultMigrateStrategy

func DefaultMigrateStrategy() *MigrateStrategy

DefaultMigrateStrategy is used for backwards compat with pre-0.8 Allocations that lack an update strategy.

This function should match its counterpart in api/tasks.go

func (*MigrateStrategy) Validate

func (m *MigrateStrategy) Validate() error

type Multiregion

type Multiregion struct {
	Strategy *MultiregionStrategy
	Regions  []*MultiregionRegion
}

func (*Multiregion) Canonicalize

func (m *Multiregion) Canonicalize()

func (*Multiregion) Copy

func (m *Multiregion) Copy() *Multiregion

func (*Multiregion) Diff

func (m *Multiregion) Diff(m2 *Multiregion) bool

Diff indicates whether the multiregion config has changed

func (*Multiregion) Validate

func (m *Multiregion) Validate(jobType string, jobDatacenters []string) error

type MultiregionRegion

type MultiregionRegion struct {
	Name        string
	Count       int
	Datacenters []string
	Meta        map[string]string
}

type MultiregionStrategy

type MultiregionStrategy struct {
	MaxParallel int
	OnFailure   string
}

type NamespacedID

type NamespacedID struct {
	ID        string
	Namespace string
}

NamespacedID is a tuple of an ID and a namespace

func NewNamespacedID

func NewNamespacedID(id, ns string) NamespacedID

NewNamespacedID returns a new namespaced ID given the ID and namespace

func (NamespacedID) String

func (n NamespacedID) String() string

type NetworkIndex

type NetworkIndex struct {
	AvailNetworks  []*NetworkResource              // List of available networks
	NodeNetworks   []*NodeNetworkResource          // List of available node networks
	AvailAddresses map[string][]NodeNetworkAddress // Map of host network aliases to list of addresses
	AvailBandwidth map[string]int                  // Bandwidth by device
	UsedPorts      map[string]Bitmap               // Ports by IP
	UsedBandwidth  map[string]int                  // Bandwidth by device
}

NetworkIndex is used to index the available network resources and the used network resources on a machine given allocations

func NewNetworkIndex

func NewNetworkIndex() *NetworkIndex

NewNetworkIndex is used to construct a new network index

func (*NetworkIndex) AddAllocs

func (idx *NetworkIndex) AddAllocs(allocs []*Allocation) (collide bool)

AddAllocs is used to add the used network resources. Returns true if there is a collision

func (*NetworkIndex) AddReserved

func (idx *NetworkIndex) AddReserved(n *NetworkResource) (collide bool)

AddReserved is used to add a reserved network usage, returns true if there is a port collision

func (*NetworkIndex) AddReservedPortRange

func (idx *NetworkIndex) AddReservedPortRange(ports string) (collide bool)

AddReservedPortRange marks the ports given as reserved on all network interfaces. The port format is comma delimited, with spans given as n1-n2 (80,100-200,205)

func (*NetworkIndex) AddReservedPorts

func (idx *NetworkIndex) AddReservedPorts(ports AllocatedPorts) (collide bool)

func (*NetworkIndex) AddReservedPortsForIP

func (idx *NetworkIndex) AddReservedPortsForIP(ports string, ip string) (collide bool)

AddReservedPortsForIP

func (*NetworkIndex) AssignNetwork

func (idx *NetworkIndex) AssignNetwork(ask *NetworkResource) (out *NetworkResource, err error)

AssignNetwork is used to assign network resources given an ask. If the ask cannot be satisfied, returns nil

func (*NetworkIndex) AssignPorts

func (idx *NetworkIndex) AssignPorts(ask *NetworkResource) (AllocatedPorts, error)

func (*NetworkIndex) Overcommitted

func (idx *NetworkIndex) Overcommitted() bool

Overcommitted checks if the network is overcommitted

func (*NetworkIndex) Release

func (idx *NetworkIndex) Release()

Release is called when the network index is no longer needed to attempt to re-use some of the memory it has allocated

func (*NetworkIndex) SetNode

func (idx *NetworkIndex) SetNode(node *Node) (collide bool)

SetNode is used to setup the available network resources. Returns true if there is a collision

type NetworkResource

type NetworkResource struct {
	Mode          string     // Mode of the network
	Device        string     // Name of the device
	CIDR          string     // CIDR block of addresses
	IP            string     // Host IP address
	MBits         int        // Throughput
	DNS           *DNSConfig // DNS Configuration
	ReservedPorts []Port     // Host Reserved ports
	DynamicPorts  []Port     // Host Dynamically assigned ports
}

NetworkResource is used to represent available network resources

func AllocatedPortsToNetworkResouce

func AllocatedPortsToNetworkResouce(ask *NetworkResource, ports AllocatedPorts, node *NodeResources) *NetworkResource

COMPAT(1.0) remove when NetworkResource is no longer used for materialized client view of ports

func (*NetworkResource) Add

func (n *NetworkResource) Add(delta *NetworkResource)

Add adds the resources of the delta to this, potentially returning an error if not possible.

func (*NetworkResource) Canonicalize

func (n *NetworkResource) Canonicalize()

func (*NetworkResource) Copy

func (n *NetworkResource) Copy() *NetworkResource

Copy returns a deep copy of the network resource

func (*NetworkResource) Diff

func (r *NetworkResource) Diff(other *NetworkResource, contextual bool) *ObjectDiff

Diff returns a diff of two network resources. If contextual diff is enabled, non-changed fields will still be returned.

func (*NetworkResource) Equals

func (nr *NetworkResource) Equals(other *NetworkResource) bool

func (*NetworkResource) GoString

func (n *NetworkResource) GoString() string

func (*NetworkResource) Hash

func (nr *NetworkResource) Hash() uint32

func (*NetworkResource) MeetsMinResources

func (n *NetworkResource) MeetsMinResources() error

MeetsMinResources returns an error if the resources specified are less than the minimum allowed.

func (*NetworkResource) PortForService

func (n *NetworkResource) PortForService(serviceName string) (Port, bool)

ConnectPort returns the Connect port for the given service. Returns false if no port was found for a service with that name.

func (*NetworkResource) PortLabels

func (n *NetworkResource) PortLabels() map[string]int

PortLabels returns a map of port labels to their assigned host ports.

type Networks

type Networks []*NetworkResource

Networks defined for a task on the Resources struct.

func (Networks) Copy

func (ns Networks) Copy() Networks

func (*Networks) Equals

func (ns *Networks) Equals(o *Networks) bool

Equals equates Networks as a set

func (Networks) NetIndex

func (ns Networks) NetIndex(n *NetworkResource) int

func (Networks) Port

func (ns Networks) Port(label string) (string, int)

Port assignment and IP for the given label or empty values.

type Node

type Node struct {
	// ID is a unique identifier for the node. It can be constructed
	// by doing a concatenation of the Name and Datacenter as a simple
	// approach. Alternatively a UUID may be used.
	ID string

	// SecretID is an ID that is only known by the Node and the set of Servers.
	// It is not accessible via the API and is used to authenticate nodes
	// conducting privileged activities.
	SecretID string

	// Datacenter for this node
	Datacenter string

	// Node name
	Name string

	// HTTPAddr is the address on which the Nomad client is listening for http
	// requests
	HTTPAddr string

	// TLSEnabled indicates if the Agent has TLS enabled for the HTTP API
	TLSEnabled bool

	// Attributes is an arbitrary set of key/value
	// data that can be used for constraints. Examples
	// include "kernel.name=linux", "arch=386", "driver.docker=1",
	// "docker.runtime=1.8.3"
	Attributes map[string]string

	// NodeResources captures the available resources on the client.
	NodeResources *NodeResources

	// ReservedResources captures the set resources on the client that are
	// reserved from scheduling.
	ReservedResources *NodeReservedResources

	// Resources is the available resources on the client.
	// For example 'cpu=2' 'memory=2048'
	// COMPAT(0.10): Remove in 0.10
	Resources *Resources

	// Reserved is the set of resources that are reserved,
	// and should be subtracted from the total resources for
	// the purposes of scheduling. This may be provide certain
	// high-watermark tolerances or because of external schedulers
	// consuming resources.
	Reserved *Resources

	// Links are used to 'link' this client to external
	// systems. For example 'consul=foo.dc1' 'aws=i-83212'
	// 'ami=ami-123'
	Links map[string]string

	// Meta is used to associate arbitrary metadata with this
	// client. This is opaque to Nomad.
	Meta map[string]string

	// NodeClass is an opaque identifier used to group nodes
	// together for the purpose of determining scheduling pressure.
	NodeClass string

	// ComputedClass is a unique id that identifies nodes with a common set of
	// attributes and capabilities.
	ComputedClass string

	// COMPAT: Remove in Nomad 0.9
	// Drain is controlled by the servers, and not the client.
	// If true, no jobs will be scheduled to this node, and existing
	// allocations will be drained. Superseded by DrainStrategy in Nomad
	// 0.8 but kept for backward compat.
	Drain bool

	// DrainStrategy determines the node's draining behavior. Will be nil
	// when Drain=false.
	DrainStrategy *DrainStrategy

	// SchedulingEligibility determines whether this node will receive new
	// placements.
	SchedulingEligibility string

	// Status of this node
	Status string

	// StatusDescription is meant to provide more human useful information
	StatusDescription string

	// StatusUpdatedAt is the time stamp at which the state of the node was
	// updated
	StatusUpdatedAt int64

	// Events is the most recent set of events generated for the node,
	// retaining only MaxRetainedNodeEvents number at a time
	Events []*NodeEvent

	// Drivers is a map of driver names to current driver information
	Drivers map[string]*DriverInfo

	// CSIControllerPlugins is a map of plugin names to current CSI Plugin info
	CSIControllerPlugins map[string]*CSIInfo
	// CSINodePlugins is a map of plugin names to current CSI Plugin info
	CSINodePlugins map[string]*CSIInfo

	// HostVolumes is a map of host volume names to their configuration
	HostVolumes map[string]*ClientHostVolumeConfig

	// Raft Indexes
	CreateIndex uint64
	ModifyIndex uint64
}

Node is a representation of a schedulable client node

func MockNode

func MockNode() *Node

func MockNvidiaNode

func MockNvidiaNode() *Node

NvidiaNode returns a node with two instances of an Nvidia GPU

func (*Node) Canonicalize

func (n *Node) Canonicalize()

func (*Node) ComparableReservedResources

func (n *Node) ComparableReservedResources() *ComparableResources

COMPAT(0.11): Remove in 0.11 ComparableReservedResources returns the reserved resouces on the node handling upgrade paths. Reserved networks must be handled separately. After 0.11 calls to this should be replaced with: node.ReservedResources.Comparable()

func (*Node) ComparableResources

func (n *Node) ComparableResources() *ComparableResources

COMPAT(0.11): Remove in 0.11 ComparableResources returns the resouces on the node handling upgrade paths. Networking must be handled separately. After 0.11 calls to this should be replaced with: node.NodeResources.Comparable()

func (*Node) ComputeClass

func (n *Node) ComputeClass() error

ComputeClass computes a derived class for the node based on its attributes. ComputedClass is a unique id that identifies nodes with a common set of attributes and capabilities. Thus, when calculating a node's computed class we avoid including any uniquely identifying fields.

func (*Node) Copy

func (n *Node) Copy() *Node

func (Node) HashInclude

func (n Node) HashInclude(field string, v interface{}) (bool, error)

HashInclude is used to blacklist uniquely identifying node fields from being included in the computed node class.

func (Node) HashIncludeMap

func (n Node) HashIncludeMap(field string, k, v interface{}) (bool, error)

HashIncludeMap is used to blacklist uniquely identifying node map keys from being included in the computed node class.

func (*Node) Ready

func (n *Node) Ready() bool

Ready returns true if the node is ready for running allocations

func (*Node) Stub

func (n *Node) Stub() *NodeListStub

Stub returns a summarized version of the node

func (*Node) TerminalStatus

func (n *Node) TerminalStatus() bool

TerminalStatus returns if the current status is terminal and will no longer transition.

type NodeAllocsResponse

type NodeAllocsResponse struct {
	Allocs []*Allocation
	QueryMeta
}

NodeAllocsResponse is used to return allocs for a single node

type NodeBatchDeregisterRequest

type NodeBatchDeregisterRequest struct {
	NodeIDs []string
	WriteRequest
}

NodeBatchDeregisterRequest is used for Node.BatchDeregister endpoint to deregister a batch of nodes from being schedulable entities.

type NodeClientAllocsResponse

type NodeClientAllocsResponse struct {
	Allocs map[string]uint64

	// MigrateTokens are used when ACLs are enabled to allow cross node,
	// authenticated access to sticky volumes
	MigrateTokens map[string]string

	QueryMeta
}

NodeClientAllocsResponse is used to return allocs meta data for a single node

type NodeConnQueryResponse

type NodeConnQueryResponse struct {
	// Connected indicates whether a connection to the Client exists
	Connected bool

	// Established marks the time at which the connection was established
	Established time.Time

	QueryMeta
}

NodeConnQueryResponse is used to respond to a query of whether a server has a connection to a specific Node

type NodeCpuResources

type NodeCpuResources struct {
	// CpuShares is the CPU shares available. This is calculated by number of
	// cores multiplied by the core frequency.
	CpuShares int64
}

NodeCpuResources captures the CPU resources of the node.

func (*NodeCpuResources) Equals

func (n *NodeCpuResources) Equals(o *NodeCpuResources) bool

func (*NodeCpuResources) Merge

func (n *NodeCpuResources) Merge(o *NodeCpuResources)

type NodeDeregisterRequest

type NodeDeregisterRequest struct {
	NodeID string
	WriteRequest
}

NodeDeregisterRequest is used for Node.Deregister endpoint to deregister a node as being a schedulable entity.

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.

func (*NodeDevice) Copy

func (n *NodeDevice) Copy() *NodeDevice

func (*NodeDevice) Equals

func (n *NodeDevice) Equals(o *NodeDevice) bool

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.

func (*NodeDeviceLocality) Copy

func (n *NodeDeviceLocality) Copy() *NodeDeviceLocality

func (*NodeDeviceLocality) Equals

func (n *NodeDeviceLocality) Equals(o *NodeDeviceLocality) bool

type NodeDeviceResource

type NodeDeviceResource struct {
	Vendor     string
	Type       string
	Name       string
	Instances  []*NodeDevice
	Attributes map[string]*psstructs.Attribute
}

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

func (*NodeDeviceResource) Copy

func (n *NodeDeviceResource) Copy() *NodeDeviceResource

func (*NodeDeviceResource) Equals

func (n *NodeDeviceResource) Equals(o *NodeDeviceResource) bool

func (NodeDeviceResource) HashInclude

func (n NodeDeviceResource) HashInclude(field string, v interface{}) (bool, error)

HashInclude is used to blacklist uniquely identifying node fields from being included in the computed node class.

func (NodeDeviceResource) HashIncludeMap

func (n NodeDeviceResource) HashIncludeMap(field string, k, v interface{}) (bool, error)

HashIncludeMap is used to blacklist uniquely identifying node map keys from being included in the computed node class.

func (*NodeDeviceResource) ID

func (n *NodeDeviceResource) ID() *DeviceIdTuple

type NodeDiskResources

type NodeDiskResources struct {
	// DiskMB is the total available disk space on the node
	DiskMB int64
}

NodeDiskResources captures the disk resources of the node

func (*NodeDiskResources) Equals

func (n *NodeDiskResources) Equals(o *NodeDiskResources) bool

func (*NodeDiskResources) Merge

func (n *NodeDiskResources) Merge(o *NodeDiskResources)

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 NodeEvaluateRequest

type NodeEvaluateRequest struct {
	NodeID string
	WriteRequest
}

NodeEvaluateRequest is used to re-evaluate the node

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

func NewNodeEvent

func NewNodeEvent() *NodeEvent

NewNodeEvent generates a new node event storing the current time as the timestamp

func (*NodeEvent) AddDetail

func (ne *NodeEvent) AddDetail(k, v string) *NodeEvent

AddDetail is used to add a detail to the node event

func (*NodeEvent) Copy

func (ne *NodeEvent) Copy() *NodeEvent

func (*NodeEvent) SetMessage

func (ne *NodeEvent) SetMessage(msg string) *NodeEvent

SetMessage is used to set the message on the node event

func (*NodeEvent) SetSubsystem

func (ne *NodeEvent) SetSubsystem(sys string) *NodeEvent

SetSubsystem is used to set the subsystem on the node event

func (*NodeEvent) SetTimestamp

func (ne *NodeEvent) SetTimestamp(ts time.Time) *NodeEvent

SetTimestamp is used to set the timestamp on the node event

func (*NodeEvent) String

func (ne *NodeEvent) String() string

type NodeListRequest

type NodeListRequest struct {
	QueryOptions
}

NodeListRequest is used to parameterize a list request

type NodeListResponse

type NodeListResponse struct {
	Nodes []*NodeListStub
	QueryMeta
}

NodeListResponse is used for a list request

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
	HostVolumes           map[string]*ClientHostVolumeConfig
	CreateIndex           uint64
	ModifyIndex           uint64
}

NodeListStub is used to return a subset of job information for the job list

type NodeMemoryResources

type NodeMemoryResources struct {
	// MemoryMB is the total available memory on the node
	MemoryMB int64
}

NodeMemoryResources captures the memory resources of the node

func (*NodeMemoryResources) Equals

func (n *NodeMemoryResources) Equals(o *NodeMemoryResources) bool

func (*NodeMemoryResources) Merge

func (n *NodeMemoryResources) Merge(o *NodeMemoryResources)

type NodeNetworkAF

type NodeNetworkAF string
const (
	NodeNetworkAF_IPv4 NodeNetworkAF = "ipv4"
	NodeNetworkAF_IPv6 NodeNetworkAF = "ipv6"
)

type NodeNetworkAddress

type NodeNetworkAddress struct {
	Family        NodeNetworkAF
	Alias         string
	Address       string
	ReservedPorts string
	Gateway       string // default route for this address
}

type NodeNetworkResource

type NodeNetworkResource struct {
	Mode string // host for physical networks, cni/<name> for cni networks

	// The following apply only to host networks
	Device     string // interface name
	MacAddress string
	Speed      int

	Addresses []NodeNetworkAddress // not valid for cni, for bridge there will only be 1 ip
}

NodeNetworkResource is used to describe a fingerprinted network of a node

func (*NodeNetworkResource) Equals

func (n *NodeNetworkResource) Equals(o *NodeNetworkResource) bool

func (*NodeNetworkResource) HasAlias

func (n *NodeNetworkResource) HasAlias(alias string) bool

type NodeRegisterRequest

type NodeRegisterRequest struct {
	Node      *Node
	NodeEvent *NodeEvent
	WriteRequest
}

NodeRegisterRequest is used for Node.Register endpoint to register a node as being a schedulable entity.

type NodeReservedCpuResources

type NodeReservedCpuResources struct {
	CpuShares int64
}

NodeReservedCpuResources captures the reserved CPU resources of the node.

type NodeReservedDiskResources

type NodeReservedDiskResources struct {
	DiskMB int64
}

NodeReservedDiskResources captures the reserved disk resources of the node.

type NodeReservedMemoryResources

type NodeReservedMemoryResources struct {
	MemoryMB int64
}

NodeReservedMemoryResources captures the reserved memory resources of the node.

type NodeReservedNetworkResources

type NodeReservedNetworkResources struct {
	// ReservedHostPorts is the set of ports reserved on all host network
	// interfaces. Its format is a comma separate list of integers or integer
	// ranges. (80,443,1000-2000,2005)
	ReservedHostPorts string
}

NodeReservedNetworkResources captures the reserved network resources of the node.

func (*NodeReservedNetworkResources) ParseReservedHostPorts

func (n *NodeReservedNetworkResources) ParseReservedHostPorts() ([]uint64, error)

ParsePortHostPorts returns the reserved host ports.

type NodeReservedResources

type NodeReservedResources struct {
	Cpu      NodeReservedCpuResources
	Memory   NodeReservedMemoryResources
	Disk     NodeReservedDiskResources
	Networks NodeReservedNetworkResources
}

NodeReservedResources is used to capture the resources on a client node that should be reserved and not made available to jobs.

func (*NodeReservedResources) Comparable

func (n *NodeReservedResources) Comparable() *ComparableResources

Comparable returns a comparable version of the node's reserved resources. The returned resources doesn't contain any network information. This conversion can be lossy so care must be taken when using it.

func (*NodeReservedResources) Copy

func (n *NodeReservedResources) Copy() *NodeReservedResources

type NodeResources

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

NodeResources is used to define the resources available on a client node.

func (*NodeResources) Comparable

func (n *NodeResources) Comparable() *ComparableResources

Comparable returns a comparable version of the nodes resources. This conversion can be lossy so care must be taken when using it.

func (*NodeResources) Copy

func (n *NodeResources) Copy() *NodeResources

func (*NodeResources) Equals

func (n *NodeResources) Equals(o *NodeResources) bool

func (NodeResources) HashInclude

func (n NodeResources) HashInclude(field string, v interface{}) (bool, error)

HashInclude is used to blacklist uniquely identifying node fields from being included in the computed node class.

func (*NodeResources) Merge

func (n *NodeResources) Merge(o *NodeResources)

type NodeScoreMeta

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

NodeScoreMeta captures scoring meta data derived from different scoring factors.

func CopySliceNodeScoreMeta

func CopySliceNodeScoreMeta(s []*NodeScoreMeta) []*NodeScoreMeta

func (*NodeScoreMeta) Copy

func (s *NodeScoreMeta) Copy() *NodeScoreMeta

func (*NodeScoreMeta) Data

func (s *NodeScoreMeta) Data() interface{}

func (*NodeScoreMeta) Score

func (s *NodeScoreMeta) Score() float64

func (*NodeScoreMeta) String

func (s *NodeScoreMeta) String() string

type NodeServerInfo

type NodeServerInfo struct {
	// RPCAdvertiseAddr is the IP endpoint that a Nomad Server wishes to
	// be contacted at for RPCs.
	RPCAdvertiseAddr string

	// RpcMajorVersion is the major version number the Nomad Server
	// supports
	RPCMajorVersion int32

	// RpcMinorVersion is the minor version number the Nomad Server
	// supports
	RPCMinorVersion int32

	// Datacenter is the datacenter that a Nomad server belongs to
	Datacenter string
}

NodeServerInfo is used to in NodeUpdateResponse to return Nomad server information used in RPC server lists.

type NodeSpecificRequest

type NodeSpecificRequest struct {
	NodeID   string
	SecretID string
	QueryOptions
}

NodeSpecificRequest is used when we just need to specify a target node

type NodeUpdateDrainRequest

type NodeUpdateDrainRequest struct {
	NodeID        string
	DrainStrategy *DrainStrategy

	// COMPAT Remove in version 0.10
	// As part of Nomad 0.8 we have deprecated the drain boolean in favor of a
	// drain strategy but we need to handle the upgrade path where the Raft log
	// contains drain updates with just the drain boolean being manipulated.
	Drain bool

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

	// NodeEvent is the event added to the node
	NodeEvent *NodeEvent

	// UpdatedAt represents server time of receiving request
	UpdatedAt int64

	WriteRequest
}

NodeUpdateDrainRequest is used for updating the drain strategy

type NodeUpdateEligibilityRequest

type NodeUpdateEligibilityRequest struct {
	NodeID      string
	Eligibility string

	// NodeEvent is the event added to the node
	NodeEvent *NodeEvent

	// UpdatedAt represents server time of receiving request
	UpdatedAt int64

	WriteRequest
}

NodeUpdateEligibilityRequest is used for updating the scheduling eligibility

type NodeUpdateResponse

type NodeUpdateResponse struct {
	HeartbeatTTL    time.Duration
	EvalIDs         []string
	EvalCreateIndex uint64
	NodeModifyIndex uint64

	// Features informs clients what enterprise features are allowed
	Features uint64

	// LeaderRPCAddr is the RPC address of the current Raft Leader.  If
	// empty, the current Nomad Server is in the minority of a partition.
	LeaderRPCAddr string

	// NumNodes is the number of Nomad nodes attached to this quorum of
	// Nomad Servers at the time of the response.  This value can
	// fluctuate based on the health of the cluster between heartbeats.
	NumNodes int32

	// Servers is the full list of known Nomad servers in the local
	// region.
	Servers []*NodeServerInfo

	QueryMeta
}

NodeUpdateResponse is used to respond to a node update

type NodeUpdateStatusRequest

type NodeUpdateStatusRequest struct {
	NodeID    string
	Status    string
	NodeEvent *NodeEvent
	UpdatedAt int64
	WriteRequest
}

NodeUpdateStatusRequest is used for Node.UpdateStatus endpoint to update the status of a node.

type ObjectDiff

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

ObjectDiff contains the diff of two generic objects.

func (*ObjectDiff) GoString

func (o *ObjectDiff) GoString() string

func (*ObjectDiff) Less

func (o *ObjectDiff) Less(other *ObjectDiff) bool

type ObjectDiffs

type ObjectDiffs []*ObjectDiff

For sorting ObjectDiffs

func (ObjectDiffs) Len

func (o ObjectDiffs) Len() int

func (ObjectDiffs) Less

func (o ObjectDiffs) Less(i, j int) bool

func (ObjectDiffs) Swap

func (o ObjectDiffs) Swap(i, j int)

type ParameterizedJobConfig

type ParameterizedJobConfig struct {
	// Payload configure the payload requirements
	Payload string

	// MetaRequired is metadata keys that must be specified by the dispatcher
	MetaRequired []string

	// MetaOptional is metadata keys that may be specified by the dispatcher
	MetaOptional []string
}

ParameterizedJobConfig is used to configure the parameterized job

func (*ParameterizedJobConfig) Canonicalize

func (d *ParameterizedJobConfig) Canonicalize()

func (*ParameterizedJobConfig) Copy

func (d *ParameterizedJobConfig) Copy() *ParameterizedJobConfig

func (*ParameterizedJobConfig) Validate

func (d *ParameterizedJobConfig) Validate() error

type PeriodicConfig

type PeriodicConfig struct {
	// Enabled determines if the job should be run periodically.
	Enabled bool

	// Spec specifies the interval the job should be run as. It is parsed based
	// on the SpecType.
	Spec string

	// SpecType defines the format of the spec.
	SpecType string

	// ProhibitOverlap enforces that spawned jobs do not run in parallel.
	ProhibitOverlap bool

	// TimeZone is the user specified string that determines the time zone to
	// launch against. The time zones must be specified from IANA Time Zone
	// database, such as "America/New_York".
	// Reference: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
	// Reference: https://www.iana.org/time-zones
	TimeZone string
	// contains filtered or unexported fields
}

Periodic defines the interval a job should be run at.

func (*PeriodicConfig) Canonicalize

func (p *PeriodicConfig) Canonicalize()

func (*PeriodicConfig) Copy

func (p *PeriodicConfig) Copy() *PeriodicConfig

func (*PeriodicConfig) GetLocation

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

GetLocation returns the location to use for determining the time zone to run the periodic job against.

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.

func (*PeriodicConfig) Validate

func (p *PeriodicConfig) Validate() error

type PeriodicForceRequest

type PeriodicForceRequest struct {
	JobID string
	WriteRequest
}

PeriodicForceRequest is used to force a specific periodic job.

type PeriodicForceResponse

type PeriodicForceResponse struct {
	EvalID          string
	EvalCreateIndex uint64
	WriteMeta
}

PeriodicForceResponse is used to respond to a periodic job force launch

type PeriodicLaunch

type PeriodicLaunch struct {
	ID        string    // ID of the periodic job.
	Namespace string    // Namespace of the periodic job
	Launch    time.Time // The last launch time.

	// Raft Indexes
	CreateIndex uint64
	ModifyIndex uint64
}

PeriodicLaunch tracks the last launch time of a periodic job.

type Plan

type Plan struct {

	// EvalID is the evaluation ID this plan is associated with
	EvalID string

	// EvalToken is used to prevent a split-brain processing of
	// an evaluation. There should only be a single scheduler running
	// an Eval at a time, but this could be violated after a leadership
	// transition. This unique token is used to reject plans that are
	// being submitted from a different leader.
	EvalToken string

	// Priority is the priority of the upstream job
	Priority int

	// AllAtOnce is used to control if incremental scheduling of task groups
	// is allowed or if we must do a gang scheduling of the entire job.
	// If this is false, a plan may be partially applied. Otherwise, the
	// entire plan must be able to make progress.
	AllAtOnce bool

	// Job is the parent job of all the allocations in the Plan.
	// Since a Plan only involves a single Job, we can reduce the size
	// of the plan by only including it once.
	Job *Job

	// NodeUpdate contains all the allocations for each node. For each node,
	// this is a list of the allocations to update to either stop or evict.
	NodeUpdate map[string][]*Allocation

	// NodeAllocation contains all the allocations for each node.
	// The evicts must be considered prior to the allocations.
	NodeAllocation map[string][]*Allocation

	// Annotations contains annotations by the scheduler to be used by operators
	// to understand the decisions made by the scheduler.
	Annotations *PlanAnnotations

	// Deployment is the deployment created or updated by the scheduler that
	// should be applied by the planner.
	Deployment *Deployment

	// DeploymentUpdates is a set of status updates to apply to the given
	// deployments. This allows the scheduler to cancel any unneeded deployment
	// because the job is stopped or the update block is removed.
	DeploymentUpdates []*DeploymentStatusUpdate

	// NodePreemptions is a map from node id to a set of allocations from other
	// lower priority jobs that are preempted. Preempted allocations are marked
	// as evicted.
	NodePreemptions map[string][]*Allocation

	// SnapshotIndex is the Raft index of the snapshot used to create the
	// Plan. The leader will wait to evaluate the plan until its StateStore
	// has reached at least this index.
	SnapshotIndex uint64
	// contains filtered or unexported fields
}

Plan is used to submit a commit plan for task allocations. These are submitted to the leader which verifies that resources have not been overcommitted before admitting the plan.

func (*Plan) AppendAlloc

func (p *Plan) AppendAlloc(alloc *Allocation, job *Job)

AppendAlloc appends the alloc to the plan allocations. Uses the passed job if explicitly passed, otherwise it is assumed the alloc will use the plan Job version.

func (*Plan) AppendPreemptedAlloc

func (p *Plan) AppendPreemptedAlloc(alloc *Allocation, preemptingAllocID string)

AppendPreemptedAlloc is used to append an allocation that's being preempted to the plan. To minimize the size of the plan, this only sets a minimal set of fields in the allocation

func (*Plan) AppendStoppedAlloc

func (p *Plan) AppendStoppedAlloc(alloc *Allocation, desiredDesc, clientStatus, followupEvalID string)

AppendStoppedAlloc marks an allocation to be stopped. The clientStatus of the allocation may be optionally set by passing in a non-empty value.

func (*Plan) IsNoOp

func (p *Plan) IsNoOp() bool

IsNoOp checks if this plan would do nothing

func (*Plan) NormalizeAllocations

func (p *Plan) NormalizeAllocations()

NormalizeAllocations normalizes allocations to remove fields that can be fetched from the MemDB instead of sending over the wire

func (*Plan) PopUpdate

func (p *Plan) PopUpdate(alloc *Allocation)

type PlanAnnotations

type PlanAnnotations struct {
	// DesiredTGUpdates is the set of desired updates per task group.
	DesiredTGUpdates map[string]*DesiredUpdates

	// PreemptedAllocs is the set of allocations to be preempted to make the placement successful.
	PreemptedAllocs []*AllocListStub
}

PlanAnnotations holds annotations made by the scheduler to give further debug information to operators.

type PlanRequest

type PlanRequest struct {
	Plan *Plan
	WriteRequest
}

PlanRequest is used to submit an allocation plan to the leader

type PlanResponse

type PlanResponse struct {
	Result *PlanResult
	WriteMeta
}

PlanResponse is used to return from a PlanRequest

type PlanResult

type PlanResult struct {
	// NodeUpdate contains all the updates that were committed.
	NodeUpdate map[string][]*Allocation

	// NodeAllocation contains all the allocations that were committed.
	NodeAllocation map[string][]*Allocation

	// Deployment is the deployment that was committed.
	Deployment *Deployment

	// DeploymentUpdates is the set of deployment updates that were committed.
	DeploymentUpdates []*DeploymentStatusUpdate

	// NodePreemptions is a map from node id to a set of allocations from other
	// lower priority jobs that are preempted. Preempted allocations are marked
	// as stopped.
	NodePreemptions map[string][]*Allocation

	// RefreshIndex is the index the worker should refresh state up to.
	// This allows all evictions and allocations to be materialized.
	// If any allocations were rejected due to stale data (node state,
	// over committed) this can be used to force a worker refresh.
	RefreshIndex uint64

	// AllocIndex is the Raft index in which the evictions and
	// allocations took place. This is used for the write index.
	AllocIndex uint64
}

PlanResult is the result of a plan submitted to the leader.

func (*PlanResult) FullCommit

func (p *PlanResult) FullCommit(plan *Plan) (bool, int, int)

FullCommit is used to check if all the allocations in a plan were committed as part of the result. Returns if there was a match, and the number of expected and actual allocations.

func (*PlanResult) IsNoOp

func (p *PlanResult) IsNoOp() bool

IsNoOp checks if this plan result would do nothing

type Port

type Port struct {
	// Label is the key for HCL port stanzas: port "foo" {}
	Label string

	// Value is the static or dynamic port value. For dynamic ports this
	// will be 0 in the jobspec and set by the scheduler.
	Value int

	// To is the port inside a network namespace where this port is
	// forwarded. -1 is an internal sentinel value used by Consul Connect
	// to mean "same as the host port."
	To int

	// HostNetwork is the name of the network this port should be assigned
	// to. Jobs with a HostNetwork set can only be placed on nodes with
	// that host network available.
	HostNetwork string
}

type PreemptionConfig

type PreemptionConfig struct {
	// SystemSchedulerEnabled specifies if preemption is enabled for system jobs
	SystemSchedulerEnabled bool `hcl:"system_scheduler_enabled"`

	// BatchSchedulerEnabled specifies if preemption is enabled for batch jobs
	BatchSchedulerEnabled bool `hcl:"batch_scheduler_enabled"`

	// ServiceSchedulerEnabled specifies if preemption is enabled for service jobs
	ServiceSchedulerEnabled bool `hcl:"service_scheduler_enabled"`
}

PreemptionConfig specifies whether preemption is enabled based on scheduler type

type QueryMeta

type QueryMeta struct {
	// This is the index associated with the read
	Index uint64

	// If AllowStale is used, this is time elapsed since
	// last contact between the follower and leader. This
	// can be used to gauge staleness.
	LastContact time.Duration

	// Used to indicate if there is a known leader node
	KnownLeader bool
}

QueryMeta allows a query response to include potentially useful metadata about a query

type QueryOptions

type QueryOptions struct {
	// The target region for this query
	Region string

	// Namespace is the target namespace for the query.
	//
	// Since handlers do not have a default value set they should access
	// the Namespace via the RequestNamespace method.
	//
	// Requests accessing specific namespaced objects must check ACLs
	// against the namespace of the object, not the namespace in the
	// request.
	Namespace string

	// If set, wait until query exceeds given index. Must be provided
	// with MaxQueryTime.
	MinQueryIndex uint64

	// Provided with MinQueryIndex to wait for change.
	MaxQueryTime time.Duration

	// If set, any follower can service the request. Results
	// may be arbitrarily stale.
	AllowStale bool

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

	// AuthToken is secret portion of the ACL token used for the request
	AuthToken string

	InternalRpcInfo
}

QueryOptions is used to specify various flags for read queries

func (QueryOptions) AllowStaleRead

func (q QueryOptions) AllowStaleRead() bool

func (QueryOptions) IsRead

func (q QueryOptions) IsRead() bool

QueryOption only applies to reads, so always true

func (QueryOptions) RequestNamespace

func (q QueryOptions) RequestNamespace() string

RequestNamespace returns the request's namespace or the default namespace if no explicit namespace was sent.

Requests accessing specific namespaced objects must check ACLs against the namespace of the object, not the namespace in the request.

func (QueryOptions)