This repository has been archived by the owner on Jul 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
handler_inference_proxy.go
144 lines (128 loc) · 4.16 KB
/
handler_inference_proxy.go
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
package server
import (
"errors"
"fmt"
"net"
"net/http"
"net/http/httputil"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus"
"github.com/tensorchord/openmodelz/agent/errdefs"
)
// @Summary Inference.
// @Description Inference proxy.
// @Tags inference-proxy
// @Accept json
// @Produce json
// @Router /inference/{name} [post]
// @Router /inference/{name} [get]
// @Router /inference/{name} [put]
// @Router /inference/{name} [delete]
func (s *Server) handleInferenceProxy(c *gin.Context) error {
namespacedName := c.Param("name")
if namespacedName == "" {
return NewError(
http.StatusBadRequest, errors.New("name is required"), "inference-proxy")
}
namespace, name, err := getNamespaceAndName(namespacedName)
if err != nil {
return NewError(
http.StatusBadRequest, err, "inference-proxy")
}
// Update metrics.
s.metricsOptions.GatewayInferenceInvocationStarted.
WithLabelValues(namespacedName).Inc()
s.metricsOptions.GatewayInferenceInvocationInflight.
WithLabelValues(namespacedName).Inc()
start := time.Now()
label := prometheus.Labels{"inference_name": namespacedName, "code": strconv.Itoa(http.StatusProcessing)}
defer func() {
s.metricsOptions.GatewayInferenceInvocationInflight.
WithLabelValues(namespacedName).Dec()
s.metricsOptions.GatewayInferencesHistogram.With(label).
Observe(time.Since(start).Seconds())
s.metricsOptions.GatewayInferenceInvocation.With(label).Inc()
}()
res := s.scaler.Scale(c.Request.Context(), namespace, name)
if !res.Found {
label["code"] = strconv.Itoa(http.StatusNotFound)
return NewError(
http.StatusNotFound, errors.New("inference not found"), "inference-proxy")
} else if res.Error != nil {
label["code"] = strconv.Itoa(http.StatusInternalServerError)
return NewError(
http.StatusInternalServerError, res.Error, "inference-proxy")
}
if res.Available {
statusCode, err := s.forward(c, namespace, name)
if err != nil {
label["code"] = strconv.Itoa(statusCode)
return NewError(statusCode, err, "inference-proxy")
}
label["code"] = strconv.Itoa(statusCode)
return nil
} else {
// The inference is still being created.
label["code"] = strconv.Itoa(http.StatusSeeOther)
return NewError(http.StatusSeeOther,
fmt.Errorf("inference %s is not available", name), "inference-proxy")
}
}
func (s *Server) forward(c *gin.Context, namespace, name string) (int, error) {
backendURL, err := s.endpointResolver.Resolve(namespace, name)
if err != nil {
return 0, errdefs.InvalidParameter(err)
}
defer s.endpointResolver.Close(backendURL)
proxyServer := httputil.NewSingleHostReverseProxy(&backendURL)
proxyServer.Transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: s.config.Server.ReadTimeout,
KeepAlive: s.config.Server.ReadTimeout,
DualStack: true,
}).DialContext,
}
proxyServer.Director = func(req *http.Request) {
targetQuery := backendURL.RawQuery
req.URL.Scheme = backendURL.Scheme
req.URL.Host = backendURL.Host
// req.URL.Path, req.URL.RawPath = joinURLPath(target, req.URL)
if targetQuery == "" || req.URL.RawQuery == "" {
req.URL.RawQuery = targetQuery + req.URL.RawQuery
} else {
req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
}
req.URL.Path = c.Param("proxyPath")
if req.URL.Path == "" {
req.URL.Path = "/"
}
s.logger.WithField("url", backendURL.String()).
WithField("path", req.URL.Path).
WithField("raw-query", req.URL.RawQuery).Debug("proxying")
}
var statusCode int
proxyServer.ModifyResponse = func(resp *http.Response) error {
statusCode = resp.StatusCode
return nil
}
proxyServer.ServeHTTP(c.Writer, c.Request)
return statusCode, nil
}
func getNamespaceAndName(name string) (string, string, error) {
if !strings.Contains(name, ".") {
return "", "", fmt.Errorf("name is not namespaced")
}
namespace := name[strings.LastIndexAny(name, ".")+1:]
infName := strings.TrimSuffix(name, "."+namespace)
if namespace == "" {
return "", "", fmt.Errorf("namespace is empty")
}
if infName == "" {
return "", "", fmt.Errorf("inference name is empty")
}
return namespace, infName, nil
}