Skip to content

Commit 4c6b5fb

Browse files
committed
refactor: simplify the concurrency logic
1 parent d08e72a commit 4c6b5fb

File tree

1 file changed

+21
-37
lines changed

1 file changed

+21
-37
lines changed

cmd/kar-controllers/app/server.go

Lines changed: 21 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,15 @@ func Run(ctx context.Context, opt *options.ServerOption) error {
5050
config.QPS = 100.0
5151
config.Burst = 200.0
5252

53+
g, gCtx := errgroup.WithContext(ctx)
5354

54-
// Start the health and metrics servers
55-
err = startHealthAndMetricsServers(ctx, opt)
55+
// metrics server
56+
metricsServer, err := NewServer(opt.MetricsListenPort, "/metrics", metrics.PrometheusHandler())
57+
if err != nil {
58+
return err
59+
}
60+
61+
healthServer, err := NewServer(opt.HealthProbeListenPort, "/healthz", healthHandler())
5662
if err != nil {
5763
return err
5864
}
@@ -63,54 +69,32 @@ func Run(ctx context.Context, opt *options.ServerOption) error {
6369
return fmt.Errorf("failed to create a job controller")
6470
}
6571

66-
// Run the job controller in a goroutine and wait for it to exit
67-
wg := sync.WaitGroup{}
72+
wg := &sync.WaitGroup{}
6873
wg.Add(1)
69-
go func() {
74+
g.Go(func() error {
7075
defer wg.Done()
71-
jobctrl.Run(ctx.Done())
72-
}()
73-
74-
wg.Wait()
75-
76-
77-
return nil
78-
}
79-
80-
func healthHandler() http.Handler {
81-
healthHandler := http.NewServeMux()
82-
healthHandler.Handle("/healthz", &health.Handler{})
83-
return healthHandler
84-
}
85-
86-
// Starts the health probe listener
87-
func startHealthAndMetricsServers(ctx context.Context, opt *options.ServerOption) error {
88-
g, ctx := errgroup.WithContext(ctx)
89-
90-
// metrics server
91-
metricsServer, err := NewServer(opt.MetricsListenPort, "/metrics", metrics.PrometheusHandler())
92-
if err != nil {
93-
return err
94-
}
95-
96-
healthServer, err := NewServer(opt.HealthProbeListenPort, "/healthz", healthHandler())
97-
if err != nil {
98-
return err
99-
}
76+
jobctrl.Run(gCtx.Done())
77+
return nil
78+
})
10079

10180
g.Go(metricsServer.Start)
10281
g.Go(healthServer.Start)
10382

10483
g.Go(func() error {
105-
<-ctx.Done()
84+
wg.Wait()
10685
return metricsServer.Shutdown()
10786
})
10887

10988
g.Go(func() error {
110-
<-ctx.Done()
89+
wg.Wait()
11190
return healthServer.Shutdown()
11291
})
11392

114-
return g.Wait()
93+
return g.Wait()
11594
}
11695

96+
func healthHandler() http.Handler {
97+
healthHandler := http.NewServeMux()
98+
healthHandler.Handle("/healthz", &health.Handler{})
99+
return healthHandler
100+
}

0 commit comments

Comments
 (0)