Skip to content

Commit b1f8e05

Browse files
authored
cmd/crowdsec: refact dump.go, loops (#4158)
* unused parameters * refact dump.go * break -> return * extract unregisterWatcher()
1 parent 3221f7b commit b1f8e05

File tree

11 files changed

+52
-70
lines changed

11 files changed

+52
-70
lines changed

cmd/crowdsec/appsec_stub.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,6 @@ import (
66
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
77
)
88

9-
func LoadAppsecRules(hub *cwhub.Hub) error {
9+
func LoadAppsecRules(_ *cwhub.Hub) error {
1010
return nil
1111
}

cmd/crowdsec/crowdsec.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,6 @@ func startLPMetrics(ctx context.Context, cConfig *csconfig.Config, apiClient *ap
111111
apiClient,
112112
lpMetricsDefaultInterval,
113113
log.WithField("service", "lpmetrics"),
114-
[]string{},
115114
datasources,
116115
hub,
117116
)
@@ -198,8 +197,10 @@ func serveCrowdsec(ctx context.Context, parsers *parser.Parsers, cConfig *csconf
198197

199198
log.Debugf("everything is dead, return crowdsecTomb")
200199

201-
if dumpStates {
202-
if err := dumpAllStates(); err != nil {
200+
if flags.DumpDir != "" {
201+
log.Debugf("Dumping parser+bucket states to %s", flags.DumpDir)
202+
203+
if err := dumpAllStates(flags.DumpDir); err != nil {
203204
log.Fatal(err)
204205
}
205206

cmd/crowdsec/dump.go

Lines changed: 13 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -5,52 +5,38 @@ import (
55
"os"
66
"path/filepath"
77

8-
log "github.com/sirupsen/logrus"
98
"gopkg.in/yaml.v3"
109

1110
leaky "github.com/crowdsecurity/crowdsec/pkg/leakybucket"
1211
"github.com/crowdsecurity/crowdsec/pkg/parser"
1312
)
1413

15-
func dumpAllStates() error {
16-
log.Debugf("Dumping parser+bucket states to %s", parser.DumpFolder)
14+
func dumpAllStates(dir string) error {
15+
err := os.MkdirAll(dir, 0o755)
16+
if err != nil {
17+
return err
18+
}
1719

18-
if err := dumpState(
19-
filepath.Join(parser.DumpFolder, "parser-dump.yaml"),
20-
parser.StageParseCache,
21-
); err != nil {
22-
return fmt.Errorf("while dumping parser state: %w", err)
20+
if err := dumpState(dir, "parser-dump.yaml", parser.StageParseCache); err != nil {
21+
return fmt.Errorf("dumping parser state: %w", err)
2322
}
2423

25-
if err := dumpState(
26-
filepath.Join(parser.DumpFolder, "bucket-dump.yaml"),
27-
bucketOverflows,
28-
); err != nil {
29-
return fmt.Errorf("while dumping bucket overflow state: %w", err)
24+
if err := dumpState(dir, "bucket-dump.yaml", bucketOverflows); err != nil {
25+
return fmt.Errorf("dumping bucket overflow state: %w", err)
3026
}
3127

32-
if err := dumpState(
33-
filepath.Join(parser.DumpFolder, "bucketpour-dump.yaml"),
34-
leaky.BucketPourCache,
35-
); err != nil {
36-
return fmt.Errorf("while dumping bucket pour state: %w", err)
28+
if err := dumpState(dir, "bucketpour-dump.yaml", leaky.BucketPourCache); err != nil {
29+
return fmt.Errorf("dumping bucket pour state: %w", err)
3730
}
3831

3932
return nil
4033
}
4134

42-
func dumpState(destPath string, obj any) error {
43-
dir := filepath.Dir(destPath)
44-
45-
err := os.MkdirAll(dir, 0o755)
46-
if err != nil {
47-
return err
48-
}
49-
35+
func dumpState(dir, name string, obj any) error {
5036
out, err := yaml.Marshal(obj)
5137
if err != nil {
5238
return err
5339
}
5440

55-
return os.WriteFile(destPath, out, 0o666)
41+
return os.WriteFile(filepath.Join(dir, name), out, 0o666)
5642
}

cmd/crowdsec/flags.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ type Flags struct {
2828
Transform string
2929
OrderEvent bool
3030
CPUProfile string
31+
DumpDir string
3132
}
3233

3334
func (f *Flags) haveTimeMachine() bool {
@@ -80,7 +81,7 @@ func (f *Flags) parse() {
8081
flag.StringVar(&f.WinSvc, "winsvc", "", "Windows service Action: Install, Remove etc..")
8182
}
8283

83-
flag.StringVar(&dumpFolder, "dump-data", "", "dump parsers/buckets raw outputs")
84+
flag.StringVar(&f.DumpDir, "dump-data", "", "dump parsers/buckets raw outputs")
8485
flag.StringVar(&f.CPUProfile, "cpu-profile", "", "write cpu profile to file")
8586
flag.Parse()
8687

cmd/crowdsec/lpmetrics.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ func getHubState(hub *cwhub.Hub) models.HubItems {
8787
}
8888

8989
// newStaticMetrics is called when the process starts, or reloads the configuration
90-
func newStaticMetrics(consoleOptions []string, datasources []acquisition.DataSource, hub *cwhub.Hub) staticMetrics {
90+
func newStaticMetrics(datasources []acquisition.DataSource, hub *cwhub.Hub) staticMetrics {
9191
datasourceMap := map[string]int64{}
9292

9393
for _, ds := range datasources {
@@ -111,11 +111,10 @@ func NewMetricsProvider(
111111
apic *apiclient.ApiClient,
112112
interval time.Duration,
113113
logger *logrus.Entry,
114-
consoleOptions []string,
115114
datasources []acquisition.DataSource,
116115
hub *cwhub.Hub,
117116
) *MetricsProvider {
118-
static := newStaticMetrics(consoleOptions, datasources, hub)
117+
static := newStaticMetrics(datasources, hub)
119118

120119
logger.Debugf("Detected %s %s (family: %s)", static.osName, static.osVersion, static.osFamily)
121120

cmd/crowdsec/main.go

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,6 @@ func LoadAcquisition(ctx context.Context, cConfig *csconfig.Config) ([]acquisiti
101101
}
102102

103103
var (
104-
dumpFolder string
105-
dumpStates bool
106104
additionalLabels = make(labelsMap)
107105
)
108106

@@ -124,11 +122,9 @@ func LoadConfig(configFile string, disableAgent bool, disableAPI bool, quiet boo
124122
}
125123
}
126124

127-
if dumpFolder != "" {
125+
if flags.DumpDir != "" {
128126
parser.ParseDump = true
129-
parser.DumpFolder = dumpFolder
130127
leakybucket.BucketPourTrack = true
131-
dumpStates = true
132128
}
133129

134130
if flags.haveTimeMachine() {

cmd/crowdsec/output.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ func runOutput(
123123

124124
// if the Alert is nil, it's to signal bucket is ready for GC, don't track this
125125
// dump after postoveflow processing to avoid missing whitelist info
126-
if dumpStates && ov.Alert != nil {
126+
if flags.DumpDir != "" && ov.Alert != nil {
127127
bucketOverflows = append(bucketOverflows, event)
128128
}
129129

@@ -141,7 +141,7 @@ func runOutput(
141141
}
142142
}
143143

144-
if dumpStates {
144+
if flags.DumpDir != "" {
145145
continue
146146
}
147147

cmd/crowdsec/serve.go

Lines changed: 25 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,24 @@ func drainChan(c chan pipeline.Event) {
216216
}
217217
}
218218

219+
func unregisterWatcher(ctx context.Context, cConfig *csconfig.Config) (bool, error) {
220+
if cConfig.API == nil || cConfig.API.Client == nil || !cConfig.API.Client.UnregisterOnExit {
221+
return false, nil
222+
}
223+
224+
lapiClient, err := apiclient.GetLAPIClient()
225+
if err != nil {
226+
return false, err
227+
}
228+
229+
_, err = lapiClient.Auth.UnregisterWatcher(ctx)
230+
if err != nil {
231+
return false, err
232+
}
233+
234+
return true, nil
235+
}
236+
219237
func HandleSignals(ctx context.Context, cConfig *csconfig.Config) error {
220238
var (
221239
newConfig *csconfig.Config
@@ -240,7 +258,6 @@ func HandleSignals(ctx context.Context, cConfig *csconfig.Config) error {
240258
go func() {
241259
defer trace.CatchPanic("crowdsec/HandleSignals")
242260

243-
Loop:
244261
for {
245262
s := <-signalChan
246263
switch s {
@@ -250,14 +267,12 @@ func HandleSignals(ctx context.Context, cConfig *csconfig.Config) error {
250267

251268
if err = shutdown(s, cConfig); err != nil {
252269
exitChan <- fmt.Errorf("failed shutdown: %w", err)
253-
254-
break Loop
270+
return
255271
}
256272

257273
if newConfig, err = reloadHandler(ctx, s); err != nil {
258274
exitChan <- fmt.Errorf("reload handler failure: %w", err)
259-
260-
break Loop
275+
return
261276
}
262277

263278
if newConfig != nil {
@@ -269,8 +284,7 @@ func HandleSignals(ctx context.Context, cConfig *csconfig.Config) error {
269284

270285
if err = shutdown(s, cConfig); err != nil {
271286
exitChan <- fmt.Errorf("failed shutdown: %w", err)
272-
273-
break Loop
287+
return
274288
}
275289

276290
exitChan <- nil
@@ -283,20 +297,11 @@ func HandleSignals(ctx context.Context, cConfig *csconfig.Config) error {
283297
log.Warning("Crowdsec service shutting down")
284298
}
285299

286-
if cConfig.API != nil && cConfig.API.Client != nil && cConfig.API.Client.UnregisterOnExit {
287-
log.Warning("Unregistering watcher")
288-
289-
lapiClient, err := apiclient.GetLAPIClient()
290-
if err != nil {
291-
return err
292-
}
293-
294-
_, err = lapiClient.Auth.UnregisterWatcher(ctx)
295-
if err != nil {
296-
return fmt.Errorf("failed to unregister watcher: %w", err)
300+
if ok, werr := unregisterWatcher(ctx, cConfig); werr != nil {
301+
log.WithError(werr).Warning("unregistering watcher")
302+
if ok {
303+
log.Warning("Watcher unregistered")
297304
}
298-
299-
log.Warning("Watcher unregistered")
300305
}
301306

302307
return err

cmd/crowdsec/win_service.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ func (m *crowdsec_winservice) Execute(args []string, r <-chan svc.ChangeRequest,
3131
changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
3232

3333
go func() {
34-
loop:
3534
for {
3635
select {
3736
case <-tick:
@@ -47,7 +46,7 @@ func (m *crowdsec_winservice) Execute(args []string, r <-chan svc.ChangeRequest,
4746
log.Errorf("Error while shutting down: %s", err)
4847
// don't return, we still want to notify windows that we are stopped ?
4948
}
50-
break loop
49+
return
5150
default:
5251
log.Errorf("unexpected control request #%d", c)
5352
}

cmd/crowdsec/win_service_manage.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,6 @@ import (
1010
"fmt"
1111
"time"
1212

13-
//"time"
14-
1513
"golang.org/x/sys/windows/svc"
1614
"golang.org/x/sys/windows/svc/mgr"
1715
)

0 commit comments

Comments
 (0)