Compare commits
4 Commits
Author | SHA1 | Date | |
---|---|---|---|
44a125a524 | |||
63b9abbc76 | |||
2bac049856 | |||
31d3892d89 |
11
.github/workflows/build.yml
vendored
11
.github/workflows/build.yml
vendored
@ -42,6 +42,17 @@ jobs:
|
||||
- name: build darwin arm64
|
||||
run: CGO_ENABLE=0 GOOS=darwin GOARCH=arm64 go build -ldflags='-s -w' -o dist/esgo2dump_${{ github.ref_name }}_darwin_arm64 .
|
||||
|
||||
|
||||
- name: run upx
|
||||
uses: crazy-max/ghaction-upx@v3
|
||||
with:
|
||||
version: latest
|
||||
args: --best --ultra-brute
|
||||
files: |
|
||||
dist/esgo2dump_${{ github.ref_name }}_linux_amd64
|
||||
dist/esgo2dump_${{ github.ref_name }}_linux_arm64
|
||||
dist/esgo2dump_${{ github.ref_name }}_windows_amd64.exe
|
||||
|
||||
- name: create releases
|
||||
id: create_releases
|
||||
uses: "marvinpinto/action-automatic-releases@latest"
|
||||
|
9
.gitignore
vendored
9
.gitignore
vendored
@ -1,9 +1,10 @@
|
||||
.idea
|
||||
.vscode
|
||||
.DS_Store
|
||||
data.json
|
||||
mapping.json
|
||||
setting.json
|
||||
output.json
|
||||
*data.json
|
||||
*mapping.json
|
||||
*setting.json
|
||||
*output.json
|
||||
*test.json
|
||||
*.txt
|
||||
dist
|
6
go.mod
6
go.mod
@ -3,14 +3,20 @@ module github.com/loveuer/esgo2dump
|
||||
go 1.18
|
||||
|
||||
require (
|
||||
github.com/elastic/go-elasticsearch/v6 v6.8.10
|
||||
github.com/elastic/go-elasticsearch/v7 v7.17.10
|
||||
github.com/fatih/color v1.16.0
|
||||
github.com/samber/lo v1.39.0
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/spf13/cobra v1.8.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/stretchr/testify v1.8.4 // indirect
|
||||
golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17 // indirect
|
||||
golang.org/x/sys v0.14.0 // indirect
|
||||
)
|
||||
|
15
go.sum
15
go.sum
@ -2,13 +2,24 @@ github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46t
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/elastic/go-elasticsearch/v6 v6.8.10 h1:2lN0gJ93gMBXvkhwih5xquldszpm8FlUwqG5sPzr6a8=
|
||||
github.com/elastic/go-elasticsearch/v6 v6.8.10/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI=
|
||||
github.com/elastic/go-elasticsearch/v7 v7.17.10 h1:TCQ8i4PmIJuBunvBS6bwT2ybzVFxxUhhltAs3Gyu1yo=
|
||||
github.com/elastic/go-elasticsearch/v7 v7.17.10/go.mod h1:OJ4wdbtDNk5g503kvlHLyErCgQwwzmDtaFC4XyOxXA4=
|
||||
github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM=
|
||||
github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/samber/lo v1.39.0 h1:4gTz1wUhNYLhFSKl6O+8peW0v2F4BCY034GRpU9WnuA=
|
||||
github.com/samber/lo v1.39.0/go.mod h1:+m/ZKRl6ClXCE2Lgf3MsQlWfh4bn1bz6CXEOxnEXnEA=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
|
||||
@ -19,7 +30,11 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17 h1:3MTrJm4PyNL9NBqvYDSj3DHl46qQakyfqfWo4jgfaEM=
|
||||
golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17/go.mod h1:lgLbSvA5ygNOMpwM/9anMpWVlVJ7Z+cHWq/eFuinpGE=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q=
|
||||
golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
|
@ -19,8 +19,14 @@ esgo2dump --input=http://127.0.0.1:9200/some_index --output=./data.json
|
||||
|
||||
esgo2dump --input=http://127.0.0.1:9200/some_index --output=http://192.168.1.1:9200/some_index --limit=5000
|
||||
|
||||
esgo2dump --input=http://127.0.0.1:9200/some_index --i-version 6 --output=./data.json
|
||||
|
||||
esgo2dump --output=http://127.0.0.1:9200/some_index --o-version 6 --input=./data.json
|
||||
|
||||
esgo2dump --input=https://username:password@127.0.0.1:9200/some_index --output=./data.json
|
||||
|
||||
esgo2dump --input=http://127.0.0.1:9200/some_index --source='id;name;age;address' --output=./data.json
|
||||
|
||||
esgo2dump --input=http://127.0.0.1:9200/some_index --output=./data.json --query='{"match": {"name": "some_name"}}'
|
||||
|
||||
esgo2dump --input=http://127.0.0.1:9200/some_index --output=./data.json --query_file=my_queries.json`,
|
||||
@ -30,11 +36,14 @@ esgo2dump --input=http://127.0.0.1:9200/some_index --output=./data.json --query_
|
||||
f_output string
|
||||
f_limit int
|
||||
f_type string
|
||||
f_source string
|
||||
f_query string
|
||||
|
||||
f_query_file string
|
||||
|
||||
f_version bool
|
||||
|
||||
es_iversion, es_oversion string
|
||||
)
|
||||
|
||||
func init() {
|
||||
@ -44,7 +53,10 @@ func init() {
|
||||
|
||||
rootCommand.Flags().StringVarP(&f_input, "input", "i", "", "*required: input file or es url (example :data.json / http://127.0.0.1:9200/my_index)")
|
||||
rootCommand.Flags().StringVarP(&f_output, "output", "o", "output.json", "")
|
||||
rootCommand.Flags().StringVar(&es_iversion, "i-version", "7", "input(es) version")
|
||||
rootCommand.Flags().StringVar(&es_oversion, "o-version", "7", "output(es) version")
|
||||
rootCommand.Flags().StringVarP(&f_type, "type", "t", "data", "data/mapping/setting")
|
||||
rootCommand.Flags().StringVarP(&f_source, "source", "s", "", "query source, use ';' to separate")
|
||||
rootCommand.Flags().StringVarP(&f_query, "query", "q", "", `query dsl, example: {"bool":{"must":[{"term":{"name":{"value":"some_name"}}}],"must_not":[{"range":{"age":{"gte":18,"lt":60}}}]}}`)
|
||||
rootCommand.Flags().StringVar(&f_query_file, "query_file", "", `query json file (will execute line by line)`)
|
||||
rootCommand.Flags().IntVarP(&f_limit, "limit", "l", 100, "")
|
||||
|
@ -4,14 +4,18 @@ import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/loveuer/esgo2dump/internal/log"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/loveuer/esgo2dump/internal/interfaces"
|
||||
"github.com/loveuer/esgo2dump/internal/opt"
|
||||
"github.com/loveuer/esgo2dump/internal/xes"
|
||||
"github.com/loveuer/esgo2dump/internal/xfile"
|
||||
"github.com/samber/lo"
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
@ -48,22 +52,24 @@ func run(cmd *cobra.Command, args []string) error {
|
||||
|
||||
if opt.Debug {
|
||||
logrus.SetLevel(logrus.DebugLevel)
|
||||
logrus.SetReportCaller(true)
|
||||
logrus.SetFormatter(&logrus.JSONFormatter{})
|
||||
}
|
||||
|
||||
if f_version {
|
||||
logrus.Infof("esgo2dump (Version: %s)", opt.Version)
|
||||
return nil
|
||||
fmt.Printf("esgo2dump (Version: %s)\n", opt.Version)
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
if err = check(cmd); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if ioi, err = newIO(f_input, interfaces.IOInput); err != nil {
|
||||
if ioi, err = newIO(f_input, interfaces.IOInput, es_iversion); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if ioo, err = newIO(f_output, interfaces.IOOutput); err != nil {
|
||||
if ioo, err = newIO(f_output, interfaces.IOOutput, es_oversion); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@ -76,13 +82,17 @@ func run(cmd *cobra.Command, args []string) error {
|
||||
return fmt.Errorf("with file input, query or query_file can't be supported")
|
||||
}
|
||||
|
||||
if (f_source != "") && ioi.IsFile() {
|
||||
return fmt.Errorf("with file input, source can't be supported")
|
||||
}
|
||||
|
||||
switch f_type {
|
||||
case "data":
|
||||
if err = executeData(cmd.Context(), ioi, ioo); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logrus.Info("Dump: write data succeed!!!")
|
||||
log.Info("Dump: write data succeed!!!")
|
||||
|
||||
return nil
|
||||
case "mapping":
|
||||
@ -95,7 +105,7 @@ func run(cmd *cobra.Command, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
logrus.Info("Dump: write mapping succeed!!!")
|
||||
log.Info("Dump: write mapping succeed!!!")
|
||||
|
||||
return nil
|
||||
case "setting":
|
||||
@ -108,7 +118,7 @@ func run(cmd *cobra.Command, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
logrus.Info("Dump: write setting succeed!!!")
|
||||
log.Info("Dump: write setting succeed!!!")
|
||||
|
||||
return nil
|
||||
default:
|
||||
@ -122,8 +132,15 @@ func executeData(ctx context.Context, input, output interfaces.DumpIO) error {
|
||||
ch = make(chan []*interfaces.ESSource, 1)
|
||||
errCh = make(chan error)
|
||||
queries = make([]map[string]any, 0)
|
||||
sources = make([]string, 0)
|
||||
)
|
||||
|
||||
if f_source != "" {
|
||||
sources = lo.Map(strings.Split(f_source, ";"), func(item string, idx int) string {
|
||||
return strings.TrimSpace(item)
|
||||
})
|
||||
}
|
||||
|
||||
if f_query != "" {
|
||||
query := make(map[string]any)
|
||||
if err = json.Unmarshal([]byte(f_query), &query); err != nil {
|
||||
@ -187,18 +204,21 @@ func executeData(ctx context.Context, input, output interfaces.DumpIO) error {
|
||||
case <-c.Done():
|
||||
return
|
||||
default:
|
||||
if lines, err = input.ReadData(c, f_limit, query); err != nil {
|
||||
if lines, err = input.ReadData(c, f_limit, query, sources); err != nil {
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
|
||||
logrus.Debugf("executeData: input read_data got lines=%d", len(lines))
|
||||
logrus.
|
||||
WithField("action", "input read data got lines").
|
||||
WithField("lines", len(lines)).
|
||||
Debug()
|
||||
|
||||
if len(lines) == 0 {
|
||||
input.ResetOffset()
|
||||
if query != nil {
|
||||
bs, _ := json.Marshal(query)
|
||||
logrus.Infof("Dump: query_file query=%s read done!!!", string(bs))
|
||||
log.Info("Dump: query_file query=%s read done!!!", string(bs))
|
||||
}
|
||||
continue Loop
|
||||
}
|
||||
@ -234,20 +254,23 @@ func executeData(ctx context.Context, input, output interfaces.DumpIO) error {
|
||||
return err
|
||||
}
|
||||
|
||||
logrus.Debugf("executeData: output write_data succeed lines=%d", succeed)
|
||||
logrus.
|
||||
WithField("action", "output wrote data lines").
|
||||
WithField("lines", succeed).
|
||||
Debug()
|
||||
|
||||
if succeed != len(docs) {
|
||||
return fmt.Errorf("cmd.run: got lines=%d, only succeed=%d", len(docs), succeed)
|
||||
return fmt.Errorf("output got lines=%d, only succeed=%d", len(docs), succeed)
|
||||
}
|
||||
|
||||
total += succeed
|
||||
|
||||
logrus.Infof("Dump: succeed=%d total=%d docs succeed!!!", succeed, total)
|
||||
log.Info("Dump: succeed=%d total=%d docs succeed!!!", succeed, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newIO(source string, ioType interfaces.IO) (interfaces.DumpIO, error) {
|
||||
func newIO(source string, ioType interfaces.IO, esv string) (interfaces.DumpIO, error) {
|
||||
var (
|
||||
err error
|
||||
iurl *url.URL
|
||||
@ -255,33 +278,64 @@ func newIO(source string, ioType interfaces.IO) (interfaces.DumpIO, error) {
|
||||
qm = make(map[string]any)
|
||||
)
|
||||
|
||||
logrus.Debugf("newIO.%s: source string=%s", ioType.Code(), source)
|
||||
logrus.
|
||||
WithField("action", "new_io").
|
||||
WithField("type", ioType.Code()).
|
||||
WithField("source", source).
|
||||
WithField("es_version", esv).
|
||||
Debug()
|
||||
|
||||
if iurl, err = url.Parse(source); err != nil {
|
||||
logrus.Debugf("newIO.%s: url parse source err=%v", ioType.Code(), err)
|
||||
logrus.
|
||||
WithField("action", "new_io url parse error").
|
||||
WithField("type", ioType.Code()).
|
||||
WithField("source", source).
|
||||
WithField("err", err).
|
||||
Debug()
|
||||
goto ClientByFile
|
||||
}
|
||||
|
||||
if !(iurl.Scheme == "http" || iurl.Scheme == "https") {
|
||||
logrus.Debugf("newIO.%s: url scheme=%s invalid", ioType.Code(), iurl.Scheme)
|
||||
logrus.
|
||||
WithField("action", "new_io url scheme error").
|
||||
WithField("type", ioType.Code()).
|
||||
WithField("source", source).
|
||||
WithField("scheme", iurl.Scheme).
|
||||
Debug()
|
||||
goto ClientByFile
|
||||
}
|
||||
|
||||
if iurl.Host == "" {
|
||||
logrus.Debugf("newIO.%s: url host empty", ioType.Code())
|
||||
logrus.
|
||||
WithField("action", "new_io url host empty").
|
||||
WithField("type", ioType.Code()).
|
||||
WithField("source", source).
|
||||
Debug()
|
||||
goto ClientByFile
|
||||
}
|
||||
|
||||
if ioType == interfaces.IOInput && f_query != "" {
|
||||
if err = json.Unmarshal([]byte(f_query), &qm); err != nil {
|
||||
logrus.Debugf("newIO.%s: query=%s invalid to map[string]any", ioType.Code(), f_query)
|
||||
logrus.
|
||||
WithField("action", "new_io query string invalid").
|
||||
WithField("type", ioType.Code()).
|
||||
WithField("source", source).
|
||||
WithField("query", f_query).
|
||||
Debug()
|
||||
return nil, fmt.Errorf("invalid query err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
logrus.Debugf("newIO.%s: source as url=%+v", ioType.Code(), *iurl)
|
||||
|
||||
return xes.NewClient(iurl, ioType)
|
||||
switch esv {
|
||||
case "7":
|
||||
return xes.NewClient(iurl, ioType)
|
||||
case "6":
|
||||
return xes.NewClientV6(iurl, ioType)
|
||||
case "8":
|
||||
return nil, errors.New("es version 8 coming soon")
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown es version=%s", esv)
|
||||
}
|
||||
|
||||
ClientByFile:
|
||||
if ioType == interfaces.IOOutput {
|
||||
|
@ -3,7 +3,7 @@ package interfaces
|
||||
import "context"
|
||||
|
||||
type DumpIO interface {
|
||||
ReadData(context.Context, int, map[string]any) ([]*ESSource, error)
|
||||
ReadData(ctx context.Context, size int, query map[string]any, includeFields []string) ([]*ESSource, error)
|
||||
WriteData(ctx context.Context, docs []*ESSource) (int, error)
|
||||
|
||||
ResetOffset()
|
||||
|
@ -31,3 +31,20 @@ type ESMapping map[string]struct {
|
||||
Properties map[string]any `json:"properties"`
|
||||
} `json:"mappings"`
|
||||
}
|
||||
|
||||
type ESResponseV6 struct {
|
||||
ScrollId string `json:"_scroll_id"`
|
||||
Took int `json:"took"`
|
||||
TimedOut bool `json:"timed_out"`
|
||||
Shards struct {
|
||||
Total int `json:"total"`
|
||||
Successful int `json:"successful"`
|
||||
Skipped int `json:"skipped"`
|
||||
Failed int `json:"failed"`
|
||||
} `json:"_shards"`
|
||||
Hits struct {
|
||||
Total int `json:"total"`
|
||||
MaxScore float64 `json:"max_score"`
|
||||
Hits []*ESSource `json:"hits"`
|
||||
} `json:"hits"`
|
||||
}
|
||||
|
43
internal/log/log.go
Normal file
43
internal/log/log.go
Normal file
@ -0,0 +1,43 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"github.com/fatih/color"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
red = color.New(color.FgRed)
|
||||
green = color.New(color.FgGreen)
|
||||
yellow = color.New(color.FgYellow)
|
||||
|
||||
locker = &sync.Mutex{}
|
||||
|
||||
timeFormat = "06/01/02T15:04:05"
|
||||
)
|
||||
|
||||
func Info(msg string, data ...any) {
|
||||
buf := &bytes.Buffer{}
|
||||
_, _ = green.Fprint(buf, "Info ")
|
||||
_, _ = fmt.Fprintf(buf, "| %s | ", time.Now().Format(timeFormat))
|
||||
_, _ = fmt.Fprintf(buf, msg, data...)
|
||||
fmt.Println(buf.String())
|
||||
}
|
||||
|
||||
func Warn(msg string, data ...any) {
|
||||
buf := &bytes.Buffer{}
|
||||
_, _ = yellow.Fprint(buf, "Warn ")
|
||||
_, _ = fmt.Fprintf(buf, "| %s | ", time.Now().Format(timeFormat))
|
||||
_, _ = fmt.Fprintf(buf, msg, data...)
|
||||
fmt.Println(buf.String())
|
||||
}
|
||||
|
||||
func Error(msg string, data ...any) {
|
||||
buf := &bytes.Buffer{}
|
||||
_, _ = red.Fprint(buf, "Error ")
|
||||
_, _ = fmt.Fprintf(buf, "| %s | ", time.Now().Format(timeFormat))
|
||||
_, _ = fmt.Fprintf(buf, msg, data...)
|
||||
fmt.Println(buf.String())
|
||||
}
|
@ -1,3 +1,3 @@
|
||||
package opt
|
||||
|
||||
const Version = "v0.1.2"
|
||||
const Version = "v0.2.1"
|
||||
|
@ -6,6 +6,7 @@ import (
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/loveuer/esgo2dump/internal/log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@ -39,7 +40,13 @@ func NewClient(url *url.URL, iot interfaces.IO) (interfaces.DumpIO, error) {
|
||||
}
|
||||
}
|
||||
|
||||
logrus.Debugf("xes.NewClient: endpoint=%s index=%s (username=%s password=%s)", address, urlIndex, urlUsername, urlPassword)
|
||||
logrus.
|
||||
WithField("action", "new es client v7").
|
||||
WithField("endpoint", address).
|
||||
WithField("index", urlIndex).
|
||||
WithField("username", urlUsername).
|
||||
WithField("password", urlPassword).
|
||||
Debug()
|
||||
|
||||
if urlIndex == "" {
|
||||
return nil, fmt.Errorf("please specify index name: (like => http://127.0.0.1:9200/my_index)")
|
||||
@ -67,20 +74,30 @@ func NewClient(url *url.URL, iot interfaces.IO) (interfaces.DumpIO, error) {
|
||||
},
|
||||
},
|
||||
); err != nil {
|
||||
logrus.Debugf("xes.NewClient: elastic new client with endpont=%s err=%v", endpoints, err)
|
||||
logrus.
|
||||
WithField("action", "new es client v7 error").
|
||||
WithField("endpoints", endpoints).
|
||||
WithField("err", err).
|
||||
Debug()
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
|
||||
if infoResp, err = cli.Info(); err != nil {
|
||||
logrus.Debugf("xes.NewClient: ping err=%v", err)
|
||||
logrus.
|
||||
WithField("action", "es client v7 ping error").
|
||||
WithField("err", err).
|
||||
Debug()
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
|
||||
if infoResp.StatusCode != 200 {
|
||||
err = fmt.Errorf("info xes status=%d", infoResp.StatusCode)
|
||||
logrus.Debugf("xes.NewClient: status err=%v", err)
|
||||
logrus.
|
||||
WithField("action", "es client v7 ping status error").
|
||||
WithField("status", infoResp.StatusCode).
|
||||
Debug()
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
@ -141,12 +158,12 @@ func (c *client) ResetOffset() {
|
||||
c.c.ClearScroll.WithBody(bytes.NewReader(bs)),
|
||||
)
|
||||
if err != nil {
|
||||
logrus.Warnf("ResetOffset: clear scroll id=%s err=%v", c.scrollId, err)
|
||||
log.Warn("ResetOffset: clear scroll id=%s err=%v", c.scrollId, err)
|
||||
return
|
||||
}
|
||||
|
||||
if rr.StatusCode != 200 {
|
||||
logrus.Warnf("ResetOffset: clear scroll id=%s msg=%s", c.scrollId, rr.String())
|
||||
log.Warn("ResetOffset: clear scroll id=%s msg=%s", c.scrollId, rr.String())
|
||||
}
|
||||
}
|
||||
func (c *client) WriteData(ctx context.Context, docs []*interfaces.ESSource) (int, error) {
|
||||
@ -157,9 +174,12 @@ func (c *client) WriteData(ctx context.Context, docs []*interfaces.ESSource) (in
|
||||
be error
|
||||
)
|
||||
if indexer, err = esutil.NewBulkIndexer(esutil.BulkIndexerConfig{
|
||||
Client: c.c,
|
||||
Index: c.index,
|
||||
Refresh: "",
|
||||
Client: c.c,
|
||||
Index: c.index,
|
||||
ErrorTrace: true,
|
||||
OnError: func(ctx context.Context, err error) {
|
||||
|
||||
},
|
||||
}); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@ -201,7 +221,7 @@ func (c *client) WriteData(ctx context.Context, docs []*interfaces.ESSource) (in
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (c *client) ReadData(ctx context.Context, i int, query map[string]any) ([]*interfaces.ESSource, error) {
|
||||
func (c *client) ReadData(ctx context.Context, i int, query map[string]any, source []string) ([]*interfaces.ESSource, error) {
|
||||
var (
|
||||
err error
|
||||
resp *esapi.Response
|
||||
@ -217,6 +237,10 @@ func (c *client) ReadData(ctx context.Context, i int, query map[string]any) ([]*
|
||||
c.c.Search.WithScroll(time.Duration(opt.Timeout*2) * time.Second),
|
||||
}
|
||||
|
||||
if len(source) > 0 {
|
||||
qs = append(qs, c.c.Search.WithSourceIncludes(source...))
|
||||
}
|
||||
|
||||
if query != nil && len(query) > 0 {
|
||||
queryBs, _ := json.Marshal(map[string]any{"query": query})
|
||||
qs = append(qs, c.c.Search.WithBody(bytes.NewReader(queryBs)))
|
||||
|
381
internal/xes/xes6.go
Normal file
381
internal/xes/xes6.go
Normal file
@ -0,0 +1,381 @@
|
||||
package xes
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/loveuer/esgo2dump/internal/log"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
elastic "github.com/elastic/go-elasticsearch/v6"
|
||||
"github.com/elastic/go-elasticsearch/v6/esapi"
|
||||
"github.com/elastic/go-elasticsearch/v6/esutil"
|
||||
"github.com/loveuer/esgo2dump/internal/interfaces"
|
||||
"github.com/loveuer/esgo2dump/internal/opt"
|
||||
"github.com/loveuer/esgo2dump/internal/util"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func NewClientV6(url *url.URL, iot interfaces.IO) (interfaces.DumpIO, error) {
|
||||
|
||||
var (
|
||||
address = fmt.Sprintf("%s://%s", url.Scheme, url.Host)
|
||||
urlIndex = strings.TrimPrefix(url.Path, "/")
|
||||
urlUsername string
|
||||
urlPassword string
|
||||
errCh = make(chan error)
|
||||
cliCh = make(chan *elastic.Client)
|
||||
)
|
||||
|
||||
if url.User != nil {
|
||||
urlUsername = url.User.Username()
|
||||
if p, ok := url.User.Password(); ok {
|
||||
urlPassword = p
|
||||
}
|
||||
}
|
||||
|
||||
logrus.
|
||||
WithField("action", "new es client v6").
|
||||
WithField("endpoint", address).
|
||||
WithField("index", urlIndex).
|
||||
WithField("username", urlUsername).
|
||||
WithField("password", urlPassword).
|
||||
Debug()
|
||||
|
||||
if urlIndex == "" {
|
||||
return nil, fmt.Errorf("please specify index name: (like => http://127.0.0.1:9200/my_index)")
|
||||
}
|
||||
|
||||
ncFunc := func(endpoints []string, username, password, index string) {
|
||||
var (
|
||||
err error
|
||||
cli *elastic.Client
|
||||
infoResp *esapi.Response
|
||||
)
|
||||
|
||||
if cli, 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,
|
||||
},
|
||||
},
|
||||
); err != nil {
|
||||
logrus.
|
||||
WithField("action", "new es client v6 error").
|
||||
WithField("endpoints", endpoints).
|
||||
WithField("err", err).
|
||||
Debug()
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
|
||||
if infoResp, err = cli.Info(); err != nil {
|
||||
logrus.
|
||||
WithField("action", "es client v6 ping error").
|
||||
WithField("err", err).
|
||||
Debug()
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
|
||||
if infoResp.StatusCode != 200 {
|
||||
err = fmt.Errorf("info xes status=%d", infoResp.StatusCode)
|
||||
logrus.
|
||||
WithField("action", "es client v6 ping status error").
|
||||
WithField("status", infoResp.StatusCode).
|
||||
Debug()
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
|
||||
cliCh <- cli
|
||||
}
|
||||
|
||||
go ncFunc([]string{address}, urlUsername, urlPassword, urlIndex)
|
||||
|
||||
select {
|
||||
case <-util.Timeout(10).Done():
|
||||
return nil, fmt.Errorf("dial es=%s err=%v", address, context.DeadlineExceeded)
|
||||
case c := <-cliCh:
|
||||
return &clientv6{c: c, index: urlIndex, iot: iot}, nil
|
||||
case e := <-errCh:
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
|
||||
type clientv6 struct {
|
||||
c *elastic.Client
|
||||
iot interfaces.IO
|
||||
index string
|
||||
scrollId string
|
||||
}
|
||||
|
||||
func (c *clientv6) checkResponse(r *esapi.Response) error {
|
||||
if r.StatusCode == 200 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("status=%d msg=%s", r.StatusCode, r.String())
|
||||
}
|
||||
|
||||
func (c *clientv6) IOType() interfaces.IO {
|
||||
return c.iot
|
||||
}
|
||||
|
||||
func (c *clientv6) IsFile() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *clientv6) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *clientv6) ResetOffset() {
|
||||
defer func() {
|
||||
c.scrollId = ""
|
||||
}()
|
||||
|
||||
bs, _ := json.Marshal(map[string]string{
|
||||
"scroll_id": c.scrollId,
|
||||
})
|
||||
|
||||
rr, err := c.c.ClearScroll(
|
||||
c.c.ClearScroll.WithContext(util.Timeout(3)),
|
||||
c.c.ClearScroll.WithBody(bytes.NewReader(bs)),
|
||||
)
|
||||
if err != nil {
|
||||
log.Warn("ResetOffset: clear scroll id=%s err=%v", c.scrollId, err)
|
||||
return
|
||||
}
|
||||
|
||||
if rr.StatusCode != 200 {
|
||||
log.Warn("ResetOffset: clear scroll id=%s msg=%s", c.scrollId, rr.String())
|
||||
}
|
||||
}
|
||||
func (c *clientv6) WriteData(ctx context.Context, docs []*interfaces.ESSource) (int, error) {
|
||||
var (
|
||||
err error
|
||||
indexer esutil.BulkIndexer
|
||||
count int
|
||||
be error
|
||||
)
|
||||
if indexer, err = esutil.NewBulkIndexer(esutil.BulkIndexerConfig{
|
||||
Client: c.c,
|
||||
Index: c.index,
|
||||
DocumentType: "_doc",
|
||||
ErrorTrace: true,
|
||||
}); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
for _, doc := range docs {
|
||||
var bs []byte
|
||||
|
||||
if bs, err = json.Marshal(doc.Content); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
logrus.WithField("raw", string(bs)).Debug()
|
||||
|
||||
if err = indexer.Add(context.Background(), esutil.BulkIndexerItem{
|
||||
Action: "index",
|
||||
Index: c.index,
|
||||
DocumentID: doc.DocId,
|
||||
Body: bytes.NewReader(bs),
|
||||
OnFailure: func(ctx context.Context, item esutil.BulkIndexerItem, item2 esutil.BulkIndexerResponseItem, bulkErr error) {
|
||||
be = bulkErr
|
||||
},
|
||||
}); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
count++
|
||||
}
|
||||
|
||||
if err = indexer.Close(util.TimeoutCtx(ctx, opt.Timeout)); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if be != nil {
|
||||
return 0, be
|
||||
}
|
||||
|
||||
stats := indexer.Stats()
|
||||
if stats.NumFailed > 0 {
|
||||
return count, fmt.Errorf("write to xes failed_count=%d bulk_count=%d", stats.NumFailed, count)
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (c *clientv6) ReadData(ctx context.Context, i int, query map[string]any, source []string) ([]*interfaces.ESSource, error) {
|
||||
var (
|
||||
err error
|
||||
resp *esapi.Response
|
||||
result = new(interfaces.ESResponseV6)
|
||||
bs []byte
|
||||
)
|
||||
|
||||
if c.scrollId == "" {
|
||||
qs := []func(*esapi.SearchRequest){
|
||||
c.c.Search.WithContext(util.TimeoutCtx(ctx, opt.Timeout)),
|
||||
c.c.Search.WithIndex(c.index),
|
||||
c.c.Search.WithSize(i),
|
||||
c.c.Search.WithFrom(0),
|
||||
c.c.Search.WithScroll(time.Duration(opt.Timeout*2) * time.Second),
|
||||
}
|
||||
|
||||
if len(source) > 0 {
|
||||
qs = append(qs, c.c.Search.WithSourceIncludes(source...))
|
||||
}
|
||||
|
||||
if query != nil && len(query) > 0 {
|
||||
queryBs, _ := json.Marshal(map[string]any{"query": query})
|
||||
qs = append(qs, c.c.Search.WithBody(bytes.NewReader(queryBs)))
|
||||
}
|
||||
|
||||
if resp, err = c.c.Search(qs...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return nil, fmt.Errorf(resp.String())
|
||||
}
|
||||
|
||||
if bs, err = io.ReadAll(resp.Body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(bs, result); err != nil {
|
||||
logrus.
|
||||
WithField("err", err.Error()).
|
||||
WithField("raw", string(bs)).
|
||||
Debug()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c.scrollId = result.ScrollId
|
||||
|
||||
return result.Hits.Hits, nil
|
||||
}
|
||||
|
||||
if resp, err = c.c.Scroll(
|
||||
c.c.Scroll.WithScrollID(c.scrollId),
|
||||
c.c.Scroll.WithScroll(time.Duration(opt.Timeout*2)*time.Second),
|
||||
); err != nil {
|
||||
return result.Hits.Hits, nil
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(resp.Body)
|
||||
if err = decoder.Decode(result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return result.Hits.Hits, nil
|
||||
}
|
||||
|
||||
func (c *clientv6) ReadMapping(ctx context.Context) (map[string]any, error) {
|
||||
r, err := c.c.Indices.GetMapping(
|
||||
c.c.Indices.GetMapping.WithIndex(c.index),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if r.StatusCode != 200 {
|
||||
return nil, fmt.Errorf("status=%d, msg=%s", r.StatusCode, r.String())
|
||||
}
|
||||
|
||||
m := make(map[string]any)
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
if err = decoder.Decode(&m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return m, nil
|
||||
}
|
||||
func (c *clientv6) WriteMapping(ctx context.Context, m map[string]any) error {
|
||||
var (
|
||||
err error
|
||||
bs []byte
|
||||
result *esapi.Response
|
||||
)
|
||||
|
||||
for idxKey := range m {
|
||||
if bs, err = json.Marshal(m[idxKey]); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if result, err = c.c.Indices.Create(
|
||||
c.index,
|
||||
c.c.Indices.Create.WithContext(util.TimeoutCtx(ctx, opt.Timeout)),
|
||||
c.c.Indices.Create.WithBody(bytes.NewReader(bs)),
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = c.checkResponse(result); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *clientv6) ReadSetting(ctx context.Context) (map[string]any, error) {
|
||||
r, err := c.c.Indices.GetSettings(
|
||||
c.c.Indices.GetSettings.WithContext(util.TimeoutCtx(ctx, opt.Timeout)),
|
||||
c.c.Indices.GetSettings.WithIndex(c.index),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if r.StatusCode != 200 {
|
||||
return nil, fmt.Errorf("status=%d, msg=%s", r.StatusCode, r.String())
|
||||
}
|
||||
|
||||
m := make(map[string]any)
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
if err = decoder.Decode(&m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (c *clientv6) WriteSetting(ctx context.Context, m map[string]any) error {
|
||||
var (
|
||||
err error
|
||||
bs []byte
|
||||
result *esapi.Response
|
||||
)
|
||||
|
||||
if bs, err = json.Marshal(m); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if result, err = c.c.Indices.PutSettings(
|
||||
bytes.NewReader(bs),
|
||||
c.c.Indices.PutSettings.WithContext(util.TimeoutCtx(ctx, opt.Timeout)),
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.checkResponse(result)
|
||||
}
|
@ -4,10 +4,11 @@ import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/loveuer/esgo2dump/internal/opt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/loveuer/esgo2dump/internal/opt"
|
||||
|
||||
"github.com/loveuer/esgo2dump/internal/interfaces"
|
||||
)
|
||||
|
||||
@ -111,7 +112,7 @@ func (c *client) WriteData(ctx context.Context, docs []*interfaces.ESSource) (in
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (c *client) ReadData(ctx context.Context, i int, _ map[string]any) ([]*interfaces.ESSource, error) {
|
||||
func (c *client) ReadData(ctx context.Context, i int, _ map[string]any, _ []string) ([]*interfaces.ESSource, error) {
|
||||
var (
|
||||
err error
|
||||
count = 0
|
||||
|
7
main.go
7
main.go
@ -2,12 +2,11 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/loveuer/esgo2dump/internal/log"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"github.com/loveuer/esgo2dump/internal/cmd"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@ -16,9 +15,7 @@ func main() {
|
||||
defer cancel()
|
||||
|
||||
if err := cmd.Start(ctx); err != nil {
|
||||
logrus.Error(err)
|
||||
log.Error(err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
logrus.Debug("main: cmd start success!!!")
|
||||
}
|
||||
|
@ -26,8 +26,14 @@ esgo2dump --input=http://127.0.0.1:9200/some_index --output=./data.json
|
||||
|
||||
esgo2dump --input=http://127.0.0.1:9200/some_index --output=http://192.168.1.1:9200/some_index --limit=5000
|
||||
|
||||
esgo2dump --input=http://127.0.0.1:9200/some_index --i-version 6 --output=./data.json
|
||||
|
||||
esgo2dump --output=http://127.0.0.1:9200/some_index --o-version 6 --input=./data.json
|
||||
|
||||
esgo2dump --input=https://username:password@127.0.0.1:9200/some_index --output=./data.json
|
||||
|
||||
esgo2dump --input=http://127.0.0.1:9200/some_index --source='id;name;age;address;phones' --output=./data.json
|
||||
|
||||
esgo2dump --input=http://127.0.0.1:9200/some_index --output=./data.json --query='{"match": {"name": "some_name"}}'
|
||||
|
||||
esgo2dump --input=http://127.0.0.1:9200/some_index --output=./data.json --query_file=my_queries.json
|
||||
@ -48,4 +54,5 @@ esgo2dump --input=http://127.0.0.1:9200/some_index --output=./data.json --query_
|
||||
- [x] es to es
|
||||
- [x] auto create index with mapping
|
||||
- [ ] auto create index with mapping,setting
|
||||
- [ ] support es8
|
||||
- [x] support es6
|
||||
- [ ] support es8
|
||||
|
Reference in New Issue
Block a user