From 54df16c26fd35f5f6b66bd65ebc84d52b515876d Mon Sep 17 00:00:00 2001 From: Branden Horiuchi Date: Wed, 1 Dec 2021 10:03:57 -0800 Subject: [PATCH] Exposes the http router to the plugin manager In order to expose the http router to plugins a private router property was added to the plugin manager along with a GetRouter method to access it. A router is also initialized in the NewRuntime function if one is not provided in the runtime params. Fixes #2777 Signed-off-by: Branden Horiuchi --- plugins/plugins.go | 15 +++++++++++++++ runtime/runtime.go | 7 ++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/plugins/plugins.go b/plugins/plugins.go index 0e3fbb1a23..9c1ec0e614 100644 --- a/plugins/plugins.go +++ b/plugins/plugins.go @@ -11,6 +11,7 @@ import ( "sync" "time" + "github.com/gorilla/mux" "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/bundle" "github.com/open-policy-agent/opa/config" @@ -185,6 +186,7 @@ type Manager struct { serverInitializedOnce sync.Once printHook print.Hook enablePrintStatements bool + router *mux.Router } type managerContextKey string @@ -336,6 +338,12 @@ func PrintHook(h print.Hook) func(*Manager) { } } +func WithRouter(r *mux.Router) func(*Manager) { + return func(m *Manager) { + m.router = r + } +} + // New creates a new Manager using config. func New(raw []byte, id string, store storage.Store, opts ...func(*Manager)) (*Manager, error) { @@ -518,6 +526,13 @@ func (m *Manager) setCompiler(compiler *ast.Compiler) { m.compiler = compiler } +// GetRouter returns the managers router if set +func (m *Manager) GetRouter() *mux.Router { + m.mtx.Lock() + defer m.mtx.Unlock() + return m.router +} + // RegisterCompilerTrigger registers for change notifications when the compiler // is changed. func (m *Manager) RegisterCompilerTrigger(f func(txn storage.Transaction)) { diff --git a/runtime/runtime.go b/runtime/runtime.go index 8dde89e9cd..f7c5057c7b 100644 --- a/runtime/runtime.go +++ b/runtime/runtime.go @@ -299,6 +299,10 @@ func NewRuntime(ctx context.Context, params Params) (*Runtime, error) { consoleLogger = params.ConsoleLogger } + if params.Router == nil { + params.Router = mux.NewRouter() + } + manager, err := plugins.New(config, params.ID, inmem.New(), @@ -310,7 +314,8 @@ func NewRuntime(ctx context.Context, params Params) (*Runtime, error) { plugins.ConsoleLogger(consoleLogger), plugins.Logger(logger), plugins.EnablePrintStatements(logger.GetLevel() >= logging.Info), - plugins.PrintHook(loggingPrintHook{logger: logger})) + plugins.PrintHook(loggingPrintHook{logger: logger}), + plugins.WithRouter(params.Router)) if err != nil { return nil, errors.Wrap(err, "config error") }