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()) +}