-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathmain.go
433 lines (390 loc) · 10.3 KB
/
main.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// Copyright 2022 The Ip2Region Authors. All rights reserved.
// Use of this source code is governed by a Apache2.0-style
// license that can be found in the LICENSE file.
package main
import (
"bufio"
"fmt"
"github.com/lionsoul2014/ip2region/maker/golang/xdb"
"log"
"os"
"regexp"
"strings"
"time"
)
func printHelp() {
fmt.Printf("ip2region xdb maker\n")
fmt.Printf("%s [command] [command options]\n", os.Args[0])
fmt.Printf("Command: \n")
fmt.Printf(" gen generate the binary db file\n")
fmt.Printf(" search binary xdb search test\n")
fmt.Printf(" bench binary xdb bench test\n")
fmt.Printf(" edit edit the source ip data\n")
}
// Iterate the cli flags
func iterateFlags(cb func(key string, val string) error) error {
for i := 2; i < len(os.Args); i++ {
r := os.Args[i]
if len(r) < 5 {
continue
}
if strings.Index(r, "--") != 0 {
continue
}
var sIdx = strings.Index(r, "=")
if sIdx < 0 {
return fmt.Errorf("missing = for args pair '%s'", r)
}
if err := cb(r[2:sIdx], r[sIdx+1:]); err != nil {
return err
}
}
return nil
}
func genDb() {
var err error
var srcFile, dstFile = "", ""
var indexPolicy = xdb.VectorIndexPolicy
var fErr = iterateFlags(func(key string, val string) error {
switch key {
case "src":
srcFile = val
case "dst":
dstFile = val
case "index":
indexPolicy, err = xdb.IndexPolicyFromString(val)
if err != nil {
return fmt.Errorf("parse policy: %w", err)
}
default:
return fmt.Errorf("undefine option `%s=%s`\n", key, val)
}
return nil
})
if fErr != nil {
fmt.Printf("failed to parse flags: %s", fErr)
return
}
if srcFile == "" || dstFile == "" {
fmt.Printf("%s gen [command options]\n", os.Args[0])
fmt.Printf("options:\n")
fmt.Printf(" --src string source ip text file path\n")
fmt.Printf(" --dst string destination binary xdb file path\n")
return
}
// make the binary file
tStart := time.Now()
maker, err := xdb.NewMaker(indexPolicy, srcFile, dstFile)
if err != nil {
fmt.Printf("failed to create %s\n", err)
return
}
err = maker.Init()
if err != nil {
fmt.Printf("failed Init: %s\n", err)
return
}
err = maker.Start()
if err != nil {
fmt.Printf("failed Start: %s\n", err)
return
}
err = maker.End()
if err != nil {
fmt.Printf("failed End: %s\n", err)
}
log.Printf("Done, elapsed: %s\n", time.Since(tStart))
}
func testSearch() {
var err error
var dbFile = ""
var fErr = iterateFlags(func(key string, val string) error {
if key == "db" {
dbFile = val
} else {
return fmt.Errorf("undefined option '%s=%s'\n", key, val)
}
return nil
})
if fErr != nil {
fmt.Printf("failed to parse flags: %s", fErr)
return
}
if dbFile == "" {
fmt.Printf("%s search [command options]\n", os.Args[0])
fmt.Printf("options:\n")
fmt.Printf(" --db string ip2region binary xdb file path\n")
return
}
searcher, err := xdb.NewSearcher(dbFile)
if err != nil {
fmt.Printf("failed to create searcher with `%s`: %s\n", dbFile, err.Error())
return
}
defer func() {
searcher.Close()
fmt.Printf("test program exited, thanks for trying\n")
}()
fmt.Println(`ip2region xdb search test program, commands:
loadIndex : load the vector index for search speedup.
clearIndex: clear the vector index.
quit : exit the test program`)
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("ip2region>> ")
str, err := reader.ReadString('\n')
if err != nil {
log.Fatalf("failed to read string: %s", err)
}
line := strings.TrimSpace(strings.TrimSuffix(str, "\n"))
if len(line) == 0 {
continue
}
// command interception and execution
if line == "loadIndex" {
err = searcher.LoadVectorIndex()
if err != nil {
log.Fatalf("failed to load vector index: %s", err)
}
fmt.Printf("vector index cached\n")
continue
} else if line == "clearIndex" {
searcher.ClearVectorIndex()
fmt.Printf("vector index cleared\n")
continue
} else if line == "quit" {
break
}
ip, err := xdb.CheckIP(line)
if err != nil {
fmt.Printf("invalid ip address `%s`\n", line)
continue
}
tStart := time.Now()
region, ioCount, err := searcher.Search(ip)
if err != nil {
fmt.Printf("\x1b[0;31m{err:%s, iocount:%d}\x1b[0m\n", err.Error(), ioCount)
} else {
fmt.Printf("\x1b[0;32m{region:%s, iocount:%d, took:%s}\x1b[0m\n", region, ioCount, time.Since(tStart))
}
}
}
func testBench() {
var err error
var dbFile, srcFile = "", ""
var ignoreError = false
var fErr = iterateFlags(func(key string, val string) error {
switch key {
case "db":
dbFile = val
case "src":
srcFile = val
case "ignore-error":
if val == "true" || val == "1" {
ignoreError = true
} else if val == "false" || val == "0" {
ignoreError = false
} else {
return fmt.Errorf("invalid value for ignore-error option, could be false/0 or true/1\n")
}
default:
return fmt.Errorf("undefined option '%s=%s'\n", key, val)
}
return nil
})
if fErr != nil {
fmt.Printf("failed to parse flags: %s", fErr)
return
}
if dbFile == "" || srcFile == "" {
fmt.Printf("%s bench [command options]\n", os.Args[0])
fmt.Printf("options:\n")
fmt.Printf(" --db string ip2region binary xdb file path\n")
fmt.Printf(" --src string source ip text file path\n")
fmt.Printf(" --ignore-error bool keep going if bench failed\n")
return
}
searcher, err := xdb.NewSearcher(dbFile)
if err != nil {
fmt.Printf("failed to create searcher with `%s`: %s\n", dbFile, err)
return
}
defer func() {
searcher.Close()
}()
handle, err := os.OpenFile(srcFile, os.O_RDONLY, 0600)
if err != nil {
fmt.Printf("failed to open source text file: %s\n", err)
return
}
var count, errCount, tStart = 0, 0, time.Now()
var iErr = xdb.IterateSegments(handle, nil, func(seg *xdb.Segment) error {
var l = fmt.Sprintf("%d|%d|%s", seg.StartIP, seg.EndIP, seg.Region)
fmt.Printf("try to bench segment: `%s`\n", l)
mip := xdb.MidIP(seg.StartIP, seg.EndIP)
for _, ip := range []uint32{seg.StartIP, xdb.MidIP(seg.EndIP, mip), mip, xdb.MidIP(mip, seg.EndIP), seg.EndIP} {
fmt.Printf("|-try to bench ip '%s' ... ", xdb.Long2IP(ip))
r, _, err := searcher.Search(ip)
if err != nil {
return fmt.Errorf("failed to search ip '%s': %s\n", xdb.Long2IP(ip), err)
}
// check the region info
count++
if r != seg.Region {
errCount++
fmt.Printf(" --[Failed] (%s != %s)\n", r, seg.Region)
if ignoreError == false {
return fmt.Errorf("")
}
} else {
fmt.Printf(" --[Ok]\n")
}
}
return nil
})
if iErr != nil {
fmt.Printf("%s", err)
return
}
fmt.Printf("Bench finished, {count: %d, failed: %d, took: %s}\n", count, errCount, time.Since(tStart))
}
func edit() {
var err error
var srcFile = ""
var fErr = iterateFlags(func(key string, val string) error {
switch key {
case "src":
srcFile = val
default:
return fmt.Errorf("undefined option '%s=%s'\n", key, val)
}
return nil
})
if fErr != nil {
fmt.Printf("failed to parse flags: %s", fErr)
return
}
if srcFile == "" {
fmt.Printf("%s edit [command options]\n", os.Args[0])
fmt.Printf("options:\n")
fmt.Printf(" --src string source ip text file path\n")
return
}
rExp, err := regexp.Compile("\\s+")
if err != nil {
fmt.Printf("failed to compile regexp: %s\n", err)
return
}
fmt.Printf("init the editor from source @ `%s` ... \n", srcFile)
var tStart = time.Now()
editor, err := xdb.NewEditor(srcFile)
if err != nil {
fmt.Printf("failed to init editor: %s", err)
return
}
fmt.Printf("all segments loaded, length: %d, elapsed: %s\n", editor.SegLen(), time.Since(tStart))
var help = func() {
fmt.Printf("command list: \n")
fmt.Printf(" put [segment] : put the specifield $segment\n")
fmt.Printf(" put_file [file] : put all the segments from the specified $file\n")
fmt.Printf(" list [offset] [size] : list the first $size segments start from $offset\n")
fmt.Printf(" save : save all the changes to the destination source file\n")
fmt.Printf(" quit : exit the program\n")
fmt.Printf(" help : print this help menu\n")
}
help()
var sTip = ""
var reader = bufio.NewReader(os.Stdin)
for {
if editor.NeedSave() {
sTip = "*"
} else {
sTip = ""
}
fmt.Printf("%seditor>> ", sTip)
line, err := reader.ReadString('\n')
if err != nil {
fmt.Printf("failed to read line from cli: %s\n", err)
break
}
cmd := strings.TrimSpace(line)
if cmd == "help" {
help()
} else if cmd == "quit" {
if editor.NeedSave() {
fmt.Printf("there are changes that need to save, type 'quit!' to force quit\n")
} else {
break
}
} else if cmd == "quit!" {
// quit directly
break
} else if cmd == "save" {
err = editor.Save()
if err != nil {
fmt.Printf("failed to save the changes: %s\n", err)
continue
}
fmt.Printf("all segments saved to %s\n", srcFile)
} else if strings.HasPrefix(cmd, "list") {
var sErr error
off, size, l := 0, 10, len("list")
str := strings.TrimSpace(cmd)
if len(str) > l {
sets := rExp.Split(cmd, 3)
switch len(sets) {
case 2:
_, sErr = fmt.Sscanf(cmd, "%s %d", &str, &off)
case 3:
_, sErr = fmt.Sscanf(cmd, "%s %d %d", &str, &off, &size)
}
}
if sErr != nil {
fmt.Printf("failed to parse the offset and size: %s\n", sErr)
continue
}
fmt.Printf("+-slice(%d,%d): \n", off, size)
for _, s := range editor.Slice(off, size) {
fmt.Printf("%s\n", s)
}
} else if strings.HasPrefix(cmd, "put ") {
seg := strings.TrimSpace(cmd[len("put "):])
o, n, err := editor.Put(seg)
if err != nil {
fmt.Printf("failed to Put(%s): %s\n", seg, err)
continue
}
fmt.Printf("Put(%s): Ok, with %d deletes and %d additions\n", seg, o, n)
} else if strings.HasPrefix(cmd, "put_file ") {
file := strings.TrimSpace(cmd[len("put_file "):])
o, n, err := editor.PutFile(file)
if err != nil {
fmt.Printf("failed to PutFile(%s): %s\n", file, err)
continue
}
fmt.Printf("PutFile(%s): Ok, with %d deletes and %d additions\n", file, o, n)
} else if len(cmd) > 0 {
help()
}
}
}
func main() {
if len(os.Args) < 2 {
printHelp()
return
}
// set the log flag
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
switch strings.ToLower(os.Args[1]) {
case "gen":
genDb()
case "search":
testSearch()
case "bench":
testBench()
case "edit":
edit()
default:
printHelp()
}
}