/
logs.go
105 lines (87 loc) · 2.27 KB
/
logs.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
package proxy
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"strconv"
"time"
"github.com/openfaas/faas-provider/logs"
)
// GetLogs return stream for the logs
func (c *Client) GetLogs(ctx context.Context, params logs.Request) (<-chan logs.Message, error) {
logRequest, err := c.newRequest(http.MethodGet, "/system/logs", url.Values{}, nil)
if err != nil {
return nil, fmt.Errorf("cannot connect to OpenFaaS on URL: %s", c.GatewayURL.String())
}
logRequest.URL.RawQuery = reqAsQueryValues(params).Encode()
if os.Getenv("FAAS_DEBUG") == "1" {
fmt.Printf("%s\n", logRequest.URL.RawQuery)
}
res, err := c.doRequest(ctx, logRequest)
if err != nil {
return nil, fmt.Errorf("cannot connect to OpenFaaS on URL: %s", c.GatewayURL.String())
}
logStream := make(chan logs.Message, 1000)
switch res.StatusCode {
case http.StatusOK:
go func() {
defer close(logStream)
defer res.Body.Close()
decoder := json.NewDecoder(res.Body)
for decoder.More() {
msg := logs.Message{}
err := decoder.Decode(&msg)
if err != nil {
log.Printf("cannot parse log results: %s\n", err.Error())
return
}
logStream <- msg
}
}()
case http.StatusUnauthorized:
return nil, fmt.Errorf("unauthorized access, run \"faas-cli login\" to setup authentication for this server")
default:
bytesOut, err := io.ReadAll(res.Body)
if err == nil {
return nil, fmt.Errorf("server returned unexpected status code: %d - %s", res.StatusCode, string(bytesOut))
}
}
return logStream, nil
}
func reqAsQueryValues(r logs.Request) url.Values {
query := url.Values{}
query.Add("name", r.Name)
if len(r.Namespace) > 0 {
query.Add("namespace", r.Namespace)
}
query.Add("follow", strconv.FormatBool(r.Follow))
if r.Instance != "" {
query.Add("instance", r.Instance)
}
if r.Since != nil {
query.Add("since", r.Since.Format(time.RFC3339))
}
if r.Tail != 0 {
query.Add("tail", strconv.Itoa(r.Tail))
}
return query
}
func makeStreamingHTTPClient(tlsInsecure bool) http.Client {
client := http.Client{}
if tlsInsecure {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
}
if tlsInsecure {
tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: tlsInsecure}
}
client.Transport = tr
}
return client
}