Skip to content
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

Report botkube status #978

Merged
merged 5 commits into from
Feb 17, 2023
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
22 changes: 19 additions & 3 deletions cmd/botkube/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,12 @@ import (
"sigs.k8s.io/controller-runtime/pkg/manager/signals"

"github.com/kubeshop/botkube/internal/analytics"
"github.com/kubeshop/botkube/internal/graphql"
"github.com/kubeshop/botkube/internal/lifecycle"
"github.com/kubeshop/botkube/internal/loggerx"
"github.com/kubeshop/botkube/internal/plugin"
"github.com/kubeshop/botkube/internal/source"
"github.com/kubeshop/botkube/internal/status"
"github.com/kubeshop/botkube/internal/storage"
"github.com/kubeshop/botkube/pkg/action"
"github.com/kubeshop/botkube/pkg/bot"
Expand Down Expand Up @@ -72,7 +74,8 @@ func main() {
func run(ctx context.Context) error {
// Load configuration
config.RegisterFlags(pflag.CommandLine)
cfgProvider := config.GetProvider()
gqlClient := graphql.NewDefaultGqlClient()
cfgProvider := config.GetProvider(gqlClient)
configs, err := cfgProvider.Configs(ctx)
if err != nil {
return fmt.Errorf("while loading configuration files: %w", err)
Expand All @@ -84,6 +87,7 @@ func run(ctx context.Context) error {
}

logger := loggerx.New(conf.Settings.Log)
statusReporter := status.NewStatusReporter(logger, gqlClient)

if confDetails.ValidateWarnings != nil {
logger.Warnf("Configuration validation warnings: %v", confDetails.ValidateWarnings.Error())
Expand All @@ -104,7 +108,7 @@ func run(ctx context.Context) error {
// The reader must be not closed to report the panic properly.
defer analytics.ReportPanicIfOccurs(logger, reporter)

reportFatalError := reportFatalErrFn(logger, reporter)
reportFatalError := reportFatalErrFn(logger, reporter, statusReporter)

errGroup, ctx := errgroup.WithContext(ctx)

Expand Down Expand Up @@ -370,8 +374,13 @@ func run(ctx context.Context) error {
router.BuildTable(conf),
actionProvider,
reporter,
statusReporter,
)

if _, err := statusReporter.ReportDeploymentStartup(ctx); err != nil {
return reportFatalError("while reporting botkube startup", err)
}

err = ctrl.Start(ctx)
if err != nil {
return reportFatalError("while starting controller", err)
Expand Down Expand Up @@ -450,14 +459,21 @@ func getK8sClients(cfg *rest.Config) (dynamic.Interface, discovery.DiscoveryInte
return dynamicK8sCli, discoCacheClient, mapper, nil
}

func reportFatalErrFn(logger logrus.FieldLogger, reporter analytics.Reporter) func(ctx string, err error) error {
func reportFatalErrFn(logger logrus.FieldLogger, reporter analytics.Reporter, status status.StatusReporter) func(ctx string, err error) error {
return func(ctx string, err error) error {
// use separate ctx as parent ctx might be cancelled already
ctxTimeout, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
wrappedErr := fmt.Errorf("%s: %w", ctx, err)

if reportErr := reporter.ReportFatalError(err); reportErr != nil {
logger.Errorf("while reporting fatal error: %s", err.Error())
}

if _, err := status.ReportDeploymentFailed(ctxTimeout); err != nil {
logger.Errorf("while reporting botkube deployment status: %s", err.Error())
}

return wrappedErr
}
}
Expand Down
86 changes: 12 additions & 74 deletions internal/config/gql_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,69 +3,26 @@ package config
import (
"context"
"fmt"
"net/http"
"time"

"github.com/hasura/go-graphql-client"
)

const (
defaultTimeout = 30 * time.Second
//nolint:gosec // warns us about 'Potential hardcoded credentials' but there is no security issue here
apiKeyHeaderName = "X-API-Key"
gql "github.com/kubeshop/botkube/internal/graphql"
)

// GqlClient defines GraphQL client.
type GqlClient interface {
// DeploymentClient defines GraphQL client.
type DeploymentClient interface {
GetDeployment(ctx context.Context) (Deployment, error)
}

// Option define GraphQL client option.
type Option func(*Gql)

// WithEndpoint configures ApiURL for GraphQL endpoint.
func WithEndpoint(url string) Option {
return func(client *Gql) {
client.Endpoint = url
}
}

// WithAPIKey configures API key for GraphQL endpoint.
func WithAPIKey(apiKey string) Option {
return func(client *Gql) {
client.APIKey = apiKey
}
}

// WithDeploymentID configures deployment id for GraphQL endpoint.
func WithDeploymentID(id string) Option {
return func(client *Gql) {
client.DeploymentID = id
}
}

// Gql defines GraphQL client data structure.
type Gql struct {
Cli *graphql.Client
Endpoint string
APIKey string
DeploymentID string
client *gql.Gql
deploymentID string
}

// NewGqlClient initializes GraphQL client.
func NewGqlClient(options ...Option) *Gql {
c := &Gql{}
for _, opt := range options {
opt(c)
}

httpCli := &http.Client{
Transport: newAPIKeySecuredTransport(c.APIKey),
Timeout: defaultTimeout,
}

c.Cli = graphql.NewClient(c.Endpoint, httpCli)
return c
// NewDeploymentClient initializes GraphQL client.
func NewDeploymentClient(client *gql.Gql) *Gql {
return &Gql{client: client, deploymentID: client.DeploymentID}
}

// Deployment returns deployment with Botkube configuration.
Expand All @@ -74,35 +31,16 @@ type Deployment struct {
}

// GetDeployment retrieves deployment by id.
func (c *Gql) GetDeployment(ctx context.Context) (Deployment, error) {
func (g *Gql) GetDeployment(ctx context.Context) (Deployment, error) {
var query struct {
Deployment Deployment `graphql:"deployment(id: $id)"`
}
variables := map[string]interface{}{
"id": graphql.ID(c.DeploymentID),
"id": graphql.ID(g.deploymentID),
}
err := c.Cli.Query(ctx, &query, variables)
err := g.client.Cli.Query(ctx, &query, variables)
if err != nil {
return Deployment{}, fmt.Errorf("while querying deployment details for %q: %w", c.DeploymentID, err)
return Deployment{}, fmt.Errorf("while querying deployment details for %q: %w", g.deploymentID, err)
}
return query.Deployment, nil
}

type apiKeySecuredTransport struct {
apiKey string
transport *http.Transport
}

func newAPIKeySecuredTransport(apiKey string) *apiKeySecuredTransport {
return &apiKeySecuredTransport{
apiKey: apiKey,
transport: http.DefaultTransport.(*http.Transport).Clone(),
}
}

func (t *apiKeySecuredTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if t.apiKey != "" {
req.Header.Set(apiKeyHeaderName, t.apiKey)
}
return t.transport.RoundTrip(req)
}
9 changes: 8 additions & 1 deletion internal/config/gql_client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import (
"testing"

"github.com/stretchr/testify/assert"

"github.com/kubeshop/botkube/internal/graphql"
)

func TestGql_GetDeployment(t *testing.T) {
Expand Down Expand Up @@ -41,7 +43,12 @@ func TestGql_GetDeployment(t *testing.T) {
}))
defer svr.Close()

g := NewGqlClient(WithEndpoint(svr.URL), WithDeploymentID("my-id"), WithAPIKey("api-key"))
gqlClient := graphql.NewGqlClient(
graphql.WithEndpoint(svr.URL),
graphql.WithAPIKey("api-key"),
graphql.WithDeploymentID("my-id"),
)
g := NewDeploymentClient(gqlClient)
deployment, err := g.GetDeployment(context.Background())
assert.NoError(t, err)
assert.NotNil(t, deployment.BotkubeConfig)
Expand Down
15 changes: 4 additions & 11 deletions internal/config/gql_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,19 @@ import (
"sigs.k8s.io/yaml"
)

const (
GqlProviderEndpointEnvKey = "CONFIG_PROVIDER_ENDPOINT"
GqlProviderIdentifierEnvKey = "CONFIG_PROVIDER_IDENTIFIER"
//nolint:gosec // warns us about 'Potential hardcoded credentials' but there is no security issue here
GqlProviderAPIKeyEnvKey = "CONFIG_PROVIDER_API_KEY"
)

// GqlProvider is GraphQL provider
type GqlProvider struct {
GqlClient GqlClient
client DeploymentClient
}

// NewGqlProvider initializes new GraphQL config source provider
func NewGqlProvider(gql GqlClient) *GqlProvider {
return &GqlProvider{GqlClient: gql}
func NewGqlProvider(dc DeploymentClient) *GqlProvider {
return &GqlProvider{client: dc}
}

// Configs returns list of config files
func (g *GqlProvider) Configs(ctx context.Context) (YAMLFiles, error) {
deployment, err := g.GqlClient.GetDeployment(ctx)
deployment, err := g.client.GetDeployment(ctx)
if err != nil {
return nil, errors.Wrapf(err, "while getting deployment")
}
Expand Down
2 changes: 1 addition & 1 deletion internal/config/gql_provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"github.com/stretchr/testify/assert"
)

var _ GqlClient = &fakeGqlClient{}
var _ DeploymentClient = &fakeGqlClient{}

type fakeGqlClient struct {
}
Expand Down
100 changes: 100 additions & 0 deletions internal/graphql/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package graphql

import (
"net/http"
"os"
"time"

"github.com/hasura/go-graphql-client"
)

const (
defaultTimeout = 30 * time.Second
//nolint:gosec // warns us about 'Potential hardcoded credentials' but there is no security issue here
apiKeyHeaderName = "X-API-Key"

GqlProviderEndpointEnvKey = "CONFIG_PROVIDER_ENDPOINT"
GqlProviderIdentifierEnvKey = "CONFIG_PROVIDER_IDENTIFIER"
//nolint:gosec // warns us about 'Potential hardcoded credentials' but there is no security issue here
GqlProviderAPIKeyEnvKey = "CONFIG_PROVIDER_API_KEY"
)

// Option define GraphQL client option.
type Option func(*Gql)

// WithEndpoint configures ApiURL for GraphQL endpoint.
func WithEndpoint(url string) Option {
return func(client *Gql) {
client.Endpoint = url
}
}

// WithAPIKey configures API key for GraphQL endpoint.
func WithAPIKey(apiKey string) Option {
return func(client *Gql) {
client.APIKey = apiKey
}
}

// WithDeploymentID configures deployment id for GraphQL endpoint.
func WithDeploymentID(id string) Option {
return func(client *Gql) {
client.DeploymentID = id
}
}

// Gql defines GraphQL client data structure.
type Gql struct {
Cli *graphql.Client
Endpoint string
APIKey string
DeploymentID string
}

// NewGqlClient initializes GraphQL client.
func NewGqlClient(options ...Option) *Gql {
c := &Gql{}
for _, opt := range options {
opt(c)
}

// skip client creation when not requested
if c.Endpoint == "" {
return c
}

httpCli := &http.Client{
Transport: newAPIKeySecuredTransport(c.APIKey),
Timeout: defaultTimeout,
}

c.Cli = graphql.NewClient(c.Endpoint, httpCli)
return c
}

func NewDefaultGqlClient() *Gql {
return NewGqlClient(
WithEndpoint(os.Getenv(GqlProviderEndpointEnvKey)),
WithAPIKey(os.Getenv(GqlProviderAPIKeyEnvKey)),
WithDeploymentID(os.Getenv(GqlProviderIdentifierEnvKey)),
)
}

type apiKeySecuredTransport struct {
apiKey string
transport *http.Transport
}

func newAPIKeySecuredTransport(apiKey string) *apiKeySecuredTransport {
return &apiKeySecuredTransport{
apiKey: apiKey,
transport: http.DefaultTransport.(*http.Transport).Clone(),
}
}

func (t *apiKeySecuredTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if t.apiKey != "" {
req.Header.Set(apiKeyHeaderName, t.apiKey)
}
return t.transport.RoundTrip(req)
}
Loading