api

package module
v0.0.0-...-7874d21 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2024 License: MPL-2.0 Imports: 35 Imported by: 920

Documentation

Index

Constants

View Source
const (
	// ACLAuthMethodTokenLocalityLocal is the ACLAuthMethod.TokenLocality that
	// will generate ACL tokens which can only be used on the local cluster the
	// request was made.
	ACLAuthMethodTokenLocalityLocal = "local"

	// ACLAuthMethodTokenLocalityGlobal is the ACLAuthMethod.TokenLocality that
	// will generate ACL tokens which can be used on all federated clusters.
	ACLAuthMethodTokenLocalityGlobal = "global"

	// ACLAuthMethodTypeOIDC the ACLAuthMethod.Type and represents an
	// auth-method which uses the OIDC protocol.
	ACLAuthMethodTypeOIDC = "OIDC"

	// ACLAuthMethodTypeJWT the ACLAuthMethod.Type and represents an auth-method
	// which uses the JWT type.
	ACLAuthMethodTypeJWT = "JWT"
)
View Source
const (
	// ACLBindingRuleBindTypeRole is the ACL binding rule bind type that only
	// allows the binding rule to function if a role exists at login-time. The
	// role will be specified within the ACLBindingRule.BindName parameter, and
	// will identify whether this is an ID or Name.
	ACLBindingRuleBindTypeRole = "role"

	// ACLBindingRuleBindTypePolicy is the ACL binding rule bind type that
	// assigns a policy to the generate ACL token. The role will be specified
	// within the ACLBindingRule.BindName parameter, and will be the policy
	// name.
	ACLBindingRuleBindTypePolicy = "policy"

	// ACLBindingRuleBindTypeManagement is the ACL binding rule bind type that
	// will generate management ACL tokens when matched.
	ACLBindingRuleBindTypeManagement = "management"
)
View Source
const (
	AllocDesiredStatusRun   = "run"   // Allocation should run
	AllocDesiredStatusStop  = "stop"  // Allocation should stop
	AllocDesiredStatusEvict = "evict" // Allocation should stop, and was evicted
)
View Source
const (
	AllocClientStatusPending  = "pending"
	AllocClientStatusRunning  = "running"
	AllocClientStatusComplete = "complete"
	AllocClientStatusFailed   = "failed"
	AllocClientStatusLost     = "lost"
	AllocClientStatusUnknown  = "unknown"
)
View Source
const (
	// AllNamespacesNamespace is a sentinel Namespace value to indicate that api should search for
	// jobs and allocations in all the namespaces the requester can access.
	AllNamespacesNamespace = "*"

	// PermissionDeniedErrorContent is the string content of an error returned
	// by the API which indicates the caller does not have permission to
	// perform the action.
	PermissionDeniedErrorContent = "Permission denied"
)
View Source
const (
	ConstraintDistinctProperty  = "distinct_property"
	ConstraintDistinctHosts     = "distinct_hosts"
	ConstraintRegex             = "regexp"
	ConstraintVersion           = "version"
	ConstraintSemver            = "semver"
	ConstraintSetContains       = "set_contains"
	ConstraintSetContainsAll    = "set_contains_all"
	ConstraintSetContainsAny    = "set_contains_any"
	ConstraintAttributeIsSet    = "is_set"
	ConstraintAttributeIsNotSet = "is_not_set"
)
View Source
const (
	CSIVolumeTypeHost = "host"
	CSIVolumeTypeCSI  = "csi"
)
View Source
const (
	DeploymentStatusRunning    = "running"
	DeploymentStatusPaused     = "paused"
	DeploymentStatusFailed     = "failed"
	DeploymentStatusSuccessful = "successful"
	DeploymentStatusCancelled  = "cancelled"
	DeploymentStatusPending    = "pending"
	DeploymentStatusBlocked    = "blocked"
	DeploymentStatusUnblocking = "unblocking"
)
View Source
const (
	EvalStatusBlocked   = "blocked"
	EvalStatusPending   = "pending"
	EvalStatusComplete  = "complete"
	EvalStatusFailed    = "failed"
	EvalStatusCancelled = "canceled"
)
View Source
const (
	// OriginStart and OriginEnd are the available parameters for the origin
	// argument when streaming a file. They respectively offset from the start
	// and end of a file.
	OriginStart = "start"
	OriginEnd   = "end"

	// FSLogNameStdout is the name given to the stdout log stream of a task. It
	// can be used when calling AllocFS.Logs as the logType parameter.
	FSLogNameStdout = "stdout"

	// FSLogNameStderr is the name given to the stderr log stream of a task. It
	// can be used when calling AllocFS.Logs as the logType parameter.
	FSLogNameStderr = "stderr"
)
View Source
const (
	// JobTypeService indicates a long-running processes
	JobTypeService = "service"

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

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

	// JobTypeSysbatch indicates a short-lived system process that should run
	// on all clients.
	JobTypeSysbatch = "sysbatch"

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

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

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

	// For Job configuration, GlobalRegion is a sentinel region value
	// that users may specify to indicate the job should be run on
	// the region of the node that the job was submitted to.
	// For Client configuration, if no region information is given,
	// the client node will default to be part of the GlobalRegion.
	GlobalRegion = "global"
)
View Source
const (
	// JobPeriodicLaunchSuffix is the string appended to the periodic jobs ID
	// when launching derived instances of it.
	JobPeriodicLaunchSuffix = "/periodic-"

	// JobDispatchLaunchSuffix is the string appended to the parameterized job's ID
	// when dispatching instances of it.
	JobDispatchLaunchSuffix = "/dispatch-"
)
View Source
const (
	RootKeyStateInactive   RootKeyState = "inactive"
	RootKeyStateActive                  = "active"
	RootKeyStateRekeying                = "rekeying"
	RootKeyStateDeprecated              = "deprecated"
)
View Source
const (

	// DefaultLockTTL is the default value used to maintain a lock before it needs to
	// be renewed. The actual value comes from the experience with Consul.
	DefaultLockTTL = 15 * time.Second

	// DefaultLockDelay is the default a lock will be blocked after the TTL
	// went by without any renews. It is intended to prevent split brain situations.
	// The actual value comes from the experience with Consul.
	DefaultLockDelay = 15 * time.Second
)
View Source
const (
	// NodePoolAll is the node pool that always includes all nodes.
	NodePoolAll = "all"

	// NodePoolDefault is the default node pool.
	NodePoolDefault = "default"
)
View Source
const (
	NodeStatusInit         = "initializing"
	NodeStatusReady        = "ready"
	NodeStatusDown         = "down"
	NodeStatusDisconnected = "disconnected"

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

	DrainStatusDraining DrainStatus = "draining"
	DrainStatusComplete DrainStatus = "complete"
	DrainStatusCanceled DrainStatus = "canceled"
)
View Source
const (
	NodeEventSubsystemDrain     = "Drain"
	NodeEventSubsystemDriver    = "Driver"
	NodeEventSubsystemHeartbeat = "Heartbeat"
	NodeEventSubsystemCluster   = "Cluster"
)
View Source
const (
	OnUpdateRequireHealthy = "require_healthy"
	OnUpdateIgnoreWarn     = "ignore_warnings"
	OnUpdateIgnore         = "ignore"

	// ServiceProviderConsul is the default provider for services when no
	// parameter is set.
	ServiceProviderConsul = "consul"
)
View Source
const (
	// RestartPolicyModeDelay causes an artificial delay till the next interval is
	// reached when the specified attempts have been reached in the interval.
	RestartPolicyModeDelay = "delay"

	// RestartPolicyModeFail causes a job to fail if the specified number of
	// attempts are reached within an interval.
	RestartPolicyModeFail = "fail"

	// ReconcileOption is used to specify the behavior of the reconciliation process
	// between the original allocations and the replacements when a previously
	// disconnected client comes back online.
	ReconcileOptionKeepOriginal    = "keep_original"
	ReconcileOptionKeepReplacement = "keep_replacement"
	ReconcileOptionBestScore       = "best_score"
	ReconcileOptionLongestRunning  = "longest_running"
)
View Source
const (
	VolumeMountPropagationPrivate       = "private"
	VolumeMountPropagationHostToTask    = "host-to-task"
	VolumeMountPropagationBidirectional = "bidirectional"
)
View Source
const (
	TaskLifecycleHookPrestart  = "prestart"
	TaskLifecycleHookPoststart = "poststart"
	TaskLifecycleHookPoststop  = "poststop"
)
View Source
const (
	TaskSetup                  = "Task Setup"
	TaskSetupFailure           = "Setup Failure"
	TaskDriverFailure          = "Driver Failure"
	TaskDriverMessage          = "Driver"
	TaskReceived               = "Received"
	TaskFailedValidation       = "Failed Validation"
	TaskStarted                = "Started"
	TaskTerminated             = "Terminated"
	TaskKilling                = "Killing"
	TaskKilled                 = "Killed"
	TaskRestarting             = "Restarting"
	TaskNotRestarting          = "Not Restarting"
	TaskDownloadingArtifacts   = "Downloading Artifacts"
	TaskArtifactDownloadFailed = "Failed Artifact Download"
	TaskSiblingFailed          = "Sibling Task Failed"
	TaskSignaling              = "Signaling"
	TaskRestartSignal          = "Restart Signaled"
	TaskLeaderDead             = "Leader Task Dead"
	TaskBuildingTaskDir        = "Building Task Directory"
	TaskClientReconnected      = "Reconnected"
)
View Source
const (
	AllocRestartReasonWithinPolicy = "Restart within policy"
)
View Source
const (
	// ErrVariableNotFound was used as the content of an error string.
	//
	// Deprecated: use ErrVariablePathNotFound instead.
	ErrVariableNotFound = "variable not found"
)
View Source
const (
	// RegisterEnforceIndexErrPrefix is the prefix to use in errors caused by
	// enforcing the job modify index during registers.
	RegisterEnforceIndexErrPrefix = "Enforcing job modify index"
)
View Source
const (
	// ScalingPolicyTypeHorizontal indicates a policy that does horizontal scaling.
	ScalingPolicyTypeHorizontal = "horizontal"
)

Variables

View Source
var (
	// ErrLockConflict is returned in case a lock operation can't be performed
	// because the caller is not the current holder of the lock.
	ErrLockConflict = errors.New("conflicting operation over lock")

	//LockNoPathErr is returned when no path is provided in the variable to be
	// used for the lease mechanism
	LockNoPathErr = errors.New("variable's path can't be empty")
)
View Source
var (
	// ClientConnTimeout is the timeout applied when attempting to contact a
	// client directly before switching to a connection through the Nomad
	// server. For cluster topologies where API consumers don't have network
	// access to Nomad clients, set this to a small value (ex 1ms) to avoid
	// pausing on client APIs such as AllocFS.
	ClientConnTimeout = 1 * time.Second
)
View Source
var (
	// ErrVariablePathNotFound is returned when trying to read a variable that
	// does not exist.
	ErrVariablePathNotFound = errors.New("variable not found")
)
View Source
var (
	// NodeDownErr marks an operation as not able to complete since the node is
	// down.
	NodeDownErr = errors.New("node down")
)

Functions

func AllocSuffix

func AllocSuffix(name string) string

func ConfigureTLS

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

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

Types

type ACLAuth

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

ACLAuth is used to query the ACL auth endpoints.

func (*ACLAuth) CompleteAuth

func (a *ACLAuth) CompleteAuth(req *ACLOIDCCompleteAuthRequest, q *WriteOptions) (*ACLToken, *WriteMeta, error)

CompleteAuth exchanges the OIDC provider token for a Nomad token with the appropriate claims attached.

func (*ACLAuth) GetAuthURL

GetAuthURL generates the OIDC provider authentication URL. This URL should be visited in order to sign in to the provider.

func (*ACLAuth) Login

func (a *ACLAuth) Login(req *ACLLoginRequest, q *WriteOptions) (*ACLToken, *WriteMeta, error)

Login exchanges the third party token for a Nomad token with the appropriate claims attached.

type ACLAuthMethod

type ACLAuthMethod struct {

	// Name is the identifier for this auth-method and is a required parameter.
	Name string

	// Type is the SSO identifier this auth-method is. Nomad currently only
	// supports "oidc" and the API contains ACLAuthMethodTypeOIDC for
	// convenience.
	Type string

	// Defines whether the auth-method creates a local or global token when
	// performing SSO login. This should be set to either "local" or "global"
	// and the API contains ACLAuthMethodTokenLocalityLocal and
	// ACLAuthMethodTokenLocalityGlobal for convenience.
	TokenLocality string

	// TokenNameFormat defines the HIL template to use when building the token name
	TokenNameFormat string

	// MaxTokenTTL is the maximum life of a token created by this method.
	MaxTokenTTL time.Duration

	// Default identifies whether this is the default auth-method to use when
	// attempting to login without specifying an auth-method name to use.
	Default bool

	// Config contains the detailed configuration which is specific to the
	// auth-method.
	Config *ACLAuthMethodConfig

	CreateTime  time.Time
	ModifyTime  time.Time
	CreateIndex uint64
	ModifyIndex uint64
}

ACLAuthMethod is used to capture the properties of an authentication method used for single sing-on.

func (*ACLAuthMethod) MarshalJSON

func (m *ACLAuthMethod) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface and allows ACLAuthMethod.MaxTokenTTL to be marshaled correctly.

func (*ACLAuthMethod) UnmarshalJSON

func (m *ACLAuthMethod) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface and allows ACLAuthMethod.MaxTokenTTL to be unmarshalled correctly.

type ACLAuthMethodConfig

type ACLAuthMethodConfig struct {
	// A list of PEM-encoded public keys to use to authenticate signatures
	// locally
	JWTValidationPubKeys []string
	// JSON Web Key Sets url for authenticating signatures
	JWKSURL string
	// The OIDC Discovery URL, without any .well-known component (base path)
	OIDCDiscoveryURL string
	// The OAuth Client ID configured with the OIDC provider
	OIDCClientID string
	// The OAuth Client Secret configured with the OIDC provider
	OIDCClientSecret string
	// Disable claims from the OIDC UserInfo endpoint
	OIDCDisableUserInfo bool
	// List of OIDC scopes
	OIDCScopes []string
	// List of auth claims that are valid for login
	BoundAudiences []string
	// The value against which to match the iss claim in a JWT
	BoundIssuer []string
	// A list of allowed values for redirect_uri
	AllowedRedirectURIs []string
	// PEM encoded CA certs for use by the TLS client used to talk with the
	// OIDC Discovery URL.
	DiscoveryCaPem []string
	// PEM encoded CA cert for use by the TLS client used to talk with the JWKS
	// URL
	JWKSCACert string
	// A list of supported signing algorithms
	SigningAlgs []string
	// Duration in seconds of leeway when validating expiration of a token to
	// account for clock skew
	ExpirationLeeway time.Duration
	// Duration in seconds of leeway when validating not before values of a
	// token to account for clock skew.
	NotBeforeLeeway time.Duration
	// Duration in seconds of leeway when validating all claims to account for
	// clock skew.
	ClockSkewLeeway time.Duration
	// Mappings of claims (key) that will be copied to a metadata field
	// (value).
	ClaimMappings     map[string]string
	ListClaimMappings map[string]string
}

ACLAuthMethodConfig is used to store configuration of an auth method.

func (*ACLAuthMethodConfig) MarshalJSON

func (c *ACLAuthMethodConfig) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface and allows time.Duration fields to be marshaled correctly.

func (*ACLAuthMethodConfig) UnmarshalJSON

func (c *ACLAuthMethodConfig) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface and allows time.Duration fields to be unmarshalled correctly.

type ACLAuthMethodListStub

type ACLAuthMethodListStub struct {
	Name    string
	Type    string
	Default bool

	CreateIndex uint64
	ModifyIndex uint64
}

ACLAuthMethodListStub is the stub object returned when performing a listing of ACL auth-methods. It is intentionally minimal due to the unauthenticated nature of the list endpoint.

type ACLAuthMethods

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

ACLAuthMethods is used to query the ACL auth-methods endpoints.

func (*ACLAuthMethods) Create

func (a *ACLAuthMethods) Create(authMethod *ACLAuthMethod, w *WriteOptions) (*ACLAuthMethod, *WriteMeta, error)

Create is used to create an ACL auth-method.

func (*ACLAuthMethods) Delete

func (a *ACLAuthMethods) Delete(authMethodName string, w *WriteOptions) (*WriteMeta, error)

Delete is used to delete an ACL auth-method.

func (*ACLAuthMethods) Get

func (a *ACLAuthMethods) Get(authMethodName string, q *QueryOptions) (*ACLAuthMethod, *QueryMeta, error)

Get is used to look up an ACL auth-method.

func (*ACLAuthMethods) List

List is used to detail all the ACL auth-methods currently stored within state.

func (*ACLAuthMethods) Update

func (a *ACLAuthMethods) Update(authMethod *ACLAuthMethod, w *WriteOptions) (*ACLAuthMethod, *WriteMeta, error)

Update is used to update an existing ACL auth-method.

type ACLBindingRule

type ACLBindingRule struct {

	// ID is an internally generated UUID for this rule and is controlled by
	// Nomad.
	ID string

	// Description is a human-readable, operator set description that can
	// provide additional context about the binding rule. This is an
	// operational field.
	Description string

	// AuthMethod is the name of the auth method for which this rule applies
	// to. This is required and the method must exist within state before the
	// cluster administrator can create the rule.
	AuthMethod string

	// Selector is an expression that matches against verified identity
	// attributes returned from the auth method during login. This is optional
	// and when not set, provides a catch-all rule.
	Selector string

	// BindType adjusts how this binding rule is applied at login time. The
	// valid values are ACLBindingRuleBindTypeRole,
	// ACLBindingRuleBindTypePolicy, and ACLBindingRuleBindTypeManagement.
	BindType string

	// BindName is the target of the binding. Can be lightly templated using
	// HIL ${foo} syntax from available field names. How it is used depends
	// upon the BindType.
	BindName string

	CreateTime  time.Time
	ModifyTime  time.Time
	CreateIndex uint64
	ModifyIndex uint64
}

ACLBindingRule contains a direct relation to an ACLAuthMethod and represents a rule to apply when logging in via the named AuthMethod. This allows the transformation of OIDC provider claims, to Nomad based ACL concepts such as ACL Roles and Policies.

type ACLBindingRuleListStub

type ACLBindingRuleListStub struct {

	// ID is an internally generated UUID for this role and is controlled by
	// Nomad.
	ID string

	// Description is a human-readable, operator set description that can
	// provide additional context about the binding role. This is an
	// operational field.
	Description string

	// AuthMethod is the name of the auth method for which this rule applies
	// to. This is required and the method must exist within state before the
	// cluster administrator can create the rule.
	AuthMethod string

	CreateIndex uint64
	ModifyIndex uint64
}

ACLBindingRuleListStub is the stub object returned when performing a listing of ACL binding rules.

type ACLBindingRules

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

ACLBindingRules is used to query the ACL auth-methods endpoints.

func (*ACLBindingRules) Create

func (a *ACLBindingRules) Create(bindingRule *ACLBindingRule, w *WriteOptions) (*ACLBindingRule, *WriteMeta, error)

Create is used to create an ACL binding rule.

func (*ACLBindingRules) Delete

func (a *ACLBindingRules) Delete(bindingRuleID string, w *WriteOptions) (*WriteMeta, error)

Delete is used to delete an ACL binding rule.

func (*ACLBindingRules) Get

func (a *ACLBindingRules) Get(bindingRuleID string, q *QueryOptions) (*ACLBindingRule, *QueryMeta, error)

Get is used to look up an ACL binding rule.

func (*ACLBindingRules) List

List is used to detail all the ACL binding rules currently stored within state.

func (*ACLBindingRules) Update

func (a *ACLBindingRules) Update(bindingRule *ACLBindingRule, w *WriteOptions) (*ACLBindingRule, *WriteMeta, error)

Update is used to update an existing ACL binding rule.

type ACLLoginRequest

type ACLLoginRequest struct {
	// AuthMethodName is the name of the auth method being used to login. This
	// is a required parameter.
	AuthMethodName string
	// LoginToken is the token used to login. This is a required parameter.
	LoginToken string
}

ACLLoginRequest is the request object to begin auth with an external bearer token provider.

type ACLOIDC deprecated

type ACLOIDC struct {
	ACLAuth
	// contains filtered or unexported fields
}

ACLOIDC is used to query the ACL OIDC endpoints.

Deprecated: ACLOIDC is deprecated, use ACLAuth instead.

type ACLOIDCAuthURLRequest

type ACLOIDCAuthURLRequest struct {

	// AuthMethodName is the OIDC auth-method to use. This is a required
	// parameter.
	AuthMethodName string

	// RedirectURI is the URL that authorization should redirect to. This is a
	// required parameter.
	RedirectURI string

	// ClientNonce is a randomly generated string to prevent replay attacks. It
	// is up to the client to generate this and Go integrations should use the
	// oidc.NewID function within the hashicorp/cap library.
	ClientNonce string
}

ACLOIDCAuthURLRequest is the request to make when starting the OIDC authentication login flow.

type ACLOIDCAuthURLResponse

type ACLOIDCAuthURLResponse struct {

	// AuthURL is URL to begin authorization and is where the user logging in
	// should go.
	AuthURL string
}

ACLOIDCAuthURLResponse is the response when starting the OIDC authentication login flow.

type ACLOIDCCompleteAuthRequest

type ACLOIDCCompleteAuthRequest struct {

	// AuthMethodName is the name of the auth method being used to login via
	// OIDC. This will match AuthUrlArgs.AuthMethodName. This is a required
	// parameter.
	AuthMethodName string

	// ClientNonce, State, and Code are provided from the parameters given to
	// the redirect URL. These are all required parameters.
	ClientNonce string
	State       string
	Code        string

	// RedirectURI is the URL that authorization should redirect to. This is a
	// required parameter.
	RedirectURI string
}

ACLOIDCCompleteAuthRequest is the request object to begin completing the OIDC auth cycle after receiving the callback from the OIDC provider.

type ACLPolicies

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

ACLPolicies is used to query the ACL Policy endpoints.

func (*ACLPolicies) Delete

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

Delete is used to delete a policy

func (*ACLPolicies) Info

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

Info is used to query a specific policy

func (*ACLPolicies) List

List is used to dump all of the policies.

func (*ACLPolicies) Upsert

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

Upsert is used to create or update a policy

type ACLPolicy

type ACLPolicy struct {
	Name        string
	Description string
	Rules       string
	JobACL      *JobACL

	CreateIndex uint64
	ModifyIndex uint64
}

ACLPolicy is used to represent an ACL policy

type ACLPolicyListStub

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

ACLPolicyListStub is used to for listing ACL policies

type ACLRole

type ACLRole struct {

	// ID is an internally generated UUID for this role and is controlled by
	// Nomad. It can be used after role creation to update the existing role.
	ID string

	// Name is unique across the entire set of federated clusters and is
	// supplied by the operator on role creation. The name can be modified by
	// updating the role and including the Nomad generated ID. This update will
	// not affect tokens created and linked to this role. This is a required
	// field.
	Name string

	// Description is a human-readable, operator set description that can
	// provide additional context about the role. This is an optional field.
	Description string

	// Policies is an array of ACL policy links. Although currently policies
	// can only be linked using their name, in the future we will want to add
	// IDs also and thus allow operators to specify either a name, an ID, or
	// both. At least one entry is required.
	Policies []*ACLRolePolicyLink

	CreateIndex uint64
	ModifyIndex uint64
}

ACLRole is an abstraction for the ACL system which allows the grouping of ACL policies into a single object. ACL tokens can be created and linked to a role; the token then inherits all the permissions granted by the policies.

type ACLRoleListStub

type ACLRoleListStub struct {

	// ID is an internally generated UUID for this role and is controlled by
	// Nomad.
	ID string

	// Name is unique across the entire set of federated clusters and is
	// supplied by the operator on role creation. The name can be modified by
	// updating the role and including the Nomad generated ID. This update will
	// not affect tokens created and linked to this role. This is a required
	// field.
	Name string

	// Description is a human-readable, operator set description that can
	// provide additional context about the role. This is an operational field.
	Description string

	// Policies is an array of ACL policy links. Although currently policies
	// can only be linked using their name, in the future we will want to add
	// IDs also and thus allow operators to specify either a name, an ID, or
	// both.
	Policies []*ACLRolePolicyLink

	CreateIndex uint64
	ModifyIndex uint64
}

ACLRoleListStub is the stub object returned when performing a listing of ACL roles. While it might not currently be different to the full response object, it allows us to future-proof the RPC in the event the ACLRole object grows over time.

type ACLRolePolicyLink struct {

	// Name is the ACLPolicy.Name value which will be linked to the ACL role.
	Name string
}

ACLRolePolicyLink is used to link a policy to an ACL role. We use a struct rather than a list of strings as in the future we will want to add IDs to policies and then link via these.

type ACLRoles

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

ACLRoles is used to query the ACL Role endpoints.

func (*ACLRoles) Create

func (a *ACLRoles) Create(role *ACLRole, w *WriteOptions) (*ACLRole, *WriteMeta, error)

Create is used to create an ACL role.

func (*ACLRoles) Delete

func (a *ACLRoles) Delete(roleID string, w *WriteOptions) (*WriteMeta, error)

Delete is used to delete an ACL role.

func (*ACLRoles) Get

func (a *ACLRoles) Get(roleID string, q *QueryOptions) (*ACLRole, *QueryMeta, error)

Get is used to look up an ACL role.

func (*ACLRoles) GetByName

func (a *ACLRoles) GetByName(roleName string, q *QueryOptions) (*ACLRole, *QueryMeta, error)

GetByName is used to look up an ACL role using its name.

func (*ACLRoles) List

func (a *ACLRoles) List(q *QueryOptions) ([]*ACLRoleListStub, *QueryMeta, error)

List is used to detail all the ACL roles currently stored within state.

func (*ACLRoles) Update

func (a *ACLRoles) Update(role *ACLRole, w *WriteOptions) (*ACLRole, *WriteMeta, error)

Update is used to update an existing ACL role.

type ACLToken

type ACLToken struct {
	AccessorID string
	SecretID   string
	Name       string
	Type       string
	Policies   []string

	// Roles represents the ACL roles that this token is tied to. The token
	// will inherit the permissions of all policies detailed within the role.
	Roles []*ACLTokenRoleLink

	Global     bool
	CreateTime time.Time

	// ExpirationTime represents the point after which a token should be
	// considered revoked and is eligible for destruction. The zero value of
	// time.Time does not respect json omitempty directives, so we must use a
	// pointer.
	ExpirationTime *time.Time `json:",omitempty"`

	// ExpirationTTL is a convenience field for helping set ExpirationTime to a
	// value of CreateTime+ExpirationTTL. This can only be set during token
	// creation. This is a string version of a time.Duration like "2m".
	ExpirationTTL time.Duration `json:",omitempty"`

	CreateIndex uint64
	ModifyIndex uint64
}

ACLToken represents a client token which is used to Authenticate

func (*ACLToken) MarshalJSON

func (a *ACLToken) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface and allows ACLToken.ExpirationTTL to be marshaled correctly.

func (*ACLToken) UnmarshalJSON

func (a *ACLToken) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON implements the json.Unmarshaler interface and allows ACLToken.ExpirationTTL to be unmarshalled correctly.

type ACLTokenListStub

type ACLTokenListStub struct {
	AccessorID string
	Name       string
	Type       string
	Policies   []string
	Roles      []*ACLTokenRoleLink
	Global     bool
	CreateTime time.Time

	// ExpirationTime represents the point after which a token should be
	// considered revoked and is eligible for destruction. A nil value
	// indicates no expiration has been set on the token.
	ExpirationTime *time.Time `json:",omitempty"`

	CreateIndex uint64
	ModifyIndex uint64
}
type ACLTokenRoleLink struct {

	// ID is the ACLRole.ID UUID. This field is immutable and represents the
	// absolute truth for the link.
	ID string

	// Name is the human friendly identifier for the ACL role and is a
	// convenience field for operators.
	Name string
}

ACLTokenRoleLink is used to link an ACL token to an ACL role. The ACL token can therefore inherit all the ACL policy permissions that the ACL role contains.

type ACLTokens

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

ACLTokens is used to query the ACL token endpoints.

func (*ACLTokens) Bootstrap

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

Bootstrap is used to get the initial bootstrap token

See BootstrapOpts to set ACL bootstrapping options.

func (*ACLTokens) BootstrapOpts

func (a *ACLTokens) BootstrapOpts(btoken string, q *WriteOptions) (*ACLToken, *WriteMeta, error)

BootstrapOpts is used to get the initial bootstrap token or pass in the one that was provided in the API

func (*ACLTokens) Create

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

Create is used to create a token

func (*ACLTokens) Delete

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

Delete is used to delete a token

func (*ACLTokens) ExchangeOneTimeToken

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

ExchangeOneTimeToken is used to create a one-time token

func (*ACLTokens) Info

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

Info is used to query a token

func (*ACLTokens) List

List is used to dump all of the tokens.

func (*ACLTokens) Self

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

Self is used to query our own token

func (*ACLTokens) Update

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

Update is used to update an existing token

func (*ACLTokens) UpsertOneTimeToken

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

UpsertOneTimeToken is used to create a one-time token

type Action

type Action struct {
	Name    string   `hcl:"name,label"`
	Command string   `mapstructure:"command" hcl:"command"`
	Args    []string `mapstructure:"args" hcl:"args,optional"`
}

type Affinity

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

Affinity is used to serialize task group affinities

func NewAffinity

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

func (*Affinity) Canonicalize

func (a *Affinity) Canonicalize()

type Agent

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

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

func (*Agent) CPUProfile

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

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

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

func (*Agent) Datacenter

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

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

func (*Agent) ForceLeave

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

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

func (*Agent) ForceLeaveWithOptions

func (a *Agent) ForceLeaveWithOptions(node string, opts ForceLeaveOpts) error

ForceLeaveWithOptions is used to eject an existing node from the cluster with additional options such as prune.

func (*Agent) GetSchedulerWorkerConfig

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

GetSchedulerWorkerConfig returns the targeted agent's worker pool configuration

func (*Agent) GetSchedulerWorkersInfo

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

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

func (*Agent) Health

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

Health queries the agent's health

func (*Agent) Host

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

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

func (*Agent) InstallKey

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

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

func (*Agent) Join

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

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

func (*Agent) ListKeys

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

ListKeys returns the list of installed keys

func (*Agent) Lookup

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

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

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

func (*Agent) Members

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

Members is used to query all of the known server members

func (*Agent) MembersOpts

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

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

func (*Agent) Monitor

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

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

func (*Agent) NodeName

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

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

func (*Agent) Region

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

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

func (*Agent) RemoveKey

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

RemoveKey removes a particular key from keyrings of serf members

func (*Agent) Self

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

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

func (*Agent) Servers

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

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

func (*Agent) SetSchedulerWorkerConfig

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

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

func (*Agent) SetServers

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

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

func (*Agent) Trace

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

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

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

func (*Agent) UseKey

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

UseKey uses a key from the keyring of serf members

type AgentHealth

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

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

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

type AgentHealthResponse

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

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

type AgentMember

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

AgentMember represents a cluster member known to the agent

type AgentMembersNameSort

type AgentMembersNameSort []*AgentMember

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

func (AgentMembersNameSort) Len

func (a AgentMembersNameSort) Len() int

func (AgentMembersNameSort) Less

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

func (AgentMembersNameSort) Swap

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

type AgentSchedulerWorkerConfigRequest

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

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

type AgentSchedulerWorkerConfigResponse

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

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

type AgentSchedulerWorkerInfo

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

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

type AgentSchedulerWorkersInfo

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

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

type AgentSelf

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

type AggregateSample

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

AggregateSample is used to hold aggregate metrics about a sample

type AllocCheckStatus

type AllocCheckStatus struct {
	ID         string
	Check      string
	Group      string
	Mode       string
	Output     string
	Service    string
	Task       string
	Status     string
	StatusCode int
	Timestamp  int64
}

AllocCheckStatus contains the current status of a nomad service discovery check.

type AllocCheckStatuses

type AllocCheckStatuses map[string]AllocCheckStatus

AllocCheckStatuses holds the set of nomad service discovery checks within the allocation (including group and task level service checks).

type AllocDeploymentStatus

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

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

type AllocFS

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

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

func (*AllocFS) Cat

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

Cat is used to read contents of a file at the given path in an allocation directory. Note: for cluster topologies where API consumers don't have network access to Nomad clients, set api.ClientConnTimeout to a small value (ex 1ms) to avoid long pauses on this API call.

func (*AllocFS) List

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

List is used to list the files at a given path of an allocation directory. Note: for cluster topologies where API consumers don't have network access to Nomad clients, set api.ClientConnTimeout to a small value (ex 1ms) to avoid long pauses on this API call.

func (*AllocFS) Logs

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

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

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

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

Note: for cluster topologies where API consumers don't have network access to Nomad clients, set api.ClientConnTimeout to a small value (ex 1ms) to avoid long pauses on this API call.

func (*AllocFS) ReadAt

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

ReadAt is used to read bytes at a given offset until limit at the given path in an allocation directory. If limit is <= 0, there is no limit. Note: for cluster topologies where API consumers don't have network access to Nomad clients, set api.ClientConnTimeout to a small value (ex 1ms) to avoid long pauses on this API call.

func (*AllocFS) Stat

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

Stat is used to stat a file at a given path of an allocation directory. Note: for cluster topologies where API consumers don't have network access to Nomad clients, set api.ClientConnTimeout to a small value (ex 1ms) to avoid long pauses on this API call.

func (*AllocFS) Stream

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

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

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

Note: for cluster topologies where API consumers don't have network access to Nomad clients, set api.ClientConnTimeout to a small value (ex 1ms) to avoid long pauses on this API call.

type AllocFileInfo

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

AllocFileInfo holds information about a file inside the AllocDir

type AllocIndexSort

type AllocIndexSort []*AllocationListStub

AllocIndexSort reverse sorts allocs by CreateIndex.

func (AllocIndexSort) Len

func (a AllocIndexSort) Len() int

func (AllocIndexSort) Less

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

func (AllocIndexSort) Swap

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

type AllocNetworkStatus

type AllocNetworkStatus struct {
	InterfaceName string
	Address       string
	DNS           *DNSConfig
}

AllocNetworkStatus captures the status of an allocation's network during runtime. Depending on the network mode, an allocation's address may need to be known to other systems in Nomad such as service registration.

type AllocResourceUsage

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

AllocResourceUsage holds the aggregated task resource usage of the allocation.

type AllocSignalRequest

type AllocSignalRequest struct {
	Task   string
	Signal string
}

type AllocStopResponse

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

	WriteMeta
}

AllocStopResponse is the response to an `AllocStopRequest`

type AllocatedCpuResources

type AllocatedCpuResources struct {
	CpuShares int64
}

type AllocatedDeviceResource

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

type AllocatedMemoryResources

type AllocatedMemoryResources struct {
	MemoryMB    int64
	MemoryMaxMB int64
}

type AllocatedResources

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

type AllocatedSharedResources

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

type AllocatedTaskResources

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

type Allocation

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

Allocation is used for serialization of allocations.

func (*Allocation) ClientTerminalStatus

func (a *Allocation) ClientTerminalStatus() bool

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

func (Allocation) GetTaskGroup

func (a Allocation) GetTaskGroup() *TaskGroup

func (Allocation) RescheduleInfo

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

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

func (*Allocation) ServerTerminalStatus

func (a *Allocation) ServerTerminalStatus() bool

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

func (*Allocation) Stub

func (a *Allocation) Stub() *AllocationListStub

Stub returns a list stub for the allocation

type AllocationListStub

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

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

type AllocationMetric

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

AllocationMetric is used to deserialize allocation metrics.

type AllocationRestartRequest

type AllocationRestartRequest struct {
	TaskName string
	AllTasks bool
}

type AllocationSort

type AllocationSort []*Allocation

AllocationSort reverse sorts allocs by CreateIndex.

func (AllocationSort) Len

func (a AllocationSort) Len() int

func (AllocationSort) Less

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

func (AllocationSort) Swap

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

type Allocations

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

Allocations is used to query the alloc-related endpoints.

func (*Allocations) Checks

func (a *Allocations) Checks(allocID string, q *QueryOptions) (AllocCheckStatuses, error)

Checks gets status information for nomad service checks that exist in the allocation.

Note: for cluster topologies where API consumers don't have network access to Nomad clients, set api.ClientConnTimeout to a small value (ex 1ms) to avoid long pauses on this API call.

func (*Allocations) Exec

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

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

The parameters are:

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

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

Note: for cluster topologies where API consumers don't have network access to Nomad clients, set api.ClientConnTimeout to a small value (ex 1ms) to avoid long pauses on this API call.

func (*Allocations) GC

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

GC forces a garbage collection of client state for an allocation.

Note: for cluster topologies where API consumers don't have network access to Nomad clients, set api.ClientConnTimeout to a small value (ex 1ms) to avoid long pauses on this API call.

func (*Allocations) Info

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

Info is used to retrieve a single allocation.

func (*Allocations) List

List returns a list of all of the allocations.

func (*Allocations) PrefixList

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

func (*Allocations) Restart

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

Restart restarts the tasks that are currently running or a specific task if taskName is provided. An error is returned if the task to be restarted is not running.

Note: for cluster topologies where API consumers don't have network access to Nomad clients, set api.ClientConnTimeout to a small value (ex 1ms) to avoid long pauses on this API call.

func (*Allocations) RestartAllTasks

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

RestartAllTasks restarts all tasks in the allocation, regardless of lifecycle type or state. Tasks will restart following their lifecycle order.

Note: for cluster topologies where API consumers don't have network access to Nomad clients, set api.ClientConnTimeout to a small value (ex 1ms) to avoid long pauses on this API call.

DEPRECATED: This method will be removed in 1.6.0

func (*Allocations) Services

func (a *Allocations) Services(allocID string, q *QueryOptions) ([]*ServiceRegistration, *QueryMeta, error)

Services is used to return a list of service registrations associated to the specified allocID.

func (*Allocations) Signal

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

Signal sends a signal to the allocation.

Note: for cluster topologies where API consumers don't have network access to Nomad clients, set api.ClientConnTimeout to a small value (ex 1ms) to avoid long pauses on this API call.

func (*Allocations) Stats

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

Stats gets allocation resource usage statistics about an allocation.

Note: for cluster topologies where API consumers don't have network access to Nomad clients, set api.ClientConnTimeout to a small value (ex 1ms) to avoid long pauses on this API call.

func (*Allocations) Stop

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

Stop stops an allocation.

Note: for cluster topologies where API consumers don't have network access to Nomad clients, set api.ClientConnTimeout to a small value (ex 1ms) to avoid long pauses on this API call.

BREAKING: This method will have the following signature in 1.6.0 func (a *Allocations) Stop(allocID string, w *WriteOptions) (*AllocStopResponse, error) {

type ApplyLicenseOptions

type ApplyLicenseOptions struct {
	Force bool
}

type Attribute

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

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

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

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

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

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

func (Attribute) String

func (a Attribute) String() string

type AutopilotConfiguration

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

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

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

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

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

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

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

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

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

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

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

func (*AutopilotConfiguration) MarshalJSON

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

func (*AutopilotConfiguration) UnmarshalJSON

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

type AutopilotUpgrade

type AutopilotUpgrade struct {
	// Status of the upgrade.
	Status string

	// TargetVersion is the version that the cluster is upgrading to.
	TargetVersion string

	// TargetVersionVoters holds the list of servers that are voters in the Raft
	// configuration of the TargetVersion.
	TargetVersionVoters []string

	// TargetVersionNonVoters holds the list of servers that are non-voters in
	// the Raft configuration of the TargetVersion.
	TargetVersionNonVoters []string

	// TargetVersionReadReplicas holds the list of servers that are read
	// replicas in the Raft configuration of the TargetVersion.
	TargetVersionReadReplicas []string

	// OtherVersionVoters holds the list of servers that are voters in the Raft
	// configuration of a version other than the TargetVersion.
	OtherVersionVoters []string

	// OtherVersionNonVoters holds the list of servers that are non-voters in
	// the Raft configuration of a version other than the TargetVersion.
	OtherVersionNonVoters []string

	// OtherVersionReadReplicas holds the list of servers that are read replicas
	// in the Raft configuration of a version other than the TargetVersion.
	OtherVersionReadReplicas []string

	// RedundancyZones holds the list of servers in each redundancy zone for the
	// TargetVersion.
	RedundancyZones map[string]AutopilotZoneUpgradeVersions
}

AutopilotUpgrade holds the current upgrade status. (Enterprise only)

type AutopilotZone

type AutopilotZone struct {
	// Servers holds the list of servers in the redundancy zone.
	Servers []string

	// Voters holds the list of servers that are voters in the redundancy zone.
	Voters []string

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

AutopilotZone holds the list of servers in a redundancy zone. (Enterprise only)

type AutopilotZoneUpgradeVersions

type AutopilotZoneUpgradeVersions struct {
	TargetVersionVoters    []string
	TargetVersionNonVoters []string
	OtherVersionVoters     []string
	OtherVersionNonVoters  []string
}

AutopilotZoneUpgradeVersions holds the list of servers in a redundancy zone for a specific version. (Enterprise only)

type BootstrapRequest

type BootstrapRequest struct {
	BootstrapSecret string
}

BootstrapRequest is used for when operators provide an ACL Bootstrap Token

type CSIControllerInfo

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

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

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

	// SupportsGetCapacity indicates plugin support for GET_CAPACITY
	SupportsGetCapacity bool

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

	// SupportsListSnapshots indicates plugin support for LIST_SNAPSHOTS
	SupportsListSnapshots bool

	// SupportsClone indicates plugin support for CLONE_VOLUME
	SupportsClone bool

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

	// SupportsExpand indicates plugin support for EXPAND_VOLUME
	SupportsExpand bool

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

	// SupportsCondition indicates plugin support for VOLUME_CONDITION
	SupportsCondition bool

	// SupportsGet indicates plugin support for GET_VOLUME
	SupportsGet bool
}

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

type CSIInfo

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

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

type CSIMountOptions

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

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

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

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

func (*CSIMountOptions) Merge

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

type CSINodeInfo

type CSINodeInfo struct {
	ID                 string
	MaxVolumes         int64
	AccessibleTopology *CSITopology

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

	// SupportsStats indicates plugin support for GET_VOLUME_STATS
	SupportsStats bool

	// SupportsExpand indicates plugin support for EXPAND_VOLUME
	SupportsExpand bool

	// SupportsCondition indicates plugin support for VOLUME_CONDITION
	SupportsCondition bool
}

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

type CSIPlugin

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

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

type CSIPluginIndexSort

type CSIPluginIndexSort []*CSIPluginListStub

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

func (CSIPluginIndexSort) Len

func (v CSIPluginIndexSort) Len() int

func (CSIPluginIndexSort) Less

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

func (CSIPluginIndexSort) Swap

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

type CSIPluginListStub

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

type CSIPluginType

type CSIPluginType string

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

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

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

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

type CSIPlugins

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

CSI Plugins are jobs with plugin specific data

func (*CSIPlugins) Info

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

Info is used to retrieve a single CSI Plugin Job

func (*CSIPlugins) List

List returns all CSI plugins

type CSISecrets

type CSISecrets map[string]string

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

type CSISnapshot

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

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

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

type CSISnapshotCreateRequest

type CSISnapshotCreateRequest struct {
	Snapshots []*CSISnapshot
	WriteRequest
}

type CSISnapshotCreateResponse

type CSISnapshotCreateResponse struct {
	Snapshots []*CSISnapshot
	QueryMeta
}

type CSISnapshotListRequest

type CSISnapshotListRequest struct {
	PluginID string
	Secrets  CSISecrets
	QueryOptions
}

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

type CSISnapshotListResponse

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

type CSISnapshotSort

type CSISnapshotSort []*CSISnapshot

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

func (CSISnapshotSort) Len

func (v CSISnapshotSort) Len() int

func (CSISnapshotSort) Less

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

func (CSISnapshotSort) Swap

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

type CSITopology

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

type CSITopologyRequest

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

type CSIVolume

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

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

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

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

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

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

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

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

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

	CreateIndex uint64
	ModifyIndex uint64

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

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

type CSIVolumeAccessMode

type CSIVolumeAccessMode string

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

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

type CSIVolumeAttachmentMode

type CSIVolumeAttachmentMode string

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

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

type CSIVolumeCapability

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

CSIVolumeCapability is a requested attachment and access mode for a volume

type CSIVolumeCreateRequest

type CSIVolumeCreateRequest struct {
	Volumes []*CSIVolume
	WriteRequest
}

type CSIVolumeCreateResponse

type CSIVolumeCreateResponse struct {
	Volumes []*CSIVolume
	QueryMeta
}

type CSIVolumeDeleteRequest

type CSIVolumeDeleteRequest struct {
	ExternalVolumeID string
	Secrets          CSISecrets
	WriteRequest
}

type CSIVolumeDeregisterRequest

type CSIVolumeDeregisterRequest struct {
	VolumeIDs []string
	WriteRequest
}

type CSIVolumeExternalStub

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

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

type CSIVolumeExternalStubSort

type CSIVolumeExternalStubSort []*CSIVolumeExternalStub

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

func (CSIVolumeExternalStubSort) Len

func (CSIVolumeExternalStubSort) Less

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

func (CSIVolumeExternalStubSort) Swap

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

type CSIVolumeIndexSort

type CSIVolumeIndexSort []*CSIVolumeListStub

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

func (CSIVolumeIndexSort) Len

func (v CSIVolumeIndexSort) Len() int

func (CSIVolumeIndexSort) Less

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

func (CSIVolumeIndexSort) Swap

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

type CSIVolumeListExternalResponse

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

type CSIVolumeListStub

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

	CreateIndex uint64
	ModifyIndex uint64
}

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

type CSIVolumeRegisterRequest

type CSIVolumeRegisterRequest struct {
	Volumes []*CSIVolume
	WriteRequest
}

type CSIVolumes

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

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

func (*CSIVolumes) Create

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

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

func (*CSIVolumes) CreateSnapshot

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

CreateSnapshot snapshots an external storage volume.

func (*CSIVolumes) Delete

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

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

func (*CSIVolumes) DeleteOpts

func (v *CSIVolumes) DeleteOpts(req *CSIVolumeDeleteRequest, w *WriteOptions) error

DeleteOpts deletes a CSI volume from an external storage provider. The ID passed in the request is for the storage provider's ID, so a volume that's already been deregistered can be deleted.

func (*CSIVolumes) DeleteSnapshot

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

DeleteSnapshot deletes an external storage volume snapshot.

func (*CSIVolumes) Deregister

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

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

func (*CSIVolumes) Detach

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

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

func (*CSIVolumes) Info

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

Info is used to retrieve a single CSIVolume

func (*CSIVolumes) List

List returns all CSI volumes.

func (*CSIVolumes) ListExternal

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

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

func (*CSIVolumes) ListSnapshots

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

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

func (*CSIVolumes) ListSnapshotsOpts

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

ListSnapshotsOpts lists external storage volume snapshots.

func (*CSIVolumes) PluginList

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

PluginList returns all CSI volumes for the specified plugin id

func (*CSIVolumes) Register

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

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

type ChangeScript

type ChangeScript struct {
	Command     *string        `mapstructure:"command" hcl:"command"`
	Args        []string       `mapstructure:"args" hcl:"args,optional"`
	Timeout     *time.Duration `mapstructure:"timeout" hcl:"timeout,optional"`
	FailOnError *bool          `mapstructure:"fail_on_error" hcl:"fail_on_error"`
}

func (*ChangeScript) Canonicalize

func (ch *ChangeScript) Canonicalize()

type CheckRestart

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

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

func (*CheckRestart) Canonicalize

func (c *CheckRestart) Canonicalize()

Canonicalize CheckRestart fields if not nil.

func (*CheckRestart) Copy

func (c *CheckRestart) Copy() *CheckRestart

Copy returns a copy of CheckRestart or nil if unset.

func (*CheckRestart) Merge

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

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

type Client

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

Client provides a client to the Nomad API

func NewClient

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

NewClient returns a new client

func (*Client) ACLAuth

func (c *Client) ACLAuth() *ACLAuth

ACLAuth returns a new handle on the ACL auth-methods API client.

func (*Client) ACLAuthMethods

func (c *Client) ACLAuthMethods() *ACLAuthMethods

ACLAuthMethods returns a new handle on the ACL auth-methods API client.

func (*Client) ACLBindingRules

func (c *Client) ACLBindingRules() *ACLBindingRules

ACLBindingRules returns a new handle on the ACL auth-methods API client.

func (*Client) ACLOIDC deprecated

func (c *Client) ACLOIDC() *ACLOIDC

ACLOIDC returns a new handle on the ACL auth-methods API client.

Deprecated: c.ACLOIDC() is deprecated, use c.ACLAuth() instead.

func (*Client) ACLPolicies

func (c *Client) ACLPolicies() *ACLPolicies

ACLPolicies returns a new handle on the ACL policies.

func (*Client) ACLRoles

func (c *Client) ACLRoles() *ACLRoles

ACLRoles returns a new handle on the ACL roles API client.

func (*Client) ACLTokens

func (c *Client) ACLTokens() *ACLTokens

ACLTokens returns a new handle on the ACL tokens.

func (*Client) Address

func (c *Client) Address() string

Address return the address of the Nomad agent

func (*Client) Agent

func (c *Client) Agent() *Agent

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

func (*Client) AllocFS

func (c *Client) AllocFS() *AllocFS

AllocFS returns an handle to the AllocFS endpoints

func (*Client) Allocations

func (c *Client) Allocations() *Allocations

Allocations returns a handle on the allocs endpoints.

func (*Client) CSIPlugins

func (c *Client) CSIPlugins() *CSIPlugins

CSIPlugins returns a handle on the CSIPlugins endpoint

func (*Client) CSIVolumes

func (c *Client) CSIVolumes() *CSIVolumes

CSIVolumes returns a handle on the CSIVolumes endpoint.

func (*Client) Close

func (c *Client) Close()

Close closes the client's idle keep-alived connections. The default client configuration uses keep-alive to maintain connections and you should instantiate a single Client and reuse it for all requests from the same host. Connections will be closed automatically once the client is garbage collected. If you are creating multiple clients on the same host (for example, for testing), it may be useful to call Close() to avoid hitting connection limits.

func (*Client) Deployments

func (c *Client) Deployments() *Deployments

Deployments returns a new handle on the deployments.

func (*Client) Evaluations

func (c *Client) Evaluations() *Evaluations

Evaluations returns a new handle on the evaluations.

func (*Client) EventStream

func (c *Client) EventStream() *EventStream

EventStream returns a handle to the Events endpoint

func (*Client) GetNodeClient

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

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

func (*Client) GetNodeClientWithTimeout

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

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

func (*Client) Jobs

func (c *Client) Jobs() *Jobs

Jobs returns a handle on the jobs endpoints.

func (*Client) Keyring

func (c *Client) Keyring() *Keyring

Keyring returns a handle to the Keyring endpoint

func (*Client) Locks

func (c *Client) Locks(wo WriteOptions, v Variable, opts ...LocksOption) (*Locks, error)

Locks returns a new handle on a lock for the given variable.

func (*Client) Namespaces

func (c *Client) Namespaces() *Namespaces

Namespaces returns a new handle on the namespaces.

func (*Client) NewLockLeaser

func (c *Client) NewLockLeaser(l Locker, opts ...LockLeaserOption) *LockLeaser

NewLockLeaser returns an instance of LockLeaser. callerID is optional, in case they it is not provided, internal one will be created.

func (*Client) NodePools

func (c *Client) NodePools() *NodePools

NodePools returns a handle on the node pools endpoints.

func (*Client) Nodes

func (c *Client) Nodes() *Nodes

Nodes returns a handle on the node endpoints.

func (*Client) Operator

func (c *Client) Operator() *Operator

Operator returns a handle to the operator endpoints.

func (*Client) Quotas

func (c *Client) Quotas() *Quotas

Quotas returns a new handle on the quotas.

func (*Client) Raw

func (c *Client) Raw() *Raw

Raw returns a handle to query endpoints

func (*Client) Recommendations

func (c *Client) Recommendations() *Recommendations

Recommendations returns a new handle on the recommendations endpoints.

func (*Client) Regions

func (c *Client) Regions() *Regions

Regions returns a handle on the regions endpoints.

func (*Client) Scaling

func (c *Client) Scaling() *Scaling

Scaling returns a handle on the scaling endpoints.

func (*Client) Search

func (c *Client) Search() *Search

Search returns a handle on the Search endpoints

func (*Client) SentinelPolicies

func (c *Client) SentinelPolicies() *SentinelPolicies

SentinelPolicies returns a new handle on the Sentinel policies.

func (*Client) Services

func (c *Client) Services() *Services

Services returns a new handle on the services endpoints.

func (*Client) SetNamespace

func (c *Client) SetNamespace(namespace string)

SetNamespace sets the namespace to forward API requests to.

func (*Client) SetRegion

func (c *Client) SetRegion(region string)

SetRegion sets the region to forward API requests to.

func (*Client) SetSecretID

func (c *Client) SetSecretID(secretID string)

SetSecretID sets the ACL token secret for API requests.

func (*Client) Status

func (c *Client) Status() *Status

Status returns a handle on the status endpoints.

func (*Client) System

func (c *Client) System() *System

System returns a handle on the system endpoints.

func (*Client) Variables

func (c *Client) Variables() *Variables

Variables returns a new handle on the variables.

type Config

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

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

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

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

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

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

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

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

	Headers http.Header
	// contains filtered or unexported fields
}

Config is used to configure the creation of a client

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a default configuration for the client

func (*Config) ClientConfig

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

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

func (*Config) URL

func (c *Config) URL() *url.URL

URL returns a copy of the initial parsed address and is not modified in the case of a `unix://` URL, as opposed to Address.

type Constraint

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

Constraint is used to serialize a job placement constraint.

func NewConstraint

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

NewConstraint generates a new job placement constraint.

type Consul

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

	// (Enterprise-only) Cluster represents a specific Consul cluster.
	Cluster string `mapstructure:"cluster" hcl:"cluster,optional"`

	// Partition is the Consul admin partition where the workload should
	// run. This is available in Nomad CE but only works with Consul ENT
	Partition string `mapstructure:"partition" hcl:"partition,optional"`
}

Consul represents configuration related to consul.

func (*Consul) Canonicalize

func (c *Consul) Canonicalize()

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

func (*Consul) Copy

func (c *Consul) Copy() *Consul

Copy creates a deep copy of c.

func (*Consul) MergeNamespace

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

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

type ConsulConnect

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

ConsulConnect represents a Consul Connect jobspec block.

func (*ConsulConnect) Canonicalize

func (cc *ConsulConnect) Canonicalize()

type ConsulExposeConfig

type ConsulExposeConfig struct {
	Paths []*ConsulExposePath `mapstructure:"path" hcl:"path,block"`
	Path  []*ConsulExposePath // Deprecated: only to maintain backwards compatibility. Use Paths instead.
}

func (*ConsulExposeConfig) Canonicalize

func (cec *ConsulExposeConfig) Canonicalize()

type ConsulExposePath

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

type ConsulGateway

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

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

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

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

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

func (*ConsulGateway) Canonicalize

func (g *ConsulGateway) Canonicalize()

func (*ConsulGateway) Copy

func (g *ConsulGateway) Copy() *ConsulGateway

type ConsulGatewayBindAddress

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

type ConsulGatewayProxy

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

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

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

func (*ConsulGatewayProxy) Canonicalize

func (p *ConsulGatewayProxy) Canonicalize()

func (*ConsulGatewayProxy) Copy

type ConsulGatewayTLSConfig

type ConsulGatewayTLSConfig struct {

	// Enabled indicates whether TLS is enabled for the configuration entry
	Enabled bool `hcl:"enabled,optional"`

	// TLSMinVersion specifies the minimum TLS version supported for gateway
	// listeners.
	TLSMinVersion string `hcl:"tls_min_version,optional" mapstructure:"tls_min_version"`

	// TLSMaxVersion specifies the maxmimum TLS version supported for gateway
	// listeners.
	TLSMaxVersion string `hcl:"tls_max_version,optional" mapstructure:"tls_max_version"`

	// CipherSuites specifies a list of cipher suites that gateway listeners
	// support when negotiating connections using TLS 1.2 or older.
	CipherSuites []string `hcl:"cipher_suites,optional" mapstructure:"cipher_suites"`

	// SDS specifies parameters that configure the listener to load TLS
	// certificates from an external Secrets Discovery Service (SDS).
	SDS *ConsulGatewayTLSSDSConfig `hcl:"sds,block" mapstructure:"sds"`
}

ConsulGatewayTLSConfig is used to configure TLS for a gateway. Both ConsulIngressConfigEntry and ConsulIngressService use this struct. For more details, consult the Consul documentation: https://developer.hashicorp.com/consul/docs/connect/config-entries/ingress-gateway#listeners-services-tls

func (*ConsulGatewayTLSConfig) Canonicalize

func (tc *ConsulGatewayTLSConfig) Canonicalize()

func (*ConsulGatewayTLSConfig) Copy

type ConsulGatewayTLSSDSConfig

type ConsulGatewayTLSSDSConfig struct {
	// ClusterName specifies the name of the SDS cluster where Consul should
	// retrieve certificates.
	ClusterName string `hcl:"cluster_name,optional" mapstructure:"cluster_name"`

	// CertResource specifies an SDS resource name
	CertResource string `hcl:"cert_resource,optional" mapstructure:"cert_resource"`
}

ConsulGatewayTLSSDSConfig is used to configure the gateway's TLS listener to load certificates from an external Secret Discovery Service (SDS)

func (*ConsulGatewayTLSSDSConfig) Copy

type ConsulHTTPHeaderModifiers

type ConsulHTTPHeaderModifiers struct {
	// Add is a set of name -> value pairs that should be appended to the
	// request or response (i.e. allowing duplicates if the same header already
	// exists).
	Add map[string]string `hcl:"add,block" mapstructure:"add"`

	// Set is a set of name -> value pairs that should be added to the request
	// or response, overwriting any existing header values of the same name.
	Set map[string]string `hcl:"set,block" mapstructure:"set"`

	// Remove is the set of header names that should be stripped from the
	// request or response.
	Remove []string `hcl:"remove,optional" mapstructure:"remove"`
}

ConsulHTTPHeaderModifiers is a set of rules for HTTP header modification that should be performed by proxies as the request passes through them. It can operate on either request or response headers depending on the context in which it is used.

func (*ConsulHTTPHeaderModifiers) Canonicalize

func (h *ConsulHTTPHeaderModifiers) Canonicalize()

func (*ConsulHTTPHeaderModifiers) Copy

type ConsulIngressConfigEntry

type ConsulIngressConfigEntry struct {

	// TLS specifies a TLS configuration for the gateway.
	TLS *ConsulGatewayTLSConfig `hcl:"tls,block"`

	// Listeners specifies a list of listeners in the mesh for the
	// gateway. Listeners are uniquely identified by their port number.
	Listeners []*ConsulIngressListener `hcl:"listener,block"`
}

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

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

func (*ConsulIngressConfigEntry) Canonicalize

func (e *ConsulIngressConfigEntry) Canonicalize()

func (*ConsulIngressConfigEntry) Copy

type ConsulIngressListener

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

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

func (*ConsulIngressListener) Canonicalize

func (l *ConsulIngressListener) Canonicalize()

func (*ConsulIngressListener) Copy

type ConsulIngressService

type ConsulIngressService struct {

	// Name of the service exposed through this listener.
	Name string `hcl:"name,optional"`

	// Hosts specifies one or more hosts that the listening services can receive
	// requests on.
	Hosts []string `hcl:"hosts,optional"`

	// TLS specifies a TLS configuration override for a specific service. If
	// unset this will fallback to the ConsulIngressConfigEntry's own TLS field.
	TLS *ConsulGatewayTLSConfig `hcl:"tls,block" mapstructure:"tls"`

	// RequestHeaders specifies a set of HTTP-specific header modification rules
	// applied to requests routed through the gateway
	RequestHeaders *ConsulHTTPHeaderModifiers `hcl:"request_headers,block" mapstructure:"request_headers"`

	// ResponseHeader specifies a set of HTTP-specific header modification rules
	// applied to responses routed through the gateway
	ResponseHeaders *ConsulHTTPHeaderModifiers `hcl:"response_headers,block" mapstructure:"response_headers"`

	// MaxConnections specifies the maximum number of HTTP/1.1 connections a
	// service instance is allowed to establish against the upstream
	MaxConnections *uint32 `hcl:"max_connections,optional" mapstructure:"max_connections"`

	// MaxPendingRequests specifies the maximum number of requests that are
	// allowed to queue while waiting to establish a connection
	MaxPendingRequests *uint32 `hcl:"max_pending_requests,optional" mapstructure:"max_pending_requests"`

	// MaxConcurrentRequests specifies the maximum number of concurrent HTTP/2
	// traffic requests that are allowed at a single point in time
	MaxConcurrentRequests *uint32 `hcl:"max_concurrent_requests,optional" mapstructure:"max_concurrent_requests"`
}

ConsulIngressService is used to configure a service fronted by the ingress gateway. For more details, consult the Consul documentation: https://developer.hashicorp.com/consul/docs/connect/config-entries/ingress-gateway

func (*ConsulIngressService) Canonicalize

func (s *ConsulIngressService) Canonicalize()

func (*ConsulIngressService) Copy

type ConsulLinkedService

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

func (*ConsulLinkedService) Canonicalize

func (s *ConsulLinkedService) Canonicalize()

func (*ConsulLinkedService) Copy

type ConsulMeshConfigEntry

type ConsulMeshConfigEntry struct {
}

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

func (*ConsulMeshConfigEntry) Canonicalize

func (e *ConsulMeshConfigEntry) Canonicalize()

func (*ConsulMeshConfigEntry) Copy

type ConsulMeshGateway

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

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

func (*ConsulMeshGateway) Canonicalize

func (c *ConsulMeshGateway) Canonicalize()

func (*ConsulMeshGateway) Copy

type ConsulProxy

type ConsulProxy struct {
	LocalServiceAddress string              `mapstructure:"local_service_address" hcl:"local_service_address,optional"`
	LocalServicePort    int                 `mapstructure:"local_service_port" hcl:"local_service_port,optional"`
	Expose              *ConsulExposeConfig `mapstructure:"expose" hcl:"expose,block"`
	ExposeConfig        *ConsulExposeConfig // Deprecated: only to maintain backwards compatibility. Use Expose instead.
	Upstreams           []*ConsulUpstream   `hcl:"upstreams,block"`

	// TransparentProxy configures the Envoy sidecar to use "transparent
	// proxying", which creates IP tables rules inside the network namespace to
	// ensure traffic flows thru the Envoy proxy
	TransparentProxy *ConsulTransparentProxy `mapstructure:"transparent_proxy" hcl:"transparent_proxy,block"`
	Config           map[string]interface{}  `hcl:"config,block"`
}

ConsulProxy represents a Consul Connect sidecar proxy jobspec block.

func (*ConsulProxy) Canonicalize

func (cp *ConsulProxy) Canonicalize()

type ConsulSidecarService

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

ConsulSidecarService represents a Consul Connect SidecarService jobspec block.

func (*ConsulSidecarService) Canonicalize

func (css *ConsulSidecarService) Canonicalize()

type ConsulTerminatingConfigEntry

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

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

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

func (*ConsulTerminatingConfigEntry) Canonicalize

func (e *ConsulTerminatingConfigEntry) Canonicalize()

func (*ConsulTerminatingConfigEntry) Copy

type ConsulTransparentProxy

type ConsulTransparentProxy struct {
	// UID of the Envoy proxy. Defaults to the default Envoy proxy container
	// image user.
	UID string `mapstructure:"uid" hcl:"uid,optional"`

	// OutboundPort is the Envoy proxy's outbound listener port. Inbound TCP
	// traffic hitting the PROXY_IN_REDIRECT chain will be redirected here.
	// Defaults to 15001.
	OutboundPort uint16 `mapstructure:"outbound_port" hcl:"outbound_port,optional"`

	// ExcludeInboundPorts is an additional set of ports will be excluded from
	// redirection to the Envoy proxy. Can be Port.Label or Port.Value. This set
	// will be added to the ports automatically excluded for the Expose.Port and
	// Check.Expose fields.
	ExcludeInboundPorts []string `mapstructure:"exclude_inbound_ports" hcl:"exclude_inbound_ports,optional"`

	// ExcludeOutboundPorts is a set of outbound ports that will not be
	// redirected to the Envoy proxy, specified as port numbers.
	ExcludeOutboundPorts []uint16 `mapstructure:"exclude_outbound_ports" hcl:"exclude_outbound_ports,optional"`

	// ExcludeOutboundCIDRs is a set of outbound CIDR blocks that will not be
	// redirected to the Envoy proxy.
	ExcludeOutboundCIDRs []string `mapstructure:"exclude_outbound_cidrs" hcl:"exclude_outbound_cidrs,optional"`

	// ExcludeUIDs is a set of user IDs whose network traffic will not be
	// redirected through the Envoy proxy.
	ExcludeUIDs []string `mapstructure:"exclude_uids" hcl:"exclude_uids,optional"`

	// NoDNS disables redirection of DNS traffic to Consul DNS. By default NoDNS
	// is false and transparent proxy will direct DNS traffic to Consul DNS if
	// available on the client.
	NoDNS bool `mapstructure:"no_dns" hcl:"no_dns,optional"`
}

ConsulTransparentProxy is used to configure the Envoy sidecar for "transparent proxying", which creates IP tables rules inside the network namespace to ensure traffic flows thru the Envoy proxy

func (*ConsulTransparentProxy) Canonicalize

func (tp *ConsulTransparentProxy) Canonicalize()

type ConsulUpstream

type ConsulUpstream struct {
	DestinationName      string             `mapstructure:"destination_name" hcl:"destination_name,optional"`
	DestinationNamespace string             `mapstructure:"destination_namespace" hcl:"destination_namespace,optional"`
	DestinationPeer      string             `mapstructure:"destination_peer" hcl:"destination_peer,optional"`
	DestinationPartition string             `mapstructure:"destination_partition" hcl:"destination_partition,optional"`
	DestinationType      string             `mapstructure:"destination_type" hcl:"destination_type,optional"`
	LocalBindPort        int                `mapstructure:"local_bind_port" hcl:"local_bind_port,optional"`
	Datacenter           string             `mapstructure:"datacenter" hcl:"datacenter,optional"`
	LocalBindAddress     string             `mapstructure:"local_bind_address" hcl:"local_bind_address,optional"`
	LocalBindSocketPath  string             `mapstructure:"local_bind_socket_path" hcl:"local_bind_socket_path,optional"`
	LocalBindSocketMode  string             `mapstructure:"local_bind_socket_mode" hcl:"local_bind_socket_mode,optional"`
	MeshGateway          *ConsulMeshGateway `mapstructure:"mesh_gateway" hcl:"mesh_gateway,block"`
	Config               map[string]any     `mapstructure:"config" hcl:"config,block"`
}

ConsulUpstream represents a Consul Connect upstream jobspec block.

func (*ConsulUpstream) Canonicalize

func (cu *ConsulUpstream) Canonicalize()

func (*ConsulUpstream) Copy

func (cu *ConsulUpstream) Copy() *ConsulUpstream

type CpuStats

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

CpuStats holds cpu usage related stats

type DNSConfig

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

type Deployment

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

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

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

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

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

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

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

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

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

	// The status of the deployment
	Status string

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

	CreateIndex uint64
	ModifyIndex uint64
}

Deployment is used to serialize an deployment.

type DeploymentAllocHealthRequest

type DeploymentAllocHealthRequest struct {
	DeploymentID string

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

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

	WriteRequest
}

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

type DeploymentFailRequest

type DeploymentFailRequest struct {
	DeploymentID string
	WriteRequest
}

DeploymentFailRequest is used to fail a particular deployment

type DeploymentIndexSort

type DeploymentIndexSort []*Deployment

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

func (DeploymentIndexSort) Len

func (d DeploymentIndexSort) Len() int

func (DeploymentIndexSort) Less

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

func (DeploymentIndexSort) Swap

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

type DeploymentPauseRequest

type DeploymentPauseRequest struct {
	DeploymentID string

	// Pause sets the pause status
	Pause bool

	WriteRequest
}

DeploymentPauseRequest is used to pause a deployment

type DeploymentPromoteRequest

type DeploymentPromoteRequest struct {
	DeploymentID string

	// All is to promote all task groups
	All bool

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

	WriteRequest
}

DeploymentPromoteRequest is used to promote task groups in a deployment

type DeploymentSpecificRequest

type DeploymentSpecificRequest struct {
	DeploymentID string
	QueryOptions
}

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

type DeploymentState

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

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

type DeploymentUnblockRequest

type DeploymentUnblockRequest struct {
	DeploymentID string
	WriteRequest
}

DeploymentUnblockRequest is used to unblock a particular deployment

type DeploymentUpdateResponse

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

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

type Deployments

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

Deployments is used to query the deployments endpoints.

func (*Deployments) Allocations

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

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

func (*Deployments) Fail

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

Fail is used to fail the given deployment.

func (*Deployments) Info

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

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

func (*Deployments) List

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

List is used to dump all the deployments.

func (*Deployments) Pause

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

Pause is used to pause or unpause the given deployment.

func (*Deployments) PrefixList

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

func (*Deployments) PromoteAll

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

PromoteAll is used to promote all canaries in the given deployment

func (*Deployments) PromoteGroups

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

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

func (*Deployments) SetAllocHealth

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

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

func (*Deployments) Unblock

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

Unblock is used to unblock the given deployment.

type DeregisterOptions

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

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

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

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

DeregisterOptions is used to pass through job deregistration parameters

type DesiredTransition

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

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

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

func (DesiredTransition) ShouldMigrate

func (d DesiredTransition) ShouldMigrate() bool

ShouldMigrate returns whether the transition object dictates a migration.

type DesiredUpdates

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

type DeviceGroupStats

type DeviceGroupStats struct {
	Vendor string
	Type   string
	Name   string

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

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

type DeviceStats

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

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

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

DeviceStats is the statistics for an individual device

type DisconnectStrategy

type DisconnectStrategy struct {
	// Defines for how long the server will consider the unresponsive node as
	// disconnected but alive instead of lost.
	LostAfter *time.Duration `mapstructure:"lost_after" hcl:"lost_after,optional"`

	// Defines for how long a disconnected client will keep its allocations running.
	StopOnClientAfter *time.Duration `mapstructure:"stop_on_client_after" hcl:"stop_on_client_after,optional"`

	// A boolean field used to define if the allocations should be replaced while
	// it's considered disconnected.
	Replace *bool `mapstructure:"replace" hcl:"replace,optional"`

	// Once the disconnected node starts reporting again, it will define which
	// instances to keep: the original allocations, the replacement, the one
	// running on the node with the best score as it is currently implemented,
	// or the allocation that has been running continuously the longest.
	Reconcile *ReconcileOption `mapstructure:"reconcile" hcl:"reconcile,optional"`
}

Disconnect strategy defines how both clients and server should behave in case of disconnection between them.

func NewDefaultDisconnectStrategy

func NewDefaultDisconnectStrategy() *DisconnectStrategy

func (*DisconnectStrategy) Canonicalize

func (ds *DisconnectStrategy) Canonicalize()

type DiskUsage

type DiskUsage struct {
	DiskMB int64
	UsedMB int64
}

type DispatchPayloadConfig

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

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

type DrainMetadata

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

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

type DrainOptions

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

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

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

DrainOptions is used to pass through node drain parameters

type DrainSpec

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

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

DrainSpec describes a Node's drain behavior.

type DrainStatus

type DrainStatus string

type DrainStrategy

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

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

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

DrainStrategy describes a Node's drain behavior.

func (*DrainStrategy) Equal

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

func (*DrainStrategy) String

func (d *DrainStrategy) String() string

String returns a human readable version of the drain strategy.

type DriverInfo

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

DriverInfo is used to deserialize a DriverInfo entry

type EncryptionAlgorithm

type EncryptionAlgorithm string

EncryptionAlgorithm chooses which algorithm is used for encrypting / decrypting entries with this key

const (
	EncryptionAlgorithmAES256GCM EncryptionAlgorithm = "aes256-gcm"
)

type EphemeralDisk

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

EphemeralDisk is an ephemeral disk object

func DefaultEphemeralDisk

func DefaultEphemeralDisk() *EphemeralDisk

func (*EphemeralDisk) Canonicalize

func (e *EphemeralDisk) Canonicalize()

type ErrCASConflict

type ErrCASConflict struct {
	CheckIndex uint64
	Conflict   *Variable
}

func (ErrCASConflict) Error

func (e ErrCASConflict) Error() string

type EvalCountResponse

type EvalCountResponse struct {
	Count int
	QueryMeta
}

type EvalDeleteRequest

type EvalDeleteRequest struct {
	EvalIDs []string
	Filter  string
	WriteRequest
}

type EvalDeleteResponse

type EvalDeleteResponse struct {
	Count int
}

type EvalIndexSort

type EvalIndexSort []*Evaluation

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

func (EvalIndexSort) Len

func (e EvalIndexSort) Len() int

func (EvalIndexSort) Less

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

func (EvalIndexSort) Swap

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

type EvalOptions

type EvalOptions struct {
	ForceReschedule bool
}

EvalOptions is used to encapsulate options when forcing a job evaluation

type Evaluation

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

Evaluation is used to serialize an evaluation.

type EvaluationStub

type EvaluationStub struct {
	ID                string
	Priority          int
	Type              string
	TriggeredBy       string
	Namespace         string
	JobID             string
	NodeID            string
	DeploymentID      string
	Status            string
	StatusDescription string
	WaitUntil         time.Time
	NextEval          string
	PreviousEval      string
	BlockedEval       string
	CreateIndex       uint64
	ModifyIndex       uint64
	CreateTime        int64
	ModifyTime        int64
}

EvaluationStub is used to serialize parts of an evaluation returned in the RelatedEvals field of an Evaluation.

type Evaluations

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

Evaluations is used to query the evaluation endpoints.

func (*Evaluations) Allocations

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

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

func (*Evaluations) Count

Count is used to get a count of evaluations.

func (*Evaluations) Delete

func (e *Evaluations) Delete(evalIDs []string, w *WriteOptions) (*WriteMeta, error)

Delete is used to batch delete evaluations using their IDs.

func (*Evaluations) DeleteOpts

DeleteOpts is used to batch delete evaluations using a filter.

func (*Evaluations) Info

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

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

func (*Evaluations) List

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

List is used to dump all of the evaluations.

func (*Evaluations) PrefixList

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

type Event

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

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

func (*Event) Allocation

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

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

func (*Event) Deployment

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

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

func (*Event) Evaluation

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

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

func (*Event) Job

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

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

func (*Event) Node

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

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

func (*Event) NodePool

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

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

func (*Event) Service

func (e *Event) Service() (*ServiceRegistration, error)

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

type EventStream

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

EventStream is used to stream events from Nomad

func (*EventStream) Stream

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

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

type Events

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

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

func (*Events) IsHeartbeat

func (e *Events) IsHeartbeat() bool

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

type ExecStreamingExitResult

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

ExecStreamingExitResult captures the exit code of just completed nomad exec command

type ExecStreamingIOOperation

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

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

type ExecStreamingInput

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

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

At most one field should be set.

type ExecStreamingOutput

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

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

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

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

type FieldDiff

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

type ForceLeaveOpts

type ForceLeaveOpts struct {
	// Prune indicates whether to remove a node from the list of members
	Prune bool
}

ForceLeaveOpts are used to configure the ForceLeave method.

type FrameReader

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

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

func NewFrameReader

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

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

func (*FrameReader) Close

func (f *FrameReader) Close() error

Close cancels the stream of frames

func (*FrameReader) Offset

func (f *FrameReader) Offset() int

Offset returns the offset into the stream.

func (*FrameReader) Read

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

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

func (*FrameReader) SetUnblockTime

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

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

type FuzzyMatch

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

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

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

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

type FuzzySearchRequest

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

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

	QueryOptions
}

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

type FuzzySearchResponse

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

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

	QueryMeta
}

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

type GaugeValue

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

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

type GenericResponse

type GenericResponse struct {
	WriteMeta
}

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

type HostCPUStats

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

type HostData

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

type HostDataResponse

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

type HostDiskStats

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

type HostMemoryStats

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

type HostNetworkInfo

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

HostNetworkInfo is used to return metadata about a given HostNetwork

type HostStats

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

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

type HostVolumeInfo

type HostVolumeInfo struct {
	Path     string
	ReadOnly bool
}

HostVolumeInfo is used to return metadata about a given HostVolume.

type HttpBasicAuth

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

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

HttpBasicAuth is used to authenticate http client with HTTP Basic Authentication

type Job

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

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

Job is used to serialize a job.

func NewBatchJob

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

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

func NewServiceJob

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

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

func NewSysbatchJob

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

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

func NewSystemJob

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

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

func (*Job) AddAffinity

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

AddAffinity is used to add an affinity to a job.

func (*Job) AddDatacenter

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

AddDatacenter is used to add a datacenter to a job.

func (*Job) AddPeriodicConfig

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

AddPeriodicConfig adds a periodic config to an existing job.

func (*Job) AddSpread

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

func (*Job) AddTaskGroup

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

AddTaskGroup adds a task group to an existing job.

func (*Job) Canonicalize

func (j *Job) Canonicalize()

func (*Job) Constrain

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

Constrain is used to add a constraint to a job.

func (*Job) IsMultiregion

func (j *Job) IsMultiregion() bool

IsMultiregion returns whether a job is a multiregion job

func (*Job) IsParameterized

func (j *Job) IsParameterized() bool

IsParameterized returns whether a job is parameterized job.

func (*Job) IsPeriodic

func (j *Job) IsPeriodic() bool

IsPeriodic returns whether a job is periodic.

func (*Job) LookupTaskGroup

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

LookupTaskGroup finds a task group by name

func (*Job) SetMeta

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

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

type JobACL

type JobACL struct {
	Namespace string
	JobID     string
	Group     string
	Task      string
}

JobACL represents an ACL policy's attachment to a job, group, or task.

type JobChildrenSummary

type JobChildrenSummary struct {
	Pending int64
	Running int64
	Dead    int64
}

JobChildrenSummary contains the summary of children job status

func (*JobChildrenSummary) Sum

func (jc *JobChildrenSummary) Sum() int

type JobDeregisterResponse

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

JobDeregisterResponse is used to respond to a job deregistration

type JobDiff

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

type JobDispatchRequest

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

type JobDispatchResponse

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

type JobEvaluateRequest

type JobEvaluateRequest struct {
	JobID       string
	EvalOptions EvalOptions
	WriteRequest
}

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

type JobIDSort

type JobIDSort []*JobListStub

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

func (JobIDSort) Len

func (j JobIDSort) Len() int

func (JobIDSort) Less

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

func (JobIDSort) Swap

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

type JobListFields

type JobListFields struct {
	Meta bool
}

type JobListOptions

type JobListOptions struct {
	Fields *JobListFields
}

type JobListStub

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

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

type JobPlanRequest

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

type JobPlanResponse

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

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

type JobRegisterRequest

type JobRegisterRequest struct {
	Submission *JobSubmission
	Job        *Job

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

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

	WriteRequest
}

JobRegisterRequest is used to update a job

type JobRegisterResponse

type JobRegisterResponse struct {
	EvalID          string
	EvalCreateIndex uint64
	JobModifyIndex  uint64

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

	QueryMeta
}

JobRegisterResponse is used to respond to a job registration

type JobRevertRequest

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

	// JobVersion the version to revert to.
	JobVersion uint64

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

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

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

	WriteRequest
}

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

type JobScaleStatusResponse

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

JobScaleStatusResponse is used to return information about job scaling status

type JobStabilityRequest

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

	// Set the stability
	Stable bool
	WriteRequest
}

JobStabilityRequest is used to marked a job as stable.

type JobStabilityResponse

type JobStabilityResponse struct {
	JobModifyIndex uint64
	WriteMeta
}

JobStabilityResponse is the response when marking a job as stable.

type JobSubmission

type JobSubmission struct {
	// Source contains the original job definition (may be in the format of
	// hcl1, hcl2, or json).
	Source string

	// Format indicates what the Source content was (hcl1, hcl2, or json).
	Format string

	// VariableFlags contains the CLI "-var" flag arguments as submitted with the
	// job (hcl2 only).
	VariableFlags map[string]string

	// Variables contains the opaque variables configuration as coming from
	// a var-file or the WebUI variables input (hcl2 only).
	Variables string
}

JobSubmission is used to hold information about the original content of a job specification being submitted to Nomad.

At any time a JobSubmission may be nil, indicating no information is known about the job submission.

func (*JobSubmission) Canonicalize

func (js *JobSubmission) Canonicalize()

func (*JobSubmission) Copy

func (js *JobSubmission) Copy() *JobSubmission

type JobSubmissionResponse

type JobSubmissionResponse struct {
	Submission *JobSubmission
	QueryMeta
}

JobSubmissionResponse is used for a job get submission request

type JobSummary

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

	// Raft Indexes
	CreateIndex uint64
	ModifyIndex uint64
}

JobSummary summarizes the state of the allocations of a job

type JobValidateRequest

type JobValidateRequest struct {
	Job *Job
	WriteRequest
}

JobValidateRequest is used to validate a job

type JobValidateResponse

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

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

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

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

JobValidateResponse is the response from validate request

type JobVersionsResponse

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

JobVersionsResponse is used for a job get versions request

type Jobs

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

Jobs is used to access the job-specific endpoints.

func (*Jobs) ActionExec

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

ActionExec is used to run a pre-defined command inside a running task. The call blocks until command terminates (or an error occurs), and returns the exit code.

func (*Jobs) Allocations

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

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

func (*Jobs) Deployments

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

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

func (*Jobs) Deregister

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

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

func (*Jobs) DeregisterOpts

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

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

func (*Jobs) Dispatch

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

func (*Jobs) EnforceRegister

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

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

func (*Jobs) EvaluateWithOpts

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

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

func (*Jobs) Evaluations

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

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

func (*Jobs) ForceEvaluate

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

ForceEvaluate is used to force-evaluate an existing job.

func (*Jobs) Info

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

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

func (*Jobs) LatestDeployment

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

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

func (*Jobs) List

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

List is used to list all of the existing jobs.

func (*Jobs) ListOptions

func (j *Jobs) ListOptions(opts *JobListOptions, q *QueryOptions) ([]*JobListStub, *QueryMeta, error)

List is used to list all of the existing jobs.

func (*Jobs) ParseHCL

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

ParseHCL is used to convert the HCL representation of a Job to JSON server side. To parse the HCL client side see package github.com/hashicorp/nomad/jobspec Use ParseHCLOpts if you need to customize JobsParseRequest.

func (*Jobs) ParseHCLOpts

func (j *Jobs) ParseHCLOpts(req *JobsParseRequest) (*Job, error)

ParseHCLOpts is used to request the server convert the HCL representation of a Job to JSON on our behalf. Accepts HCL1 or HCL2 jobs as input.

func (*Jobs) PeriodicForce

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

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

func (*Jobs) Plan

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

func (*Jobs) PlanOpts

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

func (*Jobs) PrefixList

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

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

func (*Jobs) Register

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

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

func (*Jobs) RegisterOpts

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

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

func (*Jobs) Revert

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

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

func (*Jobs) Scale

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

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

func (*Jobs) ScaleStatus

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

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

func (*Jobs) Services

func (j *Jobs) Services(jobID string, q *QueryOptions) ([]*ServiceRegistration, *QueryMeta, error)

Services is used to return a list of service registrations associated to the specified jobID.

func (*Jobs) Stable

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

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

func (*Jobs) Submission

func (j *Jobs) Submission(jobID string, version int, q *QueryOptions) (*JobSubmission, *QueryMeta, error)

Submission is used to retrieve the original submitted source of a job given its namespace, jobID, and version number. The original source might not be available, which case nil is returned with no error.

func (*Jobs) Summary

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

func (*Jobs) Validate

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

func (*Jobs) Versions

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

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

type JobsParseRequest

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

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

	// Variables are HCL2 variables associated with the job. Only works with hcl2.
	//
	// Interpreted as if it were the content of a variables file.
	Variables string

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

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

type Keyring

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

Keyring is used to access the Variables keyring.

func (*Keyring) Delete

func (k *Keyring) Delete(opts *KeyringDeleteOptions, w *WriteOptions) (*WriteMeta, error)

Delete deletes a specific inactive key from the keyring

func (*Keyring) List

func (k *Keyring) List(q *QueryOptions) ([]*RootKeyMeta, *QueryMeta, error)

List lists all the keyring metadata

func (*Keyring) Rotate

Rotate requests a key rotation

type KeyringDeleteOptions

type KeyringDeleteOptions struct {
	KeyID string // UUID
}

KeyringDeleteOptions are parameters for the Delete API

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 KeyringRotateOptions

type KeyringRotateOptions struct {
	Full      bool
	Algorithm EncryptionAlgorithm
}

KeyringRotateOptions are parameters for the Rotate API

type Label

type Label struct {
	Name  string
	Value string
}

type LeadershipTransferResponse

type LeadershipTransferResponse struct {
	From RaftServer
	To   RaftServer
	Noop bool
	Err  error

	WriteMeta
}

type License

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

	// The customer ID associated with the license
	CustomerID string

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

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

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

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

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

	// The product the license is valid for
	Product string

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

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

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

type LicenseReply

type LicenseReply struct {
	License        *License
	ConfigOutdated bool
	QueryMeta
}

type LockLeaser

type LockLeaser struct {
	Name string
	// contains filtered or unexported fields
}

LockLeaser is a helper used to run a protected function that should only be active if the instance that runs it is currently holding the lock. Can be used to provide synchrony among multiple independent instances.

It includes the lease renewal mechanism and tracking in case the protected function returns an error. Internally it uses an exponential retry mechanism for the api calls.

func (*LockLeaser) Start

func (ll *LockLeaser) Start(ctx context.Context, protectedFuncs ...func(ctx context.Context) error) error

Start wraps the start function in charge of executing the protected function and maintain the lease but is in charge of releasing the lock before exiting. It is a blocking function.

type LockLeaserOption

type LockLeaserOption = func(l *LockLeaser)

func LockLeaserOptionWithEarlyReturn

func LockLeaserOptionWithEarlyReturn(er bool) LockLeaserOption

LockLeaserOptionWithEarlyReturn informs the leaser to return after the lock acquire fails and to not wait to attempt again.

func LockLeaserOptionWithWaitPeriod

func LockLeaserOptionWithWaitPeriod(wp time.Duration) LockLeaserOption

LockLeaserOptionWithWaitPeriod is used to set a back off period between calls to attempt to acquire the lock. By default it is set to 1.1 * TTLs.

type Locker

type Locker interface {
	// Acquire will make the actual call to acquire the lock over the variable using
	// the ttl in the Locks to create the VariableLock.
	//
	// Acquire returns the path to the variable holding the lock.
	Acquire(ctx context.Context) (string, error)
	// Release makes the call to release the lock over a variable, even if the ttl
	// has not yet passed.
	Release(ctx context.Context) error
	// Renew is used to extend the ttl of a lock. It can be used as a heartbeat or a
	// lease to maintain the hold over the lock for longer periods or as a sync
	// mechanism among multiple instances looking to acquire the same lock.
	Renew(ctx context.Context) error

	// LockTTL returns the expiration time of the underlying lock.
	LockTTL() time.Duration
}

Locker is the interface that wraps the lock handler. It is used by the lock leaser to handle all lock operations.

type Locks

type Locks struct {
	WriteOptions
	// contains filtered or unexported fields
}

Locks is used to maintain all the resources necessary to operate over a lock. It makes the calls to the http using an exponential retry mechanism that will try until it either reaches 5 attempts or the ttl of the lock expires. The variable doesn't need to exist, one will be created internally but a path most be provided.

Important: It will be on the user to remove the variable created for the lock.

func (*Locks) Acquire

func (l *Locks) Acquire(ctx context.Context) (string, error)
Acquire will make the actual call to acquire the lock over the variable using
the ttl in the Locks to create the VariableLock. It will return the
path of the variable holding the lock.

Acquire returns the path to the variable holding the lock.

func (*Locks) LockTTL

func (l *Locks) LockTTL() time.Duration

func (*Locks) Release

func (l *Locks) Release(ctx context.Context) error

Release makes the call to release the lock over a variable, even if the ttl has not yet passed. In case of a call to release a non held lock, Release returns ErrLockConflict.

func (*Locks) Renew

func (l *Locks) Renew(ctx context.Context) error

Renew is used to extend the ttl of a lock. It can be used as a heartbeat or a lease to maintain the hold over the lock for longer periods or as a sync mechanism among multiple instances looking to acquire the same lock. Renew will return true if the renewal was successful.

In case of a call to renew a non held lock, Renew returns ErrLockConflict.

type LocksOption

type LocksOption = func(l *Locks)

func LocksOptionWithMaxRetries

func LocksOptionWithMaxRetries(maxRetries int64) LocksOption

LocksOptionWithMaxRetries allows access to configure the number of max retries the lock handler will perform in case of an expected response while interacting with the locks endpoint.

type LogConfig

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

	// COMPAT(1.6.0): Enabled had to be swapped for Disabled to fix a backwards
	// compatibility bug when restoring pre-1.5.4 jobs. Remove in 1.6.0
	Enabled *bool `mapstructure:"enabled" hcl:"enabled,optional"`

	Disabled *bool `mapstructure:"disabled" hcl:"disabled,optional"`
}

LogConfig provides configuration for log rotation

func DefaultLogConfig

func DefaultLogConfig() *LogConfig

func (*LogConfig) Canonicalize

func (l *LogConfig) Canonicalize()

type MemoryStats

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

MemoryStats holds memory usage related stats

type MetricsSummary

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

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

type MigrateStrategy

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

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

func DefaultMigrateStrategy

func DefaultMigrateStrategy() *MigrateStrategy

func (*MigrateStrategy) Canonicalize

func (m *MigrateStrategy) Canonicalize()

func (*MigrateStrategy) Copy

func (m *MigrateStrategy) Copy() *MigrateStrategy

func (*MigrateStrategy) Merge

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

type MonitorMessage

type MonitorMessage struct {
	Level   MonitorMsgLevel
	Message string
}

MonitorMessage contains a message and log level.

func Messagef

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

Messagef formats a new MonitorMessage.

func (*MonitorMessage) String

func (m *MonitorMessage) String() string

type MonitorMsgLevel

type MonitorMsgLevel int

MonitorMsgLevels represents the severity log level of a MonitorMessage.

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

type Multiregion

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

func (*Multiregion) Canonicalize

func (m *Multiregion) Canonicalize()

func (*Multiregion) Copy

func (m *Multiregion) Copy() *Multiregion

type MultiregionRegion

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

type MultiregionStrategy

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

type NUMAResource

type NUMAResource struct {
	// Affinity must be one of "none", "prefer", "require".
	Affinity string `hcl:"affinity,optional"`
}

NUMAResource contains the NUMA affinity request for scheduling purposes.

Applies only to Nomad Enterprise.

func (*NUMAResource) Canonicalize

func (n *NUMAResource) Canonicalize()

func (*NUMAResource) Copy

func (n *NUMAResource) Copy() *NUMAResource

type Namespace

type Namespace struct {
	Name                  string
	Description           string
	Quota                 string
	Capabilities          *NamespaceCapabilities          `hcl:"capabilities,block"`
	NodePoolConfiguration *NamespaceNodePoolConfiguration `hcl:"node_pool_config,block"`
	VaultConfiguration    *NamespaceVaultConfiguration    `hcl:"vault,block"`
	ConsulConfiguration   *NamespaceConsulConfiguration   `hcl:"consul,block"`
	Meta                  map[string]string
	CreateIndex           uint64
	ModifyIndex           uint64
}

Namespace is used to serialize a namespace.

type NamespaceCapabilities

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

NamespaceCapabilities represents a set of capabilities allowed for this namespace, to be checked at job submission time.

type NamespaceConsulConfiguration

type NamespaceConsulConfiguration struct {
	// Default is the Consul cluster used by jobs in this namespace that don't
	// specify a cluster of their own.
	Default string

	// Allowed specifies the Consul clusters that are allowed to be used by jobs
	// in this namespace. By default, all clusters are allowed. If an empty list
	// is provided only the namespace's default cluster is allowed. This field
	// supports wildcard globbing through the use of `*` for multi-character
	// matching. This field cannot be used with Denied.
	Allowed []string

	// Denied specifies the Consul clusters that are not allowed to be used by
	// jobs in this namespace. This field supports wildcard globbing through the
	// use of `*` for multi-character matching. If specified, any cluster is
	// allowed to be used, except for those that match any of these patterns.
	// This field cannot be used with Allowed.
	Denied []string
}

NamespaceConsulConfiguration stores configuration about permissions to Consul clusters for a namespace, for use with Nomad Enterprise.

type NamespaceIndexSort

type NamespaceIndexSort []*Namespace

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

func (NamespaceIndexSort) Len

func (n NamespaceIndexSort) Len() int

func (NamespaceIndexSort) Less

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

func (NamespaceIndexSort) Swap

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

type NamespaceNodePoolConfiguration

type NamespaceNodePoolConfiguration struct {
	Default string
	Allowed []string
	Denied  []string
}

NamespaceNodePoolConfiguration stores configuration about node pools for a namespace.

type NamespaceVaultConfiguration

type NamespaceVaultConfiguration struct {
	// Default is the Vault cluster used by jobs in this namespace that don't
	// specify a cluster of their own.
	Default string

	// Allowed specifies the Vault clusters that are allowed to be used by jobs
	// in this namespace. By default, all clusters are allowed. If an empty list
	// is provided only the namespace's default cluster is allowed. This field
	// supports wildcard globbing through the use of `*` for multi-character
	// matching. This field cannot be used with Denied.
	Allowed []string

	// Denied specifies the Vault clusters that are not allowed to be used by
	// jobs in this namespace. This field supports wildcard globbing through the
	// use of `*` for multi-character matching. If specified, any cluster is
	// allowed to be used, except for those that match any of these patterns.
	// This field cannot be used with Allowed.
	Denied []string
}

NamespaceVaultConfiguration stores configuration about permissions to Vault clusters for a namespace, for use with Nomad Enterprise.

type Namespaces

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

Namespaces is used to query the namespace endpoints.

func (*Namespaces) Delete

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

Delete is used to delete a namespace

func (*Namespaces) Info

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

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

func (*Namespaces) List

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

List is used to dump all of the namespaces.

func (*Namespaces) PrefixList

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

PrefixList is used to do a PrefixList search over namespaces

func (*Namespaces) Register

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

Register is used to register a namespace.

type NetworkResource

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

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

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

func (*NetworkResource) Canonicalize

func (n *NetworkResource) Canonicalize()

func (*NetworkResource) HasPorts

func (n *NetworkResource) HasPorts() bool

func (*NetworkResource) Megabits

func (n *NetworkResource) Megabits() int

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

type Node

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

Node is used to deserialize a node entry.

type NodeCpuResources

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

type NodeDevice

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

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

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

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

NodeDevice is an instance of a particular device.

type NodeDeviceLocality

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

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

type NodeDeviceResource

type NodeDeviceResource struct {

	// Vendor specifies the vendor of device
	Vendor string

	// Type specifies the type of the device
	Type string

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

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

	Attributes map[string]*Attribute
}

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

func (NodeDeviceResource) ID

func (r NodeDeviceResource) ID() string

type NodeDiskResources

type NodeDiskResources struct {
	DiskMB int64
}

type NodeDrainUpdateResponse

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

NodeDrainUpdateResponse is used to respond to a node drain update

type NodeEligibilityUpdateResponse

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

NodeEligibilityUpdateResponse is used to respond to a node eligibility update

type NodeEvent

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

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

type NodeIndexSort

type NodeIndexSort []*NodeListStub

NodeIndexSort reverse sorts nodes by CreateIndex

func (NodeIndexSort) Len

func (n NodeIndexSort) Len() int

func (NodeIndexSort) Less

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

func (NodeIndexSort) Swap

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

type NodeListStub

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

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

type NodeMemoryResources

type NodeMemoryResources struct {
	MemoryMB int64
}

type NodeMeta

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

NodeMeta is a client for manipulating dynamic Node metadata.

func (*NodeMeta) Apply

Apply dynamic Node metadata updates to a Node. If NodeID is unset then Node receiving the request is modified.

func (*NodeMeta) Read

func (n *NodeMeta) Read(nodeID string, qo *QueryOptions) (*NodeMetaResponse, error)

Read Node metadata (dynamic and static merged) from a Node directly. May differ from Node.Info as dynamic Node metadata updates are batched and may be delayed up to 10 seconds.

If nodeID is empty then the metadata for the Node receiving the request is returned.

type NodeMetaApplyRequest

type NodeMetaApplyRequest struct {
	NodeID string
	Meta   map[string]*string
}

NodeMetaApplyRequest contains the Node meta update.

type NodeMetaResponse

type NodeMetaResponse struct {
	// Meta is the merged static + dynamic Node metadata
	Meta map[string]string

	// Dynamic is the dynamic Node metadata (set via API)
	Dynamic map[string]*string

	// Static is the static Node metadata (set via agent configuration)
	Static map[string]string
}

NodeMetaResponse contains the merged Node metadata.

type NodePool

type NodePool struct {
	Name                   string                          `hcl:"name,label"`
	Description            string                          `hcl:"description,optional"`
	Meta                   map[string]string               `hcl:"meta,block"`
	SchedulerConfiguration *NodePoolSchedulerConfiguration `hcl:"scheduler_config,block"`
	CreateIndex            uint64
	ModifyIndex            uint64
}

NodePool is used to serialize a node pool.

type NodePoolSchedulerConfiguration

type NodePoolSchedulerConfiguration struct {
	SchedulerAlgorithm            SchedulerAlgorithm `hcl:"scheduler_algorithm,optional"`
	MemoryOversubscriptionEnabled *bool              `hcl:"memory_oversubscription_enabled,optional"`
}

NodePoolSchedulerConfiguration is used to serialize the scheduler configuration of a node pool.

type NodePools

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

NodePools is used to access node pools endpoints.

func (*NodePools) Delete

func (n *NodePools) Delete(name string, w *WriteOptions) (*WriteMeta, error)

Delete is used to delete a node pool.

func (*NodePools) Info

func (n *NodePools) Info(name string, q *QueryOptions) (*NodePool, *QueryMeta, error)

Info is used to fetch details of a specific node pool.

func (*NodePools) List

func (n *NodePools) List(q *QueryOptions) ([]*NodePool, *QueryMeta, error)

List is used to list all node pools.

func (*NodePools) ListJobs

func (n *NodePools) ListJobs(poolName string, q *QueryOptions) ([]*JobListStub, *QueryMeta, error)

ListJobs is used to list all the jobs in a node pool.

func (*NodePools) ListNodes

func (n *NodePools) ListNodes(poolName string, q *QueryOptions) ([]*NodeListStub, *QueryMeta, error)

ListNodes is used to list all the nodes in a node pool.

func (*NodePools) PrefixList

func (n *NodePools) PrefixList(prefix string, q *QueryOptions) ([]*NodePool, *QueryMeta, error)

PrefixList is used to list node pools that match a given prefix.

func (*NodePools) Register

func (n *NodePools) Register(pool *NodePool, w *WriteOptions) (*WriteMeta, error)

Register is used to create or update a node pool.

type NodePurgeResponse

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

NodePurgeResponse is used to deserialize a Purge response.

type NodeReservedCpuResources

type NodeReservedCpuResources struct {
	CpuShares uint64
}

type NodeReservedDiskResources

type NodeReservedDiskResources struct {
	DiskMB uint64
}

type NodeReservedMemoryResources

type NodeReservedMemoryResources struct {
	MemoryMB uint64
}

type NodeReservedNetworkResources

type NodeReservedNetworkResources struct {
	ReservedHostPorts string
}

type NodeResources

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

	MinDynamicPort int
	MaxDynamicPort int
}

type NodeScoreMeta

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

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

type NodeUpdateDrainRequest

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

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

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

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

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

type NodeUpdateEligibilityRequest

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

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

type Nodes

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

Nodes is used to query node-related API endpoints

func (*Nodes) Allocations

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

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

func (*Nodes) CSIVolumes

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

func (*Nodes) ForceEvaluate

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

ForceEvaluate is used to force-evaluate an existing node.

func (*Nodes) GC

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

func (*Nodes) GcAlloc

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

TODO Add tests

func (*Nodes) Info

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

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

func (*Nodes) List

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

List is used to list out all the nodes

func (*Nodes) Meta

func (n *Nodes) Meta() *NodeMeta

Meta returns a NodeMeta client.

func (*Nodes) MonitorDrain

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

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

func (*Nodes) PrefixList

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

func (*Nodes) PrefixListOpts

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

func (*Nodes) Purge

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

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

func (*Nodes) Stats

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

func (*Nodes) ToggleEligibility

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

ToggleEligibility is used to update the scheduling eligibility of the node

func (*Nodes) UpdateDrain

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

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

func (*Nodes) UpdateDrainOpts

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

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

type ObjectDiff

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

type OneTimeToken

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

type OneTimeTokenExchangeRequest

type OneTimeTokenExchangeRequest struct {
	OneTimeSecretID string
}

type OneTimeTokenExchangeResponse

type OneTimeTokenExchangeResponse struct {
	Token *ACLToken
}

type OneTimeTokenUpsertResponse

type OneTimeTokenUpsertResponse struct {
	OneTimeToken *OneTimeToken
}

type Operator

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

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

func (*Operator) ApplyLicense

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

func (*Operator) AutopilotCASConfiguration

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

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

func (*Operator) AutopilotGetConfiguration

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

AutopilotGetConfiguration is used to query the current Autopilot configuration.

func (*Operator) AutopilotServerHealth

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

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

func (*Operator) AutopilotSetConfiguration

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

AutopilotSetConfiguration is used to set the current Autopilot configuration.

func (*Operator) LicenseGet

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

func (*Operator) LicensePut

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

func (*Operator) Metrics

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

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

func (*Operator) MetricsSummary

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

MetricsSummary returns a MetricsSummary struct and query metadata

func (*Operator) RaftGetConfiguration

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

RaftGetConfiguration is used to query the current Raft peer set.

func (*Operator) RaftRemovePeerByAddress

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

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

func (*Operator) RaftRemovePeerByID

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

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

func (*Operator) RaftTransferLeadershipByAddress

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

RaftTransferLeadershipByAddress is used to transfer leadership to a different peer using its address in the form of "IP:port".

func (*Operator) RaftTransferLeadershipByID

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

RaftTransferLeadershipByID is used to transfer leadership to a different peer using its Raft ID.

func (*Operator) SchedulerCASConfiguration

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

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

func (*Operator) SchedulerGetConfiguration

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

SchedulerGetConfiguration is used to query the current Scheduler configuration.

func (*Operator) SchedulerSetConfiguration

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

SchedulerSetConfiguration is used to set the current Scheduler configuration.

func (*Operator) Snapshot

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

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

func (*Operator) SnapshotRestore

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

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

func (*Operator) UpgradeCheckVaultWorkloadIdentity

func (op *Operator) UpgradeCheckVaultWorkloadIdentity(q *QueryOptions) (*VaultWorkloadIdentityUpgradeCheck, *QueryMeta, error)

UpgradeCheckVaultWorkloadIdentity retrieves the cluster status for migrating to workload identities with Vault.

type OperatorHealthReply

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

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

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

	// The ID of the current leader.
	Leader string

	// List of servers that are voters in the Raft configuration.
	Voters []string

	// ReadReplicas holds the list of servers that are
	// read replicas in the Raft configuration. (Enterprise only)
	ReadReplicas []string `json:",omitempty"`

	// RedundancyZones holds the list of servers in each redundancy zone.
	// (Enterprise only)
	RedundancyZones map[string]AutopilotZone `json:",omitempty"`

	// Upgrade holds the current upgrade status.
	Upgrade *AutopilotUpgrade `json:",omitempty"`

	// The number of servers that could be lost without an outage
	// occurring if all the voters don't fail at once.  (Enterprise only)
	OptimisticFailureTolerance int `json:",omitempty"`
}

OperatorHealthReply is a representation of the overall health of the cluster

type ParameterizedJobConfig

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

ParameterizedJobConfig is used to configure the parameterized job.

type PeriodicConfig

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

PeriodicConfig is for serializing periodic config for a job.

func (*PeriodicConfig) Canonicalize

func (p *PeriodicConfig) Canonicalize()

func (*PeriodicConfig) GetLocation

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

func (*PeriodicConfig) Next

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

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

type PlanAnnotations

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

type PlanOptions

type PlanOptions struct {
	Diff           bool
	PolicyOverride bool
}

PlanOptions is used to pass through job planning parameters

type PointValue

type PointValue struct {
	Name   string
	Points []float32
}

type Port

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

type PortMapping

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

type PprofOptions

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

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

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

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

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

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

type PreemptionConfig

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

PreemptionConfig specifies whether preemption is enabled based on scheduler type

type QueryMeta

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

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

	// Is there a known leader
	KnownLeader bool

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

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

QueryMeta is used to return meta data about a query

type QueryOptions

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

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

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

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

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

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

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

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

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

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

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

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

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

QueryOptions are used to parametrize a query

func (*QueryOptions) Context

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

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

func (*QueryOptions) SetHeadersFromCSISecrets

func (q *QueryOptions) SetHeadersFromCSISecrets(secrets CSISecrets)

func (*QueryOptions) WithContext

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

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

type QuotaLimit

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

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

	// VariablesLimit is the maximum total size of all variables
	// Variable.EncryptedData. A value of zero is treated as unlimited and a
	// negative value is treated as fully disallowed.
	VariablesLimit *int `mapstructure:"variables_limit" hcl:"variables_limit,optional"`

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

QuotaLimit describes the resource limit in a particular region.

type QuotaLimitSort

type QuotaLimitSort []*QuotaLimit

QuotaLimitSort is a wrapper to sort QuotaLimits

func (QuotaLimitSort) Len

func (q QuotaLimitSort) Len() int

func (QuotaLimitSort) Less

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

func (QuotaLimitSort) Swap

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

type QuotaSpec

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

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

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

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

QuotaSpec specifies the allowed resource usage across regions.

type QuotaSpecIndexSort

type QuotaSpecIndexSort []*QuotaSpec

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

func (QuotaSpecIndexSort) Len

func (q QuotaSpecIndexSort) Len() int

func (QuotaSpecIndexSort) Less

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

func (QuotaSpecIndexSort) Swap

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

type QuotaUsage

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

QuotaUsage is the resource usage of a Quota

type QuotaUsageIndexSort

type QuotaUsageIndexSort []*QuotaUsage

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

func (QuotaUsageIndexSort) Len

func (q QuotaUsageIndexSort) Len() int

func (QuotaUsageIndexSort) Less

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

func (QuotaUsageIndexSort) Swap

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

type Quotas

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

Quotas is used to query the quotas endpoints.

func (*Quotas) Delete

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

Delete is used to delete a quota spec

func (*Quotas) Info

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

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

func (*Quotas) List

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

List is used to dump all of the quota specs

func (*Quotas) ListUsage

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

ListUsage is used to dump all of the quota usages

func (*Quotas) PrefixList

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

PrefixList is used to do a PrefixList search over quota specs

func (*Quotas) PrefixListUsage

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

PrefixList is used to do a PrefixList search over quota usages

func (*Quotas) Register

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

Register is used to register a quota spec.

func (*Quotas) Usage

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

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

type RaftConfiguration

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

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

RaftConfiguration is returned when querying for the current Raft configuration.

type RaftServer

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

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

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

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

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

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

RaftServer has information about a server in the Raft configuration.

type Raw

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

Raw can be used to do raw queries against custom endpoints

func (*Raw) Delete

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

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

func (*Raw) Do

func (raw *Raw) Do(req *http.Request) (*http.Response, error)

Do uses the raw client's internal httpClient to process the request

func (*Raw) Query

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

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

func (*Raw) Response

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

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

func (*Raw) Write

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

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

type Recommendation

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

	SubmitTime int64

	CreateIndex uint64
	ModifyIndex uint64
}

Recommendation is used to serialize a recommendation.

type RecommendationApplyRequest

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

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

type RecommendationApplyResponse

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

RecommendationApplyResponse is used to apply a set of recommendations

type Recommendations

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

Recommendations is used to query the recommendations endpoints.

func (*Recommendations) Apply

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

Apply is used to apply a set of recommendations

func (*Recommendations) Delete

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

Delete is used to delete a list of recommendations

func (*Recommendations) Info

Info is used to return information on a single recommendation

func (*Recommendations) List

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

func (*Recommendations) Upsert

Upsert is used to create or update a recommendation

type ReconcileOption

type ReconcileOption = string

type Regions

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

Regions is used to query the regions in the cluster.

func (*Regions) List

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

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

type RegisterOptions

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

RegisterOptions is used to pass through job registration parameters

type RequestedDevice

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

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

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

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

RequestedDevice is used to request a device for a task.

func (*RequestedDevice) Canonicalize

func (d *RequestedDevice) Canonicalize()

type RescheduleEvent

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

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

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

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

type ReschedulePolicy

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

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

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

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

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

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

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

func NewDefaultReschedulePolicy

func NewDefaultReschedulePolicy(jobType string) *ReschedulePolicy

func (*ReschedulePolicy) Canonicalize

func (r *ReschedulePolicy) Canonicalize(jobType string)

func (*ReschedulePolicy) Copy

func (*ReschedulePolicy) Merge

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

func (*ReschedulePolicy) String

func (p *ReschedulePolicy) String() string

type RescheduleTracker

type RescheduleTracker struct {
	Events []*RescheduleEvent
}

RescheduleTracker encapsulates previous reschedule events

type ResourceUsage

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

ResourceUsage holds information related to cpu and memory stats

type Resources

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

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

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

func DefaultResources

func DefaultResources() *Resources

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

func MinResources

func MinResources() *Resources

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

func (*Resources) Canonicalize

func (r *Resources) Canonicalize()

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

func (*Resources) Merge

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

Merge merges this resource with another resource.

type RestartPolicy

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

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

func (*RestartPolicy) Merge

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

type RootKeyMeta

type RootKeyMeta struct {
	KeyID       string // UUID
	Algorithm   EncryptionAlgorithm
	CreateTime  int64
	CreateIndex uint64
	ModifyIndex uint64
	State       RootKeyState
}

RootKeyMeta is the metadata used to refer to a RootKey.

type RootKeyState

type RootKeyState string

RootKeyState enum describes the lifecycle of a root key.

type SampledValue

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

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

type Scaling

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

Scaling is used to query scaling-related API endpoints

func (*Scaling) GetPolicy

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

func (*Scaling) ListPolicies

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

type ScalingEvent

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

type ScalingPolicy

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

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

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

func (*ScalingPolicy) Canonicalize

func (p *ScalingPolicy) Canonicalize(taskGroupCount int)

type ScalingPolicyListStub

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

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

type ScalingRequest

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

ScalingRequest is the payload for a generic scaling action

type SchedulerAlgorithm

type SchedulerAlgorithm string

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

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

type SchedulerConfiguration

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

	// PreemptionConfig specifies whether to enable eviction of lower
	// priority jobs to place higher priority jobs.
	PreemptionConfig PreemptionConfig

	// MemoryOversubscriptionEnabled specifies whether memory oversubscription is enabled
	MemoryOversubscriptionEnabled bool

	// RejectJobRegistration disables new job registrations except with a
	// management ACL token
	RejectJobRegistration bool

	// PauseEvalBroker stops the leader evaluation broker process from running
	// until the configuration is updated and written to the Nomad servers.
	PauseEvalBroker bool

	// CreateIndex/ModifyIndex store the create/modify indexes of this configuration.
	CreateIndex uint64
	ModifyIndex uint64
}

SchedulerConfiguration is the config for controlling scheduler behavior

type SchedulerConfigurationResponse

type SchedulerConfigurationResponse struct {
	// SchedulerConfig contains scheduler config options
	SchedulerConfig *SchedulerConfiguration

	QueryMeta
}

SchedulerConfigurationResponse is the response object that wraps SchedulerConfiguration

type SchedulerSetConfigurationResponse

type SchedulerSetConfigurationResponse struct {
	// Updated returns whether the config was actually updated
	// Only set when the request uses CAS
	Updated bool

	WriteMeta
}

SchedulerSetConfigurationResponse is the response object used when updating scheduler configuration

type SchedulerWorkerPoolArgs

type SchedulerWorkerPoolArgs struct {
	NumSchedulers     int
	EnabledSchedulers []string
}
type Search struct {
	// contains filtered or unexported fields
}

func (*Search) FuzzySearch

func (s *Search) FuzzySearch(text string, context contexts.Context, q *QueryOptions) (*FuzzySearchResponse, *QueryMeta, error)

FuzzySearch returns a set of matches for a given context and string.

func (*Search) PrefixSearch

func (s *Search) PrefixSearch(prefix string, context contexts.Context, q *QueryOptions) (*SearchResponse, *QueryMeta, error)

PrefixSearch returns a set of matches for a particular context and prefix.

type SearchRequest

type SearchRequest struct {
	Prefix  string
	Context contexts.Context
	QueryOptions
}

type SearchResponse

type SearchResponse struct {
	Matches     map[contexts.Context][]string
	Truncations map[contexts.Context]bool
	QueryMeta
}

type SentinelPolicies

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

SentinelPolicies is used to query the Sentinel Policy endpoints.

func (*SentinelPolicies) Delete

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

Delete is used to delete a policy

func (*SentinelPolicies) Info

func (a *SentinelPolicies) Info(policyName string, q *QueryOptions) (*SentinelPolicy, *QueryMeta, error)

Info is used to query a specific policy

func (*SentinelPolicies) List

List is used to dump all of the policies.

func (*SentinelPolicies) Upsert

func (a *SentinelPolicies) Upsert(policy *SentinelPolicy, q *WriteOptions) (*WriteMeta, error)

Upsert is used to create or update a policy

type SentinelPolicy

type SentinelPolicy struct {
	Name             string
	Description      string
	Scope            string
	EnforcementLevel string
	Policy           string
	CreateIndex      uint64
	ModifyIndex      uint64
}

type SentinelPolicyListStub

type SentinelPolicyListStub struct {
	Name             string
	Description      string
	Scope            string
	EnforcementLevel string
	CreateIndex      uint64
	ModifyIndex      uint64
}

type ServerHealth

type ServerHealth struct {
	// ID is the raft ID of the server.
	ID string

	// Name is the node name of the server.
	Name string

	// Address is the address of the server.
	Address string

	// The status of the SerfHealth check for the server.
	SerfStatus string

	// Version is the Nomad version of the server.
	Version string

	// Leader is whether this server is currently the leader.
	Leader bool

	// LastContact is the time since this node's last contact with the leader.
	LastContact time.Duration

	// LastTerm is the highest leader term this server has a record of in its Raft log.
	LastTerm uint64

	// LastIndex is the last log index this server has a record of in its Raft log.
	LastIndex uint64

	// Healthy is whether or not the server is healthy according to the current
	// Autopilot config.
	Healthy bool

	// Voter is whether this is a voting server.
	Voter bool

	// StableSince is the last time this server's Healthy value changed.
	StableSince time.Time
}

ServerHealth is the health (from the leader's point of view) of a server.

func (*ServerHealth) MarshalJSON

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

func (*ServerHealth) UnmarshalJSON

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

type ServerMembers

type ServerMembers struct {
	ServerName   string
	ServerRegion string
	ServerDC     string
	Members      []*AgentMember
}

type Service

type Service struct {
	Name              string            `hcl:"name,optional"`
	Tags              []string          `hcl:"tags,optional"`
	CanaryTags        []string          `mapstructure:"canary_tags" hcl:"canary_tags,optional"`
	EnableTagOverride bool              `mapstructure:"enable_tag_override" hcl:"enable_tag_override,optional"`
	PortLabel         string            `mapstructure:"port" hcl:"port,optional"`
	AddressMode       string            `mapstructure:"address_mode" hcl:"address_mode,optional"`
	Address           string            `hcl:"address,optional"`
	Checks            []ServiceCheck    `hcl:"check,block"`
	CheckRestart      *CheckRestart     `mapstructure:"check_restart" hcl:"check_restart,block"`
	Connect           *ConsulConnect    `hcl:"connect,block"`
	Meta              map[string]string `hcl:"meta,block"`
	CanaryMeta        map[string]string `hcl:"canary_meta,block"`
	TaggedAddresses   map[string]string `hcl:"tagged_addresses,block"`
	TaskName          string            `mapstructure:"task" hcl:"task,optional"`
	OnUpdate          string            `mapstructure:"on_update" hcl:"on_update,optional"`
	Identity          *WorkloadIdentity `hcl:"identity,block"`

	// Provider defines which backend system provides the service registration,
	// either "consul" (default) or "nomad".
	Provider string `hcl:"provider,optional"`

	// Cluster is valid only for Nomad Enterprise with provider: consul
	Cluster string `hcl:"cluster,optional"`
}

Service represents a Nomad job-submitters view of a Consul or Nomad service.

func (*Service) Canonicalize

func (s *Service) Canonicalize(t *Task, tg *TaskGroup, job *Job)

Canonicalize the Service by ensuring its name and address mode are set. Task will be nil for group services.

type ServiceCheck

type ServiceCheck struct {
	Name                   string              `hcl:"name,optional"`
	Type                   string              `hcl:"type,optional"`
	Command                string              `hcl:"command,optional"`
	Args                   []string            `hcl:"args,optional"`
	Path                   string              `hcl:"path,optional"`
	Protocol               string              `hcl:"protocol,optional"`
	PortLabel              string              `mapstructure:"port" hcl:"port,optional"`
	Expose                 bool                `hcl:"expose,optional"`
	AddressMode            string              `mapstructure:"address_mode" hcl:"address_mode,optional"`
	Advertise              string              `hcl:"advertise,optional"`
	Interval               time.Duration       `hcl:"interval,optional"`
	Timeout                time.Duration       `hcl:"timeout,optional"`
	InitialStatus          string              `mapstructure:"initial_status" hcl:"initial_status,optional"`
	TLSServerName          string              `mapstructure:"tls_server_name" hcl:"tls_server_name,optional"`
	TLSSkipVerify          bool                `mapstructure:"tls_skip_verify" hcl:"tls_skip_verify,optional"`
	Header                 map[string][]string `hcl:"header,block"`
	Method                 string              `hcl:"method,optional"`
	CheckRestart           *CheckRestart       `mapstructure:"check_restart" hcl:"check_restart,block"`
	GRPCService            string              `mapstructure:"grpc_service" hcl:"grpc_service,optional"`
	GRPCUseTLS             bool                `mapstructure:"grpc_use_tls" hcl:"grpc_use_tls,optional"`
	TaskName               string              `mapstructure:"task" hcl:"task,optional"`
	SuccessBeforePassing   int                 `mapstructure:"success_before_passing" hcl:"success_before_passing,optional"`
	FailuresBeforeCritical int                 `mapstructure:"failures_before_critical" hcl:"failures_before_critical,optional"`
	FailuresBeforeWarning  int                 `mapstructure:"failures_before_warning" hcl:"failures_before_warning,optional"`
	Body                   string              `hcl:"body,optional"`
	OnUpdate               string              `mapstructure:"on_update" hcl:"on_update,optional"`
}

ServiceCheck represents a Nomad job-submitters view of a Consul service health check.

type ServiceRegistration

type ServiceRegistration struct {

	// ID is the unique identifier for this registration. It currently follows
	// the Consul service registration format to provide consistency between
	// the two solutions.
	ID string

	// ServiceName is the human friendly identifier for this service
	// registration.
	ServiceName string

	// Namespace represents the namespace within which this service is
	// registered.
	Namespace string

	// NodeID is Node.ID on which this service registration is currently
	// running.
	NodeID string

	// Datacenter is the DC identifier of the node as identified by
	// Node.Datacenter.
	Datacenter string

	// JobID is Job.ID and represents the job which contained the service block
	// which resulted in this service registration.
	JobID string

	// AllocID is Allocation.ID and represents the allocation within which this
	// service is running.
	AllocID string

	// Tags are determined from either Service.Tags or Service.CanaryTags and
	// help identify this service. Tags can also be used to perform lookups of
	// services depending on their state and role.
	Tags []string

	// Address is the IP address of this service registration. This information
	// comes from the client and is not guaranteed to be routable; this depends
	// on cluster network topology.
	Address string

	// Port is the port number on which this service registration is bound. It
	// is determined by a combination of factors on the client.
	Port int

	CreateIndex uint64
	ModifyIndex uint64
}

ServiceRegistration is an instance of a single allocation advertising itself as a named service with a specific address. Each registration is constructed from the job specification Service block. Whether the service is registered within Nomad, and therefore generates a ServiceRegistration is controlled by the Service.Provider parameter.

type ServiceRegistrationListStub

type ServiceRegistrationListStub struct {

	// Namespace details the namespace in which these services have been
	// registered.
	Namespace string

	// Services is a list of services found within the namespace.
	Services []*ServiceRegistrationStub
}

ServiceRegistrationListStub represents all service registrations held within a single namespace.

type ServiceRegistrationStub

type ServiceRegistrationStub struct {

	// ServiceName is the human friendly name for this service as specified
	// within Service.Name.
	ServiceName string

	// Tags is a list of unique tags found for this service. The list is
	// de-duplicated automatically by Nomad.
	Tags []string
}

ServiceRegistrationStub is the stub object describing an individual namespaced service. The object is built in a manner which would allow us to add additional fields in the future, if we wanted.

type Services

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

Services is used to query the service endpoints.

func (*Services) Delete

func (s *Services) Delete(serviceName, serviceID string, q *WriteOptions) (*WriteMeta, error)

Delete can be used to delete an individual service registration as defined by its service name and service ID.

func (*Services) Get

func (s *Services) Get(serviceName string, q *QueryOptions) ([]*ServiceRegistration, *QueryMeta, error)

Get is used to return a list of service registrations whose name matches the specified parameter.

func (*Services) List

List can be used to list all service registrations currently stored within the target namespace. It returns a stub response object.

type SidecarTask

type SidecarTask struct {
	Name          string                 `hcl:"name,optional"`
	Driver        string                 `hcl:"driver,optional"`
	User          string                 `hcl:"user,optional"`
	Config        map[string]interface{} `hcl:"config,block"`
	Env           map[string]string      `hcl:"env,block"`
	Resources     *Resources             `hcl:"resources,block"`
	Meta          map[string]string      `hcl:"meta,block"`
	KillTimeout   *time.Duration         `mapstructure:"kill_timeout" hcl:"kill_timeout,optional"`
	LogConfig     *LogConfig             `mapstructure:"logs" hcl:"logs,block"`
	ShutdownDelay *time.Duration         `mapstructure:"shutdown_delay" hcl:"shutdown_delay,optional"`
	KillSignal    string                 `mapstructure:"kill_signal" hcl:"kill_signal,optional"`
}

SidecarTask represents a subset of Task fields that can be set to override the fields of the Task generated for the sidecar

func (*SidecarTask) Canonicalize

func (st *SidecarTask) Canonicalize()

type SingleDeploymentResponse

type SingleDeploymentResponse struct {
	Deployment *Deployment
	QueryMeta
}

SingleDeploymentResponse is used to respond with a single deployment

type SingleRecommendationApplyError

type SingleRecommendationApplyError struct {
	Namespace       string
	JobID           string
	Recommendations []string
	Error           string
}

type SingleRecommendationApplyResult

type SingleRecommendationApplyResult struct {
	Namespace       string
	JobID           string
	JobModifyIndex  uint64
	EvalID          string
	EvalCreateIndex uint64
	Warnings        string
	Recommendations []string
}

type Spread

type Spread struct {
	Attribute    string          `hcl:"attribute,optional"`
	Weight       *int8           `hcl:"weight,optional"`
	SpreadTarget []*SpreadTarget `hcl:"target,block"`
}

Spread is used to serialize task group allocation spread preferences

func NewSpread

func NewSpread(attribute string, weight int8, spreadTargets []*SpreadTarget) *Spread

func (*Spread) Canonicalize

func (s *Spread) Canonicalize()

type SpreadTarget

type SpreadTarget struct {
	Value   string `hcl:",label"`
	Percent uint8  `hcl:"percent,optional"`
}

SpreadTarget is used to serialize target allocation spread percentages

func NewSpreadTarget

func NewSpreadTarget(value string, percent uint8) *SpreadTarget

type StatObject

type StatObject struct {
	// Nested is a mapping of object name to a nested stats object.
	Nested map[string]*StatObject

	// Attributes is a mapping of statistic name to its value.
	Attributes map[string]*StatValue
}

StatObject is a collection of statistics either exposed at the top level or via nested StatObjects.

type StatValue

type StatValue struct {
	// FloatNumeratorVal exposes a floating point value. If denominator is set
	// it is assumed to be a fractional value, otherwise it is a scalar.
	FloatNumeratorVal   *float64 `json:",omitempty"`
	FloatDenominatorVal *float64 `json:",omitempty"`

	// IntNumeratorVal exposes a int value. If denominator is set it is assumed
	// to be a fractional value, otherwise it is a scalar.
	IntNumeratorVal   *int64 `json:",omitempty"`
	IntDenominatorVal *int64 `json:",omitempty"`

	// StringVal exposes a string value. These are likely annotations.
	StringVal *string `json:",omitempty"`

	// BoolVal exposes a boolean statistic.
	BoolVal *bool `json:",omitempty"`

	// Unit gives the unit type: °F, %, MHz, MB, etc.
	Unit string `json:",omitempty"`

	// Desc provides a human readable description of the statistic.
	Desc string `json:",omitempty"`
}

StatValue exposes the values of a particular statistic. The value may be of type float, integer, string or boolean. Numeric types can be exposed as a single value or as a fraction.

func (*StatValue) String

func (v *StatValue) String() string

type Status

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

Status is used to query the status-related endpoints.

func (*Status) Leader

func (s *Status) Leader() (string, error)

Leader is used to query for the current cluster leader.

func (*Status) Peers

func (s *Status) Peers() ([]string, error)

Peers is used to query the addresses of the server peers in the cluster.

func (*Status) RegionLeader

func (s *Status) RegionLeader(region string) (string, error)

RegionLeader is used to query for the leader in the passed region.

type StreamFrame

type StreamFrame struct {
	Offset    int64  `json:",omitempty"`
	Data      []byte `json:",omitempty"`
	File      string `json:",omitempty"`
	FileEvent string `json:",omitempty"`
}

StreamFrame is used to frame data of a file when streaming

func (*StreamFrame) IsHeartbeat

func (s *StreamFrame) IsHeartbeat() bool

IsHeartbeat returns if the frame is a heartbeat frame

type System

type System struct {
	// contains filtered or unexported fields
}

Status is used to query the status-related endpoints.

func (*System) GarbageCollect

func (s *System) GarbageCollect() error

func (*System) ReconcileSummaries

func (s *System) ReconcileSummaries() error

type TLSConfig

type TLSConfig struct {
	// CACert is the path to a PEM-encoded CA cert file to use to verify the
	// Nomad server SSL certificate.
	CACert string

	// CAPath is the path to a directory of PEM-encoded CA cert files to verify
	// the Nomad server SSL certificate.
	CAPath string

	// CACertPem is the PEM-encoded CA cert to use to verify the Nomad server
	// SSL certificate.
	CACertPEM []byte

	// ClientCert is the path to the certificate for Nomad communication
	ClientCert string

	// ClientCertPEM is the PEM-encoded certificate for Nomad communication
	ClientCertPEM []byte

	// ClientKey is the path to the private key for Nomad communication
	ClientKey string

	// ClientKeyPEM is the PEM-encoded private key for Nomad communication
	ClientKeyPEM []byte

	// TLSServerName, if set, is used to set the SNI host when connecting via
	// TLS.
	TLSServerName string

	// Insecure enables or disables SSL verification
	Insecure bool
}

TLSConfig contains the parameters needed to configure TLS on the HTTP client used to communicate with Nomad.

func (*TLSConfig) Copy

func (t *TLSConfig) Copy() *TLSConfig

type Task

type Task struct {
	Name            string                 `hcl:"name,label"`
	Driver          string                 `hcl:"driver,optional"`
	User            string                 `hcl:"user,optional"`
	Lifecycle       *TaskLifecycle         `hcl:"lifecycle,block"`
	Config          map[string]interface{} `hcl:"config,block"`
	Constraints     []*Constraint          `hcl:"constraint,block"`
	Affinities      []*Affinity            `hcl:"affinity,block"`
	Env             map[string]string      `hcl:"env,block"`
	Services        []*Service             `hcl:"service,block"`
	Resources       *Resources             `hcl:"resources,block"`
	RestartPolicy   *RestartPolicy         `hcl:"restart,block"`
	Meta            map[string]string      `hcl:"meta,block"`
	KillTimeout     *time.Duration         `mapstructure:"kill_timeout" hcl:"kill_timeout,optional"`
	LogConfig       *LogConfig             `mapstructure:"logs" hcl:"logs,block"`
	Artifacts       []*TaskArtifact        `hcl:"artifact,block"`
	Vault           *Vault                 `hcl:"vault,block"`
	Consul          *Consul                `hcl:"consul,block"`
	Templates       []*Template            `hcl:"template,block"`
	DispatchPayload *DispatchPayloadConfig `hcl:"dispatch_payload,block"`
	VolumeMounts    []*VolumeMount         `hcl:"volume_mount,block"`
	CSIPluginConfig *TaskCSIPluginConfig   `mapstructure:"csi_plugin" json:",omitempty" hcl:"csi_plugin,block"`
	Leader          bool                   `hcl:"leader,optional"`
	ShutdownDelay   time.Duration          `mapstructure:"shutdown_delay" hcl:"shutdown_delay,optional"`
	KillSignal      string                 `mapstructure:"kill_signal" hcl:"kill_signal,optional"`
	Kind            string                 `hcl:"kind,optional"`
	ScalingPolicies []*ScalingPolicy       `hcl:"scaling,block"`

	// Identity is the default Nomad Workload Identity and will be added to
	// Identities with the name "default"
	Identity *WorkloadIdentity

	// Workload Identities
	Identities []*WorkloadIdentity `hcl:"identity,block"`

	Actions []*Action `hcl:"action,block"`
}

Task is a single process in a task group.

func NewTask

func NewTask(name, driver string) *Task

NewTask creates and initializes a new Task.

func (*Task) AddAffinity

func (t *Task) AddAffinity(a *Affinity) *Task

AddAffinity adds a new affinity to a single task.

func (*Task) Canonicalize

func (t *Task) Canonicalize(tg *TaskGroup, job *Job)

func (*Task) Constrain

func (t *Task) Constrain(c *Constraint) *Task

Constraint adds a new constraints to a single task.

func (*Task) Require

func (t *Task) Require(r *Resources) *Task

Require is used to add resource requirements to a task.

func (*Task) SetConfig

func (t *Task) SetConfig(key string, val interface{}) *Task

Configure is used to configure a single k/v pair on the task.

func (*Task) SetLifecycle

func (t *Task) SetLifecycle(l *TaskLifecycle) *Task

SetLifecycle is used to set lifecycle config to a task.

func (*Task) SetLogConfig

func (t *Task) SetLogConfig(l *LogConfig) *Task

SetLogConfig sets a log config to a task

func (*Task) SetMeta

func (t *Task) SetMeta(key, val string) *Task

SetMeta is used to add metadata k/v pairs to the task.

type TaskArtifact

type TaskArtifact struct {
	GetterSource   *string           `mapstructure:"source" hcl:"source,optional"`
	GetterOptions  map[string]string `mapstructure:"options" hcl:"options,block"`
	GetterHeaders  map[string]string `mapstructure:"headers" hcl:"headers,block"`
	GetterMode     *string           `mapstructure:"mode" hcl:"mode,optional"`
	GetterInsecure *bool             `mapstructure:"insecure" hcl:"insecure,optional"`
	RelativeDest   *string           `mapstructure:"destination" hcl:"destination,optional"`
}

TaskArtifact is used to download artifacts before running a task.

func (*TaskArtifact) Canonicalize

func (a *TaskArtifact) Canonicalize()

type TaskCSIPluginConfig

type TaskCSIPluginConfig struct {
	// ID is the identifier of the plugin.
	// Ideally this should be the FQDN of the plugin.
	ID string `mapstructure:"id" hcl:"id,optional"`

	// CSIPluginType instructs Nomad on how to handle processing a plugin
	Type CSIPluginType `mapstructure:"type" hcl:"type,optional"`

	// MountDir is the directory (within its container) in which the plugin creates a
	// socket (called CSISocketName) for communication with Nomad. Default is /csi.
	MountDir string `mapstructure:"mount_dir" hcl:"mount_dir,optional"`

	// StagePublishBaseDir is the base directory (within its container) in which the plugin
	// mounts volumes being staged and bind mounts volumes being published.
	// e.g. staging_target_path = {StagePublishBaseDir}/staging/{volume-id}/{usage-mode}
	// e.g. target_path = {StagePublishBaseDir}/per-alloc/{alloc-id}/{volume-id}/{usage-mode}
	// Default is /local/csi.
	StagePublishBaseDir string `mapstructure:"stage_publish_base_dir" hcl:"stage_publish_base_dir,optional"`

	// HealthTimeout is the time after which the CSI plugin tasks will be killed
	// if the CSI Plugin is not healthy.
	HealthTimeout time.Duration `mapstructure:"health_timeout" hcl:"health_timeout,optional"`
}

TaskCSIPluginConfig contains the data that is required to setup a task as a CSI plugin. This will be used by the csi_plugin_supervisor_hook to configure mounts for the plugin and initiate the connection to the plugin catalog.

func (*TaskCSIPluginConfig) Canonicalize

func (t *TaskCSIPluginConfig) Canonicalize()

type TaskDiff

type TaskDiff struct {
	Type        string
	Name        string
	Fields      []*FieldDiff
	Objects     []*ObjectDiff
	Annotations []string
}

type TaskEvent

type TaskEvent struct {
	Type           string
	Time           int64
	DisplayMessage string
	Details        map[string]string
	Message        string
	// DEPRECATION NOTICE: The following fields are all deprecated. see TaskEvent struct in structs.go for details.
	FailsTask        bool
	RestartReason    string
	SetupError       string
	DriverError      string
	DriverMessage    string
	ExitCode         int
	Signal           int
	KillReason       string
	KillTimeout      time.Duration
	KillError        string
	StartDelay       int64
	DownloadError    string
	ValidationError  string
	DiskLimit        int64
	DiskSize         int64
	FailedSibling    string
	VaultError       string
	TaskSignalReason string
	TaskSignal       string
	GenericSource    string
}

TaskEvent is an event that effects the state of a task and contains meta-data appropriate to the events type.

type TaskGroup

type TaskGroup struct {
	Name             *string                   `hcl:"name,label"`
	Count            *int                      `hcl:"count,optional"`
	Constraints      []*Constraint             `hcl:"constraint,block"`
	Affinities       []*Affinity               `hcl:"affinity,block"`
	Tasks            []*Task                   `hcl:"task,block"`
	Spreads          []*Spread                 `hcl:"spread,block"`
	Volumes          map[string]*VolumeRequest `hcl:"volume,block"`
	RestartPolicy    *RestartPolicy            `hcl:"restart,block"`
	Disconnect       *DisconnectStrategy       `hcl:"disconnect,block"`
	ReschedulePolicy *ReschedulePolicy         `hcl:"reschedule,block"`
	EphemeralDisk    *EphemeralDisk            `hcl:"ephemeral_disk,block"`
	Update           *UpdateStrategy           `hcl:"update,block"`
	Migrate          *MigrateStrategy          `hcl:"migrate,block"`
	Networks         []*NetworkResource        `hcl:"network,block"`
	Meta             map[string]string         `hcl:"meta,block"`
	Services         []*Service                `hcl:"service,block"`
	ShutdownDelay    *time.Duration            `mapstructure:"shutdown_delay" hcl:"shutdown_delay,optional"`
	// Deprecated: StopAfterClientDisconnect is deprecated in Nomad 1.8. Use Disconnect.StopOnClientAfter instead.
	StopAfterClientDisconnect *time.Duration `mapstructure:"stop_after_client_disconnect" hcl:"stop_after_client_disconnect,optional"`
	// To be deprecated after 1.8.0 infavour of Disconnect.LostAfter
	MaxClientDisconnect *time.Duration `mapstructure:"max_client_disconnect" hcl:"max_client_disconnect,optional"`
	Scaling             *ScalingPolicy `hcl:"scaling,block"`
	Consul              *Consul        `hcl:"consul,block"`
	// To be deprecated after 1.8.0 infavour of Disconnect.Replace
	PreventRescheduleOnLost *bool `hcl:"prevent_reschedule_on_lost,optional"`
}

TaskGroup is the unit of scheduling.

func NewTaskGroup

func NewTaskGroup(name string, count int) *TaskGroup

NewTaskGroup creates a new TaskGroup.

func (*TaskGroup) AddAffinity

func (g *TaskGroup) AddAffinity(a *Affinity) *TaskGroup

AddAffinity is used to add a new affinity to a task group.

func (*TaskGroup) AddSpread

func (g *TaskGroup) AddSpread(s *Spread) *TaskGroup

AddSpread is used to add a new spread preference to a task group.

func (*TaskGroup) AddTask

func (g *TaskGroup) AddTask(t *Task) *TaskGroup

AddTask is used to add a new task to a task group.

func (*TaskGroup) Canonicalize

func (g *TaskGroup) Canonicalize(job *Job)

Canonicalize sets defaults and merges settings that should be inherited from the job

func (*TaskGroup) Constrain

func (g *TaskGroup) Constrain(c *Constraint) *TaskGroup

Constrain is used to add a constraint to a task group.

func (*TaskGroup) RequireDisk

func (g *TaskGroup) RequireDisk(disk *EphemeralDisk) *TaskGroup

RequireDisk adds a ephemeral disk to the task group

func (*TaskGroup) SetMeta

func (g *TaskGroup) SetMeta(key, val string) *TaskGroup

AddMeta is used to add a meta k/v pair to a task group

type TaskGroupDiff

type TaskGroupDiff struct {
	Type    string
	Name    string
	Fields  []*FieldDiff
	Objects []*ObjectDiff
	Tasks   []*TaskDiff
	Updates map[string]uint64
}

type TaskGroupScaleStatus

type TaskGroupScaleStatus struct {
	Desired   int
	Placed    int
	Running   int
	Healthy   int
	Unhealthy int
	Events    []ScalingEvent
}

type TaskGroupSummary

type TaskGroupSummary struct {
	Queued   int
	Complete int
	Failed   int
	Running  int
	Starting int
	Lost     int
	Unknown  int
}

TaskGroup summarizes the state of all the allocations of a particular TaskGroup

type TaskHandle

type TaskHandle struct {
	Version     int
	DriverState []byte
}

Experimental - TaskHandle is based on drivers.TaskHandle and used by remote task drivers to migrate task handles between allocations.

type TaskLifecycle

type TaskLifecycle struct {
	Hook    string `mapstructure:"hook" hcl:"hook,optional"`
	Sidecar bool   `mapstructure:"sidecar" hcl:"sidecar,optional"`
}

func (*TaskLifecycle) Empty

func (l *TaskLifecycle) Empty() bool

Determine if lifecycle has user-input values

type TaskResourceUsage

type TaskResourceUsage struct {
	ResourceUsage *ResourceUsage
	Timestamp     int64
	Pids          map[string]*ResourceUsage
}

TaskResourceUsage holds aggregated resource usage of all processes in a Task and the resource usage of the individual pids

type TaskState

type TaskState struct {
	State       string
	Failed      bool
	Restarts    uint64
	LastRestart time.Time
	StartedAt   time.Time
	FinishedAt  time.Time
	Events      []*TaskEvent

	// Experimental -  TaskHandle is based on drivers.TaskHandle and used
	// by remote task drivers to migrate task handles between allocations.
	TaskHandle *TaskHandle
}

TaskState tracks the current state of a task and events that caused state transitions.

type Template

type Template struct {
	SourcePath    *string        `mapstructure:"source" hcl:"source,optional"`
	DestPath      *string        `mapstructure:"destination" hcl:"destination,optional"`
	EmbeddedTmpl  *string        `mapstructure:"data" hcl:"data,optional"`
	ChangeMode    *string        `mapstructure:"change_mode" hcl:"change_mode,optional"`
	ChangeScript  *ChangeScript  `mapstructure:"change_script" hcl:"change_script,block"`
	ChangeSignal  *string        `mapstructure:"change_signal" hcl:"change_signal,optional"`
	Splay         *time.Duration `mapstructure:"splay" hcl:"splay,optional"`
	Perms         *string        `mapstructure:"perms" hcl:"perms,optional"`
	Uid           *int           `mapstructure:"uid" hcl:"uid,optional"`
	Gid           *int           `mapstructure:"gid" hcl:"gid,optional"`
	LeftDelim     *string        `mapstructure:"left_delimiter" hcl:"left_delimiter,optional"`
	RightDelim    *string        `mapstructure:"right_delimiter" hcl:"right_delimiter,optional"`
	Envvars       *bool          `mapstructure:"env" hcl:"env,optional"`
	VaultGrace    *time.Duration `mapstructure:"vault_grace" hcl:"vault_grace,optional"`
	Wait          *WaitConfig    `mapstructure:"wait" hcl:"wait,block"`
	ErrMissingKey *bool          `mapstructure:"error_on_missing_key" hcl:"error_on_missing_key,optional"`
}

func (*Template) Canonicalize

func (tmpl *Template) Canonicalize()

type TerminalSize

type TerminalSize struct {
	Height int `json:"height,omitempty"`
	Width  int `json:"width,omitempty"`
}

TerminalSize represents the size of the terminal

type Topic

type Topic string

Topic is an event Topic

const (
	TopicDeployment Topic = "Deployment"
	TopicEvaluation Topic = "Evaluation"
	TopicAllocation Topic = "Allocation"
	TopicJob        Topic = "Job"
	TopicNode       Topic = "Node"
	TopicNodePool   Topic = "NodePool"
	TopicService    Topic = "Service"
	TopicAll        Topic = "*"
)

func (Topic) String

func (t Topic) String() string

String is a convenience function which returns the topic as a string type representation.

type UnexpectedResponseError

type UnexpectedResponseError struct {
	// contains filtered or unexported fields
}

UnexpectedResponseError tracks the components for API errors encountered when requireOK and requireStatusIn's conditions are not met.

func (UnexpectedResponseError) Additional

func (e UnexpectedResponseError) Additional() error

func (UnexpectedResponseError) Body

func (UnexpectedResponseError) Error

func (e UnexpectedResponseError) Error() string

func (UnexpectedResponseError) ExpectedStatuses

func (e UnexpectedResponseError) ExpectedStatuses() []int

func (UnexpectedResponseError) HasAdditional

func (e UnexpectedResponseError) HasAdditional() bool

func (UnexpectedResponseError) HasBody

func (e UnexpectedResponseError) HasBody() bool

func (UnexpectedResponseError) HasError

func (e UnexpectedResponseError) HasError() bool

func (UnexpectedResponseError) HasExpectedStatuses

func (e UnexpectedResponseError) HasExpectedStatuses() bool

func (UnexpectedResponseError) HasStatusCode

func (e UnexpectedResponseError) HasStatusCode() bool

func (UnexpectedResponseError) HasStatusText

func (e UnexpectedResponseError) HasStatusText() bool

func (UnexpectedResponseError) StatusCode

func (e UnexpectedResponseError) StatusCode() int

func (UnexpectedResponseError) StatusText

func (e UnexpectedResponseError) StatusText() string

func (UnexpectedResponseError) Unwrap

func (e UnexpectedResponseError) Unwrap() error

type UpdateStrategy

type UpdateStrategy struct {
	Stagger          *time.Duration `mapstructure:"stagger" hcl:"stagger,optional"`
	MaxParallel      *int           `mapstructure:"max_parallel" hcl:"max_parallel,optional"`
	HealthCheck      *string        `mapstructure:"health_check" hcl:"health_check,optional"`
	MinHealthyTime   *time.Duration `mapstructure:"min_healthy_time" hcl:"min_healthy_time,optional"`
	HealthyDeadline  *time.Duration `mapstructure:"healthy_deadline" hcl:"healthy_deadline,optional"`
	ProgressDeadline *time.Duration `mapstructure:"progress_deadline" hcl:"progress_deadline,optional"`
	Canary           *int           `mapstructure:"canary" hcl:"canary,optional"`
	AutoRevert       *bool          `mapstructure:"auto_revert" hcl:"auto_revert,optional"`
	AutoPromote      *bool          `mapstructure:"auto_promote" hcl:"auto_promote,optional"`
}

UpdateStrategy defines a task groups update strategy.

func DefaultUpdateStrategy

func DefaultUpdateStrategy() *UpdateStrategy

DefaultUpdateStrategy provides a baseline that can be used to upgrade jobs with the old policy or for populating field defaults.

func (*UpdateStrategy) Canonicalize

func (u *UpdateStrategy) Canonicalize()

func (*UpdateStrategy) Copy

func (u *UpdateStrategy) Copy() *UpdateStrategy

func (*UpdateStrategy) Empty

func (u *UpdateStrategy) Empty() bool

Empty returns whether the UpdateStrategy is empty or has user defined values.

func (*UpdateStrategy) Merge

func (u *UpdateStrategy) Merge(o *UpdateStrategy)

type Variable

type Variable struct {
	// Namespace is the Nomad namespace associated with the variable
	Namespace string `hcl:"namespace"`

	// Path is the path to the variable
	Path string `hcl:"path"`

	// CreateIndex tracks the index of creation time
	CreateIndex uint64 `hcl:"create_index"`

	// ModifyTime is the unix nano of the last modified time
	ModifyIndex uint64 `hcl:"modify_index"`

	// CreateTime is the unix nano of the creation time
	CreateTime int64 `hcl:"create_time"`

	// ModifyTime is the unix nano of the last modified time
	ModifyTime int64 `hcl:"modify_time"`

	// Items contains the k/v variable component
	Items VariableItems `hcl:"items"`

	// Lock holds the information about the variable lock if its being used.
	Lock *VariableLock `hcl:",lock,optional" json:",omitempty"`
}

Variable specifies the metadata and contents to be stored in the encrypted Nomad backend.

func NewVariable

func NewVariable(path string) *Variable

NewVariable is a convenience method to more easily create a ready-to-use variable

func (*Variable) AsJSON

func (v *Variable) AsJSON() string

AsJSON returns the Variable as a JSON-formatted string

func (*Variable) AsPrettyJSON

func (v *Variable) AsPrettyJSON() string

AsPrettyJSON returns the Variable as a JSON-formatted string with indentation

func (*Variable) Copy

func (v *Variable) Copy() *Variable

Copy returns a new deep copy of this Variable

func (*Variable) IsZeroValue

func (v *Variable) IsZeroValue() bool

IsZeroValue can be used to test if a Variable has been changed from the default values it gets at creation

func (*Variable) LockID

func (v *Variable) LockID() string

LockID returns the ID of the lock. In the event this is not held, or the variable is not a lock, this string will be empty.

func (*Variable) Metadata

func (v *Variable) Metadata() *VariableMetadata

Metadata returns the VariableMetadata component of a Variable. This can be useful for comparing against a List result.

type VariableItems

type VariableItems map[string]string

VariableItems are the key/value pairs of a Variable.

type VariableLock

type VariableLock struct {
	// ID is generated by Nomad to provide a unique caller ID which can be used
	// for renewals and unlocking.
	ID string

	// TTL describes the time-to-live of the current lock holder.
	// This is a string version of a time.Duration like "2m".
	TTL string

	// LockDelay describes a grace period that exists after a lock is lost,
	// before another client may acquire the lock. This helps protect against
	// split-brains. This is a string version of a time.Duration like "2m".
	LockDelay string
}

type VariableMetadata

type VariableMetadata struct {
	// Namespace is the Nomad namespace associated with the variable
	Namespace string `hcl:"namespace"`

	// Path is the path to the variable
	Path string `hcl:"path"`

	// CreateIndex tracks the index of creation time
	CreateIndex uint64 `hcl:"create_index"`

	// ModifyTime is the unix nano of the last modified time
	ModifyIndex uint64 `hcl:"modify_index"`

	// CreateTime is the unix nano of the creation time
	CreateTime int64 `hcl:"create_time"`

	// ModifyTime is the unix nano of the last modified time
	ModifyTime int64 `hcl:"modify_time"`

	// Lock holds the information about the variable lock if its being used.
	Lock *VariableLock `hcl:",lock,optional" json:",omitempty"`
}

VariableMetadata specifies the metadata for a variable and is used as the list object

type Variables

type Variables struct {
	// contains filtered or unexported fields
}

Variables is used to access variables.

func (*Variables) AcquireLock

func (vars *Variables) AcquireLock(v *Variable, qo *WriteOptions) (*Variable, *WriteMeta, error)

AcquireLock adds a lock on the given variable and starts a lease on it. In order to make any update on the locked variable, the lock ID has to be included in the request. In order to maintain ownership of the lock, the lease needs to be periodically renewed before the lock's TTL expires.

func (*Variables) CheckedCreate

func (vars *Variables) CheckedCreate(v *Variable, qo *WriteOptions) (*Variable, *WriteMeta, error)

CheckedCreate is used to create a variable if it doesn't exist already. If it does, it will return a ErrCASConflict that can be unwrapped for more details.

func (*Variables) CheckedDelete

func (vars *Variables) CheckedDelete(path string, checkIndex uint64, qo *WriteOptions) (*WriteMeta, error)

CheckedDelete is used to conditionally delete a variable. If the existing variable does not match the provided checkIndex, it will return an ErrCASConflict that can be unwrapped for more details.

func (*Variables) CheckedUpdate

func (vars *Variables) CheckedUpdate(v *Variable, qo *WriteOptions) (*Variable, *WriteMeta, error)

CheckedUpdate is used to updated a variable if the modify index matches the one on the server. If it does not, it will return an ErrCASConflict that can be unwrapped for more details.

func (*Variables) Create

func (vars *Variables) Create(v *Variable, qo *WriteOptions) (*Variable, *WriteMeta, error)

Create is used to create a variable.

func (*Variables) Delete

func (vars *Variables) Delete(path string, qo *WriteOptions) (*WriteMeta, error)

Delete is used to delete a variable

func (*Variables) GetItems deprecated

func (vars *Variables) GetItems(path string, qo *QueryOptions) (*VariableItems, *QueryMeta, error)

GetItems returns the inner Items collection from a variable at a given path.

Deprecated: Use GetVariableItems instead.

func (*Variables) GetVariableItems

func (vars *Variables) GetVariableItems(path string, qo *QueryOptions) (VariableItems, *QueryMeta, error)

GetVariableItems returns the inner Items collection from a variable at a given path.

func (*Variables) List

func (vars *Variables) List(qo *QueryOptions) ([]*VariableMetadata, *QueryMeta, error)

List is used to dump all of the variables, can be used to pass prefix via QueryOptions rather than as a parameter

func (*Variables) Peek

func (vars *Variables) Peek(path string, qo *QueryOptions) (*Variable, *QueryMeta, error)

Peek is used to query a single variable by path, but does not error when the variable is not found

func (*Variables) PrefixList

func (vars *Variables) PrefixList(prefix string, qo *QueryOptions) ([]*VariableMetadata, *QueryMeta, error)

PrefixList is used to do a prefix List search over variables.

func (*Variables) Read

func (vars *Variables) Read(path string, qo *QueryOptions) (*Variable, *QueryMeta, error)

Read is used to query a single variable by path. This will error if the variable is not found.

func (*Variables) ReleaseLock

func (vars *Variables) ReleaseLock(v *Variable, qo *WriteOptions) (*Variable, *WriteMeta, error)

ReleaseLock removes the lock on the given variable.

func (*Variables) RenewLock

func (vars *Variables) RenewLock(v *Variable, qo *WriteOptions) (*VariableMetadata, *WriteMeta, error)

RenewLock renews the lease for the lock on the given variable. It has to be called before the lock's TTL expires or the lock will be automatically released after the delay period.

func (*Variables) Update

func (vars *Variables) Update(v *Variable, qo *WriteOptions) (*Variable, *WriteMeta, error)

Update is used to update a variable.

type Vault

type Vault struct {
	Policies             []string `hcl:"policies,optional"`
	Role                 string   `hcl:"role,optional"`
	Namespace            *string  `mapstructure:"namespace" hcl:"namespace,optional"`
	Cluster              string   `hcl:"cluster,optional"`
	Env                  *bool    `hcl:"env,optional"`
	DisableFile          *bool    `mapstructure:"disable_file" hcl:"disable_file,optional"`
	ChangeMode           *string  `mapstructure:"change_mode" hcl:"change_mode,optional"`
	ChangeSignal         *string  `mapstructure:"change_signal" hcl:"change_signal,optional"`
	AllowTokenExpiration *bool    `mapstructure:"allow_token_expiration" hcl:"allow_token_expiration,optional"`
}

func (*Vault) Canonicalize

func (v *Vault) Canonicalize()

type VaultAccessor

type VaultAccessor struct {
	// AllocID is the ID of the allocation that requested this token.
	AllocID string

	// Task is the name of the task that requested this token.
	Task string

	// NodeID is the ID of the node running the allocation that requested this
	// token.
	NodeID string

	// Accessor is the Vault ACL token accessor ID.
	Accessor string

	// CreationTTL is the TTL set when the token was created.
	CreationTTL int

	// CreateIndex is the Raft index when the token was created.
	CreateIndex uint64
}

VaultAccessor is a Vault ACL token created by Nomad for a task to access Vault using the legacy authentication flow.

type VaultWorkloadIdentityUpgradeCheck

type VaultWorkloadIdentityUpgradeCheck struct {
	// JobsWithoutVaultIdentity is the list of jobs that have a `vault` block
	// but do not have an `identity` for Vault.
	JobsWithoutVaultIdentity []*JobListStub

	// OutdatedNodes is the list of nodes running a version of Nomad that does
	// not support workload identities for Vault.
	OutdatedNodes []*NodeListStub

	// VaultTokens is the list of Vault ACL token accessors that Nomad created
	// and will no longer manage after the cluster is migrated to workload
	// identities.
	VaultTokens []*VaultAccessor
}

VaultWorkloadIdentityUpgradeCheck is the result of verifying if the cluster is ready to switch to workload identities for Vault.

func (*VaultWorkloadIdentityUpgradeCheck) Ready

Ready returns true if the cluster is ready to migrate to workload identities with Vault.

type VolumeMount

type VolumeMount struct {
	Volume          *string `hcl:"volume,optional"`
	Destination     *string `hcl:"destination,optional"`
	ReadOnly        *bool   `mapstructure:"read_only" hcl:"read_only,optional"`
	PropagationMode *string `mapstructure:"propagation_mode" hcl:"propagation_mode,optional"`
	SELinuxLabel    *string `mapstructure:"selinux_label" hcl:"selinux_label,optional"`
}

VolumeMount represents the relationship between a destination path in a task and the task group volume that should be mounted there.

func (*VolumeMount) Canonicalize

func (vm *VolumeMount) Canonicalize()

type VolumeRequest

type VolumeRequest struct {
	Name           string           `hcl:"name,label"`
	Type           string           `hcl:"type,optional"`
	Source         string           `hcl:"source,optional"`
	ReadOnly       bool             `hcl:"read_only,optional"`
	AccessMode     string           `hcl:"access_mode,optional"`
	AttachmentMode string           `hcl:"attachment_mode,optional"`
	MountOptions   *CSIMountOptions `hcl:"mount_options,block"`
	PerAlloc       bool             `hcl:"per_alloc,optional"`
	ExtraKeysHCL   []string         `hcl1:",unusedKeys,optional" json:"-"`
}

VolumeRequest is a representation of a storage volume that a TaskGroup wishes to use.

type WaitConfig

type WaitConfig struct {
	Min *time.Duration `mapstructure:"min" hcl:"min"`
	Max *time.Duration `mapstructure:"max" hcl:"max"`
}

WaitConfig is the Min/Max duration to wait for the Consul cluster to reach a consistent state before attempting to render Templates.

func (*WaitConfig) Copy

func (wc *WaitConfig) Copy() *WaitConfig

type WorkloadIdentity

type WorkloadIdentity struct {
	Name         string        `hcl:"name,optional"`
	Audience     []string      `mapstructure:"aud" hcl:"aud,optional"`
	ChangeMode   string        `mapstructure:"change_mode" hcl:"change_mode,optional"`
	ChangeSignal string        `mapstructure:"change_signal" hcl:"change_signal,optional"`
	Env          bool          `hcl:"env,optional"`
	File         bool          `hcl:"file,optional"`
	ServiceName  string        `hcl:"service_name,optional"`
	TTL          time.Duration `mapstructure:"ttl" hcl:"ttl,optional"`
}

WorkloadIdentity is the jobspec block which determines if and how a workload identity is exposed to tasks.

type WriteMeta

type WriteMeta struct {
	// LastIndex. This can be used as a WaitIndex to perform
	// a blocking query
	LastIndex uint64

	// How long did the request take
	RequestTime time.Duration
}

WriteMeta is used to return meta data about a write

type WriteOptions

type WriteOptions struct {
	// Providing a datacenter overwrites the region provided
	// by the Config
	Region string

	// Namespace is the target namespace for the write.
	Namespace string

	// AuthToken is the secret ID of an ACL token
	AuthToken string

	// Set HTTP headers on the query.
	Headers map[string]string

	// IdempotencyToken can be used to ensure the write is idempotent.
	IdempotencyToken string
	// contains filtered or unexported fields
}

WriteOptions are used to parametrize a write

func (*WriteOptions) Context

func (o *WriteOptions) Context() context.Context

Context returns the context used for canceling HTTP requests related to this write

func (*WriteOptions) SetHeadersFromCSISecrets

func (w *WriteOptions) SetHeadersFromCSISecrets(secrets CSISecrets)

func (*WriteOptions) WithContext

func (o *WriteOptions) WithContext(ctx context.Context) *WriteOptions

WithContext creates a copy of the write options using the provided context to cancel related HTTP requests

type WriteRequest

type WriteRequest struct {
	// The target region for this write
	Region string

	// Namespace is the target namespace for this write
	Namespace string

	// SecretID is the secret ID of an ACL token
	SecretID string
}

Directories

Path Synopsis
Package contexts provides constants used with the Nomad Search API.
Package contexts provides constants used with the Nomad Search API.
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL