forked from solarwinds/swo-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
238 lines (195 loc) · 5.26 KB
/
Copy pathclient.go
File metadata and controls
238 lines (195 loc) · 5.26 KB
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
// Package logs provides a client for retrieving and displaying logs from the SWO API.
package logs
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/solarwinds/swo-cli/shared"
)
var (
// ErrInvalidAPIResponse indicates a non-2xx status code was received from the API
ErrInvalidAPIResponse = errors.New("received non-2xx status code")
// ErrInvalidDateTime indicates a timestamp could not be parsed
ErrInvalidDateTime = errors.New("could not parse timestamp")
// ErrNoContent indicates an empty response body was received from the API
ErrNoContent = errors.New("no content")
)
// Client is a logs client
type Client struct {
opts *Options
httpClient http.Client
output *os.File
}
type log struct {
Time time.Time `json:"time"`
Message string `json:"message"`
Hostname string `json:"hostname"`
Severity string `json:"severity"`
Program string `json:"program"`
}
type pageInfo struct {
PrevPage string `json:"prevPage"`
NextPage string `json:"nextPage"`
}
type getLogsResponse struct {
Logs []log `json:"logs"`
pageInfo `json:"pageInfo"`
}
// NewClient creates a new logs client
func NewClient(opts *Options) (*Client, error) {
// Configure logging based on verbose flag
shared.SetupLogger(opts.Verbose)
return &Client{
httpClient: *http.DefaultClient,
opts: opts,
output: os.Stdout,
}, nil
}
func (c *Client) prepareRequest(ctx context.Context, nextPage string) (*http.Request, error) {
var logsEndpoint string
var err error
params := url.Values{}
if nextPage == "" {
logsEndpoint, err = url.JoinPath(c.opts.APIURL, "v1/logs")
if c.opts.follow {
params.Add("direction", "tail")
} else {
params.Add("direction", "forward")
}
params.Add("pageSize", "1000")
if c.opts.group != "" {
params.Add("group", c.opts.group)
}
if c.opts.minTime != "" {
params.Add("startTime", c.opts.minTime)
}
if c.opts.maxTime != "" {
params.Add("endTime", c.opts.maxTime)
}
var filter string
if c.opts.system != "" {
filter = fmt.Sprintf(`host:"%s"`, c.opts.system)
}
if len(c.opts.args) != 0 {
if len(filter) == 0 {
filter = strings.Join(c.opts.args, " ")
} else {
filter = filter + " " + strings.Join(c.opts.args, " ")
}
}
if filter != "" {
params.Add("filter", filter)
}
} else {
u, err := url.Parse(nextPage)
if err != nil {
return nil, fmt.Errorf("failed to parse nextPage field: %w", err)
}
logsEndpoint, err = url.JoinPath(c.opts.APIURL, u.Path)
if err != nil {
return nil, err
}
params, err = url.ParseQuery(u.RawQuery)
if err != nil {
return nil, err
}
if c.opts.follow {
params.Del("endTime")
}
}
if err != nil {
return nil, err
}
logsURL, err := url.Parse(logsEndpoint)
if err != nil {
return nil, err
}
logsURL.RawQuery = params.Encode()
slog.Debug("API Request", "method", "GET", "url", logsURL.String())
request, err := http.NewRequestWithContext(ctx, "GET", logsURL.String(), nil)
if err != nil {
return nil, err
}
request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.opts.Token))
request.Header.Add("Accept", "application/json")
return request, nil
}
func (c *Client) printResult(logs []log) error {
for _, l := range logs {
l.Time = l.Time.Local()
if c.opts.json {
log, err := json.Marshal(l)
if err != nil {
return err
}
_, _ = fmt.Fprintln(c.output, string(log))
} else {
_, _ = fmt.Fprintf(c.output, "%s %s %s %s\n", l.Time.Format("Jan 02 15:04:05"), l.Hostname, l.Program, l.Message)
}
}
return nil
}
func (c *Client) getLogs(ctx context.Context, nextPage string) (*getLogsResponse, error) {
request, err := c.prepareRequest(ctx, nextPage)
if err != nil {
return nil, fmt.Errorf("error while preparing http request to SWO: %w", err)
}
response, err := c.httpClient.Do(request)
if err != nil {
return nil, fmt.Errorf("error while sending http request to SWO: %w", err)
}
defer func() {
err := response.Body.Close()
if err != nil {
slog.Error("Could not close https body", "error", err)
}
}()
slog.Debug("Response status", "status_code", response.StatusCode, "status", response.Status)
content, err := io.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("error while reading http response body from SWO: %w", err)
}
slog.Debug("Response body", "length_bytes", len(content))
if response.StatusCode < 200 || response.StatusCode > 299 {
return nil, fmt.Errorf("%w: %d, response body: %s", ErrInvalidAPIResponse, response.StatusCode, string(content))
}
if len(content) == 0 {
return nil, ErrNoContent
}
var logs getLogsResponse
err = json.Unmarshal(content, &logs)
if err != nil {
return nil, fmt.Errorf("error while unmarshaling http response body from SWO: %w", err)
}
return &logs, nil
}
// Run executes the logs retrieval and printing process
func (c *Client) Run(ctx context.Context) error {
var nextPage string
for {
logs, err := c.getLogs(ctx, nextPage)
if err != nil {
return err
}
err = c.printResult(logs.Logs)
if err != nil {
return fmt.Errorf("failed to print result: %w", err)
}
if c.opts.follow && len(logs.Logs) == 0 {
time.Sleep(2 * time.Second)
}
if logs.NextPage == "" {
break
}
nextPage = logs.NextPage
}
return nil
}