-
Notifications
You must be signed in to change notification settings - Fork 52
/
cluster.go
344 lines (293 loc) · 10.5 KB
/
cluster.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package infinispan
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
consts "github.com/infinispan/infinispan-operator/pkg/controller/constants"
ispnclient "github.com/infinispan/infinispan-operator/pkg/infinispan/client/http"
"github.com/infinispan/infinispan-operator/pkg/infinispan/client/http/curl"
kube "github.com/infinispan/infinispan-operator/pkg/kubernetes"
)
// Cluster abstracts interaction with an Infinispan cluster
type Cluster struct {
Kubernetes *kube.Kubernetes
Client ispnclient.HttpClient
Namespace string
}
// ClusterHealth represents the health of the cluster
type ClusterHealth struct {
Nodes []string `json:"node_names"`
}
// Health represents the health of an Infinispan server
type Health struct {
ClusterHealth ClusterHealth `json:"cluster_health"`
}
type CacheManagerInfo struct {
Coordinator bool `json:"coordinator"`
SitesView *[]interface{} `json:"sites_view,omitempty"`
}
type Logger struct {
Name string `json:"name"`
Level string `json:"level"`
}
func (i CacheManagerInfo) GetSitesView() (map[string]bool, error) {
sitesView := make(map[string]bool)
if i.SitesView == nil {
return nil, fmt.Errorf("retrieving the cross-site view is not supported with the server image you are using")
}
for _, site := range *i.SitesView {
sitesView[site.(string)] = true
}
return sitesView, nil
}
// ClusterInterface represents the interface of a Cluster instance
type ClusterInterface interface {
GetClusterSize(podName string) (int, error)
GracefulShutdown(podName string) error
GetClusterMembers(podName string) ([]string, error)
ExistsCache(cacheName, podName string) (bool, error)
CreateCacheWithTemplate(cacheName, cacheXML, podName string) error
CreateCacheWithTemplateName(cacheName, templateName, podName string) error
GetMemoryLimitBytes(podName string) (uint64, error)
GetMaxMemoryUnboundedBytes(podName string) (uint64, error)
CacheNames(podName string) ([]string, error)
GetMetrics(podName, postfix string) (*bytes.Buffer, error)
GetCacheManagerInfo(cacheManagerName, podName string) (*CacheManagerInfo, error)
GetLoggers(podName string) (map[string]string, error)
SetLogger(podName, loggerName, loggerLevel string) error
}
// NewClusterNoAuth creates a new instance of Cluster without authentication
func NewClusterNoAuth(namespace string, protocol string, kubernetes *kube.Kubernetes) *Cluster {
return cluster(namespace, protocol, nil, kubernetes)
}
// NewCluster creates a new instance of Cluster
func NewCluster(username, password, namespace string, protocol string, kubernetes *kube.Kubernetes) *Cluster {
credentials := &ispnclient.Credentials{
Username: username,
Password: password,
}
return cluster(namespace, protocol, credentials, kubernetes)
}
func cluster(namespace, protocol string, credentials *ispnclient.Credentials, kubernetes *kube.Kubernetes) *Cluster {
client := curl.New(ispnclient.HttpConfig{
Credentials: credentials,
Namespace: namespace,
Protocol: protocol,
}, kubernetes)
return &Cluster{
Kubernetes: kubernetes,
Client: client,
Namespace: namespace,
}
}
// GetClusterSize returns the size of the cluster as seen by a given pod
func (c Cluster) GetClusterSize(podName string) (int, error) {
members, err := c.GetClusterMembers(podName)
if err != nil {
return -1, err
}
return len(members), nil
}
// GracefulShutdown performs clean cluster shutdown
func (c Cluster) GracefulShutdown(podName string) error {
rsp, err, reason := c.Client.Post(podName, consts.ServerHTTPClusterStop, "", nil)
return validateResponse(rsp, reason, err, "during graceful shutdown", http.StatusNoContent)
}
// GetClusterMembers get the cluster members as seen by a given pod
func (c Cluster) GetClusterMembers(podName string) (members []string, err error) {
rsp, err, reason := c.Client.Get(podName, consts.ServerHTTPHealthPath, nil)
if err = validateResponse(rsp, reason, err, "getting cluster members", http.StatusOK); err != nil {
return
}
defer func() {
cerr := rsp.Body.Close()
if err == nil {
err = cerr
}
}()
var health Health
if err := json.NewDecoder(rsp.Body).Decode(&health); err != nil {
return nil, fmt.Errorf("unable to decode: %v", err)
}
return health.ClusterHealth.Nodes, nil
}
// ExistsCache returns true if cacheName cache exists on the podName pod
func (c Cluster) ExistsCache(cacheName, podName string) (bool, error) {
path := fmt.Sprintf("%s/caches/%s", consts.ServerHTTPBasePath, cacheName)
rsp, err, reason := c.Client.Head(podName, path, nil)
if err := validateResponse(rsp, reason, err, "validating cache exists", http.StatusOK, http.StatusNoContent, http.StatusNotFound); err != nil {
return false, err
}
switch rsp.StatusCode {
case http.StatusOK, http.StatusNoContent:
return true, nil
case http.StatusNotFound:
return false, nil
}
return false, nil
}
// CacheNames return the names of the cluster caches available on the pod `podName`
func (c Cluster) CacheNames(podName string) (caches []string, err error) {
path := fmt.Sprintf("%s/caches", consts.ServerHTTPBasePath)
rsp, err, reason := c.Client.Get(podName, path, nil)
if err = validateResponse(rsp, reason, err, "getting caches", http.StatusOK); err != nil {
return
}
defer func() {
cerr := rsp.Body.Close()
if err == nil {
err = cerr
}
}()
if err := json.NewDecoder(rsp.Body).Decode(&caches); err != nil {
return nil, fmt.Errorf("unable to decode: %v", err)
}
return
}
// CreateCacheWithTemplate create cluster cache on the pod `podName`
func (c Cluster) CreateCacheWithTemplate(cacheName, cacheXML, podName string) error {
headers := make(map[string]string)
headers["Content-Type"] = "application/xml"
path := fmt.Sprintf("%s/caches/%s", consts.ServerHTTPBasePath, cacheName)
rsp, err, reason := c.Client.Post(podName, path, cacheXML, headers)
return validateResponse(rsp, reason, err, "creating cache", http.StatusOK)
}
// CreateCacheWithTemplateName create cluster cache on the pod `podName`
func (c Cluster) CreateCacheWithTemplateName(cacheName, templateName, podName string) error {
path := fmt.Sprintf("%s/caches/%s?template=%s", consts.ServerHTTPBasePath, cacheName, templateName)
rsp, err, reason := c.Client.Post(podName, path, "", nil)
return validateResponse(rsp, reason, err, "creating cache with template", http.StatusOK)
}
func (c Cluster) GetMemoryLimitBytes(podName string) (uint64, error) {
command := []string{"cat", "/sys/fs/cgroup/memory/memory.limit_in_bytes"}
execOptions := kube.ExecOptions{Command: command, PodName: podName, Namespace: c.Namespace}
execOut, execErr, err := c.Kubernetes.ExecWithOptions(execOptions)
if err != nil {
return 0, fmt.Errorf("unexpected error getting memory limit bytes, stderr: %v, err: %v", execErr, err)
}
result := strings.TrimSuffix(execOut.String(), "\n")
limitBytes, err := strconv.ParseUint(result, 10, 64)
if err != nil {
return 0, err
}
return limitBytes, nil
}
func (c Cluster) GetMaxMemoryUnboundedBytes(podName string) (uint64, error) {
command := []string{"cat", "/proc/meminfo"}
execOptions := kube.ExecOptions{Command: command, PodName: podName, Namespace: c.Namespace}
execOut, execErr, err := c.Kubernetes.ExecWithOptions(execOptions)
if err != nil {
return 0, fmt.Errorf("unexpected error getting max unbounded memory, stderr: %v, err: %v", execErr, err)
}
result := execOut.String()
lines := strings.Split(result, "\n")
for _, line := range lines {
if strings.Contains(line, "MemTotal:") {
tokens := strings.Fields(line)
maxUnboundKb, err := strconv.ParseUint(tokens[1], 10, 64)
if err != nil {
return 0, err
}
return maxUnboundKb * 1024, nil
}
}
return 0, fmt.Errorf("meminfo lacking MemTotal information")
}
// GetMetrics return pod metrics
func (c Cluster) GetMetrics(podName, postfix string) (buf *bytes.Buffer, err error) {
headers := make(map[string]string)
headers["Accept"] = "application/json"
path := fmt.Sprintf("metrics/%s", postfix)
rsp, err, reason := c.Client.Get(podName, path, headers)
if err = validateResponse(rsp, reason, err, "getting metrics", http.StatusOK); err != nil {
return
}
defer func() {
cerr := rsp.Body.Close()
if err == nil {
err = cerr
}
}()
buf = new(bytes.Buffer)
if _, err = buf.ReadFrom(rsp.Body); err != nil {
return
}
return
}
// GetCacheManagerInfo via REST v2 interface
func (c Cluster) GetCacheManagerInfo(cacheManagerName, podName string) (info *CacheManagerInfo, err error) {
path := fmt.Sprintf("%s/cache-managers/%s", consts.ServerHTTPBasePath, cacheManagerName)
rsp, err, reason := c.Client.Get(podName, path, nil)
if err = validateResponse(rsp, reason, err, "getting cache manager info", http.StatusOK); err != nil {
return
}
defer func() {
cerr := rsp.Body.Close()
if err == nil {
err = cerr
}
}()
if err = json.NewDecoder(rsp.Body).Decode(&info); err != nil {
return nil, fmt.Errorf("unable to decode: %v", err)
}
return
}
func (c Cluster) GetLoggers(podName string) (lm map[string]string, err error) {
rsp, err, reason := c.Client.Get(podName, consts.ServerHTTPLoggersPath, nil)
if err = validateResponse(rsp, reason, err, "getting cluster loggers", http.StatusOK); err != nil {
return
}
defer func() {
cerr := rsp.Body.Close()
if err == nil {
err = cerr
}
}()
var loggers []Logger
if err := json.NewDecoder(rsp.Body).Decode(&loggers); err != nil {
return nil, fmt.Errorf("unable to decode: %v", err)
}
lm = make(map[string]string)
for _, logger := range loggers {
if logger.Name != "" {
lm[logger.Name] = logger.Level
}
}
return
}
func (c Cluster) SetLogger(podName, loggerName, loggerLevel string) error {
path := fmt.Sprintf(consts.ServerHTTPModifyLoggerPath, loggerName, strings.ToUpper(loggerLevel))
rsp, err, reason := c.Client.Put(podName, path, "", nil)
if err := validateResponse(rsp, reason, err, "setting cluster logger", http.StatusNoContent); err != nil {
return err
}
return nil
}
func validateResponse(rsp *http.Response, reason string, inperr error, entity string, validCodes ...int) (err error) {
if inperr != nil {
return fmt.Errorf("unexpected error %s, stderr: %s, err: %v", entity, reason, inperr)
}
if rsp == nil || len(validCodes) == 0 {
return
}
for _, code := range validCodes {
if code == rsp.StatusCode {
return
}
}
defer func() {
cerr := rsp.Body.Close()
if err == nil {
err = cerr
}
}()
responseBody, responseErr := ioutil.ReadAll(rsp.Body)
if responseErr != nil {
return fmt.Errorf("server side error %s. Unable to read response body, %v", entity, responseErr)
}
return fmt.Errorf("unexpected error %s, response: %v", entity, consts.GetWithDefault(string(responseBody), rsp.Status))
}