forked from open-policy-agent/opa
/
runtime.go
651 lines (519 loc) · 15.4 KB
/
runtime.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
// Copyright 2016 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package runtime
import (
"bytes"
"context"
"crypto/rand"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"sync"
"time"
fsnotify "gopkg.in/fsnotify.v1"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/loader"
"github.com/open-policy-agent/opa/plugins"
"github.com/open-policy-agent/opa/plugins/bundle"
"github.com/open-policy-agent/opa/plugins/logs"
"github.com/open-policy-agent/opa/plugins/status"
"github.com/open-policy-agent/opa/repl"
"github.com/open-policy-agent/opa/server"
"github.com/open-policy-agent/opa/storage"
"github.com/open-policy-agent/opa/storage/inmem"
"github.com/open-policy-agent/opa/util"
"github.com/open-policy-agent/opa/version"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
var (
registeredPlugins []pluginFactory
registeredPluginsMux sync.Mutex
)
// RegisterPlugin registers a plugin with the runtime package. When a Runtime
// is created, the factory functions will be called.
func RegisterPlugin(name string, factory func(m *plugins.Manager, config []byte) (plugins.Plugin, error)) {
registeredPluginsMux.Lock()
defer registeredPluginsMux.Unlock()
registeredPlugins = append(registeredPlugins, pluginFactory{
name: name,
factory: factory,
})
}
type pluginFactory struct {
name string
factory func(m *plugins.Manager, config []byte) (plugins.Plugin, error)
}
// Params stores the configuration for an OPA instance.
type Params struct {
// Globally unique identifier for this OPA instance. If an ID is not specified,
// the runtime will generate one.
ID string
// Addr is the listening address that the OPA server will bind to.
Addr string
// InsecureAddr is the listening address that the OPA server will bind to
// in addition to Addr if TLS is enabled.
InsecureAddr string
// Authentication is the type of authentication scheme to use.
Authentication server.AuthenticationScheme
// Authorization is the type of authorization scheme to use.
Authorization server.AuthorizationScheme
// Certificate is the certificate to use in server-mode. If the certificate
// is nil, the server will NOT use TLS.
Certificate *tls.Certificate
// HistoryPath is the filename to store the interactive shell user
// input history.
HistoryPath string
// Output format controls how the REPL will print query results.
// Default: "pretty".
OutputFormat string
// Paths contains filenames of base documents and policy modules to load on
// startup. Data files may be prefixed with "<dotted-path>:" to indicate
// where the contained document should be loaded.
Paths []string
// Watch flag controls whether OPA will watch the Paths files for changes.
// If this flag is true, OPA will watch the Paths files for changes and
// reload the storage layer each time they change. This is useful for
// interactive development.
Watch bool
// ErrorLimit is the number of errors the compiler will allow to occur before
// exiting early.
ErrorLimit int
// DecisionIDFactory generates decision IDs to include in API responses
// sent by the server (in response to Data API queries.)
DecisionIDFactory func() string
// DiagnosticsBuffer is used by the server to record policy decisions.
DiagnosticsBuffer server.Buffer
// Logging configures the logging behaviour.
Logging LoggingConfig
// ConfigFile refers to the OPA configuration to load on startup.
ConfigFile string
// Output is the output stream used when run as an interactive shell. This
// is mostly for test purposes.
Output io.Writer
}
// LoggingConfig stores the configuration for OPA's logging behaviour.
type LoggingConfig struct {
Level string
Format string
}
// NewParams returns a new Params object.
func NewParams() Params {
return Params{
Output: os.Stdout,
}
}
// Runtime represents a single OPA instance.
type Runtime struct {
Params Params
Store storage.Store
Manager *plugins.Manager
decisionLogger func(context.Context, *server.Info)
}
// NewRuntime returns a new Runtime object initialized with params.
func NewRuntime(ctx context.Context, params Params) (*Runtime, error) {
if params.ID == "" {
var err error
params.ID, err = generateInstanceID()
if err != nil {
return nil, err
}
}
loaded, err := loader.All(params.Paths)
if err != nil {
return nil, err
}
store := inmem.New()
txn, err := store.NewTransaction(ctx, storage.WriteParams)
if err != nil {
return nil, err
}
if err := store.Write(ctx, txn, storage.AddOp, storage.Path{}, loaded.Documents); err != nil {
store.Abort(ctx, txn)
return nil, errors.Wrapf(err, "storage error")
}
if err := compileAndStoreInputs(ctx, store, txn, loaded.Modules, params.ErrorLimit); err != nil {
store.Abort(ctx, txn)
return nil, errors.Wrapf(err, "compile error")
}
if err := store.Commit(ctx, txn); err != nil {
return nil, errors.Wrapf(err, "storage error")
}
m, plugins, err := initPlugins(params.ID, store, params.ConfigFile)
if err != nil {
return nil, err
}
var decisionLogger func(context.Context, *server.Info)
if p, ok := plugins["decision_logs"]; ok {
decisionLogger = p.(*logs.Plugin).Log
if params.DecisionIDFactory == nil {
params.DecisionIDFactory = generateDecisionID
}
}
rt := &Runtime{
Store: store,
Manager: m,
Params: params,
decisionLogger: decisionLogger,
}
return rt, nil
}
// StartServer starts the runtime in server mode. This function will block the calling goroutine.
func (rt *Runtime) StartServer(ctx context.Context) {
setupLogging(rt.Params.Logging)
logrus.WithFields(logrus.Fields{
"addr": rt.Params.Addr,
"insecure_addr": rt.Params.InsecureAddr,
}).Infof("First line of log stream.")
if err := rt.Manager.Start(ctx); err != nil {
logrus.WithField("err", err).Fatalf("Unable to initialize plugins.")
}
s, err := server.New().
WithStore(rt.Store).
WithManager(rt.Manager).
WithCompilerErrorLimit(rt.Params.ErrorLimit).
WithAddress(rt.Params.Addr).
WithInsecureAddress(rt.Params.InsecureAddr).
WithCertificate(rt.Params.Certificate).
WithAuthentication(rt.Params.Authentication).
WithAuthorization(rt.Params.Authorization).
WithDiagnosticsBuffer(rt.Params.DiagnosticsBuffer).
WithDecisionIDFactory(rt.Params.DecisionIDFactory).
WithDecisionLogger(rt.decisionLogger).
Init(ctx)
if err != nil {
logrus.WithField("err", err).Fatalf("Unable to initialize server.")
}
if rt.Params.Watch {
if err := rt.startWatcher(ctx, rt.Params.Paths, onReloadLogger); err != nil {
fmt.Fprintln(rt.Params.Output, "error opening watch:", err)
os.Exit(1)
}
}
s.Handler = NewLoggingHandler(s.Handler)
loop1, loop2 := s.Listeners()
if loop2 != nil {
go func() {
if err := loop2(); err != nil {
logrus.WithField("err", err).Fatalf("Server exiting.")
}
}()
}
if err := loop1(); err != nil {
logrus.WithField("err", err).Fatalf("Server exiting.")
}
}
// StartREPL starts the runtime in REPL mode. This function will block the calling goroutine.
func (rt *Runtime) StartREPL(ctx context.Context) {
if err := rt.Manager.Start(ctx); err != nil {
fmt.Fprintln(rt.Params.Output, "error starting plugins:", err)
os.Exit(1)
}
banner := rt.getBanner()
repl := repl.New(rt.Store, rt.Params.HistoryPath, rt.Params.Output, rt.Params.OutputFormat, rt.Params.ErrorLimit, banner)
if rt.Params.Watch {
if err := rt.startWatcher(ctx, rt.Params.Paths, onReloadPrinter(rt.Params.Output)); err != nil {
fmt.Fprintln(rt.Params.Output, "error opening watch:", err)
os.Exit(1)
}
}
repl.Loop(ctx)
}
func (rt *Runtime) startWatcher(ctx context.Context, paths []string, onReload func(time.Duration, error)) error {
watcher, err := getWatcher(paths)
if err != nil {
return err
}
go rt.readWatcher(ctx, watcher, paths, onReload)
return nil
}
func (rt *Runtime) readWatcher(ctx context.Context, watcher *fsnotify.Watcher, paths []string, onReload func(time.Duration, error)) {
for {
select {
case evt := <-watcher.Events:
removalMask := (fsnotify.Remove | fsnotify.Rename)
mask := (fsnotify.Create | fsnotify.Write | removalMask)
if (evt.Op & mask) != 0 {
t0 := time.Now()
removed := ""
if (evt.Op & removalMask) != 0 {
removed = evt.Name
}
err := rt.processWatcherUpdate(ctx, paths, removed)
onReload(time.Since(t0), err)
}
}
}
}
func (rt *Runtime) processWatcherUpdate(ctx context.Context, paths []string, removed string) error {
loaded, err := loader.All(paths)
if err != nil {
return err
}
removed = loader.CleanPath(removed)
return storage.Txn(ctx, rt.Store, storage.WriteParams, func(txn storage.Transaction) error {
if err := rt.Store.Write(ctx, txn, storage.AddOp, storage.Path{}, loaded.Documents); err != nil {
return err
}
ids, err := rt.Store.ListPolicies(ctx, txn)
if err != nil {
return err
}
for _, id := range ids {
if id == removed {
if err := rt.Store.DeletePolicy(ctx, txn, id); err != nil {
return err
}
} else if _, exists := loaded.Modules[id]; !exists {
// This branch get hit in two cases.
// 1. Another piece of code has access to the store and inserts
// a policy out-of-band.
// 2. In between FS notification and loader.All() call above, a
// policy is removed from disk.
bs, err := rt.Store.GetPolicy(ctx, txn, id)
if err != nil {
return err
}
module, err := ast.ParseModule(id, string(bs))
if err != nil {
return err
}
if _, ok := loaded.Modules[id]; !ok {
loaded.Modules[id] = &loader.RegoFile{
Name: id,
Raw: bs,
Parsed: module,
}
}
}
}
return compileAndStoreInputs(ctx, rt.Store, txn, loaded.Modules, -1)
})
}
func (rt *Runtime) getBanner() string {
var buf bytes.Buffer
fmt.Fprintf(&buf, "OPA %v (commit %v, built at %v)\n", version.Version, version.Vcs, version.Timestamp)
fmt.Fprintf(&buf, "\n")
fmt.Fprintf(&buf, "Run 'help' to see a list of commands.\n")
return buf.String()
}
func compileAndStoreInputs(ctx context.Context, store storage.Store, txn storage.Transaction, modules map[string]*loader.RegoFile, errorLimit int) error {
policies := make(map[string]*ast.Module, len(modules))
for id, parsed := range modules {
policies[id] = parsed.Parsed
}
c := ast.NewCompiler().SetErrorLimit(errorLimit)
if c.Compile(policies); c.Failed() {
return c.Errors
}
for id, parsed := range modules {
if err := store.UpsertPolicy(ctx, txn, id, parsed.Raw); err != nil {
return err
}
}
return nil
}
func 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 {
if err := watcher.Add(path); 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, result...)
}
return paths, nil
}
func onReloadLogger(d time.Duration, err error) {
logrus.WithFields(logrus.Fields{
"duration": d,
"err": err,
}).Warn("Processed file watch event.")
}
func onReloadPrinter(output io.Writer) func(time.Duration, error) {
return func(d time.Duration, err error) {
if err != nil {
fmt.Fprintf(output, "\n# reload error (took %v): %v", d, err)
} else {
fmt.Fprintf(output, "\n# reloaded files (took %v)", d)
}
}
}
func setupLogging(config LoggingConfig) {
switch config.Format {
case "json":
logrus.SetFormatter(&logrus.JSONFormatter{})
default:
logrus.SetFormatter(&logrus.TextFormatter{
FullTimestamp: true,
})
}
lvl := logrus.InfoLevel
if config.Level != "" {
var err error
lvl, err = logrus.ParseLevel(config.Level)
if err != nil {
logrus.Fatalf("Unable to parse log level: %v", err)
}
}
logrus.SetLevel(lvl)
}
// TODO(tsandall): revisit how plugins are wired up to the manager and how
// everything is started and stopped. We could introduce a package-scoped
// plugin registry that allows for (dynamic) init-time plugin registration.
func initPlugins(id string, store storage.Store, configFile string) (*plugins.Manager, map[string]plugins.Plugin, error) {
var bs []byte
var err error
if configFile != "" {
bs, err = ioutil.ReadFile(configFile)
if err != nil {
return nil, nil, err
}
}
m, err := plugins.New(bs, id, store)
if err != nil {
return nil, nil, err
}
plugins := map[string]plugins.Plugin{}
bundlePlugin, err := initBundlePlugin(m, bs)
if err != nil {
return nil, nil, err
} else if bundlePlugin != nil {
plugins["bundle"] = bundlePlugin
}
if bundlePlugin != nil {
statusPlugin, err := initStatusPlugin(m, bs, bundlePlugin)
if err != nil {
return nil, nil, err
} else if statusPlugin != nil {
plugins["status"] = statusPlugin
}
}
decisionLogsPlugin, err := initDecisionLogsPlugin(m, bs)
if err != nil {
return nil, nil, err
} else if decisionLogsPlugin != nil {
plugins["decision_logs"] = decisionLogsPlugin
}
err = initRegisteredPlugins(m, bs)
if err != nil {
return nil, nil, err
}
return m, plugins, nil
}
func initBundlePlugin(m *plugins.Manager, bs []byte) (*bundle.Plugin, error) {
var config struct {
Bundle json.RawMessage `json:"bundle"`
}
if err := util.Unmarshal(bs, &config); err != nil {
return nil, err
}
if config.Bundle == nil {
return nil, nil
}
p, err := bundle.New(config.Bundle, m)
if err != nil {
return nil, err
}
m.Register(p)
return p, nil
}
func initDecisionLogsPlugin(m *plugins.Manager, bs []byte) (*logs.Plugin, error) {
var config struct {
DecisionLogs json.RawMessage `json:"decision_logs"`
}
if err := util.Unmarshal(bs, &config); err != nil {
return nil, err
}
if config.DecisionLogs == nil {
return nil, nil
}
p, err := logs.New(config.DecisionLogs, m)
if err != nil {
return nil, err
}
m.Register(p)
return p, nil
}
func initRegisteredPlugins(m *plugins.Manager, bs []byte) error {
var config struct {
Plugins map[string]json.RawMessage `json:"plugins"`
}
if err := util.Unmarshal(bs, &config); err != nil {
return err
}
for _, reg := range registeredPlugins {
pc, ok := config.Plugins[reg.name]
if !ok {
continue
}
plugin, err := reg.factory(m, pc)
if err != nil {
return err
}
m.Register(plugin)
}
return nil
}
func initStatusPlugin(m *plugins.Manager, bs []byte, bundlePlugin *bundle.Plugin) (*status.Plugin, error) {
var config struct {
Status json.RawMessage `json:"status"`
}
if err := util.Unmarshal(bs, &config); err != nil {
return nil, err
}
if config.Status == nil {
return nil, nil
}
p, err := status.New(config.Status, m)
if err != nil {
return nil, err
}
m.Register(p)
bundlePlugin.Register(bundlePluginListener("status-plugin"), func(s bundle.Status) {
p.Update(s)
})
return p, nil
}
func generateInstanceID() (string, error) {
return uuid4()
}
func generateDecisionID() string {
id, err := uuid4()
if err != nil {
return ""
}
return id
}
func uuid4() (string, error) {
bs := make([]byte, 16)
n, err := io.ReadFull(rand.Reader, bs)
if n != len(bs) || err != nil {
return "", err
}
bs[8] = bs[8]&^0xc0 | 0x80
bs[6] = bs[6]&^0xf0 | 0x40
return fmt.Sprintf("%x-%x-%x-%x-%x", bs[0:4], bs[4:6], bs[6:8], bs[8:10], bs[10:]), nil
}
type bundlePluginListener string