internal

package
v0.3.6 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2024 License: MPL-2.0 Imports: 27 Imported by: 0

Documentation

Overview

Package internal is code only for consumption from within the otf project.

Index

Constants

View Source
const DefaultSSLCertsDir = "/etc/ssl/certs/ca-certificates.crt"

Variables

View Source
var (
	// ErrAccessNotPermitted is returned when an authorization check fails.
	ErrAccessNotPermitted = errors.New("access to the resource is not permitted")

	// ErrUnauthorized is returned when a receiving a 401.
	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")

	// ErrEmptyValue is returned when a value is set to an empty string
	ErrEmptyValue = errors.New("value cannot be empty")

	// ErrTimeout is returned when a request exceeds a timeout.
	ErrTimeout = errors.New("request timed out")

	// ErrConflict is returned when a requests attempts to either create a
	// resource with an identifier that already exists, or if an invalid state
	// transition is attempted
	ErrConflict = errors.New("resource conflict detected")
)

Generic errors

View Source
var (
	// ErrInvalidTerraformVersion is returned when a terraform version string is
	// not a semantic version string (major.minor.patch).
	ErrInvalidTerraformVersion = errors.New("invalid terraform version")

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

View Source
var (
	// Build-time parameters set -ldflags
	Version = "unknown"
	Commit  = "unknown"
	Built   = "unknown"
)
View Source
var DefaultCacheTTL = 10 * time.Minute

DefaultCacheTTL is the default TTL for cached objects

Functions

func Bool

func Bool(b bool) *bool

func CredentialEnv

func CredentialEnv(hostname string, token []byte) string

CredentialEnv returns a host-specific environment variable credential for terraform.

func CredentialEnvKey

func CredentialEnvKey(hostname string) string

CredentialEnvKey returns the environment variable key for an API token specific to the given hostname.

func CurrentTimestamp

func CurrentTimestamp(now *time.Time) time.Time

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.

And the optional now arg gives tests the opportunity to swap out time.Now() with a deterministic time. If it's nil then time.Now() is used.

func Decrypt

func Decrypt(encrypted string, secret []byte) ([]byte, error)

Decrypt encrypted string using secret key. The encrypted string must be base64-url-encoded.

func Diff added in v0.3.6

func Diff[T comparable](a, b []T) []T

Diff returns the elements in `a` that aren't in `b`.

func Encrypt

func Encrypt(plaintext, secret []byte) (string, error)

Encrypt plaintext using secret key. The returned string is base64-url-encoded.

func ErrorIs added in v0.3.3

func ErrorIs(err error, target error, moreTargets ...error) bool

ErrorIs is a modification to the upstream errors.Is, allowing multiple targets to be checked.

func Exists

func Exists(path string) bool

Exists checks whether a file or directory at the given path exists

func FromStringCSV added in v0.1.8

func FromStringCSV[T ~string](csv string) (to []T)

FromStringCSV splits a comma-separated string into a slice of type T

func FromStringSlice added in v0.1.8

func FromStringSlice[T ~string](from []string) (to []T)

func GenerateRandomString

func GenerateRandomString(size int) string

GenerateRandomString generates a random string composed of alphanumeric characters of length size.

func GenerateRandomStringFromAlphabet added in v0.3.0

func GenerateRandomStringFromAlphabet(size int, alphabet string) string

GenerateRandomStringFromAlphabet generates a random string of a given size using characters from the given alphabet.

func GenerateToken

func GenerateToken() (string, error)

func GetOutboundIP added in v0.2.0

func GetOutboundIP() (netip.Addr, error)

GetOutboundIP gets the preferred outbound IP address of this machine.

Credit to: https://stackoverflow.com/a/37382208

func Int

func Int(i int) *int

func Int64

func Int64(i int64) *int64

func NewSigner

func NewSigner(secret []byte) *surl.Signer

NewSigner constructs a signer for signing and verifying URLs

func NewStringFromPtr added in v0.1.9

func NewStringFromPtr(s *string) string

func NormalizeAddress

func NormalizeAddress(addr *net.TCPAddr) string

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 Pack

func Pack(src string) ([]byte, error)

Pack a directory into tarball (.tar.gz) and return its contents

func ParseAddr added in v0.3.0

func ParseAddr(endpoint string) (netip.Addr, error)

ParseAddr parses the address from an endpoint string of the form "<ip>:<port>"

func ParseBranchRef

func ParseBranchRef(ref string) (string, bool)

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 ParseRef

func ParseRef(ref string) (string, bool)

ParseRef parses a git ref of the format refs/[tags|heads]/[name],

func ParseTagRef added in v0.2.3

func ParseTagRef(ref string) (string, error)

ParseTagRef parses the tag from a git reference with the format refs/tags/<tag>

func RemoveBackendBlock

func RemoveBackendBlock(f *hclwrite.File) bool

RemoveBackendBlock is an HCL operation that removes terraform remote backend / cloud configuration

func RewriteHCL

func RewriteHCL(modulePath string, operations ...hclOperation) error

RewriteHCL performs HCL surgery on a terraform module.

func SSLCertsDir

func SSLCertsDir() string

SSLCertsDir returns the directory containing CA certificates.

func SafeAppend added in v0.0.51

func SafeAppend(a []string, b ...string) []string

SafeAppend appends strings to a slice whilst ensuring the slice is not modified.

see: https://yourbasic.org/golang/gotcha-append/

func SplitCSV added in v0.1.8

func SplitCSV(csv string) []string

SplitCSV splits a string with a comma delimited (a "comma-separated-value"). It differs from strings.Split in that if no comma is found an empty slice is returned whereas strings.Split would return a single-element slice containing the original string.

func String

func String(str string) *string

func StripAnsi added in v0.1.8

func StripAnsi(str string) string

func Time

func Time(t time.Time) *time.Time

func ToStringSlice added in v0.1.8

func ToStringSlice[T ~string](from []T) (to []string)

func UInt

func UInt(i uint) *uint

func UUID

func UUID(u uuid.UUID) *uuid.UUID

func Unpack

func Unpack(r io.Reader, dst string) error

Unpack a .tar.gz byte stream to a directory

func VerifySignedURL

func VerifySignedURL(v Verifier) mux.MiddlewareFunc

VerifySignedURL is middleware that verifies signed URLs

Types

type Cache

type Cache interface {
	Get(string) ([]byte, error)
	Set(string, []byte) error
}

Cache is a key-value cache.

type ErrMissingParameter added in v0.3.3

type ErrMissingParameter struct {
	Parameter string
}

ErrMissingParameter occurs when the user has failed to provide a required parameter

func (*ErrMissingParameter) Error added in v0.3.3

func (e *ErrMissingParameter) Error() string

type ForeignKeyError

type ForeignKeyError struct {
	*pgconn.PgError
}

ForeignKeyError occurs when there is a foreign key violation.

func (*ForeignKeyError) Error

func (e *ForeignKeyError) Error() string

type Handlers

type Handlers interface {
	// AddHandlers adds http handlers to the router.
	AddHandlers(*mux.Router)
}

Handlers is an http application with handlers

type HostnameService

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

func NewHostnameService

func NewHostnameService(hostname string) *HostnameService

func (*HostnameService) Hostname

func (s *HostnameService) Hostname() string

func (*HostnameService) SetHostname

func (s *HostnameService) SetHostname(hostname string)

func (*HostnameService) SetWebhookHostname added in v0.2.4

func (s *HostnameService) SetWebhookHostname(webhookHostname string)

func (*HostnameService) URL added in v0.1.14

func (s *HostnameService) URL(path string) string

func (*HostnameService) WebhookHostname added in v0.2.4

func (s *HostnameService) WebhookHostname() string

func (*HostnameService) WebhookURL added in v0.2.4

func (s *HostnameService) WebhookURL(path string) string

type PhaseType

type PhaseType string
const (
	PendingPhase PhaseType = "pending"
	PlanPhase    PhaseType = "plan"
	ApplyPhase   PhaseType = "apply"
	FinalPhase   PhaseType = "final"
	UnknownPhase PhaseType = "unknown"
)

type SafeMap added in v0.1.14

type SafeMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

SafeMap is a concurrency-safe map

func NewSafeMap added in v0.1.14

func NewSafeMap[K comparable, V any]() *SafeMap[K, V]

NewSafeMap constructs an empty SafeMap, with the given key and value types.

func (*SafeMap[K, V]) Get added in v0.1.14

func (r *SafeMap[K, V]) Get(key K) (V, bool)

func (*SafeMap[K, V]) Set added in v0.1.14

func (r *SafeMap[K, V]) Set(key K, value V)

type Signer

type Signer interface {
	Sign(string, time.Duration) (string, error)
}

Signer cryptographically signs URLs with a limited lifespan.

type Verifier

type Verifier interface {
	Verify(string) error
}

Verifier verifies signed URLs

Directories

Path Synopsis
Package api provides commmon functionality for the OTF API
Package api provides commmon functionality for the OTF API
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 authz handles all things authorization, policing who (subjects) can do what (actions) on what (resources).
Package authz handles all things authorization, policing who (subjects) can do what (actions) on what (resources).
Package cli provides the CLI client, i.e.
Package cli provides the CLI client, i.e.
Package configversion handles terraform configurations.
Package configversion handles terraform configurations.
Package connections manages connections between VCS repositories and OTF resources, e.g.
Package connections manages connections between VCS repositories and OTF resources, e.g.
Package daemon configures and starts the otfd daemon and its subsystems.
Package daemon configures and starts the otfd daemon and its subsystems.
Package disco implements terraform's "remote service discovery protocol":
Package disco implements terraform's "remote service discovery protocol":
Package ghapphandler provides a handler for the github app webhook endpoint.
Package ghapphandler provides a handler for the github app webhook endpoint.
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.
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 loginserver implements a "terraform login protocol" server:
Package loginserver implements a "terraform login protocol" server:
Package logr provides a logger that implements the logr interface
Package logr provides a logger that implements the logr interface
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 notifications sends notifications for run state transitions and workspace events.
Package notifications sends notifications for run state transitions and workspace events.
Package organization is responsible for OTF organizations
Package organization is responsible for OTF organizations
Package pubsub provides cluster-wide publishing and subscribing of events
Package pubsub provides cluster-wide publishing and subscribing of events
Package releases manages terraform releases.
Package releases manages terraform releases.
Package repohooks manages webhooks for VCS events
Package repohooks manages webhooks for VCS events
Package resource contains code common to all resources (orgs, workspaces, runs, etc)
Package resource contains code common to all resources (orgs, workspaces, runs, etc)
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 runner contains the runner, the component responsible for carrying out runs by executing terraform processes, either as part of the server or remotely via agents.
Package runner contains the runner, the component responsible for carrying out runs by executing terraform processes, either as part of the server or remotely via agents.
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".
sql
Package sql implements persistent storage using the postgres database.
Package sql implements persistent storage using the postgres database.
sqlc
Package sqlc is mostly auto-generated by the sqlc tool
Package sqlc is mostly auto-generated by the sqlc tool
Package state manages terraform state.
Package state manages terraform state.
Package team manages teams, which are groups of users with shared privileges.
Package team manages teams, which are groups of users with shared privileges.
Package testbrowser provides browsers for e2e tests
Package testbrowser provides browsers for e2e tests
Package testcompose provides interaction with a docker compose stack of services for testing purposes.
Package testcompose provides interaction with a docker compose stack of services for testing purposes.
Package testutils provides test helpers.
Package testutils provides test helpers.
Package tfeapi provides common functionality useful for implementation of the Hashicorp TFE/TFC API, which uses the json:api encoding
Package tfeapi provides common functionality useful for implementation of the Hashicorp TFE/TFC API, which uses the json:api encoding
types
Package types provides structs suitable for marshaling to/from json:api
Package types provides structs suitable for marshaling to/from json:api
Package tokens manages token authentication
Package tokens manages token authentication
Package user manages user accounts and their team membership.
Package user manages user accounts and their team membership.
Package variable manages terraform workspace variables
Package variable manages terraform workspace variables
Package vcs handles version control system stuff.
Package vcs handles version control system stuff.
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

Jump to

Keyboard shortcuts

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