-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
179 lines (146 loc) · 3.96 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
package main
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"sync"
"time"
"cloud.google.com/go/storage"
"github.com/confluentinc/confluent-kafka-go/v2/kafka"
"google.golang.org/api/option"
)
type Log struct {
LogId string `json:"logId"`
Timestamp time.Time `json:"timestamp"`
Message string `json:"message"`
}
type ConsumedLog struct {
Log Log
TopicPartition kafka.TopicPartition
}
type Batch map[string]ConsumedLog
type App struct {
kafkaConsumer *kafka.Consumer
sqlConnection *sql.DB
storageClient *storage.Client
storageBucket string
}
func main() {
fmt.Println("Initializing")
time.Sleep(10 * time.Second)
kafkaConsumer := createKafkaConsumer()
sqlConnection := createSqlConnection()
storageClient := createStorageClient()
storageBucket := getEnvOrDefault("STORAGE_BUCKET", "logs")
app := &App{
kafkaConsumer,
sqlConnection,
storageClient,
storageBucket,
}
var wg sync.WaitGroup
wg.Add(1)
chanBatches := make(chan Batch)
go readMessages(app, chanBatches)
go processBatches(app, chanBatches)
wg.Wait()
}
func getEnvOrDefault(varName string, defaultVar string) string {
value, exists := os.LookupEnv(varName)
if !exists {
return defaultVar
}
return value
}
func createSqlConnection() *sql.DB {
user := getEnvOrDefault("DB_USER", "my_user")
password := getEnvOrDefault("DB_PASSWORD", "password123")
dbName := getEnvOrDefault("DB_NAME", "proto_parser_db")
host := getEnvOrDefault("DB_HOST", "localhost")
port := getEnvOrDefault("DB_PORT", "5432")
connectionString := fmt.Sprintf(
"postgres://%s:%s@%s:%s/%s?sslmode=disable",
user,
password,
host,
port,
dbName,
)
// create connection
db, err := sql.Open("postgres", connectionString)
if err != nil {
log.Fatalf("Error opening database connection: %v", err)
return nil
}
// check if the connection is successful
err = db.Ping()
if err != nil {
log.Fatalf("Error connecting to database: %v", err)
return nil
}
// add processed logs table
createTableQuery := `
CREATE TABLE IF NOT EXISTS processed_logs (log_id UUID);
CREATE INDEX IF NOT EXISTS processed_logs_log_id_idx ON processed_logs USING HASH (log_id);
`
_, err = db.Exec(createTableQuery)
if err != nil {
log.Fatalf("Error creating processed_logs table: %v", err)
return nil
}
return db
}
func createKafkaConsumer() *kafka.Consumer {
host := getEnvOrDefault("KAFKA_HOST", "localhost:9094")
consumerGroup := getEnvOrDefault("KAFKA_CONSUMER_GROUP", "group-1")
// create topic
adminConfig := &kafka.ConfigMap{
"bootstrap.servers": host,
}
admin, err := kafka.NewAdminClient(adminConfig)
if err != nil {
log.Fatalf("Failed to create admin client: %v\n", err)
}
defer admin.Close()
topicConfig := kafka.TopicSpecification{
Topic: "logs",
NumPartitions: 1,
ReplicationFactor: 1,
Config: map[string]string{},
}
_, err = admin.CreateTopics(context.Background(), []kafka.TopicSpecification{topicConfig})
if err != nil {
// check if the error indicates that the topic already exists
log.Fatalf("Failed to create topic: %s\n", err)
}
// create consumer
consumerConfig := &kafka.ConfigMap{
"bootstrap.servers": host,
"group.id": consumerGroup,
"auto.offset.reset": "earliest",
"enable.auto.commit": false,
}
consumer, err := kafka.NewConsumer(consumerConfig)
if err != nil {
log.Fatalf("Failed to create consumer: %v\n", err)
}
err = consumer.SubscribeTopics([]string{"logs"}, nil)
if err != nil {
log.Fatalf("Failed to create consumer: %v\n", err)
}
return consumer
}
func createStorageClient() *storage.Client {
endpoint := getEnvOrDefault("GCS_ENDPOINT", "http://localhost:4443/storage/v1/")
// make sure storage emulator host is set
// it is required by storage mock
os.Setenv("STORAGE_EMULATOR_HOST", endpoint)
client, err := storage.NewClient(context.Background(), option.WithEndpoint(endpoint))
if err != nil {
log.Fatalf("Error connecting to google storage: %v", err)
return nil
}
return client
}