summaryrefslogtreecommitdiff
path: root/cmd/cli/serve.go
blob: 2fe54932f65a083ae388f29c2566fea440cfcd73 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package cli

import (
	"log"
	"os"
	"os/signal"
	"syscall"

	"github.com/spf13/cobra"
	"github.com/spiral/errors"
	"go.uber.org/multierr"
)

func init() {
	root.AddCommand(&cobra.Command{
		Use:   "serve",
		Short: "Start RoadRunner server",
		RunE:  handler,
	})
}

func handler(cmd *cobra.Command, args []string) error {
	const op = errors.Op("handle serve command")
	/*
		We need to have path to the config at the RegisterTarget stage
		But after cobra.Execute, because cobra fills up cli variables on this stage
	*/

	err := Container.Init()
	if err != nil {
		return errors.E(op, err)
	}

	errCh, err := Container.Serve()
	if err != nil {
		return errors.E(op, err)
	}

	// https://golang.org/pkg/os/signal/#Notify
	// should be of buffer size at least 1
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)

	for {
		select {
		case e := <-errCh:
			err = multierr.Append(err, e.Error)
			log.Printf("error occurred: %v, service: %s", e.Error.Error(), e.VertexID)
			er := Container.Stop()
			if er != nil {
				err = multierr.Append(err, er)
				return errors.E(op, err)
			}
			return errors.E(op, err)
		case <-c:
			err = Container.Stop()
			if err != nil {
				return errors.E(op, err)
			}
			return nil
		}
	}
}