...
1
18
19 package api_monitoring
20
21 import (
22 "encoding/json"
23 "github.com/gorilla/mux"
24 "net/http"
25 "scheduler/errors"
26 "scheduler/faas_openfaas"
27 "scheduler/log"
28 "scheduler/utils"
29 "time"
30 )
31
32 type scaleDelayResponse struct {
33 ApproximateDelay float64 `json:"approximate_delay"`
34 ErrorMargin float64 `json:"error_margin"`
35 Attempts int `json:"attempts"`
36 }
37
38
39 func ScaleDelay(w http.ResponseWriter, r *http.Request) {
40 vars := mux.Vars(r)
41 function := vars["function"]
42
43
44 fun, _, err := faas_openfaas.FunctionGet(function)
45 if fun.Replicas != fun.AvailableReplicas {
46 log.Log.Debugf("Cannot start monitoring, service is not stabilized")
47 errors.ReplyWithError(&w, errors.InputNotValid, nil)
48 return
49 }
50
51
52 _, err = faas_openfaas.FunctionScaleByOne(function)
53 if err != nil {
54 log.Log.Debugf("Cannot scale function: %s", err.Error())
55 errors.ReplyWithError(&w, errors.GenericOpenFaasError, nil)
56 return
57 }
58
59 startLoop := time.Now()
60 attempts := 0
61 var loopTime time.Duration
62
63 for {
64 fun, _, err := faas_openfaas.FunctionGet(function)
65 attempts += 1
66 if err != nil {
67 log.Log.Debugf("Cannot get function: %s", err.Error())
68 errors.ReplyWithError(&w, errors.GenericOpenFaasError, nil)
69 break
70 }
71 if fun.Replicas == fun.AvailableReplicas {
72 loopTime = time.Since(startLoop)
73 break
74 }
75 time.Sleep(100 * time.Millisecond)
76 }
77
78
79 _, err = faas_openfaas.FunctionScaleDownByOne(function)
80 if err != nil {
81 log.Log.Debugf("Cannot scale function: %s", err.Error())
82 errors.ReplyWithError(&w, errors.GenericOpenFaasError, nil)
83
84 }
85
86 res := &scaleDelayResponse{
87 Attempts: attempts,
88 ApproximateDelay: loopTime.Seconds(),
89 ErrorMargin: 100,
90 }
91 resJson, _ := json.Marshal(res)
92 utils.HttpSendJSONResponse(&w, http.StatusOK, string(resJson), nil)
93 }
94
View as plain text