Skip to content

Feat(gateway): sentry #192

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 18 commits into from
May 15, 2025
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
69 changes: 48 additions & 21 deletions cmd/gateway.go
Original file line number Diff line number Diff line change
@@ -1,42 +1,50 @@
package cmd

import (
"context"
"errors"
"fmt"
"net/http"
"time"

"github.com/rs/zerolog/log"

openmfpcontext "github.com/openmfp/golang-commons/context"
"github.com/openmfp/golang-commons/sentry"
"github.com/spf13/cobra"
"net/http"
ctrl "sigs.k8s.io/controller-runtime"
restCfg "sigs.k8s.io/controller-runtime/pkg/client/config"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
"time"

"github.com/openmfp/golang-commons/logger"

appConfig "github.com/openmfp/kubernetes-graphql-gateway/common/config"
"github.com/openmfp/kubernetes-graphql-gateway/gateway/manager"
)

var gatewayCmd = &cobra.Command{
Use: "gateway",
Short: "Run the GQL Gateway",
Example: "go run main.go gateway",
RunE: func(cmd *cobra.Command, args []string) error {
start := time.Now()

appCfg, err := appConfig.NewFromEnv()
if err != nil {
log.Fatal().Err(err).Msg("Error getting app restCfg, exiting")
}

log, err := setupLogger(appCfg.LogLevel)
RunE: func(_ *cobra.Command, _ []string) error {
log, err := setupLogger(defaultCfg.Log.Level)
if err != nil {
return fmt.Errorf("failed to setup logger: %w", err)
}

log.Info().Str("LogLevel", log.GetLevel().String()).Msg("Starting server...")

ctx, _, shutdown := openmfpcontext.StartContext(log, appCfg, 1*time.Second)
defer shutdown()

if defaultCfg.Sentry.Dsn != "" {
err := sentry.Start(ctx,
defaultCfg.Sentry.Dsn, defaultCfg.Environment, defaultCfg.Region,
defaultCfg.Image.Name, defaultCfg.Image.Tag,
)
if err != nil {
log.Fatal().Err(err).Msg("Sentry init failed")
}

defer openmfpcontext.Recover(log)
}

ctrl.SetLogger(zap.New(zap.UseDevMode(true)))

// Get Kubernetes restCfg
Expand All @@ -55,15 +63,34 @@ var gatewayCmd = &cobra.Command{
// Set up HTTP handler
http.Handle("/", managerInstance)

// Start HTTP server
err = http.ListenAndServe(fmt.Sprintf(":%s", appCfg.Port), nil)
if err != nil {
log.Error().Err(err).Msg("Error starting server")
return fmt.Errorf("failed to start server: %w", err)
// Start HTTP server with context
server := &http.Server{
Addr: fmt.Sprintf(":%s", appCfg.Gateway.Port),
Handler: nil,
}

// Start the HTTP server in a goroutine so that we can listen for shutdown signals
go func() {
err := server.ListenAndServe()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Error().Err(err).Msg("Error starting HTTP server")
}
}()

// Wait for shutdown signal via the context
<-ctx.Done()

shutdownCtx, cancel := context.WithTimeout(context.Background(), defaultCfg.ShutdownTimeout) // ctx is closed, we need a new one
defer cancel()
log.Info().Msg("Shutting down HTTP server...")
if err := server.Shutdown(shutdownCtx); err != nil {
log.Fatal().Err(err).Msg("HTTP server shutdown failed")
}

log.Info().Float64("elapsed_seconds", time.Since(start).Seconds()).Msg("Setup completed")
// Call the shutdown cleanup
shutdown()

log.Info().Msg("Server shut down successfully")
return nil
},
}
Expand Down
39 changes: 10 additions & 29 deletions cmd/listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,14 @@ import (
"crypto/tls"
"os"

"k8s.io/client-go/discovery"

"github.com/openmfp/kubernetes-graphql-gateway/listener/discoveryclient"

kcpapis "github.com/kcp-dev/kcp/sdk/apis/apis/v1alpha1"
kcpcore "github.com/kcp-dev/kcp/sdk/apis/core/v1alpha1"
kcptenancy "github.com/kcp-dev/kcp/sdk/apis/tenancy/v1alpha1"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"

"github.com/spf13/cobra"

apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"

"k8s.io/client-go/discovery"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
Expand All @@ -27,28 +21,22 @@ import (
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
"sigs.k8s.io/controller-runtime/pkg/webhook"

"github.com/openmfp/kubernetes-graphql-gateway/common/config"
"github.com/openmfp/kubernetes-graphql-gateway/listener/discoveryclient"
"github.com/openmfp/kubernetes-graphql-gateway/listener/kcp"
)

func init() {
rootCmd.AddCommand(listenCmd)
}

var (
scheme = runtime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
webhookServer webhook.Server
metricsServerOptions metricsserver.Options
appCfg config.Config
)

var listenCmd = &cobra.Command{
Use: "listener",
Example: "KUBECONFIG=<path to kubeconfig file> go run . listener",
PreRun: func(cmd *cobra.Command, args []string) {
utilruntime.Must(clientgoscheme.AddToScheme(scheme))

utilruntime.Must(kcpapis.AddToScheme(scheme))
utilruntime.Must(kcpcore.AddToScheme(scheme))
utilruntime.Must(kcptenancy.AddToScheme(scheme))
Expand All @@ -59,20 +47,13 @@ var listenCmd = &cobra.Command{
}
ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))

var err error
appCfg, err = config.NewFromEnv()
if err != nil {
setupLog.Error(err, "failed to get operator flags from env, exiting...")
os.Exit(1)
}

disableHTTP2 := func(c *tls.Config) {
setupLog.Info("disabling http/2")
c.NextProtos = []string{"http/1.1"}
}

var tlsOpts []func(*tls.Config)
if !appCfg.EnableHTTP2 {
if !defaultCfg.EnableHTTP2 {
tlsOpts = []func(c *tls.Config){disableHTTP2}
}

Expand All @@ -81,19 +62,19 @@ var listenCmd = &cobra.Command{
})

metricsServerOptions = metricsserver.Options{
BindAddress: appCfg.MetricsAddr,
SecureServing: appCfg.SecureMetrics,
BindAddress: defaultCfg.Metrics.BindAddress,
SecureServing: defaultCfg.Metrics.Secure,
TLSOpts: tlsOpts,
}

if appCfg.SecureMetrics {
if defaultCfg.Metrics.Secure {
metricsServerOptions.FilterProvider = filters.WithAuthenticationAndAuthorization
}
},
Run: func(cmd *cobra.Command, args []string) {
ctx := ctrl.SetupSignalHandler()
restCfg := ctrl.GetConfigOrDie()
log, err := setupLogger(appCfg.LogLevel)
log, err := setupLogger(defaultCfg.Log.Level)
if err != nil {
setupLog.Error(err, "unable to setup logger")
os.Exit(1)
Expand All @@ -103,8 +84,8 @@ var listenCmd = &cobra.Command{
Scheme: scheme,
Metrics: metricsServerOptions,
WebhookServer: webhookServer,
HealthProbeBindAddress: appCfg.ProbeAddr,
LeaderElection: appCfg.EnableLeaderElection,
HealthProbeBindAddress: defaultCfg.HealthProbeBindAddress,
LeaderElection: defaultCfg.LeaderElection.Enabled,
LeaderElectionID: "72231e1f.openmfp.io",
}

Expand Down
54 changes: 50 additions & 4 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,64 @@ package cmd

import (
"github.com/spf13/cobra"
"github.com/spf13/viper"

openmfpconfig "github.com/openmfp/golang-commons/config"
"github.com/openmfp/kubernetes-graphql-gateway/common/config"
)

var (
appCfg config.Config
defaultCfg *openmfpconfig.CommonServiceConfig
v *viper.Viper
)

var rootCmd = &cobra.Command{
Use: "gateway",
Use: "listener or gateway",
}

func init() {
rootCmd.AddCommand(gatewayCmd)
}
rootCmd.AddCommand(listenCmd)

func Execute() {
if err := rootCmd.Execute(); err != nil {
var err error
v, defaultCfg, err = openmfpconfig.NewDefaultConfig(rootCmd)
if err != nil {
panic(err)
}

cobra.OnInitialize(initConfig)

err = openmfpconfig.BindConfigToFlags(v, gatewayCmd, &appCfg)
if err != nil {
panic(err)
}
}

func initConfig() {
// Top-level defaults
v.SetDefault("openapi-definitions-path", "./bin/definitions")
v.SetDefault("enable-kcp", true)
v.SetDefault("local-development", false)

// Listener
v.SetDefault("listener-apiexport-workspace", ":root")
v.SetDefault("listener-apiexport-name", "kcp.io")

// Gateway
v.SetDefault("gateway-port", "9080")
v.SetDefault("gateway-username-claim", "email")
v.SetDefault("gateway-should-impersonate", true)
// Gateway Handler config
v.SetDefault("gateway-handler-pretty", true)
v.SetDefault("gateway-handler-playground", true)
v.SetDefault("gateway-handler-graphiql", true)
// Gateway CORS
v.SetDefault("gateway-cors-enabled", false)
v.SetDefault("gateway-cors-allowed-origins", []string{"*"})
v.SetDefault("gateway-cors-allowed-headers", []string{"*"})
}

func Execute() {
cobra.CheckErr(rootCmd.Execute())
}
71 changes: 25 additions & 46 deletions common/config/config.go
Original file line number Diff line number Diff line change
@@ -1,50 +1,29 @@
package config

import (
"github.com/vrischmann/envconfig"
)

type Config struct {
Listener
Gateway

OpenApiDefinitionsPath string `envconfig:"default=./bin/definitions"`
EnableKcp bool `envconfig:"default=true,optional"`
LocalDevelopment bool `envconfig:"default=false,optional"`
}

type Gateway struct {
Port string `envconfig:"default=8080,optional"`
LogLevel string `envconfig:"default=INFO,optional"`
UserNameClaim string `envconfig:"default=email,optional"`
ShouldImpersonate bool `envconfig:"default=true,optional"`

HandlerCfg struct {
Pretty bool `envconfig:"default=true,optional"`
Playground bool `envconfig:"default=true,optional"`
GraphiQL bool `envconfig:"default=true,optional"`
}

Cors struct {
Enabled bool `envconfig:"default=false,optional"`
AllowedOrigins []string `envconfig:"default=*,optional"`
AllowedHeaders []string `envconfig:"default=*,optional"`
}
}

type Listener struct {
MetricsAddr string `envconfig:"default=0,optional"`
EnableLeaderElection bool `envconfig:"default=false,optional"`
ProbeAddr string `envconfig:"default=:8081,optional"`
SecureMetrics bool `envconfig:"default=true,optional"`
EnableHTTP2 bool `envconfig:"default=false,optional"`
ApiExportWorkspace string `envconfig:"default=:root,optional"`
ApiExportName string `envconfig:"default=kubernetes.graphql.gateway,optional"`
}

// NewFromEnv creates a Gateway from environment values
func NewFromEnv() (Config, error) {
cfg := Config{}
err := envconfig.Init(&cfg)
return cfg, err
OpenApiDefinitionsPath string `mapstructure:"openapi-definitions-path"`
EnableKcp bool `mapstructure:"enable-kcp"`
LocalDevelopment bool `mapstructure:"local-development"`

Listener struct {
// Listener fields will be added here
} `mapstructure:",squash"`

Gateway struct {
Port string `mapstructure:"gateway-port"`
UsernameClaim string `mapstructure:"gateway-username-claim"`
ShouldImpersonate bool `mapstructure:"gateway-should-impersonate"`

HandlerCfg struct {
Pretty bool `mapstructure:"gateway-handler-pretty"`
Playground bool `mapstructure:"gateway-handler-playground"`
GraphiQL bool `mapstructure:"gateway-handler-graphiql"`
} `mapstructure:",squash"`

Cors struct {
Enabled bool `mapstructure:"gateway-cors-enabled"`
AllowedOrigins []string `mapstructure:"gateway-cors-allowed-origins"`
AllowedHeaders []string `mapstructure:"gateway-cors-allowed-headers"`
} `mapstructure:",squash"`
} `mapstructure:",squash"`
}
Loading