agent

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2024 License: MPL-2.0 Imports: 54 Imported by: 0

Documentation

Overview

Package agent contains code related to agents

Package agent contains code related to agents

Index

Constants

View Source
const (
	AgentTokenKind tokens.Kind = "agent_token"
	JobTokenKind   tokens.Kind = "job_token"
)
View Source
const AllocatorLockID int64 = 5577006791947779412

AllocatorLockID guarantees only one allocator on a cluster is running at any time.

View Source
const DefaultConcurrency = 5
View Source
const ManagerLockID int64 = 5577006791947779413

ManagerLockID guarantees only one manager on a cluster is running at any time.

Variables

View Source
var (
	ErrInvalidAgentStateTransition   = errors.New("invalid agent state transition")
	ErrUnauthorizedAgentRegistration = errors.New("unauthorization agent registration")
)
View Source
var (
	PluginCacheDir = filepath.Join(os.TempDir(), "plugin-cache")
	DefaultEnvs    = []string{
		"TF_IN_AUTOMATION=true",
		"CHECKPOINT_DISABLE=true",
	}
)
View Source
var (
	ErrInvalidJobStateTransition = errors.New("invalid job state transition")
	ErrMalformedJobSpecString    = errors.New("malformed stringified job spec")
)
View Source
var (
	ErrCannotDeletePoolReferencedByWorkspaces = errors.New("agent pool is still being used by workspaces in your organization. You must switch your workspaces to a different agent pool or execution mode before you can delete this agent pool")
	ErrWorkspaceNotAllowedToUsePool           = errors.New("access to this agent pool is not allowed - you must explictly grant access to the workspace first")
	ErrPoolAssignedWorkspacesNotAllowed       = errors.New("workspaces assigned to the pool have not been granted access to the pool")
)

Functions

func NewAgentsCommand

func NewAgentsCommand(apiClient *otfapi.Client) *cobra.Command

func NewPoolDaemon

func NewPoolDaemon(logger *slog.Logger, cfg Config, apiConfig otfapi.Config) (*daemon, error)

NewPoolDaemon constructs a pool agent daemon that communicates with the otfd server via RPC.

func NewServerDaemon

func NewServerDaemon(logger *slog.Logger, cfg Config, opts ServerDaemonOptions) (*daemon, error)

NewServerDaemon constructs a server agent daemon that is part of the otfd server.

Types

type Agent

type Agent struct {
	// Unique system-wide ID
	ID string `jsonapi:"primary,agents"`
	// Optional name
	Name string `jsonapi:"attribute" json:"name"`
	// Version of agent
	Version string `jsonapi:"attribute" json:"version"`
	// Current status of agent
	Status AgentStatus `jsonapi:"attribute" json:"status"`
	// Max number of jobs agent can execute
	MaxJobs int `jsonapi:"attribute" json:"max_jobs"`
	// Current number of jobs allocated to agent.
	CurrentJobs int `jsonapi:"attribute" json:"current_jobs"`
	// Last time a ping was received from the agent
	LastPingAt time.Time `jsonapi:"attribute" json:"last-ping-at"`
	// Last time the status was updated
	LastStatusAt time.Time `jsonapi:"attribute" json:"last-status-at"`
	// IP address of agent
	IPAddress net.IP `jsonapi:"attribute" json:"ip-address"`
	// ID of agent' pool. If nil then the agent is assumed to be a server agent
	// (otfd).
	AgentPoolID *string `jsonapi:"attribute" json:"agent-pool-id"`
}

Agent describes an agent. (The agent *process* is Daemon).

func (*Agent) IsServer

func (a *Agent) IsServer() bool

IsServer determines whether the agent is part of the server process (otfd) or a separate process (otf-agent).

func (*Agent) LogValue

func (a *Agent) LogValue() slog.Value

type AgentStatus

type AgentStatus string
const (
	AgentIdle    AgentStatus = "idle"
	AgentBusy    AgentStatus = "busy"
	AgentExited  AgentStatus = "exited"
	AgentErrored AgentStatus = "errored"
	AgentUnknown AgentStatus = "unknown"
)

type Config

type Config struct {
	Name            string // descriptive name for agent
	Concurrency     int    // number of jobs the agent can execute at any one time
	Sandbox         bool   // isolate privileged ops within sandbox
	Debug           bool   // toggle debug mode
	PluginCache     bool   // toggle use of terraform's shared plugin cache
	TerraformBinDir string // destination directory for terraform binaries
}

Config is configuration for an agent daemon

func NewConfigFromFlags

func NewConfigFromFlags(flags *pflag.FlagSet) *Config

type CreateAgentPoolOptions

type CreateAgentPoolOptions struct {
	Name string `schema:"name,required"`
	// name of org
	Organization string `schema:"organization_name,required"`
	// defaults to true
	OrganizationScoped *bool
	// IDs of workspaces allowed to access the pool.
	AllowedWorkspaces []string
}

type CreateAgentTokenOptions

type CreateAgentTokenOptions struct {
	Description string `json:"description" schema:"description,required"`
}

type DaemonOptions

type DaemonOptions struct {
	Logger *slog.Logger
	Config Config
	// contains filtered or unexported fields
}

type Job

type Job struct {
	// Spec uniquely identifies the job, identifying the corresponding run
	// phase.
	Spec JobSpec `jsonapi:"primary,jobs"`
	// Current status of job.
	Status JobStatus `jsonapi:"attribute" json:"status"`
	// ID of agent pool the job's workspace is assigned to use. If non-nil then
	// the job is allocated to a pool agent belonging to the pool. If nil then
	// the job is allocated to a server agent.
	AgentPoolID *string `jsonapi:"attribute" json:"agent_pool_id"`
	// Name of job's organization
	Organization string `jsonapi:"attribute" json:"organization"`
	// ID of job's workspace
	WorkspaceID string `jsonapi:"attribute" json:"workspace_id"`
	// ID of agent that this job is allocated to. Only set once job enters
	// JobAllocated state.
	AgentID *string `jsonapi:"attribute" json:"agent_id"`
	// Signaled is non-nil when a cancelation signal has been sent to the job
	// and it is true when it has been forceably canceled.
	Signaled *bool `jsonapi:"attribute" json:"signaled"`
}

Job is the unit of work corresponding to a run phase. A job is allocated to an Agent, which then executes the work through to completion.

func (*Job) CanAccessOrganization

func (j *Job) CanAccessOrganization(action rbac.Action, name string) bool

func (*Job) CanAccessSite

func (j *Job) CanAccessSite(action rbac.Action) bool

func (*Job) CanAccessTeam

func (j *Job) CanAccessTeam(rbac.Action, string) bool

func (*Job) CanAccessWorkspace

func (j *Job) CanAccessWorkspace(action rbac.Action, policy internal.WorkspacePolicy) bool

func (*Job) IsOwner

func (j *Job) IsOwner(string) bool

func (*Job) IsSiteAdmin

func (j *Job) IsSiteAdmin() bool

func (*Job) LogValue

func (j *Job) LogValue() slog.Value

func (*Job) MarshalID

func (j *Job) MarshalID() string

func (*Job) Organizations

func (j *Job) Organizations() []string

func (*Job) String

func (j *Job) String() string

func (*Job) UnmarshalID

func (j *Job) UnmarshalID(id string) error

type JobSpec

type JobSpec struct {
	// ID of the run that this job is for.
	RunID string `json:"run_id"`
	// Phase of run that this job is for.
	Phase internal.PhaseType `json:"phase"`
}

JobSpec uniquely identifies a job.

func (JobSpec) String

func (j JobSpec) String() string

type JobStatus

type JobStatus string
const (
	JobUnallocated JobStatus = "unallocated"
	JobAllocated   JobStatus = "allocated"
	JobRunning     JobStatus = "running"
	JobFinished    JobStatus = "finished"
	JobErrored     JobStatus = "errored"
	JobCanceled    JobStatus = "canceled"
)

type Pool

type Pool struct {
	// Unique system-wide ID
	ID        string
	Name      string
	CreatedAt time.Time
	// Pool belongs to an organization with this name.
	Organization string
	// Whether pool of agents is accessible to all workspaces in organization
	// (true) or only those specified in AllowedWorkspaces (false).
	OrganizationScoped bool
	// IDs of workspaces allowed to access pool. Ignored if OrganizationScoped
	// is true.
	AllowedWorkspaces []string
	// IDs of workspaces assigned to the pool. Note: this is a subset of
	// AllowedWorkspaces.
	AssignedWorkspaces []string
}

Pool is a group of non-server agents sharing one or more tokens, assigned to an organization or particular workspaces within the organization.

func (*Pool) LogValue

func (p *Pool) LogValue() slog.Value

type ServerDaemonOptions

type ServerDaemonOptions struct {
	Logger                      *slog.Logger
	Config                      Config
	RunService                  *run.Service
	WorkspaceService            *workspace.Service
	VariableService             *variable.Service
	ConfigurationVersionService *configversion.Service
	StateService                *state.Service
	LogsService                 *logs.Service
	AgentService                Service
	HostnameService             *internal.HostnameService
}

type Service

type Service interface {
	AddHandlers(r *mux.Router)
	NewAllocator(logger *slog.Logger) *allocator
	NewManager() *manager
	CreateAgentPool(ctx context.Context, opts CreateAgentPoolOptions) (*Pool, error)
	GetAgentPool(ctx context.Context, poolID string) (*Pool, error)
	WatchAgentPools(ctx context.Context) (<-chan pubsub.Event[*Pool], func())
	WatchAgents(ctx context.Context) (<-chan pubsub.Event[*Agent], func())
	WatchJobs(ctx context.Context) (<-chan pubsub.Event[*Job], func())
	CreateAgentToken(ctx context.Context, poolID string, opts CreateAgentTokenOptions) (*agentToken, []byte, error)
	GetAgentToken(ctx context.Context, tokenID string) (*agentToken, error)
	ListAgentTokens(ctx context.Context, poolID string) ([]*agentToken, error)
	DeleteAgentToken(ctx context.Context, tokenID string) (*agentToken, error)
	// contains filtered or unexported methods
}

func NewService

func NewService(opts ServiceOptions) Service

NewService constructs, and returns a new Service.

type ServiceOptions

type ServiceOptions struct {
	Logger *slog.Logger
	*sql.Pool
	*sql.Listener
	html.Renderer
	*tfeapi.Responder

	RunService       *tofutfrun.Service
	WorkspaceService *workspace.Service
	TokensService    *tokens.Service
}

type ServiceWithTracing added in v0.10.0

type ServiceWithTracing struct {
	Service
	// contains filtered or unexported fields
}

ServiceWithTracing implements Service interface instrumented with opentracing spans

func NewServiceWithTracing added in v0.10.0

func NewServiceWithTracing(base Service, instance string, spanDecorator ...func(span trace.Span, params, results map[string]interface{})) ServiceWithTracing

NewServiceWithTracing returns ServiceWithTracing

func (ServiceWithTracing) CreateAgentPool added in v0.10.0

func (_d ServiceWithTracing) CreateAgentPool(ctx context.Context, opts CreateAgentPoolOptions) (pp1 *Pool, err error)

CreateAgentPool implements Service

func (ServiceWithTracing) CreateAgentToken added in v0.10.0

func (_d ServiceWithTracing) CreateAgentToken(ctx context.Context, poolID string, opts CreateAgentTokenOptions) (ap1 *agentToken, ba1 []byte, err error)

CreateAgentToken implements Service

func (ServiceWithTracing) DeleteAgentToken added in v0.10.0

func (_d ServiceWithTracing) DeleteAgentToken(ctx context.Context, tokenID string) (ap1 *agentToken, err error)

DeleteAgentToken implements Service

func (ServiceWithTracing) GetAgentPool added in v0.10.0

func (_d ServiceWithTracing) GetAgentPool(ctx context.Context, poolID string) (pp1 *Pool, err error)

GetAgentPool implements Service

func (ServiceWithTracing) GetAgentToken added in v0.10.0

func (_d ServiceWithTracing) GetAgentToken(ctx context.Context, tokenID string) (ap1 *agentToken, err error)

GetAgentToken implements Service

func (ServiceWithTracing) ListAgentTokens added in v0.10.0

func (_d ServiceWithTracing) ListAgentTokens(ctx context.Context, poolID string) (apa1 []*agentToken, err error)

ListAgentTokens implements Service

func (ServiceWithTracing) WatchAgentPools added in v0.10.0

func (_d ServiceWithTracing) WatchAgentPools(ctx context.Context) (ch1 <-chan pubsub.Event[*Pool], f1 func())

WatchAgentPools implements Service

func (ServiceWithTracing) WatchAgents added in v0.10.0

func (_d ServiceWithTracing) WatchAgents(ctx context.Context) (ch1 <-chan pubsub.Event[*Agent], f1 func())

WatchAgents implements Service

func (ServiceWithTracing) WatchJobs added in v0.10.0

func (_d ServiceWithTracing) WatchJobs(ctx context.Context) (ch1 <-chan pubsub.Event[*Job], f1 func())

WatchJobs implements Service

Jump to

Keyboard shortcuts

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