run

package
v0.1.18 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2023 License: MPL-2.0 Imports: 48 Imported by: 0

Documentation

Overview

Package run is responsible for OTF runs, the primary mechanism for executing terraform

Index

Constants

View Source
const ReporterLockID int64 = 179366396344335597

ReporterLockID is a unique ID guaranteeing only one reporter on a cluster is running at any time.

Variables

View Source
var ErrInvalidRunStateTransition = errors.New("invalid run state transition")

Functions

func CompilePlanReports added in v0.0.51

func CompilePlanReports(planJSON []byte) (resources Report, outputs Report, err error)

CompilePlanReports compiles reports of planned changes from a JSON representation of a plan file: one report for planned *resources*, and another for planned *outputs*.

func NewCommand added in v0.1.9

func NewCommand(api *otfapi.Client) *cobra.Command

func NewService

func NewService(opts Options) *service

Types

type CLI added in v0.1.9

type Change

type Change struct {
	Actions []ChangeAction
}

Change represents the type of change being made

type ChangeAction

type ChangeAction string
const (
	CreateAction ChangeAction = "create"
	UpdateAction ChangeAction = "update"
	DeleteAction ChangeAction = "delete"
)

type Client

type Client struct {
	*otfapi.Client
	otfapi.Config

	// Client does not implement all of service yet
	Service
}

func (*Client) FinishPhase

func (c *Client) FinishPhase(ctx context.Context, id string, phase internal.PhaseType, opts PhaseFinishOptions) (*Run, error)

func (*Client) GetLockFile

func (c *Client) GetLockFile(ctx context.Context, runID string) ([]byte, error)

func (*Client) GetPlanFile

func (c *Client) GetPlanFile(ctx context.Context, runID string, format PlanFormat) ([]byte, error)

func (*Client) GetRun

func (c *Client) GetRun(ctx context.Context, runID string) (*Run, error)

func (*Client) ListRuns

func (c *Client) ListRuns(ctx context.Context, opts ListOptions) (*resource.Page[*Run], error)

func (*Client) StartPhase

func (c *Client) StartPhase(ctx context.Context, id string, phase internal.PhaseType, opts PhaseStartOptions) (*Run, error)

func (*Client) UploadLockFile

func (c *Client) UploadLockFile(ctx context.Context, runID string, lockfile []byte) error

func (*Client) UploadPlanFile

func (c *Client) UploadPlanFile(ctx context.Context, runID string, plan []byte, format PlanFormat) error

func (*Client) Watch

func (c *Client) Watch(ctx context.Context, opts WatchOptions) (<-chan pubsub.Event, error)

Watch returns a channel subscribed to run events.

type ConfigurationVersionService

type ConfigurationVersionService configversion.Service

type CreateOptions added in v0.1.8

type CreateOptions struct {
	IsDestroy   *bool
	Refresh     *bool
	RefreshOnly *bool
	Message     *string
	// Specifies the configuration version to use for this run. If the
	// configuration version ID is nil, the run will be created using the
	// workspace's latest configuration version.
	ConfigurationVersionID *string
	TargetAddrs            []string
	ReplaceAddrs           []string
	AutoApply              *bool
	Source                 Source
	TerraformVersion       *string
	AllowEmptyApply        *bool
	// PlanOnly specifies if this is a speculative, plan-only run that
	// Terraform cannot apply. Takes precedence over whether the
	// configuration version is marked as speculative or not.
	PlanOnly  *bool
	Variables []Variable
	// contains filtered or unexported fields
}

CreateOptions represents the options for creating a new run. See api.types.RunCreateOptions for documentation on each field.

type ListOptions added in v0.1.8

type ListOptions struct {
	resource.PageOptions
	// Filter by workspace ID
	WorkspaceID *string `schema:"workspace_id,omitempty"`
	// Filter by organization name
	Organization *string `schema:"organization_name,omitempty"`
	// Filter by workspace name
	WorkspaceName *string `schema:"workspace_name,omitempty"`
	// Filter by run statuses (with an implicit OR condition)
	Statuses []Status `schema:"statuses,omitempty"`
	// Filter by plan-only runs
	PlanOnly *bool `schema:"-"`
	// Filter by sources
	Sources []Source
	// Filter by commit SHA that triggered a run
	CommitSHA *string
	// Filter by VCS user's username that triggered a run
	VCSUsername *string
}

ListOptions are options for paginating and filtering a list of runs

type Operation

type Operation string

Run operation specifies the terraform execution mode.

const (
	PlanFormatBinary = "bin"  // plan file in binary format
	PlanFormatJSON   = "json" // plan file in json format

	PlanOnlyOperation     Operation = "plan-only"
	PlanAndApplyOperation Operation = "plan-and-apply"
	DestroyAllOperation   Operation = "destroy-all"
)

type OrganizationService added in v0.1.8

type OrganizationService organization.Service

type PeriodReport added in v0.1.17

type PeriodReport struct {
	TotalTime time.Duration  `json:"total_time"`
	Periods   []StatusPeriod `json:"periods"`
}

func (PeriodReport) Percentage added in v0.1.17

func (r PeriodReport) Percentage(i int) float64

type Phase

type Phase struct {
	RunID  string      `json:"run_id"`
	Status PhaseStatus `json:"status"`

	// Timestamps of when a state transition occured. Ordered earliest
	// first.
	StatusTimestamps []PhaseStatusTimestamp `json:"status_timestamps"`

	internal.PhaseType `json:"phase"`

	// report of planned or applied resource changes
	ResourceReport *Report `json:"resource_report"`
	// report of planned or applied output changes
	OutputReport *Report `json:"output_report"`
}

Phase is a section of work performed by a run.

func (*Phase) Done added in v0.1.17

func (p *Phase) Done() bool

func (*Phase) ElapsedTime added in v0.1.17

func (p *Phase) ElapsedTime(now time.Time) time.Duration

ElapsedTime returns the time taken for the phase to complete its running state. If the run is yet to enter a running state then it returns 0. If the running state is still in progress then it returns the time since entering the running state.

func (*Phase) HasChanges

func (p *Phase) HasChanges() bool

func (*Phase) HasStarted added in v0.1.17

func (p *Phase) HasStarted() bool

func (*Phase) StartedAt added in v0.1.17

func (p *Phase) StartedAt() time.Time

StartedAt returns the time the phase started running, returning zero time if it is yet to start running.

func (*Phase) StatusTimestamp

func (p *Phase) StatusTimestamp(status PhaseStatus) (time.Time, error)

StatusTimestamp looks up the timestamp for a status

func (*Phase) String added in v0.1.17

func (p *Phase) String() string

func (*Phase) UpdateStatus

func (p *Phase) UpdateStatus(status PhaseStatus)

type PhaseFinishOptions

type PhaseFinishOptions struct {
	Errored bool `json:"errored,omitempty"`
}

PhaseFinishOptions report the status of a phase upon finishing.

type PhaseStartOptions

type PhaseStartOptions struct {
	Type    string `jsonapi:"primary,phase"`
	AgentID string `jsonapi:"attribute" json:"agent-id,omitempty"`
}

type PhaseStatus

type PhaseStatus string
const (
	PhasePending     PhaseStatus = "pending"
	PhaseQueued      PhaseStatus = "queued"
	PhaseRunning     PhaseStatus = "running"
	PhaseFinished    PhaseStatus = "finished"
	PhaseCanceled    PhaseStatus = "canceled"
	PhaseErrored     PhaseStatus = "errored"
	PhaseUnreachable PhaseStatus = "unreachable"
)

func (PhaseStatus) String

func (s PhaseStatus) String() string

type PhaseStatusTimestamp

type PhaseStatusTimestamp struct {
	Status    PhaseStatus `json:"status"`
	Timestamp time.Time   `json:"timestamp"`
}

type PlanFile

type PlanFile struct {
	ResourceChanges []ResourceChange  `json:"resource_changes"`
	OutputChanges   map[string]Change `json:"output_changes"`
}

PlanFile represents the schema of a plan file

func (*PlanFile) Summarize added in v0.0.51

func (pf *PlanFile) Summarize() (resource, output Report)

Summarize provides a tally of the types of changes proposed in the plan file.

type PlanFileOptions

type PlanFileOptions struct {
	Format PlanFormat `schema:"format,required"`
}

PlanFileOptions are options for the plan file API

type PlanFormat

type PlanFormat string

type Report added in v0.0.51

type Report struct {
	Additions    int `json:"additions"`
	Changes      int `json:"changes"`
	Destructions int `json:"destructions"`
}

Report reports a summary of additions, changes, and deletions of resources in a plan or an apply.

func ParseApplyOutput

func ParseApplyOutput(output string) (Report, error)

func (Report) HasChanges added in v0.0.51

func (r Report) HasChanges() bool

func (Report) String added in v0.0.51

func (r Report) String() string

type Reporter

Reporter reports back to VCS providers the current status of VCS-triggered runs.

func (*Reporter) Start

func (r *Reporter) Start(ctx context.Context) error

Start starts the reporter daemon. Should be invoked in a go routine.

type ReporterOptions

type ReporterOptions struct {
	ConfigurationVersionService configversion.Service
	WorkspaceService            workspace.Service
	VCSProviderService          VCSProviderService

	logr.Logger
}

type ResourceChange

type ResourceChange struct {
	Change Change
}

ResourceChange represents a proposed change to a resource in a plan file

type Run

type Run struct {
	ID                     string                  `jsonapi:"primary,runs"`
	CreatedAt              time.Time               `jsonapi:"attribute" json:"created_at"`
	IsDestroy              bool                    `jsonapi:"attribute" json:"is_destroy"`
	ForceCancelAvailableAt *time.Time              `jsonapi:"attribute" json:"force_cancel_available_at"`
	Message                string                  `jsonapi:"attribute" json:"message"`
	Organization           string                  `jsonapi:"attribute" json:"organization"`
	Refresh                bool                    `jsonapi:"attribute" json:"refresh"`
	RefreshOnly            bool                    `jsonapi:"attribute" json:"refresh_only"`
	ReplaceAddrs           []string                `jsonapi:"attribute" json:"replace_addrs"`
	PositionInQueue        int                     `jsonapi:"attribute" json:"position_in_queue"`
	TargetAddrs            []string                `jsonapi:"attribute" json:"target_addrs"`
	TerraformVersion       string                  `jsonapi:"attribute" json:"terraform_version"`
	AllowEmptyApply        bool                    `jsonapi:"attribute" json:"allow_empty_apply"`
	AutoApply              bool                    `jsonapi:"attribute" json:"auto_apply"`
	PlanOnly               bool                    `jsonapi:"attribute" json:"plan_only"`
	Source                 Source                  `jsonapi:"attribute" json:"source"`
	Status                 Status                  `jsonapi:"attribute" json:"status"`
	WorkspaceID            string                  `jsonapi:"attribute" json:"workspace_id"`
	ConfigurationVersionID string                  `jsonapi:"attribute" json:"configuration_version_id"`
	ExecutionMode          workspace.ExecutionMode `jsonapi:"attribute" json:"execution_mode"`
	Variables              []Variable              `jsonapi:"attribute" json:"variables"`
	Plan                   Phase                   `jsonapi:"attribute" json:"plan"`
	Apply                  Phase                   `jsonapi:"attribute" json:"apply"`

	// Timestamps of when a state transition occured. Ordered earliest
	// first.
	StatusTimestamps []StatusTimestamp `jsonapi:"attribute" json:"status_timestamps"`

	Latest bool `jsonapi:"attribute" json:"latest"` // is latest run for workspace

	// IngressAttributes is non-nil if run was triggered by a VCS event.
	IngressAttributes *configversion.IngressAttributes `jsonapi:"attribute" json:"ingress_attributes"`

	// Username of user who created the run. This is nil if the run was
	// instead triggered by a VCS event.
	CreatedBy *string

	// OTF doesn't support cost estimation but some go-tfe API tests expect
	// a run to enter the RunCostEstimated state, and this boolean
	// determines whether to enter that state upon finishing a plan.
	CostEstimationEnabled bool
}

Run is a terraform run.

func (*Run) CanAccessOrganization

func (r *Run) CanAccessOrganization(action rbac.Action, name string) bool

func (*Run) CanAccessSite

func (*Run) CanAccessSite(action rbac.Action) bool

func (*Run) CanAccessWorkspace

func (r *Run) CanAccessWorkspace(action rbac.Action, policy *internal.WorkspacePolicy) bool

func (*Run) Cancel

func (r *Run) Cancel() error

Cancel run. Returns a boolean indicating whether a cancel request should be enqueued (for an agent to kill an in progress process)

func (*Run) Cancelable

func (r *Run) Cancelable() bool

Cancelable determines whether run can be cancelled.

func (*Run) Confirmable

func (r *Run) Confirmable() bool

Confirmable determines whether run can be confirmed.

func (*Run) Discard

func (r *Run) Discard() error

Discard updates the state of a run to reflect it having been discarded.

func (*Run) Discardable

func (r *Run) Discardable() bool

Discardable determines whether run can be discarded.

func (*Run) Done

func (r *Run) Done() bool

Done determines whether run has reached an end state, e.g. applied, discarded, etc.

func (*Run) ElapsedTime added in v0.1.17

func (r *Run) ElapsedTime(now time.Time) time.Duration

ElapsedTime returns the total time the run has taken thus far. If the run has completed, then it is the time taken from entering the pending state (creation) through to completion. Otherwise it is the time since entering the pending state.

func (*Run) EnqueueApply

func (r *Run) EnqueueApply() error

func (*Run) EnqueuePlan

func (r *Run) EnqueuePlan() error

EnqueuePlan enqueues a plan for the run. It also sets the run as the latest run for its workspace (speculative runs are ignored).

func (*Run) Finish

func (r *Run) Finish(phase internal.PhaseType, opts PhaseFinishOptions) error

Finish updates the run to reflect its plan or apply phase having finished.

func (*Run) ForceCancel

func (r *Run) ForceCancel() error

ForceCancel force cancels a run. A cool-off period of 10 seconds must have elapsed following a cancelation request before a run can be force canceled.

func (*Run) HasChanges

func (r *Run) HasChanges() bool

func (*Run) HasStarted added in v0.1.17

func (r *Run) HasStarted() bool

HasStarted is used by the running_time.tmpl partial template to determine whether to show the "elapsed time" for a run.

func (*Run) IsAPISource added in v0.1.8

func (r *Run) IsAPISource() bool

func (*Run) IsCLISource added in v0.1.8

func (r *Run) IsCLISource() bool

func (*Run) IsGithubSource added in v0.1.8

func (r *Run) IsGithubSource() bool

func (*Run) IsGitlabSource added in v0.1.8

func (r *Run) IsGitlabSource() bool

func (*Run) IsUISource added in v0.1.8

func (r *Run) IsUISource() bool

func (*Run) PeriodReport added in v0.1.17

func (r *Run) PeriodReport(now time.Time) (report PeriodReport)

PeriodReport provides a report of the duration in which a run has been in each status thus far. Completed statuses such as completed, errored, etc, are ignored because they are an instant not a period of time.

func (*Run) Phase

func (r *Run) Phase() internal.PhaseType

Phase returns the current phase.

func (*Run) Queued

func (r *Run) Queued() bool

func (*Run) Start

func (r *Run) Start(phase internal.PhaseType) error

Start a run phase

func (*Run) StartedAt added in v0.1.17

func (r *Run) StartedAt() time.Time

StartedAt returns the time the run was created.

func (*Run) StatusTimestamp

func (r *Run) StatusTimestamp(status Status) (time.Time, error)

func (*Run) String added in v0.1.17

func (r *Run) String() string

type RunService

type RunService = Service

Alias services so they don't conflict when nested together in struct

type Service

type Service interface {
	CreateRun(ctx context.Context, workspaceID string, opts CreateOptions) (*Run, error)
	GetRun(ctx context.Context, id string) (*Run, error)
	ListRuns(ctx context.Context, opts ListOptions) (*resource.Page[*Run], error)
	EnqueuePlan(ctx context.Context, runID string) (*Run, error)
	// StartPhase starts a run phase.
	StartPhase(ctx context.Context, runID string, phase internal.PhaseType, _ PhaseStartOptions) (*Run, error)
	// FinishPhase finishes a phase. Creates a report of changes before updating the status of
	// the run.
	FinishPhase(ctx context.Context, runID string, phase internal.PhaseType, opts PhaseFinishOptions) (*Run, error)
	// GetPlanFile returns the plan file for the run.
	GetPlanFile(ctx context.Context, runID string, format PlanFormat) ([]byte, error)
	// UploadPlanFile persists a run's plan file. The plan format should be either
	// be binary or json.
	UploadPlanFile(ctx context.Context, runID string, plan []byte, format PlanFormat) error
	// Watch provides access to a stream of run events. The WatchOptions filters
	// events. Context must be cancelled to close stream.
	//
	// TODO(@leg100): it would be clearer to the caller if the stream is closed by
	// returning a stream object with a Close() method. The calling code would
	// call Watch(), and then defer a Close(), which is more readable IMO.
	Watch(ctx context.Context, opts WatchOptions) (<-chan pubsub.Event, error)
	// Cancel a run. If a run is in progress then a cancelation signal will be
	// sent out.
	Cancel(ctx context.Context, runID string) (*Run, error)
	// Apply enqueues an Apply for the run.
	Apply(ctx context.Context, runID string) error
	// Delete a run.
	Delete(ctx context.Context, runID string) error

	// DiscardRun discards a run. Run must be in the planned state.
	DiscardRun(ctx context.Context, runID string) error
	// ForceCancelRun forcefully cancels a run.
	ForceCancelRun(ctx context.Context, runID string) error

	internal.Authorizer // run authorizer
	// contains filtered or unexported methods
}

type Source added in v0.1.8

type Source string

Source represents a source type of a run.

const (
	SourceAPI       Source = "tfe-api"
	SourceUI        Source = "tfe-ui"
	SourceTerraform Source = "terraform+cloud"
	SourceGithub    Source = "github"
	SourceGitlab    Source = "gitlab"
)

type Spawner

Spawner spawns new runs in response to vcs events

type Status added in v0.1.17

type Status string

Status represents a run state.

const (
	// List all available run statuses supported in OTF.
	RunApplied            Status = "applied"
	RunApplyQueued        Status = "apply_queued"
	RunApplying           Status = "applying"
	RunCanceled           Status = "canceled"
	RunForceCanceled      Status = "force_canceled"
	RunConfirmed          Status = "confirmed"
	RunDiscarded          Status = "discarded"
	RunErrored            Status = "errored"
	RunPending            Status = "pending"
	RunPlanQueued         Status = "plan_queued"
	RunPlanned            Status = "planned"
	RunPlannedAndFinished Status = "planned_and_finished"
	RunPlanning           Status = "planning"

	// OTF doesn't support cost estimation but go-tfe API tests expect this
	// status so it is included expressly to pass the tests.
	RunCostEstimated Status = "cost_estimated"
)

func (Status) String added in v0.1.17

func (r Status) String() string

type StatusPeriod added in v0.1.17

type StatusPeriod struct {
	Status Status        `json:"status"`
	Period time.Duration `json:"period"`
}

StatusPeriod is the duration over which a run has had a status.

type StatusTimestamp added in v0.1.8

type StatusTimestamp struct {
	Status    Status    `json:"status"`
	Timestamp time.Time `json:"timestamp"`
}

type VCSProviderService

type VCSProviderService vcsprovider.Service

type Variable added in v0.1.8

type Variable struct {
	Key   string
	Value string
}

type WatchOptions

type WatchOptions struct {
	Organization *string `schema:"organization_name,omitempty"` // filter by organization name
	WorkspaceID  *string `schema:"workspace_id,omitempty"`      // filter by workspace ID; mutually exclusive with organization filter
}

WatchOptions filters events returned by the Watch endpoint.

type WorkspaceService

type WorkspaceService workspace.Service

Jump to

Keyboard shortcuts

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