From 6d931a219506f75bc88583ddcf47be1d52409550 Mon Sep 17 00:00:00 2001 From: Benoit Gagnon Date: Tue, 29 Oct 2019 05:41:31 -0400 Subject: [PATCH] Fix Windows support for custom-sd adapter (#6217) * add test to custom-sd/adapter writeOutput() function Signed-off-by: Benoit Gagnon * fix Adapter.writeOutput() function to work on Windows On that platform, files cannot be moved while a process holds a handle to them. Added an explicit Close() before that move. With this change, the unit test succeeds. Signed-off-by: Benoit Gagnon * add missing dot to comment Signed-off-by: Benoit Gagnon --- .../examples/custom-sd/adapter/adapter.go | 3 +++ .../examples/custom-sd/adapter/adapter_test.go | 15 +++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/documentation/examples/custom-sd/adapter/adapter.go b/documentation/examples/custom-sd/adapter/adapter.go index c07a79f45..806eff9ab 100644 --- a/documentation/examples/custom-sd/adapter/adapter.go +++ b/documentation/examples/custom-sd/adapter/adapter.go @@ -128,6 +128,9 @@ func (a *Adapter) writeOutput() error { return err } + // Close the file immediately for platforms (eg. Windows) that cannot move + // a file while a process is holding a file handle. + tmpfile.Close() err = os.Rename(tmpfile.Name(), a.output) if err != nil { return err diff --git a/documentation/examples/custom-sd/adapter/adapter_test.go b/documentation/examples/custom-sd/adapter/adapter_test.go index 2cdc98c61..40cbbbacf 100644 --- a/documentation/examples/custom-sd/adapter/adapter_test.go +++ b/documentation/examples/custom-sd/adapter/adapter_test.go @@ -14,6 +14,10 @@ package adapter import ( + "context" + "github.com/prometheus/prometheus/util/testutil" + "io/ioutil" + "os" "reflect" "testing" @@ -222,3 +226,14 @@ func TestGenerateTargetGroups(t *testing.T) { } } + +// TestWriteOutput checks the adapter can write a file to disk. +func TestWriteOutput(t *testing.T) { + ctx := context.Background() + tmpfile, err := ioutil.TempFile("", "sd_adapter_test") + testutil.Ok(t, err) + defer os.Remove(tmpfile.Name()) + tmpfile.Close() + adapter := NewAdapter(ctx, tmpfile.Name(), "test_sd", nil, nil) + testutil.Ok(t, adapter.writeOutput()) +}