Skip to content

Commit a30e177

Browse files
authored
Merge pull request #628 from aabidsofi19/rego-print
Add support for logging print statements from rego
2 parents 4fc6b1d + 9f59a99 commit a30e177

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

models/meshmodel/core/policies/rego_policy_relationship.go

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ import (
1010
"github.com/layer5io/meshkit/utils"
1111
"github.com/meshery/schemas/models/v1beta1/pattern"
1212
"github.com/open-policy-agent/opa/rego"
13-
1413
"github.com/open-policy-agent/opa/storage"
1514
"github.com/open-policy-agent/opa/storage/inmem"
15+
"github.com/open-policy-agent/opa/topdown/print"
1616
"github.com/sirupsen/logrus"
1717
)
1818

@@ -51,24 +51,44 @@ func NewRegoInstance(policyDir string, regManager *registry.RegistryManager) (*R
5151
}, nil
5252
}
5353

54+
// CustomPrintHook implements the print.Hook interface
55+
type CustomPrintHook struct {
56+
Messages []string
57+
}
58+
59+
// Print captures print messages from policy evaluation
60+
// Implements print.Hook interface
61+
func (h *CustomPrintHook) Print(ctx print.Context, s string) error {
62+
h.Messages = append(h.Messages, s)
63+
logrus.Info("[OPA] ", s)
64+
return nil
65+
}
66+
5467
// RegoPolicyHandler takes the required inputs and run the query against all the policy files provided
5568
func (r *Rego) RegoPolicyHandler(designFile pattern.PatternFile, regoQueryString string, relationshipsToEvalaute ...string) (pattern.EvaluationResponse, error) {
5669
var evaluationResponse pattern.EvaluationResponse
5770
if r == nil {
5871
return evaluationResponse, ErrEval(fmt.Errorf("policy engine is not yet ready"))
5972
}
73+
// Create custom print hook
74+
printHook := &CustomPrintHook{
75+
Messages: make([]string, 0),
76+
}
6077
regoEngine, err := rego.New(
78+
rego.PrintHook(printHook),
79+
rego.EnablePrintStatements(true), // Explicitly enable print statements
80+
rego.Transaction(r.transaction),
6181
rego.Query(regoQueryString),
6282
rego.Load([]string{r.policyDir}, nil),
6383
rego.Store(r.store),
64-
rego.Transaction(r.transaction),
6584
).PrepareForEval(r.ctx)
6685
if err != nil {
6786
logrus.Error("error preparing for evaluation", err)
6887
return evaluationResponse, ErrPrepareForEval(err)
6988
}
7089

7190
eval_result, err := regoEngine.Eval(r.ctx, rego.EvalInput(designFile))
91+
7292
if err != nil {
7393
return evaluationResponse, ErrEval(err)
7494
}

0 commit comments

Comments
 (0)