esgo2dump/xes/es7/client.go

84 lines
1.8 KiB
Go
Raw Permalink Normal View History

package es7
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
elastic "github.com/elastic/go-elasticsearch/v7"
"github.com/elastic/go-elasticsearch/v7/esapi"
"github.com/loveuer/esgo2dump/internal/tool"
"github.com/samber/lo"
)
2025-01-02 21:38:30 -08:00
// NewClient
// new esv7 client
// uri example:
// - http://127.0.0.1:9200
// - https://<username>:<password>@node1.dev:9200,node2.dev:19200,node3.dev:29200
2025-02-05 18:07:53 +08:00
func NewClient(ctx context.Context, uri string) (*elastic.Client, error) {
var (
2025-01-02 21:38:30 -08:00
err error
username string
password string
client *elastic.Client
ins *url.URL
)
2025-01-02 21:38:30 -08:00
if ins, err = url.Parse(uri); err != nil {
return nil, err
}
2025-01-02 21:38:30 -08:00
endpoints := lo.Map(
strings.Split(ins.Host, ","),
func(item string, index int) string {
return fmt.Sprintf("%s://%s", ins.Scheme, item)
},
)
2025-01-02 21:38:30 -08:00
if ins.User != nil {
username = ins.User.Username()
password, _ = ins.User.Password()
}
2025-01-20 13:10:46 +08:00
query := ins.Query()
2025-01-02 21:38:30 -08:00
if client, err = elastic.NewClient(
elastic.Config{
Addresses: endpoints,
Username: username,
Password: password,
CACert: nil,
RetryOnStatus: []int{429},
MaxRetries: 3,
RetryBackoff: nil,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
DialContext: (&net.Dialer{Timeout: 10 * time.Second}).DialContext,
},
2025-02-05 18:07:53 +08:00
DiscoverNodesOnStart: lo.If(query.Get("sniff") == "true", true).Else(false),
2025-01-02 21:38:30 -08:00
},
); err != nil {
return nil, err
}
2025-02-05 18:07:53 +08:00
if query.Get("ping") != "false" {
2025-01-02 21:38:30 -08:00
var res *esapi.Response
if res, err = client.Ping(client.Ping.WithContext(tool.TimeoutCtx(ctx, 5))); err != nil {
return nil, err
}
2025-01-02 21:38:30 -08:00
if res.StatusCode != 200 {
err = fmt.Errorf("ping es server response: %s", res.String())
return nil, err
}
}
2025-01-02 21:38:30 -08:00
return client, nil
}