-
Notifications
You must be signed in to change notification settings - Fork 2
/
local_bundle_watcher.go
245 lines (204 loc) · 6.35 KB
/
local_bundle_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
package runtime
import (
"context"
"path/filepath"
"strings"
"time"
"github.com/fsnotify/fsnotify"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/bundle"
"github.com/open-policy-agent/opa/loader"
"github.com/open-policy-agent/opa/metrics"
"github.com/open-policy-agent/opa/storage"
"github.com/open-policy-agent/opa/version"
"github.com/pkg/errors"
)
var versionPath = storage.MustParsePath("/system/version")
func (r *Runtime) onReloadLogger(d time.Duration, err error) {
r.Logger.Warn().
Dur("duration", d).
Err(err).
Msg("Processed file watch event.")
}
func (r *Runtime) startWatcher(ctx context.Context, paths []string, onReload func(time.Duration, error)) error {
watcher, err := r.getWatcher(paths)
if err != nil {
return err
}
go r.readWatcher(ctx, watcher, paths, onReload)
return nil
}
func (r *Runtime) getWatcher(rootPaths []string) (*fsnotify.Watcher, error) {
watchPaths, err := getWatchPaths(rootPaths)
if err != nil {
return nil, err
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
for _, path := range watchPaths {
r.Logger.Debug().Str("path", path).Msg("watching path")
if err := watcher.Add(path); err != nil {
return nil, err
}
}
if r.Config.LocalBundles.LocalPolicyImage != "" {
err = watcher.Add(filepath.Join(r.Config.LocalBundles.FileStoreRoot, "policies-root", "index.json"))
if err != nil {
return nil, err
}
}
return watcher, nil
}
func getWatchPaths(rootPaths []string) ([]string, error) {
paths := []string{}
for _, path := range rootPaths {
_, path = loader.SplitPrefix(path)
result, err := loader.Paths(path, true)
if err != nil {
return nil, err
}
paths = append(paths, loader.Dirs(result)...)
}
return paths, nil
}
func (r *Runtime) readWatcher(ctx context.Context, watcher *fsnotify.Watcher, paths []string, onReload func(time.Duration, error)) {
for {
evt := <-watcher.Events
removalMask := (fsnotify.Remove | fsnotify.Rename)
mask := (fsnotify.Create | fsnotify.Write | removalMask)
if (evt.Op & mask) != 0 {
r.Logger.Debug().Str("event", evt.String()).Msg("registered file event")
t0 := time.Now()
removed := ""
if (evt.Op & removalMask) != 0 {
removed = evt.Name
}
err := r.processWatcherUpdate(ctx, paths, removed)
onReload(time.Since(t0), err)
}
}
}
func (r *Runtime) processWatcherUpdate(ctx context.Context, paths []string, removed string) error {
if r.Config.LocalBundles.LocalPolicyImage != "" {
err := storage.Txn(ctx, r.storage, storage.WriteParams, func(txn storage.Transaction) error {
deactivatemap := make(map[string]struct{})
policies, err := r.storage.ListPolicies(ctx, txn)
if err != nil {
return err
}
if len(policies) > 0 {
path := strings.Split(policies[0], "/")
rootIndex := len(path) - 3 // default bundle root.
// bundle root detection for build images.
for i := range path {
if path[i] == "sha256" {
rootIndex = i + 2
break
}
}
root := strings.Join(path[:rootIndex], "/")
deactivatemap[root] = struct{}{}
return bundle.Deactivate(&bundle.DeactivateOpts{
Ctx: ctx,
Store: r.storage,
Txn: txn,
BundleNames: deactivatemap,
})
}
return nil
})
if err != nil {
return err
}
}
loadedBundles, err := r.loadPaths(paths)
if err != nil {
return err
}
if removed != "" {
r.Logger.Debug().Msgf("Removed event name value: %v", removed)
}
return storage.Txn(ctx, r.storage, storage.WriteParams, func(txn storage.Transaction) error {
_, err = insertAndCompile(ctx, &insertAndCompileOptions{
Store: r.storage,
Txn: txn,
Bundles: loadedBundles,
MaxErrors: -1,
})
if err != nil {
return err
}
return nil
})
}
// insertAndCompileOptions contains input for the operation.
type insertAndCompileOptions struct {
Store storage.Store
Txn storage.Transaction
Files loader.Result
Bundles map[string]*bundle.Bundle
MaxErrors int
}
// insertAndCompileResult contains the output of the operation.
type insertAndCompileResult struct {
Compiler *ast.Compiler
Metrics metrics.Metrics
}
// insertAndCompile writes data and policy into the store and returns a compiler for the
// store contents.
func insertAndCompile(ctx context.Context, opts *insertAndCompileOptions) (*insertAndCompileResult, error) {
if len(opts.Files.Documents) > 0 {
if err := opts.Store.Write(ctx, opts.Txn, storage.AddOp, storage.Path{}, opts.Files.Documents); err != nil {
return nil, errors.Wrap(err, "storage error")
}
}
policies := make(map[string]*ast.Module, len(opts.Files.Modules))
for id, parsed := range opts.Files.Modules {
policies[id] = parsed.Parsed
}
compiler := ast.NewCompiler().SetErrorLimit(opts.MaxErrors).WithPathConflictsCheck(storage.NonEmpty(ctx, opts.Store, opts.Txn))
m := metrics.New()
activation := &bundle.ActivateOpts{
Ctx: ctx,
Store: opts.Store,
Txn: opts.Txn,
Compiler: compiler,
Metrics: m,
Bundles: opts.Bundles,
ExtraModules: policies,
}
err := bundle.Activate(activation)
if err != nil {
return nil, err
}
// Policies in bundles will have already been added to the store, but
// modules loaded outside of bundles will need to be added manually.
for id, parsed := range opts.Files.Modules {
if err := opts.Store.UpsertPolicy(ctx, opts.Txn, id, parsed.Raw); err != nil {
return nil, errors.Wrap(err, "storage error")
}
}
// Set the version in the store last to prevent data files from overwriting.
if err := writeVersion(ctx, opts.Store, opts.Txn); err != nil {
return nil, errors.Wrap(err, "storage error")
}
return &insertAndCompileResult{Compiler: compiler, Metrics: m}, nil
}
// writeVersion writes the build version information into storage. This makes the
// version information available to the REPL and the HTTP server.
func writeVersion(ctx context.Context, store storage.Store, txn storage.Transaction) error {
if err := storage.MakeDir(ctx, store, txn, versionPath); err != nil {
return err
}
if err := store.Write(ctx, txn, storage.AddOp, versionPath, map[string]interface{}{
"version": version.Version,
"build_commit": version.Vcs,
"build_timestamp": version.Timestamp,
"build_hostname": version.Hostname,
}); err != nil {
return errors.Wrap(err, "failed to write version information to storage")
}
return nil
}