-
Notifications
You must be signed in to change notification settings - Fork 781
/
Copy pathrunner.go
1305 lines (1110 loc) · 41.1 KB
/
runner.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
package manager
import (
"encoding/json"
"fmt"
"io"
"log"
"os"
"strconv"
"sync"
"time"
"github.com/hashicorp/consul-template/child"
"github.com/hashicorp/consul-template/config"
dep "github.com/hashicorp/consul-template/dependency"
"github.com/hashicorp/consul-template/renderer"
"github.com/hashicorp/consul-template/template"
"github.com/hashicorp/consul-template/watch"
multierror "github.com/hashicorp/go-multierror"
shellwords "github.com/mattn/go-shellwords"
"github.com/pkg/errors"
)
const (
// saneViewLimit is the number of views that we consider "sane" before we
// warn the user that they might be DDoSing their Consul cluster.
saneViewLimit = 128
)
// Runner responsible rendering Templates and invoking Commands.
type Runner struct {
// ErrCh and DoneCh are channels where errors and finish notifications occur.
ErrCh chan error
DoneCh chan struct{}
// config is the Config that created this Runner. It is used internally to
// construct other objects and pass data.
config *config.Config
// signals sending output to STDOUT instead of to a file.
dry bool
// outStream and errStream are the io.Writer streams where the runner will
// write information. These can be modified by calling SetOutStream and
// SetErrStream accordingly.
// inStream is the ioReader where the runner will read information.
outStream, errStream io.Writer
inStream io.Reader
// ctemplatesMap is a map of each template ID to the TemplateConfigs
// that made it.
ctemplatesMap map[string]config.TemplateConfigs
// templates is the list of calculated templates.
templates []*template.Template
// renderEvents is a mapping of a template ID to the render event.
renderEvents map[string]*RenderEvent
// renderEventLock protects access into the renderEvents map
renderEventsLock sync.RWMutex
// renderedCh is used to signal that a template has been rendered
renderedCh chan struct{}
// renderEventCh is used to signal that there is a new render event. A
// render event doesn't necessarily mean that a template has been rendered,
// only that templates attempted to render and may have updated their
// dependency sets.
renderEventCh chan struct{}
// dependencies is the list of dependencies this runner is watching.
dependencies map[string]dep.Dependency
// dependenciesLock is a lock around touching the dependencies map.
dependenciesLock sync.Mutex
// watcher is the watcher this runner is using.
watcher *watch.Watcher
// brain is the internal storage database of returned dependency data.
brain *template.Brain
// child is the child process under management. This may be nil if not running
// in exec mode.
child *child.Child
// childLock is the internal lock around the child process.
childLock sync.RWMutex
// quiescenceMap is the map of templates to their quiescence timers.
// quiescenceCh is the channel where templates report returns from quiescence
// fires.
quiescenceMap map[string]*quiescence
quiescenceCh chan *template.Template
// dedup is the deduplication manager if enabled
dedup *DedupManager
// Env represents a custom set of environment variables to populate the
// template and command runtime with. These environment variables will be
// available in both the command's environment as well as the template's
// environment.
Env map[string]string
// stopLock is the lock around checking if the runner can be stopped
stopLock sync.Mutex
// stopped is a boolean of whether the runner is stopped
stopped bool
}
// RenderEvent captures the time and events that occurred for a template
// rendering.
type RenderEvent struct {
// Missing is the list of dependencies that we do not yet have data for, but
// are contained in the watcher. This is different from unwatched dependencies,
// which includes dependencies the watcher has not yet started querying for
// data.
MissingDeps *dep.Set
// Template is the template attempting to be rendered.
Template *template.Template
// Contents is the raw, rendered contents from the template.
Contents []byte
// TemplateConfigs is the list of template configs that correspond to this
// template.
TemplateConfigs []*config.TemplateConfig
// Unwatched is the list of dependencies that are not present in the watcher.
// This value may change over time due to the n-pass evaluation.
UnwatchedDeps *dep.Set
// UpdatedAt is the last time this render event was updated.
UpdatedAt time.Time
// Used is the full list of dependencies seen in the template. Because of
// the n-pass evaluation, this number can change over time. The dependencies
// in this list may or may not have data. This just contains the list of all
// dependencies parsed out of the template with the current data.
UsedDeps *dep.Set
// WouldRender determines if the template would have been rendered. A template
// would have been rendered if all the dependencies are satisfied, but may
// not have actually rendered if the file was already present or if an error
// occurred when trying to write the file.
WouldRender bool
// LastWouldRender marks the last time the template would have rendered.
LastWouldRender time.Time
// DidRender determines if the Template was actually written to disk. In dry
// mode, this will always be false, since templates are not written to disk
// in dry mode. A template is only rendered to disk if all dependencies are
// satisfied and the template is not already in place with the same contents.
DidRender bool
// LastDidRender marks the last time the template was written to disk.
LastDidRender time.Time
// ForQuiescence determines if this event is returned early in the
// render loop due to quiescence. When evaluating if all templates have
// been rendered we need to know if the event is triggered by quiesence
// and if we can skip evaluating it as a render event for those purposes
ForQuiescence bool
}
// NewRunner accepts a slice of TemplateConfigs and returns a pointer to the new
// Runner and any error that occurred during creation.
func NewRunner(config *config.Config, dry bool) (*Runner, error) {
log.Printf("[INFO] (runner) creating new runner (dry: %v, once: %v)",
dry, config.Once)
runner := &Runner{
config: config,
dry: dry,
}
if err := runner.init(); err != nil {
return nil, err
}
return runner, nil
}
// Start begins the polling for this runner. Any errors that occur will cause
// this function to push an item onto the runner's error channel and the halt
// execution. This function is blocking and should be called as a goroutine.
func (r *Runner) Start() {
log.Printf("[INFO] (runner) starting")
// Create the pid before doing anything.
if err := r.storePid(); err != nil {
r.ErrCh <- err
return
}
// Start the de-duplication manager
var dedupCh <-chan struct{}
if r.dedup != nil {
if err := r.dedup.Start(); err != nil {
r.ErrCh <- err
return
}
dedupCh = r.dedup.UpdateCh()
}
// Setup the child process exit channel
var childExitCh <-chan int
// Fire an initial run to parse all the templates and setup the first-pass
// dependencies. This also forces any templates that have no dependencies to
// be rendered immediately (since they are already renderable).
log.Printf("[DEBUG] (runner) running initial templates")
if err := r.Run(); err != nil {
r.ErrCh <- err
return
}
for {
// Warn the user if they are watching too many dependencies.
if r.watcher.Size() > saneViewLimit {
log.Printf("[WARN] (runner) watching %d dependencies - watching this "+
"many dependencies could DDoS your consul cluster", r.watcher.Size())
} else {
log.Printf("[DEBUG] (runner) watching %d dependencies", r.watcher.Size())
}
if r.allTemplatesRendered() {
log.Printf("[DEBUG] (runner) all templates rendered")
// Enable quiescence for all templates if we have specified wait
// intervals.
NEXT_Q:
for _, t := range r.templates {
if _, ok := r.quiescenceMap[t.ID()]; ok {
continue NEXT_Q
}
for _, c := range r.templateConfigsFor(t) {
if *c.Wait.Enabled {
log.Printf("[DEBUG] (runner) enabling template-specific "+
"quiescence for %q", t.ID())
r.quiescenceMap[t.ID()] = newQuiescence(
r.quiescenceCh, *c.Wait.Min, *c.Wait.Max, t)
continue NEXT_Q
}
}
if *r.config.Wait.Enabled {
log.Printf("[DEBUG] (runner) enabling global quiescence for %q",
t.ID())
r.quiescenceMap[t.ID()] = newQuiescence(
r.quiescenceCh, *r.config.Wait.Min, *r.config.Wait.Max, t)
continue NEXT_Q
}
}
// If an exec command was given and a command is not currently running,
// spawn the child process for supervision.
if config.StringPresent(r.config.Exec.Command) {
// Lock the child because we are about to check if it exists.
r.childLock.Lock()
log.Printf("[TRACE] (runner) acquired child lock for command, spawning")
if r.child == nil {
env := r.config.Exec.Env.Copy()
env.Custom = append(r.childEnv(), env.Custom...)
child, err := spawnChild(&spawnChildInput{
Stdin: r.inStream,
Stdout: r.outStream,
Stderr: r.errStream,
Command: config.StringVal(r.config.Exec.Command),
Env: env.Env(),
ReloadSignal: config.SignalVal(r.config.Exec.ReloadSignal),
KillSignal: config.SignalVal(r.config.Exec.KillSignal),
KillTimeout: config.TimeDurationVal(r.config.Exec.KillTimeout),
Splay: config.TimeDurationVal(r.config.Exec.Splay),
})
if err != nil {
r.ErrCh <- err
r.childLock.Unlock()
return
}
r.child = child
}
// Unlock the child, we are done now.
r.childLock.Unlock()
// It's possible that we didn't start a process, in which case no
// channel is returned. If we did get a new exitCh, that means a child
// was spawned, so we need to watch a new exitCh. It is also possible
// that during a run, the child process was restarted, which means a
// new exit channel should be used.
nexitCh := r.child.ExitCh()
if nexitCh != nil {
childExitCh = nexitCh
}
}
// If we are running in once mode and all our templates are rendered,
// then we should exit here.
if r.config.Once {
log.Printf("[INFO] (runner) once mode and all templates rendered")
if r.child != nil {
r.stopDedup()
r.stopWatcher()
log.Printf("[INFO] (runner) waiting for child process to exit")
select {
case c := <-childExitCh:
log.Printf("[INFO] (runner) child process died")
r.ErrCh <- NewErrChildDied(c)
return
case <-r.DoneCh:
}
}
r.Stop()
return
}
}
OUTER:
select {
case view := <-r.watcher.DataCh():
// Receive this update
r.Receive(view.Dependency(), view.Data())
// Drain all dependency data. Given a large number of dependencies, it is
// feasible that we have data for more than one of them. Instead of
// wasting CPU cycles rendering templates when we have more dependencies
// waiting to be added to the brain, we drain the entire buffered channel
// on the watcher and then reports when it is done receiving new data
// which the parent select listens for.
//
// Please see https://github.com/hashicorp/consul-template/issues/168 for
// more information about this optimization and the entire backstory.
for {
select {
case view := <-r.watcher.DataCh():
r.Receive(view.Dependency(), view.Data())
default:
break OUTER
}
}
case <-dedupCh:
// We may get triggered by the de-duplication manager for either a change
// in leadership (acquired or lost lock), or an update of data for a template
// that we are watching.
log.Printf("[INFO] (runner) watcher triggered by de-duplication manager")
break OUTER
case err := <-r.watcher.ErrCh():
// Push the error back up the stack
log.Printf("[ERR] (runner) watcher reported error: %s", err)
r.ErrCh <- err
return
case tmpl := <-r.quiescenceCh:
// Remove the quiescence for this template from the map. This will force
// the upcoming Run call to actually evaluate and render the template.
log.Printf("[DEBUG] (runner) received template %q from quiescence", tmpl.ID())
delete(r.quiescenceMap, tmpl.ID())
case c := <-childExitCh:
log.Printf("[INFO] (runner) child process died")
r.ErrCh <- NewErrChildDied(c)
return
case <-r.DoneCh:
log.Printf("[INFO] (runner) received finish")
return
}
// If we got this far, that means we got new data or one of the timers
// fired, so attempt to re-render.
if err := r.Run(); err != nil {
r.ErrCh <- err
return
}
}
}
// Stop halts the execution of this runner and its subprocesses.
func (r *Runner) Stop() {
r.internalStop(false)
}
// StopImmediately behaves like Stop but won't wait for any splay on any child
// process it may be running.
func (r *Runner) StopImmediately() {
r.internalStop(true)
}
// TemplateRenderedCh returns a channel that will be triggered when one or more
// templates are rendered.
func (r *Runner) TemplateRenderedCh() <-chan struct{} {
return r.renderedCh
}
// RenderEventCh returns a channel that will be triggered when there is a new
// render event.
func (r *Runner) RenderEventCh() <-chan struct{} {
return r.renderEventCh
}
// RenderEvents returns the render events for each template was rendered. The
// map is keyed by template ID.
func (r *Runner) RenderEvents() map[string]*RenderEvent {
r.renderEventsLock.RLock()
defer r.renderEventsLock.RUnlock()
times := make(map[string]*RenderEvent, len(r.renderEvents))
for k, v := range r.renderEvents {
times[k] = v
}
return times
}
func (r *Runner) internalStop(immediately bool) {
r.stopLock.Lock()
defer r.stopLock.Unlock()
if r.stopped {
return
}
log.Printf("[INFO] (runner) stopping")
r.stopDedup()
r.stopWatcher()
r.stopChild(immediately)
if err := r.deletePid(); err != nil {
log.Printf("[WARN] (runner) could not remove pid at %q: %s",
*r.config.PidFile, err)
}
r.stopped = true
close(r.DoneCh)
}
func (r *Runner) stopDedup() {
if r.dedup != nil {
log.Printf("[DEBUG] (runner) stopping de-duplication manager")
r.dedup.Stop()
}
}
func (r *Runner) stopWatcher() {
if r.watcher != nil {
log.Printf("[DEBUG] (runner) stopping watcher")
r.watcher.Stop()
}
}
func (r *Runner) stopChild(immediately bool) {
r.childLock.RLock()
defer r.childLock.RUnlock()
if r.child != nil {
if immediately {
log.Printf("[DEBUG] (runner) stopping child process immediately")
r.child.StopImmediately()
} else {
log.Printf("[DEBUG] (runner) stopping child process")
r.child.Stop()
}
}
}
// Receive accepts a Dependency and data for that dep. This data is
// cached on the Runner. This data is then used to determine if a Template
// is "renderable" (i.e. all its Dependencies have been downloaded at least
// once).
func (r *Runner) Receive(d dep.Dependency, data interface{}) {
r.dependenciesLock.Lock()
defer r.dependenciesLock.Unlock()
// Just because we received data, it does not mean that we are actually
// watching for that data. How is that possible you may ask? Well, this
// Runner's data channel is pooled, meaning it accepts multiple data views
// before actually blocking. Whilest this runner is performing a Run() and
// executing diffs, it may be possible that more data was pushed onto the
// data channel pool for a dependency that we no longer care about.
//
// Accepting this dependency would introduce stale data into the brain, and
// that is simply unacceptable. In fact, it is a fun little bug:
//
// https://github.com/hashicorp/consul-template/issues/198
//
// and by "little" bug, I mean really big bug.
if _, ok := r.dependencies[d.String()]; ok {
log.Printf("[DEBUG] (runner) receiving dependency %s", d)
r.brain.Remember(d, data)
}
}
// Signal sends a signal to the child process, if it exists. Any errors that
// occur are returned.
func (r *Runner) Signal(s os.Signal) error {
r.childLock.RLock()
defer r.childLock.RUnlock()
if r.child == nil {
return nil
}
return r.child.Signal(s)
}
// Run iterates over each template in this Runner and conditionally executes
// the template rendering and command execution.
//
// The template is rendered atomically. If and only if the template render
// completes successfully, the optional commands will be executed, if given.
// Please note that all templates are rendered **and then** any commands are
// executed.
func (r *Runner) Run() error {
log.Printf("[DEBUG] (runner) initiating run")
var newRenderEvent, wouldRenderAny, renderedAny bool
runCtx := &templateRunCtx{
depsMap: make(map[string]dep.Dependency),
}
for _, tmpl := range r.templates {
event, err := r.runTemplate(tmpl, runCtx)
if err != nil {
return err
}
// If there was a render event store it
if event != nil {
r.renderEventsLock.Lock()
r.renderEvents[tmpl.ID()] = event
r.renderEventsLock.Unlock()
// Record that there is at least one new render event
newRenderEvent = true
// Record that at least one template would have been rendered.
if event.WouldRender {
wouldRenderAny = true
}
// Record that at least one template was rendered.
if event.DidRender {
renderedAny = true
}
}
}
// Check if we need to deliver any rendered signals
if wouldRenderAny || renderedAny {
// Send the signal that a template got rendered
select {
case r.renderedCh <- struct{}{}:
default:
}
}
// Check if we need to deliver any event signals
if newRenderEvent {
select {
case r.renderEventCh <- struct{}{}:
default:
}
}
// Perform the diff and update the known dependencies.
r.diffAndUpdateDeps(runCtx.depsMap)
// Execute each command in sequence, collecting any errors that occur - this
// ensures all commands execute at least once.
var errs []error
for _, t := range runCtx.commands {
command := config.StringVal(t.Exec.Command)
log.Printf("[INFO] (runner) executing command %q from %s", command, t.Display())
env := t.Exec.Env.Copy()
env.Custom = append(r.childEnv(), env.Custom...)
if _, err := spawnChild(&spawnChildInput{
Stdin: r.inStream,
Stdout: r.outStream,
Stderr: r.errStream,
Command: command,
Env: env.Env(),
Timeout: config.TimeDurationVal(t.Exec.Timeout),
ReloadSignal: config.SignalVal(t.Exec.ReloadSignal),
KillSignal: config.SignalVal(t.Exec.KillSignal),
KillTimeout: config.TimeDurationVal(t.Exec.KillTimeout),
Splay: config.TimeDurationVal(t.Exec.Splay),
}); err != nil {
s := fmt.Sprintf("failed to execute command %q from %s", command, t.Display())
errs = append(errs, errors.Wrap(err, s))
}
}
// If we got this far and have a child process, we need to send the reload
// signal to the child process.
if renderedAny && r.child != nil {
r.childLock.RLock()
if err := r.child.Reload(); err != nil {
errs = append(errs, err)
}
r.childLock.RUnlock()
}
// If any errors were returned, convert them to an ErrorList for human
// readability.
if len(errs) != 0 {
var result *multierror.Error
for _, err := range errs {
result = multierror.Append(result, err)
}
return result.ErrorOrNil()
}
return nil
}
type templateRunCtx struct {
// commands is the set of commands that will be executed after all templates
// have run. When adding to the commands, care should be taken not to
// duplicate any existing command from a previous template.
commands []*config.TemplateConfig
// depsMap is the set of dependencies shared across all templates.
depsMap map[string]dep.Dependency
}
// runTemplate is used to run a particular template. It takes as input the
// template to run and a shared run context that allows sharing of information
// between templates. The run returns a potentially nil render event and any
// error that occured. The render event is nil in the case that the template has
// been already rendered and is a once template or if there is an error.
func (r *Runner) runTemplate(tmpl *template.Template, runCtx *templateRunCtx) (*RenderEvent, error) {
log.Printf("[DEBUG] (runner) checking template %s", tmpl.ID())
// Grab the last event
r.renderEventsLock.RLock()
lastEvent := r.renderEvents[tmpl.ID()]
r.renderEventsLock.RUnlock()
// Create the event
event := &RenderEvent{
Template: tmpl,
TemplateConfigs: r.templateConfigsFor(tmpl),
}
if lastEvent != nil {
event.LastWouldRender = lastEvent.LastWouldRender
event.LastDidRender = lastEvent.LastDidRender
}
// Check if we are currently the leader instance
isLeader := true
if r.dedup != nil {
isLeader = r.dedup.IsLeader(tmpl)
}
// If we are in once mode and this template was already rendered, move
// onto the next one. We do not want to re-render the template if we are
// in once mode, and we certainly do not want to re-run any commands.
if r.config.Once {
r.renderEventsLock.RLock()
event, ok := r.renderEvents[tmpl.ID()]
r.renderEventsLock.RUnlock()
if ok && (event.WouldRender || event.DidRender) {
log.Printf("[DEBUG] (runner) once mode and already rendered")
return nil, nil
}
}
// Attempt to render the template, returning any missing dependencies and
// the rendered contents. If there are any missing dependencies, the
// contents cannot be rendered or trusted!
result, err := tmpl.Execute(&template.ExecuteInput{
Brain: r.brain,
Env: r.childEnv(),
})
if err != nil {
return nil, errors.Wrap(err, tmpl.Source())
}
// Grab the list of used and missing dependencies.
missing, used := result.Missing, result.Used
// Add the dependency to the list of dependencies for this runner.
for _, d := range used.List() {
// If we've taken over leadership for a template, we may have data
// that is cached, but not have the watcher. We must treat this as
// missing so that we create the watcher and re-run the template.
if isLeader && !r.watcher.Watching(d) {
missing.Add(d)
}
if _, ok := runCtx.depsMap[d.String()]; !ok {
runCtx.depsMap[d.String()] = d
}
}
// Diff any missing dependencies the template reported with dependencies
// the watcher is watching.
unwatched := new(dep.Set)
for _, d := range missing.List() {
if !r.watcher.Watching(d) {
unwatched.Add(d)
}
}
// Update the event with the new dependency information
event.MissingDeps = missing
event.UnwatchedDeps = unwatched
event.UsedDeps = used
event.UpdatedAt = time.Now().UTC()
// If there are unwatched dependencies, start the watcher and exit since we
// won't have data.
if l := unwatched.Len(); l > 0 {
log.Printf("[DEBUG] (runner) was not watching %d dependencies", l)
for _, d := range unwatched.List() {
// If we are deduplicating, we must still handle non-sharable
// dependencies, since those will be ignored.
if isLeader || !d.CanShare() {
r.watcher.Add(d)
}
}
return event, nil
}
// If the template is missing data for some dependencies then we are not
// ready to render and need to move on to the next one.
if l := missing.Len(); l > 0 {
log.Printf("[DEBUG] (runner) missing data for %d dependencies", l)
return event, nil
}
// Trigger an update of the de-duplication manager
if r.dedup != nil && isLeader {
if err := r.dedup.UpdateDeps(tmpl, used.List()); err != nil {
log.Printf("[ERR] (runner) failed to update dependency data for de-duplication: %v", err)
}
}
// If quiescence is activated, start/update the timers and loop back around.
// We do not want to render the templates yet.
if q, ok := r.quiescenceMap[tmpl.ID()]; ok {
q.tick()
// This event is being returned early for quiescence
event.ForQuiescence = true
return event, nil
}
// For each template configuration that is tied to this template, attempt to
// render it to disk and accumulate commands for later use.
for _, templateConfig := range r.templateConfigsFor(tmpl) {
log.Printf("[DEBUG] (runner) rendering %s", templateConfig.Display())
// Render the template, taking dry mode into account
result, err := renderer.Render(&renderer.RenderInput{
Backup: config.BoolVal(templateConfig.Backup),
Contents: result.Output,
CreateDestDirs: config.BoolVal(templateConfig.CreateDestDirs),
Dry: r.dry,
DryStream: r.outStream,
Path: config.StringVal(templateConfig.Destination),
Perms: config.FileModeVal(templateConfig.Perms),
})
if err != nil {
return nil, errors.Wrap(err, "error rendering "+templateConfig.Display())
}
renderTime := time.Now().UTC()
// If we would have rendered this template (but we did not because the
// contents were the same or something), we should consider this template
// rendered even though the contents on disk have not been updated. We
// will not fire commands unless the template was _actually_ rendered to
// disk though.
if result.WouldRender {
// This event would have rendered
event.WouldRender = true
event.LastWouldRender = renderTime
}
// If we _actually_ rendered the template to disk, we want to run the
// appropriate commands.
if result.DidRender {
log.Printf("[INFO] (runner) rendered %s", templateConfig.Display())
// This event did render
event.DidRender = true
event.LastDidRender = renderTime
// Update the contents
event.Contents = result.Contents
if !r.dry {
// If the template was rendered (changed) and we are not in dry-run mode,
// aggregate commands, ignoring previously known commands
//
// Future-self Q&A: Why not use a map for the commands instead of an
// array with an expensive lookup option? Well I'm glad you asked that
// future-self! One of the API promises is that commands are executed
// in the order in which they are provided in the TemplateConfig
// definitions. If we inserted commands into a map, we would lose that
// relative ordering and people would be unhappy.
// if config.StringPresent(ctemplate.Command)
if c := config.StringVal(templateConfig.Exec.Command); c != "" {
existing := findCommand(templateConfig, runCtx.commands)
if existing != nil {
log.Printf("[DEBUG] (runner) skipping command %q from %s (already appended from %s)",
c, templateConfig.Display(), existing.Display())
} else {
log.Printf("[DEBUG] (runner) appending command %q from %s",
c, templateConfig.Display())
runCtx.commands = append(runCtx.commands, templateConfig)
}
}
}
}
}
return event, nil
}
// init() creates the Runner's underlying data structures and returns an error
// if any problems occur.
func (r *Runner) init() error {
// Ensure default configuration values
r.config = config.DefaultConfig().Merge(r.config)
r.config.Finalize()
// Print the final config for debugging
result, err := json.Marshal(r.config)
if err != nil {
return err
}
log.Printf("[DEBUG] (runner) final config: %s", result)
// Create the clientset
clients, err := newClientSet(r.config)
if err != nil {
return fmt.Errorf("runner: %s", err)
}
// Create the watcher
watcher, err := newWatcher(r.config, clients, r.config.Once)
if err != nil {
return fmt.Errorf("runner: %s", err)
}
r.watcher = watcher
numTemplates := len(*r.config.Templates)
templates := make([]*template.Template, 0, numTemplates)
ctemplatesMap := make(map[string]config.TemplateConfigs)
// Iterate over each TemplateConfig, creating a new Template resource for each
// entry. Templates are parsed and saved, and a map of templates to their
// config templates is kept so templates can lookup their commands and output
// destinations.
for _, ctmpl := range *r.config.Templates {
tmpl, err := template.NewTemplate(&template.NewTemplateInput{
Source: config.StringVal(ctmpl.Source),
Contents: config.StringVal(ctmpl.Contents),
ErrMissingKey: config.BoolVal(ctmpl.ErrMissingKey),
LeftDelim: config.StringVal(ctmpl.LeftDelim),
RightDelim: config.StringVal(ctmpl.RightDelim),
FunctionBlacklist: ctmpl.FunctionBlacklist,
SandboxPath: config.StringVal(ctmpl.SandboxPath),
})
if err != nil {
return err
}
if _, ok := ctemplatesMap[tmpl.ID()]; !ok {
templates = append(templates, tmpl)
}
if _, ok := ctemplatesMap[tmpl.ID()]; !ok {
ctemplatesMap[tmpl.ID()] = make([]*config.TemplateConfig, 0, 1)
}
ctemplatesMap[tmpl.ID()] = append(ctemplatesMap[tmpl.ID()], ctmpl)
}
// Convert the map of templates (which was only used to ensure uniqueness)
// back into an array of templates.
r.templates = templates
r.renderEvents = make(map[string]*RenderEvent, numTemplates)
r.dependencies = make(map[string]dep.Dependency)
r.renderedCh = make(chan struct{}, 1)
r.renderEventCh = make(chan struct{}, 1)
r.ctemplatesMap = ctemplatesMap
r.inStream = os.Stdin
r.outStream = os.Stdout
r.errStream = os.Stderr
r.brain = template.NewBrain()
r.ErrCh = make(chan error)
r.DoneCh = make(chan struct{})
r.quiescenceMap = make(map[string]*quiescence)
r.quiescenceCh = make(chan *template.Template)
if *r.config.Dedup.Enabled {
if r.config.Once {
log.Printf("[INFO] (runner) disabling de-duplication in once mode")
} else {
r.dedup, err = NewDedupManager(r.config.Dedup, clients, r.brain, r.templates)
if err != nil {
return err
}
}
}
return nil
}
// diffAndUpdateDeps iterates through the current map of dependencies on this
// runner and stops the watcher for any deps that are no longer required.
//
// At the end of this function, the given depsMap is converted to a slice and
// stored on the runner.
func (r *Runner) diffAndUpdateDeps(depsMap map[string]dep.Dependency) {
r.dependenciesLock.Lock()
defer r.dependenciesLock.Unlock()
// Diff and up the list of dependencies, stopping any unneeded watchers.
log.Printf("[DEBUG] (runner) diffing and updating dependencies")
for key, d := range r.dependencies {
if _, ok := depsMap[key]; !ok {
log.Printf("[DEBUG] (runner) %s is no longer needed", d)
r.watcher.Remove(d)
r.brain.Forget(d)
} else {
log.Printf("[DEBUG] (runner) %s is still needed", d)
}
}
r.dependencies = depsMap
}
// TemplateConfigFor returns the TemplateConfig for the given Template
func (r *Runner) templateConfigsFor(tmpl *template.Template) []*config.TemplateConfig {
return r.ctemplatesMap[tmpl.ID()]
}
// TemplateConfigMapping returns a mapping between the template ID and the set
// of TemplateConfig represented by the template ID
func (r *Runner) TemplateConfigMapping() map[string][]*config.TemplateConfig {
// this method is primarily used to support embedding consul-template
// in other applications (ex. Nomad)
m := make(map[string][]*config.TemplateConfig, len(r.ctemplatesMap))
for id, set := range r.ctemplatesMap {
ctmpls := make([]*config.TemplateConfig, len(set))
m[id] = ctmpls
for i, ctmpl := range set {
ctmpls[i] = ctmpl
}
}
return m
}
// allTemplatesRendered returns true if all the templates in this Runner have
// been rendered at least one time.
func (r *Runner) allTemplatesRendered() bool {
r.renderEventsLock.RLock()
defer r.renderEventsLock.RUnlock()
for _, tmpl := range r.templates {
event, rendered := r.renderEvents[tmpl.ID()]
if !rendered {
return false
}
// Skip evaluation of events from quiescence as they will
// be default unrendered as we are still waiting for the
// specified period
if event.ForQuiescence {
continue
}
// The template might already exist on disk with the exact contents, but
// we still want to count that as "rendered" [GH-1000].
if !event.DidRender && !event.WouldRender {
return false
}
}