api

package module
Version: v0.0.0-...-2d7d633 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2023 License: MPL-2.0 Imports: 33 Imported by: 833

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

	// 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 (
	NodeStatusInit  = "initializing"
	NodeStatusReady = "ready"
	NodeStatusDown  = "down"

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

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

	// 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"
)
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 (
	ErrVariableNotFound     = "variable not found"
	ErrVariableMissingItems = "variable missing Items field"
)
View Source
const (
	AllocRestartReasonWithinPolicy = "Restart within policy"
)
View Source
const (
	// RegisterEnforceIndexErrPrefix is the prefix to use in errors caused by
	// enforcing the job modify index during registers.
	RegisterEnforceIndexErrPrefix = "Enforcing job modify index"
)
View Source
const (
	// ScalingPolicyTypeHorizontal indicates a policy that does horizontal scaling.
	ScalingPolicyTypeHorizontal = "horizontal"
)

Variables

View Source
var (
	// ClientConnTimeout is the timeout applied when attempting to contact a
	// client directly before switching to a connection through the Nomad
	// server. 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 (
	// 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 the HTTP client.

Types

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

	// 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 {
	OIDCDiscoveryURL    string
	OIDCClientID        string
	OIDCClientSecret    string
	OIDCScopes          []string
	BoundAudiences      []string
	AllowedRedirectURIs []string
	DiscoveryCaPem      []string
	SigningAlgs         []string
	ClaimMappings       map[string]string
	ListClaimMappings   map[string]string
}

ACLAuthMethodConfig is used to store configuration of an auth method.

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 ACLOIDC

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

ACLOIDC is used to query the ACL OIDC endpoints.

func (*ACLOIDC) CompleteAuth

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

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

func (*ACLOIDC) GetAuthURL

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

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)

DEPRECATED: will be removed in Nomad 1.5.0 Bootstrap is used to get the initial bootstrap token

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 Affinity

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

Affinity is used to serialize task group affinities

func NewAffinity

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

func (*Affinity) Canonicalize

func (a *Affinity) Canonicalize()

type Agent

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

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

func (*Agent) CPUProfile

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

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

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

func (*Agent) Datacenter

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

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

func (*Agent) ForceLeave

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

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

func (*Agent) GetSchedulerWorkerConfig

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

GetSchedulerWorkerConfig returns the targeted agent's worker pool configuration

func (*Agent) GetSchedulerWorkersInfo

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

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

func (*Agent) Health

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

Health queries the agent's health

func (*Agent) Host

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

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

func (*Agent) InstallKey

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

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

func (*Agent) Join

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

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

func (*Agent) ListKeys

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

ListKeys returns the list of installed keys

func (*Agent) Lookup

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

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

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

func (*Agent) Members

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

Members is used to query all of the known server members

func (*Agent) MembersOpts

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

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

func (*Agent) Monitor

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

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

func (*Agent) NodeName

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

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

func (*Agent) Region

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

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

func (*Agent) RemoveKey

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

RemoveKey removes a particular key from keyrings of serf members

func (*Agent) Self

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

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

func (*Agent) Servers

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

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

func (*Agent) SetSchedulerWorkerConfig

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

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

func (*Agent) SetServers

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

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

func (*Agent) Trace

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

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

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

func (*Agent) UseKey

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

UseKey uses a key from the keyring of serf members

type AgentHealth

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

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

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

type AgentHealthResponse

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

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

type AgentMember

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

AgentMember represents a cluster member known to the agent

type AgentMembersNameSort

type AgentMembersNameSort []*AgentMember

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

func (AgentMembersNameSort) Len

func (a AgentMembersNameSort) Len() int

func (AgentMembersNameSort) Less

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

func (AgentMembersNameSort) Swap

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

type AgentSchedulerWorkerConfigRequest

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

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

type AgentSchedulerWorkerConfigResponse

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

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

type AgentSchedulerWorkerInfo

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

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

type AgentSchedulerWorkersInfo

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

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

type AgentSelf

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

type AggregateSample

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

AggregateSample is used to hold aggregate metrics about a sample

type 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 AllocResourceUsage

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

AllocResourceUsage holds the aggregated task resource usage of the allocation.

type AllocSignalRequest

type AllocSignalRequest struct {
	Task   string
	Signal string
}

type AllocStopResponse

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

	WriteMeta
}

AllocStopResponse is the response to an `AllocStopRequest`

type AllocatedCpuResources

type AllocatedCpuResources struct {
	CpuShares int64
}

type AllocatedDeviceResource

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

type AllocatedMemoryResources

type AllocatedMemoryResources struct {
	MemoryMB    int64
	MemoryMaxMB int64
}

type AllocatedResources

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

type AllocatedSharedResources

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

type AllocatedTaskResources

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

type Allocation

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

Allocation is used for serialization of allocations.

func (*Allocation) ClientTerminalStatus

func (a *Allocation) ClientTerminalStatus() bool

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

func (Allocation) GetTaskGroup

func (a Allocation) GetTaskGroup() *TaskGroup

func (Allocation) RescheduleInfo

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

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

func (*Allocation) ServerTerminalStatus

func (a *Allocation) ServerTerminalStatus() bool

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

func (*Allocation) Stub

func (a *Allocation) Stub() *AllocationListStub

Stub returns a list stub for the allocation

type AllocationListStub

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

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

type AllocationMetric

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

AllocationMetric is used to deserialize allocation metrics.

type AllocationRestartRequest

type AllocationRestartRequest struct {
	TaskName string
	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.

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.

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

func (c *Client) ACLOIDC() *ACLOIDC

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

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

func (c *Client) Namespaces() *Namespaces

Namespaces returns a new handle on the namespaces.

func (*Client) Nodes

func (c *Client) Nodes() *Nodes

Nodes returns a handle on the node endpoints.

func (*Client) Operator

func (c *Client) Operator() *Operator

Operator returns a handle to the operator endpoints.

func (*Client) Quotas

func (c *Client) Quotas() *Quotas

Quotas returns a new handle on the quotas.

func (*Client) Raw

func (c *Client) Raw() *Raw

Raw returns a handle to query endpoints

func (*Client) Recommendations

func (c *Client) Recommendations() *Recommendations

Recommendations returns a new handle on the recommendations endpoints.

func (*Client) Regions

func (c *Client) Regions() *Regions

Regions returns a handle on the regions endpoints.

func (*Client) Scaling

func (c *Client) Scaling() *Scaling

Scaling returns a handle on the scaling endpoints.

func (*Client) Search

func (c *Client) Search() *Search

Search returns a handle on the Search endpoints

func (*Client) SentinelPolicies

func (c *Client) SentinelPolicies() *SentinelPolicies

SentinelPolicies returns a new handle on the Sentinel policies.

func (*Client) 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
}

Config is used to configure the creation of a client

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a default configuration for the client

func (*Config) ClientConfig

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

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

type Constraint

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

Constraint is used to serialize a job placement constraint.

func NewConstraint

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

NewConstraint generates a new job placement constraint.

type Consul

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

Consul represents configuration related to consul.

func (*Consul) Canonicalize

func (c *Consul) Canonicalize()

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

func (*Consul) Copy

func (c *Consul) Copy() *Consul

Copy creates a deep copy of c.

func (*Consul) MergeNamespace

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

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

type ConsulConnect

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

ConsulConnect represents a Consul Connect jobspec 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       bool     `hcl:"enabled,optional"`
	TLSMinVersion string   `hcl:"tls_min_version,optional" mapstructure:"tls_min_version"`
	TLSMaxVersion string   `hcl:"tls_max_version,optional" mapstructure:"tls_max_version"`
	CipherSuites  []string `hcl:"cipher_suites,optional" mapstructure:"cipher_suites"`
}

ConsulGatewayTLSConfig is used to configure TLS for a gateway.

func (*ConsulGatewayTLSConfig) Canonicalize

func (tc *ConsulGatewayTLSConfig) Canonicalize()

func (*ConsulGatewayTLSConfig) Copy

type ConsulIngressConfigEntry

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

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

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

func (*ConsulIngressConfigEntry) Canonicalize

func (e *ConsulIngressConfigEntry) Canonicalize()

func (*ConsulIngressConfigEntry) Copy

type ConsulIngressListener

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

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

func (*ConsulIngressListener) Canonicalize

func (l *ConsulIngressListener) Canonicalize()

func (*ConsulIngressListener) Copy

type ConsulIngressService

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

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

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

func (*ConsulIngressService) Canonicalize

func (s *ConsulIngressService) Canonicalize()

func (*ConsulIngressService) Copy

type ConsulLinkedService

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

func (*ConsulLinkedService) Canonicalize

func (s *ConsulLinkedService) Canonicalize()

func (*ConsulLinkedService) Copy

type ConsulMeshConfigEntry

type ConsulMeshConfigEntry struct {
}

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

func (*ConsulMeshConfigEntry) Canonicalize

func (e *ConsulMeshConfigEntry) Canonicalize()

func (*ConsulMeshConfigEntry) Copy

type ConsulMeshGateway

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

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

func (*ConsulMeshGateway) Canonicalize

func (c *ConsulMeshGateway) Canonicalize()

func (*ConsulMeshGateway) Copy

type ConsulProxy

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

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 ConsulUpstream

type ConsulUpstream struct {
	DestinationName      string             `mapstructure:"destination_name" hcl:"destination_name,optional"`
	DestinationNamespace string             `mapstructure:"destination_namespace" hcl:"destination_namespace,optional"`
	LocalBindPort        int                `mapstructure:"local_bind_port" hcl:"local_bind_port,optional"`
	Datacenter           string             `mapstructure:"datacenter" hcl:"datacenter,optional"`
	LocalBindAddress     string             `mapstructure:"local_bind_address" hcl:"local_bind_address,optional"`
	MeshGateway          *ConsulMeshGateway `mapstructure:"mesh_gateway" hcl:"mesh_gateway,block"`
	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 of the deployments.

func (*Deployments) Pause

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

Pause is used to pause or unpause the given deployment.

func (*Deployments) PrefixList

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

func (*Deployments) PromoteAll

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

PromoteAll is used to promote all canaries in the given deployment

func (*Deployments) PromoteGroups

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

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

func (*Deployments) SetAllocHealth

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

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

func (*Deployments) Unblock

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

Unblock is used to unblock the given deployment.

type DeregisterOptions

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

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

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

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

DeregisterOptions is used to pass through job deregistration parameters

type DesiredTransition

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

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

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

func (DesiredTransition) ShouldMigrate

func (d DesiredTransition) ShouldMigrate() bool

ShouldMigrate returns whether the transition object dictates a migration.

type DesiredUpdates

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

type DeviceGroupStats

type DeviceGroupStats struct {
	Vendor string
	Type   string
	Name   string

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

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

type DeviceStats

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

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

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

DeviceStats is the statistics for an individual device

type DiskUsage

type DiskUsage struct {
	DiskMB int64
	UsedMB int64
}

type DispatchPayloadConfig

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

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

type DrainMetadata

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

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

type DrainOptions

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

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

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

DrainOptions is used to pass through node drain parameters

type DrainSpec

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

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

DrainSpec describes a Node's drain behavior.

type DrainStatus

type DrainStatus string

type DrainStrategy

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

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

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

DrainStrategy describes a Node's drain behavior.

func (*DrainStrategy) Equal

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

func (*DrainStrategy) String

func (d *DrainStrategy) String() string

String returns a human readable version of the drain strategy.

type DriverInfo

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

DriverInfo is used to deserialize a DriverInfo entry

type 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) 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 FrameReader

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

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

func NewFrameReader

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

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

func (*FrameReader) Close

func (f *FrameReader) Close() error

Close cancels the stream of frames

func (*FrameReader) Offset

func (f *FrameReader) Offset() int

Offset returns the offset into the stream.

func (*FrameReader) Read

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

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

func (*FrameReader) SetUnblockTime

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

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

type FuzzyMatch

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

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

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

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

type FuzzySearchRequest

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

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

	QueryOptions
}

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

type FuzzySearchResponse

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

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

	QueryMeta
}

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

type GaugeValue

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

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

type GenericResponse

type GenericResponse struct {
	WriteMeta
}

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

type HostCPUStats

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

type HostData

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

type HostDataResponse

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

type HostDiskStats

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

type HostMemoryStats

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

type HostNetworkInfo

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

HostNetworkInfo is used to return metadata about a given HostNetwork

type HostStats

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

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

type HostVolumeInfo

type HostVolumeInfo struct {
	Path     string
	ReadOnly bool
}

HostVolumeInfo is used to return metadata about a given HostVolume.

type HttpBasicAuth

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

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

HttpBasicAuth is used to authenticate http client with HTTP Basic Authentication

type Job

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

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

Job is used to serialize a job.

func NewBatchJob

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

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

func NewServiceJob

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

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

func 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 {
	Job *Job
	// If EnforceIndex is set then the job will only be registered if the passed
	// JobModifyIndex matches the current Jobs index. If the index is zero, the
	// register only occurs if the job is new.
	EnforceIndex   bool   `json:",omitempty"`
	JobModifyIndex uint64 `json:",omitempty"`
	PolicyOverride bool   `json:",omitempty"`
	PreserveCounts bool   `json:",omitempty"`

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

	WriteRequest
}

JobRegisterRequest is used to update a job

type JobRegisterResponse

type JobRegisterResponse struct {
	EvalID          string
	EvalCreateIndex uint64
	JobModifyIndex  uint64

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

	QueryMeta
}

JobRegisterResponse is used to respond to a job registration

type JobRevertRequest

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

	// JobVersion the version to revert to.
	JobVersion uint64

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

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

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

	WriteRequest
}

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

type JobScaleStatusResponse

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

JobScaleStatusResponse is used to return information about job scaling status

type JobStabilityRequest

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

	// Set the stability
	Stable bool
	WriteRequest
}

JobStabilityRequest is used to marked a job as stable.

type JobStabilityResponse

type JobStabilityResponse struct {
	JobModifyIndex uint64
	WriteMeta
}

JobStabilityResponse is the response when marking a job as stable.

type JobSummary

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

	// Raft Indexes
	CreateIndex uint64
	ModifyIndex uint64
}

JobSummary summarizes the state of the allocations of a job

type JobValidateRequest

type JobValidateRequest struct {
	Job *Job
	WriteRequest
}

JobValidateRequest is used to validate a job

type JobValidateResponse

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

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

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

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

JobValidateResponse is the response from validate request

type JobVersionsResponse

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

JobVersionsResponse is used for a job get versions request

type Jobs

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

Jobs is used to access the job-specific endpoints.

func (*Jobs) Allocations

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

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

func (*Jobs) Deployments

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

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

func (*Jobs) Deregister

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

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

func (*Jobs) DeregisterOpts

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

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

func (*Jobs) Dispatch

func (j *Jobs) Dispatch(jobID string, meta map[string]string,
	payload []byte, 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 repesentation 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 convert the HCL representation of a Job to JSON server side. To parse the HCL client side see package github.com/hashicorp/nomad/jobspec. ParseHCL is an alternative convenience API for HCLv2 users.

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

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

func (*Jobs) Validate

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

func (*Jobs) Versions

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

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

type JobsParseRequest

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

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

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

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

type 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 License

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

	// The customer ID associated with the license
	CustomerID string

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

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

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

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

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

	// The product the license is valid for
	Product string

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

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

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

type LicenseReply

type LicenseReply struct {
	License        *License
	ConfigOutdated bool
	QueryMeta
}

type LogConfig

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

LogConfig provides configuration for log rotation

func DefaultLogConfig

func DefaultLogConfig() *LogConfig

func (*LogConfig) Canonicalize

func (l *LogConfig) Canonicalize()

type MemoryStats

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

MemoryStats holds memory usage related stats

type MetricsSummary

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

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

type MigrateStrategy

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

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

func DefaultMigrateStrategy

func DefaultMigrateStrategy() *MigrateStrategy

func (*MigrateStrategy) Canonicalize

func (m *MigrateStrategy) Canonicalize()

func (*MigrateStrategy) Copy

func (m *MigrateStrategy) Copy() *MigrateStrategy

func (*MigrateStrategy) Merge

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

type MonitorMessage

type MonitorMessage struct {
	Level   MonitorMsgLevel
	Message string
}

MonitorMessage contains a message and log level.

func Messagef

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

Messagef formats a new MonitorMessage.

func (*MonitorMessage) String

func (m *MonitorMessage) String() string

type MonitorMsgLevel

type MonitorMsgLevel int

MonitorMsgLevels represents the severity log level of a MonitorMessage.

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

type Multiregion

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

func (*Multiregion) Canonicalize

func (m *Multiregion) Canonicalize()

func (*Multiregion) Copy

func (m *Multiregion) Copy() *Multiregion

type MultiregionRegion

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

type MultiregionStrategy

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

type Namespace

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

Namespace is used to serialize a namespace.

type NamespaceCapabilities

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

type NamespaceIndexSort

type NamespaceIndexSort []*Namespace

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

func (NamespaceIndexSort) Len

func (n NamespaceIndexSort) Len() int

func (NamespaceIndexSort) Less

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

func (NamespaceIndexSort) Swap

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

type Namespaces

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

Namespaces is used to query the namespace endpoints.

func (*Namespaces) Delete

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

Delete is used to delete a namespace

func (*Namespaces) Info

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

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

func (*Namespaces) List

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

List is used to dump all of the namespaces.

func (*Namespaces) PrefixList

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

PrefixList is used to do a PrefixList search over namespaces

func (*Namespaces) Register

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

Register is used to register a namespace.

type NetworkResource

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

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

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

func (*NetworkResource) Canonicalize

func (n *NetworkResource) Canonicalize()

func (*NetworkResource) HasPorts

func (n *NetworkResource) HasPorts() bool

func (*NetworkResource) Megabits

func (n *NetworkResource) Megabits() int

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

type Node

type Node struct {
	ID                    string
	Datacenter            string
	Name                  string
	HTTPAddr              string
	TLSEnabled            bool
	Attributes            map[string]string
	Resources             *Resources
	Reserved              *Resources
	NodeResources         *NodeResources
	ReservedResources     *NodeReservedResources
	Links                 map[string]string
	Meta                  map[string]string
	NodeClass             string
	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
	Version               string
	Drain                 bool
	SchedulingEligibility string
	Status                string
	StatusDescription     string
	Drivers               map[string]*DriverInfo
	NodeResources         *NodeResources         `json:",omitempty"`
	ReservedResources     *NodeReservedResources `json:",omitempty"`
	LastDrain             *DrainMetadata
	CreateIndex           uint64
	ModifyIndex           uint64
}

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

type NodeMemoryResources

type NodeMemoryResources struct {
	MemoryMB int64
}

type NodePurgeResponse

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

NodePurgeResponse is used to deserialize a Purge response.

type NodeReservedCpuResources

type NodeReservedCpuResources struct {
	CpuShares uint64
}

type NodeReservedDiskResources

type NodeReservedDiskResources struct {
	DiskMB uint64
}

type NodeReservedMemoryResources

type NodeReservedMemoryResources struct {
	MemoryMB uint64
}

type NodeReservedNetworkResources

type NodeReservedNetworkResources struct {
	ReservedHostPorts string
}

type NodeResources

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

	MinDynamicPort int
	MaxDynamicPort int
}

type NodeScoreMeta

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

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

type NodeUpdateDrainRequest

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

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

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

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

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

type NodeUpdateEligibilityRequest

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

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

type Nodes

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

Nodes is used to query node-related API endpoints

func (*Nodes) Allocations

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

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

func (*Nodes) CSIVolumes

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

func (*Nodes) ForceEvaluate

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

ForceEvaluate is used to force-evaluate an existing node.

func (*Nodes) GC

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

func (*Nodes) GcAlloc

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

TODO Add tests

func (*Nodes) Info

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

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

func (*Nodes) List

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

List is used to list out all of the nodes

func (*Nodes) MonitorDrain

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

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

func (*Nodes) PrefixList

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

func (*Nodes) PrefixListOpts

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

func (*Nodes) Purge

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

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

func (*Nodes) Stats

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

func (*Nodes) ToggleEligibility

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

ToggleEligibility is used to update the scheduling eligibility of the node

func (*Nodes) UpdateDrain

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

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

func (*Nodes) UpdateDrainOpts

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

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

type ObjectDiff

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

type OneTimeToken

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

type OneTimeTokenExchangeRequest

type OneTimeTokenExchangeRequest struct {
	OneTimeSecretID string
}

type OneTimeTokenExchangeResponse

type OneTimeTokenExchangeResponse struct {
	Token *ACLToken
}

type OneTimeTokenUpsertResponse

type OneTimeTokenUpsertResponse struct {
	OneTimeToken *OneTimeToken
}

type Operator

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

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

func (*Operator) ApplyLicense

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

func (*Operator) AutopilotCASConfiguration

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

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

func (*Operator) AutopilotGetConfiguration

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

AutopilotGetConfiguration is used to query the current Autopilot configuration.

func (*Operator) AutopilotServerHealth

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

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

func (*Operator) AutopilotSetConfiguration

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

AutopilotSetConfiguration is used to set the current Autopilot configuration.

func (*Operator) LicenseGet

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

func (*Operator) LicensePut

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

func (*Operator) Metrics

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

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

func (*Operator) MetricsSummary

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

MetricsSummary returns a MetricsSummary struct and query metadata

func (*Operator) RaftGetConfiguration

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

RaftGetConfiguration is used to query the current Raft peer set.

func (*Operator) RaftRemovePeerByAddress

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

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

func (*Operator) RaftRemovePeerByID

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

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

func (*Operator) SchedulerCASConfiguration

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

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

func (*Operator) SchedulerGetConfiguration

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

SchedulerGetConfiguration is used to query the current Scheduler configuration.

func (*Operator) SchedulerSetConfiguration

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

SchedulerSetConfiguration is used to set the current Scheduler configuration.

func (*Operator) Snapshot

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

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

func (*Operator) SnapshotRestore

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

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

type OperatorHealthReply

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

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

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

OperatorHealthReply is a representation of the overall health of the cluster

type ParameterizedJobConfig

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

ParameterizedJobConfig is used to configure the parameterized job.

type PeriodicConfig

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

PeriodicConfig is for serializing periodic config for a job.

func (*PeriodicConfig) Canonicalize

func (p *PeriodicConfig) Canonicalize()

func (*PeriodicConfig) GetLocation

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

func (*PeriodicConfig) Next

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

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

type PlanAnnotations

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

type PlanOptions

type PlanOptions struct {
	Diff           bool
	PolicyOverride bool
}

PlanOptions is used to pass through job planning parameters

type PointValue

type PointValue struct {
	Name   string
	Points []float32
}

type Port

type Port struct {
	Label       string `hcl:",label"`
	Value       int    `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) Query

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

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

func (*Raw) Response

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

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

func (*Raw) Write

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

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

type Recommendation

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

	SubmitTime int64

	CreateIndex uint64
	ModifyIndex uint64
}

Recommendation is used to serialize a recommendation.

type RecommendationApplyRequest

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

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

type RecommendationApplyResponse

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

RecommendationApplyResponse is used to apply a set of recommendations

type Recommendations

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

Recommendations is used to query the recommendations endpoints.

func (*Recommendations) Apply

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

Apply is used to apply a set of recommendations

func (*Recommendations) Delete

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

Delete is used to delete a list of recommendations

func (*Recommendations) Info

Info is used to return information on a single recommendation

func (*Recommendations) List

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

func (*Recommendations) Upsert

Upsert is used to create or update a recommendation

type Regions

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

Regions is used to query the regions in the cluster.

func (*Regions) List

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

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

type