Заменить lab4 на aws-sdk S3-вложения, уровень 4 и трек 2 reconciler.
Единый бинарник с objectstore/reconcile, pinned MinIO при недоступности Docker Hub, автотесты и evidence на оценку 5.
This commit is contained in:
+102
-54
@@ -1,14 +1,25 @@
|
||||
// Точка входа HTTP API и одноразового мигратора lab4.
|
||||
// Точка входа HTTP API, одноразового мигратора и reconciler (lab4).
|
||||
//
|
||||
// Режимы:
|
||||
//
|
||||
// (по умолчанию) — API-реплика: Postgres + Redis + S3, миграции НЕ применяет;
|
||||
// -migrate — применить SQL и выйти (S3 не нужен);
|
||||
// -healthcheck — локальный probe /health/ready.
|
||||
// (по умолчанию) — 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"
|
||||
@@ -21,15 +32,19 @@ import (
|
||||
|
||||
"mtusi2026lab4/internal/api"
|
||||
"mtusi2026lab4/internal/auth"
|
||||
"mtusi2026lab4/internal/blob"
|
||||
"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 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())
|
||||
@@ -53,49 +68,66 @@ func main() {
|
||||
}
|
||||
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()
|
||||
|
||||
s3cfg, err := config.LoadS3()
|
||||
if err != nil {
|
||||
log.Fatalf("s3 config: %v", err)
|
||||
}
|
||||
blobs, err := waitS3(rootCtx, s3cfg)
|
||||
if err != nil {
|
||||
log.Fatalf("s3: %v", err)
|
||||
// API стартует только при доступном S3 и существующем bucket; затем доступность
|
||||
// контролирует /health/ready (недоступный S3 → 503).
|
||||
if err := waitBucket(rootCtx, objects); err != nil {
|
||||
log.Fatalf("bucket: %v", err)
|
||||
}
|
||||
|
||||
srvAPI := api.New(st, sessions, blobs, cfg.InstanceID)
|
||||
srvAPI.MaxUploadBytes = cfg.MaxUploadBytes
|
||||
srvAPI.MaxImagePixels = cfg.MaxImagePixels
|
||||
|
||||
srvAPI := api.New(st, sessions, objects, cfg.InstanceID).WithUploadConcurrency(cfg.UploadMaxConcurrency)
|
||||
httpServer := &http.Server{
|
||||
Addr: cfg.Addr(),
|
||||
Handler: srvAPI.Handler(),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
// Upload до 10 MiB: даём запас на медленный клиент.
|
||||
ReadTimeout: 60 * time.Second,
|
||||
WriteTimeout: 60 * 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 bucket=%s",
|
||||
cfg.Addr(), cfg.Env, cfg.InstanceID, cfg.SessionTTL, cfg.MaxConns, s3cfg.Bucket)
|
||||
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
|
||||
}
|
||||
@@ -117,6 +149,54 @@ func main() {
|
||||
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
|
||||
@@ -159,38 +239,6 @@ func waitRedis(ctx context.Context, redisURL string, ttl time.Duration) (*sessio
|
||||
}
|
||||
}
|
||||
|
||||
func waitS3(ctx context.Context, cfg config.S3) (*blob.Client, error) {
|
||||
deadline := time.Now().Add(45 * time.Second)
|
||||
var last error
|
||||
for {
|
||||
c, err := blob.New(blob.Config{
|
||||
Endpoint: cfg.Endpoint,
|
||||
UseSSL: cfg.UseSSL,
|
||||
Region: cfg.Region,
|
||||
Bucket: cfg.Bucket,
|
||||
AccessKey: cfg.AccessKey,
|
||||
SecretKey: cfg.SecretKey,
|
||||
})
|
||||
if err == nil {
|
||||
if err = c.Ping(ctx); err == nil {
|
||||
return c, nil
|
||||
}
|
||||
last = err
|
||||
} else {
|
||||
last = err
|
||||
}
|
||||
if ctx.Err() != nil || time.Now().After(deadline) {
|
||||
return nil, last
|
||||
}
|
||||
log.Printf("s3 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 {
|
||||
|
||||
Reference in New Issue
Block a user