This repository has been archived by the owner on Feb 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathingester.go
138 lines (118 loc) · 2.52 KB
/
ingester.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
package main
import (
"database/sql"
"flag"
"log"
"os"
"path/filepath"
"strings"
"sync"
"github.com/ilyaglow/zp"
_ "github.com/kshvakov/clickhouse"
)
const (
insertStatement = `INSERT INTO dnszones (rtype, domain, value, tld) VALUES (?, ?, ?, ?)`
createStatement = `
CREATE TABLE IF NOT EXISTS dnszones (
rtype String,
domain String,
value String,
tld String,
date Date DEFAULT today()
) engine=MergeTree(date,(value,rtype),8192)
`
zoneExtension = "gz"
exceptionZoneFileName = "com.zone.gz"
exceptionZone = "com"
tSize = 10000
)
func main() {
sd := flag.String("f", ".", "Directory with zone files with .gz extension")
ch := flag.String("c", "http://127.0.0.1:8123/default", "Clickhouse URL")
nw := flag.Int("workers", 4, "Number of sending workers")
flag.Parse()
conn, err := sql.Open("clickhouse", *ch)
if err != nil {
log.Fatal(err)
}
if err := conn.Ping(); err != nil {
log.Fatal(err)
}
if _, err = conn.Exec(createStatement); err != nil {
log.Fatal(err)
}
rc := make(chan zp.Record)
var wg sync.WaitGroup
wg.Add(*nw)
for i := 0; i < *nw; i++ {
go func() {
defer wg.Done()
if err := send(conn, rc); err != nil {
log.Println(err)
}
}()
}
filepath.Walk(*sd, func(path string, fi os.FileInfo, err error) error {
if !strings.HasSuffix(path, zoneExtension) {
return nil
}
if strings.HasSuffix(path, exceptionZoneFileName) {
if err := zp.FetchZoneFile(path, exceptionZone, rc); err != nil {
log.Fatal(err)
}
} else {
if err := zp.FetchZoneFile(path, "", rc); err != nil {
log.Fatal(err)
}
}
return nil
})
close(rc)
wg.Wait()
}
func send(conn *sql.DB, input <-chan zp.Record) error {
var it uint
tx, err := conn.Begin()
if err != nil {
return err
}
stmt, err := tx.Prepare(insertStatement)
if err != nil {
return err
}
for rec := range input {
if _, err := stmt.Exec(
rec.RType,
rec.Domain,
rec.Value,
rec.TLD); err != nil {
return err
}
it++
if it == tSize {
log.Printf("Commit transaction with %d entries", tSize)
it = 0
if err := tx.Commit(); err != nil {
if strings.Contains(err.Error(), "Transaction") {
log.Println(err)
} else {
log.Println("tx.Commit() failed")
return err
}
}
tx, err = conn.Begin()
if err != nil {
return err
}
stmt, err = tx.Prepare(insertStatement)
if err != nil {
return err
}
}
}
log.Println("Committing the tail")
if err := tx.Commit(); err != nil {
return err
}
return nil
}