-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
294 lines (249 loc) · 7.79 KB
/
watcher.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
// Copyright 2017 Istio Authors
//
// 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 envoy
import (
"context"
"crypto/sha256"
"fmt"
"hash"
"io/ioutil"
"os"
"os/exec"
"path"
"time"
"github.com/golang/glog"
multierror "github.com/hashicorp/go-multierror"
"github.com/howeyc/fsnotify"
proxyconfig "istio.io/api/proxy/v1/config"
"istio.io/core/proxy"
)
// Watcher triggers reloads on changes to the proxy config
type Watcher interface {
// Run the watcher loop (blocking call)
Run(context.Context)
// Reload the agent with the latest configuration
Reload()
}
// CertSource is file source for certificates
type CertSource struct {
// Directory containing certificates
Directory string
// Files for certificates
Files []string
}
type watcher struct {
agent proxy.Agent
role proxy.Node
config proxyconfig.ProxyConfig
certs []CertSource
}
// NewWatcher creates a new watcher instance from a proxy agent and a set of monitored certificate paths
// (directories with files in them)
func NewWatcher(config proxyconfig.ProxyConfig, agent proxy.Agent, role proxy.Node, certs []CertSource) Watcher {
return &watcher{
agent: agent,
role: role,
config: config,
certs: certs,
}
}
// defaultMinDelay is the minimum amount of time between delivery of two successive events via updateFunc.
const defaultMinDelay = 10 * time.Second
func (w *watcher) Run(ctx context.Context) {
// agent consumes notifications from the controller
go w.agent.Run(ctx)
// kickstart the proxy with partial state (in case there are no notifications coming)
w.Reload()
// monitor certificates
certDirs := make([]string, 0, len(w.certs))
for _, cert := range w.certs {
certDirs = append(certDirs, cert.Directory)
}
go watchCerts(ctx, certDirs, watchFileEvents, defaultMinDelay, w.Reload)
<-ctx.Done()
}
func (w *watcher) Reload() {
// use LDS instead of static listeners and clusters
config := buildConfig(Listeners{}, Clusters{}, true, w.config)
// compute hash of dependent certificates
h := sha256.New()
for _, cert := range w.certs {
generateCertHash(h, cert.Directory, cert.Files)
}
config.Hash = h.Sum(nil)
w.agent.ScheduleConfigUpdate(config)
}
type watchFileEventsFn func(ctx context.Context, wch <-chan *fsnotify.FileEvent,
minDelay time.Duration, notifyFn func())
// watchFileEvents watches for changes on a channel and notifies via notifyFn().
// The function batches changes so that related changes are processed together.
// The function ensures that notifyFn() is called no more than one time per minDelay.
// The function does not return until the the context is cancelled.
func watchFileEvents(ctx context.Context, wch <-chan *fsnotify.FileEvent, minDelay time.Duration, notifyFn func()) {
// timer and channel for managing minDelay.
var timeChan <-chan time.Time
var timer *time.Timer
for {
select {
case ev := <-wch:
glog.Infof("watchFileEvents: %s", ev.String())
if timer != nil {
continue
}
// create new timer
timer = time.NewTimer(minDelay)
timeChan = timer.C
case <-timeChan:
// reset timer
timeChan = nil
timer.Stop()
timer = nil
glog.Info("watchFileEvents: notifying")
notifyFn()
case <-ctx.Done():
glog.V(2).Info("watchFileEvents has terminated")
return
}
}
}
// watchCerts watches all certificate directories and calls the provided
// `updateFunc` method when changes are detected. This method is blocking
// so it should be run as a goroutine.
// updateFunc will not be called more than one time per minDelay.
func watchCerts(ctx context.Context, certsDirs []string, watchFileEventsFn watchFileEventsFn,
minDelay time.Duration, updateFunc func()) {
fw, err := fsnotify.NewWatcher()
if err != nil {
glog.Warningf("failed to create a watcher for certificate files: %v", err)
return
}
defer func() {
if err := fw.Close(); err != nil {
glog.Warningf("closing watcher encounters an error %v", err)
}
}()
// watch all directories
for _, d := range certsDirs {
if err := fw.Watch(d); err != nil {
glog.Warningf("watching %s encounters an error %v", d, err)
return
}
}
watchFileEventsFn(ctx, fw.Event, minDelay, updateFunc)
}
func generateCertHash(h hash.Hash, certsDir string, files []string) {
if _, err := os.Stat(certsDir); os.IsNotExist(err) {
return
}
for _, file := range files {
filename := path.Join(certsDir, file)
bs, err := ioutil.ReadFile(filename)
if err != nil {
// glog.Warningf("failed to read file %q", filename)
continue
}
if _, err := h.Write(bs); err != nil {
glog.Warning(err)
}
}
}
const (
// EpochFileTemplate is a template for the root config JSON
EpochFileTemplate = "envoy-rev%d.json"
)
func configFile(config string, epoch int) string {
return path.Join(config, fmt.Sprintf(EpochFileTemplate, epoch))
}
type envoy struct {
config proxyconfig.ProxyConfig
node string
extraArgs []string
}
// NewProxy creates an instance of the proxy control commands
func NewProxy(config proxyconfig.ProxyConfig, node string) proxy.Proxy {
// inject tracing flag for higher levels
var args []string
if glog.V(4) {
args = append(args, "-l", "trace")
} else if glog.V(3) {
args = append(args, "-l", "debug")
}
return envoy{
config: config,
node: node,
extraArgs: args,
}
}
func (proxy envoy) args(fname string, epoch int) []string {
startupArgs := []string{"-c", fname,
"--restart-epoch", fmt.Sprint(epoch),
"--drain-time-s", fmt.Sprint(int(convertDuration(proxy.config.DrainDuration) / time.Second)),
"--parent-shutdown-time-s", fmt.Sprint(int(convertDuration(proxy.config.ParentShutdownDuration) / time.Second)),
"--service-cluster", proxy.config.ServiceCluster,
"--service-node", proxy.node,
}
startupArgs = append(startupArgs, proxy.extraArgs...)
if len(proxy.config.AvailabilityZone) > 0 {
startupArgs = append(startupArgs, []string{"--service-zone", proxy.config.AvailabilityZone}...)
}
return startupArgs
}
func (proxy envoy) Run(config interface{}, epoch int, abort <-chan error) error {
envoyConfig, ok := config.(*Config)
if !ok {
return fmt.Errorf("unexpected config type: %#v", config)
}
// create parent directories if necessary
if err := os.MkdirAll(proxy.config.ConfigPath, 0700); err != nil {
return multierror.Prefix(err, "failed to create directory for proxy configuration")
}
// attempt to write file
fname := configFile(proxy.config.ConfigPath, epoch)
if err := envoyConfig.WriteFile(fname); err != nil {
return err
}
// spin up a new Envoy process
args := proxy.args(fname, epoch)
glog.V(2).Infof("Envoy command: %v", args)
/* #nosec */
cmd := exec.Command(proxy.config.BinaryPath, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return err
}
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
select {
case err := <-abort:
glog.Warningf("Aborting epoch %d", epoch)
if errKill := cmd.Process.Kill(); errKill != nil {
glog.Warningf("killing epoch %d caused an error %v", epoch, errKill)
}
return err
case err := <-done:
return err
}
}
func (proxy envoy) Cleanup(epoch int) {
path := configFile(proxy.config.ConfigPath, epoch)
if err := os.Remove(path); err != nil {
glog.Warningf("Failed to delete config file %s for %d, %v", path, epoch, err)
}
}
func (proxy envoy) Panic(_ interface{}) {
glog.Fatal("cannot start the proxy with the desired configuration")
}