-
Notifications
You must be signed in to change notification settings - Fork 0
/
sequence_settings.go
97 lines (83 loc) · 2.57 KB
/
sequence_settings.go
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
package goservices
import (
"fmt"
"github.com/qdm12/goservices/hooks"
)
// SequenceSettings contains settings for a sequence of services.
type SequenceSettings struct {
// Name is the sequence name, used for hooks and errors.
Name string
// ServicesStart specifies an order of services
// to start and must be set.
ServicesStart []Service
// ServicesStart specifies an order of services
// to stop and must be set.
ServicesStop []Service
// Hooks are hooks to call when starting and stopping
// each service. It defaults to a noop hooks
// implementation.
Hooks Hooks
}
// setDefaults sets the defaults for the sequence settings.
func (s *SequenceSettings) setDefaults() {
if s.Hooks == nil {
s.Hooks = hooks.NewNoop()
}
}
// validate validates the sequence settings.
func (s SequenceSettings) validate() (err error) {
switch {
case len(s.ServicesStart) == 0:
return fmt.Errorf("%w", ErrNoServiceStart)
case len(s.ServicesStop) == 0:
return fmt.Errorf("%w", ErrNoServiceStop)
case len(s.ServicesStart) != len(s.ServicesStop):
return fmt.Errorf("%w: %d services to start (%s) and %d services to stop (%s)",
ErrServicesStartStopMismatch, len(s.ServicesStart), andServiceStrings(s.ServicesStart),
len(s.ServicesStop), andServiceStrings(s.ServicesStop))
}
for i, service := range s.ServicesStart {
if service == nil {
return fmt.Errorf("service to start at index %d: %w", i, ErrServiceIsNil)
}
}
for i, service := range s.ServicesStop {
if service == nil {
return fmt.Errorf("service to stop at index %d: %w", i, ErrServiceIsNil)
}
}
errMessage := validateServicesStartStopMatch(s.ServicesStart, s.ServicesStop)
if errMessage != "" {
return fmt.Errorf("%w: %s", ErrServicesStartStopMismatch, errMessage)
}
errMessage = validateServicesAreUnique(s.ServicesStart)
if errMessage != "" {
return fmt.Errorf("%w: %s", ErrServicesNotUnique, errMessage)
}
return nil
}
func validateServicesStartStopMatch(servicesStart, servicesStop []Service) (errMessage string) {
match := true
for _, serviceStart := range servicesStart {
serviceStartFound := false
for _, serviceStop := range servicesStop {
if serviceStart == serviceStop {
serviceStartFound = true
break
}
}
if !serviceStartFound {
match = false
break
}
}
if match {
return ""
}
if len(servicesStart) == 1 {
return fmt.Sprintf("service to start %s is not the service to stop %s",
servicesStart[0], servicesStop[0])
}
return fmt.Sprintf("services to start %s are not the services to stop %s",
andServiceStrings(servicesStart), andServiceStrings(servicesStop))
}