/
maps.go
325 lines (288 loc) · 9.35 KB
/
maps.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
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
package runtime
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/google/renameio"
native_errors "github.com/haproxytech/client-native/v5/errors"
"github.com/haproxytech/client-native/v5/models"
)
// ShowMaps returns map files description from runtime
func (s *SingleRuntime) ShowMaps() (models.Maps, error) {
response, err := s.ExecuteWithResponse("show map")
if err != nil {
return nil, fmt.Errorf("%s %w", err.Error(), native_errors.ErrNotFound)
}
return s.parseMaps(response), nil
}
// CreateMap creates a new map file with its entries. Returns an error if file already exists
func CreateMap(name string, file io.Reader) (*models.Map, error) {
ext := filepath.Ext(name) //nolint:ifshort
if ext != ".map" {
return nil, fmt.Errorf("provided file with %s extension, but supported .map %w", ext, native_errors.ErrGeneral)
}
if _, err := os.Stat(name); err == nil {
return nil, fmt.Errorf("file %s %w. You should delete an existing file first", name, native_errors.ErrAlreadyExists)
}
var buf bytes.Buffer
_, err := io.Copy(&buf, file)
if err != nil {
return nil, err
}
err = renameio.WriteFile(name, buf.Bytes(), 0o644)
if err != nil {
return nil, err
}
return &models.Map{File: name}, nil
}
// parseMaps parses output from `show map` command and return array of map files
// First line in output represents format and is ignored
// Sample output format:
// # id (file) description
// -1 (/etc/haproxy/maps/hosts.map) pattern loaded from file '/etc/haproxy/maps/hosts.map' used by map at file '/etc/haproxy/haproxy.cfg' line 26
func (s *SingleRuntime) parseMaps(output string) models.Maps {
if output == "" {
return nil
}
maps := models.Maps{}
lines := strings.Split(strings.TrimSpace(output), "\n")
for _, line := range lines {
m := s.parseMap(line)
if m != nil {
maps = append(maps, m)
}
}
return maps
}
// parseMap parses one line from map files array and return it structured
func (s *SingleRuntime) parseMap(line string) *models.Map {
if line == "" || strings.HasPrefix(strings.TrimSpace(line), "# id") {
return nil
}
parts := strings.Fields(line)
if len(parts) < 3 {
return nil
}
m := &models.Map{
ID: parts[0],
File: strings.TrimSuffix(strings.TrimPrefix(parts[1], "("), ")"),
Description: strings.Join(parts[2:], " "),
}
return m
}
// GetMap returns one structured runtime map file
func (s *SingleRuntime) GetMap(name string) (*models.Map, error) {
maps, err := s.ShowMaps()
if err != nil {
return nil, err
}
for _, m := range maps {
if m.File == name {
return m, nil
}
}
return nil, fmt.Errorf("%s %w", name, native_errors.ErrNotFound)
}
// ClearMap removes all map entries from the map file.
func (s *SingleRuntime) ClearMap(name string) error {
cmd := fmt.Sprintf("clear map %s", name)
if err := s.Execute(cmd); err != nil {
return fmt.Errorf("%s %w", err.Error(), native_errors.ErrNotFound)
}
return nil
}
// ClearMapVersioned removes all map entries from the map file.
func (s *SingleRuntime) ClearMapVersioned(name, version string) error {
cmd := fmt.Sprintf("clear map @%s %s", version, name)
if err := s.Execute(cmd); err != nil {
return fmt.Errorf("%s %w", err.Error(), native_errors.ErrNotFound)
}
return nil
}
// ShowMapEntries returns one map runtime entries
func (s *SingleRuntime) ShowMapEntries(name string) (models.MapEntries, error) {
cmd := fmt.Sprintf("show map %s", name)
response, err := s.ExecuteWithResponse(cmd)
if err != nil {
return nil, fmt.Errorf("%s %w", err.Error(), native_errors.ErrNotFound)
}
return ParseMapEntries(response, true), nil
}
// ShowMapEntriesVersioned returns one map runtime entries
func (s *SingleRuntime) ShowMapEntriesVersioned(name, version string) (models.MapEntries, error) {
cmd := fmt.Sprintf("show map @%s %s", version, name)
response, err := s.ExecuteWithResponse(cmd)
if err != nil {
return nil, fmt.Errorf("%s %w", err.Error(), native_errors.ErrNotFound)
}
return ParseMapEntries(response, true), nil
}
// ParseMapEntries parses array of entries in one map file
// One line sample entry:
// ID Key Value
// 0x55d155c6fbf0 static.example.com be_static
func ParseMapEntries(output string, hasID bool) models.MapEntries {
if output == "" {
return nil
}
me := models.MapEntries{}
lines := strings.Split(strings.TrimSpace(output), "\n")
for _, line := range lines {
e := parseMapEntry(line, hasID)
if e != nil {
me = append(me, e)
}
}
return me
}
// parseMapEntry parses one entry in one map file/runtime and returns it structured
func parseMapEntry(line string, hasID bool) *models.MapEntry {
if line == "" || strings.HasPrefix(strings.TrimSpace(line), "#") {
return nil
}
parts := strings.Fields(line)
if len(parts) < 2 {
return nil
}
m := &models.MapEntry{}
if hasID {
m.ID = parts[0] // map entries from runtime have ID
m.Key = parts[1]
m.Value = parts[2]
} else {
m.Key = parts[0] // map entries from file
m.Value = parts[1]
}
return m
}
func parseMapEntriesFromFile(inputFile io.Reader, hasID bool) models.MapEntries {
me := models.MapEntries{}
scanner := bufio.NewScanner(inputFile)
for scanner.Scan() {
e := parseMapEntry(scanner.Text(), hasID)
if e != nil {
me = append(me, e)
}
}
return me
}
// AddMapEntry adds an entry into the map file
func (s *SingleRuntime) AddMapEntry(name, key, value string) error {
m, _ := s.GetMapEntry(name, key)
if m != nil {
return fmt.Errorf("%w", native_errors.ErrAlreadyExists)
}
cmd := fmt.Sprintf("add map %s %s %s", name, key, value)
if err := s.Execute(cmd); err != nil {
return fmt.Errorf("%s %w", err.Error(), native_errors.ErrGeneral)
}
return nil
}
// AddMapEntryVersioned adds an entry into the map file
func (s *SingleRuntime) AddMapEntryVersioned(version, name, key, value string) error {
m, _ := s.GetMapEntry(name, key)
if m != nil {
return fmt.Errorf("%w", native_errors.ErrAlreadyExists)
}
cmd := fmt.Sprintf("add map @%s %s %s %s", version, name, key, value)
if err := s.Execute(cmd); err != nil {
return fmt.Errorf("%s %w", err.Error(), native_errors.ErrGeneral)
}
return nil
}
// AddMapPayload adds multiple entries to the map file
// payload param is a multi-line string where each line is a key/value pair
func (s *SingleRuntime) AddMapPayload(name, payload string) error {
prefix := "<<\n"
if len(payload) < len(prefix) || payload[0:len(prefix)] != prefix {
payload = "<<\n" + payload + "\n"
}
cmd := fmt.Sprintf("add map %s %s", name, payload)
if err := s.Execute(cmd); err != nil {
return fmt.Errorf("%s %w", err.Error(), native_errors.ErrGeneral)
}
return nil
}
func (s *SingleRuntime) PrepareMap(name string) (version string, err error) {
cmd := fmt.Sprintf("prepare map %s", name)
response, err := s.ExecuteWithResponse(cmd)
if err != nil {
return "", fmt.Errorf("%s %w", err.Error(), native_errors.ErrGeneral)
}
parts := strings.Split(response, ":")
if len(parts) < 3 {
return "", fmt.Errorf("%s %w", err.Error(), native_errors.ErrGeneral)
}
version = strings.TrimSpace(parts[2])
if _, err = strconv.ParseInt(version, 10, 64); err == nil {
return version, nil
}
return "", fmt.Errorf("%s %w", err.Error(), native_errors.ErrGeneral)
}
func (s *SingleRuntime) AddMapPayloadVersioned(version, name, payload string) error {
prefix := "<<\n"
if len(payload) < len(prefix) || payload[0:len(prefix)] != prefix {
payload = "<<\n" + payload + "\n"
}
cmd := fmt.Sprintf("add map @%s %s %s", version, name, payload)
if err := s.Execute(cmd); err != nil {
return fmt.Errorf("%s %w", err.Error(), native_errors.ErrGeneral)
}
return nil
}
func (s *SingleRuntime) CommitMap(version, name string) error {
cmd := fmt.Sprintf("commit map @%s %s", version, name)
if err := s.Execute(cmd); err != nil {
return fmt.Errorf("%s %w", err.Error(), native_errors.ErrGeneral)
}
return nil
}
// GetMapEntry returns one map runtime setting
func (s *SingleRuntime) GetMapEntry(name, id string) (*models.MapEntry, error) {
cmd := fmt.Sprintf("get map %s %s", name, id)
response, err := s.ExecuteWithResponse(cmd)
if err != nil {
return nil, fmt.Errorf("%s %w", err.Error(), native_errors.ErrNotFound)
}
m := &models.MapEntry{}
parts := strings.Split(response, ",")
for _, p := range parts {
kv := strings.Split(p, "=")
switch key := strings.TrimSpace(kv[0]); {
case key == "key":
m.Key = strings.TrimPrefix(strings.TrimSuffix(kv[1], "\""), "\"")
case key == "value":
m.Value = strings.TrimPrefix(strings.TrimSuffix(kv[1], "\""), "\"")
}
}
// safe guard m.Key != id:
// when id doesn't exist in runtime maps,
// but any existing key is substring of id
// get map command returns wrong result(BUG in HAProxy)
// so we need to check it
if m.Key == "" || m.Value == "" || m.Key != id {
return nil, fmt.Errorf("%s %w", id, native_errors.ErrNotFound)
}
return m, nil
}
// SetMapEntry replaces the value corresponding to each id in a map
func (s *SingleRuntime) SetMapEntry(name, id, value string) error {
cmd := fmt.Sprintf("set map %s %s %s", name, id, value)
if err := s.Execute(cmd); err != nil {
return fmt.Errorf("%s %w", err.Error(), native_errors.ErrNotFound)
}
return nil
}
// DeleteMapEntry deletes all the map entries from the map by its id
func (s *SingleRuntime) DeleteMapEntry(name, id string) error {
cmd := fmt.Sprintf("del map %s %s", name, id)
if err := s.Execute(cmd); err != nil {
return fmt.Errorf("%s %w", err.Error(), native_errors.ErrNotFound)
}
return nil
}