|
| 1 | +/* |
| 2 | +Copyright 2025 The llm-d Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package proxy |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "encoding/json" |
| 22 | + "fmt" |
| 23 | + "io" |
| 24 | + "net" |
| 25 | + "net/http" |
| 26 | + "net/http/httputil" |
| 27 | + "net/url" |
| 28 | + "sync" |
| 29 | + "sync/atomic" |
| 30 | + "time" |
| 31 | + |
| 32 | + "k8s.io/klog/v2" |
| 33 | +) |
| 34 | + |
| 35 | +// ConfigRequest is the request body to configure the proxy target |
| 36 | +type ConfigRequest struct { |
| 37 | + Address string `json:"address"` |
| 38 | + Port int `json:"port"` |
| 39 | +} |
| 40 | + |
| 41 | +// proxy is a lazy HTTP reverse proxy that only starts after receiving |
| 42 | +// the first configuration request |
| 43 | +type proxy struct { |
| 44 | + mu sync.RWMutex |
| 45 | + targetURL *url.URL |
| 46 | + proxy *httputil.ReverseProxy |
| 47 | + initialized atomic.Bool |
| 48 | +} |
| 49 | + |
| 50 | +// singleton instance initialized once at startup |
| 51 | +var instance = &proxy{} |
| 52 | + |
| 53 | +// Run starts the proxy server on the given port |
| 54 | +func Run(ctx context.Context, port string) error { |
| 55 | + logger := klog.FromContext(ctx).WithName("proxy-server") |
| 56 | + logger.Info("starting proxy server") |
| 57 | + |
| 58 | + mux := http.NewServeMux() |
| 59 | + mux.HandleFunc("/", serveProxy) |
| 60 | + |
| 61 | + server := &http.Server{ |
| 62 | + Addr: fmt.Sprintf(":%s", port), |
| 63 | + Handler: mux, |
| 64 | + ReadTimeout: 30 * time.Second, |
| 65 | + WriteTimeout: 5 * time.Minute, // Long timeout for inference requests |
| 66 | + IdleTimeout: 120 * time.Second, |
| 67 | + } |
| 68 | + |
| 69 | + go func() { |
| 70 | + <-ctx.Done() |
| 71 | + logger.Info("shutting down") |
| 72 | + |
| 73 | + ctx, cancelFn := context.WithTimeout(context.Background(), 60*time.Second) |
| 74 | + defer cancelFn() |
| 75 | + if err := server.Shutdown(ctx); err != nil { |
| 76 | + logger.Error(err, "failed to gracefully shutdown") |
| 77 | + } |
| 78 | + }() |
| 79 | + |
| 80 | + logger.Info("starting server", "port", port) |
| 81 | + if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { |
| 82 | + return fmt.Errorf("listen and serve error: %w", err) |
| 83 | + } |
| 84 | + |
| 85 | + logger.Info("server stopped") |
| 86 | + return nil |
| 87 | +} |
| 88 | + |
| 89 | +// serveProxy proxies requests to the target server |
| 90 | +func serveProxy(w http.ResponseWriter, r *http.Request) { |
| 91 | + if !instance.initialized.Load() { |
| 92 | + http.Error(w, "proxy not initialized", http.StatusServiceUnavailable) |
| 93 | + return |
| 94 | + } |
| 95 | + |
| 96 | + // Proxy the request |
| 97 | + instance.proxy.ServeHTTP(w, r) |
| 98 | +} |
| 99 | + |
| 100 | +// Initialize handles proxy initialization and configuration |
| 101 | +func Initialize(w http.ResponseWriter, r *http.Request) { |
| 102 | + // Get proxy status |
| 103 | + if r.Method == http.MethodGet { |
| 104 | + if instance.initialized.Load() { |
| 105 | + targetURL := instance.targetURL |
| 106 | + w.WriteHeader(http.StatusOK) |
| 107 | + if targetURL != nil { |
| 108 | + fmt.Fprintf(w, "proxying to %s", targetURL) |
| 109 | + } else { |
| 110 | + _, _ = w.Write([]byte("proxy initialized but targetURL is nil")) |
| 111 | + } |
| 112 | + } else { |
| 113 | + w.WriteHeader(http.StatusOK) |
| 114 | + _, _ = w.Write([]byte("proxy not initialized")) |
| 115 | + } |
| 116 | + return |
| 117 | + } |
| 118 | + |
| 119 | + if r.Method != http.MethodPost { |
| 120 | + http.Error(w, "invalid method", http.StatusMethodNotAllowed) |
| 121 | + return |
| 122 | + } |
| 123 | + |
| 124 | + // Try initialize server |
| 125 | + if instance.initialized.Load() { |
| 126 | + http.Error(w, "proxy already initialized", http.StatusConflict) |
| 127 | + return |
| 128 | + } |
| 129 | + |
| 130 | + // Need to initialize - acquire write lock |
| 131 | + instance.mu.Lock() |
| 132 | + defer instance.mu.Unlock() |
| 133 | + |
| 134 | + // Double-check after acquiring write lock |
| 135 | + if instance.initialized.Load() { |
| 136 | + http.Error(w, "proxy already initialized", http.StatusConflict) |
| 137 | + return |
| 138 | + } |
| 139 | + |
| 140 | + // Parse configuration from request body |
| 141 | + body, err := io.ReadAll(r.Body) |
| 142 | + if err != nil { |
| 143 | + http.Error(w, fmt.Sprintf("failed to read request body: %v", err), http.StatusBadRequest) |
| 144 | + return |
| 145 | + } |
| 146 | + defer r.Body.Close() |
| 147 | + |
| 148 | + var config ConfigRequest |
| 149 | + if err := json.Unmarshal(body, &config); err != nil { |
| 150 | + http.Error(w, fmt.Sprintf("failed to parse JSON: %v", err), http.StatusBadRequest) |
| 151 | + return |
| 152 | + } |
| 153 | + |
| 154 | + if config.Address == "" { |
| 155 | + http.Error(w, "address is required", http.StatusBadRequest) |
| 156 | + return |
| 157 | + } |
| 158 | + |
| 159 | + if config.Port <= 0 || config.Port > 65535 { |
| 160 | + http.Error(w, "invalid port", http.StatusBadRequest) |
| 161 | + return |
| 162 | + } |
| 163 | + |
| 164 | + // Create target URL |
| 165 | + targetURL := &url.URL{ |
| 166 | + Scheme: "http", |
| 167 | + Host: net.JoinHostPort(config.Address, fmt.Sprintf("%d", config.Port)), |
| 168 | + } |
| 169 | + |
| 170 | + // Create the reverse proxy |
| 171 | + instance.targetURL = targetURL |
| 172 | + instance.proxy = httputil.NewSingleHostReverseProxy(targetURL) |
| 173 | + |
| 174 | + // Customize error handling |
| 175 | + originalErrorHandler := instance.proxy.ErrorHandler |
| 176 | + instance.proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) { |
| 177 | + if originalErrorHandler != nil { |
| 178 | + originalErrorHandler(w, r, err) |
| 179 | + } else { |
| 180 | + http.Error(w, fmt.Sprintf("proxy error: %v", err), http.StatusBadGateway) |
| 181 | + } |
| 182 | + } |
| 183 | + |
| 184 | + instance.initialized.Store(true) |
| 185 | + w.WriteHeader(http.StatusOK) |
| 186 | + fmt.Fprintf(w, "initialized proxy to: %s", targetURL) |
| 187 | +} |
0 commit comments