-
Notifications
You must be signed in to change notification settings - Fork 54
/
plan.go
1249 lines (1151 loc) · 33.3 KB
/
plan.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2021 Canonical Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package plan
import (
"bytes"
"fmt"
"os"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/canonical/x-go/strutil/shlex"
"gopkg.in/yaml.v3"
"github.com/canonical/pebble/internals/logger"
"github.com/canonical/pebble/internals/osutil"
)
const (
defaultBackoffDelay = 500 * time.Millisecond
defaultBackoffFactor = 2.0
defaultBackoffLimit = 30 * time.Second
defaultCheckPeriod = 10 * time.Second
defaultCheckTimeout = 3 * time.Second
defaultCheckThreshold = 3
)
type Plan struct {
Layers []*Layer `yaml:"-"`
Services map[string]*Service `yaml:"services,omitempty"`
Checks map[string]*Check `yaml:"checks,omitempty"`
LogTargets map[string]*LogTarget `yaml:"log-targets,omitempty"`
}
type Layer struct {
Order int `yaml:"-"`
Label string `yaml:"-"`
Summary string `yaml:"summary,omitempty"`
Description string `yaml:"description,omitempty"`
Services map[string]*Service `yaml:"services,omitempty"`
Checks map[string]*Check `yaml:"checks,omitempty"`
LogTargets map[string]*LogTarget `yaml:"log-targets,omitempty"`
}
type Service struct {
// Basic details
Name string `yaml:"-"`
Summary string `yaml:"summary,omitempty"`
Description string `yaml:"description,omitempty"`
Startup ServiceStartup `yaml:"startup,omitempty"`
Override Override `yaml:"override,omitempty"`
Command string `yaml:"command,omitempty"`
// Service dependencies
After []string `yaml:"after,omitempty"`
Before []string `yaml:"before,omitempty"`
Requires []string `yaml:"requires,omitempty"`
// Options for command execution
Environment map[string]string `yaml:"environment,omitempty"`
UserID *int `yaml:"user-id,omitempty"`
User string `yaml:"user,omitempty"`
GroupID *int `yaml:"group-id,omitempty"`
Group string `yaml:"group,omitempty"`
WorkingDir string `yaml:"working-dir,omitempty"`
// Auto-restart and backoff functionality
OnSuccess ServiceAction `yaml:"on-success,omitempty"`
OnFailure ServiceAction `yaml:"on-failure,omitempty"`
OnCheckFailure map[string]ServiceAction `yaml:"on-check-failure,omitempty"`
BackoffDelay OptionalDuration `yaml:"backoff-delay,omitempty"`
BackoffFactor OptionalFloat `yaml:"backoff-factor,omitempty"`
BackoffLimit OptionalDuration `yaml:"backoff-limit,omitempty"`
KillDelay OptionalDuration `yaml:"kill-delay,omitempty"`
}
// Copy returns a deep copy of the service.
func (s *Service) Copy() *Service {
copied := *s
copied.After = append([]string(nil), s.After...)
copied.Before = append([]string(nil), s.Before...)
copied.Requires = append([]string(nil), s.Requires...)
if s.Environment != nil {
copied.Environment = make(map[string]string)
for k, v := range s.Environment {
copied.Environment[k] = v
}
}
if s.UserID != nil {
copied.UserID = copyIntPtr(s.UserID)
}
if s.GroupID != nil {
copied.GroupID = copyIntPtr(s.GroupID)
}
if s.OnCheckFailure != nil {
copied.OnCheckFailure = make(map[string]ServiceAction)
for k, v := range s.OnCheckFailure {
copied.OnCheckFailure[k] = v
}
}
return &copied
}
// Merge merges the fields set in other into s.
func (s *Service) Merge(other *Service) {
if other.Summary != "" {
s.Summary = other.Summary
}
if other.Description != "" {
s.Description = other.Description
}
if other.Startup != StartupUnknown {
s.Startup = other.Startup
}
if other.Command != "" {
s.Command = other.Command
}
if other.KillDelay.IsSet {
s.KillDelay = other.KillDelay
}
if other.UserID != nil {
s.UserID = copyIntPtr(other.UserID)
}
if other.User != "" {
s.User = other.User
}
if other.GroupID != nil {
s.GroupID = copyIntPtr(other.GroupID)
}
if other.Group != "" {
s.Group = other.Group
}
if other.WorkingDir != "" {
s.WorkingDir = other.WorkingDir
}
s.After = append(s.After, other.After...)
s.Before = append(s.Before, other.Before...)
s.Requires = append(s.Requires, other.Requires...)
for k, v := range other.Environment {
if s.Environment == nil {
s.Environment = make(map[string]string)
}
s.Environment[k] = v
}
if other.OnSuccess != "" {
s.OnSuccess = other.OnSuccess
}
if other.OnFailure != "" {
s.OnFailure = other.OnFailure
}
for k, v := range other.OnCheckFailure {
if s.OnCheckFailure == nil {
s.OnCheckFailure = make(map[string]ServiceAction)
}
s.OnCheckFailure[k] = v
}
if other.BackoffDelay.IsSet {
s.BackoffDelay = other.BackoffDelay
}
if other.BackoffFactor.IsSet {
s.BackoffFactor = other.BackoffFactor
}
if other.BackoffLimit.IsSet {
s.BackoffLimit = other.BackoffLimit
}
}
// Equal returns true when the two services are equal in value.
func (s *Service) Equal(other *Service) bool {
if s == other {
return true
}
return reflect.DeepEqual(s, other)
}
// ParseCommand returns a service command as two stream of strings.
// The base command is returned as a stream and the default arguments
// in [ ... ] group is returned as another stream.
func (s *Service) ParseCommand() (base, extra []string, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("cannot parse service %q command: %w", s.Name, err)
}
}()
args, err := shlex.Split(s.Command)
if err != nil {
return nil, nil, err
}
var inBrackets, gotBrackets bool
for idx, arg := range args {
if inBrackets {
if arg == "[" {
return nil, nil, fmt.Errorf("cannot nest [ ... ] groups")
}
if arg == "]" {
inBrackets = false
continue
}
extra = append(extra, arg)
continue
}
if gotBrackets {
return nil, nil, fmt.Errorf("cannot have any arguments after [ ... ] group")
}
if arg == "[" {
if idx == 0 {
return nil, nil, fmt.Errorf("cannot start command with [ ... ] group")
}
inBrackets = true
gotBrackets = true
continue
}
if arg == "]" {
return nil, nil, fmt.Errorf("cannot have ] outside of [ ... ] group")
}
base = append(base, arg)
}
return base, extra, nil
}
// CommandString returns a service command as a string after
// appending the arguments in "extra" to the command in "base"
func CommandString(base, extra []string) string {
output := shlex.Join(base)
if len(extra) > 0 {
output = output + " [ " + shlex.Join(extra) + " ]"
}
return output
}
// LogsTo returns true if the logs from s should be forwarded to target t.
func (s *Service) LogsTo(t *LogTarget) bool {
// Iterate backwards through t.Services until we find something matching
// s.Name.
for i := len(t.Services) - 1; i >= 0; i-- {
switch t.Services[i] {
case s.Name:
return true
case ("-" + s.Name):
return false
case "all":
return true
case "-all":
return false
}
}
// Nothing matching the service name, so it was not specified.
return false
}
type ServiceStartup string
const (
StartupUnknown ServiceStartup = ""
StartupEnabled ServiceStartup = "enabled"
StartupDisabled ServiceStartup = "disabled"
)
// Override specifies the layer override mechanism for an object.
type Override string
const (
UnknownOverride Override = ""
MergeOverride Override = "merge"
ReplaceOverride Override = "replace"
)
type ServiceAction string
const (
// Actions allowed in all contexts
ActionUnset ServiceAction = ""
ActionRestart ServiceAction = "restart"
ActionShutdown ServiceAction = "shutdown"
ActionIgnore ServiceAction = "ignore"
// Actions only allowed in specific contexts
ActionFailureShutdown ServiceAction = "failure-shutdown"
ActionSuccessShutdown ServiceAction = "success-shutdown"
)
// Check specifies configuration for a single health check.
type Check struct {
// Basic details
Name string `yaml:"-"`
Override Override `yaml:"override,omitempty"`
Level CheckLevel `yaml:"level,omitempty"`
// Common check settings
Period OptionalDuration `yaml:"period,omitempty"`
Timeout OptionalDuration `yaml:"timeout,omitempty"`
Threshold int `yaml:"threshold,omitempty"`
// Type-specific check settings (only one of these can be set)
HTTP *HTTPCheck `yaml:"http,omitempty"`
TCP *TCPCheck `yaml:"tcp,omitempty"`
Exec *ExecCheck `yaml:"exec,omitempty"`
}
// Copy returns a deep copy of the check configuration.
func (c *Check) Copy() *Check {
copied := *c
if c.HTTP != nil {
copied.HTTP = c.HTTP.Copy()
}
if c.TCP != nil {
copied.TCP = c.TCP.Copy()
}
if c.Exec != nil {
copied.Exec = c.Exec.Copy()
}
return &copied
}
// Merge merges the fields set in other into c.
func (c *Check) Merge(other *Check) {
if other.Level != "" {
c.Level = other.Level
}
if other.Period.IsSet {
c.Period = other.Period
}
if other.Timeout.IsSet {
c.Timeout = other.Timeout
}
if other.Threshold != 0 {
c.Threshold = other.Threshold
}
if other.HTTP != nil {
if c.HTTP == nil {
c.HTTP = &HTTPCheck{}
}
c.HTTP.Merge(other.HTTP)
}
if other.TCP != nil {
if c.TCP == nil {
c.TCP = &TCPCheck{}
}
c.TCP.Merge(other.TCP)
}
if other.Exec != nil {
if c.Exec == nil {
c.Exec = &ExecCheck{}
}
c.Exec.Merge(other.Exec)
}
}
// CheckLevel specifies the optional check level.
type CheckLevel string
const (
UnsetLevel CheckLevel = ""
AliveLevel CheckLevel = "alive"
ReadyLevel CheckLevel = "ready"
)
// HTTPCheck holds the configuration for an HTTP health check.
type HTTPCheck struct {
URL string `yaml:"url,omitempty"`
Headers map[string]string `yaml:"headers,omitempty"`
}
// Copy returns a deep copy of the HTTP check configuration.
func (c *HTTPCheck) Copy() *HTTPCheck {
copied := *c
if c.Headers != nil {
copied.Headers = make(map[string]string, len(c.Headers))
for k, v := range c.Headers {
copied.Headers[k] = v
}
}
return &copied
}
// Merge merges the fields set in other into c.
func (c *HTTPCheck) Merge(other *HTTPCheck) {
if other.URL != "" {
c.URL = other.URL
}
for k, v := range other.Headers {
if c.Headers == nil {
c.Headers = make(map[string]string)
}
c.Headers[k] = v
}
}
// TCPCheck holds the configuration for an HTTP health check.
type TCPCheck struct {
Port int `yaml:"port,omitempty"`
Host string `yaml:"host,omitempty"`
}
// Copy returns a deep copy of the TCP check configuration.
func (c *TCPCheck) Copy() *TCPCheck {
copied := *c
return &copied
}
// Merge merges the fields set in other into c.
func (c *TCPCheck) Merge(other *TCPCheck) {
if other.Port != 0 {
c.Port = other.Port
}
if other.Host != "" {
c.Host = other.Host
}
}
// ExecCheck holds the configuration for an exec health check.
type ExecCheck struct {
Command string `yaml:"command,omitempty"`
ServiceContext string `yaml:"service-context,omitempty"`
Environment map[string]string `yaml:"environment,omitempty"`
UserID *int `yaml:"user-id,omitempty"`
User string `yaml:"user,omitempty"`
GroupID *int `yaml:"group-id,omitempty"`
Group string `yaml:"group,omitempty"`
WorkingDir string `yaml:"working-dir,omitempty"`
}
// Copy returns a deep copy of the exec check configuration.
func (c *ExecCheck) Copy() *ExecCheck {
copied := *c
if c.Environment != nil {
copied.Environment = make(map[string]string, len(c.Environment))
for k, v := range c.Environment {
copied.Environment[k] = v
}
}
if c.UserID != nil {
copied.UserID = copyIntPtr(c.UserID)
}
if c.GroupID != nil {
copied.GroupID = copyIntPtr(c.GroupID)
}
return &copied
}
// Merge merges the fields set in other into c.
func (c *ExecCheck) Merge(other *ExecCheck) {
if other.Command != "" {
c.Command = other.Command
}
if other.ServiceContext != "" {
c.ServiceContext = other.ServiceContext
}
for k, v := range other.Environment {
if c.Environment == nil {
c.Environment = make(map[string]string)
}
c.Environment[k] = v
}
if other.UserID != nil {
c.UserID = copyIntPtr(other.UserID)
}
if other.User != "" {
c.User = other.User
}
if other.GroupID != nil {
c.GroupID = copyIntPtr(other.GroupID)
}
if other.Group != "" {
c.Group = other.Group
}
if other.WorkingDir != "" {
c.WorkingDir = other.WorkingDir
}
}
// LogTarget specifies a remote server to forward logs to.
type LogTarget struct {
Name string `yaml:"-"`
Type LogTargetType `yaml:"type"`
Location string `yaml:"location"`
Services []string `yaml:"services"`
Override Override `yaml:"override,omitempty"`
Labels map[string]string `yaml:"labels,omitempty"`
}
// LogTargetType defines the protocol to use to forward logs.
type LogTargetType string
const (
LokiTarget LogTargetType = "loki"
SyslogTarget LogTargetType = "syslog"
UnsetLogTarget LogTargetType = ""
)
// Copy returns a deep copy of the log target configuration.
func (t *LogTarget) Copy() *LogTarget {
copied := *t
copied.Services = append([]string(nil), t.Services...)
if t.Labels != nil {
copied.Labels = make(map[string]string)
for k, v := range t.Labels {
copied.Labels[k] = v
}
}
return &copied
}
// Merge merges the fields set in other into t.
func (t *LogTarget) Merge(other *LogTarget) {
if other.Type != "" {
t.Type = other.Type
}
if other.Location != "" {
t.Location = other.Location
}
t.Services = append(t.Services, other.Services...)
for k, v := range other.Labels {
if t.Labels == nil {
t.Labels = make(map[string]string)
}
t.Labels[k] = v
}
}
// FormatError is the error returned when a layer has a format error, such as
// a missing "override" field.
type FormatError struct {
Message string
}
func (e *FormatError) Error() string {
return e.Message
}
// CombineLayers combines the given layers into a single layer, with the later
// layers overriding earlier ones.
// Neither the individual layers nor the combined layer are validated here - the
// caller should have validated the individual layers prior to calling, and
// validate the combined output if required.
func CombineLayers(layers ...*Layer) (*Layer, error) {
combined := &Layer{
Services: make(map[string]*Service),
Checks: make(map[string]*Check),
LogTargets: make(map[string]*LogTarget),
}
if len(layers) == 0 {
return combined, nil
}
last := layers[len(layers)-1]
combined.Summary = last.Summary
combined.Description = last.Description
for _, layer := range layers {
for name, service := range layer.Services {
switch service.Override {
case MergeOverride:
if old, ok := combined.Services[name]; ok {
copied := old.Copy()
copied.Merge(service)
combined.Services[name] = copied
break
}
fallthrough
case ReplaceOverride:
combined.Services[name] = service.Copy()
case UnknownOverride:
return nil, &FormatError{
Message: fmt.Sprintf(`layer %q must define "override" for service %q`,
layer.Label, service.Name),
}
default:
return nil, &FormatError{
Message: fmt.Sprintf(`layer %q has invalid "override" value for service %q`,
layer.Label, service.Name),
}
}
}
for name, check := range layer.Checks {
switch check.Override {
case MergeOverride:
if old, ok := combined.Checks[name]; ok {
copied := old.Copy()
copied.Merge(check)
combined.Checks[name] = copied
break
}
fallthrough
case ReplaceOverride:
combined.Checks[name] = check.Copy()
case UnknownOverride:
return nil, &FormatError{
Message: fmt.Sprintf(`layer %q must define "override" for check %q`,
layer.Label, check.Name),
}
default:
return nil, &FormatError{
Message: fmt.Sprintf(`layer %q has invalid "override" value for check %q`,
layer.Label, check.Name),
}
}
}
for name, target := range layer.LogTargets {
switch target.Override {
case MergeOverride:
if old, ok := combined.LogTargets[name]; ok {
copied := old.Copy()
copied.Merge(target)
combined.LogTargets[name] = copied
break
}
fallthrough
case ReplaceOverride:
combined.LogTargets[name] = target.Copy()
case UnknownOverride:
return nil, &FormatError{
Message: fmt.Sprintf(`layer %q must define "override" for log target %q`,
layer.Label, target.Name),
}
default:
return nil, &FormatError{
Message: fmt.Sprintf(`layer %q has invalid "override" value for log target %q`,
layer.Label, target.Name),
}
}
}
}
// Set defaults where required.
for _, service := range combined.Services {
if !service.BackoffDelay.IsSet {
service.BackoffDelay.Value = defaultBackoffDelay
}
if !service.BackoffFactor.IsSet {
service.BackoffFactor.Value = defaultBackoffFactor
}
if !service.BackoffLimit.IsSet {
service.BackoffLimit.Value = defaultBackoffLimit
}
}
for _, check := range combined.Checks {
if !check.Period.IsSet {
check.Period.Value = defaultCheckPeriod
}
if !check.Timeout.IsSet {
check.Timeout.Value = defaultCheckTimeout
}
if check.Timeout.Value > check.Period.Value {
// The effective timeout will be the period, so make that clear.
// `.IsSet` remains false so that the capped value does not appear
// in the combined plan output - and it's not *user* set - the
// effective default timeout is the minimum of (check.Period.Value,
// default timeout).
check.Timeout.Value = check.Period.Value
}
if check.Threshold == 0 {
// Default number of failures in a row before check triggers
// action, default is >1 to avoid flapping due to glitches. For
// what it's worth, Kubernetes probes uses a default of 3 too.
check.Threshold = defaultCheckThreshold
}
}
return combined, nil
}
// Validate checks that the layer is valid. It returns nil if all the checks pass, or
// an error if there are validation errors.
// See also Plan.Validate, which does additional checks based on the combined
// layers.
func (layer *Layer) Validate() error {
if strings.HasPrefix(layer.Label, "pebble-") {
return &FormatError{
Message: `cannot use reserved label prefix "pebble-"`,
}
}
for name, service := range layer.Services {
if name == "" {
return &FormatError{
Message: fmt.Sprintf("cannot use empty string as service name"),
}
}
if name == "pebble" {
// Disallow service name "pebble" to avoid ambiguity (for example,
// in log output).
return &FormatError{
Message: fmt.Sprintf("cannot use reserved service name %q", name),
}
}
// Deprecated service names
if name == "all" || name == "default" || name == "none" {
logger.Noticef("Using keyword %q as a service name is deprecated", name)
}
if strings.HasPrefix(name, "-") {
return &FormatError{
Message: fmt.Sprintf(`cannot use service name %q: starting with "-" not allowed`, name),
}
}
if service == nil {
return &FormatError{
Message: fmt.Sprintf("service object cannot be null for service %q", name),
}
}
_, _, err := service.ParseCommand()
if err != nil {
return &FormatError{
Message: fmt.Sprintf("plan service %q command invalid: %v", name, err),
}
}
if !validServiceAction(service.OnSuccess, ActionFailureShutdown) {
return &FormatError{
Message: fmt.Sprintf("plan service %q on-success action %q invalid", name, service.OnSuccess),
}
}
if !validServiceAction(service.OnFailure, ActionSuccessShutdown) {
return &FormatError{
Message: fmt.Sprintf("plan service %q on-failure action %q invalid", name, service.OnFailure),
}
}
for _, action := range service.OnCheckFailure {
if !validServiceAction(action, ActionSuccessShutdown) {
return &FormatError{
Message: fmt.Sprintf("plan service %q on-check-failure action %q invalid", name, action),
}
}
}
if service.BackoffFactor.IsSet && service.BackoffFactor.Value < 1 {
return &FormatError{
Message: fmt.Sprintf("plan service %q backoff-factor must be 1.0 or greater, not %g", name, service.BackoffFactor.Value),
}
}
}
for name, check := range layer.Checks {
if name == "" {
return &FormatError{
Message: fmt.Sprintf("cannot use empty string as check name"),
}
}
if check == nil {
return &FormatError{
Message: fmt.Sprintf("check object cannot be null for check %q", name),
}
}
if name == "" {
return &FormatError{
Message: fmt.Sprintf("cannot use empty string as log target name"),
}
}
if check.Level != UnsetLevel && check.Level != AliveLevel && check.Level != ReadyLevel {
return &FormatError{
Message: fmt.Sprintf(`plan check %q level must be "alive" or "ready"`, name),
}
}
if check.Period.IsSet && check.Period.Value == 0 {
return &FormatError{
Message: fmt.Sprintf("plan check %q period must not be zero", name),
}
}
if check.Timeout.IsSet && check.Timeout.Value == 0 {
return &FormatError{
Message: fmt.Sprintf("plan check %q timeout must not be zero", name),
}
}
if check.Exec != nil {
_, err := shlex.Split(check.Exec.Command)
if err != nil {
return &FormatError{
Message: fmt.Sprintf("plan check %q command invalid: %v", name, err),
}
}
_, _, err = osutil.NormalizeUidGid(check.Exec.UserID, check.Exec.GroupID, check.Exec.User, check.Exec.Group)
if err != nil {
return &FormatError{
Message: fmt.Sprintf("plan check %q has invalid user/group: %v", name, err),
}
}
}
}
for name, target := range layer.LogTargets {
if target == nil {
return &FormatError{
Message: fmt.Sprintf("log target object cannot be null for log target %q", name),
}
}
for labelName := range target.Labels {
// 'pebble_*' labels are reserved
if strings.HasPrefix(labelName, "pebble_") {
return &FormatError{
Message: fmt.Sprintf(`log target %q: label %q uses reserved prefix "pebble_"`, name, labelName),
}
}
}
switch target.Type {
case LokiTarget, SyslogTarget:
// valid, continue
case UnsetLogTarget:
// will be checked when the layers are combined
default:
return &FormatError{
Message: fmt.Sprintf(`log target %q has unsupported type %q, must be %q or %q`,
name, target.Type, LokiTarget, SyslogTarget),
}
}
}
return nil
}
// Validate checks that the combined layers form a valid plan.
// See also Layer.Validate, which checks that the individual layers are valid.
func (p *Plan) Validate() error {
for name, service := range p.Services {
if service.Command == "" {
return &FormatError{
Message: fmt.Sprintf(`plan must define "command" for service %q`, name),
}
}
}
for name, check := range p.Checks {
numTypes := 0
if check.HTTP != nil {
if check.HTTP.URL == "" {
return &FormatError{
Message: fmt.Sprintf(`plan must set "url" for http check %q`, name),
}
}
numTypes++
}
if check.TCP != nil {
if check.TCP.Port == 0 {
return &FormatError{
Message: fmt.Sprintf(`plan must set "port" for tcp check %q`, name),
}
}
numTypes++
}
if check.Exec != nil {
if check.Exec.Command == "" {
return &FormatError{
Message: fmt.Sprintf(`plan must set "command" for exec check %q`, name),
}
}
_, contextExists := p.Services[check.Exec.ServiceContext]
if check.Exec.ServiceContext != "" && !contextExists {
return &FormatError{
Message: fmt.Sprintf("plan check %q service context specifies non-existent service %q",
name, check.Exec.ServiceContext),
}
}
numTypes++
}
if numTypes != 1 {
return &FormatError{
Message: fmt.Sprintf(`plan must specify one of "http", "tcp", or "exec" for check %q`, name),
}
}
}
for name, target := range p.LogTargets {
switch target.Type {
case LokiTarget, SyslogTarget:
// valid, continue
case UnsetLogTarget:
return &FormatError{
Message: fmt.Sprintf(`plan must define "type" (%q or %q) for log target %q`,
LokiTarget, SyslogTarget, name),
}
}
// Validate service names specified in log target.
for _, serviceName := range target.Services {
serviceName = strings.TrimPrefix(serviceName, "-")
if serviceName == "all" {
continue
}
if _, ok := p.Services[serviceName]; ok {
continue
}
return &FormatError{
Message: fmt.Sprintf(`log target %q specifies unknown service %q`,
target.Name, serviceName),
}
}
if target.Location == "" {
return &FormatError{
Message: fmt.Sprintf(`plan must define "location" for log target %q`, name),
}
}
}
// Ensure combined layers don't have cycles.
err := p.checkCycles()
if err != nil {
return err
}
return nil
}
// StartOrder returns the required services that must be started for the named
// services to be properly started, in the order that they must be started.
// An error is returned when a provided service name does not exist, or there
// is an order cycle involving the provided service or its dependencies.
func (p *Plan) StartOrder(names []string) ([]string, error) {
return order(p.Services, names, false)
}
// StopOrder returns the required services that must be stopped for the named
// services to be properly stopped, in the order that they must be stopped.
// An error is returned when a provided service name does not exist, or there
// is an order cycle involving the provided service or its dependencies.
func (p *Plan) StopOrder(names []string) ([]string, error) {
return order(p.Services, names, true)
}
func order(services map[string]*Service, names []string, stop bool) ([]string, error) {
// For stop, create a list of reversed dependencies.
predecessors := map[string][]string(nil)
if stop {
predecessors = make(map[string][]string)
for name, service := range services {
for _, req := range service.Requires {
predecessors[req] = append(predecessors[req], name)
}
}
}
// Collect all services that will be started or stopped.
successors := map[string][]string{}
pending := append([]string(nil), names...)
for i := 0; i < len(pending); i++ {
name := pending[i]
if _, seen := successors[name]; seen {
continue
}
successors[name] = nil
if stop {
pending = append(pending, predecessors[name]...)
} else {
service, ok := services[name]
if !ok {
return nil, &FormatError{
Message: fmt.Sprintf("service %q does not exist", name),
}
}
pending = append(pending, service.Requires...)
}
}
// Create a list of successors involving those services only.
for name := range successors {
service, ok := services[name]
if !ok {
return nil, &FormatError{
Message: fmt.Sprintf("service %q does not exist", name),
}
}
succs := successors[name]
serviceAfter := service.After
serviceBefore := service.Before
if stop {
serviceAfter, serviceBefore = serviceBefore, serviceAfter
}
for _, after := range serviceAfter {
if _, required := successors[after]; required {
succs = append(succs, after)
}
}
successors[name] = succs
for _, before := range serviceBefore {
if succs, required := successors[before]; required {
successors[before] = append(succs, name)
}
}
}
// Sort them up.