This repository has been archived by the owner on Dec 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathreplica_reader.go
84 lines (66 loc) · 1.87 KB
/
replica_reader.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
package handlers
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/client"
"github.com/gorilla/mux"
typesv1 "github.com/openfaas/faas-provider/types"
)
// ReplicaReader reads replica and image status data from a function
func ReplicaReader(c *client.Client) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
functionName := vars["name"]
log.Printf("ReplicaReader - reading function: %s\n", functionName)
functions, err := readServices(c)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
var found *typesv1.FunctionStatus
for _, function := range functions {
if function.Name == functionName {
found = &function
break
}
}
if found == nil {
w.WriteHeader(404)
return
}
replicas, replicaErr := getAvailableReplicas(c, found.Name)
if replicaErr != nil {
log.Printf("%s\n", replicaErr.Error())
// Fail-over as 0
}
found.AvailableReplicas = replicas
functionBytes, _ := json.Marshal(found)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(functionBytes)
}
}
func getAvailableReplicas(c *client.Client, service string) (uint64, error) {
taskFilter := filters.NewArgs()
taskFilter.Add("_up-to-date", "true")
taskFilter.Add("service", service)
taskFilter.Add("desired-state", "running")
tasks, err := c.TaskList(context.Background(), types.TaskListOptions{Filters: taskFilter})
if err != nil {
return 0, fmt.Errorf("getAvailableReplicas for: %s failed %s", service, err.Error())
}
replicas := uint64(0)
for _, task := range tasks {
if task.Status.State == swarm.TaskStateRunning {
replicas++
}
}
return replicas, nil
}