Documentation
¶
Overview ¶
Package otf is responsible for domain logic.
Index ¶
- Constants
- Variables
- func AddSubjectToContext(ctx context.Context, subj Subject) context.Context
- func Bool(b bool) *bool
- func Contains[E comparable](s []E, v E) bool
- func ConvertID(id, resource string) string
- func CredentialEnv(hostname string, token []byte) string
- func CredentialEnvKey(hostname string) string
- func CurrentTimestamp() time.Time
- func Exists(path string) bool
- func GenerateAuthToken(accountType string) (string, error)
- func GenerateRandomString(size int) string
- func GenerateToken() (string, error)
- func GetID(s any) (string, bool)
- func GetMapKeys(m map[string]interface{}) []string
- func Index[E comparable](s []E, v E) int
- func Int(i int) *int
- func Int64(i int64) *int64
- func NewAllowAllAuthorizer() *allowAllAuthorizer
- func NewHostnameService(hostname string) *hostnameService
- func NewID(rtype string) string
- func NewSigner(secret string) *surl.Signer
- func NormalizeAddress(addr *net.TCPAddr) string
- func Pack(src string) ([]byte, error)
- func ParseBranchRef(ref string) (string, bool)
- func ParseRef(ref string) (string, bool)
- func PrefixSlice(slice []string, prefix string) (ret []string)
- func RemoveBackendBlock(f *hclwrite.File) bool
- func RewriteHCL(modulePath string, operations ...hclOperation) error
- func SSLCertsDir() string
- func String(str string) *string
- func Time(t time.Time) *time.Time
- func UInt(i uint) *uint
- func UUID(u uuid.UUID) *uuid.UUID
- func Unpack(r io.Reader, dst string) error
- func ValidSemanticVersion(v string) bool
- func ValidStringID(v *string) bool
- func VerifySignedURL(v Verifier) mux.MiddlewareFunc
- func WriteSSEEvent(w io.Writer, data []byte, event EventType, base64encode bool)
- type Authorizer
- type Broker
- type Cache
- type Chunk
- type DB
- type Event
- type EventType
- type FakeHostnameService
- type FakePublisher
- type GetChunkOptions
- type Getter
- type HTTPError
- type Handlers
- type HostnameService
- type JSONAPIClient
- type ListOptions
- type MissingParameterError
- type Pagination
- type PhaseType
- type PubSubService
- type Publisher
- type PutChunkOptions
- type PutChunkService
- type Renderer
- type RunStatus
- type Signer
- type SiteAuthorizer
- type Subject
- type Subscriber
- type Superuser
- func (*Superuser) CanAccessOrganization(rbac.Action, string) bool
- func (*Superuser) CanAccessSite(action rbac.Action) bool
- func (*Superuser) CanAccessWorkspace(rbac.Action, WorkspacePolicy) bool
- func (s *Superuser) ID() string
- func (s *Superuser) IsOwner(string) bool
- func (s *Superuser) IsSiteAdmin() bool
- func (s *Superuser) Organizations() []string
- func (s *Superuser) String() string
- type Verifier
- type WorkspacePermission
- type WorkspacePolicy
Constants ¶
const ( STX = 0x02 // marks the beginning of logs for a phase ETX = 0x03 // marks the end of logs for a phase )
const ( // ChunkStartMarker is the special byte that prefixes the first chunk ChunkStartMarker = byte(2) // ChunkEndMarker is the special byte that suffixes the last chunk ChunkEndMarker = byte(3) )
const ( DefaultPageNumber = 1 DefaultPageSize = 10 MaxPageSize = 100 )
const ( PendingPhase PhaseType = "pending" PlanPhase PhaseType = "plan" ApplyPhase PhaseType = "apply" FinalPhase PhaseType = "final" UnknownPhase PhaseType = "unknown" // List all available run statuses supported in OTF. RunApplied RunStatus = "applied" RunApplyQueued RunStatus = "apply_queued" RunApplying RunStatus = "applying" RunCanceled RunStatus = "canceled" RunForceCanceled RunStatus = "force_canceled" RunConfirmed RunStatus = "confirmed" RunDiscarded RunStatus = "discarded" RunErrored RunStatus = "errored" RunPending RunStatus = "pending" RunPlanQueued RunStatus = "plan_queued" RunPlanned RunStatus = "planned" RunPlannedAndFinished RunStatus = "planned_and_finished" RunPlanning RunStatus = "planning" )
const DefaultSSLCertsDir = "/etc/ssl/certs/ca-certificates.crt"
Variables ¶
var ( // ErrAccessNotPermitted is returned when an authorization check fails. ErrAccessNotPermitted = errors.New("access to the resource is not permitted") ErrUnauthorized = errors.New("unauthorized") // ErrResourceNotFound is returned when a receiving a 404. ErrResourceNotFound = errors.New("resource not found") // ErrResourceAlreadyExists is returned when attempting to create a resource // that already exists. ErrResourceAlreadyExists = errors.New("resource already exists") // ErrRequiredName is returned when a name option is not present. ErrRequiredName = errors.New("name is required") // ErrInvalidName is returned when the name option has invalid value. ErrInvalidName = errors.New("invalid value for name") // ErrForeignKeyViolation is returned when attempting to delete or // update a resource that is referenced by another resource and the // delete/update would orphan the reference. ErrForeignKeyViolation = errors.New("foreign key constraint violation") // ErrWarning is a non-fatal error ErrWarning = errors.New("warning") // ErrUploadTooLarge is returned when a user attempts to upload data that // is too large. ErrUploadTooLarge = errors.New("upload is too large") )
Generic errors
var ( // ErrInvalidTerraformVersion is returned when a terraform version string is // not a semantic version string (major.minor.patch). ErrInvalidTerraformVersion = errors.New("invalid terraform version") // ErrInvalidWorkspaceID is returned when the workspace ID is invalid. ErrInvalidWorkspaceID = errors.New("invalid value for workspace ID") // ErrInvalidWorkspaceValue is returned when workspace value is invalid. ErrInvalidWorkspaceValue = errors.New("invalid value for workspace") // ErrInvalidOrg is returned when the organization option has an invalid value. ErrInvalidOrg = errors.New("invalid value for organization") // ErrRequiredOrg is returned when the organization option is not present ErrRequiredOrg = errors.New("organization is required") ErrStatusTimestampNotFound = errors.New("corresponding status timestamp not found") ErrInvalidRepo = errors.New("repository path is invalid") )
Resource Errors
var ( ErrWorkspaceAlreadyLocked = errors.New("workspace already locked") ErrWorkspaceLockedByDifferentUser = errors.New("workspace locked by different user") ErrWorkspaceAlreadyUnlocked = errors.New("workspace already unlocked") ErrWorkspaceUnlockDenied = errors.New("unauthorized to unlock workspace") ErrWorkspaceInvalidLock = errors.New("invalid workspace lock") ErrUnsupportedTerraformVersion = errors.New("unsupported terraform version") )
Workspace errors
var ( ErrRunDiscardNotAllowed = errors.New("run was not paused for confirmation or priority; discard not allowed") ErrRunCancelNotAllowed = errors.New("run was not planning or applying; cancel not allowed") ErrRunForceCancelNotAllowed = errors.New("run was not planning or applying, has not been canceled non-forcefully, or the cool-off period has not yet passed") )
Run errors
var ( // A regular expression used to validate common string ID patterns. ReStringID = regexp.MustCompile(`^[a-zA-Z0-9\-\._]+$`) // A regular expression used to validate semantic versions (major.minor.patch). ReSemanticVersion = regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+$`) )
var ( ActiveRun = []RunStatus{ RunApplyQueued, RunApplying, RunConfirmed, RunPlanQueued, RunPlanned, RunPlanning, } IncompleteRun = append(ActiveRun, RunPending) CompletedRun = []RunStatus{ RunApplied, RunErrored, RunDiscarded, RunCanceled, RunForceCanceled, } )
var ( // Build-time parameters set -ldflags Version = "unknown" Commit = "unknown" Built = "unknown" )
var DefaultCacheTTL = 10 * time.Minute
DefaultCacheTTL is the default TTL for cached objects
Functions ¶
func AddSubjectToContext ¶ added in v0.0.12
AddSubjectToContext adds a subject to a context
func Contains ¶ added in v0.0.21
func Contains[E comparable](s []E, v E) bool
Contains reports whether v is present in s.
func ConvertID ¶ added in v0.0.12
ConvertID converts an ID for use with a different resource, e.g. convert run-123 to plan-123.
func CredentialEnv ¶ added in v0.0.33
CredentialEnv returns a host-specific environment variable credential for terraform.
func CredentialEnvKey ¶ added in v0.0.33
CredentialEnvKey returns the environment variable key for an API token specific to the given hostname.
func CurrentTimestamp ¶ added in v0.0.12
CurrentTimestamp is *the* way to get a current timestamps in otf and time.Now() should be avoided.
We want timestamps to be rounded to nearest millisecond so that they can be persisted/serialised and not lose precision thereby making comparisons and testing easier.
We also want timestamps to be in the UTC time zone. Again it makes testing easier because libs such as testify's assert use DeepEqual rather than time.Equal to compare times (and structs containing times). That means the internal representation is compared, including the time zone which may differ even though two times refer to the same instant.
In any case, the time zone of the server is often not of importance, whereas that of the user often is, and conversion to their time zone is necessary regardless.
func GenerateAuthToken ¶ added in v0.0.12
GenerateAuthToken generates an authentication token for a type of account e.g. agent, user
func GenerateRandomString ¶
GenerateRandomString generates a random string composed of alphanumeric characters of length size.
func GenerateToken ¶ added in v0.0.12
func GetID ¶ added in v0.0.32
GetID retrieves the ID field of a struct contained in s. If s is not a struct, or there is no ID field, then false is returned.
func GetMapKeys ¶ added in v0.0.8
func Index ¶ added in v0.0.21
func Index[E comparable](s []E, v E) int
Index returns the index of the first occurrence of v in s, or -1 if not present.
func NewAllowAllAuthorizer ¶ added in v0.0.32
func NewAllowAllAuthorizer() *allowAllAuthorizer
func NewHostnameService ¶ added in v0.0.32
func NewHostnameService(hostname string) *hostnameService
func NewID ¶ added in v0.0.8
NewID constructs resource IDs, which are composed of the resource type and a random 16 character string, separated by a hyphen.
func NormalizeAddress ¶ added in v0.0.32
NormalizeAddress takes a host:port and converts it into a host:port appropriate for setting as the addressable hostname of otfd, e.g. converting 0.0.0.0 to 127.0.0.1.
func ParseBranchRef ¶ added in v0.0.19
ParseBranchRef parses a git ref expecting it to be a reference to a branch. If it is not then false is returned, otherwise the branch name along with true is returned.
func PrefixSlice ¶ added in v0.0.8
PrefixSlice prefixes each string in a slice with another string.
func RemoveBackendBlock ¶ added in v0.0.32
RemoveBackendBlock is an HCL operation that removes terraform remote backend / cloud configuration
func RewriteHCL ¶ added in v0.0.32
RewriteHCL performs HCL surgery on a terraform module.
func SSLCertsDir ¶ added in v0.0.21
func SSLCertsDir() string
SSLCertsDir returns the directory containing CA certificates.
func ValidSemanticVersion ¶ added in v0.0.32
ValidSemanticVersion checks if v is a valid semantic version (major.minor.patch).
func ValidStringID ¶ added in v0.0.8
ValidStringID checks if the given string pointer is non-nil and contains a typical string identifier.
func VerifySignedURL ¶ added in v0.0.32
func VerifySignedURL(v Verifier) mux.MiddlewareFunc
VerifySignedURL is middleware that verifies signed URLs
Types ¶
type Authorizer ¶ added in v0.0.27
type Authorizer interface {
CanAccess(ctx context.Context, action rbac.Action, id string) (Subject, error)
}
Authorizer is capable of granting or denying access to resources based on the subject contained within the context.
type Broker ¶ added in v0.0.33
type Broker interface { PubSubService Register(t reflect.Type, getter Getter) }
type Chunk ¶ added in v0.0.12
type Chunk struct { ID string // Uniquely identifies the chunk. RunID string // ID of run that generated the chunk Phase PhaseType // Phase that generated the chunk Offset int // Position within logs. Data []byte // The log data }
Chunk is a section of logs for a phase.
func (Chunk) Cut ¶ added in v0.0.12
func (c Chunk) Cut(opts GetChunkOptions) Chunk
Cut returns a new, smaller chunk.
func (Chunk) NextOffset ¶ added in v0.0.12
NextOffset returns the offset for the next chunk
type DB ¶ added in v0.0.12
type DB interface { // Tx provides a callback in which queries are run within a transaction. Tx(ctx context.Context, tx func(DB) error) error // Acquire dedicated connection from connection pool. Acquire(ctx context.Context) (*pgxpool.Conn, error) // Execute arbitrary SQL Exec(ctx context.Context, sql string, arguments ...interface{}) (pgconn.CommandTag, error) // Send batches of SQL queries over the wire. SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults // Wait for a session-level advisory lock to become available. WaitAndLock(ctx context.Context, id int64, fn func() error) error pggen.Querier // queries generated from SQL Close() // Close all connections in pool // additional queries that wrap the generated queries GetLogs(ctx context.Context, runID string, phase PhaseType) ([]byte, error) }
DB is the otf database. Services may wrap this and implement higher-level queries.
type Event ¶
type Event struct { Type EventType Payload interface{} Local bool // for local node only and not to be published to rest of cluster }
Event represents an event in the lifecycle of an otf resource
type EventType ¶
type EventType string
EventType identifies the type of event
const ( EventOrganizationCreated EventType = "organization_created" EventOrganizationDeleted EventType = "organization_deleted" EventWorkspaceCreated EventType = "workspace_created" EventWorkspaceRenamed EventType = "workspace_renamed" EventWorkspaceDeleted EventType = "workspace_deleted" EventRunCreated EventType = "run_created" EventRunStatusUpdate EventType = "run_status_update" EventRunDeleted EventType = "run_deleted" EventRunCancel EventType = "run_cancel" EventRunForceCancel EventType = "run_force_cancel" EventError EventType = "error" EventInfo EventType = "info" EventLogChunk EventType = "log_update" EventLogFinished EventType = "log_finished" EventVCS EventType = "vcs_event" )
type FakeHostnameService ¶ added in v0.0.32
type FakeHostnameService struct { Host string HostnameService }
func (FakeHostnameService) Hostname ¶ added in v0.0.32
func (s FakeHostnameService) Hostname() string
type FakePublisher ¶ added in v0.0.32
type FakePublisher struct{}
func (*FakePublisher) Publish ¶ added in v0.0.32
func (f *FakePublisher) Publish(Event)
type GetChunkOptions ¶
type Handlers ¶ added in v0.0.32
type Handlers interface { // AddHandlers adds http handlers to the router. AddHandlers(*mux.Router) }
Handlers is an http application with handlers
type HostnameService ¶ added in v0.0.19
HostnameService provides the OTF user-facing hostname.
type JSONAPIClient ¶ added in v0.0.27
type JSONAPIClient interface { // NewRequest constructs a new json-api request NewRequest(method, path string, params any) (*retryablehttp.Request, error) // Do sends a json-api request and populates v with a json-api response. Do(ctx context.Context, req *retryablehttp.Request, v any) error }
JSONAPIClient is a client capable of interacting with a json-api API
type ListOptions ¶ added in v0.0.8
type ListOptions struct { // The page number to request. The results vary based on the PageSize. PageNumber int `schema:"page[number],omitempty"` // The number of elements returned in a single page. PageSize int `schema:"page[size],omitempty"` }
ListOptions is used to specify pagination options when making API requests. Pagination allows breaking up large result sets into chunks, or "pages".
func (ListOptions) GetLimit ¶ added in v0.0.8
func (o ListOptions) GetLimit() int
GetLimit calculates the limit for use in SQL queries.
func (ListOptions) GetOffset ¶ added in v0.0.8
func (o ListOptions) GetOffset() int
GetOffset calculates the offset for use in SQL queries.
func (ListOptions) SanitizedPageNumber ¶ added in v0.0.16
func (o ListOptions) SanitizedPageNumber() int
SanitizedPageNumber is the page number following sanitization.
func (ListOptions) SanitizedPageSize ¶ added in v0.0.16
func (o ListOptions) SanitizedPageSize() int
SanitizedPageSize is the page size following sanitization.
type MissingParameterError ¶ added in v0.0.33
type MissingParameterError struct {
Parameter string
}
func (*MissingParameterError) Error ¶ added in v0.0.33
func (e *MissingParameterError) Error() string
type Pagination ¶ added in v0.0.8
type Pagination struct { // list options from API request Opts ListOptions // total unpaginated count Count int }
Pagination is used to return the pagination details of an API request.
func NewPagination ¶
func NewPagination(opts ListOptions, count int) *Pagination
NewPagination constructs a Pagination obj.
func (*Pagination) CurrentPage ¶ added in v0.0.8
func (p *Pagination) CurrentPage() int
func (*Pagination) NextPage ¶ added in v0.0.8
func (p *Pagination) NextPage() *int
NextPage returns the next page number or nil if there isn't one.
func (*Pagination) NextPageQuery ¶ added in v0.0.16
func (p *Pagination) NextPageQuery() string
NextPageQuery produces query params for the next page
func (*Pagination) PrevPage ¶ added in v0.0.12
func (p *Pagination) PrevPage() *int
PrevPage returns the previous page number or nil if there isn't one.
func (*Pagination) PrevPageQuery ¶ added in v0.0.16
func (p *Pagination) PrevPageQuery() string
PrevPageQuery produces query params for the previous page
func (*Pagination) TotalCount ¶ added in v0.0.8
func (p *Pagination) TotalCount() int
func (*Pagination) TotalPages ¶ added in v0.0.8
func (p *Pagination) TotalPages() int
type PubSubService ¶ added in v0.0.12
type PubSubService interface { Publisher Subscriber }
PubSubService provides low-level access to pub-sub behaviours. Access is unauthenticated.
type PutChunkOptions ¶
type PutChunkService ¶ added in v0.0.32
type PutChunkService interface {
PutChunk(ctx context.Context, opts PutChunkOptions) error
}
type Renderer ¶ added in v0.0.27
type Renderer interface { // Render template to http response. Template is provided with access // various helpers on the root object (.) and the content can be accessed at // .Content. Render(path string, w http.ResponseWriter, r *http.Request, content any) // RenderTemplate renders template to a writer. No helpers are made // available and the content is available on the root object (.) within the // template. RenderTemplate(path string, w io.Writer, content any) error }
Renderer renders templated responses to http requests.
type SiteAuthorizer ¶ added in v0.0.32
SiteAuthorizer authorizes access to site-wide actions
type Subject ¶ added in v0.0.12
type Subject interface { CanAccessSite(action rbac.Action) bool CanAccessOrganization(action rbac.Action, name string) bool CanAccessWorkspace(action rbac.Action, policy WorkspacePolicy) bool IsOwner(organization string) bool IsSiteAdmin() bool // Organizations returns subject's organization memberships Organizations() []string String() string }
Subject is an entity that carries out actions on resources.
type Subscriber ¶ added in v0.0.32
type Subscriber interface { // Subscribe subscribes the caller to OTF events. Name uniquely identifies the // caller. Subscribe(ctx context.Context, name string) (<-chan Event, error) }
Subscriber is capable of creating a subscription to events.
type Superuser ¶ added in v0.0.19
type Superuser struct {
Username string
}
Superuser is a subject with unlimited privileges.
func (*Superuser) CanAccessOrganization ¶ added in v0.0.19
func (*Superuser) CanAccessSite ¶ added in v0.0.19
func (*Superuser) CanAccessWorkspace ¶ added in v0.0.19
func (*Superuser) CanAccessWorkspace(rbac.Action, WorkspacePolicy) bool
func (*Superuser) IsSiteAdmin ¶ added in v0.0.32
func (*Superuser) Organizations ¶ added in v0.0.33
type WorkspacePermission ¶ added in v0.0.12
WorkspacePermission binds a role to a team.
type WorkspacePolicy ¶ added in v0.0.12
type WorkspacePolicy struct { Organization string WorkspaceID string Permissions []WorkspacePermission }
WorkspacePolicy binds workspace permissions to a workspace
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
Package agent provides a daemon capable of running remote operations on behalf of a user.
|
Package agent provides a daemon capable of running remote operations on behalf of a user. |
Package auth is responsible for authentication
|
Package auth is responsible for authentication |
Package authenticator is responsible for handling the authentication of users with third party identity providers.
|
Package authenticator is responsible for handling the authentication of users with third party identity providers. |
Package cli provides the CLI client, i.e.
|
Package cli provides the CLI client, i.e. |
Package client provides an abstraction for interacting with otf services either remotely or locally.
|
Package client provides an abstraction for interacting with otf services either remotely or locally. |
Package cloud provides types for use with cloud providers.
|
Package cloud provides types for use with cloud providers. |
Package cmd provides CLI functionality.
|
Package cmd provides CLI functionality. |
Package configversion handles terraform configurations.
|
Package configversion handles terraform configurations. |
Package daemon configures and starts the otfd daemon and its subsystems.
|
Package daemon configures and starts the otfd daemon and its subsystems. |
Package github provides github related code
|
Package github provides github related code |
Package gitlab provides gitlab related code
|
Package gitlab provides gitlab related code |
Package http provides an HTTP interface allowing HTTP clients to interact with OTF.
|
Package http provides an HTTP interface allowing HTTP clients to interact with OTF. |
decode
Package decode contains decoders for various HTTP artefacts
|
Package decode contains decoders for various HTTP artefacts |
html
Package html contains code relating specifically to the web UI.
|
Package html contains code relating specifically to the web UI. |
html/paths
Package paths provides rails-style path helpers for use with the web app.
|
Package paths provides rails-style path helpers for use with the web app. |
jsonapi
Package jsonapi handles marshaling/unmarshaling into/from json-api
|
Package jsonapi handles marshaling/unmarshaling into/from json-api |
Package inmem implements a layer of services in memory using purely Go constructs.
|
Package inmem implements a layer of services in memory using purely Go constructs. |
Package integration provides inter-service integration tests.
|
Package integration provides inter-service integration tests. |
Package json provides helpers for the JSON encoding.
|
Package json provides helpers for the JSON encoding. |
Package logs handles log output from a run
|
Package logs handles log output from a run |
Package module is reponsible for registry modules
|
Package module is reponsible for registry modules |
Package organization is responsible for OTF organizations
|
Package organization is responsible for OTF organizations |
Package orgcreator is responsible for the creation of organizations.
|
Package orgcreator is responsible for the creation of organizations. |
Package pubsub implements cluster-wide publishing and subscribing of events
|
Package pubsub implements cluster-wide publishing and subscribing of events |
Package rbac is concerned with authorization
|
Package rbac is concerned with authorization |
Package repo handles configuration of VCS repositories.
|
Package repo handles configuration of VCS repositories. |
Package run is responsible for OTF runs, the primary mechanism for executing terraform
|
Package run is responsible for OTF runs, the primary mechanism for executing terraform |
Package scheduler is responsible for the scheduling of runs
|
Package scheduler is responsible for the scheduling of runs |
Package semver wraps golang.org/x/mod/semver, relaxing the requirement for semantic versions to be prefixed with "v".
|
Package semver wraps golang.org/x/mod/semver, relaxing the requirement for semantic versions to be prefixed with "v". |
Package sql implements persistent storage using the postgres database.
|
Package sql implements persistent storage using the postgres database. |
Package state manages terraform state.
|
Package state manages terraform state. |
Package testutils provides test helpers.
|
Package testutils provides test helpers. |
Package tokens manages token authentication
|
Package tokens manages token authentication |
Package variable manages terraform workspace variables
|
Package variable manages terraform workspace variables |
Package vcsprovider is responsible for VCS providers
|
Package vcsprovider is responsible for VCS providers |
Package workspace provides access to terraform workspaces
|
Package workspace provides access to terraform workspaces |