| 1 |
/* |
| 2 |
Copyright 2019 The Kubernetes 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 server |
| 18 |
|
| 19 |
import ( |
| 20 |
"errors" |
| 21 |
"fmt" |
| 22 |
"io" |
| 23 |
"math/rand" |
| 24 |
"net/http" |
| 25 |
"sync" |
| 26 |
"time" |
| 27 |
|
| 28 |
"k8s.io/klog/v2" |
| 29 |
"sigs.k8s.io/apiserver-network-proxy/konnectivity-client/proto/client" |
| 30 |
"sigs.k8s.io/apiserver-network-proxy/pkg/server/metrics" |
| 31 |
) |
| 32 |
|
| 33 |
const ( |
| 34 |
// bufferSize is the size of the buffer used for reading from the hijacked connection. |
| 35 |
// It matches the gRPC window size for optimal performance. |
| 36 |
bufferSize = 1 << 15 // 32KB |
| 37 |
) |
| 38 |
|
| 39 |
// bufferPool is a pool of byte slices used for reading data from hijacked connections. |
| 40 |
// This reduces memory allocations and GC pressure by reusing buffers across connections. |
| 41 |
var bufferPool = sync.Pool{ |
| 42 |
New: func() interface{} { |
| 43 |
// Allocate a new buffer when the pool is empty |
| 44 |
buf := make([]byte, bufferSize) |
| 45 |
return &buf |
| 46 |
}, |
| 47 |
} |
| 48 |
|
| 49 |
// Tunnel implements Proxy based on HTTP Connect, which tunnels the traffic to |
| 50 |
// the agent registered in ProxyServer. |
| 51 |
type Tunnel struct { |
| 52 |
Server *ProxyServer |
| 53 |
} |
| 54 |
|
| 55 |
func (t *Tunnel) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 56 |
metrics.Metrics.HTTPConnectionInc() |
| 57 |
defer metrics.Metrics.HTTPConnectionDec() |
| 58 |
|
| 59 |
klog.V(2).InfoS("Received request for host", "method", r.Method, "host", r.Host, "userAgent", r.UserAgent()) |
| 60 |
if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 { |
| 61 |
klog.V(2).InfoS("TLS", "commonName", r.TLS.PeerCertificates[0].Subject.CommonName) |
| 62 |
} |
| 63 |
if r.Method != http.MethodConnect { |
| 64 |
http.Error(w, "this proxy only supports CONNECT passthrough", http.StatusMethodNotAllowed) |
| 65 |
return |
| 66 |
} |
| 67 |
|
| 68 |
hijacker, ok := w.(http.Hijacker) |
| 69 |
if !ok { |
| 70 |
http.Error(w, "hijacking not supported", http.StatusInternalServerError) |
| 71 |
return |
| 72 |
} |
| 73 |
|
| 74 |
conn, bufrw, err := hijacker.Hijack() |
| 75 |
if err != nil { |
| 76 |
http.Error(w, err.Error(), http.StatusInternalServerError) |
| 77 |
return |
| 78 |
} |
| 79 |
|
| 80 |
var closeOnce sync.Once |
| 81 |
defer closeOnce.Do(func() { conn.Close() }) |
| 82 |
|
| 83 |
random := rand.Int63() /* #nosec G404 */ |
| 84 |
dialRequest := &client.Packet{ |
| 85 |
Type: client.PacketType_DIAL_REQ, |
| 86 |
Payload: &client.Packet_DialRequest{ |
| 87 |
DialRequest: &client.DialRequest{ |
| 88 |
Protocol: "tcp", |
| 89 |
Address: r.Host, |
| 90 |
Random: random, |
| 91 |
}, |
| 92 |
}, |
| 93 |
} |
| 94 |
|
| 95 |
klog.V(4).Infof("Set pending(rand=%d) to %v", random, w) |
| 96 |
backend, err := t.Server.getBackend(r.Host) |
| 97 |
if err != nil { |
| 98 |
klog.ErrorS(err, "no tunnels available") |
| 99 |
conn.Write([]byte(fmt.Sprintf("HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/plain\r\n\r\ncurrently no tunnels available: %v", err))) |
| 100 |
// The hijacked connection will be closed by the closeOnce defer. |
| 101 |
return |
| 102 |
} |
| 103 |
closed := make(chan struct{}) |
| 104 |
connected := make(chan struct{}) |
| 105 |
connection := &ProxyClientConnection{ |
| 106 |
Mode: ModeHTTPConnect, |
| 107 |
HTTP: io.ReadWriter(conn), // pass as ReadWriter so the caller must close with CloseHTTP |
| 108 |
CloseHTTP: func() error { |
| 109 |
closeOnce.Do(func() { conn.Close() }) |
| 110 |
close(closed) |
| 111 |
return nil |
| 112 |
}, |
| 113 |
connected: connected, |
| 114 |
start: time.Now(), |
| 115 |
backend: backend, |
| 116 |
dialID: random, |
| 117 |
agentID: backend.GetAgentID(), |
| 118 |
} |
| 119 |
t.Server.PendingDial.Add(random, connection) |
| 120 |
|
| 121 |
// This defer acts as a safeguard to ensure we clean up the pending dial |
| 122 |
// if the connection is never successfully established. |
| 123 |
established := false |
| 124 |
dialFailureObserved := false |
| 125 |
defer func() { |
| 126 |
if !established { |
| 127 |
if t.Server.PendingDial.Remove(random) != nil { |
| 128 |
if !dialFailureObserved { |
| 129 |
metrics.Metrics.ObserveDialFailure(metrics.DialFailureFrontendClose) |
| 130 |
} |
| 131 |
} |
| 132 |
} |
| 133 |
}() |
| 134 |
|
| 135 |
if err := t.Server.sendDialRequestToBackend(backend, dialRequest); err != nil { |
| 136 |
klog.ErrorS(err, "failed to tunnel dial request", "host", r.Host, "dialID", connection.dialID, "agentID", connection.agentID) |
| 137 |
dialFailureObserved = true |
| 138 |
statusCode := http.StatusBadGateway |
| 139 |
reason := metrics.DialFailureBackendClose |
| 140 |
if errors.Is(err, errBackendDialTimeout) { |
| 141 |
statusCode = http.StatusGatewayTimeout |
| 142 |
reason = metrics.DialFailureBackendDialTimeout |
| 143 |
} |
| 144 |
metrics.Metrics.ObserveDialFailure(reason) |
| 145 |
statusText := http.StatusText(statusCode) |
| 146 |
conn.Write([]byte(fmt.Sprintf("HTTP/1.1 %d %s\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nFailed to tunnel dial request: %v\r\n", statusCode, statusText, err))) |
| 147 |
// The deferred cleanup will run when we return here. |
| 148 |
return |
| 149 |
} |
| 150 |
|
| 151 |
ctxt := backend.Context() |
| 152 |
var timeoutCh <-chan time.Time |
| 153 |
var dialTimer *time.Timer |
| 154 |
if t.Server.backendDialTimeout > 0 { |
| 155 |
dialTimer = time.NewTimer(t.Server.backendDialTimeout) |
| 156 |
defer dialTimer.Stop() |
| 157 |
timeoutCh = dialTimer.C |
| 158 |
} |
| 159 |
|
| 160 |
select { |
| 161 |
case <-connection.connected: // Waiting for response before we begin full communication. |
| 162 |
// The connection is successful. Mark it as established so the deferred |
| 163 |
// cleanup function knows not to remove it from PendingDial. |
| 164 |
established = true |
| 165 |
|
| 166 |
// Now that connection is established, send 200 OK to switch to tunnel mode |
| 167 |
_, err = conn.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n")) |
| 168 |
if err != nil { |
| 169 |
klog.ErrorS(err, "failed to send 200 connection established", "host", r.Host, "agentID", connection.agentID) |
| 170 |
// We return here, but since `established` is true, the deferred |
| 171 |
// function will not remove the pending dial. The agent-side goroutine |
| 172 |
// is responsible for the established connection now. |
| 173 |
return |
| 174 |
} |
| 175 |
klog.V(3).InfoS("Connection established, sent 200 OK", "host", r.Host, "agentID", connection.agentID, "connectionID", connection.connectID) |
| 176 |
|
| 177 |
case <-closed: // Connection was closed by the client before being established |
| 178 |
klog.V(2).InfoS("Frontend connection closed before being established", "host", r.Host, "dialID", connection.dialID, "agentID", connection.agentID) |
| 179 |
// The deferred cleanup will run when we return here. |
| 180 |
return |
| 181 |
|
| 182 |
case <-ctxt.Done(): // Backend connection died before being established |
| 183 |
klog.ErrorS(ctxt.Err(), "backend context closed before connection was established", "host", r.Host, "dialID", connection.dialID, "agentID", connection.agentID) |
| 184 |
metrics.Metrics.ObserveDialFailure(metrics.DialFailureBackendClose) |
| 185 |
dialFailureObserved = true |
| 186 |
// Send proper HTTP error response |
| 187 |
conn.Write([]byte(fmt.Sprintf("HTTP/1.1 502 Bad Gateway\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nBackend context error: %v\r\n", ctxt.Err()))) |
| 188 |
// The deferred cleanup will run when we return here. |
| 189 |
return |
| 190 |
|
| 191 |
case <-timeoutCh: |
| 192 |
klog.ErrorS(errBackendDialTimeout, "backend dial timed out before connection was established", "host", r.Host, "dialID", connection.dialID, "agentID", connection.agentID) |
| 193 |
metrics.Metrics.ObserveDialFailure(metrics.DialFailureBackendDialTimeout) |
| 194 |
dialFailureObserved = true |
| 195 |
conn.Write([]byte(fmt.Sprintf("HTTP/1.1 504 Gateway Timeout\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nBackend dial timeout: %v\r\n", errBackendDialTimeout))) |
| 196 |
// The deferred cleanup will run when we return here. |
| 197 |
return |
| 198 |
} |
| 199 |
|
| 200 |
defer func() { |
| 201 |
packet := &client.Packet{ |
| 202 |
Type: client.PacketType_CLOSE_REQ, |
| 203 |
Payload: &client.Packet_CloseRequest{ |
| 204 |
CloseRequest: &client.CloseRequest{ |
| 205 |
ConnectID: connection.connectID, |
| 206 |
}, |
| 207 |
}, |
| 208 |
} |
| 209 |
|
| 210 |
if err = backend.Send(packet); err != nil { |
| 211 |
klog.V(2).InfoS("failed to send close request packet", "host", r.Host, "agentID", connection.agentID, "connectionID", connection.connectID) |
| 212 |
} |
| 213 |
// The top-level defer handles conn.Close() |
| 214 |
}() |
| 215 |
|
| 216 |
connID := connection.connectID |
| 217 |
agentID := connection.agentID |
| 218 |
klog.V(3).InfoS("Starting proxy to host", "host", r.Host, "agentID", agentID, "connectionID", connID) |
| 219 |
|
| 220 |
// Get a buffer from the pool |
| 221 |
bufPtr := bufferPool.Get().(*[]byte) |
| 222 |
pkt := *bufPtr |
| 223 |
defer func() { |
| 224 |
// Return the buffer to the pool when done |
| 225 |
bufferPool.Put(bufPtr) |
| 226 |
}() |
| 227 |
|
| 228 |
var acc int |
| 229 |
|
| 230 |
for { |
| 231 |
n, err := bufrw.Read(pkt[:]) |
| 232 |
acc += n |
| 233 |
if err == io.EOF { |
| 234 |
klog.V(1).InfoS("EOF from host", "host", r.Host, "agentID", agentID, "connectionID", connID) |
| 235 |
break |
| 236 |
} |
| 237 |
if err != nil { |
| 238 |
klog.ErrorS(err, "Received failure on connection", "host", r.Host, "agentID", agentID, "connectionID", connID) |
| 239 |
break |
| 240 |
} |
| 241 |
|
| 242 |
packet := &client.Packet{ |
| 243 |
Type: client.PacketType_DATA, |
| 244 |
Payload: &client.Packet_Data{ |
| 245 |
Data: &client.Data{ |
| 246 |
ConnectID: connID, |
| 247 |
Data: pkt[:n], |
| 248 |
}, |
| 249 |
}, |
| 250 |
} |
| 251 |
err = backend.Send(packet) |
| 252 |
if err != nil { |
| 253 |
klog.ErrorS(err, "error sending packet", "host", r.Host, "agentID", agentID, "connectionID", connID) |
| 254 |
break |
| 255 |
} |
| 256 |
klog.V(5).InfoS("Forwarding data on tunnel to agent", |
| 257 |
"bytes", n, |
| 258 |
"totalBytes", acc, |
| 259 |
"agentID", connection.agentID, |
| 260 |
"connectionID", connection.connectID) |
| 261 |
} |
| 262 |
|
| 263 |
klog.V(5).InfoS("Stopping transfer to host", "host", r.Host, "agentID", agentID, "connectionID", connID) |
| 264 |
} |