forked from longtao.wu/droboticflow
159 lines
5.3 KiB
Go
159 lines
5.3 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
"droboticflow/internal/config"
|
|
"droboticflow/internal/objectsync"
|
|
"droboticflow/internal/retry"
|
|
"droboticflow/internal/store"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
)
|
|
|
|
func connectMongo(ctx context.Context, mongoURI string, attempts int, delay time.Duration) (*mongo.Client, error) {
|
|
return retry.Do(ctx, attempts, delay, "mongodb connection", func(ctx context.Context, _ int) (*mongo.Client, error) {
|
|
client, err := mongo.Connect(ctx, options.Client().ApplyURI(mongoURI))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := client.Ping(ctx, nil); err != nil {
|
|
_ = client.Disconnect(ctx)
|
|
return nil, err
|
|
}
|
|
return client, nil
|
|
})
|
|
}
|
|
|
|
func main() {
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
cfg, err := config.LoadValidated()
|
|
if err != nil {
|
|
fmt.Printf("[drosync-coordinator] invalid configuration: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
client, err := connectMongo(ctx, cfg.MongoURI, cfg.MongoConnectRetries, time.Duration(cfg.MongoConnectRetryDelayMS)*time.Millisecond)
|
|
if err != nil {
|
|
fmt.Printf("[drosync-coordinator] failed to connect mongo: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
defer client.Disconnect(context.Background())
|
|
dataStore := store.NewMongoStore(client.Database(cfg.MongoDB))
|
|
if err := dataStore.RunMigrations(ctx); err != nil {
|
|
fmt.Printf("[drosync-coordinator] failed to run migrations: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
if err := dataStore.EnsureIndexes(ctx); err != nil {
|
|
fmt.Printf("[drosync-coordinator] failed to ensure indexes: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
hostname, _ := os.Hostname()
|
|
coordinator, err := objectsync.NewCoordinator(dataStore, objectsync.BOSPublisher{GlobalEndpoint: cfg.GlobalBOSEndpoint}, hostname)
|
|
if err != nil {
|
|
fmt.Printf("[drosync-coordinator] initialization failed: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
if err := coordinator.ConfigureAuditSigning(cfg.ObjectSyncAuditSigningPrivateKey, cfg.ObjectSyncAuditSigningKeyID); err != nil {
|
|
fmt.Printf("[drosync-coordinator] invalid audit signing configuration: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
if cfg.ObjectSyncEnabled && !coordinator.AuditSigningConfigured() {
|
|
fmt.Println("[drosync-coordinator] DROSYNC_AUDIT_SIGNING_PRIVATE_KEY is required when object sync is enabled")
|
|
os.Exit(1)
|
|
}
|
|
if cfg.ObjectSyncEnabled {
|
|
go coordinator.Run(ctx, time.Duration(cfg.PollIntervalMS)*time.Millisecond)
|
|
}
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("/health", func(writer http.ResponseWriter, _ *http.Request) {
|
|
writer.Header().Set("Content-Type", "application/json")
|
|
_, _ = fmt.Fprintf(writer, `{"service":"drosync-coordinator","status":"ok","enabled":%t}`, cfg.ObjectSyncEnabled)
|
|
})
|
|
mux.HandleFunc("/ready", func(writer http.ResponseWriter, request *http.Request) {
|
|
writer.Header().Set("Content-Type", "application/json")
|
|
readyCtx, cancel := context.WithTimeout(request.Context(), 2*time.Second)
|
|
defer cancel()
|
|
if err := dataStore.Ready(readyCtx); err != nil {
|
|
writer.WriteHeader(http.StatusServiceUnavailable)
|
|
_, _ = fmt.Fprintf(writer, `{"ready":false,"enabled":%t}`, cfg.ObjectSyncEnabled)
|
|
return
|
|
}
|
|
_, _ = fmt.Fprintf(writer, `{"ready":true,"enabled":%t}`, cfg.ObjectSyncEnabled)
|
|
})
|
|
mux.HandleFunc("/metrics", func(writer http.ResponseWriter, _ *http.Request) {
|
|
writer.Header().Set("Content-Type", "text/plain; version=0.0.4")
|
|
metrics := coordinator.Metrics()
|
|
_, _ = fmt.Fprintf(
|
|
writer,
|
|
"drosync_coordinator_up 1\n"+
|
|
"drosync_coordinator_enabled %d\n"+
|
|
"drosync_coordinator_cycles_total %d\n"+
|
|
"drosync_coordinator_errors_total %d\n"+
|
|
"drosync_coordinator_sessions_planned_total %d\n"+
|
|
"drosync_coordinator_items_committed_total %d\n"+
|
|
"drosync_coordinator_staging_cleaned_total %d\n"+
|
|
"drosync_coordinator_reconciles_total %d\n"+
|
|
"drosync_coordinator_releases_total %d\n"+
|
|
"drosync_coordinator_audit_seals_total %d\n"+
|
|
"drosync_coordinator_last_cycle_timestamp_seconds %d\n"+
|
|
"drosync_coordinator_last_success_timestamp_seconds %d\n"+
|
|
"drosync_coordinator_cycle_duration_seconds %.3f\n",
|
|
boolMetric(cfg.ObjectSyncEnabled),
|
|
metrics.Cycles,
|
|
metrics.Errors,
|
|
metrics.Planned,
|
|
metrics.Committed,
|
|
metrics.Cleaned,
|
|
metrics.Reconciled,
|
|
metrics.Released,
|
|
metrics.Sealed,
|
|
metrics.LastCycle,
|
|
metrics.LastOK,
|
|
float64(metrics.DurationMS)/1000,
|
|
)
|
|
})
|
|
server := &http.Server{
|
|
Addr: fmt.Sprintf("0.0.0.0:%d", cfg.CoordinatorPort),
|
|
Handler: mux,
|
|
ReadHeaderTimeout: 10 * time.Second,
|
|
ReadTimeout: 30 * time.Second,
|
|
WriteTimeout: 30 * time.Second,
|
|
IdleTimeout: 2 * time.Minute,
|
|
}
|
|
serverErrors := make(chan error, 1)
|
|
go func() {
|
|
fmt.Printf("[drosync-coordinator] listening on http://0.0.0.0:%d\n", cfg.CoordinatorPort)
|
|
serverErrors <- server.ListenAndServe()
|
|
}()
|
|
select {
|
|
case err := <-serverErrors:
|
|
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
fmt.Printf("[drosync-coordinator] server failed: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
case <-ctx.Done():
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer cancel()
|
|
if err := server.Shutdown(shutdownCtx); err != nil {
|
|
fmt.Printf("[drosync-coordinator] graceful shutdown failed: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
}
|
|
|
|
func boolMetric(value bool) int {
|
|
if value {
|
|
return 1
|
|
}
|
|
return 0
|
|
}
|