Skip to content

Commit

Permalink
Shut down cleanly when 'api serve' is interrupted
Browse files Browse the repository at this point in the history
This will properly close the db and, more particularly, flush out any
profile files being written. Otherwise, they can end up empty or
truncated.

Signed-off-by: Ryan Gonzalez <ryan.gonzalez@collabora.com>
  • Loading branch information
refi64 committed Sep 25, 2023
1 parent 18203c6 commit e1cc8cc
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions cmd/api_serve.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
package cmd

import (
stdcontext "context"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"syscall"

"github.com/aptly-dev/aptly/api"
"github.com/aptly-dev/aptly/systemd/activation"
Expand Down Expand Up @@ -55,6 +59,17 @@ func aptlyAPIServe(cmd *commander.Command, args []string) error {
listen := context.Flags().Lookup("listen").Value.String()
fmt.Printf("\nStarting web server at: %s (press Ctrl+C to quit)...\n", listen)

server := http.Server{Handler: api.Router(context)}

sigchan := make(chan os.Signal, 1)
signal.Notify(sigchan, syscall.SIGINT, syscall.SIGTERM)
go (func() {
if _, ok := <-sigchan; ok {
server.Shutdown(stdcontext.Background())
}
})()
defer close(sigchan)

listenURL, err := url.Parse(listen)
if err == nil && listenURL.Scheme == "unix" {
file := listenURL.Path
Expand All @@ -67,19 +82,17 @@ func aptlyAPIServe(cmd *commander.Command, args []string) error {
}
defer listener.Close()

err = http.Serve(listener, api.Router(context))
if err != nil {
return fmt.Errorf("unable to serve: %s", err)
}
return nil
err = server.Serve(listener)
} else {
server.Addr = listen
err = server.ListenAndServe()
}

err = http.ListenAndServe(listen, api.Router(context))
if err != nil {
if err != nil && !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("unable to serve: %s", err)
}

return err
return nil
}

func makeCmdAPIServe() *commander.Command {
Expand Down

0 comments on commit e1cc8cc

Please sign in to comment.