Skip to content

Commit 9641e47

Browse files
committed
[usage] Refactor server start into a function, specify config
1 parent 7c567bf commit 9641e47

File tree

3 files changed

+109
-57
lines changed

3 files changed

+109
-57
lines changed

components/usage/cmd/run.go

Lines changed: 5 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,10 @@
55
package cmd
66

77
import (
8-
"encoding/json"
9-
"net"
10-
"os"
8+
"github.com/gitpod-io/gitpod/usage/pkg/server"
119
"time"
1210

13-
"github.com/gitpod-io/gitpod/common-go/baseserver"
1411
"github.com/gitpod-io/gitpod/common-go/log"
15-
"github.com/gitpod-io/gitpod/usage/pkg/controller"
16-
"github.com/gitpod-io/gitpod/usage/pkg/db"
17-
"github.com/gitpod-io/gitpod/usage/pkg/stripe"
1812
"github.com/spf13/cobra"
1913
)
2014

@@ -36,58 +30,12 @@ func run() *cobra.Command {
3630
Run: func(cmd *cobra.Command, args []string) {
3731
log.Init(ServiceName, Version, true, verbose)
3832

39-
conn, err := db.Connect(db.ConnectionParams{
40-
User: os.Getenv("DB_USERNAME"),
41-
Password: os.Getenv("DB_PASSWORD"),
42-
Host: net.JoinHostPort(os.Getenv("DB_HOST"), os.Getenv("DB_PORT")),
43-
Database: "gitpod",
33+
err := server.Start(server.Config{
34+
ControllerSchedule: schedule,
35+
StripeCredentialsFile: apiKeyFile,
4436
})
4537
if err != nil {
46-
log.WithError(err).Fatal("Failed to establish database connection.")
47-
}
48-
49-
var billingController controller.BillingController = &controller.NoOpBillingController{}
50-
51-
if apiKeyFile != "" {
52-
bytes, err := os.ReadFile(apiKeyFile)
53-
if err != nil {
54-
log.WithError(err).Fatal("Failed to read Stripe API keys.")
55-
}
56-
57-
var config stripe.ClientConfig
58-
err = json.Unmarshal(bytes, &config)
59-
if err != nil {
60-
log.WithError(err).Fatal("Failed to unmarshal Stripe API keys.")
61-
}
62-
63-
c, err := stripe.New(config)
64-
if err != nil {
65-
log.WithError(err).Fatal("Failed to initialize Stripe client.")
66-
}
67-
billingController = controller.NewStripeBillingController(c, controller.DefaultWorkspacePricer)
68-
}
69-
70-
ctrl, err := controller.New(schedule, controller.NewUsageReconciler(conn, billingController))
71-
if err != nil {
72-
log.WithError(err).Fatal("Failed to initialize usage controller.")
73-
}
74-
75-
err = ctrl.Start()
76-
if err != nil {
77-
log.WithError(err).Fatal("Failed to start usage controller.")
78-
}
79-
defer ctrl.Stop()
80-
81-
srv, err := baseserver.New("usage")
82-
if err != nil {
83-
log.WithError(err).Fatal("Failed to initialize server.")
84-
}
85-
86-
controller.RegisterMetrics(srv.MetricsRegistry())
87-
88-
err = srv.ListenAndServe()
89-
if err != nil {
90-
log.WithError(err).Fatal("Failed to listen and serve.")
38+
log.WithError(err).Fatal("Failed to start usage server.")
9139
}
9240
},
9341
}

components/usage/pkg/server/server.go

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
2+
// Licensed under the GNU Affero General Public License (AGPL).
3+
// See License-AGPL.txt in the project root for license information.
4+
5+
package server
6+
7+
import (
8+
"fmt"
9+
"github.com/gitpod-io/gitpod/common-go/baseserver"
10+
"github.com/gitpod-io/gitpod/common-go/log"
11+
"github.com/gitpod-io/gitpod/usage/pkg/controller"
12+
"github.com/gitpod-io/gitpod/usage/pkg/db"
13+
"github.com/gitpod-io/gitpod/usage/pkg/stripe"
14+
"net"
15+
"os"
16+
"time"
17+
)
18+
19+
type Config struct {
20+
// ControllerSchedule determines how frequently to run the Usage/Billing controller
21+
ControllerSchedule time.Duration `json:"controllerSchedule,omitempty"`
22+
23+
StripeCredentialsFile string `json:"stripeCredentialsFile,omitempty"`
24+
25+
Server *baseserver.Configuration `json:"server,omitempty"`
26+
}
27+
28+
func Start(cfg Config) error {
29+
log.WithField("config", cfg).Info("Starting usage component.")
30+
31+
conn, err := db.Connect(db.ConnectionParams{
32+
User: os.Getenv("DB_USERNAME"),
33+
Password: os.Getenv("DB_PASSWORD"),
34+
Host: net.JoinHostPort(os.Getenv("DB_HOST"), os.Getenv("DB_PORT")),
35+
Database: "gitpod",
36+
})
37+
if err != nil {
38+
return fmt.Errorf("failed to establish database connection: %w", err)
39+
}
40+
41+
var billingController controller.BillingController = &controller.NoOpBillingController{}
42+
43+
if cfg.StripeCredentialsFile != "" {
44+
config, err := stripe.ReadConfigFromFile(cfg.StripeCredentialsFile)
45+
if err != nil {
46+
return fmt.Errorf("failed to load stripe credentials: %w", err)
47+
}
48+
49+
c, err := stripe.New(config)
50+
if err != nil {
51+
return fmt.Errorf("failed to initialize stripe client: %w", err)
52+
}
53+
billingController = controller.NewStripeBillingController(c, controller.DefaultWorkspacePricer)
54+
}
55+
56+
ctrl, err := controller.New(cfg.ControllerSchedule, controller.NewUsageReconciler(conn, billingController))
57+
if err != nil {
58+
return fmt.Errorf("failed to initialize usage controller: %w", err)
59+
}
60+
61+
err = ctrl.Start()
62+
if err != nil {
63+
return fmt.Errorf("failed to start usage controller: %w", err)
64+
}
65+
defer ctrl.Stop()
66+
67+
var serverOpts []baseserver.Option
68+
if cfg.Server != nil {
69+
serverOpts = append(serverOpts, baseserver.WithConfig(cfg.Server))
70+
}
71+
srv, err := baseserver.New("usage", serverOpts...)
72+
if err != nil {
73+
return fmt.Errorf("failed to initialize usage server: %w", err)
74+
}
75+
76+
err = controller.RegisterMetrics(srv.MetricsRegistry())
77+
if err != nil {
78+
return fmt.Errorf("failed to register controller metrics: %w", err)
79+
}
80+
81+
err = srv.ListenAndServe()
82+
if err != nil {
83+
return fmt.Errorf("failed to listen and server: %w", err)
84+
}
85+
86+
return nil
87+
}

components/usage/pkg/stripe/stripe.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
package stripe
66

77
import (
8+
"encoding/json"
89
"fmt"
10+
"os"
911
"strings"
1012

1113
"github.com/gitpod-io/gitpod/common-go/log"
@@ -22,6 +24,21 @@ type ClientConfig struct {
2224
SecretKey string `json:"secretKey"`
2325
}
2426

27+
func ReadConfigFromFile(path string) (ClientConfig, error) {
28+
bytes, err := os.ReadFile(path)
29+
if err != nil {
30+
return ClientConfig{}, fmt.Errorf("failed to read stripe client config: %w", err)
31+
}
32+
33+
var config ClientConfig
34+
err = json.Unmarshal(bytes, &config)
35+
if err != nil {
36+
return ClientConfig{}, fmt.Errorf("failed to unmarshal Stripe Client config: %w", err)
37+
}
38+
39+
return config, nil
40+
}
41+
2542
// New authenticates a Stripe client using the provided config
2643
func New(config ClientConfig) (*Client, error) {
2744
return &Client{sc: client.New(config.SecretKey, nil)}, nil

0 commit comments

Comments
 (0)