Skip to content

Commit

Permalink
app: Defer cleanup to ensure pid file removal (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
adamhicks authored Oct 4, 2024
1 parent 567c0f5 commit 596ebea
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 10 deletions.
17 changes: 8 additions & 9 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ func (a *App) startup(ctx context.Context) error {
return ctx.Err()
}

func (a *App) cleanup(ctx context.Context) error {
func (a *App) runShutdownHooks(ctx context.Context) error {
var errs []error
for idx, h := range a.shutdownHooks {
if ctx.Err() != nil {
Expand Down Expand Up @@ -148,6 +148,7 @@ func (a *App) cleanup(ctx context.Context) error {
func (a *App) Run() int {
ac := NewAppContext(context.Background())
defer ac.Stop()
defer a.cleanup(ac.TerminationContext)

ctx := ac.AppContext

Expand All @@ -166,13 +167,7 @@ func (a *App) Run() int {
exit = 1
}

// TODO(adam): Move pid removal into Shutdown

// This should be called in Shutdown so that clients which call that instead of
// Run can get the right behaviour
if a.UseProcessFile {
removePIDFile(ctx)
}
log.Info(ctx, "Waiting to terminate", j.MKV{"exit_code": exit})

// Wait for termination in case we've only been told to quit
<-ac.TerminationContext.Done()
Expand Down Expand Up @@ -255,7 +250,7 @@ func (a *App) Shutdown() error {
defer a.OnEvent(ctx, Event{Type: AppTerminated})

defer func() {
err := a.cleanup(ctx)
err := a.runShutdownHooks(ctx)
if err != nil {
// NoReturnErr: Log
log.Error(ctx, errors.Wrap(err, ""))
Expand Down Expand Up @@ -325,6 +320,10 @@ func (a *App) RunningProcesses() []string {
return ret
}

func (a *App) cleanup(ctx context.Context) {
removePIDFile(ctx)
}

// Wait is a cancellable wait, it will return either when
// d has passed or ctx is cancelled.
// It will return an error if cancelled early.
Expand Down
4 changes: 3 additions & 1 deletion file.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ func createPIDFile() error {

func removePIDFile(ctx context.Context) {
err := os.Remove(fileName)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
// NoReturnErr: File already gone, no worries
} else if err != nil {
// NoReturnErr: We'll terminate after this so just log
log.Error(ctx, errors.Wrap(err, "remove pid file", j.KV("file", fileName)))
}
Expand Down

0 comments on commit 596ebea

Please sign in to comment.