-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
ofaas.go
216 lines (180 loc) 路 4.89 KB
/
ofaas.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package dao
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"strings"
"time"
"github.com/derailed/k9s/internal/client"
"github.com/derailed/k9s/internal/render"
"github.com/openfaas/faas-cli/proxy"
"github.com/openfaas/faas/gateway/requests"
"github.com/rs/zerolog/log"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/yaml"
)
const (
oFaasGatewayEnv = "OPENFAAS_GATEWAY"
oFaasJWTTokenEnv = "OPENFAAS_JWT_TOKEN"
oFaasTLSInsecure = "OPENFAAS_TLS_INSECURE"
)
var (
_ Accessor = (*OpenFaas)(nil)
_ Nuker = (*OpenFaas)(nil)
_ Describer = (*OpenFaas)(nil)
)
// OpenFaas represents a faas gateway connection.
type OpenFaas struct {
NonResource
}
// IsOpenFaasEnabled returns true if a gateway url is set in the environment.
func IsOpenFaasEnabled() bool {
return os.Getenv(oFaasGatewayEnv) != ""
}
func getOpenFAASFlags() (string, string, bool) {
gw, token := os.Getenv(oFaasGatewayEnv), os.Getenv(oFaasJWTTokenEnv)
tlsInsecure := false
if os.Getenv(oFaasTLSInsecure) == "true" {
tlsInsecure = true
}
return gw, token, tlsInsecure
}
// Get returns a function by name.
func (f *OpenFaas) Get(ctx context.Context, path string) (runtime.Object, error) {
ns, n := client.Namespaced(path)
oo, err := f.List(ctx, ns)
if err != nil {
return nil, err
}
var found runtime.Object
for _, o := range oo {
r, ok := o.(render.OpenFaasRes)
if !ok {
continue
}
if r.Function.Name == n {
found = o
break
}
}
if found == nil {
return nil, fmt.Errorf("unable to locate function %q", path)
}
return found, nil
}
// List returns a collection of functions.
func (f *OpenFaas) List(_ context.Context, ns string) ([]runtime.Object, error) {
if !IsOpenFaasEnabled() {
return nil, errors.New("OpenFAAS is not enabled on this cluster")
}
gw, token, tls := getOpenFAASFlags()
ff, err := proxy.ListFunctionsToken(gw, tls, token, ns)
if err != nil {
return nil, err
}
oo := make([]runtime.Object, 0, len(ff))
for _, f := range ff {
oo = append(oo, render.OpenFaasRes{Function: f})
}
return oo, nil
}
// Delete removes a function.
func (f *OpenFaas) Delete(path string, _, _ bool) error {
gw, token, tls := getOpenFAASFlags()
ns, n := client.Namespaced(path)
// BOZO!! openfaas spews to stdout. Not good for us...
return deleteFunctionToken(gw, n, tls, token, ns)
}
// ToYAML dumps a function to yaml.
func (f *OpenFaas) ToYAML(path string) (string, error) {
return f.Describe(path)
}
// Describe describes a function.
func (f *OpenFaas) Describe(path string) (string, error) {
o, err := f.Get(context.Background(), path)
if err != nil {
return "", err
}
fn, ok := o.(render.OpenFaasRes)
if !ok {
return "", fmt.Errorf("expecting OpenFaasRes but got %T", o)
}
raw, err := json.Marshal(fn)
if err != nil {
return "", err
}
bytes, err := yaml.JSONToYAML(raw)
if err != nil {
return "", err
}
return string(bytes), nil
}
// BOZO!! Meow! openfaas fn prints to stdout have to dup ;(
func deleteFunctionToken(gateway string, functionName string, tlsInsecure bool, token string, namespace string) error {
defaultCommandTimeout := 60 * time.Second
gateway = strings.TrimRight(gateway, "/")
delReq := requests.DeleteFunctionRequest{FunctionName: functionName}
reqBytes, _ := json.Marshal(&delReq)
reader := bytes.NewReader(reqBytes)
c := proxy.MakeHTTPClient(&defaultCommandTimeout, tlsInsecure)
deleteEndpoint, err := createSystemEndpoint(gateway, namespace)
if err != nil {
return err
}
req, err := http.NewRequest("DELETE", deleteEndpoint, reader)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
if len(token) > 0 {
proxy.SetToken(req, token)
} else {
proxy.SetAuth(req, gateway)
}
delRes, delErr := c.Do(req)
if delErr != nil {
return delErr
}
if delRes.Body != nil {
defer func() {
if err := delRes.Body.Close(); err != nil {
log.Error().Err(err).Msgf("closing delete-gtw body")
}
}()
}
switch delRes.StatusCode {
case http.StatusOK, http.StatusCreated, http.StatusAccepted:
return nil
case http.StatusNotFound:
return fmt.Errorf("no function named %s found", functionName)
case http.StatusUnauthorized:
return fmt.Errorf("unauthorized access, run \"faas-cli login\" to setup authentication for this server")
default:
bytesOut, err := ioutil.ReadAll(delRes.Body)
if err != nil {
return err
}
return fmt.Errorf("server returned unexpected status code %d %s", delRes.StatusCode, string(bytesOut))
}
}
func createSystemEndpoint(gateway, namespace string) (string, error) {
const systemPath = "/system/functions"
gatewayURL, err := url.Parse(gateway)
if err != nil {
return "", fmt.Errorf("invalid gateway URL: %s", err.Error())
}
gatewayURL.Path = path.Join(gatewayURL.Path, systemPath)
if len(namespace) > 0 {
q := gatewayURL.Query()
q.Set("namespace", namespace)
gatewayURL.RawQuery = q.Encode()
}
return gatewayURL.String(), nil
}