Files
esctl/pkg/cfg/config.go

295 lines
7.4 KiB
Go
Raw Normal View History

2026-04-21 10:50:09 +02:00
/*
Copyright © 2026 Thomas von Dein
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cfg
import (
2026-05-29 10:19:18 +02:00
"bytes"
"context"
2026-04-21 10:50:09 +02:00
"crypto/tls"
2026-05-29 10:19:18 +02:00
"encoding/json"
2026-04-21 10:50:09 +02:00
"errors"
"fmt"
2026-05-29 10:19:18 +02:00
"log/slog"
2026-04-21 10:50:09 +02:00
"net/http"
"os"
"github.com/alecthomas/repr"
2026-04-21 10:50:09 +02:00
"github.com/elastic/elastic-transport-go/v8/elastictransport"
"github.com/elastic/go-elasticsearch/v9"
"gopkg.in/yaml.v3"
2026-04-21 10:50:09 +02:00
)
const (
2026-06-03 10:14:41 +02:00
Version string = `v0.0.17`
)
var (
2026-05-21 14:00:35 +02:00
// initialized during build, see Makefile:buildlocal
APIVERSION, GOVERSION, BUILD, COMMIT, BRANCH string
2026-04-21 10:50:09 +02:00
)
type Cluster struct {
Uri, User, Pass string
ES *elasticsearch.TypedClient
}
2026-04-21 10:50:09 +02:00
type Config struct {
ConfigFile string // -c
CurrentCluster string // -C
Debug bool // -d
Output string // -o <mode>
Clusters map[string]*Cluster
DefaultCluster *Cluster
Index string // index: -i
Failed, Partials bool // index: flags
2026-05-18 13:58:08 +02:00
Shards, Replicas int // index create+allocation: -s -r
Wait bool // index create: -w
2026-05-18 13:58:08 +02:00
Primary bool // index allocation: -p
2026-06-03 10:14:41 +02:00
Searchable bool // index fields: -s
Aggretable bool // index fields: -a
From, To, MaxItems int // search: flags
Filter []string // search: -F
Path string // search+doc sh: -p
Subhelp bool // search+doc sh: -H
2026-05-29 10:19:18 +02:00
Tail bool // search: -f [tail]
Or bool // search: -O
Range string // search: -r
TimestampFormat string // search: --timestamp-format
Explain bool // search: -e
SortBy string // sort: -k
Ascending bool // sort: -a
Exclude string // cluster compare: -e (regexp)
All, Verbose bool // cluster status: -a -v
Persistent, Transient, Default bool // -p -t -D cluster settings set
Force bool // ccr follower renew: -f
HaveJQ bool // determined at runtime by ourselfes
2026-05-29 10:19:18 +02:00
DebugHTTP bool // root: --debug-http
2026-06-03 08:47:54 +02:00
Separator string // role diff: -s
NotDeployed bool // role diff: -n
Undefined bool // role diff: -u
Diff bool // role diff: -D
2026-04-21 10:50:09 +02:00
}
func NewConfig() *Config {
return &Config{Clusters: map[string]*Cluster{}}
}
func (conf *Config) Init() error {
DefaultConfig := os.Getenv("HOME") + "/.config/esctl/config.yaml"
switch {
case fileExists(DefaultConfig):
conf.ConfigFile = DefaultConfig
fallthrough
case conf.ConfigFile != "":
if err := conf.LoadConfig(); err != nil {
return err
}
default:
if err := conf.LoadEnv(); err != nil {
return err
}
}
if err := conf.SetupES(); err != nil {
return err
}
if conf.CurrentCluster != "" {
current, exists := conf.Clusters[conf.CurrentCluster]
if !exists {
return fmt.Errorf("no cluster with alias %s configured", conf.CurrentCluster)
} else {
conf.DefaultCluster = current
}
} else {
if len(conf.Clusters) == 1 {
for name, cluster := range conf.Clusters {
conf.DefaultCluster = cluster
conf.CurrentCluster = name
}
} else {
for name, cluster := range conf.Clusters {
_, err := cluster.ES.Cluster.Health().
Header("content-type", "application/json").
Header("accept", "application/json").
Do(context.Background())
if err == nil {
conf.DefaultCluster = cluster
conf.CurrentCluster = name
}
}
}
}
conf.HaveJQ = isJQinstalled()
conf.PrintDebug()
return nil
}
2026-05-11 10:46:17 +02:00
func (conf *Config) PrintDebug() {
if !conf.Debug {
2026-05-11 10:46:17 +02:00
return
}
clone := *conf
for name := range clone.Clusters {
clone.Clusters[name] = nil
}
clone.DefaultCluster = nil
fmt.Println("config:")
repr.Println(clone)
}
func (conf *Config) LoadEnv() error {
cluster := Cluster{
2026-04-21 10:50:09 +02:00
Uri: os.Getenv("ES_URI"),
User: os.Getenv("ES_USER"),
Pass: os.Getenv("ES_PASS"),
}
switch {
case cluster.Uri == "":
return errors.New("ES_URI unset")
case cluster.User == "":
return errors.New("ES_USER unset")
case cluster.Pass == "":
return errors.New("ES_PASS unset")
}
conf.Clusters["default"] = &cluster
conf.DefaultCluster = &cluster
return nil
}
func (conf *Config) LoadConfig() error {
if conf.ConfigFile == "" {
return nil
}
data, err := os.ReadFile(conf.ConfigFile)
if err != nil {
return fmt.Errorf("failed to read config file: %w", err)
}
newconf := &Config{}
err = yaml.Unmarshal(data, newconf)
if err != nil {
return fmt.Errorf("failed to unmarshal config file: %w", err)
2026-04-21 10:50:09 +02:00
}
if len(newconf.Clusters) > 0 {
conf.Clusters = newconf.Clusters
_, exists := conf.Clusters["default"]
if !exists {
// no "default", just use the first we stumble upon
for _, cluster := range conf.Clusters {
conf.DefaultCluster = cluster
break
}
} else {
conf.DefaultCluster = newconf.Clusters["default"]
}
}
return nil
}
2026-05-29 10:19:18 +02:00
func (conf *Config) getTransport() elastictransport.Option {
transport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
if conf.DebugHTTP {
return elastictransport.WithTransport(
&DebugTransport{Transport: transport},
)
}
return elastictransport.WithTransport(transport)
}
func (conf *Config) SetupES() error {
for _, cluster := range conf.Clusters {
es, err := elasticsearch.NewTyped(
elasticsearch.WithAddresses(cluster.Uri),
elasticsearch.WithBasicAuth(cluster.User, cluster.Pass),
2026-05-29 10:19:18 +02:00
elasticsearch.WithTransportOptions(conf.getTransport()),
)
if err != nil {
return fmt.Errorf("failed to setup elasticsearch connection: %w", err)
}
2026-04-21 10:50:09 +02:00
cluster.ES = es
}
2026-04-21 10:50:09 +02:00
return nil
2026-04-21 10:50:09 +02:00
}
2026-05-29 10:19:18 +02:00
// used to print uri, path and body of a request made by the go-client
type DebugTransport struct {
Transport http.RoundTripper
}
func (t *DebugTransport) RoundTrip(req *http.Request) (*http.Response, error) {
2026-05-29 11:27:40 +02:00
content := ""
contentline := ""
2026-05-29 10:19:18 +02:00
2026-05-29 11:27:40 +02:00
if req.ContentLength > 0 {
buf := new(bytes.Buffer)
body, _ := req.GetBody()
2026-05-29 10:19:18 +02:00
2026-05-29 11:27:40 +02:00
_, err := buf.ReadFrom(body)
if err != nil {
return nil, err
}
2026-05-29 10:19:18 +02:00
2026-05-29 11:27:40 +02:00
var pretty bytes.Buffer
err = json.Indent(&pretty, buf.Bytes(), "", "\t")
if err != nil {
return nil, fmt.Errorf("json parse error: %s", err)
}
content = pretty.String()
contentline = buf.String()
2026-05-29 10:19:18 +02:00
}
2026-05-29 11:27:40 +02:00
slog.Info("req", "host", req.URL.Host, "uri", req.URL.Path, "body", content, "bodyline", contentline)
2026-05-29 10:19:18 +02:00
return t.Transport.RoundTrip(req)
}
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if err != nil {
// return false on any error
return false
}
return !info.IsDir()
}