From 9289df6d352ea57f5107019fc8c2c447aacdb5d9 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Thu, 25 Jul 2013 21:24:49 -0500 Subject: [PATCH] packer/plugin: connect stdin to parent stdin --- packer/plugin/client.go | 1 + packer/plugin/client_test.go | 49 ++++++++++++++++++++++++++++++++++++ packer/plugin/plugin_test.go | 14 +++++++++++ 3 files changed, 64 insertions(+) diff --git a/packer/plugin/client.go b/packer/plugin/client.go index ac5d54f67..716d20990 100644 --- a/packer/plugin/client.go +++ b/packer/plugin/client.go @@ -216,6 +216,7 @@ func (c *Client) Start() (address string, err error) { cmd := c.config.Cmd cmd.Env = append(cmd.Env, os.Environ()...) cmd.Env = append(cmd.Env, env...) + cmd.Stdin = os.Stdin cmd.Stderr = stderr cmd.Stdout = stdout diff --git a/packer/plugin/client_test.go b/packer/plugin/client_test.go index 305308735..0601ed74d 100644 --- a/packer/plugin/client_test.go +++ b/packer/plugin/client_test.go @@ -1,6 +1,8 @@ package plugin import ( + "io/ioutil" + "os" "testing" "time" ) @@ -47,3 +49,50 @@ func TestClient_Start_Timeout(t *testing.T) { t.Fatal("err should not be nil") } } + +func TestClient_Stdin(t *testing.T) { + // Overwrite stdin for this test with a temporary file + tf, err := ioutil.TempFile("", "packer") + if err != nil { + t.Fatalf("err: %s", err) + } + defer os.Remove(tf.Name()) + defer tf.Close() + + if _, err = tf.WriteString("hello"); err != nil { + t.Fatalf("error: %s", err) + } + + if err = tf.Sync(); err != nil { + t.Fatalf("error: %s", err) + } + + if _, err = tf.Seek(0, 0); err != nil { + t.Fatalf("error: %s", err) + } + + oldStdin := os.Stdin + defer func() { os.Stdin = oldStdin }() + os.Stdin = tf + + process := helperProcess("stdin") + c := NewClient(&ClientConfig{Cmd: process}) + defer c.Kill() + + _, err = c.Start() + if err != nil { + t.Fatalf("error: %s", err) + } + + for { + if c.Exited() { + break + } + + time.Sleep(50 * time.Millisecond) + } + + if !process.ProcessState.Success() { + t.Fatal("process didn't exit cleanly") + } +} diff --git a/packer/plugin/plugin_test.go b/packer/plugin/plugin_test.go index a3b385511..c892616dc 100644 --- a/packer/plugin/plugin_test.go +++ b/packer/plugin/plugin_test.go @@ -2,6 +2,7 @@ package plugin import ( "fmt" + "log" "os" "os/exec" "testing" @@ -65,6 +66,19 @@ func TestHelperProcess(*testing.T) { ServeProvisioner(new(helperProvisioner)) case "start-timeout": time.Sleep(1 * time.Minute) + os.Exit(1) + case "stdin": + fmt.Println(":1234") + data := make([]byte, 5) + if _, err := os.Stdin.Read(data); err != nil { + log.Printf("stdin read error: %s", err) + os.Exit(100) + } + + if string(data) == "hello" { + os.Exit(0) + } + os.Exit(1) default: fmt.Fprintf(os.Stderr, "Unknown command: %q\n", cmd)