From 6136ce6f002498cc98d9a3badac79f37fe74f80e Mon Sep 17 00:00:00 2001 From: Sergey Matveev Date: Thu, 5 Dec 2019 00:07:31 +0300 Subject: [PATCH] Prevent resourceful operations when shutting down --- gocheese.go | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/gocheese.go b/gocheese.go index 712783a..f5a3918 100644 --- a/gocheese.go +++ b/gocheese.go @@ -82,6 +82,8 @@ var ( maxClients = flag.Int("maxclients", 128, "Maximal amount of simultaneous clients") version = flag.Bool("version", false, "Print version information") warranty = flag.Bool("warranty", false, "Print warranty information") + + killed bool ) func mkdirForPkg(w http.ResponseWriter, r *http.Request, dir string) bool { @@ -139,6 +141,11 @@ func refreshDir(w http.ResponseWriter, r *http.Request, dir, filenameGet string) return false } if filename == filenameGet { + if killed { + // Skip heavy remote call, when shutting down + http.Error(w, "shutting down", http.StatusInternalServerError) + return false + } log.Println(r.RemoteAddr, "pypi download", filename) path = filepath.Join(*root, dir, filename) resp, err = http.Get(uri) @@ -242,6 +249,11 @@ func listDir(w http.ResponseWriter, r *http.Request, dir string, autorefresh boo if !strings.HasSuffix(file.Name(), SHA256Ext) { continue } + if killed { + // Skip expensive I/O when shutting down + http.Error(w, "shutting down", http.StatusInternalServerError) + return + } data, err = ioutil.ReadFile(filepath.Join(dirPath, file.Name())) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) @@ -464,7 +476,7 @@ func main() { needsRefreshPasswd := make(chan os.Signal, 0) needsShutdown := make(chan os.Signal, 0) - killed := make(chan error, 0) + exitErr := make(chan error, 0) signal.Notify(needsRefreshPasswd, syscall.SIGHUP) signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT) go func() { @@ -475,9 +487,10 @@ func main() { }() go func(s *http.Server) { <-needsShutdown + killed = true log.Println("Shutting down") ctx, cancel := context.WithTimeout(context.TODO(), time.Minute) - killed <- s.Shutdown(ctx) + exitErr <- s.Shutdown(ctx) cancel() }(server) @@ -489,7 +502,7 @@ func main() { if err != http.ErrServerClosed { log.Fatal(err) } - if err := <-killed; err != nil { + if err := <-exitErr; err != nil { log.Fatal(err) } } -- 2.44.0