summaryrefslogtreecommitdiff
path: root/internal/cli/reset/command.go
blob: 0c9176f6c2133cfa1cf96611a04a0884d533be84 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package reset

import (
	"log"
	"sync"

	internalRpc "github.com/roadrunner-server/roadrunner/v2024/internal/rpc"
	"github.com/roadrunner-server/roadrunner/v2024/internal/sdnotify"

	"github.com/roadrunner-server/errors"
	"github.com/spf13/cobra"
)

const (
	op            = errors.Op("reset_handler")
	resetterList  = "resetter.List"
	resetterReset = "resetter.Reset"
)

// NewCommand creates `reset` command.
func NewCommand(cfgFile *string, override *[]string, silent *bool) *cobra.Command {
	return &cobra.Command{
		Use:   "reset",
		Short: "Reset workers of all or specific RoadRunner service",
		RunE: func(_ *cobra.Command, args []string) error {
			if cfgFile == nil {
				return errors.E(op, errors.Str("no configuration file provided"))
			}

			client, err := internalRpc.NewClient(*cfgFile, *override)
			if err != nil {
				return err
			}

			defer func() { _ = client.Close() }()

			plugins := args        // by default, we expect services list from user
			if len(plugins) == 0 { // but if nothing was passed - request all services list
				if err = client.Call(resetterList, true, &plugins); err != nil {
					return err
				}
			}

			_, _ = sdnotify.SdNotify(sdnotify.Reloading)

			var wg sync.WaitGroup
			wg.Add(len(plugins))

			for _, plugin := range plugins {
				// simulating some work
				go func(p string) {
					if !*silent {
						log.Printf("resetting plugin: [%s] ", p)
					}
					defer wg.Done()

					var done bool
					<-client.Go(resetterReset, p, &done, nil).Done

					if err != nil {
						log.Println(err)

						return
					}

					if !*silent {
						log.Printf("plugin reset: [%s]", p)
					}
				}(plugin)
			}

			wg.Wait()

			_, _ = sdnotify.SdNotify(sdnotify.Ready)

			return nil
		},
	}
}