keyshare-root.go 1.54 KB
Newer Older
1
2
package cmd

3
4
5
6
7
8
9
10
11
12
import (
	"context"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"github.com/privacybydesign/irmago/server"
	"github.com/sirupsen/logrus"
13
14
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
15
)
16

17
var keyshareRootCmd = &cobra.Command{
18
	Use:   "keyshare",
19
	Short: "IRMA keyshare server components",
20
21
22
}

func init() {
23
	RootCmd.AddCommand(keyshareRootCmd)
24
}
25
26
27
28
29
30
31
32

type stoppableServer interface {
	Handler() http.Handler
	Stop()
}

func runServer(serv stoppableServer, logger *logrus.Logger) {
	// Determine full listening address.
33
	fullAddr := fmt.Sprintf("%s:%d", viper.GetString("listen_addr"), viper.GetInt("port"))
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

	// Load TLS configuration
	TLSConfig := configureTLS()

	httpServer := &http.Server{
		Addr:      fullAddr,
		Handler:   serv.Handler(),
		TLSConfig: TLSConfig,
	}

	stopped := make(chan struct{})
	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)

	go func() {
		var err error
		if TLSConfig != nil {
			err = server.FilterStopError(httpServer.ListenAndServeTLS("", ""))
		} else {
			err = server.FilterStopError(httpServer.ListenAndServe())
		}
		if err != nil {
			_ = server.LogError(err)
		}
58
		logger.Debug("Server stopped")
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
		stopped <- struct{}{}
	}()

	for {
		select {
		case <-interrupt:
			logger.Debug("Caught interrupt")
			err := httpServer.Shutdown(context.Background())
			if err != nil {
				_ = server.LogError(err)
			}
			serv.Stop()
			logger.Debug("Sent stop signal to server")
		case <-stopped:
			logger.Info("Exiting")
			close(stopped)
			close(interrupt)
			return
		}
	}
}