Skip to content

[baseserver] Support common config struct #9999

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
May 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .github/CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

/components/blobserve @gitpod-io/engineering-workspace
/components/common-go @gitpod-io/engineering-workspace @gitpod-io/engineering-webapp
/components/common-go/baseserver @gitpod-io/engineering-webapp
/components/content-service-api @csweichel @geropl
/components/content-service @gitpod-io/engineering-workspace
/components/dashboard @gitpod-io/engineering-webapp
Expand Down
33 changes: 33 additions & 0 deletions components/common-go/baseserver/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
// Licensed under the GNU Affero General Public License (AGPL).
// See License-AGPL.txt in the project root for license information.

package baseserver

type Configuration struct {
Services ServicesConfiguration `json:"services" yaml:"services"`
}

type ServicesConfiguration struct {
GRPC *ServerConfiguration `json:"grpc,omitempty" yaml:"grpc,omitempty"`
HTTP *ServerConfiguration `json:"http,omitempty" yaml:"http,omitempty"`
}

type ServerConfiguration struct {
Address string `json:"address" yaml:"address"`
TLS *TLSConfiguration `json:"tls" yaml:"tls"`
}

// GetAddress returns the configured address or an empty string of s is nil
func (s *ServerConfiguration) GetAddress() string {
if s == nil {
return ""
}
return s.Address
}

type TLSConfiguration struct {
CAPath string `json:"caPath" yaml:"caPath"`
CertPath string `json:"certPath" yaml:"certPath"`
KeyPath string `json:"keyPath" yaml:"keyPath"`
}
92 changes: 44 additions & 48 deletions components/common-go/baseserver/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,25 @@ package baseserver
import (
"context"
"fmt"
"time"

"github.com/gitpod-io/gitpod/common-go/log"
"github.com/heptiolabs/healthcheck"
"github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus"
"google.golang.org/grpc/health/grpc_health_v1"
"time"
)

type config struct {
type options struct {
logger *logrus.Entry

// hostname is the hostname on which our servers will listen.
hostname string
// debugPort is the port we listen on for metrics, pprof, readiness and livenss checks
debugPort int
// grpcPort is the port we listen on for gRPC traffic
grpcPort int
// httpPort is the port we listen on for HTTP traffic
httpPort int
config *Configuration

// closeTimeout is the amount we allow for the server to shut down cleanly
closeTimeout time.Duration

underTest bool

// metricsRegistry configures the metrics registry to use for exporting metrics. When not set, the default prometheus registry is used.
metricsRegistry *prometheus.Registry

Expand All @@ -38,111 +34,111 @@ type config struct {
grpcHealthCheck grpc_health_v1.HealthServer
}

func defaultConfig() *config {
return &config{
logger: log.New(),
hostname: "localhost",
httpPort: -1, // disabled by default
grpcPort: -1, // disabled by default
debugPort: 9500,
func defaultOptions() *options {
return &options{
logger: log.New(),
config: &Configuration{
Services: ServicesConfiguration{
GRPC: nil, // disabled by default
HTTP: nil, // disabled by default
},
},

closeTimeout: 5 * time.Second,
healthHandler: healthcheck.NewHandler(),
metricsRegistry: prometheus.NewRegistry(),
grpcHealthCheck: &GrpcHealthService{},
}
}

type Option func(cfg *config) error
type Option func(opts *options) error

func WithHostname(hostname string) Option {
return func(cfg *config) error {
cfg.hostname = hostname
// WithConfig uses a config struct to initialise the services
func WithConfig(config *Configuration) Option {
return func(opts *options) error {
opts.config = config
return nil
}
}

// WithHTTPPort sets the port to use for an HTTP server. Setting WithHTTPPort also enables an HTTP server on the baseserver.
func WithHTTPPort(port int) Option {
return func(cfg *config) error {
cfg.httpPort = port
func WithUnderTest() Option {
return func(opts *options) error {
opts.underTest = true
return nil
}
}

// WithGRPCPort sets the port to use for an HTTP server. Setting WithGRPCPort also enables a gRPC server on the baseserver.
func WithGRPCPort(port int) Option {
return func(cfg *config) error {
cfg.grpcPort = port
// WithHTTP configures and enables the HTTP server.
func WithHTTP(cfg *ServerConfiguration) Option {
return func(opts *options) error {
opts.config.Services.HTTP = cfg
return nil
}
}

func WithDebugPort(port int) Option {
return func(cfg *config) error {
if port < 0 {
return fmt.Errorf("grpc port must not be negative, got: %d", port)
}

cfg.debugPort = port
// WithGRPC configures and enables the GRPC server.
func WithGRPC(cfg *ServerConfiguration) Option {
return func(opts *options) error {
opts.config.Services.GRPC = cfg
return nil
}
}

func WithLogger(logger *logrus.Entry) Option {
return func(cfg *config) error {
return func(opts *options) error {
if logger == nil {
return fmt.Errorf("nil logger specified")
}

cfg.logger = logger
opts.logger = logger
return nil
}
}

func WithCloseTimeout(d time.Duration) Option {
return func(cfg *config) error {
cfg.closeTimeout = d
return func(opts *options) error {
opts.closeTimeout = d
return nil
}
}

func WithMetricsRegistry(r *prometheus.Registry) Option {
return func(cfg *config) error {
return func(opts *options) error {
if r == nil {
return fmt.Errorf("nil prometheus registry received")
}

cfg.metricsRegistry = r
opts.metricsRegistry = r
return nil
}
}

func WithHealthHandler(handler healthcheck.Handler) Option {
return func(cfg *config) error {
return func(opts *options) error {
if handler == nil {
return fmt.Errorf("nil healthcheck handler provided")
}

cfg.healthHandler = handler
opts.healthHandler = handler
return nil
}
}

func WithGRPCHealthService(svc grpc_health_v1.HealthServer) Option {
return func(cfg *config) error {
return func(opts *options) error {
if svc == nil {
return fmt.Errorf("nil healthcheck handler provided")
}

cfg.grpcHealthCheck = svc
opts.grpcHealthCheck = svc
return nil
}
}

func evaluateOptions(cfg *config, opts ...Option) (*config, error) {
func evaluateOptions(cfg *options, opts ...Option) (*options, error) {
for _, opt := range opts {
if err := opt(cfg); err != nil {
return nil, fmt.Errorf("failed to evaluate config: %w", err)
return nil, fmt.Errorf("failed to evaluate options: %w", err)
}
}

Expand Down
86 changes: 18 additions & 68 deletions components/common-go/baseserver/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,105 +5,55 @@
package baseserver

import (
"testing"
"time"

"github.com/gitpod-io/gitpod/common-go/log"
"github.com/heptiolabs/healthcheck"
"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/health/grpc_health_v1"
"testing"
"time"
)

func TestOptions(t *testing.T) {
logger := log.New()
httpPort := 8080
grpcPort := 8081
debugPort := 8082
timeout := 10 * time.Second
hostname := "another_hostname"
registry := prometheus.NewRegistry()
health := healthcheck.NewHandler()
grpcHealthService := &grpc_health_v1.UnimplementedHealthServer{}
httpCfg := ServerConfiguration{Address: "localhost:8080"}
grpcCfg := ServerConfiguration{Address: "localhost:8081"}

var opts = []Option{
WithHostname(hostname),
WithDebugPort(debugPort),
WithHTTPPort(httpPort),
WithGRPCPort(grpcPort),
WithHTTP(&httpCfg),
WithGRPC(&grpcCfg),
WithLogger(logger),
WithCloseTimeout(timeout),
WithMetricsRegistry(registry),
WithHealthHandler(health),
WithGRPCHealthService(grpcHealthService),
}
cfg, err := evaluateOptions(defaultConfig(), opts...)
actual, err := evaluateOptions(defaultOptions(), opts...)
require.NoError(t, err)

require.Equal(t, &config{
logger: logger,
hostname: hostname,
grpcPort: grpcPort,
httpPort: httpPort,
debugPort: debugPort,
expected := &options{
logger: logger,
config: &Configuration{
Services: ServicesConfiguration{
GRPC: &grpcCfg,
HTTP: &httpCfg,
},
},
closeTimeout: timeout,
metricsRegistry: registry,
healthHandler: health,
grpcHealthCheck: grpcHealthService,
}, cfg)
}

func TestWithHTTPPort(t *testing.T) {
for _, scenario := range []struct {
Port int
Expected int
}{
{Port: -1, Expected: -1},
{Port: 0, Expected: 0},
{Port: 9000, Expected: 9000},
} {
cfg, err := evaluateOptions(defaultConfig(), WithHTTPPort(scenario.Port))
require.NoError(t, err)
require.Equal(t, scenario.Expected, cfg.httpPort)
}
}

func TestWithGRPCPort(t *testing.T) {
for _, scenario := range []struct {
Port int
Expected int
}{
{Port: -1, Expected: -1},
{Port: 0, Expected: 0},
{Port: 9000, Expected: 9000},
} {
cfg, err := evaluateOptions(defaultConfig(), WithGRPCPort(scenario.Port))
require.NoError(t, err)
require.Equal(t, scenario.Expected, cfg.grpcPort)
}
}

func TestWithDebugPort(t *testing.T) {
for _, scenario := range []struct {
Port int

Errors bool
Expected int
}{
{Port: -1, Errors: true},
{Port: 0, Expected: 0},
{Port: 9000, Expected: 9000},
} {
cfg, err := evaluateOptions(defaultConfig(), WithDebugPort(scenario.Port))
if scenario.Errors {
require.Error(t, err)
continue
}

require.Equal(t, scenario.Expected, cfg.debugPort)
}
require.Equal(t, expected, actual)
}

func TestLogger_ErrorsWithNilLogger(t *testing.T) {
_, err := evaluateOptions(defaultConfig(), WithLogger(nil))
_, err := evaluateOptions(defaultOptions(), WithLogger(nil))
require.Error(t, err)
}
Loading