server

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: May 23, 2019 License: Apache-2.0 Imports: 37 Imported by: 0

Documentation

Overview

Package server handles the web server and executing commands that come in via webhooks.

Index

Constants

View Source
const (
	// LockViewRouteName is the named route in mux.Router for the lock view.
	// The route can be retrieved by this name, ex:
	//   mux.Router.Get(LockViewRouteName)
	LockViewRouteName = "lock-detail"
	// LockViewRouteIDQueryParam is the query parameter needed to construct the lock view
	// route. ex:
	//   mux.Router.Get(LockViewRouteName).URL(LockViewRouteIDQueryParam, "my id")
	LockViewRouteIDQueryParam = "id"
)

Variables

This section is empty.

Functions

func ParseAtlantisURL added in v0.4.12

func ParseAtlantisURL(u string) (*url.URL, error)

ParseAtlantisURL parses the user-passed atlantis URL to ensure it is valid and we can use it in our templates. It removes any trailing slashes from the path so we can concatenate it with other paths without checking.

Types

type Config added in v0.1.3

type Config struct {
	AllowForkPRsFlag     string
	AtlantisURLFlag      string
	AtlantisVersion      string
	DefaultTFVersionFlag string
	RepoConfigJSONFlag   string
}

Config holds config for server that isn't passed in by the user.

type DefaultGithubRequestValidator added in v0.2.0

type DefaultGithubRequestValidator struct{}

DefaultGithubRequestValidator handles checking if GitHub requests are signed properly by the secret.

func (*DefaultGithubRequestValidator) Validate added in v0.2.0

func (d *DefaultGithubRequestValidator) Validate(r *http.Request, secret []byte) ([]byte, error)

Validate returns the JSON payload of the request. If secret is not empty, it checks that the request was signed by secret and returns an error if it was not. If secret is empty, it does not check if the request was signed.

type DefaultGitlabRequestParserValidator added in v0.4.0

type DefaultGitlabRequestParserValidator struct{}

DefaultGitlabRequestParserValidator parses and validates GitLab requests.

func (*DefaultGitlabRequestParserValidator) ParseAndValidate added in v0.4.0

func (d *DefaultGitlabRequestParserValidator) ParseAndValidate(r *http.Request, secret []byte) (interface{}, error)

ParseAndValidate returns the JSON payload of the request. See GitlabRequestParserValidator.ParseAndValidate().

type EventsController added in v0.1.3

type EventsController struct {
	CommandRunner events.CommandRunner
	PullCleaner   events.PullCleaner
	Logger        *logging.SimpleLogger
	Parser        events.EventParsing
	CommentParser events.CommentParsing
	// GithubWebhookSecret is the secret added to this webhook via the GitHub
	// UI that identifies this call as coming from GitHub. If empty, no
	// request validation is done.
	GithubWebhookSecret          []byte
	GithubRequestValidator       GithubRequestValidator
	GitlabRequestParserValidator GitlabRequestParserValidator
	// GitlabWebhookSecret is the secret added to this webhook via the GitLab
	// UI that identifies this call as coming from GitLab. If empty, no
	// request validation is done.
	GitlabWebhookSecret  []byte
	RepoWhitelistChecker *events.RepoWhitelistChecker
	// SilenceWhitelistErrors controls whether we write an error comment on
	// pull requests from non-whitelisted repos.
	SilenceWhitelistErrors bool
	// SupportedVCSHosts is which VCS hosts Atlantis was configured upon
	// startup to support.
	SupportedVCSHosts []models.VCSHostType
	VCSClient         vcs.Client
	TestingMode       bool
	// BitbucketWebhookSecret is the secret added to this webhook via the Bitbucket
	// UI that identifies this call as coming from Bitbucket. If empty, no
	// request validation is done.
	BitbucketWebhookSecret []byte
}

EventsController handles all webhook requests which signify 'events' in the VCS host, ex. GitHub.

func (*EventsController) HandleBitbucketCloudCommentEvent added in v0.4.4

func (e *EventsController) HandleBitbucketCloudCommentEvent(w http.ResponseWriter, body []byte, reqID string)

HandleBitbucketCloudCommentEvent handles comment events from Bitbucket.

func (*EventsController) HandleBitbucketServerCommentEvent added in v0.4.4

func (e *EventsController) HandleBitbucketServerCommentEvent(w http.ResponseWriter, body []byte, reqID string)

HandleBitbucketServerCommentEvent handles comment events from Bitbucket.

func (*EventsController) HandleGithubCommentEvent added in v0.2.0

func (e *EventsController) HandleGithubCommentEvent(w http.ResponseWriter, event *github.IssueCommentEvent, githubReqID string)

HandleGithubCommentEvent handles comment events from GitHub where Atlantis commands can come from. It's exported to make testing easier.

func (*EventsController) HandleGithubPullRequestEvent added in v0.2.0

func (e *EventsController) HandleGithubPullRequestEvent(w http.ResponseWriter, pullEvent *github.PullRequestEvent, githubReqID string)

HandleGithubPullRequestEvent will delete any locks associated with the pull request if the event is a pull request closed event. It's exported to make testing easier.

func (*EventsController) HandleGitlabCommentEvent added in v0.2.0

func (e *EventsController) HandleGitlabCommentEvent(w http.ResponseWriter, event gitlab.MergeCommentEvent)

HandleGitlabCommentEvent handles comment events from GitLab where Atlantis commands can come from. It's exported to make testing easier.

func (*EventsController) HandleGitlabMergeRequestEvent added in v0.2.0

func (e *EventsController) HandleGitlabMergeRequestEvent(w http.ResponseWriter, event gitlab.MergeEvent)

HandleGitlabMergeRequestEvent will delete any locks associated with the pull request if the event is a merge request closed event. It's exported to make testing easier.

func (*EventsController) Post added in v0.1.3

Post handles POST webhook requests.

type GithubRequestValidator added in v0.2.0

type GithubRequestValidator interface {
	// Validate returns the JSON payload of the request.
	// If secret is not empty, it checks that the request was signed
	// by secret and returns an error if it was not.
	// If secret is empty, it does not check if the request was signed.
	Validate(r *http.Request, secret []byte) ([]byte, error)
}

GithubRequestValidator handles checking if GitHub requests are signed properly by the secret.

type GitlabRequestParserValidator added in v0.4.0

type GitlabRequestParserValidator interface {
	// ParseAndValidate validates that the request has a token header matching secret.
	// If the secret does not match it returns an error.
	// If secret is empty it does not check the token header.
	// It then parses the request as a GitLab object depending on the header
	// provided by GitLab identifying the webhook type. If the webhook type
	// is not recognized it will return nil but will not return an error.
	// Usage:
	//	event, err := GitlabRequestParserValidator.ParseAndValidate(r, secret)
	//	if err != nil {
	//		return
	//	}
	//	switch event := event.(type) {
	//	case gitlab.MergeCommentEvent:
	//		// handle
	//	case gitlab.MergeEvent:
	//		// handle
	//	default:
	//		// unsupported event
	//	}
	ParseAndValidate(r *http.Request, secret []byte) (interface{}, error)
}

GitlabRequestParserValidator parses and validates GitLab requests.

type IndexData added in v0.3.3

type IndexData struct {
	Locks           []LockIndexData
	AtlantisVersion string
	// CleanedBasePath is the path Atlantis is accessible at externally. If
	// not using a path-based proxy, this will be an empty string. Never ends
	// in a '/' (hence "cleaned").
	CleanedBasePath string
}

IndexData holds the data for rendering the index page

type LockDetailData added in v0.1.3

type LockDetailData struct {
	LockKeyEncoded  string
	LockKey         string
	RepoOwner       string
	RepoName        string
	PullRequestLink string
	LockedBy        string
	Workspace       string
	Time            time.Time
	AtlantisVersion string
	// CleanedBasePath is the path Atlantis is accessible at externally. If
	// not using a path-based proxy, this will be an empty string. Never ends
	// in a '/' (hence "cleaned").
	CleanedBasePath string
}

LockDetailData holds the fields needed to display the lock detail view.

type LockIndexData added in v0.1.3

type LockIndexData struct {
	LockPath     string
	RepoFullName string
	PullNum      int
	Time         time.Time
}

LockIndexData holds the fields needed to display the index view for locks.

type LocksController added in v0.3.10

type LocksController struct {
	AtlantisVersion    string
	AtlantisURL        *url.URL
	Locker             locking.Locker
	Logger             *logging.SimpleLogger
	VCSClient          vcs.Client
	LockDetailTemplate TemplateWriter
	WorkingDir         events.WorkingDir
	WorkingDirLocker   events.WorkingDirLocker
	DB                 *db.BoltDB
}

LocksController handles all requests relating to Atlantis locks.

func (*LocksController) DeleteLock added in v0.3.10

func (l *LocksController) DeleteLock(w http.ResponseWriter, r *http.Request)

DeleteLock handles deleting the lock at id and commenting back on the pull request that the lock has been deleted.

func (*LocksController) GetLock added in v0.3.10

func (l *LocksController) GetLock(w http.ResponseWriter, r *http.Request)

GetLock is the GET /locks/{id} route. It renders the lock detail view.

type RequestLogger

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

RequestLogger logs requests and their response codes.

func NewRequestLogger

func NewRequestLogger(logger *logging.SimpleLogger) *RequestLogger

NewRequestLogger creates a RequestLogger.

func (*RequestLogger) ServeHTTP

func (l *RequestLogger) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)

ServeHTTP implements the middleware function. It logs a request at INFO level unless it's a request to /static/*.

type Router added in v0.4.0

type Router struct {
	// Underlying is the router that the routes have been constructed on.
	Underlying *mux.Router
	// LockViewRouteName is the named route for the lock view that can be Get'd
	// from the Underlying router.
	LockViewRouteName string
	// LockViewRouteIDQueryParam is the query parameter needed to construct the
	// lock view: underlying.Get(LockViewRouteName).URL(LockViewRouteIDQueryParam, "my id").
	LockViewRouteIDQueryParam string
	// AtlantisURL is the fully qualified URL that Atlantis is
	// accessible from externally.
	AtlantisURL *url.URL
}

Router can be used to retrieve Atlantis URLs. It acts as an intermediary between the underlying router and the rest of Atlantis that might need to construct URLs to different resources.

func (*Router) GenerateLockURL added in v0.4.0

func (r *Router) GenerateLockURL(lockID string) string

GenerateLockURL returns a fully qualified URL to view the lock at lockID.

type Server

type Server struct {
	AtlantisVersion    string
	AtlantisURL        *url.URL
	Router             *mux.Router
	Port               int
	CommandRunner      *events.DefaultCommandRunner
	Logger             *logging.SimpleLogger
	Locker             locking.Locker
	EventsController   *EventsController
	LocksController    *LocksController
	IndexTemplate      TemplateWriter
	LockDetailTemplate TemplateWriter
	SSLCertFile        string
	SSLKeyFile         string
}

Server runs the Atlantis web server.

func NewServer

func NewServer(userConfig UserConfig, config Config) (*Server, error)

NewServer returns a new server. If there are issues starting the server or its dependencies an error will be returned. This is like the main() function for the server CLI command because it injects all the dependencies.

func (*Server) Healthz added in v0.4.1

func (s *Server) Healthz(w http.ResponseWriter, _ *http.Request)

Healthz returns the health check response. It always returns a 200 currently.

func (*Server) Index added in v0.1.3

func (s *Server) Index(w http.ResponseWriter, _ *http.Request)

Index is the / route.

func (*Server) Start

func (s *Server) Start() error

Start creates the routes and starts serving traffic.

type TemplateWriter added in v0.1.3

type TemplateWriter interface {
	// Execute applies a parsed template to the specified data object,
	// writing the output to wr.
	Execute(wr io.Writer, data interface{}) error
}

TemplateWriter is an interface over html/template that's used to enable mocking.

type UserConfig added in v0.3.3

type UserConfig struct {
	AllowForkPRs           bool   `mapstructure:"allow-fork-prs"`
	AllowRepoConfig        bool   `mapstructure:"allow-repo-config"`
	AtlantisURL            string `mapstructure:"atlantis-url"`
	Automerge              bool   `mapstructure:"automerge"`
	BitbucketBaseURL       string `mapstructure:"bitbucket-base-url"`
	BitbucketToken         string `mapstructure:"bitbucket-token"`
	BitbucketUser          string `mapstructure:"bitbucket-user"`
	BitbucketWebhookSecret string `mapstructure:"bitbucket-webhook-secret"`
	CheckoutStrategy       string `mapstructure:"checkout-strategy"`
	DataDir                string `mapstructure:"data-dir"`
	DisableApplyAll        bool   `mapstructure:"disable-apply-all"`
	GithubHostname         string `mapstructure:"gh-hostname"`
	GithubToken            string `mapstructure:"gh-token"`
	GithubUser             string `mapstructure:"gh-user"`
	GithubWebhookSecret    string `mapstructure:"gh-webhook-secret"`
	GitlabHostname         string `mapstructure:"gitlab-hostname"`
	GitlabToken            string `mapstructure:"gitlab-token"`
	GitlabUser             string `mapstructure:"gitlab-user"`
	GitlabWebhookSecret    string `mapstructure:"gitlab-webhook-secret"`
	LogLevel               string `mapstructure:"log-level"`
	Port                   int    `mapstructure:"port"`
	RepoConfig             string `mapstructure:"repo-config"`
	RepoConfigJSON         string `mapstructure:"repo-config-json"`
	RepoWhitelist          string `mapstructure:"repo-whitelist"`
	// RequireApproval is whether to require pull request approval before
	// allowing terraform apply's to be run.
	RequireApproval bool `mapstructure:"require-approval"`
	// RequireMergeable is whether to require pull requests to be mergeable before
	// allowing terraform apply's to run.
	RequireMergeable       bool            `mapstructure:"require-mergeable"`
	SilenceWhitelistErrors bool            `mapstructure:"silence-whitelist-errors"`
	SlackToken             string          `mapstructure:"slack-token"`
	SSLCertFile            string          `mapstructure:"ssl-cert-file"`
	SSLKeyFile             string          `mapstructure:"ssl-key-file"`
	TFEToken               string          `mapstructure:"tfe-token"`
	DefaultTFVersion       string          `mapstructure:"default-tf-version"`
	Webhooks               []WebhookConfig `mapstructure:"webhooks"`
}

UserConfig holds config values passed in by the user. The mapstructure tags correspond to flags in cmd/server.go and are used when the config is parsed from a YAML file.

func (UserConfig) ToLogLevel added in v0.4.13

func (u UserConfig) ToLogLevel() logging.LogLevel

ToLogLevel returns the LogLevel object corresponding to the user-passed log level.

type WebhookConfig added in v0.2.0

type WebhookConfig struct {
	// Event is the type of event we should send this webhook for, ex. apply.
	Event string `mapstructure:"event"`
	// WorkspaceRegex is a regex that is used to match against the workspace
	// that is being modified for this event. If the regex matches, we'll
	// send the webhook, ex. "production.*".
	WorkspaceRegex string `mapstructure:"workspace-regex"`
	// Kind is the type of webhook we should send, ex. slack.
	Kind string `mapstructure:"kind"`
	// Channel is the channel to send this webhook to. It only applies to
	// slack webhooks. Should be without '#'.
	Channel string `mapstructure:"channel"`
}

WebhookConfig is nested within UserConfig. It's used to configure webhooks.

Directories

Path Synopsis
db
Package db handles our database layer.
Package db handles our database layer.
locking/mocks/matchers
Code generated by pegomock.
Code generated by pegomock.
matchers
Code generated by pegomock.
Code generated by pegomock.
mocks/matchers
Code generated by pegomock.
Code generated by pegomock.
runtime
Package runtime holds code for actually running commands vs.
Package runtime holds code for actually running commands vs.
runtime/mocks/matchers
Code generated by pegomock.
Code generated by pegomock.
terraform/mocks/matchers
Code generated by pegomock.
Code generated by pegomock.
vcs
vcs/bitbucketcloud
Package bitbucketcloud holds code for Bitbucket Cloud aka (bitbucket.org).
Package bitbucketcloud holds code for Bitbucket Cloud aka (bitbucket.org).
vcs/common
Package common is used to share common code between all VCS clients without running into circular dependency issues.
Package common is used to share common code between all VCS clients without running into circular dependency issues.
vcs/mocks/matchers
Code generated by pegomock.
Code generated by pegomock.
webhooks/mocks/matchers
Code generated by pegomock.
Code generated by pegomock.
yaml/raw
Package raw contains the golang representations of the YAML elements supported in atlantis.yaml.
Package raw contains the golang representations of the YAML elements supported in atlantis.yaml.
yaml/valid
Package valid contains the structs representing the atlantis.yaml config after it's been parsed and validated.
Package valid contains the structs representing the atlantis.yaml config after it's been parsed and validated.
mocks/matchers
Code generated by pegomock.
Code generated by pegomock.
matchers
Code generated by pegomock.
Code generated by pegomock.

Jump to

Keyboard shortcuts

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