-
Notifications
You must be signed in to change notification settings - Fork 3
/
config.go
371 lines (332 loc) · 11.1 KB
/
config.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package shimesaba
import (
"errors"
"fmt"
"log"
"path/filepath"
"strconv"
"strings"
"time"
gv "github.com/hashicorp/go-version"
gc "github.com/kayac/go-config"
"github.com/mashiike/shimesaba/internal/timeutils"
)
// Config for App
type Config struct {
RequiredVersion string `yaml:"required_version" json:"required_version"`
SLOConfig `yaml:"-,inline" json:"-,inline"`
SLO []*SLOConfig `yaml:"slo" json:"slo"`
configFilePath string
versionConstraints gv.Constraints
}
// SLOConfig is a setting related to SLI/SLO
type SLOConfig struct {
ID string `json:"id" yaml:"id"`
RollingPeriod string `yaml:"rolling_period" json:"rolling_period"`
Destination *DestinationConfig `yaml:"destination" json:"destination"`
ErrorBudgetSize interface{} `yaml:"error_budget_size" json:"error_budget_size"`
AlertBasedSLI []*AlertBasedSLIConfig `json:"alert_based_sli" yaml:"alert_based_sli"`
CalculateInterval string `yaml:"calculate_interval" json:"calculate_interval"`
rollingPeriod time.Duration
errorBudgetSizePercentage float64
calculateInterval time.Duration
}
// DestinationConfig is a configuration for submitting service metrics to Mackerel
type DestinationConfig struct {
ServiceName string `json:"service_name" yaml:"service_name"`
MetricPrefix string `json:"metric_prefix" yaml:"metric_prefix"`
MetricSuffix string `json:"metric_suffix" yaml:"metric_suffix"`
Metrics map[string]*DestinationMetricConfig `json:"metrics" yaml:"metrics"`
}
type DestinationMetricConfig struct {
MetricTypeName string `json:"metric_type_name,omitempty" yaml:"metric_type_name,omitempty"`
Enabled *bool `json:"enabled,omitempty" yaml:"enabled,omitempty"`
}
type AlertBasedSLIConfig struct {
MonitorID string `json:"monitor_id,omitempty" yaml:"monitor_id,omitempty"`
MonitorName string `json:"monitor_name,omitempty" yaml:"monitor_name,omitempty"`
MonitorNamePrefix string `json:"monitor_name_prefix,omitempty" yaml:"monitor_name_prefix,omitempty"`
MonitorNameSuffix string `json:"monitor_name_suffix,omitempty" yaml:"monitor_name_suffix,omitempty"`
MonitorType string `json:"monitor_type,omitempty" yaml:"monitor_type,omitempty"`
TryReassessment bool `json:"try_reassessment,omitempty" yaml:"try_reassessment,omitempty"`
}
const (
defaultMetricPrefix = "shimesaba"
)
// NewDefaultConfig creates a default configuration.
func NewDefaultConfig() *Config {
return &Config{
SLOConfig: SLOConfig{
RollingPeriod: "28d",
Destination: &DestinationConfig{
MetricPrefix: defaultMetricPrefix,
},
CalculateInterval: "1h",
},
}
}
// Load loads configuration file from file paths.
func (c *Config) Load(paths ...string) error {
if len(paths) == 0 {
return errors.New("no config")
}
if err := gc.LoadWithEnv(c, paths...); err != nil {
return err
}
c.configFilePath = filepath.Dir(paths[len(paths)-1])
return c.Restrict()
}
// Restrict restricts a configuration.
func (c *Config) Restrict() error {
if c.RequiredVersion != "" {
constraints, err := gv.NewConstraint(c.RequiredVersion)
if err != nil {
return fmt.Errorf("required_version has invalid format: %w", err)
}
c.versionConstraints = constraints
}
if len(c.SLO) == 0 {
return errors.New("slo definition not found")
}
sloIDs := make(map[string]struct{}, len(c.SLO))
for i, cfg := range c.SLO {
mergedCfg := c.SLOConfig.Merge(cfg)
if _, ok := sloIDs[mergedCfg.ID]; ok {
return fmt.Errorf("slo id=%s is duplicated", mergedCfg.ID)
}
c.SLO[i] = mergedCfg
if err := mergedCfg.Restrict(); err != nil {
return fmt.Errorf("slo[%s] is invalid: %w", mergedCfg.ID, err)
}
}
return nil
}
// Restrict restricts a definition configuration.
func (c *SLOConfig) Restrict() error {
if c.ID == "" {
return errors.New("id is required")
}
if c.RollingPeriod == "" {
return errors.New("rolling_period is required")
}
var err error
c.rollingPeriod, err = timeutils.ParseDuration(c.RollingPeriod)
if err != nil {
return fmt.Errorf("rolling_period is invalid format: %w", err)
}
if c.rollingPeriod < time.Minute {
return fmt.Errorf("rolling_period must over or equal 1m")
}
if c.Destination == nil {
return errors.New("destination is not configured")
}
if err := c.Destination.Restrict(c.ID); err != nil {
return fmt.Errorf("destination %w", err)
}
if errorBudgetSizePercentage, ok := c.ErrorBudgetSize.(float64); ok {
log.Printf("[warn] make sure to set it in m with units. example %f%%", errorBudgetSizePercentage*100.0)
c.errorBudgetSizePercentage = errorBudgetSizePercentage
}
if errorBudgetSizeString, ok := c.ErrorBudgetSize.(string); ok {
if strings.ContainsRune(errorBudgetSizeString, '%') {
value, err := strconv.ParseFloat(strings.TrimRight(errorBudgetSizeString, `%`), 64)
if err != nil {
return fmt.Errorf("error_budget can not parse as percentage: %w", err)
}
c.errorBudgetSizePercentage = value / 100.0
} else {
errorBudgetSizeDuration, err := timeutils.ParseDuration(errorBudgetSizeString)
if err != nil {
return fmt.Errorf("error_budget can not parse as duration: %w", err)
}
if errorBudgetSizeDuration >= c.rollingPeriod || errorBudgetSizeDuration == 0 {
return fmt.Errorf("error_budget must between %s and 0m", c.rollingPeriod)
}
c.errorBudgetSizePercentage = float64(errorBudgetSizeDuration) / float64(c.rollingPeriod)
}
}
if c.errorBudgetSizePercentage >= 1.0 || c.errorBudgetSizePercentage <= 0.0 {
return errors.New("error_budget must between 1.0 and 0.0")
}
for i, alertBasedSLI := range c.AlertBasedSLI {
if err := alertBasedSLI.Restrict(); err != nil {
return fmt.Errorf("alert_based_sli[%d] %w", i, err)
}
}
if c.CalculateInterval == "" {
return errors.New("calculate_interval is required")
}
c.calculateInterval, err = timeutils.ParseDuration(c.CalculateInterval)
if err != nil {
return fmt.Errorf("calculate_interval is invalid format: %w", err)
}
if c.calculateInterval < time.Minute {
return fmt.Errorf("calculate_interval must over or equal 1m")
}
if c.calculateInterval >= 24*time.Hour {
log.Printf("[warn] We do not recommend calculate_interval=`%s` setting. because can not post service metrics older than 24 hours to Mackerel.\n", c.CalculateInterval)
}
return nil
}
// Restrict restricts a definition configuration.
func (c *DestinationConfig) Restrict(sloID string) error {
if c.ServiceName == "" {
return errors.New("service_name is required")
}
if c.MetricPrefix == "" {
log.Printf("[debug] metric_prefix is empty, fallback %s", defaultMetricPrefix)
c.MetricPrefix = defaultMetricPrefix
}
if c.MetricSuffix == "" {
log.Printf("[debug] metric_suffix is empty, fallback %s", sloID)
c.MetricSuffix = sloID
}
if c.Metrics == nil {
c.Metrics = make(map[string]*DestinationMetricConfig)
}
keys := DestinationMetricTypeValues()
for _, key := range keys {
metricCfg, ok := c.Metrics[key.ID()]
if !ok {
metricCfg = &DestinationMetricConfig{}
}
if err := metricCfg.Restrict(key); err != nil {
return fmt.Errorf("metrics `%s`: %w", key.ID(), err)
}
c.Metrics[key.ID()] = metricCfg
}
return nil
}
// Restrict restricts a definition configuration.
func (c *DestinationMetricConfig) Restrict(t DestinationMetricType) error {
if c.MetricTypeName == "" {
c.MetricTypeName = t.DefaultTypeName()
}
if c.Enabled == nil {
enabled := t.DefaultEnabled()
c.Enabled = &enabled
}
return nil
}
// Restrict restricts a configuration.
func (c *AlertBasedSLIConfig) Restrict() error {
if c.MonitorID != "" {
return nil
}
if c.MonitorName != "" {
return nil
}
if c.MonitorNamePrefix != "" {
return nil
}
if c.MonitorNameSuffix != "" {
return nil
}
if c.MonitorType != "" {
return nil
}
return errors.New("either monitor_id, monitor_name, monitor_name_prefix, monitor_name_suffix or monitor_type is required")
}
// Merge merges SLOConfig together
func (c *SLOConfig) Merge(o *SLOConfig) *SLOConfig {
ret := &SLOConfig{
ID: coalesceString(o.ID, c.ID),
RollingPeriod: coalesceString(o.RollingPeriod, c.RollingPeriod),
Destination: c.Destination.Merge(o.Destination),
ErrorBudgetSize: c.ErrorBudgetSize,
CalculateInterval: coalesceString(o.CalculateInterval, c.CalculateInterval),
}
if o.ErrorBudgetSize != nil {
ret.ErrorBudgetSize = o.ErrorBudgetSize
}
ret.AlertBasedSLI = append(ret.AlertBasedSLI, c.AlertBasedSLI...)
ret.AlertBasedSLI = append(ret.AlertBasedSLI, o.AlertBasedSLI...)
return ret
}
// Merge merges DestinationConfig together
func (c *DestinationConfig) Merge(o *DestinationConfig) *DestinationConfig {
if o == nil {
o = &DestinationConfig{}
}
ret := &DestinationConfig{
ServiceName: coalesceString(o.ServiceName, c.ServiceName),
MetricPrefix: coalesceString(o.MetricPrefix, c.MetricPrefix),
MetricSuffix: coalesceString(o.MetricSuffix, c.MetricSuffix),
}
keys := DestinationMetricTypeValues()
metrics := make(map[string]*DestinationMetricConfig, len(keys))
base := c.Metrics
if base == nil {
base = make(map[string]*DestinationMetricConfig)
}
if o.Metrics != nil {
for _, key := range keys {
metricCfg, ok := base[key.ID()]
if !ok {
metricCfg = &DestinationMetricConfig{}
}
metrics[key.ID()] = metricCfg.Merge(o.Metrics[key.ID()])
}
} else {
metrics = base
}
ret.Metrics = metrics
return ret
}
// Merge merges DestinationMetricConfig together
func (c *DestinationMetricConfig) Merge(o *DestinationMetricConfig) *DestinationMetricConfig {
if o == nil {
o = &DestinationMetricConfig{}
}
ret := &DestinationMetricConfig{
MetricTypeName: coalesceString(o.MetricTypeName, c.MetricTypeName),
Enabled: coalesce(o.Enabled, c.Enabled),
}
return ret
}
// ValidateVersion validates a version satisfies required_version.
func (c *Config) ValidateVersion(version string) error {
if c.versionConstraints == nil {
log.Println("[warn] required_version is empty. Skip checking required_version.")
return nil
}
versionParts := strings.SplitN(version, "-", 2)
v, err := gv.NewVersion(versionParts[0])
if err != nil {
log.Printf("[warn]: Invalid version format \"%s\". Skip checking required_version.", version)
// invalid version string (e.g. "current") always allowed
return nil
}
if !c.versionConstraints.Check(v) {
return fmt.Errorf("version %s does not satisfy constraints required_version: %s", version, c.versionConstraints)
}
return nil
}
// DurationRollingPeriod converts RollingPeriod as time.Duration
func (c *SLOConfig) DurationRollingPeriod() time.Duration {
return c.rollingPeriod
}
// DurationCalculate converts CalculateInterval as time.Duration
func (c *SLOConfig) DurationCalculate() time.Duration {
return c.calculateInterval
}
func (c *SLOConfig) ErrorBudgetSizePercentage() float64 {
return c.errorBudgetSizePercentage
}
func coalesceString(strs ...string) string {
for _, str := range strs {
if str != "" {
return str
}
}
return ""
}
func coalesce[T any](elements ...*T) *T {
for _, element := range elements {
if element != nil {
ret := *element
return &ret
}
}
return nil
}