forked from mtusi2026/mtusi2026lab5
lab5 na4
This commit is contained in:
+133
@@ -0,0 +1,133 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"mtusi2026/internal/blobstore"
|
||||
"mtusi2026/internal/cache"
|
||||
"mtusi2026/internal/config"
|
||||
"mtusi2026/internal/db"
|
||||
"mtusi2026/internal/httpapi"
|
||||
"mtusi2026/internal/sessionstore"
|
||||
"mtusi2026/internal/store"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func main() {
|
||||
ctx := context.Background()
|
||||
|
||||
dbCfg := db.Config{
|
||||
DSN: config.GetEnv("DATABASE_URL", ""),
|
||||
MaxConns: int32(config.ParseIntEnv("DB_MAX_CONNS", 10)),
|
||||
MinConns: int32(config.ParseIntEnv("DB_MIN_CONNS", 2)),
|
||||
ConnMaxLifetime: config.ParseDurationSecondsEnv("DB_CONN_MAX_LIFETIME_SECONDS", 3600),
|
||||
ConnTimeout: config.ParseDurationSecondsEnv("DB_CONN_TIMEOUT_SECONDS", 5),
|
||||
}
|
||||
if dbCfg.DSN == "" {
|
||||
log.Fatal("DATABASE_URL is required")
|
||||
}
|
||||
|
||||
pool, err := db.Connect(ctx, dbCfg)
|
||||
if err != nil {
|
||||
log.Fatalf("db connect: %v", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
maxMessages := int64(config.ParseIntEnv("MAX_MESSAGES", 10000))
|
||||
maxConcurrent := config.ParseIntEnv("MAX_CONCURRENT_REQUESTS", 50)
|
||||
|
||||
limiter := store.NewLimiter(maxMessages, maxConcurrent)
|
||||
|
||||
cacheURL := config.GetEnv("CACHE_URL", "")
|
||||
if cacheURL == "" {
|
||||
log.Fatal("CACHE_URL is required")
|
||||
}
|
||||
|
||||
redisOpts, err := redis.ParseURL(cacheURL)
|
||||
if err != nil {
|
||||
log.Fatalf("redis config: %v", err)
|
||||
}
|
||||
|
||||
redisClient := redis.NewClient(redisOpts)
|
||||
defer redisClient.Close()
|
||||
|
||||
if err := redisClient.Ping(ctx).Err(); err != nil {
|
||||
log.Fatalf("redis connect: %v", err)
|
||||
}
|
||||
|
||||
sessionStore := sessionstore.NewRedis(redisClient)
|
||||
|
||||
chatCacheTTL := config.ParseDurationSecondsEnv("CHAT_CACHE_TTL_SECONDS", 30)
|
||||
chatCache := cache.New(redisClient, chatCacheTTL)
|
||||
|
||||
s := store.New(pool, limiter)
|
||||
|
||||
instanceID := config.GetEnv("INSTANCE_ID", "")
|
||||
if instanceID == "" {
|
||||
instanceID, _ = os.Hostname()
|
||||
}
|
||||
var draining atomic.Bool
|
||||
|
||||
var blobs blobstore.Store
|
||||
if ep := config.GetEnv("S3_ENDPOINT", ""); ep != "" {
|
||||
b, err := blobstore.NewS3(ctx, blobstore.S3Config{
|
||||
Endpoint: ep,
|
||||
Region: config.GetEnv("S3_REGION", "us-east-1"),
|
||||
Bucket: config.GetEnv("S3_BUCKET", ""),
|
||||
AccessKey: config.GetEnv("S3_ACCESS_KEY", ""),
|
||||
SecretKey: config.GetEnv("S3_SECRET_KEY", ""),
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("s3 config: %v", err)
|
||||
}
|
||||
blobs = b
|
||||
}
|
||||
|
||||
mux := httpapi.NewRouterWithCache(s, pool, sessionStore, chatCache, httpapi.Options{
|
||||
InstanceID: instanceID,
|
||||
Redis: redisClient,
|
||||
Draining: &draining,
|
||||
Blobs: blobs,
|
||||
MaxUploads: config.ParseIntEnv("MAX_UPLOADS", 4),
|
||||
})
|
||||
|
||||
port := config.GetEnv("PORT", "8080")
|
||||
srv := &http.Server{
|
||||
Addr: ":" + port,
|
||||
Handler: mux,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 60 * time.Second,
|
||||
WriteTimeout: 60 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer stop()
|
||||
|
||||
go func() {
|
||||
log.Printf("запуск на :%s instance=%s", port, instanceID)
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalf("сервер упал: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
<-ctx.Done()
|
||||
log.Println("Получен сигнал остановки: readiness -> 503, жду LB...")
|
||||
draining.Store(true)
|
||||
time.Sleep(time.Duration(config.ParseIntEnv("DRAIN_SECONDS", 4)) * time.Second)
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
log.Printf("принудительное завершение: %v", err)
|
||||
}
|
||||
log.Println("Остановлен")
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"mtusi2026/internal/blobstore"
|
||||
"mtusi2026/internal/config"
|
||||
"mtusi2026/internal/db"
|
||||
"mtusi2026/internal/reconcile"
|
||||
)
|
||||
|
||||
func main() {
|
||||
dry := flag.Bool("dry-run", false, "only report orphans, delete nothing")
|
||||
grace := flag.Duration("grace", time.Hour, "do not touch objects younger than this")
|
||||
loop := flag.Duration("loop", 0, "repeat with this interval; 0 = run once")
|
||||
missing := flag.Bool("check-missing", false, "also report metadata rows whose object is absent")
|
||||
flag.Parse()
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer stop()
|
||||
|
||||
pool, err := db.Connect(ctx, db.Config{
|
||||
DSN: config.GetEnv("DATABASE_URL", ""), MaxConns: 2, MinConns: 0,
|
||||
ConnMaxLifetime: time.Hour, ConnTimeout: 5 * time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("db: %v", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
blobs, err := blobstore.NewS3(ctx, blobstore.S3Config{
|
||||
Endpoint: config.GetEnv("S3_ENDPOINT", ""), Region: config.GetEnv("S3_REGION", "us-east-1"),
|
||||
Bucket: config.GetEnv("S3_BUCKET", ""), AccessKey: config.GetEnv("S3_ACCESS_KEY", ""),
|
||||
SecretKey: config.GetEnv("S3_SECRET_KEY", ""),
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("s3: %v", err)
|
||||
}
|
||||
|
||||
for {
|
||||
start := time.Now()
|
||||
rep, err := reconcile.Run(ctx, pool, blobs, *grace, *dry, *missing, log.Printf)
|
||||
log.Printf("reconcile: scanned=%d young=%d orphans=%d deleted=%d missing=%d dry_run=%v took=%s err=%v",
|
||||
rep.Scanned, rep.Young, rep.Orphans, rep.Deleted, rep.Missing, *dry, time.Since(start).Round(time.Millisecond), err)
|
||||
if *loop == 0 {
|
||||
if err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(*loop):
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"mtusi2026/internal/blobstore"
|
||||
"mtusi2026/internal/config"
|
||||
"mtusi2026/internal/jobs"
|
||||
)
|
||||
|
||||
func main() {
|
||||
mode := flag.String("mode", "worker", "worker | relay | failed | replay")
|
||||
id := flag.String("job", "", "failed job UUID")
|
||||
reason := flag.String("reason", "", "audited replay reason (required)")
|
||||
flag.Parse()
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer stop()
|
||||
pool, err := pgxpool.New(ctx, config.GetEnv("DATABASE_URL", ""))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
timeout := config.ParseDurationSecondsEnv("JOB_TIMEOUT_SECONDS", 30)
|
||||
concurrency := config.ParseIntEnv("WORKER_CONCURRENCY", 1)
|
||||
attempts := config.ParseIntEnv("JOB_MAX_ATTEMPTS", 5)
|
||||
if concurrency < 1 || concurrency > 4 || attempts < 1 || timeout < time.Second || timeout > 5*time.Minute {
|
||||
log.Fatal("invalid worker limits")
|
||||
}
|
||||
repo := jobs.Repo{Pool: pool, MaxAttempts: attempts, Lease: timeout + 10*time.Second}
|
||||
if *mode == "failed" {
|
||||
rows, err := repo.Failed(ctx)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
json.NewEncoder(os.Stdout).Encode(rows)
|
||||
return
|
||||
}
|
||||
if *mode == "replay" {
|
||||
if strings.TrimSpace(*reason) == "" {
|
||||
log.Fatal("reason is required")
|
||||
}
|
||||
if err := repo.Replay(ctx, *id, *reason); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
log.Printf("replay queued job=%s", *id)
|
||||
return
|
||||
}
|
||||
opts, err := redis.ParseURL(config.GetEnv("BROKER_URL", "redis://broker:6379/0"))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
broker := redis.NewClient(opts)
|
||||
defer broker.Close()
|
||||
blobs, err := blobstore.NewS3(ctx, blobstore.S3Config{Endpoint: config.GetEnv("S3_ENDPOINT", ""), Region: config.GetEnv("S3_REGION", "us-east-1"), Bucket: config.GetEnv("S3_BUCKET", ""), AccessKey: config.GetEnv("S3_ACCESS_KEY", ""), SecretKey: config.GetEnv("S3_SECRET_KEY", "")})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
rt := jobs.Runtime{Repo: repo, Broker: broker, Blobs: blobs, Concurrency: concurrency, Timeout: timeout, Retention: config.ParseDurationSecondsEnv("STAGING_RETENTION_SECONDS", 86400), Fault: config.GetEnv("PIPELINE_FAULT", "")}
|
||||
log.Printf("pipeline mode=%s concurrency=%d prefetch=1 timeout=%s lease=%s attempts=%d", *mode, concurrency, timeout, repo.Lease, attempts)
|
||||
switch *mode {
|
||||
case "worker":
|
||||
if err := rt.Workers(ctx); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
case "relay":
|
||||
rt.Relay(ctx)
|
||||
default:
|
||||
log.Fatal("unknown mode")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user