aboutsummaryrefslogtreecommitdiff
path: root/core/setup/startupshutdown.go
blob: 1cf2c62e0e640c226fe36b27e7307392a5610ccd (plain) (blame)
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
64
package setup

import (
	"os"
	"os/exec"
	"strings"

	"github.com/miekg/coredns/middleware"
)

// Startup registers a startup callback to execute during server start.
func Startup(c *Controller) (middleware.Middleware, error) {
	return nil, registerCallback(c, &c.FirstStartup)
}

// Shutdown registers a shutdown callback to execute during process exit.
func Shutdown(c *Controller) (middleware.Middleware, error) {
	return nil, registerCallback(c, &c.Shutdown)
}

// registerCallback registers a callback function to execute by
// using c to parse the line. It appends the callback function
// to the list of callback functions passed in by reference.
func registerCallback(c *Controller, list *[]func() error) error {
	var funcs []func() error

	for c.Next() {
		args := c.RemainingArgs()
		if len(args) == 0 {
			return c.ArgErr()
		}

		nonblock := false
		if len(args) > 1 && args[len(args)-1] == "&" {
			// Run command in background; non-blocking
			nonblock = true
			args = args[:len(args)-1]
		}

		command, args, err := middleware.SplitCommandAndArgs(strings.Join(args, " "))
		if err != nil {
			return c.Err(err.Error())
		}

		fn := func() error {
			cmd := exec.Command(command, args...)
			cmd.Stdin = os.Stdin
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr

			if nonblock {
				return cmd.Start()
			}
			return cmd.Run()
		}

		funcs = append(funcs, fn)
	}

	return c.OncePerServerBlock(func() error {
		*list = append(*list, funcs...)
		return nil
	})
}