Skip to content

Commit 7143bde

Browse files
authored
breaking-change(redis): change Redis Architecture (#36)
* feat(redis): change redis architecture and fix unimplemented parts * chore: change log * feat(cmd): add version command * feat(cmd): add batch size option * chore: change err message * chore: fix test * chore: check batch-size * feat(redis): update redis architecture * chore(integration): update test * chore: increase the sample_rate
1 parent e306c1f commit 7143bde

File tree

16 files changed

+355
-117
lines changed

16 files changed

+355
-117
lines changed

GNUmakefile

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ clean-integration:
8383
-pkill go-cpe.old
8484
-pkill go-cpe.new
8585
-rm integration/go-cpe.old integration/go-cpe.new integration/go-cpe.old.sqlite3 integration/go-cpe.new.sqlite3
86+
-rm -rf integration/diff
8687
-docker kill redis-old redis-new
8788
-docker rm redis-old redis-new
8889

@@ -102,21 +103,21 @@ fetch-redis:
102103
integration/go-cpe.new fetch jvn --dbtype redis --dbpath "redis://127.0.0.1:6380/0"
103104

104105
diff-server-rdb:
105-
integration/go-cpe.old server --dbpath=$(PWD)/integration/go-cpe.old.sqlite3 --port 1325 > /dev/null &
106-
integration/go-cpe.new server --dbpath=$(PWD)/integration/go-cpe.new.sqlite3 --port 1326 > /dev/null &
107-
@ python integration/diff_server_mode.py cpes --sample_rate 0.001
106+
integration/go-cpe.old server --dbpath=$(PWD)/integration/go-cpe.old.sqlite3 --port 1325 > /dev/null 2>&1 &
107+
integration/go-cpe.new server --dbpath=$(PWD)/integration/go-cpe.new.sqlite3 --port 1326 > /dev/null 2>&1 &
108+
@ python integration/diff_server_mode.py cpes --sample_rate 0.01
108109
pkill go-cpe.old
109110
pkill go-cpe.new
110111

111112
diff-server-redis:
112-
integration/go-cpe.old server --dbtype redis --dbpath "redis://127.0.0.1:6379/0" --port 1325 > /dev/null &
113-
integration/go-cpe.new server --dbtype redis --dbpath "redis://127.0.0.1:6380/0" --port 1326 > /dev/null &
114-
@ python integration/diff_server_mode.py cpes --sample_rate 0.001
113+
integration/go-cpe.old server --dbtype redis --dbpath "redis://127.0.0.1:6379/0" --port 1325 > /dev/null 2>&1 &
114+
integration/go-cpe.new server --dbtype redis --dbpath "redis://127.0.0.1:6380/0" --port 1326 > /dev/null 2>&1 &
115+
@ python integration/diff_server_mode.py cpes --sample_rate 0.01
115116
pkill go-cpe.old
116117
pkill go-cpe.new
117118

118119
diff-server-rdb-redis:
119-
integration/go-cpe.new server --dbpath=$(PWD)/integration/go-cpe.new.sqlite3 --port 1325 > /dev/null &
120-
integration/go-cpe.new server --dbtype redis --dbpath "redis://127.0.0.1:6380/0" --port 1326 > /dev/null &
121-
@ python integration/diff_server_mode.py cpes --sample_rate 0.001
120+
integration/go-cpe.new server --dbpath=$(PWD)/integration/go-cpe.new.sqlite3 --port 1325 > /dev/null 2>&1 &
121+
integration/go-cpe.new server --dbtype redis --dbpath "redis://127.0.0.1:6380/0" --port 1326 > /dev/null 2>&1 &
122+
@ python integration/diff_server_mode.py cpes --sample_rate 0.01
122123
pkill go-cpe.new

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ Global Flags:
105105
--http-proxy string http://proxy-url:port (default: empty)
106106
--log-dir string /path/to/log (default "/var/log/go-cpe-dictionary")
107107
--log-json output log as JSON
108+
--log-to-file output log to file
108109

109110
Use "go-cpe-dictionary fetch [command] --help" for more information about a command.
110111

@@ -128,6 +129,7 @@ Global Flags:
128129
--http-proxy string http://proxy-url:port (default: empty)
129130
--log-dir string /path/to/log (default "/var/log/go-cpe-dictionary")
130131
--log-json output log as JSON
132+
--log-to-file output log to file
131133
```
132134

133135
----

commands/fetch.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ func init() {
2626
fetchCmd.PersistentFlags().Int("threads", runtime.NumCPU(), "The number of threads to be used")
2727
_ = viper.BindPFlag("threads", fetchCmd.PersistentFlags().Lookup("threads"))
2828

29+
fetchCmd.PersistentFlags().Int("batch-size", 100, "The number of batch size to insert.")
30+
_ = viper.BindPFlag("batch-size", fetchCmd.PersistentFlags().Lookup("batch-size"))
31+
2932
fetchCmd.PersistentFlags().Uint("expire", 0, "timeout to set for Redis keys in seconds. If set to 0, the key is persistent.")
3033
_ = viper.BindPFlag("expire", fetchCmd.PersistentFlags().Lookup("expire"))
3134
}

commands/fetchjvn.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"github.com/vulsio/go-cpe-dictionary/db"
1010
"github.com/vulsio/go-cpe-dictionary/fetcher"
1111
"github.com/vulsio/go-cpe-dictionary/models"
12+
"github.com/vulsio/go-cpe-dictionary/util"
1213
"golang.org/x/xerrors"
1314
)
1415

@@ -24,6 +25,10 @@ func init() {
2425
}
2526

2627
func fetchJvn(cmd *cobra.Command, args []string) (err error) {
28+
if err := util.SetLogger(viper.GetBool("log-to-file"), viper.GetString("log-dir"), viper.GetBool("debug"), viper.GetBool("log-json")); err != nil {
29+
return xerrors.Errorf("Failed to SetLogger. err: %w", err)
30+
}
31+
2732
log15.Info("Initialize Database")
2833
driver, locked, err := db.NewDB(viper.GetString("dbtype"), viper.GetString("dbpath"), viper.GetBool("debug-sql"))
2934
if err != nil {

commands/fetchnvd.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"github.com/vulsio/go-cpe-dictionary/db"
1010
"github.com/vulsio/go-cpe-dictionary/fetcher"
1111
"github.com/vulsio/go-cpe-dictionary/models"
12+
"github.com/vulsio/go-cpe-dictionary/util"
1213
"golang.org/x/xerrors"
1314
)
1415

@@ -24,6 +25,10 @@ func init() {
2425
}
2526

2627
func fetchNvd(cmd *cobra.Command, args []string) (err error) {
28+
if err := util.SetLogger(viper.GetBool("log-to-file"), viper.GetString("log-dir"), viper.GetBool("debug"), viper.GetBool("log-json")); err != nil {
29+
return xerrors.Errorf("Failed to SetLogger. err: %w", err)
30+
}
31+
2732
log15.Info("Initialize Database")
2833
driver, locked, err := db.NewDB(viper.GetString("dbtype"), viper.GetString("dbpath"), viper.GetBool("debug-sql"))
2934
if err != nil {

commands/root.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ func init() {
2828

2929
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.go-cpe-dictionary.yaml)")
3030

31+
RootCmd.PersistentFlags().Bool("log-to-file", false, "output log to file")
32+
_ = viper.BindPFlag("log-to-file", RootCmd.PersistentFlags().Lookup("log-to-file"))
33+
3134
RootCmd.PersistentFlags().String("log-dir", util.GetDefaultLogDir(), "/path/to/log")
3235
_ = viper.BindPFlag("log-dir", RootCmd.PersistentFlags().Lookup("log-dir"))
3336

@@ -74,8 +77,4 @@ func initConfig() {
7477
if err := viper.ReadInConfig(); err == nil {
7578
fmt.Println("Using config file:", viper.ConfigFileUsed())
7679
}
77-
logDir := viper.GetString("log-dir")
78-
debug := viper.GetBool("debug")
79-
logJSON := viper.GetBool("log-json")
80-
util.SetLogger(logDir, debug, logJSON)
8180
}

commands/server.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import (
66
"github.com/spf13/viper"
77
"github.com/vulsio/go-cpe-dictionary/db"
88
"github.com/vulsio/go-cpe-dictionary/server"
9+
"github.com/vulsio/go-cpe-dictionary/util"
10+
"golang.org/x/xerrors"
911
)
1012

1113
var serverCmd = &cobra.Command{
@@ -26,7 +28,10 @@ func init() {
2628
}
2729

2830
func executeServer(cmd *cobra.Command, args []string) (err error) {
29-
logDir := viper.GetString("log-dir")
31+
if err := util.SetLogger(viper.GetBool("log-to-file"), viper.GetString("log-dir"), viper.GetBool("debug"), viper.GetBool("log-json")); err != nil {
32+
return xerrors.Errorf("Failed to SetLogger. err: %w", err)
33+
}
34+
3035
driver, locked, err := db.NewDB(viper.GetString("dbtype"), viper.GetString("dbpath"), viper.GetBool("debug-sql"))
3136
if err != nil {
3237
if locked {
@@ -36,7 +41,7 @@ func executeServer(cmd *cobra.Command, args []string) (err error) {
3641
}
3742

3843
log15.Info("Starting HTTP Server...")
39-
if err = server.Start(logDir, driver); err != nil {
44+
if err = server.Start(viper.GetBool("log-to-file"), viper.GetString("log-dir"), driver); err != nil {
4045
log15.Error("Failed to start server.", "err", err)
4146
return err
4247
}

commands/version.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package commands
2+
3+
import (
4+
"fmt"
5+
6+
"github.com/spf13/cobra"
7+
"github.com/vulsio/go-cpe-dictionary/config"
8+
)
9+
10+
func init() {
11+
RootCmd.AddCommand(versionCmd)
12+
}
13+
14+
var versionCmd = &cobra.Command{
15+
Use: "version",
16+
Short: "Show version",
17+
Long: `Show version`,
18+
Run: func(cmd *cobra.Command, args []string) {
19+
fmt.Printf("go-cpe-dictionary %s %s\n", config.Version, config.Revision)
20+
},
21+
}

db/common_test.go

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77

88
"github.com/knqyf263/go-cpe/common"
99
"github.com/knqyf263/go-cpe/naming"
10+
"github.com/spf13/viper"
1011
"github.com/vulsio/go-cpe-dictionary/models"
1112
)
1213

@@ -53,6 +54,7 @@ func prepareTestData(driver DB) error {
5354
})
5455
}
5556

57+
viper.Set("batch-size", 1)
5658
return driver.InsertCpes(models.NVD, testCpes)
5759
}
5860

@@ -74,15 +76,15 @@ func testGetVendorProducts(t *testing.T, driver DB) {
7476
"OK": {
7577
Expected: Expected{
7678
VendorProduct: []string{
77-
"ntp::ntp",
78-
"responsive_coming_soon_page_project::responsive_coming_soon_page",
79-
"vendorName1::productName1\\-1", // TODO: what's with these slashes? Is it a bug?
80-
"vendorName1::productName1\\-2", // TODO: what's with these slashes? Is it a bug?
81-
"vendorName2::productName2",
82-
"vendorName3::productName3",
83-
"vendorName4::productName4",
84-
"vendorName5::productName5",
85-
"vendorName6::productName6",
79+
"ntp#ntp",
80+
"responsive_coming_soon_page_project#responsive_coming_soon_page",
81+
"vendorName1#productName1\\-1", // TODO: what's with these slashes? Is it a bug?
82+
"vendorName1#productName1\\-2", // TODO: what's with these slashes? Is it a bug?
83+
"vendorName2#productName2",
84+
"vendorName3#productName3",
85+
"vendorName4#productName4",
86+
"vendorName5#productName5",
87+
"vendorName6#productName6",
8688
},
8789
},
8890
},

db/rdb.go

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"github.com/cheggaaa/pb/v3"
1212
"github.com/inconshreveable/log15"
1313
sqlite3 "github.com/mattn/go-sqlite3"
14+
"github.com/spf13/viper"
1415
"github.com/vulsio/go-cpe-dictionary/config"
1516
"github.com/vulsio/go-cpe-dictionary/models"
1617
"golang.org/x/xerrors"
@@ -43,12 +44,17 @@ func (r *RDBDriver) Name() string {
4344
func (r *RDBDriver) OpenDB(dbType, dbPath string, debugSQL bool) (locked bool, err error) {
4445
gormConfig := gorm.Config{
4546
DisableForeignKeyConstraintWhenMigrating: true,
46-
Logger: logger.Default.LogMode(logger.Silent),
47+
Logger: logger.New(
48+
log.New(os.Stderr, "\r\n", log.LstdFlags),
49+
logger.Config{
50+
LogLevel: logger.Silent,
51+
},
52+
),
4753
}
4854

4955
if debugSQL {
5056
gormConfig.Logger = logger.New(
51-
log.New(os.Stdout, "\r\n", log.LstdFlags),
57+
log.New(os.Stderr, "\r\n", log.LstdFlags),
5258
logger.Config{
5359
SlowThreshold: time.Second,
5460
LogLevel: logger.Info,
@@ -171,7 +177,7 @@ func (r *RDBDriver) GetVendorProducts() (vendorProducts []string, err error) {
171177
}
172178

173179
for _, vp := range results {
174-
vendorProducts = append(vendorProducts, fmt.Sprintf("%s::%s", vp.Vendor, vp.Product))
180+
vendorProducts = append(vendorProducts, fmt.Sprintf("%s#%s", vp.Vendor, vp.Product))
175181
}
176182
return
177183
}
@@ -209,6 +215,11 @@ func (r *RDBDriver) deleteAndInsertCpes(conn *gorm.DB, fetchType models.FetchTyp
209215
tx.Commit()
210216
}()
211217

218+
batchSize := viper.GetInt("batch-size")
219+
if batchSize < 1 {
220+
return xerrors.New("Failed to set batch-size. err: batch-size option is not set properly")
221+
}
222+
212223
// Delete all old records
213224
oldIDs := []int64{}
214225
result := tx.Model(models.CategorizedCpe{}).Select("id").Where("fetch_type = ?", fetchType).Find(&oldIDs)
@@ -218,15 +229,15 @@ func (r *RDBDriver) deleteAndInsertCpes(conn *gorm.DB, fetchType models.FetchTyp
218229

219230
if result.RowsAffected > 0 {
220231
log15.Info(fmt.Sprintf("Deleting records that match fetch_type = %s from your DB. This will take some time.", fetchType))
221-
for idx := range chunkSlice(len(oldIDs), 10000) {
232+
for idx := range chunkSlice(len(oldIDs), batchSize) {
222233
if err := tx.Where("id IN ?", oldIDs[idx.From:idx.To]).Delete(&models.CategorizedCpe{}).Error; err != nil {
223234
return xerrors.Errorf("Failed to delete: %w", err)
224235
}
225236
}
226237
}
227238

228239
bar := pb.StartNew(len(cpes))
229-
for idx := range chunkSlice(len(cpes), 2000) {
240+
for idx := range chunkSlice(len(cpes), batchSize) {
230241
if err := tx.Create(cpes[idx.From:idx.To]).Error; err != nil {
231242
return xerrors.Errorf("Failed to insert. err: %w", err)
232243
}

0 commit comments

Comments
 (0)