Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
zizdlp committed Aug 19, 2024
1 parent c1c72a5 commit 60926c5
Show file tree
Hide file tree
Showing 8 changed files with 169 additions and 97 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
zbook_data
__snapshots__
.swc
geoip_data.sql.gz
geoip_data.sql.gz
*.mmdb
8 changes: 8 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,14 @@ migratedown:
convert_db:
cd zbook_database && \
python convert.py
mmdb2psql:
cd zbook_backend && \
go run cmd/mmdb2psql/main.go ${CURRENT_DIR}/GeoLite2-City.mmdb
download_data:
pg_dump -U root -d zbook -t geoip --data-only > geoip_data.sql # in database docker container
gzip geoip_data.sql # in database docker container
docker cp zbook-local-database:/geoip_data.sql.gz .
psql -U root -d zbook -f geoip_data.sql
import_data:
docker cp geoip_data.sql.gz $(POD_NAME):/tmp/
docker exec -it $(POD_NAME) sh -c "gunzip /tmp/geoip_data.sql.gz"
Expand Down
152 changes: 152 additions & 0 deletions zbook_backend/cmd/mmdb2psql/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
package main

import (
"context"
"os"
"sync"
"time"

"github.com/jackc/pgx/v5/pgxpool"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"

"github.com/oschwald/maxminddb-golang"
)

type GeoData struct {
IPRangeCIDR string
CityNameEn *string
CityNameZhCn *string
Latitude *float64
Longitude *float64
}

type CityNames struct {
En *string `maxminddb:"en"`
ZhCN *string `maxminddb:"zh-CN"`
}

type Location struct {
Latitude *float64 `maxminddb:"latitude"`
Longitude *float64 `maxminddb:"longitude"`
}

type GeoRecord struct {
City struct {
Names CityNames `maxminddb:"names"`
} `maxminddb:"city"`
Location Location `maxminddb:"location"`
}

func processBatch(batchData []GeoData, db *pgxpool.Pool, wg *sync.WaitGroup) {
defer wg.Done()

ctx := context.Background()
tx, err := db.Begin(ctx)
if err != nil {
log.Error().Err(err).Msg("Failed to begin transaction")
return
}
defer tx.Rollback(ctx)

stmt := `
INSERT INTO geoip (ip_range_cidr, city_name_en, city_name_zh_cn, latitude, longitude)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (ip_range_cidr) DO NOTHING;
`

for _, data := range batchData {
_, err := tx.Exec(ctx, stmt, data.IPRangeCIDR, data.CityNameEn, data.CityNameZhCn, data.Latitude, data.Longitude)
if err != nil {
log.Error().Err(err).Msg("Failed to execute statement")
}
}

if err := tx.Commit(ctx); err != nil {
log.Error().Err(err).Msg("Failed to commit transaction")
return
}
}

func main() {
// Set up logging to output to standard error with console formatting
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})

if len(os.Args) != 2 {
log.Error().Msg("Please provide the mmdb file path")
return
}
dbPath := os.Args[1]

// Record start time
startTime := time.Now()

connStr := "user=root password=secret dbname=zbook host=localhost sslmode=disable"
config, err := pgxpool.ParseConfig(connStr)
if err != nil {
log.Error().Err(err).Msg("Failed to parse database connection string")
return
}

db, err := pgxpool.NewWithConfig(context.Background(), config)
if err != nil {
log.Error().Err(err).Msg("Failed to connect to database")
return
}
defer db.Close()

reader, err := maxminddb.Open(dbPath)
if err != nil {
log.Error().Err(err).Msg("Failed to open MMDB file:")
return
}
defer reader.Close()

batchSize := 1000
var batchData []GeoData
var wg sync.WaitGroup

networkIter := reader.Networks()
for networkIter.Next() {
var geoRecord GeoRecord
network, err := networkIter.Network(&geoRecord)
if err != nil {
log.Error().Err(err).Msgf("Error processing network: %v", err)
continue
}

ipRange := network.String()

cityNameEn := geoRecord.City.Names.En
cityNameZhCn := geoRecord.City.Names.ZhCN
latitude := geoRecord.Location.Latitude
longitude := geoRecord.Location.Longitude

batchData = append(batchData, GeoData{
IPRangeCIDR: ipRange,
CityNameEn: cityNameEn,
CityNameZhCn: cityNameZhCn,
Latitude: latitude,
Longitude: longitude,
})

if len(batchData) >= batchSize {
wg.Add(1)
go processBatch(batchData, db, &wg)
batchData = nil
}
}

if len(batchData) > 0 {
wg.Add(1)
go processBatch(batchData, db, &wg)
}

wg.Wait()

// Record end time and calculate duration
endTime := time.Now()
duration := endTime.Sub(startTime)

log.Info().Msgf("Data processing complete. Total time taken: %s", duration)
}
3 changes: 2 additions & 1 deletion zbook_backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ require (
github.com/magiconair/properties v1.8.7 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/o1egl/paseto v1.0.0
github.com/oschwald/maxminddb-golang v1.13.1
github.com/pelletier/go-toml/v2 v2.2.0 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/spf13/afero v1.11.0 // indirect
Expand All @@ -85,7 +86,7 @@ require (
github.com/subosito/gotenv v1.6.0 // indirect
github.com/yuin/goldmark v1.7.0
golang.org/x/image v0.18.0
golang.org/x/sys v0.20.0 // indirect
golang.org/x/sys v0.21.0 // indirect
golang.org/x/text v0.16.0 // indirect
google.golang.org/protobuf v1.33.0
gopkg.in/ini.v1 v1.67.0 // indirect
Expand Down
4 changes: 4 additions & 0 deletions zbook_backend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,8 @@ github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/opencontainers/image-spec v1.0.2 h1:9yCKha/T5XdGtO0q9Q9a6T5NUCsTn/DrBg0D7ufOcFM=
github.com/opencontainers/image-spec v1.0.2/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0=
github.com/oschwald/maxminddb-golang v1.13.1 h1:G3wwjdN9JmIK2o/ermkHM+98oX5fS+k5MbwsmL4MRQE=
github.com/oschwald/maxminddb-golang v1.13.1/go.mod h1:K4pgV9N/GcK694KSTmVSDTODk4IsCNThNdTmnaBZ/F8=
github.com/pelletier/go-toml/v2 v2.2.0 h1:QLgLl2yMN7N+ruc31VynXs1vhMZa7CeHHejIeBAsoHo=
github.com/pelletier/go-toml/v2 v2.2.0/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
Expand Down Expand Up @@ -240,6 +242,8 @@ golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws=
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
Expand Down
2 changes: 1 addition & 1 deletion zbook_backend/statik/statik.go

Large diffs are not rendered by default.

89 changes: 0 additions & 89 deletions zbook_database/convert.py

This file was deleted.

5 changes: 0 additions & 5 deletions zbook_database/convert.sh

This file was deleted.

0 comments on commit 60926c5

Please sign in to comment.