diff --git a/Makefile b/Makefile index 6a54198..e1207a5 100644 --- a/Makefile +++ b/Makefile @@ -29,12 +29,11 @@ GCP_PROJECT ?= escli SUPPORTED_PLATFORMS = linux-amd64 darwin-amd64 windows-amd64.exe linux-arm64 BUILD_PACKAGE = $(REPOPATH)/$(COMMAND_PKG) -escli_TEST_PACKAGES = ./pkg/... ./cmd/... ./hack/... +escli_TEST_PACKAGES = ./cmd/... GO_FILES = $(shell find . -type f -name '*.go' -not -path "./vendor/*" -not -path "./pkg/diag/*") -VERSION_PACKAGE = $(REPOPATH)/pkg/version +VERSION_PACKAGE = $(REPOPATH)/internal/version COMMIT = $(shell git rev-parse HEAD) -TEST_PACKAGES = ./pkg/... ./hack/... ifeq "$(strip $(VERSION))" "" override VERSION = $(shell git describe --always --tags --dirty) @@ -99,7 +98,7 @@ $(BUILD_DIR): mkdir -p $(BUILD_DIR) .PHONY: release -release: clean format linters test permission cross $(BUILD_DIR)/VERSION upload-only +release: clean format linters cross $(BUILD_DIR)/VERSION upload-only .PHONY: build build: format cross $(BUILD_DIR)/VERSION diff --git a/README.md b/README.md index 0d0036a..f868905 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,19 @@ # escli -`escli` is a command-line tool for managing elasticsearch cluster. +`escli` is a command-line tool for managing elasticsearch cluster. If you want to set number_of_replicas of index, you should do with curl like below example. +```bash +$ curl -X PUT "localhost:9200/my-index-000001/_settings?pretty" -H 'Content-Type: application/json' -d' +{ + "index" : { + "number_of_replicas" : 2 + } +} +' +``` +But with escli, you type below command. +```bash +$ escli index setting my-index-000001 number_of_replicas 2 +``` +`escli` should be make your elasticsearch experience more powerful. ## Installation ### Required @@ -81,30 +95,121 @@ application-log-2021.01.06 green open 100 1 | snapshot list | shows information of repositories and snapshots. it calls `_cat/snapshot` API. | | snapshot archive | change storage class of snapshots to S3 glacier. it works on AWS only. | | snapshot restore | change storage class of snapshots to S3 standard and restore snapshot. | -| snapshot take | take snapshot of indices. | +| snapshot create | create snapshot of indices. | #### available options | option | description | | ------------- | ---------------------------------------------------------------- | -| force | do not ask continue. it will be used for automated batch job. | +| force | do not ask continue. it will be used for automated batch job. (only `archive`, `restore` command) | +| with-repo | shows snapshots of specified repo (only `list` command) | +| repo-only | shows only information of repos (only `list` command) | #### examples ```bash -$ escli snapshot list +$ escli snapshot list --repo-only +Repository ID : log-archive +Repository ID : log-archive-standard-ia +Repository ID : log-archive-standard +``` + +```bash +$ escli snapshot create prod-snapshot snapshots-2021-01-01 result-prod-2021-01-01 +snapshots-2021-01-01 is created +``` + +```bash +$ escli snapshot archive send-mail-result-prod-snapshot snapshots-2020-12-31 --region us-east-1 +bucket name : result-prod +base path : elasticsearch-snapshot-standard +Downloaded /tmp/index-456 81207 bytes +index name : result-prod-2020-12-31 +elasticsearch-snapshot-standard/indices/z8bqmUmAQxy8tuwSsmFEKg/0/__-urzTmmuR8K6s6kpLryZ5g +? Change Storage Class to GLACIER ``` +- If you use `--force` option to `snapshot arvhice` command, escli doesn't ask you to continue. It makes all archiving job. + ### `index` command #### command list -| command | description | -| ----------- | --------------------------------------------------------- | -| index settings | get or set settings of index. | +| command | description | +| index settings | get or set index settings | -#### available options -| option | description | -| ------------- | ---------------------------------------------------------------- | -| force | do not ask continue. it will be used for automated batch job. | +#### examples + +```bash +$ escli index settings prod-2021-01-01 +{ + "prod-2021-01-01" : { + "settings" : { + "index" : { + "creation_date" : "1609906432373", + "number_of_shards" : "5", + "number_of_replicas" : "2", + "uuid" : "ha6Y6uiCSfOV_syHJwFCqA", + "version" : { + "created" : "6080099" + }, + "provided_name" : "send-mail-result-prod-2021-01-01" + } + } + } +} +``` + +```bash +$ escli index settings prod-2021-01-12 number_of_replicas ok 3s +{ + "prod-2021-01-12" : { + "settings" : { + "index" : { + "number_of_replicas" : "1" + } + } + } +} +``` + +```bash +$ escli index settings send-mail-result-prod-2021-01-12 number_of_replicas 2 ok +{ + "acknowledged" : true +} +``` + +### `cluster` command + +#### command list +| command | description | +| cluster settings | get or set index settings | #### examples +```bash +$ escli cluster settings +{ + "persistent" : { + "cluster" : { + "routing" : { + "allocation" : { +...... +} +``` + +```bash +$ escli cluster settings persistent indices.recovery.max_bytes_per_sec 50mb +``` + +### `diag` command + +#### examples + +```bash +$ escli diag +check cluster status...........................[green] 😎 +check yellow status indices....................[0] 😎 +check red status indices.......................[0] 😎 +check number of master nodes...................[3] +check maximum disk used percent of nodes.......[36] +``` \ No newline at end of file diff --git a/cmd/cmd/builder/flag.go b/cmd/cmd/builder/flag.go index 8e67a88..a6ccbf2 100644 --- a/cmd/cmd/builder/flag.go +++ b/cmd/cmd/builder/flag.go @@ -17,7 +17,6 @@ limitations under the license. package builder import ( - "github.com/DevopsArtFactory/escli/internal/constants" "reflect" "github.com/aws/aws-sdk-go/aws" @@ -25,6 +24,7 @@ import ( "github.com/spf13/pflag" "github.com/spf13/viper" + "github.com/DevopsArtFactory/escli/internal/constants" "github.com/DevopsArtFactory/escli/internal/util" ) @@ -49,7 +49,7 @@ var FlagRegistry = []Flag{ Value: aws.Bool(false), DefValue: false, FlagAddMethod: "BoolVar", - DefinedOn: []string{ + DefinedOn: []string{ "snapshot restore [repositoryID] [snapshotID] [indexName]", "snapshot create", "snapshot delete", @@ -94,7 +94,7 @@ var FlagRegistry = []Flag{ Value: aws.String(constants.EmptyString), DefValue: constants.EmptyString, FlagAddMethod: "StringVar", - DefinedOn: []string{ + DefinedOn: []string{ "snapshot restore [repositoryID] [snapshotID] [indexName]", "snapshot archive [repositoryID] [snapshotID]"}, }, diff --git a/cmd/cmd/cat.go b/cmd/cmd/cat.go index 8c4b58e..ba5c1f3 100644 --- a/cmd/cmd/cat.go +++ b/cmd/cmd/cat.go @@ -17,9 +17,9 @@ limitations under the license. package cmd import ( - "github.com/DevopsArtFactory/escli/cmd/cmd/builder" "github.com/spf13/cobra" + "github.com/DevopsArtFactory/escli/cmd/cmd/builder" "github.com/DevopsArtFactory/escli/cmd/cmd/cat" ) diff --git a/cmd/cmd/cat/indices.go b/cmd/cmd/cat/indices.go index 4650e79..5860bc8 100644 --- a/cmd/cmd/cat/indices.go +++ b/cmd/cmd/cat/indices.go @@ -18,12 +18,12 @@ package cat import ( "context" - "github.com/DevopsArtFactory/escli/internal/executor" "io" "github.com/spf13/cobra" "github.com/DevopsArtFactory/escli/cmd/cmd/builder" + "github.com/DevopsArtFactory/escli/internal/executor" ) func NewCatIndicesCommand() *cobra.Command { diff --git a/cmd/cmd/cat/nodes.go b/cmd/cmd/cat/nodes.go index f498fdb..60df136 100644 --- a/cmd/cmd/cat/nodes.go +++ b/cmd/cmd/cat/nodes.go @@ -18,12 +18,12 @@ package cat import ( "context" - "github.com/DevopsArtFactory/escli/internal/executor" "io" "github.com/spf13/cobra" "github.com/DevopsArtFactory/escli/cmd/cmd/builder" + "github.com/DevopsArtFactory/escli/internal/executor" ) func NewCatNodesCommand() *cobra.Command { diff --git a/cmd/cmd/cat/shards.go b/cmd/cmd/cat/shards.go index 8fbb2d7..4ee9d0a 100644 --- a/cmd/cmd/cat/shards.go +++ b/cmd/cmd/cat/shards.go @@ -18,12 +18,12 @@ package cat import ( "context" - "github.com/DevopsArtFactory/escli/internal/executor" "io" "github.com/spf13/cobra" "github.com/DevopsArtFactory/escli/cmd/cmd/builder" + "github.com/DevopsArtFactory/escli/internal/executor" ) func NewCatShardsCommand() *cobra.Command { diff --git a/cmd/cmd/cluster.go b/cmd/cmd/cluster.go index f14008d..941c86e 100644 --- a/cmd/cmd/cluster.go +++ b/cmd/cmd/cluster.go @@ -17,8 +17,9 @@ limitations under the license. package cmd import ( - "github.com/DevopsArtFactory/escli/cmd/cmd/cluster" "github.com/spf13/cobra" + + "github.com/DevopsArtFactory/escli/cmd/cmd/cluster" ) func NewClusterCommand() *cobra.Command { diff --git a/cmd/cmd/cluster/settings.go b/cmd/cmd/cluster/settings.go index 36bf1bb..d7a471f 100644 --- a/cmd/cmd/cluster/settings.go +++ b/cmd/cmd/cluster/settings.go @@ -34,6 +34,6 @@ func NewClusterSettingsCommand() *cobra.Command { func funcClusterSettings(ctx context.Context, out io.Writer, args []string) error { return executor.RunExecutor(ctx, func(executor executor.Executor) error { - return executor.Runner.IndexSettings(out, args) + return executor.Runner.ClusterSettings(out, args) }) } diff --git a/cmd/cmd/diag.go b/cmd/cmd/diag.go index da0a291..a4e09e1 100644 --- a/cmd/cmd/diag.go +++ b/cmd/cmd/diag.go @@ -18,11 +18,11 @@ package cmd import ( "context" - "github.com/DevopsArtFactory/escli/cmd/cmd/builder" "io" "github.com/spf13/cobra" + "github.com/DevopsArtFactory/escli/cmd/cmd/builder" "github.com/DevopsArtFactory/escli/internal/executor" ) diff --git a/cmd/cmd/index.go b/cmd/cmd/index.go index ba5df8f..254e86f 100644 --- a/cmd/cmd/index.go +++ b/cmd/cmd/index.go @@ -17,8 +17,9 @@ limitations under the license. package cmd import ( - "github.com/DevopsArtFactory/escli/cmd/cmd/index" "github.com/spf13/cobra" + + "github.com/DevopsArtFactory/escli/cmd/cmd/index" ) func NewIndexCommand() *cobra.Command { diff --git a/cmd/cmd/snapshot.go b/cmd/cmd/snapshot.go index f80420e..b257867 100644 --- a/cmd/cmd/snapshot.go +++ b/cmd/cmd/snapshot.go @@ -17,9 +17,9 @@ limitations under the license. package cmd import ( - "github.com/DevopsArtFactory/escli/cmd/cmd/builder" "github.com/spf13/cobra" + "github.com/DevopsArtFactory/escli/cmd/cmd/builder" "github.com/DevopsArtFactory/escli/cmd/cmd/snapshot" ) diff --git a/deploy/cross/Dockerfile b/deploy/cross/Dockerfile new file mode 100644 index 0000000..eef192e --- /dev/null +++ b/deploy/cross/Dockerfile @@ -0,0 +1,34 @@ +# Copyright 2020 The escli Authors All rights reserved. +# +# 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. + +FROM dockercore/golang-cross:1.13.10 as base + +# The base image is not yet available for go 1.14. +# Let's just replace the Go that's installed with a newer one. +RUN rm -Rf /usr/local/go && mkdir /usr/local/go +RUN curl --fail --show-error --silent --location https://dl.google.com/go/go1.14.2.linux-amd64.tar.gz \ + | tar xz --directory=/usr/local/go --strip-components=1 + +# Cross compile escli for Linux, Windows and MacOS +ARG GOOS +ARG GOARCH +ARG TAGS +ARG LDFLAGS + +WORKDIR /escli +COPY . ./ + +RUN if [ "$GOOS" = "darwin" ]; then export CC=o64-clang CXX=o64-clang++; fi; \ + GOOS=$GOOS GOARCH=$GOARCH CGO_ENABLED=1 \ + go build -tags "${TAGS}" -ldflags "${LDFLAGS}" -o /build/escli cmd/main.go diff --git a/internal/builder/builder.go b/internal/builder/builder.go index cb0c12e..0a7c13e 100644 --- a/internal/builder/builder.go +++ b/internal/builder/builder.go @@ -26,12 +26,12 @@ import ( ) type Flags struct { - Region string `json:"region"` Force bool `json:"force"` TroubledOnly bool `json:"troubled-only"` - SortBy string `json:"sort-by"` RepoOnly bool `json:"repo-only"` WithRepo string `json:"with-repo"` + Region string `json:"region"` + SortBy string `json:"sort-by"` } func ParseFlags() (*Flags, error) { diff --git a/internal/client/elasticsearch.go b/internal/client/elasticsearch.go index d90eb0d..c5e779c 100644 --- a/internal/client/elasticsearch.go +++ b/internal/client/elasticsearch.go @@ -18,14 +18,14 @@ package client import ( "bytes" - "fmt" - "github.com/DevopsArtFactory/escli/internal/constants" "strings" "github.com/elastic/go-elasticsearch" "github.com/elastic/go-elasticsearch/esapi" - "github.com/DevopsArtFactory/escli/internal/schema" + "github.com/DevopsArtFactory/escli/internal/constants" + catSchema "github.com/DevopsArtFactory/escli/internal/schema/cat" + snapshotSchema "github.com/DevopsArtFactory/escli/internal/schema/snapshot" "github.com/DevopsArtFactory/escli/internal/util" ) @@ -40,8 +40,8 @@ func GetESClientFn(elasticSearchURL string) *elasticsearch.Client { return es } -func (c Client) GetRepositories() ([]schema.CatRepositoryMetadata, error) { - var repositoriesMetadata []schema.CatRepositoryMetadata +func (c Client) GetRepositories() ([]catSchema.Repository, error) { + var repositories []catSchema.Repository resp, err := c.ESClient.Cat.Repositories( c.ESClient.Cat.Repositories.WithFormat("json")) @@ -49,22 +49,22 @@ func (c Client) GetRepositories() ([]schema.CatRepositoryMetadata, error) { return nil, err } - util.ConvertJSONtoMetadata(resp.Body, &repositoriesMetadata) + util.ConvertJSONtoMetadata(resp.Body, &repositories) - return repositoriesMetadata, nil + return repositories, nil } -func (c Client) GetSnapshots(repositoryID string) (schema.SnapshotSnapshotsMetadata, error) { - var snapshotsMetadata schema.SnapshotSnapshotsMetadata +func (c Client) GetSnapshots(repositoryID string) (snapshotSchema.Snapshots, error) { + var snapshots snapshotSchema.Snapshots resp, err := c.ESClient.Snapshot.Get(repositoryID, []string{"*"}) if err != nil { - return snapshotsMetadata, err + return snapshots, err } - util.ConvertJSONtoMetadata(resp.Body, &snapshotsMetadata) + util.ConvertJSONtoMetadata(resp.Body, &snapshots) - return snapshotsMetadata, nil + return snapshots, nil } func (c Client) CreateSnapshot(repositoryID, snapshotID, requestBody string) (int, error) { @@ -83,7 +83,7 @@ func (c Client) DeleteSnapshot(repositoryID, snapshotID string) (int, error) { resp, err := c.ESClient.Snapshot.Delete( repositoryID, snapshotID, - ) + ) if err != nil { return resp.StatusCode, err } @@ -91,24 +91,24 @@ func (c Client) DeleteSnapshot(repositoryID, snapshotID string) (int, error) { return resp.StatusCode, util.ReturnErrorFromResponseBody(resp) } -func (c Client) GetSnapshotRepositoryMetadata(repositoryID string) schema.SnapshotRepositoryMetadata { - var snapshotRepositoryMetadata map[string]schema.SnapshotRepositoryMetadata +func (c Client) GetRepository(repositoryID string) snapshotSchema.Repository { + var repositories map[string]snapshotSchema.Repository resp, _ := c.ESClient.Snapshot.GetRepository(c.ESClient.Snapshot.GetRepository.WithRepository(repositoryID)) - util.ConvertJSONtoMetadata(resp.Body, &snapshotRepositoryMetadata) + util.ConvertJSONtoMetadata(resp.Body, &repositories) - return snapshotRepositoryMetadata[repositoryID] + return repositories[repositoryID] } -func (c Client) GetSnapshotSnapshotsMetadata(repositoryID string, snapshotID string) schema.SnapshotSnapshotsMetadata { - var snapshotSnapshotsMetadata schema.SnapshotSnapshotsMetadata +func (c Client) GetSnapshot(repositoryID string, snapshotID string) snapshotSchema.Snapshot { + var snapshots snapshotSchema.Snapshots resp, _ := c.ESClient.Snapshot.Get(repositoryID, []string{snapshotID}) - util.ConvertJSONtoMetadata(resp.Body, &snapshotSnapshotsMetadata) + util.ConvertJSONtoMetadata(resp.Body, &snapshots) - return snapshotSnapshotsMetadata + return snapshots.Snapshots[0] } func (c Client) RestoreSnapshot(requestBody string, repositoryName string, snapshotName string) (*esapi.Response, error) { @@ -118,8 +118,8 @@ func (c Client) RestoreSnapshot(requestBody string, repositoryName string, snaps return resp, err } -func (c Client) CatHealth() ([]schema.CatHealthMetadata, error) { - var healthMetadata []schema.CatHealthMetadata +func (c Client) CatHealth() ([]catSchema.Health, error) { + var healthMetadata []catSchema.Health resp, err := c.ESClient.Cat.Health( c.ESClient.Cat.Health.WithFormat("json")) @@ -131,8 +131,8 @@ func (c Client) CatHealth() ([]schema.CatHealthMetadata, error) { return healthMetadata, nil } -func (c Client) CatIndices(sortKey string) ([]schema.CatIndexMetadata, error) { - var indicesMetadata []schema.CatIndexMetadata +func (c Client) CatIndices(sortKey string) ([]catSchema.Index, error) { + var indicesMetadata []catSchema.Index if sortKey == constants.EmptyString { sortKey = "index" @@ -149,8 +149,8 @@ func (c Client) CatIndices(sortKey string) ([]schema.CatIndexMetadata, error) { return indicesMetadata, nil } -func (c Client) CatNodes(sortKey string) ([]schema.CatNodeMetadata, error) { - var nodesMetadata []schema.CatNodeMetadata +func (c Client) CatNodes(sortKey string) ([]catSchema.Node, error) { + var nodesMetadata []catSchema.Node if sortKey == constants.EmptyString { sortKey = "id" @@ -168,8 +168,8 @@ func (c Client) CatNodes(sortKey string) ([]schema.CatNodeMetadata, error) { return nodesMetadata, nil } -func (c Client) CatShards(sortKey string) ([]schema.CatShardMetadata, error) { - var shardsMetadata []schema.CatShardMetadata +func (c Client) CatShards(sortKey string) ([]catSchema.Shard, error) { + var shardsMetadata []catSchema.Shard if sortKey == constants.EmptyString { sortKey = "index" @@ -187,7 +187,7 @@ func (c Client) CatShards(sortKey string) ([]schema.CatShardMetadata, error) { return shardsMetadata, nil } -func (c Client) GetIndexSetting(indexName, settingName string) error { +func (c Client) GetIndexSetting(indexName, settingName string) (string, error) { var resp *esapi.Response var err error @@ -199,37 +199,66 @@ func (c Client) GetIndexSetting(indexName, settingName string) error { } else { resp, err = c.ESClient.Indices.GetSettings( c.ESClient.Indices.GetSettings.WithIndex(indexName), - c.ESClient.Indices.GetSettings.WithName("index." + settingName), + c.ESClient.Indices.GetSettings.WithName("index."+settingName), c.ESClient.Indices.GetSettings.WithPretty(), ) } if err != nil { - return err + return constants.EmptyString, err } buf := new(bytes.Buffer) buf.ReadFrom(resp.Body) - fmt.Println(buf.String()) - - return nil + return buf.String(), nil } -func (c Client) PutIndexSetting(indexName, requestBody string) error { - +func (c Client) PutIndexSetting(indexName, requestBody string) (string, error) { resp, err := c.ESClient.Indices.PutSettings( strings.NewReader(requestBody), c.ESClient.Indices.PutSettings.WithIndex(indexName), + c.ESClient.Indices.PutSettings.WithPretty(), ) if err != nil { - return err + return constants.EmptyString, err } buf := new(bytes.Buffer) buf.ReadFrom(resp.Body) - fmt.Println(buf.String()) + return buf.String(), nil +} + +func (c Client) GetClusterSetting() (string, error) { + var resp *esapi.Response + var err error + + resp, err = c.ESClient.Cluster.GetSettings( + c.ESClient.Cluster.GetSettings.WithPretty(), + c.ESClient.Cluster.GetSettings.WithIncludeDefaults(true)) + + if err != nil { + return constants.EmptyString, err + } + buf := new(bytes.Buffer) + buf.ReadFrom(resp.Body) + + return buf.String(), nil +} + +func (c Client) PutClusterSetting(requestBody string) (string, error) { + resp, err := c.ESClient.Cluster.PutSettings( + strings.NewReader(requestBody), + c.ESClient.Cluster.PutSettings.WithPretty(), + ) + + if err != nil { + return constants.EmptyString, err + } + + buf := new(bytes.Buffer) + buf.ReadFrom(resp.Body) - return nil + return buf.String(), nil } diff --git a/internal/constants/constants.go b/internal/constants/constants.go index e4221b0..3638d58 100644 --- a/internal/constants/constants.go +++ b/internal/constants/constants.go @@ -24,9 +24,12 @@ const ( ) const ( - GetSetting = 1 - GetSettingWithName = 2 - PutSetting = 3 + GetIndexSetting = 1 + GetIndexSettingWithName = 2 + PutIndexSetting = 3 + + GetClusterSetting = 0 + PutClusterSetting = 3 ) var ( diff --git a/internal/executor/executor.go b/internal/executor/executor.go index f2d7af0..fbbf28e 100644 --- a/internal/executor/executor.go +++ b/internal/executor/executor.go @@ -18,6 +18,7 @@ package executor import ( "context" + "github.com/DevopsArtFactory/escli/internal/builder" "github.com/DevopsArtFactory/escli/internal/config" "github.com/DevopsArtFactory/escli/internal/runner" diff --git a/internal/runner/cat.go b/internal/runner/cat.go index 93c8e8c..0d0673e 100644 --- a/internal/runner/cat.go +++ b/internal/runner/cat.go @@ -18,9 +18,10 @@ package runner import ( "fmt" - "github.com/DevopsArtFactory/escli/internal/util" "io" "reflect" + + "github.com/DevopsArtFactory/escli/internal/util" ) func (r Runner) CatHealth(out io.Writer) error { @@ -50,7 +51,7 @@ func (r Runner) CatIndices(out io.Writer) error { return err } - fmt.Fprintf(out,"%-50s\t%s\t%s\t%s\t%s\t%10s\n", + fmt.Fprintf(out, "%-50s\t%s\t%s\t%s\t%s\t%10s\n", "index", "health", "status", @@ -135,6 +136,5 @@ func (r Runner) CatShards(out io.Writer) error { shard.UnassignedReason) } - return nil -} \ No newline at end of file +} diff --git a/internal/runner/cluster.go b/internal/runner/cluster.go index b2e3117..8c5de7f 100644 --- a/internal/runner/cluster.go +++ b/internal/runner/cluster.go @@ -17,22 +17,48 @@ limitations under the license. package runner import ( + "encoding/json" "errors" - "github.com/DevopsArtFactory/escli/internal/constants" + "fmt" "io" + + "github.com/DevopsArtFactory/escli/internal/constants" + clusterSchema "github.com/DevopsArtFactory/escli/internal/schema/cluster" ) func (r Runner) ClusterSettings(out io.Writer, args []string) error { + var resp string + var err error + switch len(args) { - case constants.GetSetting: - return r.Client.GetIndexSetting(args[0], "") - case constants.GetSettingWithName: - return r.Client.GetIndexSetting(args[0], args[1]) - case constants.PutSetting: - r.Client.GetIndexSetting(args[0], args[1]) + case constants.GetClusterSetting: + resp, err = r.Client.GetClusterSetting() + case constants.PutClusterSetting: + requestBody, _ := json.Marshal(composeClusterRequestBody(args)) + resp, err = r.Client.PutClusterSetting(string(requestBody)) default: - errors.New("arguments must be 2 or 3") + return errors.New("arguments must be 0 or 3") } - return nil -} \ No newline at end of file + fmt.Fprintf(out, "%s\n", resp) + return err +} + +func composeClusterRequestBody(args []string) clusterSchema.RequestBody { + switch args[0] { + case "persistent": + return clusterSchema.RequestBody{ + Persistent: map[string]string{ + args[1]: args[2], + }, + } + case "transient": + return clusterSchema.RequestBody{ + Transient: map[string]string{ + args[1]: args[2], + }, + } + default: + return clusterSchema.RequestBody{} + } +} diff --git a/internal/runner/diag.go b/internal/runner/diag.go index 69b4701..99b4253 100644 --- a/internal/runner/diag.go +++ b/internal/runner/diag.go @@ -25,7 +25,7 @@ import ( "github.com/enescakir/emoji" "github.com/fatih/color" - "github.com/DevopsArtFactory/escli/internal/schema" + catSchema "github.com/DevopsArtFactory/escli/internal/schema/cat" "github.com/DevopsArtFactory/escli/internal/util" ) @@ -44,10 +44,10 @@ func (r Runner) DiagCluster(out io.Writer) error { } fmt.Fprintf(out, "check yellow status indices....................") - printIndicesByHealth(out, indexMetadata, "yellow", false) + printIndicesByHealth(out, indexMetadata, "yellow") fmt.Fprintf(out, "check red status indices.......................") - printIndicesByHealth(out, indexMetadata, "red", false) + printIndicesByHealth(out, indexMetadata, "red") // Check role of nodes fmt.Fprintf(out, "check number of master nodes...................") @@ -62,21 +62,20 @@ func (r Runner) DiagCluster(out io.Writer) error { // Check role of nodes fmt.Fprintf(out, "check maximum disk used percent of nodes.......") - checkDiskUsedPercentOfNodes(out, nodeMetadata, false) + checkDiskUsedPercentOfNodes(out, nodeMetadata) return nil } -func printStatusByHealth(out io.Writer, healthMetadata schema.CatHealthMetadata) { - if healthMetadata.Status != "green" { - fmt.Fprintf(out, "[%s] %v\n", util.StringWithColor(healthMetadata.Status), emoji.FaceScreamingInFear) +func printStatusByHealth(out io.Writer, health catSchema.Health) { + if health.Status != "green" { + fmt.Fprintf(out, "[%s] %v\n", util.StringWithColor(health.Status), emoji.FaceScreamingInFear) } else { - fmt.Fprintf(out, "[%s] %v\n", util.StringWithColor(healthMetadata.Status), emoji.SmilingFaceWithSunglasses) + fmt.Fprintf(out, "[%s] %v\n", util.StringWithColor(health.Status), emoji.SmilingFaceWithSunglasses) } - } -func checkDiskUsedPercentOfNodes(out io.Writer, nodeMetadata []schema.CatNodeMetadata, detailed bool) { +func checkDiskUsedPercentOfNodes(out io.Writer, nodeMetadata []catSchema.Node) { maximumDiskUsedPercent := 0.0 for _, v := range nodeMetadata { diskUsedPercent, _ := strconv.ParseFloat(v.DiskUsedPercent, 64) @@ -87,7 +86,7 @@ func checkDiskUsedPercentOfNodes(out io.Writer, nodeMetadata []schema.CatNodeMet fmt.Fprintf(out, "[%s]\n", util.FloatWithColor(maximumDiskUsedPercent)) } -func checkNumberOfMasterNodes(out io.Writer, nodeMetadata []schema.CatNodeMetadata) { +func checkNumberOfMasterNodes(out io.Writer, nodeMetadata []catSchema.Node) { numberOfMasterNodes := 0 for _, v := range nodeMetadata { if strings.Contains(v.NodeRole, "m") { @@ -105,7 +104,7 @@ func checkNumberOfMasterNodes(out io.Writer, nodeMetadata []schema.CatNodeMetada } } -func printIndicesByHealth(out io.Writer, indexMetadata []schema.CatIndexMetadata, health string, detailed bool) { +func printIndicesByHealth(out io.Writer, indexMetadata []catSchema.Index, health string) { numberOfTroubledIndices := 0 for _, v := range indexMetadata { if v.Health == health { @@ -114,9 +113,7 @@ func printIndicesByHealth(out io.Writer, indexMetadata []schema.CatIndexMetadata } if numberOfTroubledIndices > 0 { fmt.Fprintf(out, "[%s] %v\n", util.IntWithColor(numberOfTroubledIndices, "red"), emoji.FaceScreamingInFear) - if !detailed { - fmt.Fprintf(out, "%v check more information by %s\n", emoji.ExclamationMark, util.StringWithColor("escli cat indices")) - } + fmt.Fprintf(out, "%v check more information by %s\n", emoji.ExclamationMark, util.StringWithColor("escli cat indices")) } else { fmt.Fprintf(out, "[%s] %v\n", util.IntWithColor(numberOfTroubledIndices, "green"), emoji.SmilingFaceWithSunglasses) } diff --git a/internal/runner/index.go b/internal/runner/index.go index da7a314..2741091 100644 --- a/internal/runner/index.go +++ b/internal/runner/index.go @@ -19,29 +19,37 @@ package runner import ( "encoding/json" "errors" - "github.com/DevopsArtFactory/escli/internal/constants" - "github.com/DevopsArtFactory/escli/internal/schema" + "fmt" "io" + + "github.com/DevopsArtFactory/escli/internal/constants" + indexSchema "github.com/DevopsArtFactory/escli/internal/schema/index" ) func (r Runner) IndexSettings(out io.Writer, args []string) error { + var resp string + var err error + switch len(args) { - case constants.GetSetting: - return r.Client.GetIndexSetting(args[0], "") - case constants.GetSettingWithName: - return r.Client.GetIndexSetting(args[0], args[1]) - case constants.PutSetting: - requestBody, _ := json.Marshal( - schema.IndexIndexSettingsRequestBody{ - Index: map[string]string{ - args[1]: args[2], - }, - }, - ) - return r.Client.PutIndexSetting(args[0], string(requestBody)) + case constants.GetIndexSetting: + resp, err = r.Client.GetIndexSetting(args[0], "") + case constants.GetIndexSettingWithName: + resp, err = r.Client.GetIndexSetting(args[0], args[1]) + case constants.PutIndexSetting: + requestBody, _ := json.Marshal(composeIndexRequestBody(args)) + resp, err = r.Client.PutIndexSetting(args[0], string(requestBody)) default: - errors.New("arguments must be 2 or 3") + return errors.New("arguments must be 1 or 2 or 3") } - return nil -} \ No newline at end of file + fmt.Fprintf(out, "%s\n", resp) + return err +} + +func composeIndexRequestBody(args []string) indexSchema.RequestBody { + return indexSchema.RequestBody{ + Index: map[string]string{ + args[1]: args[2], + }, + } +} diff --git a/internal/runner/snapshot.go b/internal/runner/snapshot.go index b089963..322ec47 100644 --- a/internal/runner/snapshot.go +++ b/internal/runner/snapshot.go @@ -21,7 +21,6 @@ import ( "encoding/json" "errors" "fmt" - "github.com/DevopsArtFactory/escli/internal/constants" "io" "os" "regexp" @@ -32,17 +31,18 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/fatih/color" - "github.com/DevopsArtFactory/escli/internal/schema" + "github.com/DevopsArtFactory/escli/internal/constants" + snapshotSchema "github.com/DevopsArtFactory/escli/internal/schema/snapshot" "github.com/DevopsArtFactory/escli/internal/util" ) func (r Runner) ListSnapshot(out io.Writer) error { - repositoriesMetadata, err := r.Client.GetRepositories() + repositories, err := r.Client.GetRepositories() if err != nil { return err } - for _, repository := range repositoriesMetadata { + for _, repository := range repositories { if r.Flag.WithRepo == repository.ID || r.Flag.WithRepo == constants.EmptyString { fmt.Fprintf(out, "Repository ID : %s\n", util.StringWithColor(repository.ID)) } @@ -55,12 +55,12 @@ func (r Runner) ListSnapshot(out io.Writer) error { fmt.Fprintf(out, "%-50s\t%s\n", "ID", "state") - for _, snapshotMetadata := range snapshotsMetadata.SnapshotSnapshotMetadata { + for _, snapshot := range snapshotsMetadata.Snapshots { fmt.Fprintf(out, "%-50s\t%s\n", - snapshotMetadata.Snapshot, - util.StringWithColor(snapshotMetadata.State)) + snapshot.Snapshot, + util.StringWithColor(snapshot.State)) fmt.Fprintf(out, "%s\n", - snapshotMetadata.Indices) + snapshot.Indices) } } } @@ -74,16 +74,21 @@ func (r Runner) CreateSnapshot(out io.Writer, args []string) error { indices := args[2] requestBody, err := json.Marshal( - schema.SnapshotRequestBody{ - Indices: indices, - }, + snapshotSchema.RequestBody{ + Indices: indices, + }, ) if err != nil { return err } statusCode, err := r.Client.CreateSnapshot(repositoryID, snapshotID, string(requestBody)) - fmt.Fprintf(out, "%d\n", statusCode) + switch statusCode { + case 200: + fmt.Fprintf(out, "%s\n", util.GreenString(snapshotID+" is created")) + default: + fmt.Fprintf(out, "%s\n", util.RedString(snapshotID+" is not created")) + } return err } @@ -93,7 +98,12 @@ func (r Runner) DeleteSnapshot(out io.Writer, args []string) error { snapshotID := args[1] statusCode, err := r.Client.DeleteSnapshot(repositoryID, snapshotID) - fmt.Fprintf(out, "%d\n", statusCode) + switch statusCode { + case 200: + fmt.Fprintf(out, "%s\n", util.GreenString(snapshotID+" is deleted")) + default: + fmt.Fprintf(out, "%s\n", util.RedString(snapshotID+" is not deleted")) + } return err } @@ -105,66 +115,62 @@ func (r Runner) ArchiveSnapshot(out io.Writer, args []string) error { var wait sync.WaitGroup runtime.GOMAXPROCS(4) - snapshotRepositoryMetadata := r.Client.GetSnapshotRepositoryMetadata(repositoryID) + repository := r.Client.GetRepository(repositoryID) - if snapshotRepositoryMetadata.Type != "s3" { + if repository.Type != "s3" { return errors.New("archive is only supported s3 type repository") } - if snapshotRepositoryMetadata.Settings.Bucket == constants.EmptyString { + if repository.Settings.Bucket == constants.EmptyString { return errors.New("archive is only supported normal s3 type repository. this repository doesn't have settings information") } - fmt.Fprintf(out, "bucket name : %s\n", util.StringWithColor(snapshotRepositoryMetadata.Settings.Bucket)) - fmt.Fprintf(out, "base path : %s\n", util.StringWithColor(snapshotRepositoryMetadata.Settings.BasePath)) + fmt.Fprintf(out, "bucket name : %s\n", util.StringWithColor(repository.Settings.Bucket)) + fmt.Fprintf(out, "base path : %s\n", util.StringWithColor(repository.Settings.BasePath)) - snapshotSnapshotsMetadata := r.Client.GetSnapshotSnapshotsMetadata(repositoryID, snapshotID) + snapshot := r.Client.GetSnapshot(repositoryID, snapshotID) - snapshotSnapshotsIndicesMetadata, err := r.getIndexIDFromS3( - aws.String(snapshotRepositoryMetadata.Settings.Bucket), - aws.String(snapshotRepositoryMetadata.Settings.BasePath+"/"), + snapshotsIndicesS3, err := r.getIndexIDFromS3( + aws.String(repository.Settings.Bucket), + aws.String(repository.Settings.BasePath+"/"), ) if err != nil { return err } - for _, indexName := range snapshotSnapshotsMetadata.SnapshotSnapshotMetadata[0].Indices { + for _, indexName := range snapshot.Indices { fmt.Fprintf(out, "index name : %s\n", util.StringWithColor(indexName)) - metaData := snapshotSnapshotsIndicesMetadata.Indices[indexName] - prefix := snapshotRepositoryMetadata.Settings.BasePath + "/indices/" + metaData.ID + "/" + metaData := snapshotsIndicesS3.Indices[indexName] + prefix := repository.Settings.BasePath + "/indices/" + metaData.ID + "/" - objs, _ := r.Client.GetObjects(aws.String(snapshotRepositoryMetadata.Settings.Bucket), aws.String(prefix), nil, nil) + objs, _ := r.Client.GetObjects(aws.String(repository.Settings.Bucket), aws.String(prefix), nil, nil) for { for _, item := range objs.Contents { - fmt.Println(*item.Key) + fmt.Fprintf(out, "%s\n", *item.Key) if *item.StorageClass != "GLACIER" { if r.Flag.Force { color.Green("Change Storage Class to %s -> GLACIER", *item.StorageClass) wait.Add(1) go func(key string) { defer wait.Done() - _, err := r.Client.TransitObject(aws.String(snapshotRepositoryMetadata.Settings.Bucket), aws.String(key), "GLACIER") + _, err := r.Client.TransitObject(aws.String(repository.Settings.Bucket), aws.String(key), "GLACIER") if err != nil { panic(err) } }(*item.Key) } else { - reader := bufio.NewReader(os.Stdin) - - color.Blue("Change Storage Class to GLACIER [y/n]: ") - - resp, _ := reader.ReadString('\n') - if strings.ToLower(strings.TrimSpace(resp)) == "y" { - color.Green("Change Storage Class to %s -> GLACIER", *item.StorageClass) - wait.Add(1) - _, err := r.Client.TransitObject(aws.String(snapshotRepositoryMetadata.Settings.Bucket), item.Key, "GLACIER") - if err != nil { - panic(err) - } - } else { + if err := util.AskContinue("Change Storage Class to GLACIER "); err != nil { color.Red("Don't change storage class %s", *item.Key) + return errors.New("task has been cancelled") + } + + color.Green("Change Storage Class to %s -> GLACIER", *item.StorageClass) + wait.Add(1) + _, err := r.Client.TransitObject(aws.String(repository.Settings.Bucket), item.Key, "GLACIER") + if err != nil { + panic(err) } } } @@ -172,7 +178,7 @@ func (r Runner) ArchiveSnapshot(out io.Writer, args []string) error { wait.Wait() if *objs.IsTruncated { - objs, _ = r.Client.GetObjects(aws.String(snapshotRepositoryMetadata.Settings.Bucket), aws.String(prefix), nil, objs.NextContinuationToken) + objs, _ = r.Client.GetObjects(aws.String(repository.Settings.Bucket), aws.String(prefix), nil, objs.NextContinuationToken) } else { break } @@ -181,8 +187,8 @@ func (r Runner) ArchiveSnapshot(out io.Writer, args []string) error { return nil } -func (r Runner) getIndexIDFromS3(bucket *string, prefix *string) (*schema.SnapshotSnapshotsIndicesMetadata, error) { - var SnapshotSnapshotsIndicesMetadata schema.SnapshotSnapshotsIndicesMetadata +func (r Runner) getIndexIDFromS3(bucket *string, prefix *string) (*snapshotSchema.SnapshotsIndicesS3, error) { + var snapshotsIndicesS3 snapshotSchema.SnapshotsIndicesS3 resp, err := r.Client.GetObjects(bucket, prefix, aws.String("/"), nil) if err != nil { return nil, err @@ -211,9 +217,9 @@ func (r Runner) getIndexIDFromS3(bucket *string, prefix *string) (*schema.Snapsh } defer jsonFile.Close() - util.ConvertJSONtoMetadata(jsonFile, &SnapshotSnapshotsIndicesMetadata) + util.ConvertJSONtoMetadata(jsonFile, &snapshotsIndicesS3) - return &SnapshotSnapshotsIndicesMetadata, nil + return &snapshotsIndicesS3, nil } func (r Runner) RestoreSnapshot(out io.Writer, args []string) error { @@ -222,34 +228,33 @@ func (r Runner) RestoreSnapshot(out io.Writer, args []string) error { indexName := args[2] areAllObjectsStandard := true - snapshotRepositoryMetadata := r.Client.GetSnapshotRepositoryMetadata(repositoryID) + repository := r.Client.GetRepository(repositoryID) - if snapshotRepositoryMetadata.Type == "s3" { - fmt.Fprintf(out, "bucket name : %s\n", util.StringWithColor(snapshotRepositoryMetadata.Settings.Bucket)) - fmt.Fprintf(out, "base path : %s\n", util.StringWithColor(snapshotRepositoryMetadata.Settings.BasePath)) + if repository.Type == "s3" { + fmt.Fprintf(out, "bucket name : %s\n", util.StringWithColor(repository.Settings.Bucket)) + fmt.Fprintf(out, "base path : %s\n", util.StringWithColor(repository.Settings.BasePath)) - snapshotSnapshotsIndicesMetadata, err := r.getIndexIDFromS3( - aws.String(snapshotRepositoryMetadata.Settings.Bucket), - aws.String(snapshotRepositoryMetadata.Settings.BasePath+"/"), + snapshotsIndicesS3, err := r.getIndexIDFromS3( + aws.String(repository.Settings.Bucket), + aws.String(repository.Settings.BasePath+"/"), ) if err != nil { return err } - for { - metaData := snapshotSnapshotsIndicesMetadata.Indices[indexName] - prefix := snapshotRepositoryMetadata.Settings.BasePath + "/indices/" + metaData.ID + "/" - - objs, _ := r.Client.GetObjects(aws.String(snapshotRepositoryMetadata.Settings.Bucket), aws.String(prefix), nil, nil) + metaData := snapshotsIndicesS3.Indices[indexName] + prefix := repository.Settings.BasePath + "/indices/" + metaData.ID + "/" + objs, _ := r.Client.GetObjects(aws.String(repository.Settings.Bucket), aws.String(prefix), nil, nil) + for { for _, item := range objs.Contents { fmt.Println(*item.Key) if *item.StorageClass == "GLACIER" { areAllObjectsStandard = false if r.Flag.Force { color.Green("Restore Storage Class to %s -> STANDARD", *item.StorageClass) - err := r.restoreObject(out, aws.String(snapshotRepositoryMetadata.Settings.Bucket), item.Key) + err := r.restoreObject(out, aws.String(repository.Settings.Bucket), item.Key) if err != nil { panic(err) } @@ -261,7 +266,7 @@ func (r Runner) RestoreSnapshot(out io.Writer, args []string) error { resp, _ := reader.ReadString('\n') if strings.ToLower(strings.TrimSpace(resp)) == "y" { color.Green("Change Storage Class to %s -> STANDARD", *item.StorageClass) - err := r.restoreObject(out, aws.String(snapshotRepositoryMetadata.Settings.Bucket), item.Key) + err := r.restoreObject(out, aws.String(repository.Settings.Bucket), item.Key) if err != nil { panic(err) } @@ -271,18 +276,18 @@ func (r Runner) RestoreSnapshot(out io.Writer, args []string) error { } } } + if *objs.IsTruncated { - objs, _ = r.Client.GetObjects(aws.String(snapshotRepositoryMetadata.Settings.Bucket), aws.String(prefix), nil, objs.NextContinuationToken) + objs, _ = r.Client.GetObjects(aws.String(repository.Settings.Bucket), aws.String(prefix), nil, objs.NextContinuationToken) } else { break } } - } if areAllObjectsStandard { requestBody, _ := json.Marshal( - schema.SnapshotRequestBody{ + snapshotSchema.RequestBody{ Indices: indexName, }, ) @@ -305,10 +310,9 @@ func (r Runner) restoreObject(out io.Writer, bucket *string, key *string) error if *resp.Restore == "ongoing-request=\"true\"" { fmt.Fprintf(out, "%s is ongoing-restore\n", util.StringWithColor(*key)) return nil - } else { - r.Client.TransitObject(bucket, key, "STANDARD") - return nil } + r.Client.TransitObject(bucket, key, "STANDARD") + return nil } err = r.Client.RestoreObject(bucket, key) @@ -318,4 +322,4 @@ func (r Runner) restoreObject(out io.Writer, bucket *string, key *string) error } return nil -} \ No newline at end of file +} diff --git a/internal/schema/cat.go b/internal/schema/cat/schema.go similarity index 77% rename from internal/schema/cat.go rename to internal/schema/cat/schema.go index f264ecd..c16ebca 100644 --- a/internal/schema/cat.go +++ b/internal/schema/cat/schema.go @@ -14,9 +14,9 @@ see the license for the specific language governing permissions and limitations under the license. */ -package schema +package cats -type CatHealthMetadata struct { +type Health struct { Cluster string `json:"cluster"` Status string `json:"status"` NodeTotal string `json:"node.total"` @@ -26,7 +26,7 @@ type CatHealthMetadata struct { ActiveShardsPercent string `json:"active_shards_percent"` } -type CatIndexMetadata struct { +type Index struct { Health string `json:"health"` Status string `json:"status"` Index string `json:"Index"` @@ -36,7 +36,7 @@ type CatIndexMetadata struct { StoreSize string `json:"store.size"` } -type CatNodeMetadata struct { +type Node struct { IP string `json:"ip"` NodeRole string `json:"node.role"` Name string `json:"name"` @@ -47,19 +47,19 @@ type CatNodeMetadata struct { Uptime string `json:"uptime"` } -type CatShardMetadata struct { - Index string `json:"index"` - Shard string `json:"shard"` - PriRep string `json:"prirep"` - State string `json:"state"` - Docs string `json:"docs"` - Store string `json:"store"` - IP string `json:"ip"` - Node string `json:"node"` +type Shard struct { + Index string `json:"index"` + Shard string `json:"shard"` + PriRep string `json:"prirep"` + State string `json:"state"` + Docs string `json:"docs"` + Store string `json:"store"` + IP string `json:"ip"` + Node string `json:"node"` UnassignedReason string `json:"unassigned.reason"` } -type CatRepositoryMetadata struct { +type Repository struct { ID string `json:"id"` Type string `json:"type"` -} \ No newline at end of file +} diff --git a/internal/schema/cluster/schema.go b/internal/schema/cluster/schema.go new file mode 100644 index 0000000..2b9244a --- /dev/null +++ b/internal/schema/cluster/schema.go @@ -0,0 +1,22 @@ +/* +copyright 2020 the Escli authors + +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 cluster + +type RequestBody struct { + Persistent map[string]string `json:"persistent,omitempty"` + Transient map[string]string `json:"transient,omitempty"` +} diff --git a/internal/schema/index.go b/internal/schema/index/schema.go similarity index 91% rename from internal/schema/index.go rename to internal/schema/index/schema.go index f1aa1a3..e767c51 100644 --- a/internal/schema/index.go +++ b/internal/schema/index/schema.go @@ -14,8 +14,8 @@ see the license for the specific language governing permissions and limitations under the license. */ -package schema +package index -type IndexIndexSettingsRequestBody struct { +type RequestBody struct { Index map[string]string `json:"index"` } diff --git a/internal/schema/snapshot.go b/internal/schema/snapshot/schema.go similarity index 68% rename from internal/schema/snapshot.go rename to internal/schema/snapshot/schema.go index 1dfd822..9efee8c 100644 --- a/internal/schema/snapshot.go +++ b/internal/schema/snapshot/schema.go @@ -14,15 +14,15 @@ see the license for the specific language governing permissions and limitations under the license. */ -package schema +package snapshotschema import "time" -type SnapshotSnapshotsMetadata struct { - SnapshotSnapshotMetadata []SnapshotSnapshotMetadata `json:"snapshots"` +type Snapshots struct { + Snapshots []Snapshot `json:"snapshots"` } -type SnapshotSnapshotMetadata struct { +type Snapshot struct { Name string `json:"name,omitempty"` Snapshot string `json:"snapshot,omitempty"` UUID string `json:"uuid,omitempty"` @@ -44,35 +44,34 @@ type SnapshotSnapshotMetadata struct { } `json:"shards,omitempty"` } -type SnapshotRequestBody struct { +type RequestBody struct { Indices string `json:"indices"` } -type SnapshotRepositoryMetadata struct { - Type string `json:"type"` - Settings SnapshotRepositorySettingsMetadata `json:"settings"` +type Repository struct { + Type string `json:"type"` + Settings RepositorySettings `json:"settings"` } -type SnapshotRepositorySettingsMetadata struct { - Bucket string `json:"bucket"` - BasePath string `json:"base_path"` +type RepositorySettings struct { + Bucket string `json:"bucket"` + BasePath string `json:"base_path"` StorageClass string `json:"storage_class"` - Region string `json:"region"` + Region string `json:"region"` } -type SnapshotSnapshotsIndicesMetadata struct { - Snapshots []SnapshotSnapshotS3Metadata `json:"snapshots"` - Indices map[string] SnapshotIndexMetadata `json:"indices"` +type SnapshotsIndicesS3 struct { + Snapshots []SnapshotS3 `json:"snapshots"` + Indices map[string]IndexS3 `json:"indices"` } -type SnapshotIndexMetadata struct { - ID string `json:"id"` +type IndexS3 struct { + ID string `json:"id"` Snapshots []string `json:"snapshots"` } -type SnapshotSnapshotS3Metadata struct { - Name string `json:"name"` - UUID string `json:"uuid"` - State int `json:"state"` +type SnapshotS3 struct { + Name string `json:"name"` + UUID string `json:"uuid"` + State int `json:"state"` } - diff --git a/internal/util/util.go b/internal/util/util.go index fe04ccd..e917e66 100644 --- a/internal/util/util.go +++ b/internal/util/util.go @@ -21,9 +21,6 @@ import ( "encoding/json" "errors" "fmt" - "github.com/elastic/go-elasticsearch/esapi" - "github.com/fatih/color" - "github.com/spf13/cobra" "io" "io/ioutil" "os" @@ -31,6 +28,9 @@ import ( "strings" "github.com/AlecAivazis/survey/v2" + "github.com/elastic/go-elasticsearch/esapi" + "github.com/fatih/color" + "github.com/spf13/cobra" ) func ConvertJSONtoMetadata(r io.Reader, d interface{}) { @@ -88,6 +88,18 @@ func CreateFile(filePath string, writeData string) error { return nil } +func GreenString(content string) string { + return color.GreenString(content) +} + +func RedString(content string) string { + return color.RedString(content) +} + +func YellowString(content string) string { + return color.YellowString(content) +} + func StringWithColor(content string) string { switch content { case "green": @@ -129,23 +141,20 @@ func IntWithColor(number int, status string) string { } func FloatWithColor(number float64) string { - if number > 90 { + switch { + case number > 90: return color.RedString("%.0f", number) - } else if number > 80 { + case number > 80: return color.YellowString("%.0f", number) - } else if number > 70 { + case number > 70: return color.BlueString("%.0f", number) + default: + return color.GreenString("%.0f", number) } - - return color.GreenString("%.0f", number) } func IsEvenNumber(number int) bool { - if number%2 == 0 { - return true - } else { - return false - } + return number%2 == 0 } func GetFullCommandUse(cmd *cobra.Command) string { @@ -164,8 +173,8 @@ func ReturnErrorFromResponseBody(response *esapi.Response) error { } } -func responseBodyToString(closer io.ReadCloser) string { +func responseBodyToString(closer io.Reader) string { buf := new(bytes.Buffer) buf.ReadFrom(closer) return buf.String() -} \ No newline at end of file +}