Skip to content

Commit

Permalink
Fix issue 186 - default is ignored (#420)
Browse files Browse the repository at this point in the history
## Description

<!-- 
Please do not leave this blank 
This PR [adds/removes/fixes/replaces] the [feature/bug/etc]. 
-->

Please include a summary of the changes and the related issue. Please
also include relevant motivation and context. List any dependencies that
are required for this change.


## What type of PR is this? (check all applicable)

- [ ] 🍕 Feature
- [x] 🐛 Bug Fix
- [ ] 📝 Documentation Update
- [ ] 🎨 Style
- [ ] 🧑‍💻 Code Refactor
- [ ] 🔥 Performance Improvements
- [x] ✅ Test
- [ ] 🤖 Build
- [ ] 🔁 CI
- [ ] 📦 Chore (Release)
- [ ] ⏩ Revert

## Related Tickets & Documents

<!-- 
Please use this format link issue numbers: Fixes #123

https://docs.github.com/en/free-pro-team@latest/github/managing-your-work-on-github/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword
-->
- Related Issue # (issue)
- Closes # 186
- Fixes # 186
> Remove if not applicable

## Screenshots

<!-- Visual changes require screenshots -->


## Added tests?

- [x ] 👍 yes
- [ ] 🙅 no, because they aren't needed
- [ ] 🙋 no, because I need help
- [ ] Separate ticket for tests # (issue/pr)

Please describe the tests that you ran to verify your changes. Provide
instructions so we can reproduce. Please also list any relevant details
for your test configuration


## Added to documentation?

- [ ] 📜 README.md
- [x ] 🙅 no documentation needed

## Checklist:

- [x ] My code follows the style guidelines of this project
- [ x] I have performed a self-review of my code
- [ x] I have commented my code, particularly in hard-to-understand
areas
- [ ] I have made corresponding changes to the documentation
- [x ] My changes generate no new warnings
- [ x] I have added tests that prove my fix is effective or that my
feature works
- [ x] New and existing unit tests pass locally with my changes  **
- [ ] Any dependent changes have been merged and published in downstream
modules

** NOTE:
Tests in screenshot below are failing on the main branch as well. So
while not all tests are passing with my change it is not the case that I
added any new failures.


![image](https://github.com/open-component-model/ocm-controller/assets/82829708/0d33bf10-a889-44ee-b7ce-4f784e1126be)

---------

Co-authored-by: Gergely Brautigam <182850+Skarlso@users.noreply.github.com>
  • Loading branch information
dee0sap and Skarlso authored May 15, 2024
1 parent 697c798 commit 82d095a
Show file tree
Hide file tree
Showing 7 changed files with 257 additions and 40 deletions.
40 changes: 12 additions & 28 deletions controllers/mutation_reconcile_looper.go
Original file line number Diff line number Diff line change
Expand Up @@ -507,47 +507,31 @@ func (m *MutationReconcileLooper) createSubstitutionRulesForConfigurationValues(

func (m *MutationReconcileLooper) generateSubstitutions(
subst []localize.Substitution,
defaults, values, schema []byte,
defaults, configValues, schema []byte,
) (localize.Substitutions, error) {
// configure defaults
templ := make(map[string]any)
if err := ocmruntime.DefaultYAMLEncoding.Unmarshal(defaults, &templ); err != nil {
return nil, fmt.Errorf("cannot unmarshal template: %w", err)
}

// configure values overrides... must be a better way
var valuesMap map[string]any
if err := ocmruntime.DefaultYAMLEncoding.Unmarshal(values, &valuesMap); err != nil {
return nil, fmt.Errorf("cannot unmarshal values: %w", err)
}
var err error
var spiffTemplateDoc *spiffTemplateDoc

for k, v := range valuesMap {
if _, ok := templ[k]; ok {
templ[k] = v
}
if spiffTemplateDoc, err = mergeDefaultsAndConfigValues(defaults, configValues); err != nil {
return nil, err
}

// configure adjustments
list := []any{}
for _, e := range subst {
list = append(list, e)
if err = spiffTemplateDoc.addSpiffRules(subst); err != nil {
return nil, err
}

templateKey := "ocmAdjustmentsTemplateKey"
templ[templateKey] = list

templateBytes, err := ocmruntime.DefaultJSONEncoding.Marshal(templ)
if err != nil {
return nil, fmt.Errorf("cannot marshal template: %w", err)
var spiffTemplateBytes []byte
if spiffTemplateBytes, err = spiffTemplateDoc.marshal(); err != nil {
return nil, err
}

if len(schema) > 0 {
if err := spiff.ValidateByScheme(values, schema); err != nil {
if err := spiff.ValidateByScheme(configValues, schema); err != nil {
return nil, fmt.Errorf("validation failed: %w", err)
}
}

config, err := spiff.CascadeWith(spiff.TemplateData(templateKey, templateBytes), spiff.Mode(spiffing.MODE_PRIVATE))
config, err := spiff.CascadeWith(spiff.TemplateData(ocmAdjustmentsTemplateKey, spiffTemplateBytes), spiff.Mode(spiffing.MODE_PRIVATE))
if err != nil {
return nil, fmt.Errorf("error while doing cascade with: %w", err)
}
Expand Down
32 changes: 32 additions & 0 deletions controllers/mutation_reconcile_looper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package controllers

import (
"context"
"encoding/json"
"testing"

"cuelang.org/go/cue"
Expand All @@ -17,6 +18,7 @@ import (

v1 "github.com/open-component-model/ocm/pkg/contexts/ocm/compdesc/meta/v1"
"github.com/open-component-model/ocm/pkg/contexts/ocm/compdesc/versions/ocm.software/v3alpha1"
"github.com/open-component-model/ocm/pkg/contexts/ocm/utils/localize"
ocmruntime "github.com/open-component-model/ocm/pkg/runtime"

"github.com/open-component-model/ocm-controller/api/v1alpha1"
Expand All @@ -43,6 +45,36 @@ type reference struct {
component string
}

func TestGenerateSubstitutionsUseDefaults(t *testing.T) {
m := &MutationReconcileLooper{}
iSbs := localize.Substitutions{
localize.Substitution{
FilePath: "values.yaml",
ValueMapping: localize.ValueMapping{
Name: "1",
ValuePath: "dmi.gcp_project_id",
Value: []byte("\"(( dmi.gcp_project_id ))\""),
},
},
}

dflts := `dmi:
some_aws_val: foo
gcp_project_id: ~`

vls := `dmi:
some_aws_val: blah`

schm := ""

oSbs, err := m.generateSubstitutions(iSbs, []byte(dflts), []byte(vls), []byte(schm))
assert.NoError(t, err)
assert.Equal(t, len(iSbs), len(oSbs))
var expected json.RawMessage
expected.UnmarshalJSON([]byte("null"))
assert.Equal(t, oSbs[0].ValueMapping.Value, expected)
}

func TestPopulateReferences(t *testing.T) {
ctx := context.Background()
cueCtx := cuecontext.New()
Expand Down
139 changes: 139 additions & 0 deletions controllers/spifftemplatedoc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
// SPDX-FileCopyrightText: 2022 SAP SE or an SAP affiliate company and Open Component Model contributors.
//
// SPDX-License-Identifier: Apache-2.0

package controllers

import (
"bytes"
"container/list"
"fmt"

"github.com/mikefarah/yq/v4/pkg/yqlib"
"github.com/open-component-model/ocm/pkg/contexts/ocm/utils/localize"
ocmruntime "github.com/open-component-model/ocm/pkg/runtime"
)

// Key we store spiff rules under within spiff template doc.
const ocmAdjustmentsTemplateKey = "ocmAdjustmentsTemplateKey"

// makeYqNode unmarshalls bytes into a CandidateNode
// In order to make debugging easier later during yaml processing we take in
// file name, document index and file index values which are then set on
// the CandidateNode.
func makeYqNode(docBytes []byte, fileName string, docIndex, fileIndex uint) (*yqlib.CandidateNode, error) {
yamlPreferences := yqlib.NewDefaultYamlPreferences()
yamlDecoder := yqlib.NewYamlDecoder(yamlPreferences)
rdr := bytes.NewBuffer(docBytes)

if err := yamlDecoder.Init(rdr); err != nil {
return nil, err
}

ret, err := yamlDecoder.Decode()
if err != nil {
return nil, err
}

ret.SetDocument(docIndex)
ret.SetFilename(fileName)
ret.SetFileIndex(int(fileIndex))

return ret, nil
}

// spiffTemplateDoc is a wrapper around CandidateNode. Its purpose is to make the code in
// MutationReconcileLooper::generateSubstitutions easier to read.
//
// spiffTemplateDoc also represents a spiff++ template with a particular structure :
// ( defaults yaml merged with config values yaml )
// + sequence of ocm controller conifg rules stored under the key 'ocmAdjustmentsTemplateKey'.
type spiffTemplateDoc yqlib.CandidateNode

// Store subst, in json form, under key ocmAdjustmentsTemplateKey.
func (s *spiffTemplateDoc) addSpiffRules(subst []localize.Substitution) error {
var err error

var adjustmentBytes []byte
if adjustmentBytes, err = ocmruntime.DefaultJSONEncoding.Marshal(subst); err != nil {
return fmt.Errorf("failed to marshal substitutions: %w", err)
}

var adjustmentsDoc *yqlib.CandidateNode

const fileIndex = 2
if adjustmentsDoc, err = makeYqNode(adjustmentBytes, "adjustments", 0, fileIndex); err != nil {
return fmt.Errorf("failed to marshal adjustments: %w", err)
}

((*yqlib.CandidateNode)(s)).AddKeyValueChild(
&yqlib.CandidateNode{
Kind: yqlib.ScalarNode,
Value: ocmAdjustmentsTemplateKey,
},
adjustmentsDoc)

return nil
}

func (s *spiffTemplateDoc) marshal() ([]byte, error) {
encoder := yqlib.NewYamlEncoder(yqlib.NewDefaultYamlPreferences())
buf := bytes.NewBuffer([]byte{})
pw := yqlib.NewSinglePrinterWriter(buf)
p := yqlib.NewPrinter(encoder, pw)

// Often yq is working with list of nodes because matches what
// yaml files are. Yaml files are sequences of yaml documents.
// This is one of those case.
nodes := list.New()
nodes.PushBack(((*yqlib.CandidateNode)(s)))

if err := p.PrintResults(nodes); err != nil {
return nil, fmt.Errorf("failed to print results: %w", err)
}

return buf.Bytes(), nil
}

// mergeDefaultsAndConfigValues unmarshals defaults and configValues to yaml
// and then returns the deep merge result produced by yqlib.
func mergeDefaultsAndConfigValues(defaults, configValues []byte) (*spiffTemplateDoc, error) {
var err error
var defaultsDoc, configValuesDoc *yqlib.CandidateNode

if defaultsDoc, err = makeYqNode(defaults, "defaults", 0, 0); err != nil {
return nil, fmt.Errorf("failed to make default document: %w", err)
}

if configValuesDoc, err = makeYqNode(configValues, "values", 0, 1); err != nil {
return nil, fmt.Errorf("failed to parse values values: %w", err)
}

evaluator := yqlib.NewAllAtOnceEvaluator()
var mergeResult *list.List
const mergeExpression = ". as $item ireduce({}; . * $item )"

// We get back a list because yq supports expressions that produce
// multiple yaml documents.
// And unfortunately golang lists aren't type safe.
// So now we have all these assertions to make sure we got back a single
// yaml document like we expect.
if mergeResult, err = evaluator.EvaluateNodes(mergeExpression, defaultsDoc, configValuesDoc); err != nil {
return nil, fmt.Errorf("failed to evaluate nodes: %w", err)
}

if docCount := mergeResult.Len(); docCount != 1 {
return nil, fmt.Errorf("merge of defaults and config has incorrect doc count. docCount: %v expression: '%v' defaults: '%v' config values '%v",
docCount, mergeExpression, defaultsDoc, configValuesDoc)
}

if value := mergeResult.Front().Value; value == nil {
return nil, fmt.Errorf("merge of defaults and config values produced nil result. expression: '%v' defaults: '%v' config values '%v",
mergeExpression, defaultsDoc, configValuesDoc)
} else if node, ok := value.(*yqlib.CandidateNode); ok {
return ((*spiffTemplateDoc)(node)), nil
}

return nil, fmt.Errorf("merge of defaults and config values did not produce *CandidateNode. expression: '%v' defaults: '%v' config values '%v",
mergeExpression, defaultsDoc, configValuesDoc)
}
20 changes: 20 additions & 0 deletions controllers/yqlib_log_init.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//go:build test

// SPDX-FileCopyrightText: 2022 SAP SE or an SAP affiliate company and Open Component Model contributors.
//
// SPDX-License-Identifier: Apache-2.0

package controllers

import (
glog "gopkg.in/op/go-logging.v1"
)

// In production main func will take care of setting the log yq-lib log level.
// In test we count on this to set the default log level for all tests.
// We do this because yqlib log is very chatty even if it is sometimes very useful.
// Of course in an individual test one could change the level and reset to the default
// via a defer call.
func init() {
glog.SetLevel(glog.WARNING, "yq-lib")
}
18 changes: 13 additions & 5 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ require (
github.com/vmware-labs/yaml-jsonpath v0.3.2
github.com/xeipuuv/gojsonschema v1.2.0
golang.org/x/exp v0.0.0-20240103183307-be819d1f06fc
gopkg.in/op/go-logging.v1 v1.0.0-20160211212156-b2cb9fa56473
helm.sh/helm/v3 v3.14.2
k8s.io/apimachinery v0.29.0
k8s.io/client-go v0.29.0
Expand Down Expand Up @@ -92,7 +93,9 @@ require (
github.com/Microsoft/hcsshim v0.12.0-rc.1 // indirect
github.com/ProtonMail/go-crypto v0.0.0-20230923063757-afb1ddc0824c // indirect
github.com/ThalesIgnite/crypto11 v1.2.5 // indirect
github.com/a8m/envsubst v1.4.2 // indirect
github.com/acomagu/bufpipe v1.0.3 // indirect
github.com/alecthomas/participle/v2 v2.1.1 // indirect
github.com/alibabacloud-go/alibabacloud-gateway-spi v0.0.4 // indirect
github.com/alibabacloud-go/cr-20160607 v1.0.1 // indirect
github.com/alibabacloud-go/cr-20181201 v1.0.10 // indirect
Expand Down Expand Up @@ -161,6 +164,7 @@ require (
github.com/docker/libtrust v0.0.0-20160708172513-aabc10ec26b7 // indirect
github.com/dprotaso/go-yit v0.0.0-20191028211022-135eb7262960 // indirect
github.com/drone/envsubst v1.0.3 // indirect
github.com/elliotchance/orderedmap v1.5.1 // indirect
github.com/emicklei/go-restful/v3 v3.11.1 // indirect
github.com/evanphx/json-patch v5.7.0+incompatible // indirect
github.com/evanphx/json-patch/v5 v5.7.0 // indirect
Expand Down Expand Up @@ -194,6 +198,7 @@ require (
github.com/go-openapi/strfmt v0.22.1 // indirect
github.com/go-openapi/validate v0.22.4 // indirect
github.com/go-test/deep v1.1.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/goccy/go-yaml v1.11.3 // indirect
github.com/golang-jwt/jwt/v4 v4.5.0 // indirect
github.com/golang/snappy v0.0.4 // indirect
Expand Down Expand Up @@ -224,6 +229,7 @@ require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
github.com/jedisct1/go-minisign v0.0.0-20230811132847-661be99b8267 // indirect
github.com/jinzhu/copier v0.4.0 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/klauspost/compress v1.17.4 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
Expand Down Expand Up @@ -256,7 +262,7 @@ require (
github.com/opentracing/opentracing-go v1.2.0 // indirect
github.com/pborman/uuid v1.2.1 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.0 // indirect
github.com/peterbourgon/diskv v2.0.1+incompatible // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
Expand Down Expand Up @@ -299,6 +305,7 @@ require (
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xlab/treeprint v1.2.0 // indirect
github.com/yuin/gopher-lua v1.1.1 // indirect
github.com/zeebo/blake3 v0.2.3 // indirect
github.com/zeebo/errs v1.3.0 // indirect
go.mongodb.org/mongo-driver v1.14.0 // indirect
Expand Down Expand Up @@ -347,6 +354,7 @@ require (
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mikefarah/yq/v4 v4.43.1
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
Expand All @@ -358,11 +366,11 @@ require (
github.com/spf13/pflag v1.0.5 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.26.0 // indirect
golang.org/x/crypto v0.19.0 // indirect
golang.org/x/net v0.20.0 // indirect
golang.org/x/crypto v0.21.0 // indirect
golang.org/x/net v0.22.0 // indirect
golang.org/x/oauth2 v0.16.0 // indirect
golang.org/x/sys v0.17.0 // indirect
golang.org/x/term v0.17.0 // indirect
golang.org/x/sys v0.18.0 // indirect
golang.org/x/term v0.18.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/time v0.5.0 // indirect
gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect
Expand Down
Loading

0 comments on commit 82d095a

Please sign in to comment.