Fix Windows support for custom-sd adapter (#6217)

* add test to custom-sd/adapter writeOutput() function

Signed-off-by: Benoit Gagnon <benoit.gagnon@ubisoft.com>

* 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 <benoit.gagnon@ubisoft.com>

* add missing dot to comment

Signed-off-by: Benoit Gagnon <benoit.gagnon@ubisoft.com>
This commit is contained in:
Benoit Gagnon 2019-10-29 05:41:31 -04:00 committed by Simon Pasquier
parent e0443e6fa3
commit 6d931a2195
2 changed files with 18 additions and 0 deletions

View file

@ -128,6 +128,9 @@ func (a *Adapter) writeOutput() error {
return err 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) err = os.Rename(tmpfile.Name(), a.output)
if err != nil { if err != nil {
return err return err

View file

@ -14,6 +14,10 @@
package adapter package adapter
import ( import (
"context"
"github.com/prometheus/prometheus/util/testutil"
"io/ioutil"
"os"
"reflect" "reflect"
"testing" "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())
}