summaryrefslogtreecommitdiff
path: root/internal/cli/reset/command.go
blob: a0634c3195106e6191984c6811e3e586653b0776 (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package reset

import (
	"fmt"
	"sync"

	internalRpc "github.com/roadrunner-server/roadrunner/v2/internal/rpc"

	"github.com/fatih/color"
	"github.com/mattn/go-runewidth"
	"github.com/roadrunner-server/errors"
	"github.com/spf13/cobra"
	"github.com/vbauerster/mpb/v5"
	"github.com/vbauerster/mpb/v5/decor"
)

var spinnerStyle = []string{"∙∙∙", "●∙∙", "∙●∙", "∙∙●", "∙∙∙"} //nolint:gochecknoglobals

// NewCommand creates `reset` command.
func NewCommand(cfgFile *string) *cobra.Command { //nolint:funlen
	return &cobra.Command{
		Use:   "reset",
		Short: "Reset workers of all or specific RoadRunner service",
		RunE: func(_ *cobra.Command, args []string) error {
			const (
				op            = errors.Op("reset_handler")
				resetterList  = "resetter.List"
				resetterReset = "resetter.Reset"
			)

			if cfgFile == nil {
				return errors.E(op, errors.Str("no configuration file provided"))
			}

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

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

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

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

			pr := mpb.New(mpb.WithWaitGroup(&wg), mpb.WithWidth(6)) //nolint:gomnd

			for _, service := range services {
				var (
					bar    *mpb.Bar
					name   = runewidth.FillRight(fmt.Sprintf("Resetting plugin: [%s]", color.HiYellowString(service)), 27)
					result = make(chan interface{})
				)

				bar = pr.AddSpinner(
					1,
					mpb.SpinnerOnMiddle,
					mpb.SpinnerStyle(spinnerStyle),
					mpb.PrependDecorators(decor.Name(name)),
					mpb.AppendDecorators(onComplete(result)),
				)

				// simulating some work
				go func(service string, result chan interface{}) {
					defer wg.Done()
					defer bar.Increment()

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

					if err != nil {
						result <- errors.E(op, err)

						return
					}

					result <- nil
				}(service, result)
			}

			pr.Wait()

			return nil
		},
	}
}

func onComplete(result chan interface{}) decor.Decorator {
	return decor.Any(func(s decor.Statistics) string {
		select {
		case r := <-result:
			if err, ok := r.(error); ok {
				return color.HiRedString(err.Error())
			}

			return color.HiGreenString("done")
		default:
			return ""
		}
	})
}