diff --git a/cmd/github-metrics/BUILD.bazel b/cmd/github-metrics/BUILD.bazel index 4cde3b5..9cfc56e 100644 --- a/cmd/github-metrics/BUILD.bazel +++ b/cmd/github-metrics/BUILD.bazel @@ -8,11 +8,18 @@ repo_files() go_library( name = "github-metrics_lib", - srcs = ["main.go"], + srcs = [ + "main.go", + "reconciler.go", + ], importpath = "github.com/tbhb-dev/github-metrics/cmd/github-metrics", visibility = ["//:__pkg__"], deps = [ + "//internal/appauth", + "//internal/budget", + "//internal/ghclient", "//internal/receiver", + "//internal/reconcile", "//internal/recorder", "//internal/store", "//internal/telemetry", diff --git a/cmd/github-metrics/main.go b/cmd/github-metrics/main.go index 41e6b2c..80d4fff 100644 --- a/cmd/github-metrics/main.go +++ b/cmd/github-metrics/main.go @@ -1,12 +1,18 @@ // SPDX-License-Identifier: Apache-2.0 // Copyright Tony Burns -// Command github-metrics runs the webhook receiver and queue worker. +// Command github-metrics runs the webhook receiver, queue worker and optional reconciler. // // WEBHOOK_SECRET_FILE names a file that contains the App's webhook secret. // // STORE_FILE names the store file for the webhook queue and dedupe table. // +// OTEL_EXPORTER_OTLP_ENDPOINT enables metric export and is required for reconciliation. +// GITHUB_APP_ID and GITHUB_INSTALLATION_ID are positive integers that identify +// the GitHub App and its installation. GITHUB_APP_KEY_FILE names the App's +// private key file. Set all three to configure reconciliation. +// GITHUB_API_URL is the GitHub API base and defaults to https://api.github.com. +// // LISTEN_ADDR is the listen address and defaults to :8080. The health check // probes that address, or loopback when its host is a wildcard. // @@ -66,14 +72,23 @@ func main() { log := slog.New(slog.NewJSONHandler(os.Stdout, nil)) - err := run(addr, log) + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + err := run(ctx, addr, log) + + stop() + if err != nil { log.Error("exit", "error", err) os.Exit(1) } } -func run(addr string, log *slog.Logger) error { +func run(ctx context.Context, addr string, log *slog.Logger) error { + cfg, err := reconcilerConfig(os.Getenv) + if err != nil { + return err + } + file := os.Getenv("WEBHOOK_SECRET_FILE") if file == "" { return errNoSecretFile @@ -106,7 +121,7 @@ func run(addr string, log *slog.Logger) error { srv := receiver.NewServer(addr, receiver.Handler(secret, repo, log)) - ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + ctx, stop := context.WithCancel(ctx) defer stop() shutdownTelemetry, meter, err := telemetry.Setup(ctx, "github-metrics", version) @@ -116,16 +131,14 @@ func run(addr string, log *slog.Logger) error { endpoint := os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT") - consumer, err := newRecorder(endpoint, meter, repo) + consumer, loop, err := newConsumers(ctx, endpoint, cfg, meter, repo, log) if err != nil { - shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) + shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), shutdownTimeout) defer cancel() return errors.Join(err, shutdownTelemetry(shutdownCtx), repo.Close()) } - log.InfoContext(ctx, "recorder mode", "configured", endpoint != "") - workerErr := make(chan error, 1) go func() { @@ -134,24 +147,28 @@ func run(addr string, log *slog.Logger) error { stop() }() + reconcileErr := startReconciler(ctx, loop, stop) + serveErr := make(chan error, 1) go func() { serveErr <- srv.ListenAndServe() }() - log.Info("listening", "addr", addr) + log.InfoContext(ctx, "listening", "addr", addr) select { case err = <-serveErr: - // Shut down the worker before closing its store. + // Shut down the worker and reconciler before closing their store. case <-ctx.Done(): } stop() - shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) + shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), shutdownTimeout) defer cancel() - return errors.Join(err, srv.Shutdown(shutdownCtx), <-workerErr, shutdownTelemetry(shutdownCtx), repo.Close()) + return errors.Join( + err, srv.Shutdown(shutdownCtx), <-workerErr, <-reconcileErr, shutdownTelemetry(shutdownCtx), repo.Close(), + ) } func logRepairFloor(log *slog.Logger, ledger recorder.Ledger) error { diff --git a/cmd/github-metrics/main_test.go b/cmd/github-metrics/main_test.go index 1082d91..fb7b60e 100644 --- a/cmd/github-metrics/main_test.go +++ b/cmd/github-metrics/main_test.go @@ -5,9 +5,13 @@ package main import ( "bytes" + "context" "encoding/json" "errors" "log/slog" + "net/http/httptest" + "os" + "path/filepath" "testing" "time" @@ -141,3 +145,129 @@ func TestNewRecorderWithEndpoint(t *testing.T) { t.Fatalf("metric = %v, want one github.events observation", measurement) } } + +func TestRunWithoutReconciler(t *testing.T) { + for _, name := range []string{appIDEnv, installationIDEnv, appKeyFileEnv, apiURLEnv, "OTEL_EXPORTER_OTLP_ENDPOINT"} { + t.Setenv(name, "") + } + + dir := t.TempDir() + secretFile := filepath.Join(dir, "secret") + t.Setenv("WEBHOOK_SECRET_FILE", secretFile) + t.Setenv("STORE_FILE", filepath.Join(dir, "store.db")) + + err := os.WriteFile(secretFile, []byte("test secret"), 0o600) + if err != nil { + t.Fatal(err) + } + + address := httptest.NewUnstartedServer(nil) + addr := address.Listener.Addr().String() + address.Close() + + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + + var logs bytes.Buffer + + log := slog.New(slog.NewJSONHandler(&logs, nil)) + done := make(chan error, 1) + + go func() { done <- run(ctx, addr, log) }() + + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + + for probe(addr) != 0 { + select { + case err = <-done: + t.Fatalf("service exited before it was healthy: %v", err) + case <-ctx.Done(): + t.Fatalf("service did not become healthy, shutdown error = %v", <-done) + case <-ticker.C: + } + } + + cancel() + + err = <-done + if err != nil { + t.Fatal(err) + } + + if bytes.Count(logs.Bytes(), []byte(`"level":"INFO","msg":"reconciler disabled"`)) != 1 { + t.Fatalf("want one INFO line for the disabled reconciler, got %s", logs.String()) + } +} + +func TestReconcilerConfigDisabled(t *testing.T) { + t.Parallel() + + env := map[string]string{apiURLEnv: defaultGitHubAPI} + + var disabled reconcileConfig + + cfg, err := reconcilerConfig(func(name string) string { return env[name] }) + if err != nil || cfg != disabled { + t.Fatalf("want disabled configuration, got error %v", err) + } +} + +func TestReconcilerConfigPartial(t *testing.T) { + t.Parallel() + + for _, test := range []struct{ set, missing string }{ + {appIDEnv, installationIDEnv + ", " + appKeyFileEnv}, + {installationIDEnv, appIDEnv + ", " + appKeyFileEnv}, + {appKeyFileEnv, appIDEnv + ", " + installationIDEnv}, + } { + env := map[string]string{test.set: "test private value"} + want := errMissingReconcilerConfig.Error() + ": " + test.missing + + _, err := reconcilerConfig(func(name string) string { return env[name] }) + if !errors.Is(err, errMissingReconcilerConfig) || err.Error() != want { + t.Errorf("with %s set, want an error naming only %s", test.set, test.missing) + } + } +} + +func TestReconcilerConfigInvalidIDs(t *testing.T) { + t.Parallel() + + const invalid = "test private value" + + for name, want := range map[string]error{appIDEnv: errInvalidAppID, installationIDEnv: errInvalidInstallationID} { + env := map[string]string{appIDEnv: "1", installationIDEnv: "2", appKeyFileEnv: "test-key.pem"} + env[name] = invalid + + _, err := reconcilerConfig(func(name string) string { return env[name] }) + if !errors.Is(err, want) || err.Error() != want.Error() { + t.Errorf("want an error naming %s without its value", name) + } + } +} + +func TestReconcilerConfigComplete(t *testing.T) { + t.Parallel() + + const keyFile = "test-key.pem" + + for _, apiURL := range []string{"", defaultGitHubAPI + "/api/v3"} { + env := map[string]string{appIDEnv: "1", installationIDEnv: "2", appKeyFileEnv: keyFile, apiURLEnv: apiURL} + + cfg, err := reconcilerConfig(func(name string) string { return env[name] }) + if err != nil { + t.Fatal(err) + } + + wantURL := apiURL + if wantURL == "" { + wantURL = defaultGitHubAPI + } + + want := reconcileConfig{keyFile: keyFile, apiURL: wantURL, appID: 1, installationID: 2} + if cfg != want { + t.Fatalf("config = %+v, want %+v", cfg, want) + } + } +} diff --git a/cmd/github-metrics/reconciler.go b/cmd/github-metrics/reconciler.go new file mode 100644 index 0000000..6359ea0 --- /dev/null +++ b/cmd/github-metrics/reconciler.go @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright Tony Burns + +package main + +import ( + "cmp" + "context" + "errors" + "fmt" + "log/slog" + "net/http" + "net/url" + "os" + "strconv" + "strings" + "time" + + "go.opentelemetry.io/otel/metric" + + "github.com/tbhb-dev/github-metrics/internal/appauth" + "github.com/tbhb-dev/github-metrics/internal/budget" + "github.com/tbhb-dev/github-metrics/internal/ghclient" + "github.com/tbhb-dev/github-metrics/internal/reconcile" + "github.com/tbhb-dev/github-metrics/internal/recorder" + "github.com/tbhb-dev/github-metrics/internal/store" + "github.com/tbhb-dev/github-metrics/internal/worker" +) + +const ( + appIDEnv = "GITHUB_APP_ID" + installationIDEnv = "GITHUB_INSTALLATION_ID" + appKeyFileEnv = "GITHUB_APP_KEY_FILE" + apiURLEnv = "GITHUB_API_URL" + defaultGitHubAPI = "https://api.github.com" +) + +var ( + errMissingReconcilerConfig = errors.New("missing reconciler configuration") + errInvalidAppID = errors.New(appIDEnv + " must be a positive integer") + errInvalidInstallationID = errors.New(installationIDEnv + " must be a positive integer") + errInvalidBaseURL = errors.New(apiURLEnv + " must be a valid HTTPS API base URL") + errReadAppKey = errors.New("read " + appKeyFileEnv) +) + +type reconcileConfig struct { + keyFile string + apiURL string + appID int64 + installationID int64 +} + +func reconcilerConfig(env func(string) string) (reconcileConfig, error) { + app, installation, keyFile := env(appIDEnv), env(installationIDEnv), env(appKeyFileEnv) + credentials := [...]struct{ name, value string }{ + {appIDEnv, app}, {installationIDEnv, installation}, {appKeyFileEnv, keyFile}, + } + + var ( + disabled reconcileConfig + missing []string + ) + + for _, credential := range credentials { + if credential.value == "" { + missing = append(missing, credential.name) + } + } + + if len(missing) == len(credentials) { + return disabled, nil + } + + if len(missing) != 0 { + return reconcileConfig{}, fmt.Errorf("%w: %s", errMissingReconcilerConfig, strings.Join(missing, ", ")) + } + + appID, err := strconv.ParseInt(app, 10, 64) + if err != nil || appID <= 0 { + return reconcileConfig{}, errInvalidAppID + } + + installationID, err := strconv.ParseInt(installation, 10, 64) + if err != nil || installationID <= 0 { + return reconcileConfig{}, errInvalidInstallationID + } + + return reconcileConfig{ + keyFile: keyFile, + apiURL: cmp.Or(env(apiURLEnv), defaultGitHubAPI), + appID: appID, + installationID: installationID, + }, nil +} + +//nolint:ireturn // The worker accepts either recorder through its interface. +func newConsumers( + ctx context.Context, endpoint string, cfg reconcileConfig, meter metric.Meter, repo *store.Bolt, log *slog.Logger, +) (worker.Recorder, *reconcile.Loop, error) { + // cspell:ignore contextcheck + consumer, err := newRecorder(endpoint, meter, repo) //nolint:contextcheck // Recorder setup seeds its counters. + if err != nil { + return nil, nil, err + } + + log.InfoContext(ctx, "recorder mode", "configured", endpoint != "") + + record, configured := consumer.(*recorder.Recorder) + if !configured || cfg.keyFile == "" { + log.InfoContext(ctx, "reconciler disabled") + + return consumer, nil, nil + } + + loop, err := newReconciler(cfg, meter, record, repo, log) + + return consumer, loop, err +} + +func newReconciler( + cfg reconcileConfig, meter metric.Meter, record *recorder.Recorder, repo reconcile.Watermarks, log *slog.Logger, +) (*reconcile.Loop, error) { + // Relative request paths must resolve inside the API base path. + base, err := url.Parse(strings.TrimRight(cfg.apiURL, "/") + "/") + if err != nil || base.Scheme != "https" { + return nil, errInvalidBaseURL + } + + key, err := os.ReadFile(cfg.keyFile) + if err != nil { + return nil, errReadAppKey + } + + source, err := appauth.New(appauth.Config{ + HTTPClient: nil, Now: nil, Logger: log, BaseURL: base.String(), PrivateKeyPEM: key, + AppID: cfg.appID, InstallationID: cfg.installationID, + }) + if err != nil { + return nil, fmt.Errorf("create installation token source: %w", err) + } + + tags := ghclient.NewETags() + + client, err := ghclient.New(base.String(), http.DefaultClient, budget.New(), source, tags) + if err != nil { + return nil, errInvalidBaseURL + } + + lister := reconcile.NewLister(client, tags, base) + pass := func(ctx context.Context) (reconcile.RunResult, error) { + return reconcile.Run(ctx, lister, lister, record, repo, reconcileClock{}) + } + + loop, err := reconcile.NewLoop(pass, meter, log, nil) + if err != nil { + return nil, fmt.Errorf("create reconciler loop: %w", err) + } + + return loop, nil +} + +func startReconciler(ctx context.Context, loop *reconcile.Loop, stop context.CancelFunc) <-chan error { + done := make(chan error, 1) + if loop == nil { + close(done) + + return done + } + + go func() { + err := loop.Start(ctx) + done <- err + + if err != nil { + stop() + } + }() + + return done +} + +type reconcileClock struct{} + +func (reconcileClock) Now() time.Time { return time.Now() } diff --git a/deploy/compose.yaml b/deploy/compose.yaml index 4a17bd5..05e9cc8 100644 --- a/deploy/compose.yaml +++ b/deploy/compose.yaml @@ -21,6 +21,8 @@ # source, secrets/github_app_key, stays owned by the deploy account with mode # 0600. up.sh prepares secrets/runtime/github_app_key with uid 65532 and mode # 0400 inside a root-owned mode-0700 directory before Compose mounts it. +# Set both GitHub IDs to configure reconciliation. Compose passes the mounted +# key path to the service when GITHUB_APP_ID is set. # The named `store` volume mounts at `/var/lib/github-metrics`, which the image # creates owned by 65532:65532 so the receiver can write its store file while # the root filesystem stays read-only. @@ -53,7 +55,10 @@ services: LISTEN_ADDR: ":8080" OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-} STORE_FILE: /var/lib/github-metrics/store.db - GITHUB_APP_KEY_FILE: /run/secrets/github_app_key + GITHUB_APP_ID: ${GITHUB_APP_ID:-} + GITHUB_INSTALLATION_ID: ${GITHUB_INSTALLATION_ID:-} + GITHUB_API_URL: ${GITHUB_API_URL:-} + GITHUB_APP_KEY_FILE: ${GITHUB_APP_ID:+/run/secrets/github_app_key} WEBHOOK_SECRET_FILE: /run/secrets/webhook_secret volumes: - store:/var/lib/github-metrics diff --git a/deploy/deploy_test.go b/deploy/deploy_test.go index 4097b49..6296a00 100644 --- a/deploy/deploy_test.go +++ b/deploy/deploy_test.go @@ -473,7 +473,10 @@ func TestReceiverServiceSettings(t *testing.T) { "\n user: \"65532:65532\"\n", "\n read_only: true\n", "\n OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-}\n", - "\n GITHUB_APP_KEY_FILE: /run/secrets/github_app_key\n", + "\n GITHUB_APP_ID: ${GITHUB_APP_ID:-}\n", + "\n GITHUB_INSTALLATION_ID: ${GITHUB_INSTALLATION_ID:-}\n", + "\n GITHUB_API_URL: ${GITHUB_API_URL:-}\n", + "\n GITHUB_APP_KEY_FILE: ${GITHUB_APP_ID:+/run/secrets/github_app_key}\n", "\n secrets:\n - webhook_secret\n - github_app_key\n", "\n STORE_FILE: /var/lib/github-metrics/store.db\n", "\n volumes:\n - store:/var/lib/github-metrics\n",