Skip to content

Commit 2b5987c

Browse files
committed
refactor: simplify the concurrency logic
1 parent 0d92fca commit 2b5987c

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
@@ -73,9 +73,15 @@ func Run(ctx context.Context, opt *options.ServerOption) error {
7373
return fmt.Errorf("failed to create a job controller")
7474
}
7575

76+
g, gCtx := errgroup.WithContext(ctx)
7677

77-
// Start the health and metrics servers
78-
err = startHealthAndMetricsServers(ctx, opt)
78+
// metrics server
79+
metricsServer, err := NewServer(opt.MetricsListenPort, "/metrics", metrics.PrometheusHandler())
80+
if err != nil {
81+
return err
82+
}
83+
84+
healthServer, err := NewServer(opt.HealthProbeListenPort, "/healthz", healthHandler())
7985
if err != nil {
8086
return err
8187
}
@@ -86,54 +92,32 @@ func Run(ctx context.Context, opt *options.ServerOption) error {
8692
return fmt.Errorf("failed to create a job controller")
8793
}
8894

89-
// Run the job controller in a goroutine and wait for it to exit
90-
wg := sync.WaitGroup{}
95+
wg := &sync.WaitGroup{}
9196
wg.Add(1)
92-
go func() {
97+
g.Go(func() error {
9398
defer wg.Done()
94-
jobctrl.Run(ctx.Done())
95-
}()
96-
97-
wg.Wait()
98-
99-
100-
return nil
101-
}
102-
103-
func healthHandler() http.Handler {
104-
healthHandler := http.NewServeMux()
105-
healthHandler.Handle("/healthz", &health.Handler{})
106-
return healthHandler
107-
}
108-
109-
// Starts the health probe listener
110-
func startHealthAndMetricsServers(ctx context.Context, opt *options.ServerOption) error {
111-
g, ctx := errgroup.WithContext(ctx)
112-
113-
// metrics server
114-
metricsServer, err := NewServer(opt.MetricsListenPort, "/metrics", metrics.PrometheusHandler())
115-
if err != nil {
116-
return err
117-
}
118-
119-
healthServer, err := NewServer(opt.HealthProbeListenPort, "/healthz", healthHandler())
120-
if err != nil {
121-
return err
122-
}
99+
jobctrl.Run(gCtx.Done())
100+
return nil
101+
})
123102

124103
g.Go(metricsServer.Start)
125104
g.Go(healthServer.Start)
126105

127106
g.Go(func() error {
128-
<-ctx.Done()
107+
wg.Wait()
129108
return metricsServer.Shutdown()
130109
})
131110

132111
g.Go(func() error {
133-
<-ctx.Done()
112+
wg.Wait()
134113
return healthServer.Shutdown()
135114
})
136115

137-
return g.Wait()
116+
return g.Wait()
138117
}
139118

119+
func healthHandler() http.Handler {
120+
healthHandler := http.NewServeMux()
121+
healthHandler.Handle("/healthz", &health.Handler{})
122+
return healthHandler
123+
}

0 commit comments

Comments
 (0)