Skip to content

Commit 0061334

Browse files
committed
Implement scaling ranges
Scaling ranges keep the OpenFaaS CE gateway's requests to within the intended bounds already implemented in other components. Signed-off-by: Alex Ellis (OpenFaaS Ltd) <alex@openfaas.com>
1 parent e0144b0 commit 0061334

2 files changed

Lines changed: 50 additions & 1 deletion

File tree

gateway/main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ func main() {
168168

169169
prometheusQuery := metrics.NewPrometheusQuery(config.PrometheusHost, config.PrometheusPort, &http.Client{})
170170
faasHandlers.ListFunctions = metrics.AddMetricsHandler(faasHandlers.ListFunctions, prometheusQuery)
171-
faasHandlers.ScaleFunction = handlers.MakeForwardingProxyHandler(reverseProxy, forwardingNotifiers, urlResolver, nilURLTransformer, serviceAuthInjector)
171+
faasHandlers.ScaleFunction = scaling.MakeHorizontalScalingHandler(handlers.MakeForwardingProxyHandler(reverseProxy, forwardingNotifiers, urlResolver, nilURLTransformer, serviceAuthInjector))
172172

173173
if credentials != nil {
174174
faasHandlers.Alert =

gateway/scaling/ranges.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,14 @@
11
package scaling
22

3+
import (
4+
"bytes"
5+
"encoding/json"
6+
"io/ioutil"
7+
"net/http"
8+
9+
"github.com/openfaas/faas-provider/types"
10+
)
11+
312
const (
413
// DefaultMinReplicas is the minimal amount of replicas for a service.
514
DefaultMinReplicas = 1
@@ -21,3 +30,43 @@ const (
2130
// ScalingFactorLabel label indicates the scaling factor for a function
2231
ScalingFactorLabel = "com.openfaas.scale.factor"
2332
)
33+
34+
func MakeHorizontalScalingHandler(next http.HandlerFunc) http.HandlerFunc {
35+
return func(w http.ResponseWriter, r *http.Request) {
36+
if r.Method != http.MethodPost {
37+
http.Error(w, "Only POST is allowed", http.StatusMethodNotAllowed)
38+
return
39+
}
40+
41+
if r.Body == nil {
42+
http.Error(w, "Error reading request body", http.StatusBadRequest)
43+
return
44+
}
45+
46+
body, err := ioutil.ReadAll(r.Body)
47+
if err != nil {
48+
http.Error(w, "Error reading request body", http.StatusBadRequest)
49+
return
50+
}
51+
52+
scaleRequest := types.ScaleServiceRequest{}
53+
if err := json.Unmarshal(body, &scaleRequest); err != nil {
54+
http.Error(w, "Error unmarshalling request body", http.StatusBadRequest)
55+
return
56+
}
57+
58+
if scaleRequest.Replicas < 1 {
59+
scaleRequest.Replicas = 1
60+
}
61+
62+
if scaleRequest.Replicas > DefaultMaxReplicas {
63+
scaleRequest.Replicas = DefaultMaxReplicas
64+
}
65+
66+
upstreamReq, _ := json.Marshal(scaleRequest)
67+
// Restore the io.ReadCloser to its original state
68+
r.Body = ioutil.NopCloser(bytes.NewBuffer(upstreamReq))
69+
70+
next.ServeHTTP(w, r)
71+
}
72+
}

0 commit comments

Comments
 (0)