helpers_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package volumes
  2. import (
  3. "context"
  4. "os"
  5. "os/exec"
  6. "path/filepath"
  7. "testing"
  8. "time"
  9. "github.com/docker/docker/api/types"
  10. "github.com/docker/docker/testutil/fixtures/plugin"
  11. "github.com/moby/locker"
  12. "github.com/pkg/errors"
  13. "gotest.tools/v3/assert"
  14. )
  15. var pluginBuildLock = locker.New()
  16. // ensurePlugin makes the that a plugin binary has been installed on the system.
  17. // Plugins that have not been installed are built from `cmd/<name>`.
  18. func ensurePlugin(t *testing.T, name string) string {
  19. pluginBuildLock.Lock(name)
  20. defer pluginBuildLock.Unlock(name)
  21. goPath := os.Getenv("GOPATH")
  22. if goPath == "" {
  23. goPath = "/go"
  24. }
  25. installPath := filepath.Join(goPath, "bin", name)
  26. if _, err := os.Stat(installPath); err == nil {
  27. return installPath
  28. }
  29. goBin, err := exec.LookPath("go")
  30. assert.NilError(t, err)
  31. cmd := exec.Command(goBin, "build", "-o", installPath, "./"+filepath.Join("cmd", name))
  32. cmd.Env = append(os.Environ(), "CGO_ENABLED=0", "GO111MODULE=off")
  33. if out, err := cmd.CombinedOutput(); err != nil {
  34. t.Fatal(errors.Wrapf(err, "error building basic plugin bin: %s", string(out)))
  35. }
  36. return installPath
  37. }
  38. func withSockPath(name string) func(*plugin.Config) {
  39. return func(cfg *plugin.Config) {
  40. cfg.Interface.Socket = name
  41. }
  42. }
  43. func createPlugin(ctx context.Context, t *testing.T, client plugin.CreateClient, alias, bin string, opts ...plugin.CreateOpt) {
  44. pluginBin := ensurePlugin(t, bin)
  45. opts = append(opts, withSockPath("plugin.sock"))
  46. opts = append(opts, plugin.WithBinary(pluginBin))
  47. ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
  48. err := plugin.Create(ctx, client, alias, opts...)
  49. cancel()
  50. assert.NilError(t, err)
  51. }
  52. func asVolumeDriver(cfg *plugin.Config) {
  53. cfg.Interface.Types = []types.PluginInterfaceType{
  54. {Capability: "volumedriver", Prefix: "docker", Version: "1.0"},
  55. }
  56. }