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

core: fix deadlock when dependable node replaced with non-dependable one #2968

Merged
merged 3 commits into from
Aug 11, 2015
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
17 changes: 15 additions & 2 deletions dag/dag.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package dag

import (
"fmt"
"log"
"sort"
"strings"
"sync"
"time"

"github.com/hashicorp/go-multierror"
)
Expand Down Expand Up @@ -197,8 +199,19 @@ func (g *AcyclicGraph) Walk(cb WalkFunc) error {
readyCh := make(chan bool)
go func(v Vertex, deps []Vertex, chs []<-chan struct{}, readyCh chan<- bool) {
// First wait for all the dependencies
for _, ch := range chs {
<-ch
for i, ch := range chs {
DepSatisfied:
for {
select {
case <-ch:
break DepSatisfied
case <-time.After(time.Second * 5):
log.Printf("[DEBUG] vertex %s, waiting for: %s",
VertexName(v), VertexName(deps[i]))
}
}
log.Printf("[DEBUG] vertex %s, got dep: %s",
VertexName(v), VertexName(deps[i]))
Copy link
Contributor

Choose a reason for hiding this comment

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

I like this debugging.

}

// Then, check the map to see if any of our dependencies failed
Expand Down
26 changes: 6 additions & 20 deletions terraform/context_plan_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"strings"
"sync"
"testing"
"time"
)

func TestContext2Plan(t *testing.T) {
Expand Down Expand Up @@ -176,16 +175,11 @@ func TestContext2Plan_moduleCycle(t *testing.T) {
}

func TestContext2Plan_moduleDeadlock(t *testing.T) {
m := testModule(t, "plan-module-deadlock")
p := testProvider("aws")
p.DiffFn = testDiffFn
timeout := make(chan bool, 1)
done := make(chan bool, 1)
go func() {
time.Sleep(3 * time.Second)
timeout <- true
}()
go func() {
testCheckDeadlock(t, func() {
m := testModule(t, "plan-module-deadlock")
p := testProvider("aws")
p.DiffFn = testDiffFn

ctx := testContext2(t, &ContextOpts{
Module: m,
Providers: map[string]ResourceProviderFactory{
Expand All @@ -194,7 +188,6 @@ func TestContext2Plan_moduleDeadlock(t *testing.T) {
})

plan, err := ctx.Plan()
done <- true
if err != nil {
t.Fatalf("err: %s", err)
}
Expand All @@ -215,14 +208,7 @@ STATE:
if actual != expected {
t.Fatalf("expected:\n%sgot:\n%s", expected, actual)
}
}()

select {
case <-timeout:
t.Fatalf("timed out! probably deadlock")
case <-done:
// ok
}
})
}

func TestContext2Plan_moduleInput(t *testing.T) {
Expand Down
95 changes: 95 additions & 0 deletions terraform/context_refresh_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"reflect"
"sort"
"strings"
"sync"
"testing"
)

Expand Down Expand Up @@ -685,6 +686,100 @@ func TestContext2Refresh_vars(t *testing.T) {
}
}

func TestContext2Refresh_orphanModule(t *testing.T) {
p := testProvider("aws")
m := testModule(t, "refresh-module-orphan")

// Create a custom refresh function to track the order they were visited
var order []string
var orderLock sync.Mutex
p.RefreshFn = func(
info *InstanceInfo,
is *InstanceState) (*InstanceState, error) {
orderLock.Lock()
defer orderLock.Unlock()

order = append(order, is.ID)
return is, nil
}

state := &State{
Modules: []*ModuleState{
&ModuleState{
Path: rootModulePath,
Resources: map[string]*ResourceState{
"aws_instance.foo": &ResourceState{
Primary: &InstanceState{
ID: "i-abc123",
Attributes: map[string]string{
"childid": "i-bcd234",
"grandchildid": "i-cde345",
},
},
Dependencies: []string{
"module.child",
"module.child",
},
},
},
},
&ModuleState{
Path: append(rootModulePath, "child"),
Resources: map[string]*ResourceState{
"aws_instance.bar": &ResourceState{
Primary: &InstanceState{
ID: "i-bcd234",
Attributes: map[string]string{
"grandchildid": "i-cde345",
},
},
Dependencies: []string{
"module.grandchild",
},
},
},
Outputs: map[string]string{
"id": "i-bcd234",
"grandchild_id": "i-cde345",
},
},
&ModuleState{
Path: append(rootModulePath, "child", "grandchild"),
Resources: map[string]*ResourceState{
"aws_instance.baz": &ResourceState{
Primary: &InstanceState{
ID: "i-cde345",
},
},
},
Outputs: map[string]string{
"id": "i-cde345",
},
},
},
}
ctx := testContext2(t, &ContextOpts{
Module: m,
Providers: map[string]ResourceProviderFactory{
"aws": testProviderFuncFixed(p),
},
State: state,
})

testCheckDeadlock(t, func() {
_, err := ctx.Refresh()
if err != nil {
t.Fatalf("err: %s", err)
}

// TODO: handle order properly for orphaned modules / resources
// expected := []string{"i-abc123", "i-bcd234", "i-cde345"}
// if !reflect.DeepEqual(order, expected) {
// t.Fatalf("expected: %#v, got: %#v", expected, order)
// }
})
}

func TestContext2Validate(t *testing.T) {
p := testProvider("aws")
m := testModule(t, "validate-good")
Expand Down
22 changes: 22 additions & 0 deletions terraform/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"strings"
"testing"
"time"
)

func testContext2(t *testing.T, opts *ContextOpts) *Context {
Expand Down Expand Up @@ -170,6 +171,27 @@ func resourceState(resourceType, resourceID string) *ResourceState {
}
}

// Test helper that gives a function 3 seconds to finish, assumes deadlock and
// fails test if it does not.
func testCheckDeadlock(t *testing.T, f func()) {
timeout := make(chan bool, 1)
done := make(chan bool, 1)
go func() {
time.Sleep(3 * time.Second)
timeout <- true
}()
Copy link
Contributor

Choose a reason for hiding this comment

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

You should just use time.After here, it'll do all this for you.

go func(f func(), done chan bool) {
defer func() { done <- true }()
f()
}(f, done)
select {
case <-timeout:
Copy link
Contributor

Choose a reason for hiding this comment

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

Actually, you can just remove all the above timeout stuff and replace this with <-time.After(3 *time.Second)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I knew I had used something more concise before! Will do in a follow up commit. 👍

t.Fatalf("timed out! probably deadlock")
case <-done:
// ok
}
}

const testContextGraph = `
root: root
aws_instance.bar
Expand Down
6 changes: 5 additions & 1 deletion terraform/graph.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,11 @@ func (g *Graph) Replace(o, n dag.Vertex) bool {
// Go through and update our lookaside to point to the new vertex
for k, v := range g.dependableMap {
if v == o {
g.dependableMap[k] = n
if _, ok := n.(GraphNodeDependable); ok {
g.dependableMap[k] = n
} else {
delete(g.dependableMap, k)
}
}
}

Expand Down
37 changes: 34 additions & 3 deletions terraform/graph_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package terraform

import (
"reflect"
"strings"
"testing"
)
Expand All @@ -20,7 +21,7 @@ func TestGraphAdd(t *testing.T) {

func TestGraphConnectDependent(t *testing.T) {
var g Graph
g.Add(&testGraphDependable{VertexName: "a", Mock: []string{"a"}})
g.Add(&testGraphDependable{VertexName: "a"})
b := g.Add(&testGraphDependable{
VertexName: "b",
DependentOnMock: []string{"a"},
Expand All @@ -37,18 +38,48 @@ func TestGraphConnectDependent(t *testing.T) {
}
}

func TestGraphReplace_DependableWithNonDependable(t *testing.T) {
var g Graph
a := g.Add(&testGraphDependable{VertexName: "a"})
b := g.Add(&testGraphDependable{
VertexName: "b",
DependentOnMock: []string{"a"},
})
newA := "non-dependable-a"

if missing := g.ConnectDependent(b); len(missing) > 0 {
t.Fatalf("bad: %#v", missing)
}

if !g.Replace(a, newA) {
t.Fatalf("failed to replace")
}

c := g.Add(&testGraphDependable{
VertexName: "c",
DependentOnMock: []string{"a"},
})

// This should fail by reporting missing, since a node with dependable
// name "a" is no longer in the graph.
missing := g.ConnectDependent(c)
expected := []string{"a"}
if !reflect.DeepEqual(expected, missing) {
t.Fatalf("expected: %#v, got: %#v", expected, missing)
}
}

type testGraphDependable struct {
VertexName string
DependentOnMock []string
Mock []string
}

func (v *testGraphDependable) Name() string {
return v.VertexName
}

func (v *testGraphDependable) DependableName() []string {
return v.Mock
return []string{v.VertexName}
}

func (v *testGraphDependable) DependentOn() []string {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
resource "aws_instance" "baz" {}

output "id" { value = "${aws_instance.baz.id}" }
10 changes: 10 additions & 0 deletions terraform/test-fixtures/refresh-module-orphan/child/main.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module "grandchild" {
source = "./grandchild"
}

resource "aws_instance" "bar" {
grandchildid = "${module.grandchild.id}"
}

output "id" { value = "${aws_instance.bar.id}" }
output "grandchild_id" { value = "${module.grandchild.id}" }
10 changes: 10 additions & 0 deletions terraform/test-fixtures/refresh-module-orphan/main.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*
module "child" {
source = "./child"
}

resource "aws_instance" "bar" {
childid = "${module.child.id}"
grandchildid = "${module.child.grandchild_id}"
}
*/