-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.go
210 lines (187 loc) · 4.54 KB
/
table.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package main
import (
"bufio"
"errors"
"fmt"
"github.com/json-iterator/go"
"github.com/luciferofwg/ESClient/global"
"github.com/satori/go.uuid"
"github.com/valyala/fasthttp"
"io"
"net/http"
"os"
"strings"
"sync"
"time"
)
type Scan interface {
Read()
Write()
}
var (
host, template, typ string
filesplite string
)
type TableFile struct {
ch chan interface{}
wg sync.WaitGroup
path string
}
func NewTableFile(path, fileSplite, esHost, esTemplate, esTyp string) *TableFile {
host = esHost
template = esTemplate
typ = esTyp
filesplite = fileSplite
return &TableFile{
ch: make(chan interface{}, 100),
path: path,
}
}
func (this *TableFile) Start() {
this.wg.Add(2)
this.read()
this.write()
this.wg.Wait()
}
func (this *TableFile) read() {
defer func() {
this.wg.Done()
if err := recover(); err != nil {
global.Log.Critical("读取文件异常:%v", err)
}
global.Log.Info("数据读完,退出")
}()
if !global.IsExist(this.path) {
s := fmt.Sprintf("文件%s不存在", this.path)
global.Log.Critical("%v", s)
panic(s)
}
fd, err := os.Open(this.path)
if err != nil {
s := fmt.Sprintf("打开文件失败,错误:%v", err)
global.Log.Critical(s)
panic(s)
}
defer fd.Close()
rd := bufio.NewReader(fd)
var bHead bool = true
var headers []string
totalLine := 0
errLine := 0
defer func() {
global.Log.Info("文件读取完成,一共%v行,错误%v行", totalLine, errLine)
}()
for {
line, err := rd.ReadString('\r')
ls := strings.TrimSpace(string(line))
if err != nil || io.EOF == err {
global.Log.Error("%v", err)
close(this.ch)
return
}
if bHead {
headers = readHeader(ls, filesplite)
bHead = false
continue
}
totalLine++
if len(ls) == 0 {
continue
}
global.Log.Debug("%v", ls)
l := dealLines(headers, ls, filesplite)
if len(l) != 0 {
fmt.Printf("$$:%#v", l)
this.ch <- l
} else {
errLine++
}
time.Sleep(time.Millisecond)
}
}
func (this *TableFile) write() {
defer func() {
this.wg.Done()
if err := recover(); err != nil {
global.Log.Critical("写数据异常:%v", err)
}
global.Log.Info("数据写完,退出")
}()
for {
select {
case data, isClose := <-this.ch:
if !isClose {
return
}
if err := send2ES(data); err != nil {
global.Log.Error("%v", err)
}
}
time.Sleep(time.Millisecond)
}
}
func readHeader(head, splite string) []string {
var heads []string
for k, head := range strings.Split(head, splite) {
global.Log.Debug("%v--%s", k, head)
heads = append(heads, head)
}
if len(heads) == 0 {
panic("获取表头失败")
}
return heads
}
func dealLines(headers []string, line, splite string) map[string]interface{} {
values := strings.Split(line, splite)
if len(headers) != len(values) {
global.Log.Error(fmt.Sprintf("表头长度%v和值长度%v不一致,headers:%v, line:%v", len(headers), len(values), headers, line))
return nil
}
res := make(map[string]interface{})
for i := 0; i < len(headers); i++ {
res[headers[i]] = values[i]
}
return res
}
func send2ES(data interface{}) error {
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req)
req.Header.SetContentType("application/json")
req.Header.SetMethod(http.MethodPost)
req.Header.SetHost(fmt.Sprintf("%s:9200", host))
req.SetRequestURI(fmt.Sprintf("/%s/%s/%s", template, typ, GenetateUUID()))
val, _ := jsoniter.Marshal(data)
global.Log.Debug("数据:%s", string(val))
global.Log.Debug("url:%s", req.URI().String())
req.SetBody(val)
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
global.Log.Debug("请求包:%v", req.String())
if err := fasthttp.DoTimeout(req, resp, time.Millisecond*100); err != nil && resp.StatusCode() != http.StatusOK {
return errors.New(fmt.Sprintf("数据发送失败,超时时间:%v ms, 错误:%v", time.Millisecond*100, err))
}
global.Log.Error("===:%v", resp)
res := &AutoGenerated{}
if err := jsoniter.Unmarshal(resp.Body(), res); err != nil {
return errors.New(fmt.Sprintf("数据发送回复包:%v, 反序列化失败,错误:%v", resp.Body(), err))
}
return nil
}
type AutoGenerated struct {
Index string `json:"_index"`
Type string `json:"_type"`
ID string `json:"_id"`
Version int `json:"_version"`
Result string `json:"result"`
Shards struct {
Total int `json:"total"`
Successful int `json:"successful"`
Failed int `json:"failed"`
} `json:"_shards"`
SeqNo int `json:"_seq_no"`
PrimaryTerm int `json:"_primary_term"`
}
func GenetateUUID() string {
u1, _ := uuid.NewV4()
return u1.String()
}