1 В избранное 0 Ответвления 0

OSCHINA-MIRROR/didiopensource-elastic-trib

Присоединиться к Gitlife
Откройте для себя и примите участие в публичных проектах с открытым исходным кодом с участием более 10 миллионов разработчиков. Приватные репозитории также полностью бесплатны :)
Присоединиться бесплатно
Клонировать/Скачать
indices_cmd.go 17 КБ
Копировать Редактировать Web IDE Исходные данные Просмотреть построчно История
soarpenguin Отправлено 14.06.2019 19:09 e3f6c64
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
package main
import (
ctx "context"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"github.com/Sirupsen/logrus"
"github.com/codegangsta/cli"
"github.com/olivere/elastic"
)
var indicesCommand = cli.Command{
Name: "indices",
Aliases: []string{"i"},
Usage: "Elastic indices operation cmd.",
Subcommands: []cli.Command{
// indices cat
indicesCatCommand,
// indices list
indicesListCommand,
// indices cat shards
indicesCatShardsCommand,
// indices open
indicesOpenCommand,
// indices close
indicesCloseCommand,
// indices delete
indicesDeleteCommand,
// indices settings
indicesSettingsCommand,
// indices template
indicesTemplateCommand,
// indices cat aliases
indicesCatAliasesCommand,
},
}
//cat alias
var indicesCatAliasesCommand = cli.Command{
Name: "alias",
Usage: "cat indices alias list from elastic cluster.",
ArgsUsage: `[-i "alias* or alias1,alias2"]`,
Description: `Display the cat indices of elastic cluster.`,
Flags: []cli.Flag{
cli.StringFlag{
Name: "format",
Value: "text",
Usage: "set the format of output('text' (default),or 'json')",
},
cli.StringFlag{
Name: "alias",
Value: "",
Usage: "set alias for query(alias1,alias2).",
},
},
Action: func(context *cli.Context) error {
return indicesCatAliasCmd(context)
},
}
func indicesCatAliasCmd(context *cli.Context) error {
client, err := NewElasticClient(context)
if err != nil {
return err
}
defer client.Stop()
ctx := ctx.Background()
aliasService := client.CatAliasService()
aliases := context.String("alias")
if aliases != "" {
aliaesarray := strings.Split(aliases, ",")
if len(aliaesarray) > 0 {
aliasService.Alias(aliaesarray...)
}
}
res, err := aliasService.Do(ctx)
if err != nil {
return err
}
format := context.String("format")
switch format {
case "text":
printAliasesList(res)
case "json":
jsonStr, err := json.Marshal(res)
if err != nil {
return err
}
fmt.Println(jsonPrettyPrint(string(jsonStr)))
default:
return fmt.Errorf("unknows format %q", format)
}
return nil
}
// aliases alias index filter routing.index routing.search
func printAliasesList(CatAliasResponse *elastic.CatAliasResponse) error {
if CatAliasResponse == nil {
return nil
}
display := NewTableDisplay()
display.AddRow([]string{"alias", "index", "filter", "routingIndex", "routingSearch"})
for _, indiceInfo := range CatAliasResponse.Aliases {
display.AddRow([]string{
indiceInfo.Alias,
indiceInfo.Index,
indiceInfo.Filter,
indiceInfo.Routingindex,
indiceInfo.Routingsearch})
}
display.Flush()
return nil
}
// cat
var indicesCatCommand = cli.Command{
Name: "cat",
Usage: "cat indices list from elastic cluster.",
ArgsUsage: `[-i "indices* or index1,index2"]`,
Description: `Display the cat indices of elastic cluster.`,
Flags: []cli.Flag{
cli.StringFlag{
Name: "format",
Value: "text",
Usage: "set the format of output('text' (default), or 'json').",
},
cli.StringFlag{
Name: "indices, i",
Value: "",
Usage: "set indices for query (index1,index2).",
},
},
Action: func(context *cli.Context) error {
return indicesCatCmd(context)
},
}
func indicesCatCmd(context *cli.Context) error {
// Create a client and connect to addr.
client, err := NewElasticClient(context)
if err != nil {
return err
}
defer client.Stop()
// Starting with elastic.v5, you must pass a context to execute each service
ctx := ctx.Background()
catService := client.CatIndicesService()
indices := context.String("indices")
if indices != "" {
iarray := strings.Split(indices, ",")
if len(iarray) > 0 {
catService.Index(iarray...)
}
}
res, err := catService.Do(ctx)
if err != nil {
return err
}
format := context.String("format")
switch format {
case "text":
printIndicesList(res)
case "json":
jsonStr, err := json.Marshal(res)
if err != nil {
return err
}
fmt.Println(jsonPrettyPrint(string(jsonStr)))
default:
return fmt.Errorf("unknown format %q", context.String("format"))
}
return nil
}
// health status index pri rep docs.count docs.deleted store.size pri.store.size
func printIndicesList(indicesInfoResponse *elastic.CatIndicesResponse) error {
if indicesInfoResponse == nil {
return nil
}
display := NewTableDisplay()
display.AddRow([]string{"health", "status", "index", "uuid", "pri", "rep", " count", "deleted", "size", "storeSize"})
for _, indice := range indicesInfoResponse.Indices {
display.AddRow([]string{
indice.Health,
indice.Status,
indice.Index,
indice.UUID,
indice.Pri,
indice.Rep,
indice.Count,
indice.Deleted,
indice.Size,
indice.StoreSize})
}
display.Flush()
return nil
}
// shards
var indicesCatShardsCommand = cli.Command{
Name: "shards",
Aliases: []string{"s"},
Usage: "Display the cat shards of elastic cluster.",
ArgsUsage: `[-i "indices* or index1,index2"]`,
Description: `get cat shards from elastic cluster.`,
Flags: []cli.Flag{
cli.StringFlag{
Name: "format",
Value: "text",
Usage: "set the format of output('text' (default), or 'json').",
},
cli.StringFlag{
Name: "indices, i",
Value: "",
Usage: "set indices for query (index1,index2).",
},
},
Action: func(context *cli.Context) error {
return indicesCatShardsCmd(context)
},
}
func indicesCatShardsCmd(context *cli.Context) error {
// Create a client and connect to addr.
client, err := NewElasticClient(context)
if err != nil {
return err
}
defer client.Stop()
// Starting with elastic.v5, you must pass a context to execute each service
ctx := ctx.Background()
catService := client.CatShardsService()
indices := context.String("indices")
if indices != "" {
iarray := strings.Split(indices, ",")
if len(iarray) > 0 {
catService.Index(iarray...)
}
}
res, err := catService.Do(ctx)
if err != nil {
return err
}
format := context.String("format")
switch format {
case "text":
printShardsList(res)
case "json":
jsonStr, err := json.Marshal(res)
if err != nil {
return err
}
fmt.Println(jsonPrettyPrint(string(jsonStr)))
default:
return fmt.Errorf("unknown format %q", context.String("format"))
}
return nil
}
// index shard prirep state docs store ip node
func printShardsList(shardsInfoResponse *elastic.CatShardsResponse) error {
if shardsInfoResponse == nil {
return nil
}
display := NewTableDisplay()
display.AddRow([]string{"index", "shard", "prirep", "state", "docs", "store", "ip", "node"})
for _, shard := range shardsInfoResponse.Shards {
display.AddRow([]string{
shard.Index,
shard.Shard,
shard.Prirep,
shard.State,
shard.Docs,
shard.Store,
shard.Ip,
shard.Node})
}
display.Flush()
return nil
}
// list
var indicesListCommand = cli.Command{
Name: "list",
Usage: "Display the indices list of elastic cluster.",
Description: `get indices list from elastic cluster.`,
Action: func(context *cli.Context) error {
return indicesListCmd(context)
},
}
func indicesListCmd(context *cli.Context) error {
// Create a client and connect to addr.
client, err := NewElasticClient(context)
if err != nil {
return err
}
defer client.Stop()
// Starting with elastic.v5, you must pass a context to execute each service
//ctx := ctx.Background()
res, err := client.IndexNames()
if err != nil {
return err
}
jsonStr, err := json.Marshal(res)
if err != nil {
return err
}
fmt.Println(jsonPrettyPrint(string(jsonStr)))
return nil
}
// open indicesName
var indicesOpenCommand = cli.Command{
Name: "open",
Usage: "The command open the elasticsearch indices.",
ArgsUsage: `indicesName`,
Description: `open the elasticsearch indices.`,
Action: func(context *cli.Context) error {
if context.NArg() != 1 {
fmt.Printf("Incorrect Usage.\n\n")
cli.ShowCommandHelp(context, "open")
logrus.Fatalf("Must provide indicesName for open command!")
}
return indicesOpenCmd(context)
},
}
func indicesOpenCmd(context *cli.Context) error {
var indicesName string
if indicesName = context.Args().Get(0); indicesName == "" {
return errors.New("please check indicesName for open command")
}
// Create a client and connect to addr.
client, err := NewElasticClient(context)
if err != nil {
return err
}
defer client.Stop()
// Starting with elastic.v5, you must pass a context to execute each service
ctx := ctx.Background()
res, err := client.OpenIndex(indicesName).Do(ctx)
if err != nil {
return err
}
jsonStr, err := json.Marshal(res)
if err != nil {
return err
}
fmt.Println(jsonPrettyPrint(string(jsonStr)))
return nil
}
// close indicesName
var indicesCloseCommand = cli.Command{
Name: "close",
Usage: "Close the elasticsearch indices.",
ArgsUsage: `indicesName`,
Description: `The command close the elasticsearch indices.`,
Action: func(context *cli.Context) error {
if context.NArg() != 1 {
fmt.Printf("Incorrect Usage.\n\n")
cli.ShowCommandHelp(context, "close")
logrus.Fatalf("Must provide indicesName for close command!")
}
return indicesCloseCmd(context)
},
}
func indicesCloseCmd(context *cli.Context) error {
var indicesName string
if indicesName = context.Args().Get(0); indicesName == "" {
return errors.New("please check indicesName for close command")
}
// Create a client and connect to addr.
client, err := NewElasticClient(context)
if err != nil {
return err
}
defer client.Stop()
// Starting with elastic.v5, you must pass a context to execute each service
ctx := ctx.Background()
res, err := client.CloseIndex(indicesName).Do(ctx)
if err != nil {
return err
}
jsonStr, err := json.Marshal(res)
if err != nil {
return err
}
fmt.Println(jsonPrettyPrint(string(jsonStr)))
return nil
}
// delete indicesName
var indicesDeleteCommand = cli.Command{
Name: "delete",
Usage: "Delete the elasticsearch indices.",
Aliases: []string{"del"},
ArgsUsage: `index1,index2`,
Description: `The command delete the elasticsearch indices.`,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "yes, y",
Usage: "Answer delete indices conform.",
},
},
Action: func(context *cli.Context) error {
if context.NArg() != 1 {
fmt.Printf("Incorrect Usage.\n\n")
cli.ShowCommandHelp(context, "delete")
logrus.Fatalf("Must provide indicesName for delete command!")
}
return indicesDeleteCmd(context)
},
}
func indicesDeleteCmd(context *cli.Context) error {
var indicesName string
if indicesName = context.Args().Get(0); indicesName == "" {
return errors.New("please check indicesName for delete command")
}
indicesList := strings.Split(indicesName, ",")
// Create a client and connect to addr.
client, err := NewElasticClient(context)
if err != nil {
return err
}
defer client.Stop()
// Starting with elastic.v5, you must pass a context to execute each service
ctx := ctx.Background()
fmt.Println(sgrBoldBlue("[Attention] Delete below indices? type (yes) to conform delete."))
if !context.Bool("yes") {
YesOrDie(strings.Join(indicesList, " "))
}
res, err := client.DeleteIndex(indicesList...).Do(ctx)
if err != nil {
return err
}
jsonStr, err := json.Marshal(res)
if err != nil {
return err
}
fmt.Println(jsonPrettyPrint(string(jsonStr)))
return nil
}
// settings indicesName
var indicesSettingsCommand = cli.Command{
Name: "settings",
Usage: "Get settings of the elasticsearch indices.",
Aliases: []string{"set"},
ArgsUsage: `index1,index2`,
Description: `The command get settings of the elasticsearch indices.`,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "get, g",
Usage: "get the settings of indices(index1,index2).",
},
cli.StringFlag{
Name: "set, s",
Value: "",
Usage: "set the settings of indices(index1,index2): -s '{settings_json}'.",
},
cli.StringFlag{
Name: "replicas, r",
Value: "",
Usage: "set the number_of_replicas of indices(index1,index2): -r num.",
},
},
Action: func(context *cli.Context) error {
if context.NArg() != 1 {
fmt.Printf("Incorrect Usage.\n\n")
cli.ShowCommandHelp(context, "settings")
logrus.Fatalf("Must provide indicesName for settings command!")
}
return indicesSettingsCmd(context)
},
}
func indicesSettingsCmd(context *cli.Context) error {
var indicesName string
if indicesName = context.Args().Get(0); indicesName == "" {
return errors.New("please check indicesName for settings command")
}
indicesList := strings.Split(indicesName, ",")
// Create a client and connect to addr.
client, err := NewElasticClient(context)
if err != nil {
return err
}
defer client.Stop()
// Starting with elastic.v5, you must pass a context to execute each service
ctx := ctx.Background()
if context.Bool("get") {
indexGetSetting := client.IndexGetSettings(indicesList...)
res, err := indexGetSetting.FlatSettings(true).Do(ctx)
if err != nil {
return err
}
jsonStr, err := json.Marshal(res)
if err != nil {
return err
}
fmt.Println(jsonPrettyPrint(string(jsonStr)))
} else if str := context.String("set"); str != "" {
str = strings.Trim(str, " ")
if !isJSON(str) {
return fmt.Errorf("'%s' is not a json string", str)
}
indexPutSetting := client.IndexPutSettings(indicesList...)
res, err := indexPutSetting.BodyJson(str).Do(ctx)
if err != nil {
return err
}
jsonStr, err := json.Marshal(res)
if err != nil {
return err
}
fmt.Println(jsonPrettyPrint(string(jsonStr)))
} else if str := context.String("replicas"); str != "" {
if num, err := strconv.Atoi(str); err != nil || num < 0 {
return fmt.Errorf("Invalid replicas num: %s", str)
}
jsonStr := fmt.Sprintf("{\"index.number_of_replicas\": \"%s\"}", str)
if !isJSON(jsonStr) {
return fmt.Errorf("'%s' is not a json string", jsonStr)
}
indexPutSetting := client.IndexPutSettings(indicesList...)
res, err := indexPutSetting.BodyJson(jsonStr).Do(ctx)
if err != nil {
return err
}
jsonRes, err := json.Marshal(res)
if err != nil {
return err
}
fmt.Println(jsonPrettyPrint(string(jsonRes)))
} else {
cli.ShowCommandHelp(context, "settings")
return fmt.Errorf("indices settings must provide -g or -s parameters")
}
return nil
}
// template
var indicesTemplateCommand = cli.Command{
Name: "template",
Usage: "Get template of the elasticsearch indices.",
Aliases: []string{"tpl"},
ArgsUsage: `tpl1,tpl2`,
Description: `The command get template of the elasticsearch indices.`,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "get, g",
Usage: "get the template of templates(tpl1,tpl2).",
},
cli.StringFlag{
Name: "set, s",
Value: "",
Usage: "set the template of templates(tpl1,tpl2): -s '{settings_json}'.",
},
cli.StringFlag{
Name: "replicas, r",
Value: "",
Usage: "set the number_of_replicas of template(tpl1,tpl2): -r num.",
},
},
Action: func(context *cli.Context) error {
if context.NArg() != 1 {
fmt.Printf("Incorrect Usage.\n\n")
cli.ShowCommandHelp(context, "template")
logrus.Fatalf("Must provide templateName for template command!")
}
return indicesTemplateCmd(context)
},
}
func indicesTemplateCmd(context *cli.Context) error {
var templatesName string
if templatesName = context.Args().Get(0); templatesName == "" {
return errors.New("please check templatesName for template command")
}
templatesList := strings.Split(templatesName, ",")
// Create a client and connect to addr.
client, err := NewElasticClient(context)
if err != nil {
return err
}
defer client.Stop()
// Starting with elastic.v5, you must pass a context to execute each service
ctx := ctx.Background()
if context.Bool("get") {
indexGetTemplate := client.IndexGetTemplate(templatesList...)
res, err := indexGetTemplate.FlatSettings(true).Do(ctx)
if err != nil {
return err
}
jsonStr, err := json.Marshal(res)
if err != nil {
return err
}
fmt.Println(jsonPrettyPrint(string(jsonStr)))
} else if str := context.String("set"); str != "" {
str = strings.Trim(str, " ")
if !isJSON(str) {
return fmt.Errorf("'%s' is not a json string", str)
}
indexPutTemplate := client.IndexPutTemplate(templatesList[0])
res, err := indexPutTemplate.BodyJson(str).Do(ctx)
if err != nil {
return err
}
jsonStr, err := json.Marshal(res)
if err != nil {
return err
}
fmt.Println(jsonPrettyPrint(string(jsonStr)))
} else if str := context.String("replicas"); str != "" {
if num, err := strconv.Atoi(str); err != nil || num < 0 {
return fmt.Errorf("Invalid replicas num: %s", str)
}
indexGetTemplate := client.IndexGetTemplate(templatesList[0])
res, err := indexGetTemplate.FlatSettings(true).Do(ctx)
if err != nil {
return err
}
jsonStr, err := json.Marshal(res)
if err != nil {
return err
}
out := map[string]interface{}{}
json.Unmarshal([]byte(jsonStr), &out)
fmt.Println(out)
// jsonStr := fmt.Sprintf("{\"index.number_of_replicas\": \"%s\"}", str)
// if !isJSON(jsonStr) {
// return fmt.Errorf("'%s' is not a json string", jsonStr)
// }
// indexPutTemplate := client.IndexPutTemplate(templatesList[0])
// res, err := indexPutTemplate.BodyJson(jsonStr).Do(ctx)
// if err != nil {
// return err
// }
// jsonRes, err := json.Marshal(res)
// if err != nil {
// return err
// }
// fmt.Println(jsonPrettyPrint(string(jsonRes)))
} else {
cli.ShowCommandHelp(context, "template")
return fmt.Errorf("indices template must provide -g or -s parameters")
}
return nil
}

Опубликовать ( 0 )

Вы можете оставить комментарий после Вход в систему

1
https://api.gitlife.ru/oschina-mirror/didiopensource-elastic-trib.git
git@api.gitlife.ru:oschina-mirror/didiopensource-elastic-trib.git
oschina-mirror
didiopensource-elastic-trib
didiopensource-elastic-trib
master