-
Notifications
You must be signed in to change notification settings - Fork 472
/
replica_updater.go
100 lines (79 loc) · 2.58 KB
/
replica_updater.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
// Copyright (c) Alex Ellis 2017. All rights reserved.
// Copyright 2020 OpenFaaS Author(s)
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package handlers
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/openfaas/faas-provider/types"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
// MakeReplicaUpdater updates desired count of replicas
func MakeReplicaUpdater(defaultNamespace string, clientset *kubernetes.Clientset) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Println("Update replicas")
vars := mux.Vars(r)
functionName := vars["name"]
q := r.URL.Query()
namespace := q.Get("namespace")
lookupNamespace := defaultNamespace
if len(namespace) > 0 {
lookupNamespace = namespace
}
if lookupNamespace != defaultNamespace {
http.Error(w, fmt.Sprintf("namespace must be: %s", defaultNamespace), http.StatusBadRequest)
return
}
req := types.ScaleServiceRequest{}
if r.Body != nil {
defer r.Body.Close()
bytesIn, _ := io.ReadAll(r.Body)
marshalErr := json.Unmarshal(bytesIn, &req)
if marshalErr != nil {
w.WriteHeader(http.StatusBadRequest)
msg := "Cannot parse request. Please pass valid JSON."
w.Write([]byte(msg))
log.Println(msg, marshalErr)
return
}
}
if req.Replicas == 0 {
http.Error(w, "replicas cannot be set to 0 in OpenFaaS CE",
http.StatusBadRequest)
return
}
options := metav1.GetOptions{
TypeMeta: metav1.TypeMeta{
Kind: "Deployment",
APIVersion: "apps/v1",
},
}
deployment, err := clientset.AppsV1().Deployments(lookupNamespace).Get(context.TODO(), functionName, options)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Unable to lookup function deployment " + functionName))
log.Println(err)
return
}
oldReplicas := *deployment.Spec.Replicas
replicas := int32(req.Replicas)
if replicas >= MaxReplicas {
replicas = MaxReplicas
}
log.Printf("Set replicas - %s %s, %d/%d\n", functionName, lookupNamespace, replicas, oldReplicas)
deployment.Spec.Replicas = &replicas
if _, err = clientset.AppsV1().Deployments(lookupNamespace).
Update(context.TODO(), deployment, metav1.UpdateOptions{}); err != nil {
log.Printf("unable to update function deployment: %s, %s", functionName, err)
http.Error(w, fmt.Sprintf("unable to update function deployment: %s", functionName), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusAccepted)
}
}