Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
166 lines (154 loc) · 5.19 KB
/
Copy pathmain.go
File metadata and controls
166 lines (154 loc) · 5.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
package main
import (
"context"
"fmt"
"log"
"log/slog"
"net/http"
"net/url"
"os"
"os/signal"
"sync/atomic"
"syscall"
"time"
"github.com/hashicorp/go-cleanhttp"
"github.com/hekmon/httplog/v3"
autoslog "github.com/iguanesolutions/auto-slog/v2"
sysd "github.com/iguanesolutions/go-systemd/v6"
sysdnotify "github.com/iguanesolutions/go-systemd/v6/notify"
)
const (
stopTimeout = 3 * time.Minute
)
var (
logger *slog.Logger
modifiedRequests atomic.Int64
)
func main() {
cfg, err := LoadConfig()
if err != nil {
log.Fatalf("load config: %s\n", err)
}
// Init
logger = autoslog.NewLogger(slog.HandlerOptions{
AddSource: true,
Level: parseLogLevel(cfg.LogLevel),
})
// Warn if COMPLETE log level is enabled
if cfg.LogLevel == COMPLETE_LEVEL {
logger.Warn("COMPLETE log level enabled - full request/response bodies will be logged, including potentially sensitive data",
slog.String("log_level", cfg.LogLevel),
)
}
backendURL, err := url.Parse(cfg.Target)
if err != nil {
logger.Error("failed to parse backend URL", slog.Any("error", err))
os.Exit(1)
}
// Define HTTP handlers and middleware
httplogger := httplog.New(logger, &httplog.Config{
RequestDumpLogLevel: COMPLETE,
ResponseDumpLogLevel: COMPLETE,
})
// Create pooled HTTP client for forwarding requests
httpClient := cleanhttp.DefaultPooledClient()
// Explicit handlers for POST paths that need transformation
http.HandleFunc("POST /tokenize", httplogger.LogFunc(
tokenize(httpClient, backendURL,
cfg.ServedModelName, cfg.ThinkingGeneralModel, cfg.ThinkingCodingModel,
cfg.InstructGeneralModel, cfg.InstructReasoningModel,
),
))
http.HandleFunc("POST /v1/responses", httplogger.LogFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w,
"responses endpoint on vLLM does not support kwargs to activate Qwen profiles",
http.StatusNotImplemented,
)
}))
http.HandleFunc("POST /v1/chat/completions", httplogger.LogFunc(
transform(httpClient, backendURL,
cfg.ServedModelName, cfg.ThinkingGeneralModel, cfg.ThinkingCodingModel,
cfg.InstructGeneralModel, cfg.InstructReasoningModel, cfg.EnforceSamplingParams,
),
))
http.HandleFunc("POST /v1/completions", httplogger.LogFunc(
legacyCompletions(httpClient, backendURL,
cfg.ServedModelName, cfg.ThinkingGeneralModel, cfg.ThinkingCodingModel,
cfg.InstructGeneralModel, cfg.InstructReasoningModel,
),
))
// Models endpoint handler (enriches backend models with virtual model names)
http.HandleFunc("GET /v1/models", httplogger.LogFunc(
models(httpClient, backendURL,
cfg.ServedModelName, cfg.ThinkingGeneralModel, cfg.ThinkingCodingModel,
cfg.InstructGeneralModel, cfg.InstructReasoningModel),
))
// Health check endpoints (not logged)
http.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status":"healthy"}`))
})
// Catch-all for all other paths (passthrough)
http.HandleFunc("/", httplogger.LogFunc(passthrough(httpClient, backendURL)))
// Prepare HTTP server and clean stop
server := &http.Server{Addr: fmt.Sprintf("%s:%d", cfg.Listen, cfg.Port)}
signalStopCtx, signalStopCtxCancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer signalStopCtxCancel()
go cleanStop(signalStopCtx, server)
// Handle systemd if needed
if invocationID, sysdStarted := sysd.GetInvocationID(); sysdStarted {
logger.Info("systemd detected, activating systemd integration",
slog.String("invocation_id", invocationID),
)
go systemdIntegration(signalStopCtx, httplogger)
} else {
logger.Debug("systemd not detected, skipping systemd integration")
}
// Start server
logger.Info("starting reverse proxy server",
slog.String("listen", cfg.Listen),
slog.Int("port", cfg.Port),
slog.String("target", backendURL.String()),
)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Error("failed to start HTTP server", "err", err)
os.Exit(1)
}
}
func systemdIntegration(signalStopCtx context.Context, httplogger *httplog.Logger) {
var err error
if err = sysdnotify.Ready(); err != nil {
logger.Error("failed to send systemd ready notification", "err", err)
}
sysdUpdateTicker := time.NewTicker(time.Minute)
defer sysdUpdateTicker.Stop()
for {
select {
case <-sysdUpdateTicker.C:
logger.Debug("sending systemd status notification")
if err = sysdnotify.Status(fmt.Sprintf("Modified %d requests on the %d proxified",
modifiedRequests.Load(),
httplogger.TotalRequests(),
)); err != nil {
logger.Error("failed to send systemd status notification", "err", err)
}
case <-signalStopCtx.Done():
if err = sysdnotify.Stopping(); err != nil {
logger.Error("failed to send systemd stopping notification", "err", err)
}
return
}
}
}
func cleanStop(signalStopCtx context.Context, server *http.Server) {
<-signalStopCtx.Done()
logger.Info("shutting down HTTP server...",
slog.Duration("grace_period", stopTimeout),
)
ctx, cancel := context.WithTimeout(context.Background(), stopTimeout)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
logger.Error("failed to shutdown HTTP server properly", "err", err)
}
}