forked from openfaas/faas-netes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.go
93 lines (74 loc) · 2.38 KB
/
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
85
86
87
88
89
90
91
92
93
// 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 (
"encoding/json"
"fmt"
"log"
"net/http"
types "github.com/innoobijr/faas-provider/types"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
v1 "k8s.io/client-go/listers/apps/v1"
klog "k8s.io/klog"
"github.com/innoobijr/faas-netes/pkg/k8s"
)
// MakeFunctionReader handler for reading functions deployed in the cluster as deployments.
func MakeFunctionReader(defaultNamespace string, deploymentLister v1.DeploymentLister) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
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
}
if lookupNamespace == "kube-system" {
http.Error(w, "unable to list within the kube-system namespace", http.StatusUnauthorized)
return
}
functions, err := getServiceList(lookupNamespace, deploymentLister)
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
functionBytes, err := json.Marshal(functions)
if err != nil {
klog.Errorf("Failed to marshal functions: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Failed to marshal functions"))
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(functionBytes)
}
}
func getServiceList(functionNamespace string, deploymentLister v1.DeploymentLister) ([]types.FunctionStatus, error) {
functions := []types.FunctionStatus{}
sel := labels.NewSelector()
req, err := labels.NewRequirement("faas_function", selection.Exists, []string{})
if err != nil {
return functions, err
}
onlyFunctions := sel.Add(*req)
res, err := deploymentLister.Deployments(functionNamespace).List(onlyFunctions)
if err != nil {
return nil, err
}
for _, item := range res {
if item != nil {
function := k8s.AsFunctionStatus(*item)
if function != nil {
functions = append(functions, *function)
}
}
}
return functions, nil
}