Skip to content

Commit b26daf6

Browse files
authored
Merge pull request #268 from intelops/migrate-with-env
modified migration with ttl with ttl interval as configurable
2 parents a24e7d7 + c479f42 commit b26daf6

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+155
-76
lines changed

cmd/cli/commands/sql.go

Lines changed: 6 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@ import (
55
"log"
66
"os"
77

8-
"github.com/golang-migrate/migrate/v4"
9-
cm "github.com/golang-migrate/migrate/v4/database/clickhouse"
108
_ "github.com/golang-migrate/migrate/v4/source/file"
119
"github.com/intelops/kubviz/cmd/cli/config"
1210
"github.com/spf13/cobra"
@@ -47,28 +45,15 @@ migration sql -e --no`,
4745

4846
if executeFlag {
4947
if yesFlag {
50-
db, cfg, err := config.OpenClickHouseConn()
48+
cfg, err := config.New()
5149
if err != nil {
52-
log.Fatalf("Failed to open ClickHouse connection: %v", err)
50+
log.Fatalf("failed to parse the env : %v", err.Error())
51+
return
5352
}
54-
defer db.Close()
55-
driver, err := cm.WithInstance(db, &cm.Config{})
56-
if err != nil {
57-
log.Fatalf("Failed to create migrate driver: %v", err)
58-
}
59-
60-
m, err := migrate.NewWithDatabaseInstance(
61-
fmt.Sprintf("file://%s", cfg.SchemaPath),
62-
"clickhouse",
63-
driver,
64-
)
65-
if err != nil {
66-
log.Fatalf("Clickhouse Migration initialization failed: %v", err)
67-
}
68-
if err := m.Up(); err != nil && err != migrate.ErrNoChange {
69-
log.Fatalf("Migration failed: %v", err)
53+
if err := cfg.Migrate(); err != nil {
54+
log.Fatalf("failed to migrate : %v", err.Error())
55+
return
7056
}
71-
fmt.Println("Clickhouse Migrations applied successfully!")
7257
} else {
7358
fmt.Println("Clickhouse Migration skipped due to --no flag.")
7459
}

cmd/cli/config/config.go

Lines changed: 5 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
11
package config
22

33
import (
4-
"database/sql"
5-
"fmt"
6-
7-
"github.com/ClickHouse/clickhouse-go/v2"
84
"github.com/kelseyhightower/envconfig"
95
)
106

@@ -14,40 +10,15 @@ type Config struct {
1410
ClickHouseUsername string `envconfig:"CLICKHOUSE_USERNAME"`
1511
ClickHousePassword string `envconfig:"CLICKHOUSE_PASSWORD"`
1612
SchemaPath string `envconfig:"SCHEMA_PATH" default:"/sql"`
13+
TtlInterval string `envconfig:"TTL_INTERVAL" default:"1"`
14+
TtlUnit string `envconfig:"TTL_UNIT" default:"MONTH"`
1715
}
1816

19-
func OpenClickHouseConn() (*sql.DB, *Config, error) {
17+
func New() (*Config, error) {
2018
var cfg Config
2119
err := envconfig.Process("", &cfg)
2220
if err != nil {
23-
return nil, nil, err
24-
}
25-
var options clickhouse.Options
26-
27-
if cfg.ClickHouseUsername != "" && cfg.ClickHousePassword != "" {
28-
fmt.Println("Using provided username and password")
29-
options = clickhouse.Options{
30-
Addr: []string{fmt.Sprintf("%s:%d", cfg.DBAddress, cfg.DbPort)},
31-
Debug: true,
32-
Auth: clickhouse.Auth{
33-
Username: cfg.ClickHouseUsername,
34-
Password: cfg.ClickHousePassword,
35-
},
36-
}
37-
} else {
38-
fmt.Println("Using connection without username and password")
39-
options = clickhouse.Options{
40-
Addr: []string{fmt.Sprintf("%s:%d", cfg.DBAddress, cfg.DbPort)},
41-
}
42-
}
43-
44-
conn := clickhouse.OpenDB(&options)
45-
if err := conn.Ping(); err != nil {
46-
if exception, ok := err.(*clickhouse.Exception); ok {
47-
return nil, nil, fmt.Errorf("[%d] %s %s", exception.Code, exception.Message, exception.StackTrace)
48-
} else {
49-
return nil, nil, err
50-
}
21+
return nil, err
5122
}
52-
return conn, &cfg, nil
23+
return &cfg, nil
5324
}

cmd/cli/config/utils.go

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
package config
2+
3+
import (
4+
"bytes"
5+
"database/sql"
6+
"fmt"
7+
"html/template"
8+
"io"
9+
"os"
10+
"path/filepath"
11+
"strings"
12+
13+
"github.com/ClickHouse/clickhouse-go/v2"
14+
"github.com/golang-migrate/migrate/v4"
15+
ch "github.com/golang-migrate/migrate/v4/database/clickhouse"
16+
_ "github.com/golang-migrate/migrate/v4/source/file"
17+
)
18+
19+
func (cfg *Config) openClickHouseConn() (*sql.DB, error) {
20+
21+
var options clickhouse.Options
22+
if cfg.ClickHouseUsername != "" && cfg.ClickHousePassword != "" {
23+
fmt.Println("Using provided username and password")
24+
options = clickhouse.Options{
25+
Addr: []string{fmt.Sprintf("%s:%d", cfg.DBAddress, cfg.DbPort)},
26+
Debug: true,
27+
Auth: clickhouse.Auth{
28+
Username: cfg.ClickHouseUsername,
29+
Password: cfg.ClickHousePassword,
30+
},
31+
}
32+
33+
} else {
34+
fmt.Println("Using connection without username and password")
35+
options = clickhouse.Options{
36+
Addr: []string{fmt.Sprintf("%s:%d", cfg.DBAddress, cfg.DbPort)},
37+
}
38+
}
39+
40+
conn := clickhouse.OpenDB(&options)
41+
if err := conn.Ping(); err != nil {
42+
if exception, ok := err.(*clickhouse.Exception); ok {
43+
return nil, fmt.Errorf("[%d] %s %s", exception.Code, exception.Message, exception.StackTrace)
44+
} else {
45+
return nil, err
46+
}
47+
}
48+
return conn, nil
49+
}
50+
51+
func (cfg *Config) processSQLTemplate(filePath string) (string, error) {
52+
53+
file, err := os.Open(filePath)
54+
if err != nil {
55+
return "", err
56+
}
57+
data, err := io.ReadAll(file)
58+
if err != nil {
59+
return "", err
60+
}
61+
tmpl, err := template.New("sql").Parse(string(data))
62+
if err != nil {
63+
return "", err
64+
}
65+
66+
params := map[string]string{
67+
"TTLValue": cfg.TtlInterval,
68+
"TTLUnit": cfg.TtlUnit,
69+
}
70+
71+
var buf bytes.Buffer
72+
err = tmpl.Execute(&buf, params)
73+
if err != nil {
74+
return "", err
75+
}
76+
return buf.String(), nil
77+
}
78+
79+
func (cfg *Config) Migrate() error {
80+
dir := cfg.SchemaPath
81+
files, err := os.ReadDir(dir)
82+
if err != nil {
83+
return fmt.Errorf("failed to read directory %w", err)
84+
}
85+
86+
for _, file := range files {
87+
if strings.HasSuffix(file.Name(), ".up.sql") {
88+
fullPath := filepath.Join(dir, file.Name())
89+
processedSQL, err := cfg.processSQLTemplate(fullPath)
90+
if err != nil {
91+
return fmt.Errorf("failed to process the sql template for file %s : %w", file.Name(), err)
92+
}
93+
94+
err = os.WriteFile(fullPath, []byte(processedSQL), 0644)
95+
if err != nil {
96+
return fmt.Errorf("failed to write to file %s : %w", fullPath, err)
97+
}
98+
}
99+
}
100+
101+
conn, err := cfg.openClickHouseConn()
102+
if err != nil {
103+
return fmt.Errorf("unable to create a clickhouse conection %w", err)
104+
}
105+
106+
driver, err := ch.WithInstance(conn, &ch.Config{})
107+
if err != nil {
108+
return fmt.Errorf("failed to create migrate driver %w", err)
109+
}
110+
m, err := migrate.NewWithDatabaseInstance(
111+
fmt.Sprintf("file://%s", dir),
112+
"clickhouse",
113+
driver,
114+
)
115+
if err != nil {
116+
return fmt.Errorf("clickhouse migration initialization failed %w", err)
117+
}
118+
if err := m.Up(); err != nil && err != migrate.ErrNoChange {
119+
return fmt.Errorf("migration failed %w", err)
120+
}
121+
fmt.Println("Clickhouse Migration applied successfully!")
122+
return nil
123+
}

dockerfiles/migration/Dockerfile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ WORKDIR /
1616
COPY --from=builder /workspace/migration .
1717
COPY --from=builder /workspace/sql /sql
1818
COPY --from=builder /workspace/script /script
19-
19+
RUN chmod -R 777 /sql
2020
USER 65532:65532
2121

2222
ENTRYPOINT ["/migration"]
File renamed without changes.

sql/20230915101844_trivy_misconfig.up.sql renamed to sql/0000010_trivy_misconfig.up.sql

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ CREATE TABLE IF NOT EXISTS trivy_misconfig (
1515
misconfig_severity String,
1616
misconfig_status String,
1717
EventTime DateTime('UTC'),
18-
ExpiryDate DateTime DEFAULT now() + INTERVAL 6 MONTH
18+
ExpiryDate DateTime DEFAULT now() + INTERVAL {{.TTLValue}} {{.TTLUnit}}
1919
) ENGINE = MergeTree()
2020
ORDER BY ExpiryDate
2121
TTL ExpiryDate;
File renamed without changes.

sql/20230915101910_trivyimage.up.sql renamed to sql/0000011_trivyimage.up.sql

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ CREATE TABLE IF NOT EXISTS trivyimage (
1111
vul_severity String,
1212
vul_published_date DateTime('UTC'),
1313
vul_last_modified_date DateTime('UTC'),
14-
ExpiryDate DateTime DEFAULT now() + INTERVAL 6 MONTH
14+
ExpiryDate DateTime DEFAULT now() + INTERVAL {{.TTLValue}} {{.TTLUnit}}
1515
) ENGINE = MergeTree()
1616
ORDER BY ExpiryDate
1717
TTL ExpiryDate;
File renamed without changes.

sql/20230915102122_dockerhubbuild.up.sql renamed to sql/0000012_dockerhubbuild.up.sql

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ CREATE TABLE IF NOT EXISTS dockerhubbuild (
66
Owner String,
77
Event String,
88
EventTime DateTime('UTC'),
9-
ExpiryDate DateTime DEFAULT now() + INTERVAL 6 MONTH
9+
ExpiryDate DateTime DEFAULT now() + INTERVAL {{.TTLValue}} {{.TTLUnit}}
1010
) ENGINE = MergeTree()
1111
ORDER BY ExpiryDate
1212
TTL ExpiryDate;

0 commit comments

Comments
 (0)