File: client.go

package info (click to toggle)
golang-github-crc-org-crc 2.34.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,548 kB
  • sloc: sh: 398; makefile: 326; javascript: 40
file content (274 lines) | stat: -rw-r--r-- 6,294 bytes parent folder | download
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package client

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"
)

type Client interface {
	Version() (VersionResult, error)
	Status() (ClusterStatusResult, error)
	Start(config StartConfig) (StartResult, error)
	Stop() error
	Delete() error
	WebconsoleURL() (*ConsoleResult, error)
	GetConfig(configs []string) (GetConfigResult, error)
	SetConfig(configs SetConfigRequest) (SetOrUnsetConfigResult, error)
	UnsetConfig(configs []string) (SetOrUnsetConfigResult, error)
	Telemetry(action string) error
	IsPullSecretDefined() (bool, error)
	SetPullSecret(data string) error
}

type HTTPError struct {
	URL        string
	Method     string
	StatusCode int
	Body       string
}

func (err *HTTPError) Error() string {
	return err.Body
}

type client struct {
	client *http.Client
	base   string
}

func New(httpClient *http.Client, baseURL string) Client {
	return &client{
		client: httpClient,
		base:   baseURL,
	}
}

func (c *client) Version() (VersionResult, error) {
	var vr = VersionResult{}
	body, err := c.sendGetRequest("/version")
	if err != nil {
		return vr, err
	}
	err = json.Unmarshal(body, &vr)
	if err != nil {
		return vr, err
	}
	return vr, nil
}

func (c *client) Status() (ClusterStatusResult, error) {
	var sr = ClusterStatusResult{}
	body, err := c.sendGetRequest("/status")
	if err != nil {
		return sr, err
	}
	err = json.Unmarshal(body, &sr)
	if err != nil {
		return sr, err
	}
	return sr, nil
}

func (c *client) Start(config StartConfig) (StartResult, error) {
	var sr = StartResult{}
	var data = new(bytes.Buffer)

	if config != (StartConfig{}) {
		if err := json.NewEncoder(data).Encode(config); err != nil {
			return sr, fmt.Errorf("Failed to encode data to JSON: %w", err)
		}
	}
	body, err := c.sendPostRequest("/start", data)
	if err != nil {
		return sr, err
	}
	err = json.Unmarshal(body, &sr)
	if err != nil {
		return sr, err
	}
	return sr, nil
}

func (c *client) Stop() error {
	_, err := c.sendGetRequest("/stop")
	return err
}

func (c *client) Delete() error {
	_, err := c.sendGetRequest("/delete")
	return err
}

func (c *client) WebconsoleURL() (*ConsoleResult, error) {
	var cr = ConsoleResult{}
	body, err := c.sendGetRequest("/webconsoleurl")
	if err != nil {
		return &cr, err
	}
	err = json.Unmarshal(body, &cr)
	if err != nil {
		return &cr, err
	}
	return &cr, nil
}

func (c *client) GetConfig(configs []string) (GetConfigResult, error) {
	var gcr = GetConfigResult{}
	var escapeConfigs []string
	for _, v := range configs {
		escapeConfigs = append(escapeConfigs, url.QueryEscape(v))
	}
	queryString := strings.Join(escapeConfigs, "&")
	body, err := c.sendGetRequest(fmt.Sprintf("/config?%s", queryString))
	if err != nil {
		return gcr, err
	}
	err = json.Unmarshal(body, &gcr)
	if err != nil {
		return gcr, err
	}
	return gcr, nil
}

func (c *client) SetConfig(configs SetConfigRequest) (SetOrUnsetConfigResult, error) {
	var scr = SetOrUnsetConfigResult{}
	var data = new(bytes.Buffer)

	if len(configs.Properties) == 0 {
		return scr, fmt.Errorf("No config key value pair provided to set")
	}

	if err := json.NewEncoder(data).Encode(configs); err != nil {
		return scr, fmt.Errorf("Failed to encode data to JSON: %w", err)
	}

	body, err := c.sendPostRequest("/config", data)
	if err != nil {
		return scr, err
	}

	err = json.Unmarshal(body, &scr)
	if err != nil {
		return scr, err
	}
	return scr, nil
}

func (c *client) UnsetConfig(configs []string) (SetOrUnsetConfigResult, error) {
	var ucr = SetOrUnsetConfigResult{}
	var data = new(bytes.Buffer)

	cfg := GetOrUnsetConfigRequest{
		Properties: configs,
	}
	if err := json.NewEncoder(data).Encode(cfg); err != nil {
		return ucr, fmt.Errorf("Failed to encode data to JSON: %w", err)
	}
	body, err := c.sendDeleteRequest("/config", data)
	if err != nil {
		return ucr, err
	}
	err = json.Unmarshal(body, &ucr)
	if err != nil {
		return ucr, err
	}
	return ucr, nil
}

func (c *client) Telemetry(action string) error {
	data, err := json.Marshal(TelemetryRequest{
		Action: action,
	})
	if err != nil {
		return fmt.Errorf("Failed to encode data to JSON: %w", err)
	}

	_, err = c.sendPostRequest("/telemetry", bytes.NewReader(data))

	return err
}

func (c *client) IsPullSecretDefined() (bool, error) {
	res, err := c.client.Get(fmt.Sprintf("%s%s", c.base, "/pull-secret"))
	if err != nil {
		return false, err
	}
	defer res.Body.Close()
	return res.StatusCode == http.StatusOK, nil
}

func (c *client) SetPullSecret(data string) error {
	_, err := c.sendPostRequest("/pull-secret", bytes.NewReader([]byte(data)))
	if err != nil {
		return err
	}
	return nil
}

func (c *client) sendGetRequest(url string) ([]byte, error) {
	res, err := c.client.Get(fmt.Sprintf("%s%s", c.base, url))
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		return nil, fmt.Errorf("Unknown error reading response: %w", err)
	}

	if res.StatusCode != http.StatusOK {
		return nil, &HTTPError{
			URL:        url,
			Method:     "GET",
			StatusCode: res.StatusCode,
			Body:       string(body),
		}
	}

	return body, nil
}

func (c *client) sendPostRequest(url string, data io.Reader) ([]byte, error) {
	return c.sendRequest(url, http.MethodPost, data)
}

func (c *client) sendDeleteRequest(url string, data io.Reader) ([]byte, error) {
	return c.sendRequest(url, http.MethodDelete, data)
}

func (c *client) sendRequest(url string, method string, data io.Reader) ([]byte, error) {
	req, err := http.NewRequest(method, fmt.Sprintf("%s%s", c.base, url), data)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")

	res, err := c.client.Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	switch method {
	case http.MethodPost:
		if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated {
			return nil, fmt.Errorf("Error occurred sending POST request to : %s : %d", url, res.StatusCode)
		}
	case http.MethodDelete, http.MethodGet:
		if res.StatusCode != http.StatusOK {
			return nil, fmt.Errorf("Error occurred sending %s request to : %s : %d", method, url, res.StatusCode)
		}
	}

	body, err := io.ReadAll(res.Body)
	if err != nil {
		return nil, fmt.Errorf("Unknown error reading response: %w", err)
	}
	return body, nil
}