Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(reset): Improve cycle detector #709

Merged
merged 2 commits into from
Nov 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 39 additions & 12 deletions loader/reset.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,12 @@ import (
type ResetProcessor struct {
target interface{}
paths []tree.Path
visitedNodes map[*yaml.Node]string
visitedNodes map[*yaml.Node][]string
}

// UnmarshalYAML implement yaml.Unmarshaler
func (p *ResetProcessor) UnmarshalYAML(value *yaml.Node) error {
p.visitedNodes = make(map[*yaml.Node][]string)
resolved, err := p.resolveReset(value, tree.NewPath())
p.visitedNodes = nil
if err != nil {
Expand Down Expand Up @@ -144,20 +145,46 @@ func (p *ResetProcessor) applyNullOverrides(target any, path tree.Path) error {
}

func (p *ResetProcessor) checkForCycle(node *yaml.Node, path tree.Path) error {
if p.visitedNodes == nil {
p.visitedNodes = make(map[*yaml.Node]string)
}
paths := p.visitedNodes[node]
pathStr := path.String()

// Check for cycle by seeing if the node has already been visited at this path
if previousPath, found := p.visitedNodes[node]; found {
// If the current node has been visited, we have a cycle if the previous path is a prefix
if strings.HasPrefix(path.String(), strings.TrimRight(previousPath, "<<")) {
return fmt.Errorf("cycle detected at path: %s", previousPath)
for _, prevPath := range paths {
// If we're visiting the exact same path, it's not a cycle
if pathStr == prevPath {
continue
}
}

// Mark the current node as visited
p.visitedNodes[node] = path.String()
// If either path is using a merge key, it's legitimate YAML merging
if strings.Contains(prevPath, "<<") || strings.Contains(pathStr, "<<") {
continue
}

// Only consider it a cycle if one path is contained within the other
// and they're not in different service definitions
if (strings.HasPrefix(pathStr, prevPath+".") ||
strings.HasPrefix(prevPath, pathStr+".")) &&
!areInDifferentServices(pathStr, prevPath) {
return fmt.Errorf("cycle detected: node at path %s references node at path %s", pathStr, prevPath)
}
}

p.visitedNodes[node] = append(paths, pathStr)
return nil
}

// areInDifferentServices checks if two paths are in different service definitions
func areInDifferentServices(path1, path2 string) bool {
// Split paths into components
parts1 := strings.Split(path1, ".")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: could use path.Parts() if you don't convert it to a string

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the function accepts strings and the field also has a list of strings visitedNodes map[*yaml.Node][]string, do you suggest to use path everywhere? or to convert the strings inside the func into paths and use Parts()? it looks like overhead, isn't it?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

some overhead indeed, but my point is that Path abstraction allows to ignore "implementation details" like the dot notation and [] or * patterns. I had in mind at some point we might want to use an alternate implementation vs string as we actually have to split this string many times during parsing.
From an encapsulation point of view, I'd prefer we add more utility func to Path to support required submatching.
ANYWAY I'm fine we merge this PR as a quick fix for this issue, and revisit this later

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ndeloof agree, that sounds reasonable.

parts2 := strings.Split(path2, ".")

// Look for the services component and compare the service names
for i := 0; i < len(parts1) && i < len(parts2); i++ {
if parts1[i] == "services" && i+1 < len(parts1) &&
parts2[i] == "services" && i+1 < len(parts2) {
// If they're different services, it's not a cycle
return parts1[i+1] != parts2[i+1]
}
}
return false
}
39 changes: 30 additions & 9 deletions loader/reset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func TestResetCycle(t *testing.T) {
errorMsg string
}{
{
name: "no cycle",
name: "simple_alias_no_cycle",
config: `
name: test
services:
Expand All @@ -99,10 +99,9 @@ services:
a2: *a
`,
expectError: false,
errorMsg: "",
},
{
name: "no cycle reversed",
name: "simple_alias_reversed_no_cycle",
config: `
name: test
services:
Expand All @@ -111,12 +110,11 @@ services:
a: *a
`,
expectError: false,
errorMsg: "",
},
{
name: "no cycle 2",
name: "nested_merge_no_cycle",
config: `
name: blah
name: test
x-templates:
x-gluetun: &gluetun
environment: &gluetun_env
Expand All @@ -131,17 +129,40 @@ x-templates:
<<: *gluetun_env_pia
`,
expectError: false,
errorMsg: "",
},
{
name: "healthcheck_cycle",
name: "multiple_services_common_config",
config: `
name: test
x-common:
&common
restart: unless-stopped

services:
backend:
<<: *common
image: alpine:latest

backend-static:
<<: *common
image: alpine:latest

backend-worker:
<<: *common
image: alpine:latest
`,
expectError: false,
},
{
name: "direct_self_reference_cycle",
config: `
name: test
x-healthcheck: &healthcheck
egress-service:
<<: *healthcheck
`,
expectError: true,
errorMsg: "cycle detected at path: x-healthcheck.egress-service",
errorMsg: "cycle detected: node at path x-healthcheck.egress-service.egress-service references node at path x-healthcheck.egress-service",
},
}

Expand Down