Skip to content

Commit

Permalink
cmd/cue: handle signals and perform a graceful shutdown for mod registry
Browse files Browse the repository at this point in the history
The registry did not handle signals. The default behavior of a Go
program for receiving `SIGINT` and `SIGTERM` signals is to exit and
return `128 + <signal number>`, regardless of whether it exits
successfully or not.

Handle signals and perform a graceful shutdown for the registry. Return
zero when it exits successfully.

Fixes #3224

Change-Id: I90a534d47f43b2d9f93db7f460df8892a695f134
Signed-off-by: haoqixu <[email protected]>
Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/1196370
Reviewed-by: Daniel Martí <[email protected]>
TryBot-Result: CUEcueckoo <[email protected]>
Unity-Result: CUE porcuepine <[email protected]>
  • Loading branch information
haoqixu authored and mvdan committed Jul 9, 2024
1 parent 695fefc commit 27adbac
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
30 changes: 27 additions & 3 deletions cmd/cue/cmd/modregistry.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,21 @@ package cmd

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

"cuelabs.dev/go/oci/ociregistry"
"cuelabs.dev/go/oci/ociregistry/ocimem"
"cuelabs.dev/go/oci/ociregistry/ociserver"
"github.com/spf13/cobra"
)

// TODO: add testing for this command.

func newModRegistryCmd(c *Command) *cobra.Command {
cmd := &cobra.Command{
// This command is hidden, for now at least,
Expand Down Expand Up @@ -63,7 +66,28 @@ func runModRegistry(cmd *Command, args []string) error {
r := ocimem.NewWithConfig(&ocimem.Config{
ImmutableTags: true,
})
return http.Serve(l, ociserver.New(ociTagLoggerRegistry{r}, nil))

srv := http.Server{
Handler: ociserver.New(ociTagLoggerRegistry{r}, nil),
}
var serveErr error
go func() {
if err := srv.Serve(l); !errors.Is(err, http.ErrServerClosed) {
serveErr = err
}
}()

sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt, syscall.SIGTERM)
<-sigint

ctx, cancal := context.WithTimeout(context.Background(), 2*time.Second)
defer cancal()
if err := srv.Shutdown(ctx); err != nil {
fmt.Printf("HTTP server Shutdown: %v\n", err)
return err
}
return serveErr
}

type ociTagLoggerRegistry struct {
Expand Down
19 changes: 19 additions & 0 deletions cmd/cue/cmd/testdata/script/mod_registry.txtar
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# TODO: use a random unused port
env CUE_REGISTRY=localhost:41331
exec cue mod registry ${CUE_REGISTRY} &
exec cue mod publish v0.0.1
cmpenv stdout expect-stdout

-- expect-stdout --
published mod.example/[email protected] to ${CUE_REGISTRY}/mod.example/blah:v0.0.1
-- blah.cue --
package blah
blah: 42
-- cue.mod/module.cue --
module: "mod.example/blah@v0"
language: {
version: "v0.9.0"
}
source: {
kind: "self"
}

0 comments on commit 27adbac

Please sign in to comment.