Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] Add elastic client #10

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,24 @@ This will store the encrypted file at `keys/production/oauth.pem.asc`.
cat oauth.pen.asc | bay kms decrypt > oauth.pem
```

## Elastic Cloud
Commands for querying and interacting with the Elastic Cloud API.

#### Required environment variables

> [!CAUTION]
> Variables are deployment specific - make sure the deployment you are targeting is not a production deployment.

* EC_API_KEY - Generated from the deployments Kibana settings
* EC_CLOUD_ID - Found on the deployments Elastic Cloud 'manage' page
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would this be better as a flag or argument instead of an envvar?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because they're creds I thought it safer to keep them stored as env vars but I suppose we could set them as env vars and reference them in the argument. Am I being too cautious in not allowing a user to expose those vars directly in an arg on the cli (and therefore making it available in their shell history)?


#### Usage
`delete-stale` Delete indices that are greater than 30 days old

```
bay elastic-cloud delete-stale
```

# Installation

## Homebrew (OSX)
Expand Down
133 changes: 133 additions & 0 deletions cmd/elastic-cloud/index.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package elastic_cloud

import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"strconv"
"strings"
"time"

"github.com/elastic/go-elasticsearch/v8"
"github.com/elastic/go-elasticsearch/v8/esapi"
"github.com/manifoldco/promptui"
"github.com/urfave/cli/v2"

envconfig "github.com/sethvargo/go-envconfig"
ctrl "sigs.k8s.io/controller-runtime"
)

// Config for Elasticsearch client
type EsConfig struct {
ApiKey string `env:"EC_API_KEY"`
CloudId string `env:"EC_CLOUD_ID"`
}

type IndexSettings struct {
IndexItem struct {
IndexDetail struct {
CreationDate string `json:"creation_date"`
} `json:"index"`
} `json:"settings"`
}

type Indices map[string]IndexSettings

var setupLog = ctrl.Log.WithName("setup")

func DeleteStaleIndices(c *cli.Context) error {
force := c.Bool("force")
deleteList := make([]string, 0)

var config EsConfig
if err := envconfig.Process(context.Background(), &config); err != nil {
setupLog.Error(err, "unable to parse environment variables")
os.Exit(1)
}

client, err := elasticsearch.NewClient(elasticsearch.Config{APIKey: config.ApiKey, CloudID: config.CloudId})

if err != nil {
return err
}

settings, err := esapi.IndicesGetSettingsRequest{FilterPath: []string{"*.settings.index.creation_date"}}.Do(context.TODO(), client)

if err != nil {
return err
}

list := Indices{}

if err := json.NewDecoder(settings.Body).Decode(&list); err != nil {
log.Fatalf("Error parsing the response body: %s", err)
} else {
for k, i := range list {
if strings.Contains(k, "elasticsearch_index") {
now := time.Now().UnixMilli()
created, err := strconv.ParseInt(i.IndexItem.IndexDetail.CreationDate, 10, 64)
Copy link
Contributor Author

@GROwen GROwen Feb 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using the creation date is a very rudimentary way of identifying stale indices because it does not identify the last time an index was updated.

I believe it may be possible to use data from the shards API to determine how 'fresh' an index is based on refresh, write or read metrics.

However because content is ephemeral and these are development indices we don't need to be too concerned about destructive requests.

if err != nil {
return err
}

diffInDays := (now - created) / (1000 * 60 * 60 * 24)
if diffInDays > 30 {
fmt.Printf("The index %+v is %v days old and will be marked for deletion\n", k, diffInDays)
deleteList = append(deleteList, k)
}
}
}
if c := len(deleteList); c > 0 {
if force {
fmt.Println("Deleting indices marked for deletion.")
statusCode, err := deleteIndices(client, deleteList, c)
if err != nil {
return err
} else {
if statusCode == 200 {
fmt.Printf("Deletion request failed. Status code %+v", statusCode)
} else {
fmt.Printf("%+v indices successfully deleted.", c)
}
}
} else {
prompt := promptui.Prompt{
Label: "Delete indices",
IsConfirm: true,
}

prompt_result, _ := prompt.Run()

if prompt_result == "y" {
_, err := deleteIndices(client, deleteList, c)
if err != nil {
return err
}
} else {
fmt.Printf("Operation cancelled.\nThere are %+v indices marked for deletion.\n", c)
}
}
} else {
fmt.Printf("No indices meet the criteria for deletion.")
}
}
return nil
}

func deleteIndices(client *elasticsearch.Client, deleteList []string, c int) (int, error) {
res, err := esapi.IndicesDeleteRequest{Index: deleteList}.Do(context.TODO(), client)
if err != nil {
return res.StatusCode, err
} else {
if res.StatusCode == 200 {
fmt.Printf("Deletion request failed. Status code %+v", res.StatusCode)
return res.StatusCode, errors.New("non 200 status code")
} else {
fmt.Printf("%+v indices successfully deleted.", c)
return res.StatusCode, nil
}
}
}
73 changes: 71 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,19 +1,28 @@
module github.com/dpc-sdp/bay-cli

go 1.20
go 1.21

toolchain go1.21.1

require (
github.com/alexeyco/simpletable v1.0.0
github.com/aws/aws-sdk-go-v2/config v1.26.3
github.com/aws/aws-sdk-go-v2/service/kms v1.27.9
github.com/elastic/go-elasticsearch v0.0.0
github.com/elastic/go-elasticsearch/v8 v8.12.0
github.com/manifoldco/promptui v0.9.0
github.com/pkg/errors v0.9.1
github.com/rs/zerolog v1.32.0
github.com/sethvargo/go-envconfig v1.0.0
github.com/spf13/cobra v1.8.0
github.com/urfave/cli/v2 v2.27.1
github.com/uselagoon/machinery v0.0.16
golang.org/x/crypto v0.18.0
gopkg.in/yaml.v3 v3.0.1
sigs.k8s.io/controller-runtime v0.17.2
)

require (
github.com/alexeyco/simpletable v1.0.0 // indirect
github.com/aws/aws-sdk-go-v2 v1.24.1 // indirect
github.com/aws/aws-sdk-go-v2/credentials v1.16.14 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.14.11 // indirect
Expand All @@ -26,14 +35,74 @@ require (
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.21.6 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.26.7 // indirect
github.com/aws/smithy-go v1.19.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.3 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/elastic/elastic-transport-go/v8 v8.4.0 // indirect
github.com/emicklei/go-restful/v3 v3.11.0 // indirect
github.com/evanphx/json-patch/v5 v5.8.0 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/go-logr/logr v1.4.1 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-openapi/jsonpointer v0.19.6 // indirect
github.com/go-openapi/jsonreference v0.20.2 // indirect
github.com/go-openapi/swag v0.22.3 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/google/gnostic-models v0.6.8 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/gofuzz v1.2.0 // indirect
github.com/google/uuid v1.5.0 // indirect
github.com/guregu/null v4.0.0+incompatible // indirect
github.com/hashicorp/go-version v1.6.0 // indirect
github.com/imdario/mergo v0.3.6 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/machinebox/graphql v0.2.2 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/mattn/go-runewidth v0.0.12 // indirect
github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/prometheus/client_golang v1.18.0 // indirect
github.com/prometheus/client_model v0.5.0 // indirect
github.com/prometheus/common v0.45.0 // indirect
github.com/prometheus/procfs v0.12.0 // indirect
github.com/rivo/uniseg v0.1.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/xrash/smetrics v0.0.0-20231213231151-1d8dd44e695e // indirect
go.opentelemetry.io/otel v1.21.0 // indirect
go.opentelemetry.io/otel/metric v1.21.0 // indirect
go.opentelemetry.io/otel/trace v1.21.0 // indirect
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e // indirect
golang.org/x/net v0.19.0 // indirect
golang.org/x/oauth2 v0.12.0 // indirect
golang.org/x/sys v0.16.0 // indirect
golang.org/x/term v0.16.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/time v0.3.0 // indirect
gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/protobuf v1.31.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
k8s.io/api v0.29.0 // indirect
k8s.io/apiextensions-apiserver v0.29.0 // indirect
k8s.io/apimachinery v0.29.0 // indirect
k8s.io/client-go v0.29.0 // indirect
k8s.io/component-base v0.29.0 // indirect
k8s.io/klog/v2 v2.110.1 // indirect
k8s.io/kube-openapi v0.0.0-20231010175941-2dd684a91f00 // indirect
k8s.io/utils v0.0.0-20230726121419-3b25d923346b // indirect
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect
sigs.k8s.io/yaml v1.4.0 // indirect
)
Loading