-
Notifications
You must be signed in to change notification settings - Fork 71
/
runner.go
558 lines (475 loc) · 15.2 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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package main
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"os"
"regexp"
"sync"
"time"
"strings"
"github.com/hashicorp/consul-template/config"
dep "github.com/hashicorp/consul-template/dependency"
"github.com/hashicorp/consul-template/watch"
"github.com/hashicorp/consul/api"
"github.com/hashicorp/go-multierror"
"github.com/pkg/errors"
)
// Regexp for invalid characters in keys
var InvalidRegexp = regexp.MustCompile(`[^a-zA-Z0-9_]`)
// Status is an internal struct that is responsible for marshaling and
// unmarshaling JSON responses into keys.
type Status struct {
// LastReplicated is the last time the replication occurred.
LastReplicated uint64
// Source and Destination are the given and final destination.
Source, Destination string
}
type Runner struct {
sync.RWMutex
// // Prefix is the KeyPrefixDependency associated with this Runner.
// Prefix *dependency.StoreKeyPrefix
// 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
// client is the consul/api client.
clients *dep.ClientSet
// data is the internal storage engine for this runner with the key being the
// String() for the dependency and the result being the view that holds the
// data.
data map[string]*watch.View
// once indicates the runner should get data exactly one time and then stop.
once bool
// minTimer and maxTimer are used for quiescence.
minTimer, maxTimer <-chan time.Time
// outStream and errStream are the io.Writer streams where the runner will
// write information.
outStream, errStream io.Writer
// watcher is the watcher this runner is using.
watcher *watch.Watcher
}
// NewRunner accepts a config, command, and boolean value for once mode.
func NewRunner(config *Config, once bool) (*Runner, error) {
log.Printf("[INFO] (runner) creating new runner (once: %v)", once)
runner := &Runner{
config: config,
once: once,
}
if err := runner.init(); err != nil {
return nil, err
}
return runner, nil
}
// Start creates a new runner and begins watching dependencies and quiescence
// timers. This is the main event loop and will block until finished.
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
}
// Add the dependencies to the watcher
for _, prefix := range *r.config.Prefixes {
if _, err := r.watcher.Add(prefix.Dependency); err != nil {
log.Printf("ERR (runner) failed to add watch: %v", err)
}
}
// If once mode is on, wait until we get data back from all the views before proceeding
onceCh := make(chan struct{}, 1)
if r.once {
for i := 0; i < len(*r.config.Prefixes); i++ {
select {
case view := <-r.watcher.DataCh():
r.Receive(view)
case err := <-r.watcher.ErrCh():
r.ErrCh <- err
return
}
}
onceCh <- struct{}{}
}
for {
select {
case view := <-r.watcher.DataCh():
r.Receive(view)
// Drain all views that have data
OUTER:
for {
select {
case view = <-r.watcher.DataCh():
r.Receive(view)
default:
break OUTER
}
}
// If we are waiting for quiescence, setup the timers
if *r.config.Wait.Min != 0 && *r.config.Wait.Max != 0 {
log.Printf("[INFO] (runner) quiescence timers starting")
r.minTimer = time.After(*r.config.Wait.Min)
if r.maxTimer == nil {
r.maxTimer = time.After(*r.config.Wait.Max)
}
continue
}
case <-r.minTimer:
log.Printf("[INFO] (runner) quiescence minTimer fired")
r.minTimer, r.maxTimer = nil, nil
case <-r.maxTimer:
log.Printf("[INFO] (runner) quiescence maxTimer fired")
r.minTimer, r.maxTimer = nil, nil
case err := <-r.watcher.ErrCh():
log.Printf("[ERR] (runner) watcher reported error: %s", err)
r.ErrCh <- err
case <-r.DoneCh:
log.Printf("[INFO] (runner) received finish")
return
case <-onceCh:
}
// If we got this far, that means we got new data or one of the timers
// fired, so attempt to run.
if err := r.Run(); err != nil {
r.ErrCh <- err
return
}
if r.once {
log.Printf("[INFO] (runner) run finished and -once is set, exiting")
r.DoneCh <- struct{}{}
return
}
}
}
// Stop halts the execution of this runner and its subprocesses.
func (r *Runner) Stop() {
log.Printf("[INFO] (runner) stopping")
r.watcher.Stop()
if err := r.deletePid(); err != nil {
log.Printf("[WARN] (runner) could not remove pid at %q: %s",
*r.config.PidFile, err)
}
close(r.DoneCh)
}
// Receive accepts data from Consul and maps that data to the prefix.
func (r *Runner) Receive(view *watch.View) {
r.Lock()
defer r.Unlock()
r.data[view.Dependency().String()] = view
}
// Run invokes a single pass of the runner.
func (r *Runner) Run() error {
log.Printf("[INFO] (runner) running")
prefixes := *r.config.Prefixes
doneCh := make(chan struct{}, len(prefixes))
errCh := make(chan error, len(prefixes))
// Replicate each prefix in a goroutine
for _, prefix := range prefixes {
go r.replicate(prefix, r.config.Excludes, doneCh, errCh)
}
var errs *multierror.Error
for i := 0; i < len(prefixes); i++ {
select {
case <-doneCh:
// OK
case err := <-errCh:
errs = multierror.Append(errs, err)
}
}
return errs.ErrorOrNil()
}
// 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 = DefaultConfig().Merge(r.config)
r.config.Finalize()
// Print the final config for debugging
result, err := json.MarshalIndent(r.config, "", " ")
if err != nil {
return err
}
log.Printf("[DEBUG] (runner) final config (tokens suppressed):\n\n%s\n\n",
result)
// Create the client
clients, err := newClientSet(r.config)
if err != nil {
return fmt.Errorf("runner: %s", err)
}
r.clients = clients
// Create the watcher
watcher, err := newWatcher(r.config, clients, r.once)
if err != nil {
return fmt.Errorf("runner: %s", err)
}
r.watcher = watcher
r.data = make(map[string]*watch.View)
r.outStream = os.Stdout
r.errStream = os.Stderr
r.ErrCh = make(chan error)
r.DoneCh = make(chan struct{})
return nil
}
// get returns the data for a particular view in the watcher.
func (r *Runner) get(prefix *PrefixConfig) (*watch.View, bool) {
r.RLock()
defer r.RUnlock()
result, ok := r.data[prefix.Dependency.String()]
return result, ok
}
// replicate performs replication into the current datacenter from the given
// prefix. This function is designed to be called via a goroutine since it is
// expensive and needs to be parallelized.
func (r *Runner) replicate(prefix *PrefixConfig, excludes *ExcludeConfigs, doneCh chan struct{}, errCh chan error) {
// Ensure we are not self-replicating
info, err := r.clients.Consul().Agent().Self()
if err != nil {
errCh <- fmt.Errorf("failed to query agent: %s", err)
return
}
localDatacenter := info["Config"]["Datacenter"].(string)
if localDatacenter == config.StringVal(prefix.Datacenter) {
errCh <- fmt.Errorf("local datacenter cannot be the source datacenter")
return
}
// Get the last status
status, err := r.getStatus(prefix)
if err != nil {
errCh <- fmt.Errorf("failed to read replication status: %s", err)
return
}
// Get the prefix data
view, ok := r.get(prefix)
if !ok {
log.Printf("[INFO] (runner) no data for %q", prefix.Dependency)
doneCh <- struct{}{}
return
}
// Get the data from the view
data, lastIndex := view.DataAndLastIndex()
pairs, ok := data.([]*dep.KeyPair)
if !ok {
errCh <- fmt.Errorf("could not convert watch data")
return
}
kv := r.clients.Consul().KV()
// Update keys to the most recent versions
updates := 0
usedKeys := make(map[string]struct{}, len(pairs))
for _, pair := range pairs {
key := config.StringVal(prefix.Destination) +
strings.TrimPrefix(pair.Path, config.StringVal(prefix.Source))
usedKeys[key] = struct{}{}
// Ignore if the key falls under an excluded prefix
if len(*excludes) > 0 {
excluded := false
for _, exclude := range *excludes {
if strings.HasPrefix(pair.Path, config.StringVal(exclude.Source)) {
log.Printf("[DEBUG] (runner) key %q has prefix %q, excluding",
pair.Path, config.StringVal(exclude.Source))
excluded = true
}
}
if excluded {
continue
}
}
// Ignore if the modify index is old
if pair.ModifyIndex <= status.LastReplicated {
log.Printf("[DEBUG] (runner) skipping because %q is already "+
"replicated", key)
continue
}
// Check if lock
if pair.Flags == api.SemaphoreFlagValue {
log.Printf("[WARN] (runner) lock in use at %q, but sessions cannot be "+
"replicated across datacenters", key)
}
// Check if semaphore
if pair.Flags == api.LockFlagValue {
log.Printf("[WARN] (runner) semaphore in use at %q, but sessions cannot "+
"be replicated across datacenters", key)
}
// Check if session attached
if pair.Session != "" {
log.Printf("[WARN] (runner) %q has attached session, but sessions "+
"cannot be replicated across datacenters", key)
}
if _, err := kv.Put(&api.KVPair{
Key: key,
Flags: pair.Flags,
Value: []byte(pair.Value),
}, nil); err != nil {
errCh <- fmt.Errorf("failed to write %q: %s", key, err)
return
}
log.Printf("[DEBUG] (runner) updated key %q", key)
updates++
}
// Handle deletes
deletes := 0
localKeys, _, err := kv.Keys(config.StringVal(prefix.Destination), "", nil)
if err != nil {
errCh <- fmt.Errorf("failed to list keys: %s", err)
return
}
for _, key := range localKeys {
excluded := false
// Ignore if the key falls under an excluded prefix
if len(*excludes) > 0 {
sourceKey := strings.Replace(key, config.StringVal(prefix.Destination), config.StringVal(prefix.Source), -1)
for _, exclude := range *excludes {
if strings.HasPrefix(sourceKey, config.StringVal(exclude.Source)) {
log.Printf("[DEBUG] (runner) key %q has prefix %q, excluding from deletes",
sourceKey, *exclude.Source)
excluded = true
}
}
}
if _, ok := usedKeys[key]; !ok && !excluded {
if _, err := kv.Delete(key, nil); err != nil {
errCh <- fmt.Errorf("failed to delete %q: %s", key, err)
return
}
log.Printf("[DEBUG] (runner) deleted %q", key)
deletes++
}
}
// Update our status
status.LastReplicated = lastIndex
status.Source = config.StringVal(prefix.Source)
status.Destination = config.StringVal(prefix.Destination)
if err := r.setStatus(prefix, status); err != nil {
errCh <- fmt.Errorf("failed to checkpoint status: %s", err)
return
}
if updates > 0 || deletes > 0 {
log.Printf("[INFO] (runner) replicated %d updates, %d deletes", updates, deletes)
}
// We are done!
doneCh <- struct{}{}
}
// getStatus is used to read the last replication status.
func (r *Runner) getStatus(prefix *PrefixConfig) (*Status, error) {
kv := r.clients.Consul().KV()
pair, _, err := kv.Get(r.statusPath(prefix), nil)
if err != nil {
return nil, err
}
status := &Status{}
if pair != nil {
if err := json.Unmarshal(pair.Value, &status); err != nil {
return nil, err
}
}
return status, nil
}
// setStatus is used to update the last replication status.
func (r *Runner) setStatus(prefix *PrefixConfig, status *Status) error {
// Encode the JSON as pretty so operators can easily view it in the Consul UI.
enc, err := json.MarshalIndent(status, "", " ")
if err != nil {
return err
}
// Put the key to Consul.
kv := r.clients.Consul().KV()
_, err = kv.Put(&api.KVPair{
Key: r.statusPath(prefix),
Value: enc,
}, nil)
return err
}
func (r *Runner) statusPath(prefix *PrefixConfig) string {
plain := fmt.Sprintf("%s-%s", config.StringVal(prefix.Source), config.StringVal(prefix.Destination))
hash := md5.Sum([]byte(plain))
enc := hex.EncodeToString(hash[:])
return strings.TrimRight(config.StringVal(r.config.StatusDir), "/") + "/" + enc
}
// storePid is used to write out a PID file to disk.
func (r *Runner) storePid() error {
path := config.StringVal(r.config.PidFile)
if path == "" {
return nil
}
log.Printf("[INFO] creating pid file at %q", path)
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
if err != nil {
return fmt.Errorf("runner: could not open pid file: %s", err)
}
defer f.Close()
pid := os.Getpid()
_, err = f.WriteString(fmt.Sprintf("%d", pid))
if err != nil {
return fmt.Errorf("runner: could not write to pid file: %s", err)
}
return nil
}
// deletePid is used to remove the PID on exit.
func (r *Runner) deletePid() error {
path := config.StringVal(r.config.PidFile)
if path == "" {
return nil
}
log.Printf("[DEBUG] removing pid file at %q", path)
stat, err := os.Stat(path)
if err != nil {
return fmt.Errorf("runner: could not remove pid file: %s", err)
}
if stat.IsDir() {
return fmt.Errorf("runner: specified pid file path is directory")
}
err = os.Remove(path)
if err != nil {
return fmt.Errorf("runner: could not remove pid file: %s", err)
}
return nil
}
// newClientSet creates a new client set from the given config.
func newClientSet(c *Config) (*dep.ClientSet, error) {
clients := dep.NewClientSet()
if err := clients.CreateConsulClient(&dep.CreateConsulClientInput{
Address: config.StringVal(c.Consul.Address),
Token: config.StringVal(c.Consul.Token),
AuthEnabled: config.BoolVal(c.Consul.Auth.Enabled),
AuthUsername: config.StringVal(c.Consul.Auth.Username),
AuthPassword: config.StringVal(c.Consul.Auth.Password),
SSLEnabled: config.BoolVal(c.Consul.SSL.Enabled),
SSLVerify: config.BoolVal(c.Consul.SSL.Verify),
SSLCert: config.StringVal(c.Consul.SSL.Cert),
SSLKey: config.StringVal(c.Consul.SSL.Key),
SSLCACert: config.StringVal(c.Consul.SSL.CaCert),
SSLCAPath: config.StringVal(c.Consul.SSL.CaPath),
ServerName: config.StringVal(c.Consul.SSL.ServerName),
TransportDialKeepAlive: config.TimeDurationVal(c.Consul.Transport.DialKeepAlive),
TransportDialTimeout: config.TimeDurationVal(c.Consul.Transport.DialTimeout),
TransportDisableKeepAlives: config.BoolVal(c.Consul.Transport.DisableKeepAlives),
TransportIdleConnTimeout: config.TimeDurationVal(c.Consul.Transport.IdleConnTimeout),
TransportMaxIdleConns: config.IntVal(c.Consul.Transport.MaxIdleConns),
TransportMaxIdleConnsPerHost: config.IntVal(c.Consul.Transport.MaxIdleConnsPerHost),
TransportTLSHandshakeTimeout: config.TimeDurationVal(c.Consul.Transport.TLSHandshakeTimeout),
}); err != nil {
return nil, fmt.Errorf("runner: %s", err)
}
return clients, nil
}
// newWatcher creates a new watcher.
func newWatcher(c *Config, clients *dep.ClientSet, once bool) (*watch.Watcher, error) {
log.Printf("[INFO] (runner) creating watcher")
w, err := watch.NewWatcher(&watch.NewWatcherInput{
Clients: clients,
MaxStale: config.TimeDurationVal(c.MaxStale),
Once: once,
RetryFuncConsul: watch.RetryFunc(c.Consul.Retry.RetryFunc()),
RetryFuncDefault: nil,
})
if err != nil {
return nil, errors.Wrap(err, "runner")
}
return w, nil
}