I want to do a fire and forget api call when an EC2 is terminated by an auto scaling group.
So far, I simply used the graceful shutdown pattern by listening to OS signals but it looks like it's not getting triggered when I terminate the EC2.
package main
func main() {
go server.Start() // some server doing server things
graceFullShutdown()
}
func graceFullShutdown() {
log.Info("Setup Graceful Shutdown for Server")
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGKILL)
<-c
api.Deregister()
log.Info("Gracefully shutting down")
os.Exit(0)
}
And the api apackage simply does an http post to an api.
func Deregister() error {
return apiCall("deregister")
}
func apiCall(path string) error {
for {
req, err := http.NewRequest(http.MethodPost, "api/" + path, bytes.NewBuffer("{\"InstanceId\":\"someid\"}"))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
io.Copy(ioutil.Discard, resp.Body)
if resp.StatusCode >= 200 && resp.StatusCode <= 299 {
log.Infof("Server %v deregisterd", r)
break
} else {
log.Warn("Couldn't deregisterd serverin 10 seconds")
time.Sleep(10 * time.Second)
}
}
return nil
}
Am I missing the right syscall to listen too or is there something wrong with this approach? Is there a way to terminate the application with a lifecycle hook so that the deregistration would be called?