I have a program in golang in EC2.
The requirements are to perform clean up on EC2 termination. I am trying to achieve this by the below code in which I have created a channel listening to os signals:
func InitTermination(){
signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGKILL) //listen to termination signals (ctrl+c)
go func() {
<-c
log.Println("Calling uploadLogFiles on system/program termination")
*termination = true
for {
if !(*lock) {
err := uploadCompletedLogs()
if err != nil {
log.Fatalf("Error: %v", err)
}
break
} else {
time.Sleep(100 * time.Millisecond)
}
}
if !(os.Getenv("TEST") == "true") {
os.Exit(1)
}
}()
}
On instance termination or stopping I want method uploadCompletedLogs() to be executed, which performs some cleanup, but I am not able to achieve the desired behavior.
Can some one guide me how can i achieve this?
As JimB noted, and per the documentation, you cannot handle SIGKILL or SIGSTOP. These are likely what is being sent at shutdown. If you're managing processes with something like init.d, you may be getting whatever your init.d script sends when it's called with stop
(probably SIGTERM), which you may be able to catch, but you have very limited time between when that is called and when the machine shuts down completely. Any processing that takes more than a second or two is not likely to finish in time. If you want to make sure something is done before the machine shuts down, you should do it regularly rather than waiting to do it at shutdown time.