Skip to content

Commit 0dc0fcd

Browse files
committed
improve shutdown
Signed-off-by: Markus Blaschke <[email protected]>
1 parent 76a2a6b commit 0dc0fcd

File tree

2 files changed

+35
-4
lines changed

2 files changed

+35
-4
lines changed

autopilot/main.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ type (
3737
update *cron.Cron
3838
}
3939

40+
wg sync.WaitGroup
41+
4042
prometheus struct {
4143
general struct {
4244
errors *prometheus.CounterVec
@@ -208,6 +210,18 @@ func (r *AzureK8sAutopilot) Start() {
208210
}()
209211
}
210212

213+
func (r *AzureK8sAutopilot) Stop() {
214+
if r.cron.repair != nil {
215+
r.cron.repair.Stop()
216+
}
217+
218+
if r.cron.update != nil {
219+
r.cron.update.Stop()
220+
}
221+
222+
r.wg.Wait()
223+
}
224+
211225
func (r *AzureK8sAutopilot) startAutopilotRepair() {
212226
// repair job
213227
r.cron.repair = cron.New(
@@ -221,6 +235,9 @@ func (r *AzureK8sAutopilot) startAutopilotRepair() {
221235
)
222236

223237
_, err := r.cron.repair.AddFunc(r.Config.Repair.Crontab, func() {
238+
r.wg.Add(1)
239+
defer r.wg.Done()
240+
224241
contextLogger := log.WithField("job", "repair")
225242

226243
// concurrency repair limit
@@ -254,6 +271,9 @@ func (r *AzureK8sAutopilot) startAutopilotUpdate() {
254271
)
255272

256273
_, err := r.cron.update.AddFunc(r.Config.Update.Crontab, func() {
274+
r.wg.Add(1)
275+
defer r.wg.Done()
276+
257277
contextLogger := log.WithField("job", "update")
258278

259279
// concurrency repair limit

main.go

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,11 @@ import (
99
"github.com/webdevopos/azure-k8s-autopilot/config"
1010
"net/http"
1111
"os"
12+
"os/signal"
1213
"path"
1314
"runtime"
1415
"strings"
16+
"syscall"
1517
)
1618

1719
const (
@@ -34,14 +36,21 @@ func main() {
3436
log.Infof("starting Azure K8S cluster autopilot v%s (%s; %s; by %v)", gitTag, gitCommit, runtime.Version(), Author)
3537
log.Info(string(opts.GetJson()))
3638

37-
autorepair := autopilot.AzureK8sAutopilot{
39+
pilot := autopilot.AzureK8sAutopilot{
3840
Config: opts,
3941
}
40-
autorepair.Init()
41-
autorepair.Start()
42+
pilot.Init()
43+
pilot.Start()
4244

4345
log.Infof("starting http server on %s", opts.ServerBind)
4446
startHttpServer()
47+
48+
termChan := make(chan os.Signal)
49+
signal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM)
50+
<-termChan
51+
log.Info("shutdown signal received, trying to stop")
52+
pilot.Stop()
53+
log.Info("finished, terminating now")
4554
}
4655

4756
// init argparser and parse/validate arguments
@@ -103,5 +112,7 @@ func startHttpServer() {
103112
})
104113

105114
http.Handle("/metrics", promhttp.Handler())
106-
log.Fatal(http.ListenAndServe(opts.ServerBind, nil))
115+
go func() {
116+
log.Fatal(http.ListenAndServe(opts.ServerBind, nil))
117+
}()
107118
}

0 commit comments

Comments
 (0)