service

package
v0.54.1 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2024 License: BSD-3-Clause Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ContextJWT contextKey = iota
	ContextJWTRaw
	ContextJWTFromCookie
	ContextSessionID
)
View Source
const JWTCookieName = "jwt_token"

Variables

This section is empty.

Functions

func Accepted

func Accepted(w http.ResponseWriter) error

Accepted is a helper function used by asynchronous handlers

func CheckSessionJWT

func CheckSessionJWT(jwtToken string, keyFunc jwt.Keyfunc) (*jwt.Token, *sdk.AuthSessionJWTClaims, error)

CheckSessionJWT validate given session jwt token.

func DefaultHeaders

func DefaultHeaders() map[string]string

DefaultHeaders is a set of default header for the router

func FormBool

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

FormBool return true if the form value is set to true|TRUE|yes|YES|1

func FormInt

func FormInt(r *http.Request, s string) int

FormInt return a int.

func FormInt64

func FormInt64(r *http.Request, s string) int64

FormInt64 return a int64.

func FormUInt

func FormUInt(r *http.Request, s string) uint

FormUInt return a uint.

func GetMetricHandler

func GetMetricHandler(prefix string) func() Handler

func GetPrometheustMetricsHandler

func GetPrometheustMetricsHandler(s NamedService) func() Handler

GetPrometheustMetricsHandler returns a Handler to exposer prometheus views

func JWTMiddleware

func JWTMiddleware(ctx context.Context, _ http.ResponseWriter, req *http.Request, _ *HandlerConfig, keyFunc jwt.Keyfunc) (context.Context, error)

func ParseServiceConfig added in v0.52.0

func ParseServiceConfig(cfg interface{}) (sdk.ServiceConfig, error)

ParseServiceConfig parse any object to craft a sdk.ServiceConfig

func TracingPostMiddleware added in v0.52.0

func TracingPostMiddleware(ctx context.Context, w http.ResponseWriter, req *http.Request, rc *HandlerConfig) (context.Context, error)

func UnmarshalBody

func UnmarshalBody(r *http.Request, i interface{}) error

UnmarshalBody read the request body and tries to json.unmarshal it. It returns sdk.ErrWrongRequest in case of error.

func UnmarshalRequest added in v0.52.0

func UnmarshalRequest(ctx context.Context, req *http.Request, entity interface{}) error

UnmarshalRequest unmarshal the request into the specified entity. The body request can be a JSON or a YAML format

func Write

func Write(w http.ResponseWriter, r io.Reader, status int, contentType string) error

Write is a helper function

func WriteError

func WriteError(ctx context.Context, w http.ResponseWriter, r *http.Request, err error)

WriteError is a helper function to return error in a language the called understand

func WriteJSON

func WriteJSON(w http.ResponseWriter, data interface{}, status int) error

WriteJSON is a helper function to marshal json, handle errors and set Content-Type for the best

func WriteMarshal added in v0.52.0

func WriteMarshal(w http.ResponseWriter, req *http.Request, data interface{}, status int) error

WriteMarshal is a helper function to marshal json/yaml, handle errors and set Content-Type for the best Response format could be application/json or appliation/x-yaml, depends on the Accept header default response is application/x-yaml

func WriteProcessTime

func WriteProcessTime(ctx context.Context, w http.ResponseWriter)

WriteProcessTime writes the duration of the call in the responsewriter

Types

type APIServiceConfiguration

type APIServiceConfiguration struct {
	HTTP struct {
		URL      string `toml:"url" default:"http://localhost:8081" json:"url"`
		Insecure bool   `toml:"insecure" commented:"true" json:"insecure"`
	} `toml:"http" json:"http"`
	Token                string `toml:"token" default:"************" json:"-"`
	RequestTimeout       int    `toml:"requestTimeout" default:"10" json:"requestTimeout"`
	MaxHeartbeatFailures int    `toml:"maxHeartbeatFailures" default:"10" json:"maxHeartbeatFailures"`
}

APIServiceConfiguration is an exposed type for CDS API

type AsynchronousHandler

type AsynchronousHandler func(ctx context.Context, r *http.Request) error

AsynchronousHandler defines the HTTP asynchronous handler used in CDS engine

type AsynchronousHandlerFunc

type AsynchronousHandlerFunc func() AsynchronousHandler

AsynchronousHandlerFunc defines the way to instantiate a handler

type BeforeStart

type BeforeStart interface {
	BeforeStart(ctx context.Context) error
}

BeforeStart has to be implemented if you want to run some code after the ApplyConfiguration and before the Serve of a Service

type Common

type Common struct {
	Client                cdsclient.Interface
	APIPublicKey          []byte
	ParsedAPIPublicKey    *rsa.PublicKey
	StartupTime           time.Time
	HTTPURL               string
	MaxHeartbeatFailures  int
	ServiceName           string
	ServiceType           string
	ServiceInstance       *sdk.Service
	PrivateKey            *rsa.PrivateKey
	Signer                jose.Signer
	CDNConfig             sdk.CDNConfig
	ServiceLogger         *logrus.Logger
	GoRoutines            *sdk.GoRoutines
	Region                string
	IgnoreJobWithNoRegion bool
	ModelType             string
}

Common is the struct representing a CDS µService

func (*Common) CommonMetricsHandler

func (c *Common) CommonMetricsHandler() Handler

func (*Common) Heartbeat

func (c *Common) Heartbeat(ctx context.Context, status func(ctx context.Context) *sdk.MonitoringStatus) error

Heartbeat have to be launch as a goroutine, call DoHeartBeat each 30s

func (*Common) Name

func (c *Common) Name() string

func (*Common) NewMonitoringStatus

func (c *Common) NewMonitoringStatus() *sdk.MonitoringStatus

NewMonitoringStatus returns a MonitoringStatus for the current service

func (*Common) RegisterCommonMetricsView

func (c *Common) RegisterCommonMetricsView(ctx context.Context)

func (*Common) Signin

func (c *Common) Signin(ctx context.Context, cdsclientConfig cdsclient.ServiceConfig, srvConfig interface{}) error

Signin a new service on API

func (*Common) Start

func (c *Common) Start(ctx context.Context) error

func (*Common) Type

func (c *Common) Type() string

func (*Common) Unregister

func (c *Common) Unregister(ctx context.Context) error

Unregister logout the service

type ErrorResponse

type ErrorResponse struct {
	sdk.Error
	RequestID string `json:"request_id"`
}

type HTTPRouterConfiguration

type HTTPRouterConfiguration struct {
	Addr                string `toml:"addr" default:"" commented:"true" comment:"Listen HTTP address without port, example: 127.0.0.1" json:"addr"`
	Port                int    `toml:"port" default:"8081" json:"port"`
	HeaderXForwardedFor string `` /* 179-byte string literal not displayed */
}

type Handler

type Handler func(ctx context.Context, w http.ResponseWriter, r *http.Request) error

Handler defines the HTTP handler used in CDS engine

func GetAllProfilesHandler

func GetAllProfilesHandler() Handler

func GetMetricsHandler

func GetMetricsHandler() Handler

func GetProfileHandler

func GetProfileHandler() Handler

func VersionHandler

func VersionHandler() Handler

VersionHandler returns version of current uservice

type HandlerConfig

type HandlerConfig struct {
	Name                   string
	Method                 string
	Handler                Handler
	IsDeprecated           bool
	OverrideAuthMiddleware Middleware
	MaintenanceAware       bool
	AllowedScopes          []sdk.AuthConsumerScope
	PermissionLevel        int
	CleanURL               string
	RbacCheckers           []RbacChecker
}

HandlerConfig is the configuration for one handler

type HandlerConfigParam

type HandlerConfigParam func(*HandlerConfig)

HandlerConfigParam is a type used in handler configuration, to set specific config on a route given a method

func OverrideAuth

func OverrideAuth(m Middleware) HandlerConfigParam

type HandlerFunc

type HandlerFunc func() Handler

HandlerFunc defines the way to instantiate a handler

type HandlerFuncV2 added in v0.52.0

type HandlerFuncV2 func() ([]RbacChecker, Handler)

type HatcheryCommonConfiguration

type HatcheryCommonConfiguration struct {
	Name          string                  `toml:"name" default:"" comment:"Name of Hatchery" json:"name"`
	RSAPrivateKey string                  `toml:"rsaPrivateKey" default:"" comment:"The RSA Private Key used by the hatchery.\nThis is mandatory." json:"-"`
	HTTP          HTTPRouterConfiguration `toml:"http" comment:"######################\n CDS Hatchery HTTP Configuration \n######################" json:"http"`
	URL           string                  `toml:"url" default:"http://localhost:8086" comment:"URL of this Hatchery" json:"url"`
	API           struct {
		HTTP struct {
			URL      string `toml:"url" default:"http://localhost:8081" comment:"CDS API URL" json:"url"`
			Insecure bool   `` /* 149-byte string literal not displayed */
		} `toml:"http" json:"http"`
		Token                string `` /* 131-byte string literal not displayed */
		TokenV2              string `toml:"tokenV2" default:"" comment:"Hatchery consumer Token. Allow to reach CDS API on /v2 routes" json:"-"`
		RequestTimeout       int    `toml:"requestTimeout" default:"10" comment:"Request CDS API: timeout in seconds" json:"requestTimeout"`
		MaxHeartbeatFailures int    `` /* 136-byte string literal not displayed */
	} `toml:"api" json:"api"`
	CDN struct {
		URL string `` /* 193-byte string literal not displayed */
		TCP struct {
			EnableTLS bool   `toml:"enableTLS" commented:"true" comment:"Enable TLS for CDN TCP connection" json:"enable_tls"`
			URL       string `` /* 185-byte string literal not displayed */
		} `toml:"tcp" json:"tcp"`
	} `toml:"cdn" json:"cdn"`
	Provision struct {
		InjectEnvVars             []string `toml:"injectEnvVars" commented:"true" comment:"Inject env variables in workers" json:"-" mapstructure:"injectEnvVars"`
		MaxWorker                 int      `toml:"maxWorker" default:"10" comment:"Maximum allowed simultaneous workers" json:"maxWorker"`
		MaxConcurrentProvisioning int      `` /* 138-byte string literal not displayed */
		MaxConcurrentRegistering  int      `` /* 178-byte string literal not displayed */
		RegisterFrequency         int      `` /* 136-byte string literal not displayed */
		Region                    string   `` /* 186-byte string literal not displayed */
		IgnoreJobWithNoRegion     bool     `` /* 154-byte string literal not displayed */
		WorkerAPIHTTP             struct {
			URL      string `` /* 188-byte string literal not displayed */
			Insecure bool   `` /* 149-byte string literal not displayed */
		} `toml:"workerApiHttp" json:"workerApiHttp"`
		WorkerCDN struct {
			URL string `` /* 178-byte string literal not displayed */
			TCP struct {
				EnableTLS bool   `toml:"enableTLS" commented:"true" comment:"Enable TLS for CDN TCP connection" json:"enable_tls"`
				URL       string `` /* 166-byte string literal not displayed */
			} `toml:"tcp" json:"tcp"`
		} `toml:"workerCdn" json:"workerCdn"`
		WorkerBasedir     string `toml:"workerBasedir" commented:"true" comment:"Worker Basedir" json:"workerBasedir"`
		WorkerLogsOptions struct {
			Level   string `toml:"level" comment:"Worker log level" json:"level"`
			Graylog struct {
				Host       string `toml:"host" comment:"Example: thot.ovh.com" json:"host"`
				Port       int    `toml:"port" comment:"Example: 12202" json:"port"`
				Protocol   string `toml:"protocol" default:"tcp" comment:"tcp or udp" json:"protocol"`
				ExtraKey   string `toml:"extraKey" comment:"Example: X-OVH-TOKEN. You can use many keys: aaa,bbb" json:"extraKey"`
				ExtraValue string `toml:"extraValue" comment:"value for extraKey field. For many keys: valueaaa,valuebbb" json:"-"`
			} `toml:"graylog" json:"graylog"`
		} `toml:"workerLogsOptions" comment:"Worker Log Configuration" json:"workerLogsOptions"`
		MaxAttemptsNumberBeforeFailure int `` /* 201-byte string literal not displayed */
	} `toml:"provision" json:"provision"`
	LogOptions struct {
		SpawnOptions struct {
			ThresholdCritical int `` /* 134-byte string literal not displayed */
			ThresholdWarning  int `` /* 131-byte string literal not displayed */
		} `toml:"spawnOptions" json:"spawnOptions"`
	} `toml:"logOptions" comment:"Hatchery Log Configuration" json:"logOptions"`
}

HatcheryCommonConfiguration is the base configuration for all hatcheries

func (HatcheryCommonConfiguration) Check

func (hcc HatcheryCommonConfiguration) Check() error

type Middleware

type Middleware func(ctx context.Context, w http.ResponseWriter, req *http.Request, rc *HandlerConfig) (context.Context, error)

Middleware defines the HTTP Middleware used in CDS engine

func CheckRequestSignatureMiddleware

func CheckRequestSignatureMiddleware(pubKey *rsa.PublicKey) Middleware

func TracingMiddlewareFunc

func TracingMiddlewareFunc(s Service) Middleware

type NamedService

type NamedService interface {
	Name() string
	Type() string
}

type RbacChecker added in v0.52.0

type RbacChecker func(ctx context.Context, auth *sdk.AuthUserConsumer, cache cache.Store, db gorp.SqlExecutor, vars map[string]string) error

func RBAC added in v0.52.0

func RBAC(checkers ...RbacChecker) []RbacChecker

type RbacCheckers added in v0.52.0

type RbacCheckers []RbacChecker

type RouterConfig

type RouterConfig struct {
	Config map[string]*HandlerConfig
}

RouterConfig contains a map of handler configuration. Key is the method of the http route

type RouterConfigParam

type RouterConfigParam func(rc *RouterConfig)

RouterConfigParam is the type of anonymous function returned by POST, GET and PUT functions

type Service

type Service interface {
	ApplyConfiguration(cfg interface{}) error
	Serve(ctx context.Context) error
	CheckConfiguration(cfg interface{}) error
	Start(ctx context.Context) error
	Init(cfg interface{}) (cdsclient.ServiceConfig, error)
	Signin(ctx context.Context, clientConfig cdsclient.ServiceConfig, srvConfig interface{}) error
	Unregister(ctx context.Context) error
	Heartbeat(ctx context.Context, status func(ctx context.Context) *sdk.MonitoringStatus) error
	Status(ctx context.Context) *sdk.MonitoringStatus
	NamedService
}

Service is the interface for a engine service Lifecycle: ApplyConfiguration->?BeforeStart->Init->Signin->Register->Start->Serve->Heartbeat

Jump to

Keyboard shortcuts

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