-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathalias.go
84 lines (73 loc) · 1.95 KB
/
alias.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
package eskeeper
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
)
func (c *esclient) existAlias(ctx context.Context, alias string) (bool, error) {
exists := c.client.Indices.ExistsAlias
res, err := exists(
[]string{alias},
exists.WithContext(ctx),
)
if err != nil {
return false, fmt.Errorf("check alias exists: %w", err)
}
if res.StatusCode == 200 {
return true, nil
}
return false, nil
}
func (c *esclient) syncAlias(ctx context.Context, alias alias) error {
i := c.client.Indices
query := aliasQuery(alias.Name, alias.Indices)
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(query); err != nil {
return fmt.Errorf("build query: %w", err)
}
res, err := i.UpdateAliases(&buf, i.UpdateAliases.WithContext(ctx))
if err != nil {
return fmt.Errorf("upsert aliases: %w", err)
}
if res.StatusCode != 200 {
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("failed to sync alias [alias=%v, statusCode=%v]", alias.Name, res.StatusCode)
}
return fmt.Errorf("failed to sync alias [alias=%v, statusCode=%v, res=%v]", alias.Name, res.StatusCode, string(body))
}
return nil
}
func (c *esclient) syncAliases(ctx context.Context, conf config) error {
for _, alias := range conf.Aliases {
err := c.syncAlias(ctx, alias)
if err != nil {
c.logf("[fail] alias: %v\n", alias.Name)
return fmt.Errorf("sync alias: %w", err)
}
c.logf("[synced] alias: %v\n", alias.Name)
}
return nil
}
func aliasQuery(aliasName string, indices []string) map[string]interface{} {
Actions := make([]map[string]interface{}, 0, len(indices)+1)
Actions = append(Actions, map[string]interface{}{
"remove": map[string]interface{}{
"index": "*",
"alias": aliasName,
},
})
for _, index := range indices {
Actions = append(Actions, map[string]interface{}{
"add": map[string]interface{}{
"index": index,
"alias": aliasName,
},
})
}
return map[string]interface{}{
"actions": Actions,
}
}