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

Add es-index-cleaner golang implementation #3192

Merged
merged 2 commits into from
Aug 12, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
69 changes: 69 additions & 0 deletions cmd/es-index-cleaner/app/flags.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Copyright (c) 2021 The Jaeger 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 app

import (
"flag"

"github.com/spf13/viper"
)

const (
indexPrefix = "index-prefix"
archive = "archive"
rollover = "rollover"
timeout = "timeout"
indexDateSeparator = "index-date-separator"
username = "es.username"
password = "es.password"
)

// Config holds configuration for index cleaner binary.
type Config struct {
IndexPrefix string
Archive bool
Rollover bool
MasterNodeTimeoutSeconds int
IndexDateSeparator string
Username string
Password string
TLSEnabled bool
}

// AddFlags adds flags for TLS to the FlagSet.
func (c *Config) AddFlags(flags *flag.FlagSet) {
flags.String(indexPrefix, "", "Index prefix")
flags.Bool(archive, false, "Whether to remove archive indices")
flags.Bool(rollover, false, "Whether to remove indices created by rollover")
flags.Int(timeout, 120, "Number of seconds to wait for master node response")
Copy link
Contributor

Choose a reason for hiding this comment

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

Is the reason for using seconds instead of Duration for compatibility with the python version?

Copy link
Member Author

Choose a reason for hiding this comment

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

yes

flags.String(indexDateSeparator, "-", "Index date separator")
flags.String(username, "", "The username required by storage")
flags.String(password, "", "The password required by storage")
}

// InitFromViper initializes config from viper.Viper.
func (c *Config) InitFromViper(v *viper.Viper) {
c.IndexPrefix = v.GetString(indexPrefix)
if c.IndexPrefix != "" {
c.IndexPrefix += "-"
}

c.Archive = v.GetBool(archive)
c.Rollover = v.GetBool(rollover)
c.MasterNodeTimeoutSeconds = v.GetInt(timeout)
c.IndexDateSeparator = v.GetString(indexDateSeparator)
c.Username = v.GetString(username)
c.Password = v.GetString(password)
}
55 changes: 55 additions & 0 deletions cmd/es-index-cleaner/app/flags_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright (c) 2021 The Jaeger 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 app

import (
"flag"
"testing"

"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestBindFlags(t *testing.T) {
v := viper.New()
c := &Config{}
command := cobra.Command{}
flags := &flag.FlagSet{}
c.AddFlags(flags)
command.PersistentFlags().AddGoFlagSet(flags)
v.BindPFlags(command.PersistentFlags())

err := command.ParseFlags([]string{
"--index-prefix=tenant1",
"--rollover=true",
"--archive=true",
"--timeout=150",
"--index-date-separator=@",
"--es.username=admin",
"--es.password=admin",
})
require.NoError(t, err)

c.InitFromViper(v)
assert.Equal(t, "tenant1-", c.IndexPrefix)
assert.Equal(t, true, c.Rollover)
assert.Equal(t, true, c.Archive)
assert.Equal(t, 150, c.MasterNodeTimeoutSeconds)
assert.Equal(t, "@", c.IndexDateSeparator)
assert.Equal(t, "admin", c.Username)
assert.Equal(t, "admin", c.Password)
}
144 changes: 144 additions & 0 deletions cmd/es-index-cleaner/app/index_client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
// Copyright (c) 2021 The Jaeger 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 app

import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)

// Index represents ES index.
type Index struct {
// Index name.
Index string
// Index creation time.
CreationTime time.Time
// Aliases
Aliases map[string]bool
}

// IndicesClient is a client used to manipulate with indices.
pavolloffay marked this conversation as resolved.
Show resolved Hide resolved
type IndicesClient struct {
// Http client.
Client *http.Client
// ES server endpoint.
Endpoint string
// ES master_timeout parameter.
MasterTimeoutSeconds int
BasicAuth string
}

// GetJaegerIndices queries all Jaeger indices including the archive and rollover.
// Jaeger daily indices are:
// jaeger-span-2019-01-01, jaeger-service-2019-01-01, jaeger-dependencies-2019-01-01
// jaeger-span-archive
// Rollover indices:
// aliases: jaeger-span-read, jaeger-span-write, jaeger-service-read, jaeger-service-write
// indices: jaeger-span-000001, jaeger-service-000001 etc.
// aliases: jaeger-span-archive-read, jaeger-span-archive-write
// indices: jaeger-span-archive-000001
func (i *IndicesClient) GetJaegerIndices(prefix string) ([]Index, error) {
prefix += "jaeger-*"
r, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/%s?flat_settings=true&filter_path=*.aliases,*.settings", i.Endpoint, prefix), nil)
Copy link
Contributor

Choose a reason for hiding this comment

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

Question, do we need to URL encode the prefix?

Copy link
Member Author

Choose a reason for hiding this comment

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

doesn't the NewRequest encode the url?

Copy link
Contributor

@rubenvp8510 rubenvp8510 Aug 12, 2021

Choose a reason for hiding this comment

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

not sure, I don't think it is important. I was just wondering what happen if the prefix is for instance pattern is jaeger/tracing-*

if err != nil {
return nil, err
}
i.setAuthorization(r)
response, err := i.Client.Do(r)
if err != nil {
return nil, fmt.Errorf("failed to query Jaeger indices: %q", err)
pavolloffay marked this conversation as resolved.
Show resolved Hide resolved
}

if response.StatusCode != 200 {
Copy link
Contributor

Choose a reason for hiding this comment

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

You might want to accept the whole 200 class (like 204), instead of specifically the 200.

Copy link
Contributor

Choose a reason for hiding this comment

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

Also, you might want to have a list of errors that are retriable, making this more resilient.

Copy link
Member Author

Choose a reason for hiding this comment

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

I want to be strict here ES returns only 200.

Retries can be added later as a separate feature.

pavolloffay marked this conversation as resolved.
Show resolved Hide resolved
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
pavolloffay marked this conversation as resolved.
Show resolved Hide resolved
}
return nil, fmt.Errorf("failed to query Jaeger indices: %s", string(body))
pavolloffay marked this conversation as resolved.
Show resolved Hide resolved
}

body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}

type indexInfo struct {
Aliases map[string]interface{} `json:"aliases"`
Settings map[string]string `json:"settings"`
}
var indicesInfo map[string]indexInfo
if err = json.Unmarshal(body, &indicesInfo); err != nil {
return nil, fmt.Errorf("failed to unmarshall response: %q", err)
pavolloffay marked this conversation as resolved.
Show resolved Hide resolved
}

var indices []Index
for k, v := range indicesInfo {
aliases := map[string]bool{}
for alias := range v.Aliases {
aliases[alias] = true
}
// ignoring error, ES should return valid date
creationDate, _ := strconv.ParseInt(v.Settings["index.creation_date"], 10, 64)

indices = append(indices, Index{
Index: k,
CreationTime: time.Unix(0, int64(time.Millisecond)*creationDate),
Aliases: aliases,
})
}
return indices, nil
}

// DeleteIndices deletes specified set of indices.
func (i *IndicesClient) DeleteIndices(indices []Index) error {
concatIndices := ""
for _, i := range indices {
concatIndices += i.Index
concatIndices += ","
}

r, err := http.NewRequest(http.MethodDelete, fmt.Sprintf("%s/%s?master_timeout=%ds", i.Endpoint, concatIndices, i.MasterTimeoutSeconds), nil)
if err != nil {
pavolloffay marked this conversation as resolved.
Show resolved Hide resolved
return err
}
i.setAuthorization(r)

response, err := i.Client.Do(r)
if err != nil {
return err
}
if response.StatusCode != 200 {
var body string
if response.Body != nil {
pavolloffay marked this conversation as resolved.
Show resolved Hide resolved
bodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
return fmt.Errorf("deleting indices failed: %q", err)
pavolloffay marked this conversation as resolved.
Show resolved Hide resolved
}
body = string(bodyBytes)
}
return fmt.Errorf("deleting indices failed: %s", body)
}
return nil
}

func (i *IndicesClient) setAuthorization(r *http.Request) {
if i.BasicAuth != "" {
r.Header.Add("Authorization", fmt.Sprintf("Basic %s", i.BasicAuth))
}
}
Loading