forked from cadence-workflow/cadence
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadmin_elastic_search_commands.go
538 lines (496 loc) · 15.2 KB
/
admin_elastic_search_commands.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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package cli
import (
"bufio"
"context"
"encoding/json"
"fmt"
"math"
"os"
"strconv"
"strings"
"time"
"github.com/olekukonko/tablewriter"
"github.com/olivere/elastic"
"github.com/urfave/cli"
"github.com/uber/cadence/.gen/go/indexer"
"github.com/uber/cadence/common/clock"
"github.com/uber/cadence/common/elasticsearch"
es "github.com/uber/cadence/common/elasticsearch"
"github.com/uber/cadence/common/elasticsearch/esql"
"github.com/uber/cadence/common/tokenbucket"
)
const (
versionTypeExternal = "external"
)
var timeKeys = map[string]bool{
"StartTime": true,
"CloseTime": true,
"ExecutionTime": true,
}
func timeKeyFilter(key string) bool {
return timeKeys[key]
}
func timeValProcess(timeStr string) (string, error) {
// first check if already in int64 format
if _, err := strconv.ParseInt(timeStr, 10, 64); err == nil {
return timeStr, nil
}
// try to parse time
parsedTime, err := time.Parse(defaultDateTimeFormat, timeStr)
if err != nil {
return "", err
}
return fmt.Sprintf("%v", parsedTime.UnixNano()), nil
}
type ESIndexRow struct {
Health string `header:"Health"`
Status string `header:"Status"`
Index string `header:"Index"`
PrimaryShards int `header:"Pri"`
ReplicaShards int `header:"Rep"`
DocsCount int `header:"Docs Count"`
DocsDeleted int `header:"Docs Deleted"`
StorageSize string `header:"Store Size"`
PrimaryStorageSize string `header:"Pri Store Size"`
}
// AdminCatIndices cat indices for ES cluster
func AdminCatIndices(c *cli.Context) {
esClient := cFactory.ElasticSearchClient(c)
ctx := context.Background()
resp, err := esClient.CatIndices().Do(ctx)
if err != nil {
ErrorAndExit("Unable to cat indices", err)
}
table := []ESIndexRow{}
for _, row := range resp {
table = append(table, ESIndexRow{
Health: row.Health,
Status: row.Status,
Index: row.Index,
PrimaryShards: row.Pri,
ReplicaShards: row.Rep,
DocsCount: row.DocsCount,
DocsDeleted: row.DocsDeleted,
StorageSize: row.StoreSize,
PrimaryStorageSize: row.PriStoreSize,
})
}
Render(c, table, RenderOptions{DefaultTemplate: templateTable, Color: true, Border: true})
}
// AdminIndex used to bulk insert message from kafka parse
func AdminIndex(c *cli.Context) {
esClient := cFactory.ElasticSearchClient(c)
indexName := getRequiredOption(c, FlagIndex)
inputFileName := getRequiredOption(c, FlagInputFile)
batchSize := c.Int(FlagBatchSize)
messages, err := parseIndexerMessage(inputFileName)
if err != nil {
ErrorAndExit("Unable to parse indexer message", err)
}
bulkRequest := esClient.Bulk()
bulkConductFn := func() {
_, err := bulkRequest.Do(context.Background())
if err != nil {
ErrorAndExit("Bulk failed", err)
}
if bulkRequest.NumberOfActions() != 0 {
ErrorAndExit(fmt.Sprintf("Bulk request not done, %d", bulkRequest.NumberOfActions()), err)
}
}
for i, message := range messages {
docID := message.GetWorkflowID() + elasticsearch.GetESDocDelimiter() + message.GetRunID()
var req elastic.BulkableRequest
switch message.GetMessageType() {
case indexer.MessageTypeIndex:
doc := generateESDoc(message)
req = elastic.NewBulkIndexRequest().
Index(indexName).
Type(elasticsearch.GetESDocType()).
Id(docID).
VersionType(versionTypeExternal).
Version(message.GetVersion()).
Doc(doc)
case indexer.MessageTypeDelete:
req = elastic.NewBulkDeleteRequest().
Index(indexName).
Type(elasticsearch.GetESDocType()).
Id(docID).
VersionType(versionTypeExternal).
Version(message.GetVersion())
case indexer.MessageTypeCreate:
req = elastic.NewBulkIndexRequest().
OpType("create").
Index(indexName).
Type(elasticsearch.GetESDocType()).
Id(docID).
VersionType("internal")
default:
ErrorAndExit("Unknown message type", nil)
}
bulkRequest.Add(req)
if i%batchSize == batchSize-1 {
bulkConductFn()
}
}
if bulkRequest.NumberOfActions() != 0 {
bulkConductFn()
}
}
// AdminDelete used to delete documents from ElasticSearch with input of list result
func AdminDelete(c *cli.Context) {
esClient := cFactory.ElasticSearchClient(c)
indexName := getRequiredOption(c, FlagIndex)
inputFileName := getRequiredOption(c, FlagInputFile)
batchSize := c.Int(FlagBatchSize)
rps := c.Int(FlagRPS)
ratelimiter := tokenbucket.New(rps, clock.NewRealTimeSource())
// This is only executed from the CLI by an admin user
// #nosec
file, err := os.Open(inputFileName)
if err != nil {
ErrorAndExit("Cannot open input file", nil)
}
defer file.Close()
scanner := bufio.NewScanner(file)
scanner.Scan() // skip first line
i := 0
bulkRequest := esClient.Bulk()
bulkConductFn := func() {
ok, waitTime := ratelimiter.TryConsume(1)
if !ok {
time.Sleep(waitTime)
}
_, err := bulkRequest.Do(context.Background())
if err != nil {
ErrorAndExit(fmt.Sprintf("Bulk failed, current processed row %d", i), err)
}
if bulkRequest.NumberOfActions() != 0 {
ErrorAndExit(fmt.Sprintf("Bulk request not done, current processed row %d", i), err)
}
}
for scanner.Scan() {
line := strings.Split(scanner.Text(), "|")
docID := strings.TrimSpace(line[1]) + elasticsearch.GetESDocDelimiter() + strings.TrimSpace(line[2])
req := elastic.NewBulkDeleteRequest().
Index(indexName).
Type(elasticsearch.GetESDocType()).
Id(docID).
VersionType(versionTypeExternal).
Version(math.MaxInt64)
bulkRequest.Add(req)
if i%batchSize == batchSize-1 {
bulkConductFn()
}
i++
}
if bulkRequest.NumberOfActions() != 0 {
bulkConductFn()
}
}
func parseIndexerMessage(fileName string) (messages []*indexer.Message, err error) {
// Executed from the CLI to parse existing elastiseach files
// #nosec
file, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
idx := 0
for scanner.Scan() {
idx++
line := strings.TrimSpace(scanner.Text())
if len(line) == 0 {
fmt.Printf("line %v is empty, skipped\n", idx)
continue
}
msg := &indexer.Message{}
err := json.Unmarshal([]byte(line), msg)
if err != nil {
fmt.Printf("line %v cannot be deserialized to indexer message: %v.\n", idx, line)
return nil, err
}
messages = append(messages, msg)
}
if err := scanner.Err(); err != nil {
return nil, err
}
return messages, nil
}
func generateESDoc(msg *indexer.Message) map[string]interface{} {
doc := make(map[string]interface{})
doc[es.DomainID] = msg.GetDomainID()
doc[es.WorkflowID] = msg.GetWorkflowID()
doc[es.RunID] = msg.GetRunID()
for k, v := range msg.Fields {
switch v.GetType() {
case indexer.FieldTypeString:
doc[k] = v.GetStringData()
case indexer.FieldTypeInt:
doc[k] = v.GetIntData()
case indexer.FieldTypeBool:
doc[k] = v.GetBoolData()
case indexer.FieldTypeBinary:
doc[k] = v.GetBinaryData()
default:
ErrorAndExit("Unknown field type", nil)
}
}
return doc
}
// This function is used to trim unnecessary tag in returned json for table header
func trimBucketKey(k string) string {
// group key is in form of "group_key", we only need "key" as the column name
k = strings.TrimPrefix(k, "group_")
k = strings.TrimPrefix(k, "Attr_")
return fmt.Sprintf(`%v(*)`, k)
}
// parse the returned time to readable string if time is in int64 format
func toTimeStr(s interface{}) string {
floatTime, err := strconv.ParseFloat(s.(string), 64)
intTime := int64(floatTime)
if err != nil {
return s.(string)
}
t := time.Unix(0, intTime)
return t.Format(time.RFC3339)
}
// GenerateReport generate report for an aggregation query to ES
func GenerateReport(c *cli.Context) {
// use url command argument to create client
index := getRequiredOption(c, FlagIndex)
sql := getRequiredOption(c, FlagListQuery)
var reportFormat, reportFilePath string
if c.IsSet(FlagOutputFormat) {
reportFormat = c.String(FlagOutputFormat)
}
if c.IsSet(FlagOutputFilename) {
reportFilePath = c.String(FlagOutputFilename)
} else {
reportFilePath = "./report." + reportFormat
}
esClient := cFactory.ElasticSearchClient(c)
ctx := context.Background()
// convert sql to dsl
e := esql.NewESql()
e.SetCadence(true)
e.ProcessQueryValue(timeKeyFilter, timeValProcess)
dsl, sortFields, err := e.ConvertPrettyCadence(sql, "")
if err != nil {
ErrorAndExit("Fail to convert sql to dsl", err)
}
// query client
resp, err := esClient.Search(index).Source(dsl).Do(ctx)
if err != nil {
ErrorAndExit("Fail to talk with ES", err)
}
// Show result to terminal
table := tablewriter.NewWriter(os.Stdout)
var headers []string
var groupby, bucket map[string]interface{}
var buckets []interface{}
err = json.Unmarshal(*resp.Aggregations["groupby"], &groupby)
if err != nil {
ErrorAndExit("Fail to parse groupby", err)
}
buckets = groupby["buckets"].([]interface{})
if len(buckets) == 0 {
fmt.Println("no matching bucket")
return
}
// get the FIRST bucket in bucket list to extract all tags. These extracted tags are to be used as table heads
bucket = buckets[0].(map[string]interface{})
// record the column position in the table of each returned item
ids := make(map[string]int)
// We want these 3 columns shows at leftmost of the table in cadence report usage. It can be changed in future.
primaryCols := []string{"group_DomainID", "group_WorkflowType", "group_CloseStatus"}
primaryColsMap := map[string]int{
"group_DomainID": 1,
"group_WorkflowType": 1,
"group_CloseStatus": 1,
}
buckKeys := 0 // number of bucket keys, used for table collapsing in html report
if v, exist := bucket["key"]; exist {
vmap := v.(map[string]interface{})
// first search whether primaryCols keys exist, if found, put them at the table beginning
for _, k := range primaryCols {
if _, exist := vmap[k]; exist {
k = trimBucketKey(k) // trim the unnecessary prefix
headers = append(headers, k)
ids[k] = len(ids)
buckKeys++
}
}
// extract all remaining bucket keys
for k := range vmap {
if _, exist := primaryColsMap[k]; !exist {
k = trimBucketKey(k)
headers = append(headers, k)
ids[k] = len(ids)
buckKeys++
}
}
}
// extract all other non-key items and set the table head accordingly
for k := range bucket {
if k != "key" {
if k == "doc_count" {
k = "count"
}
headers = append(headers, k)
ids[k] = len(ids)
}
}
table.SetHeader(headers)
// read each bucket and fill the table, use map ids to find the correct spot
var tableData [][]string
for _, b := range buckets {
bucket = b.(map[string]interface{})
data := make([]string, len(headers))
for k, v := range bucket {
switch k {
case "key": // fill group key
vmap := v.(map[string]interface{})
for kk, vv := range vmap {
kk = trimBucketKey(kk)
data[ids[kk]] = fmt.Sprintf("%v", vv)
}
case "doc_count": // fill bucket size count
data[ids["count"]] = fmt.Sprintf("%v", v)
default:
var datum string
vmap := v.(map[string]interface{})
if strings.Contains(k, "Attr_CustomDatetimeField") {
datum = fmt.Sprintf("%v", vmap["value_as_string"])
} else {
datum = fmt.Sprintf("%v", vmap["value"])
// convert Cadence stored time (unix nano) to readable format
if strings.Contains(k, "Time") && !strings.Contains(k, "Attr_") {
datum = toTimeStr(datum)
}
}
data[ids[k]] = datum
}
}
table.Append(data)
tableData = append(tableData, data)
}
table.Render()
switch reportFormat {
case "html", "HTML":
sorted := len(sortFields) > 0 || strings.Contains(sql, "ORDER BY") || strings.Contains(sql, "order by")
generateHTMLReport(reportFilePath, buckKeys, sorted, headers, tableData)
case "csv", "CSV":
generateCSVReport(reportFilePath, headers, tableData)
default:
ErrorAndExit(fmt.Sprintf(`Report format %v not supported.`, reportFormat), nil)
}
}
func generateCSVReport(reportFileName string, headers []string, tableData [][]string) {
// write csv report
f, err := os.Create(reportFileName)
if err != nil {
ErrorAndExit("Fail to create csv report file", err)
}
csvContent := strings.Join(headers, ",") + "\n"
for _, data := range tableData {
csvContent += strings.Join(data, ",") + "\n"
}
_, err = f.WriteString(csvContent)
if err != nil {
fmt.Printf("Error write to file, err: %v", err)
}
f.Close()
}
func generateHTMLReport(reportFileName string, numBuckKeys int, sorted bool, headers []string, tableData [][]string) {
// write html report
f, err := os.Create(reportFileName)
if err != nil {
ErrorAndExit("Fail to create html report file", err)
}
var htmlContent string
m, n := len(headers), len(tableData)
rowSpan := make([]int, m) // record the collapsing size of each column
for i := 0; i < m; i++ {
rowSpan[i] = 1
cell := wrapWithTag(headers[i], "td", "")
htmlContent += cell
}
htmlContent = wrapWithTag(htmlContent, "tr", "")
for row := 0; row < n; row++ {
var rowData string
for col := 0; col < m; col++ {
rowSpan[col]--
// don't do collapsing if sorted
if col < numBuckKeys-1 && !sorted {
if rowSpan[col] == 0 {
for i := row; i < n; i++ {
if tableData[i][col] == tableData[row][col] {
rowSpan[col]++
} else {
break
}
}
var property string
if rowSpan[col] > 1 {
property = fmt.Sprintf(`rowspan="%d"`, rowSpan[col])
}
cell := wrapWithTag(tableData[row][col], "td", property)
rowData += cell
}
} else {
cell := wrapWithTag(tableData[row][col], "td", "")
rowData += cell
}
}
rowData = wrapWithTag(rowData, "tr", "")
htmlContent += rowData
}
htmlContent = wrapWithTag(htmlContent, "table", "")
htmlContent = wrapWithTag(htmlContent, "body", "")
htmlContent = wrapWithTag(htmlContent, "html", "")
//nolint:errcheck
f.WriteString("<!DOCTYPE html>\n")
f.WriteString(`<head>
<style>
table, th, td {
border: 1px solid black;
padding: 5px;
}
table {
border-spacing: 2px;
}
</style>
</head>` + "\n")
f.WriteString(htmlContent)
f.Close()
}
// return a string that use tag to wrap content
func wrapWithTag(content string, tag string, property string) string {
if property != "" {
property = " " + property
}
if tag != "td" {
content = "\n" + content
}
return "<" + tag + property + ">" + content + "</" + tag + ">\n"
}