-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathos_client_v2.go
434 lines (373 loc) · 12.2 KB
/
os_client_v2.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
/*
Copyright AppsCode Inc. and Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package elasticsearch
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
dbapi "kubedb.dev/apimachinery/apis/kubedb/v1"
"github.com/opensearch-project/opensearch-go/opensearchapi"
osv2 "github.com/opensearch-project/opensearch-go/v2"
osv2api "github.com/opensearch-project/opensearch-go/v2/opensearchapi"
"github.com/pkg/errors"
core "k8s.io/api/core/v1"
"k8s.io/klog/v2"
kutil "kmodules.xyz/client-go"
)
var _ ESClient = &OSClientV2{}
type OSClientV2 struct {
client *osv2.Client
}
func (os *OSClientV2) ClusterHealthInfo() (map[string]interface{}, error) {
res, err := os.client.Cluster.Health(
os.client.Cluster.Health.WithPretty(),
)
if err != nil {
return nil, err
}
defer res.Body.Close()
response := make(map[string]interface{})
if err2 := json.NewDecoder(res.Body).Decode(&response); err2 != nil {
return nil, errors.Wrap(err2, "failed to parse the response body")
}
return response, nil
}
func (os *OSClientV2) NodesStats() (map[string]interface{}, error) {
req := osv2api.NodesStatsRequest{
Pretty: true,
Human: true,
}
resp, err := req.Do(context.Background(), os.client)
if err != nil {
return nil, err
}
defer resp.Body.Close()
nodesStats := make(map[string]interface{})
if err := json.NewDecoder(resp.Body).Decode(&nodesStats); err != nil {
return nil, fmt.Errorf("failed to deserialize the response: %v", err)
}
return nodesStats, nil
}
func (es *OSClientV2) ShardStats() ([]ShardInfo, error) {
req := osv2api.CatShardsRequest{
Bytes: "b",
Format: "json",
Pretty: true,
Human: true,
H: []string{"index", "shard", "prirep", "state", "unassigned.reason"},
}
resp, err := req.Do(context.Background(), es.client)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading body:", err)
}
var shardStats []ShardInfo
err = json.Unmarshal(body, &shardStats)
if err != nil {
return nil, err
}
return shardStats, nil
}
// GetIndicesInfo will return the indices' info of an Elasticsearch database
func (os *OSClientV2) GetIndicesInfo() ([]interface{}, error) {
req := osv2api.CatIndicesRequest{
Bytes: "b", // will return resource size field into byte unit
Format: "json",
Pretty: true,
Human: true,
}
resp, err := req.Do(context.Background(), os.client)
if err != nil {
return nil, err
}
defer resp.Body.Close()
indicesInfo := make([]interface{}, 0)
if err := json.NewDecoder(resp.Body).Decode(&indicesInfo); err != nil {
return nil, fmt.Errorf("failed to deserialize the response: %v", err)
}
return indicesInfo, nil
}
func (os *OSClientV2) ClusterStatus() (string, error) {
res, err := os.client.Cluster.Health(
os.client.Cluster.Health.WithPretty(),
)
if err != nil {
return "", err
}
defer res.Body.Close()
response := make(map[string]interface{})
if err2 := json.NewDecoder(res.Body).Decode(&response); err2 != nil {
return "", errors.Wrap(err2, "failed to parse the response body")
}
if value, ok := response["status"]; ok {
if strValue, ok := value.(string); ok {
return strValue, nil
}
return "", errors.New("failed to convert response to string")
}
return "", errors.New("status is missing")
}
func (os *OSClientV2) GetClusterWriteStatus(ctx context.Context, db *dbapi.Elasticsearch) error {
// Build the request index & request body
// send the db specs as body
indexBody := WriteRequestIndexBody{
ID: writeRequestID,
}
indexReq := WriteRequestIndex{indexBody}
ReqBody := db.Spec
// encode the request index & request body
index, err1 := json.Marshal(indexReq)
if err1 != nil {
return errors.Wrap(err1, "Failed to encode index for performing write request")
}
body, err2 := json.Marshal(ReqBody)
if err2 != nil {
return errors.Wrap(err2, "Failed to encode request body for performing write request")
}
// make write request & fetch response
// check for write request failure & error from response body
// Bulk API Performs multiple indexing or delete operations in a single API call
// This reduces overhead and can greatly increase indexing speed it Indexes the specified document
// If the document exists, replaces the document and increments the version
res, err3 := osv2api.BulkRequest{
Index: writeRequestIndex,
Body: strings.NewReader(strings.Join([]string{string(index), string(body)}, "\n") + "\n"),
Pretty: true,
}.Do(ctx, os.client.Transport)
if err3 != nil {
return errors.Wrap(err3, "Failed to perform write request")
}
if res.IsError() {
return fmt.Errorf("failed to get response from write request with error statuscode %d", res.StatusCode)
}
defer func(res *osv2api.Response) {
if res != nil {
err3 = res.Body.Close()
if err3 != nil {
klog.Errorf("Failed to close write request response body, reason: %s", err3)
}
}
}(res)
responseBody := make(map[string]interface{})
if err4 := json.NewDecoder(res.Body).Decode(&responseBody); err4 != nil {
return errors.Wrap(err4, "Failed to decode response from write request")
}
// Parse the responseBody to check if write operation failed after request being successful
// `errors` field(boolean) in the json response becomes true if there's and error caused, otherwise it stays nil
if value, ok := responseBody["errors"]; ok {
if strValue, ok := value.(bool); ok {
if !strValue {
return nil
}
return errors.Errorf("Write request responded with error, %v", responseBody)
}
return errors.New("Failed to parse value for `errors` in response from write request")
}
return errors.New("Failed to parse key `errors` in response from write request")
}
func (os *OSClientV2) GetClusterReadStatus(ctx context.Context, db *dbapi.Elasticsearch) error {
// Perform a read request in writeRequestIndex/writeRequestID (kubedb-system/info) API
// Handle error specifically if index has not been created yet
res, err := osv2api.GetRequest{
Index: writeRequestIndex,
DocumentID: writeRequestID,
}.Do(ctx, os.client.Transport)
if err != nil {
return errors.Wrap(err, "Failed to perform read request")
}
defer func(res *osv2api.Response) {
if res != nil {
err = res.Body.Close()
if err != nil {
klog.Errorf("failed to close read request response body, reason: %s", err)
}
}
}(res)
if res.StatusCode == http.StatusNotFound {
return kutil.ErrNotFound
}
if res.IsError() {
return fmt.Errorf("failed to get response from read request with error statuscode %d", res.StatusCode)
}
return nil
}
func (os *OSClientV2) GetTotalDiskUsage(ctx context.Context) (string, error) {
// Perform a DiskUsageRequest to database to calculate store size of all the elasticsearch indices
// primary purpose of this function is to provide operator calculated storage of interimVolumeTemplate while taking backup
// Analyzing field disk usage is resource-intensive. To use the API, RunExpensiveTasks must be set to true. Defaults to false.
// Get disk usage for all indices using "*" wildcard.
flag := true
res, err := osv2api.IndicesDiskUsageRequest{
Index: diskUsageRequestIndex,
Pretty: true,
Human: true,
RunExpensiveTasks: &flag,
ExpandWildcards: diskUsageRequestWildcards,
}.Do(ctx, os.client.Transport)
if err != nil {
return "", errors.Wrap(err, "Failed to perform Disk Usage Request")
}
defer func(Body io.ReadCloser) {
err = Body.Close()
if err != nil {
klog.Errorf("failed to close response body from Disk Usage Request, reason: %s", err)
}
}(res.Body)
// Parse the json response to get total storage used for all index
totalDiskUsage, err := calculateDatabaseSize(res.Body)
if err != nil {
return "", errors.Wrap(err, "Failed to parse json response to get disk usage")
}
return totalDiskUsage, nil
}
func (os *OSClientV2) SyncCredentialFromSecret(secret *core.Secret) error {
return nil
}
func (os *OSClientV2) GetDBUserRole(ctx context.Context) (error, bool) {
return errors.New("not supported in os version 2"), false
}
func (os *OSClientV2) CreateDBUserRole(ctx context.Context) error {
return errors.New("not supported in os version 2")
}
func (os *OSClientV2) IndexExistsOrNot(index string) error {
req := opensearchapi.IndicesExistsRequest{
Index: []string{index},
}
res, err := req.Do(context.Background(), os.client)
if err != nil {
klog.Errorf("failed to get response while checking either index exists or not %v", err)
return err
}
defer func(Body io.ReadCloser) {
err = Body.Close()
if err != nil {
klog.Errorf("failed to close response body for checking the existence of index, reason: %s", err)
}
}(res.Body)
if res.IsError() {
klog.Errorf("index does not exist")
return fmt.Errorf("failed to get index with statuscode %d", res.StatusCode)
}
return nil
}
func (os *OSClientV2) CreateIndex(index string) error {
req := opensearchapi.IndicesCreateRequest{
Index: index,
Pretty: true,
Human: true,
}
res, err := req.Do(context.Background(), os.client)
if err != nil {
klog.Errorf("failed to apply create index request, reason: %s", err)
return err
}
defer func(Body io.ReadCloser) {
err = Body.Close()
if err != nil {
klog.Errorf("failed to close response body for creating index, reason: %s", err)
}
}(res.Body)
if res.IsError() {
klog.Errorf("creating index failed with statuscode %d", res.StatusCode)
return errors.New("failed to create index")
}
return nil
}
func (os *OSClientV2) DeleteIndex(index string) error {
req := opensearchapi.IndicesDeleteRequest{
Index: []string{index},
}
res, err := req.Do(context.Background(), os.client)
if err != nil {
klog.Errorf("failed to apply delete index request, reason: %s", err)
return err
}
defer func(Body io.ReadCloser) {
err = Body.Close()
if err != nil {
klog.Errorf("failed to close response body for deleting index, reason: %s", err)
}
}(res.Body)
if res.IsError() {
klog.Errorf("failed to delete index with status code %d", res.StatusCode)
return errors.New("failed to delete index")
}
return nil
}
func (os *OSClientV2) CountData(index string) (int, error) {
req := opensearchapi.CountRequest{
Index: []string{index},
}
res, err := req.Do(context.Background(), os.client)
if err != nil {
return 0, err
}
defer func(Body io.ReadCloser) {
err = Body.Close()
if err != nil {
klog.Errorf("failed to close response body for counting data, reason: %s", err)
}
}(res.Body)
if res.IsError() {
klog.Errorf("failed to count number of documents in index with statuscode %d", res.StatusCode)
return 0, errors.New("failed to count number of documents in index")
}
var response map[string]interface{}
if err := json.NewDecoder(res.Body).Decode(&response); err != nil {
return 0, err
}
count, ok := response["count"]
if !ok {
return 0, errors.New("failed to parse value for index count in response body")
}
return int(count.(float64)), nil
}
func (os *OSClientV2) PutData(index, id string, data map[string]interface{}) error {
var b strings.Builder
dataBytes, err := json.Marshal(data)
if err != nil {
return errors.Wrap(err, "failed to Marshal data")
}
b.Write(dataBytes)
// CreateRequest is not supported in OS V2.
req := opensearchapi.IndexRequest{
Index: index,
DocumentID: id,
Body: strings.NewReader(b.String()),
Pretty: true,
Human: true,
}
res, err := req.Do(context.Background(), os.client)
if err != nil {
klog.Errorf("failed to put data in the index, reason: %s", err)
return err
}
defer func(Body io.ReadCloser) {
err = Body.Close()
if err != nil {
klog.Errorf("failed to close response body for putting data in the index, reason: %s", err)
}
}(res.Body)
if res.IsError() {
klog.Errorf("failed to put data in an index with statuscode %d", res.StatusCode)
return errors.New("failed to put data in an index")
}
return nil
}