Единый бинарник с objectstore/reconcile, pinned MinIO при недоступности Docker Hub, автотесты и evidence на оценку 5.
263 lines
8.5 KiB
Go
263 lines
8.5 KiB
Go
// Точка входа HTTP API, одноразового мигратора и reconciler (lab4).
|
||
//
|
||
// Режимы:
|
||
//
|
||
// (по умолчанию) — API-реплика: ждёт Postgres/Redis/S3, слушает порт, миграции НЕ
|
||
// применяет (их гоняет отдельный сервис migrate, чтобы реплики не гонялись);
|
||
// -migrate — применить встроенные SQL, проверить наличие bucket, выйти с кодом 0/1;
|
||
// -healthcheck — локальный probe /health/ready для Docker HEALTHCHECK;
|
||
// -reconcile — сверка S3 и PostgreSQL: удалить orphan-объекты старше grace,
|
||
// отчитаться о missing-объектах (трек 2). Печатает JSON-отчёт;
|
||
// -reconcile-dry-run — то же, но ничего не удаляет (подразумевает -reconcile);
|
||
// -reconcile-prune-missing — дополнительно удалять СТАРЫЕ НЕИСПОЛЬЗУЕМЫЕ строки без объекта.
|
||
//
|
||
// Коды выхода -reconcile: 0 — успех, 1 — ошибка (S3/PG недоступны), 2 — найдены
|
||
// используемые вложения без объекта (потеря данных, нужен человек).
|
||
//
|
||
// SIGTERM: /health/ready → 503 (LB снимает реплику) и Shutdown до 10 секунд.
|
||
package main
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"flag"
|
||
"fmt"
|
||
"io"
|
||
"log"
|
||
"net/http"
|
||
"os"
|
||
"os/signal"
|
||
"syscall"
|
||
"time"
|
||
|
||
"mtusi2026lab4/internal/api"
|
||
"mtusi2026lab4/internal/auth"
|
||
"mtusi2026lab4/internal/config"
|
||
"mtusi2026lab4/internal/objectstore"
|
||
"mtusi2026lab4/internal/reconcile"
|
||
"mtusi2026lab4/internal/session"
|
||
"mtusi2026lab4/internal/store"
|
||
)
|
||
|
||
func main() {
|
||
healthcheck := flag.Bool("healthcheck", false, "probe local /health/ready and exit")
|
||
migrateOnly := flag.Bool("migrate", false, "apply SQL migrations, ensure bucket and exit")
|
||
doReconcile := flag.Bool("reconcile", false, "reconcile S3 objects with PostgreSQL attachments and exit")
|
||
reconcileDry := flag.Bool("reconcile-dry-run", false, "reconcile without deleting anything (implies -reconcile)")
|
||
reconcilePrune := flag.Bool("reconcile-prune-missing", false, "reconcile: also delete stale UNUSED rows whose object is missing")
|
||
flag.Parse()
|
||
if *healthcheck {
|
||
os.Exit(runHealthcheck())
|
||
}
|
||
|
||
cfg, err := config.Load()
|
||
if err != nil {
|
||
log.Fatalf("config: %v", err)
|
||
}
|
||
hasher, err := auth.NewHasher()
|
||
if err != nil {
|
||
log.Fatalf("password hasher: %v", err)
|
||
}
|
||
|
||
rootCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||
defer stop()
|
||
|
||
st, err := waitPostgres(rootCtx, cfg.DatabaseURL, hasher, cfg.MaxConns)
|
||
if err != nil {
|
||
log.Fatalf("postgres: %v", err)
|
||
}
|
||
defer st.Close()
|
||
|
||
objects, err := objectstore.New(objectstore.Config{
|
||
Endpoint: cfg.S3Endpoint,
|
||
Region: cfg.S3Region,
|
||
Bucket: cfg.S3Bucket,
|
||
AccessKey: cfg.S3AccessKey,
|
||
SecretKey: cfg.S3SecretKey,
|
||
ForcePathStyle: cfg.S3ForcePathStyle,
|
||
})
|
||
if err != nil {
|
||
log.Fatalf("object store: %v", err)
|
||
}
|
||
|
||
if *migrateOnly || cfg.RunMigrations {
|
||
if err := st.Migrate(rootCtx); err != nil {
|
||
log.Fatalf("migrate: %v", err)
|
||
}
|
||
log.Printf("migrations applied")
|
||
// Bucket создаёт minio-init (root-учётка). Здесь только идемпотентная проверка:
|
||
// мигратор падает с понятной причиной, если стенд поднят без minio-init.
|
||
if err := waitBucket(rootCtx, objects); err != nil {
|
||
log.Fatalf("bucket: %v", err)
|
||
}
|
||
log.Printf("bucket %q is available", objects.Bucket())
|
||
if *migrateOnly {
|
||
return
|
||
}
|
||
}
|
||
|
||
if *doReconcile || *reconcileDry {
|
||
os.Exit(runReconcile(rootCtx, st, objects, cfg, *reconcileDry, *reconcilePrune))
|
||
}
|
||
|
||
sessions, err := waitRedis(rootCtx, cfg.RedisURL, cfg.SessionTTL)
|
||
if err != nil {
|
||
log.Fatalf("redis: %v", err)
|
||
}
|
||
defer sessions.Close()
|
||
|
||
// API стартует только при доступном S3 и существующем bucket; затем доступность
|
||
// контролирует /health/ready (недоступный S3 → 503).
|
||
if err := waitBucket(rootCtx, objects); err != nil {
|
||
log.Fatalf("bucket: %v", err)
|
||
}
|
||
|
||
srvAPI := api.New(st, sessions, objects, cfg.InstanceID).WithUploadConcurrency(cfg.UploadMaxConcurrency)
|
||
httpServer := &http.Server{
|
||
Addr: cfg.Addr(),
|
||
Handler: srvAPI.Handler(),
|
||
ReadHeaderTimeout: 5 * time.Second,
|
||
// 10 MiB загрузка/скачивание по медленному клиенту дольше обычного JSON-запроса.
|
||
// Лимиты размера и семафор слотов не дают этому стать способом занять RAM.
|
||
ReadTimeout: 30 * time.Second,
|
||
WriteTimeout: 30 * time.Second,
|
||
IdleTimeout: 60 * time.Second,
|
||
}
|
||
|
||
errCh := make(chan error, 1)
|
||
go func() {
|
||
log.Printf("listening on %s env=%s instance=%s session_ttl=%s db_max_conns=%d",
|
||
cfg.Addr(), cfg.Env, cfg.InstanceID, cfg.SessionTTL, cfg.MaxConns)
|
||
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||
errCh <- err
|
||
}
|
||
}()
|
||
|
||
select {
|
||
case err := <-errCh:
|
||
log.Fatalf("listen: %v", err)
|
||
case <-rootCtx.Done():
|
||
}
|
||
log.Printf("shutting down instance=%s", cfg.InstanceID)
|
||
srvAPI.BeginDrain()
|
||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||
defer cancel()
|
||
if err := httpServer.Shutdown(ctx); err != nil {
|
||
log.Printf("shutdown error: %v", err)
|
||
os.Exit(1)
|
||
}
|
||
log.Printf("shutdown complete")
|
||
}
|
||
|
||
// waitBucket ждёт S3 и идемпотентно проверяет bucket (до 45 с, как и для Postgres/Redis).
|
||
func waitBucket(ctx context.Context, objects *objectstore.Store) error {
|
||
deadline := time.Now().Add(45 * time.Second)
|
||
var last error
|
||
for {
|
||
last = objects.EnsureBucket(ctx)
|
||
if last == nil {
|
||
return nil
|
||
}
|
||
if ctx.Err() != nil || time.Now().After(deadline) {
|
||
return last
|
||
}
|
||
log.Printf("object store not ready, retrying")
|
||
select {
|
||
case <-ctx.Done():
|
||
return ctx.Err()
|
||
case <-time.After(time.Second):
|
||
}
|
||
}
|
||
}
|
||
|
||
// runReconcile — режим трека 2. Отчёт JSON — в stdout (годится для evidence), подробности — в лог.
|
||
func runReconcile(ctx context.Context, st *store.Store, objects *objectstore.Store, cfg config.Config, dry, prune bool) int {
|
||
rc := &reconcile.Reconciler{
|
||
DB: st,
|
||
Objects: objects,
|
||
Opts: reconcile.Options{
|
||
DryRun: dry,
|
||
Grace: cfg.S3OrphanGrace,
|
||
PruneMissing: prune,
|
||
Logf: log.Printf,
|
||
},
|
||
}
|
||
log.Printf("reconcile start dry_run=%t grace=%s prune_missing=%t", dry, cfg.S3OrphanGrace, prune)
|
||
rep, err := rc.Run(ctx)
|
||
out, _ := json.MarshalIndent(rep, "", " ")
|
||
fmt.Println(string(out))
|
||
if err != nil {
|
||
log.Printf("reconcile failed: %v", err)
|
||
return 1
|
||
}
|
||
if rep.MissingUsed > 0 {
|
||
log.Printf("reconcile: %d used attachment(s) lost their object, manual action required", rep.MissingUsed)
|
||
return 2
|
||
}
|
||
return 0
|
||
}
|
||
|
||
func waitPostgres(ctx context.Context, dsn string, hasher *auth.Hasher, maxConns int32) (*store.Store, error) {
|
||
deadline := time.Now().Add(45 * time.Second)
|
||
var last error
|
||
for {
|
||
st, err := store.Open(ctx, dsn, hasher, maxConns)
|
||
if err == nil {
|
||
return st, nil
|
||
}
|
||
last = err
|
||
if ctx.Err() != nil || time.Now().After(deadline) {
|
||
return nil, last
|
||
}
|
||
log.Printf("postgres not ready, retrying")
|
||
select {
|
||
case <-ctx.Done():
|
||
return nil, ctx.Err()
|
||
case <-time.After(time.Second):
|
||
}
|
||
}
|
||
}
|
||
|
||
func waitRedis(ctx context.Context, redisURL string, ttl time.Duration) (*session.Store, error) {
|
||
deadline := time.Now().Add(45 * time.Second)
|
||
var last error
|
||
for {
|
||
st, err := session.Open(redisURL, ttl)
|
||
if err == nil {
|
||
return st, nil
|
||
}
|
||
last = err
|
||
if ctx.Err() != nil || time.Now().After(deadline) {
|
||
return nil, last
|
||
}
|
||
log.Printf("redis not ready, retrying")
|
||
select {
|
||
case <-ctx.Done():
|
||
return nil, ctx.Err()
|
||
case <-time.After(time.Second):
|
||
}
|
||
}
|
||
}
|
||
|
||
func runHealthcheck() int {
|
||
cfg, err := config.Load()
|
||
if err != nil {
|
||
return 1
|
||
}
|
||
host := cfg.Host
|
||
if host == "0.0.0.0" || host == "::" {
|
||
host = "127.0.0.1"
|
||
}
|
||
client := &http.Client{Timeout: 2 * time.Second}
|
||
resp, err := client.Get(fmt.Sprintf("http://%s:%d/health/ready", host, cfg.Port))
|
||
if err != nil {
|
||
return 1
|
||
}
|
||
defer resp.Body.Close()
|
||
_, _ = io.Copy(io.Discard, resp.Body)
|
||
if resp.StatusCode != http.StatusOK {
|
||
return 1
|
||
}
|
||
return 0
|
||
}
|