/
util.go
97 lines (84 loc) · 2.1 KB
/
util.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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"sort"
"time"
"github.com/kaneshin/esindex/elasticsearch"
)
const (
versionFormat = "20060102150405"
)
func indexNameFromAliasName(aliasName string) string {
return fmt.Sprintf("%s_v%s", aliasName, time.Now().Format(versionFormat))
}
func aliasNameFromIndexName(indexName string) string {
indexLen := len(indexName)
versionLen := len("_v" + versionFormat)
if versionLen < indexLen {
return indexName[:indexLen-versionLen]
}
return ""
}
func indexNamesAndAliasedIndexByAliasName(client *elasticsearch.Client, aliasName string) (names []string, aliased map[string]bool) {
req := elasticsearch.NewRequest("GET", "_aliases", nil)
res, err := client.Do(req)
if err != nil {
return
}
aliased = map[string]bool{}
for idxName, idx := range res {
if aliasNameFromIndexName(idxName) != aliasName {
continue
}
names = append(names, idxName)
if idx, ok := idx.(map[string]interface{}); ok {
if aliases, ok := idx["aliases"].(map[string]interface{}); ok {
for alias := range aliases {
if alias == aliasName {
aliased[idxName] = true
}
}
}
}
}
sort.Sort(sort.StringSlice(names))
return
}
type Action struct {
Alias string `json:"alias"`
Index string `json:"index"`
}
func updateAliases(client *elasticsearch.Client, addActions, removeActions []Action) error {
actions := []map[string]Action{}
for _, action := range addActions {
actions = append(actions, map[string]Action{
"add": action,
})
}
for _, action := range removeActions {
actions = append(actions, map[string]Action{
"remove": action,
})
}
body, err := json.Marshal(map[string]interface{}{"actions": actions})
if err != nil {
return err
}
req := elasticsearch.NewRequest("POST", "_aliases", bytes.NewReader(body))
res, err := client.Do(req)
if err != nil {
return err
}
if v, ok := res["error"].(string); ok && len(v) > 0 {
return errors.New(v)
}
return nil
}
func makeAlias(client *elasticsearch.Client, aliasName, indexName string) error {
return updateAliases(client, []Action{
Action{aliasName, indexName},
}, nil)
}