api

package
v0.50.0 Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2021 License: BSD-3-Clause Imports: 112 Imported by: 5

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	Errors              *stats.Int64Measure
	Hits                *stats.Int64Measure
	WebSocketClients    *stats.Int64Measure
	WebSocketEvents     *stats.Int64Measure
	ServerRequestCount  *stats.Int64Measure
	ServerRequestBytes  *stats.Int64Measure
	ServerResponseBytes *stats.Int64Measure
	ServerLatency       *stats.Float64Measure
)
View Source
var DEPRECATED = func(rc *service.HandlerConfig) {
	rc.IsDeprecated = true
}

DEPRECATED marks the handler as deprecated

View Source
var (
	ScopeNone = func() HandlerScope { return nil }
)

Functions

func DisableWorker

func DisableWorker(ctx context.Context, db *gorp.DbMap, id string, maxLogSize int64) error

DisableWorker disable a worker

func FormString

func FormString(r *http.Request, s string) string

FormString return a string

func InitRouterMetrics

func InitRouterMetrics(ctx context.Context, s service.NamedService) error

InitRouterMetrics initialize prometheus metrics

func MaintenanceAware

func MaintenanceAware() service.HandlerConfigParam

MaintenanceAware route need CDS maintenance off

func QueryBool

func QueryBool(r *http.Request, s string) bool

QueryBool return a boolean from a query parameter

func QuerySort

func QuerySort(r *http.Request) (map[string]SortOrder, error)

QuerySort returns the a of key found in sort query param or nil if sort param not found.

func QueryString

func QueryString(r *http.Request, s string) string

QueryString return a string from a query parameter

func QueryStrings

func QueryStrings(r *http.Request, key string) ([]string, error)

QueryStrings returns the list of values for given query param key or nil if key no values.

func SetTracker

func SetTracker(resp http.ResponseWriter, k log.Field, v interface{})

func SortCompareInt

func SortCompareInt(i, j int, o SortOrder) bool

SortCompareInt returns the result of the right compare equation depending of given sort order.

func TracingMiddlewareFunc

func TracingMiddlewareFunc(s service.Service, db gorp.SqlExecutor, store cache.Store) service.Middleware

Types

type API

type API struct {
	service.Common
	Router              *Router
	Config              Configuration
	DBConnectionFactory *database.DBConnectionFactory
	SharedStorage       objectstore.Driver
	StartupTime         time.Time
	Maintenance         bool
	WSBroker            *websocket.Broker
	WSServer            *websocketServer
	Cache               cache.Store
	Metrics             struct {
		WorkflowRunFailed  *stats.Int64Measure
		WorkflowRunStarted *stats.Int64Measure
		Sessions           *stats.Int64Measure

		WorkflowRunsMarkToDelete *stats.Int64Measure
		WorkflowRunsDeleted      *stats.Int64Measure
		DatabaseConns            *stats.Int64Measure
		// contains filtered or unexported fields
	}
	AuthenticationDrivers map[sdk.AuthConsumerType]sdk.AuthDriver
}

API is a struct containing the configuration, the router, the database connection factory and so on

func New

func New() *API

New instanciates a new API object

func (*API) ApplyConfiguration

func (a *API) ApplyConfiguration(config interface{}) error

ApplyConfiguration apply an object of type api.Configuration after checking it

func (*API) CheckConfiguration

func (a *API) CheckConfiguration(config interface{}) error

CheckConfiguration checks the validity of the configuration object

func (*API) ConfigAPIHandler

func (api *API) ConfigAPIHandler() service.Handler

func (*API) ConfigCDNHandler

func (api *API) ConfigCDNHandler() service.Handler

func (*API) ConfigUserHandler

func (api *API) ConfigUserHandler() service.Handler

ConfigUserHandler return url of CDS UI

func (*API) ConfigVCShandler

func (api *API) ConfigVCShandler() service.Handler

ConfigVCShandler return the configuration of vcs server

func (*API) Init

func (*API) Init(i interface{}) (cdsclient.ServiceConfig, error)

func (*API) InitRouter

func (api *API) InitRouter()

InitRouter initializes the router and all the routes

func (*API) Serve

func (a *API) Serve(ctx context.Context) error

Serve will start the http api server

func (*API) Service

func (*API) Service() sdk.Service

Service returns an instance of sdk.Service for the API

func (*API) SetCookie

func (a *API) SetCookie(w http.ResponseWriter, name, value string, expires time.Time, httpOnly bool)

SetCookie on given response writter, automatically add domain and path based on api config.

func (*API) SetCookieSession

func (a *API) SetCookieSession(w http.ResponseWriter, name, value string)

SetCookieSession on given response writter, automatically add domain and path based on api config. This will returns a cookie with no expiration date that should be dropped by browser when closed.

func (*API) Status

func (api *API) Status(ctx context.Context) *sdk.MonitoringStatus

Status returns status, implements interface service.Service

func (*API) UnsetCookie

func (a *API) UnsetCookie(w http.ResponseWriter, name string, httpOnly bool)

UnsetCookie on given response writter, automatically add domain and path based on api config.

func (*API) WorkflowRunCraft

func (api *API) WorkflowRunCraft(ctx context.Context, tick time.Duration) error

func (*API) WorkflowSendEvent

func (api *API) WorkflowSendEvent(ctx context.Context, proj sdk.Project, report *workflow.ProcessorReport)

WorkflowSendEvent Send event on workflow run

type Configuration

type Configuration struct {
	Name string `toml:"name" comment:"Name of this CDS API Service\n Enter a name to enable this service" json:"name"`
	URL  struct {
		API string `toml:"api" default:"http://localhost:8081" json:"api"`
		UI  string `toml:"ui" default:"http://localhost:8080" json:"ui"`
	} `toml:"url" comment:"#####################\n CDS URLs Settings \n####################" json:"url"`
	HTTP    service.HTTPRouterConfiguration `toml:"http" json:"http"`
	Secrets struct {
		Key string `toml:"key" json:"-"`
	} `toml:"secrets" json:"secrets"`
	Database database.DBConfigurationWithEncryption `` /* 139-byte string literal not displayed */
	Cache    struct {
		TTL   int `toml:"ttl" default:"60" json:"ttl"`
		Redis struct {
			Host     string `` /* 192-byte string literal not displayed */
			Password string `toml:"password" json:"-"`
		} `` /* 134-byte string literal not displayed */
	} `toml:"cache" comment:"######################\n CDS Cache Settings \n#####################" json:"cache"`
	Download struct {
		Directory          string   `` /* 256-byte string literal not displayed */
		SupportedOSArch    []string `` /* 271-byte string literal not displayed */
		DownloadFromGitHub bool     `toml:"downloadFromGitHub" default:"true" json:"downloadFromGitHub" comment:"allow downloading binaries from GitHub"`
		Artifactory        struct {
			URL        string `toml:"url" default:"https://your-artifactory/artifactory" json:"url" comment:"URL of your artifactory" commented:"true"`
			Path       string `` /* 177-byte string literal not displayed */
			Repository string `toml:"repository" default:"artifactoryRepository" json:"repository" comment:"artifactory repository"`
			Token      string `toml:"token" default:"artifactoryToken" json:"-" comment:"token used to get binaries"`
		} `toml:"artifactory" default:"true" json:"artifactory" comment:"Artifactory Configuration (optional)." commented:"true"`
	} `toml:"download" json:"download"`
	InternalServiceMesh struct {
		RequestSecondsTimeout int  `toml:"requestSecondsTimeout" json:"requestSecondsTimeout" default:"60"`
		InsecureSkipVerifyTLS bool `toml:"insecureSkipVerifyTLS" json:"insecureSkipVerifyTLS" default:"false"`
	} `toml:"internalServiceMesh" json:"internalServiceMesh"`
	Auth struct {
		TokenDefaultDuration         int64           `toml:"tokenDefaultDuration" default:"30" comment:"The default duration of a token (in days)" json:"tokenDefaultDuration"`
		TokenOverlapDefaultDuration  string          `` /* 144-byte string literal not displayed */
		DefaultGroup                 string          `` /* 141-byte string literal not displayed */
		DisableAddUserInDefaultGroup bool            `` /* 157-byte string literal not displayed */
		RSAPrivateKey                string          `` /* 148-byte string literal not displayed */
		AllowedOrganizations         sdk.StringSlice `` /* 167-byte string literal not displayed */
		LDAP                         struct {
			Enabled         bool   `toml:"enabled" default:"false" json:"enabled"`
			SignupDisabled  bool   `toml:"signupDisabled" default:"false" json:"signupDisabled"`
			Host            string `toml:"host" json:"host"`
			Port            int    `toml:"port" default:"636" json:"port"`
			SSL             bool   `toml:"ssl" default:"true" json:"ssl"`
			RootDN          string `toml:"rootDN" default:"dc=myorganization,dc=com" json:"rootDN"`
			UserSearchBase  string `toml:"userSearchBase" default:"ou=people" json:"userSearchBase"`
			UserSearch      string `toml:"userSearch" default:"uid={0}" json:"userSearch"`
			UserFullname    string `toml:"userFullname" default:"{{.givenName}} {{.sn}}" json:"userFullname"`
			ManagerDN       string `` /* 136-byte string literal not displayed */
			ManagerPassword string `toml:"managerPassword" default:"SECRET_PASSWORD_MANAGER" comment:"Define it if ldapsearch need to be authenticated" json:"-"`
		} `toml:"ldap" json:"ldap"`
		Local struct {
			Enabled              bool   `toml:"enabled" default:"true" json:"enabled"`
			SignupDisabled       bool   `toml:"signupDisabled" default:"false" json:"signupDisabled"`
			SignupAllowedDomains string `` /* 196-byte string literal not displayed */
		} `toml:"local" json:"local"`
		CorporateSSO struct {
			MFASupportEnabled bool   `json:"mfa_support_enabled" default:"false" toml:"mfaSupportEnabled"`
			Enabled           bool   `json:"enabled" default:"false" toml:"enabled"`
			SignupDisabled    bool   `json:"signupDisabled" default:"false" toml:"signupDisabled"`
			RedirectMethod    string `json:"redirect_method" toml:"redirectMethod"`
			RedirectURL       string `json:"redirect_url" toml:"redirectURL"`
			Keys              struct {
				RequestSigningKey  string `json:"-" toml:"requestSigningKey"`
				TokenSigningKey    string `json:"-" toml:"tokenSigningKey"`
				TokenKeySigningKey struct {
					KeySigningKey   string `json:"public_signing_key" toml:"keySigningKey"`
					SigningKeyClaim string `json:"signing_key_claim" toml:"signingKeyClaim"`
				} `json:"-" toml:"tokenKeySigningKey"`
			} `json:"-" toml:"keys"`
		} `json:"corporate_sso" toml:"corporateSSO"`
		Github struct {
			Enabled        bool   `toml:"enabled" default:"false" json:"enabled"`
			SignupDisabled bool   `toml:"signupDisabled" default:"false" json:"signupDisabled"`
			URL            string `toml:"url" json:"url" default:"https://github.com" comment:"GitHub URL"`
			APIURL         string `toml:"apiUrl" json:"apiUrl" default:"https://api.github.com" comment:"GitHub API URL"`
			ClientID       string `toml:"clientId" json:"-" comment:"GitHub OAuth Client ID"`
			ClientSecret   string `toml:"clientSecret" json:"-" comment:"GitHub OAuth Client Secret"`
		} `` /* 168-byte string literal not displayed */
		Gitlab struct {
			Enabled        bool   `toml:"enabled" default:"false" json:"enabled"`
			SignupDisabled bool   `toml:"signupDisabled" default:"false" json:"signupDisabled"`
			URL            string `toml:"url" json:"url" default:"https://gitlab.com" comment:"GitLab URL"`
			ApplicationID  string `toml:"applicationID" json:"-" comment:"GitLab OAuth Application ID"`
			Secret         string `toml:"secret" json:"-" comment:"GitLab OAuth Application Secret"`
		} `` /* 168-byte string literal not displayed */
		OIDC struct {
			Enabled        bool   `toml:"enabled" default:"false" json:"enabled"`
			SignupDisabled bool   `toml:"signupDisabled" default:"false" json:"signupDisabled"`
			URL            string `toml:"url" json:"url" default:"" comment:"Open ID connect config URL"`
			ClientID       string `toml:"clientId" json:"-" comment:"OIDC Client ID"`
			ClientSecret   string `toml:"clientSecret" json:"-" comment:"OIDC Client Secret"`
		} `` /* 159-byte string literal not displayed */
	} `` /* 127-byte string literal not displayed */
	SMTP struct {
		Disable               bool   `` /* 154-byte string literal not displayed */
		Host                  string `toml:"host" json:"host" comment:"smtp host"`
		Port                  string `toml:"port" json:"port" comment:"smtp port"`
		ModeTLS               string `toml:"modeTLS" json:"modeTLS" default:"" comment:"possible values: empty, tls, starttls"`
		InsecureSkipVerifyTLS bool   `` /* 130-byte string literal not displayed */
		User                  string `toml:"user" json:"user" comment:"smtp username"`
		Password              string `toml:"password" json:"-" comment:"smtp password"`
		From                  string `toml:"from" default:"no-reply@cds.local" json:"from" comment:"smtp from"`
	} `toml:"smtp" comment:"#####################\n# CDS SMTP Settings \n####################" json:"smtp"`
	Artifact struct {
		Mode  string `toml:"mode" default:"local" comment:"swift, awss3 or local" json:"mode"`
		Local struct {
			BaseDirectory string `toml:"baseDirectory" default:"/var/lib/cds-engine/artifacts" json:"baseDirectory"`
		} `toml:"local"`
		Openstack struct {
			URL             string `toml:"url" comment:"Authentication Endpoint, generally value of $OS_AUTH_URL" json:"url"`
			Username        string `toml:"username" comment:"Openstack Username, generally value of $OS_USERNAME" json:"username"`
			Password        string `toml:"password" comment:"Openstack Password, generally value of $OS_PASSWORD" json:"-"`
			Tenant          string `toml:"tenant" comment:"Openstack Tenant, generally value of $OS_TENANT_NAME, v2 auth only" json:"tenant"`
			Domain          string `toml:"domain" comment:"Openstack Domain, generally value of $OS_DOMAIN_NAME, v3 auth only" json:"domain"`
			Region          string `toml:"region" comment:"Region, generally value of $OS_REGION_NAME" json:"region"`
			ContainerPrefix string `toml:"containerPrefix" comment:"Use if your want to prefix containers for CDS Artifacts" json:"containerPrefix"`
			DisableTempURL  bool   `` /* 143-byte string literal not displayed */
		} `toml:"openstack" json:"openstack"`
		AWSS3 struct {
			BucketName          string `toml:"bucketName" json:"bucketName" comment:"Name of the S3 bucket to use when storing artifacts"`
			Region              string `toml:"region" json:"region" default:"us-east-1" comment:"The AWS region"`
			Prefix              string `` /* 135-byte string literal not displayed */
			AuthFromEnvironment bool   `` /* 146-byte string literal not displayed */
			SharedCredsFile     string `toml:"sharedCredsFile" json:"sharedCredsFile" comment:"The path for the AWS credential file, used with profile"`
			Profile             string `toml:"profile" json:"profile" comment:"The profile within the AWS credentials file to use"`
			AccessKeyID         string `toml:"accessKeyId" json:"accessKeyId" comment:"A static AWS Secret Key ID"`
			SecretAccessKey     string `toml:"secretAccessKey" json:"-" comment:"A static AWS Secret Access Key"`
			SessionToken        string `toml:"sessionToken" json:"-" comment:"A static AWS session token"`
			Endpoint            string `toml:"endpoint" json:"endpoint" comment:"S3 API Endpoint (optional)" commented:"true"` //optional
			DisableSSL          bool   `toml:"disableSSL" json:"disableSSL" commented:"true"`                                  //optional
			ForcePathStyle      bool   `toml:"forcePathStyle" json:"forcePathStyle" commented:"true"`                          //optional
		} `toml:"awss3" json:"awss3"`
	} `toml:"artifact" comment:"Either filesystem local storage or Openstack Swift Storage are supported" json:"artifact"`
	DefaultOS   string `` /* 209-byte string literal not displayed */
	DefaultArch string `` /* 196-byte string literal not displayed */
	Graylog     struct {
		AccessToken string `toml:"accessToken" json:"-"`
		Stream      string `toml:"stream" json:"-"`
		URL         string `toml:"url" comment:"Example: http://localhost:9000" json:"url"`
	} `` /* 299-byte string literal not displayed */
	Log struct {
		StepMaxSize    int64 `toml:"stepMaxSize" default:"15728640" comment:"Max step logs size in bytes (default: 15MB)" json:"stepMaxSize"`
		ServiceMaxSize int64 `toml:"serviceMaxSize" default:"15728640" comment:"Max service logs size in bytes (default: 15MB)" json:"serviceMaxSize"`
	} `toml:"log" json:"log" comment:"###########################\n Log settings.\n##########################"`
	Help struct {
		Content string `` /* 138-byte string literal not displayed */
		Error   string `` /* 158-byte string literal not displayed */
	} `toml:"help" comment:"######################\n 'Help' informations \n######################" json:"help"`
	Workflow struct {
		MaxRuns                int64  `toml:"maxRuns" comment:"Maximum of runs by workflow" json:"maxRuns" default:"255"`
		DefaultRetentionPolicy string `` /* 269-byte string literal not displayed */
		DisablePurgeDeletion   bool   `` /* 177-byte string literal not displayed */
	} `toml:"workflow" comment:"######################\n 'Workflow' global configuration \n######################" json:"workflow"`
}

Configuration is the configuration structure for CDS API

type DefaultValues

type DefaultValues struct {
	ServerSecretsKey     string
	AuthSharedInfraToken string
	// For LDAP Client
	LDAPBase  string
	GivenName string
	SN        string
	BindDN    string
	BindPwd   string
}

DefaultValues is the struc for API Default configuration default values

type HandlerConfigFunc

type HandlerConfigFunc func(service.Handler, ...service.HandlerConfigParam) *service.HandlerConfig

HandlerConfigFunc is a type used in the router configuration fonction "Handle"

type HandlerScope

type HandlerScope []sdk.AuthConsumerScope

func Scope

Scope set for handler. If multiple scopes are given, one should match consumer scopes.

type PermCheckFunc

type PermCheckFunc func(ctx context.Context, w http.ResponseWriter, key string, perm int, routeVars map[string]string) error

PermCheckFunc defines func call to check permission

type Router

type Router struct {
	Background            context.Context
	Mux                   *mux.Router
	SetHeaderFunc         func() map[string]string
	Prefix                string
	URL                   string
	Middlewares           []service.Middleware
	DefaultAuthMiddleware service.Middleware
	PostAuthMiddlewares   []service.Middleware
	PostMiddlewares       []service.Middleware

	Config service.HTTPRouterConfiguration
	// contains filtered or unexported fields
}

Router is a wrapper around mux.Router

func (*Router) DELETE

DELETE will set given handler only for DELETE request

func (*Router) GET

GET will set given handler only for GET request

func (*Router) GetRoute

func (r *Router) GetRoute(method string, handler service.HandlerFunc, vars map[string]string) string

GetRoute returns the routes given a handler

func (*Router) Handle

func (r *Router) Handle(uri string, scope HandlerScope, handlers ...*service.HandlerConfig)

Handle adds all handler for their specific verb in gorilla router for given uri

func (*Router) HandlePrefix

func (r *Router) HandlePrefix(uri string, scope HandlerScope, handlers ...*service.HandlerConfig)

func (*Router) NotFoundHandler

func (r *Router) NotFoundHandler(w http.ResponseWriter, req *http.Request)

NotFoundHandler is called by default by Mux is any matching handler has been found

func (*Router) POST

POST will set given handler only for POST request

func (*Router) POSTEXECUTE

POSTEXECUTE will set given handler only for POST request and add a flag for execution permission

func (*Router) PUT

PUT will set given handler only for PUT request

func (*Router) StatusPanic

func (r *Router) StatusPanic() sdk.MonitoringStatusLine

StatusPanic returns router status. If nbPanic > 30 -> Alert, if nbPanic > 0 -> Warn

type SortOrder

type SortOrder string

SortOrder constant.

const (
	ASC  SortOrder = "asc"
	DESC SortOrder = "desc"
)

SortOrders.

type StartupConfig

type StartupConfig struct {
	Consumers []StartupConfigConsumer `json:"consumers"`
	IAT       int64                   `json:"iat"`
}

type StartupConfigConsumer

type StartupConfigConsumer struct {
	ID          string                    `json:"id"`
	Name        string                    `json:"name"`
	Description string                    `json:"description"`
	Type        StartupConfigConsumerType `json:"type"`
}

type StartupConfigConsumerType

type StartupConfigConsumerType string
const (
	StartupConfigConsumerTypeUI            StartupConfigConsumerType = "ui"
	StartupConfigConsumerTypeHatchery      StartupConfigConsumerType = "hatchery"
	StartupConfigConsumerTypeHooks         StartupConfigConsumerType = "hooks"
	StartupConfigConsumerTypeRepositories  StartupConfigConsumerType = "repositories"
	StartupConfigConsumerTypeDBMigrate     StartupConfigConsumerType = "db-migrate"
	StartupConfigConsumerTypeVCS           StartupConfigConsumerType = "vcs"
	StartupConfigConsumerTypeCDN           StartupConfigConsumerType = "cdn"
	StartupConfigConsumerTypeCDNStorageCDS StartupConfigConsumerType = "cdn-storage-cds"
	StartupConfigConsumerTypeElasticsearch StartupConfigConsumerType = "elasticsearch"
)

Source Files

Directories

Path Synopsis
database
artifact_manager/mock_artifact_manager
Package mock_artifact_manager is a generated GoMock package.
Package mock_artifact_manager is a generated GoMock package.
mock_services
Package mock_services is a generated GoMock package.
Package mock_services is a generated GoMock package.

Jump to

Keyboard shortcuts

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