2020-05-21 23:07:18 +00:00
|
|
|
package mssqlhelper
|
|
|
|
|
|
|
|
import (
|
2020-09-15 14:01:26 +00:00
|
|
|
"context"
|
2020-05-21 23:07:18 +00:00
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
2020-09-15 14:01:26 +00:00
|
|
|
"net/url"
|
2020-05-21 23:07:18 +00:00
|
|
|
"os"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/hashicorp/vault/helper/testhelpers/docker"
|
|
|
|
)
|
|
|
|
|
2020-09-15 14:01:26 +00:00
|
|
|
const mssqlPassword = "yourStrong(!)Password"
|
|
|
|
|
2020-09-28 16:03:23 +00:00
|
|
|
// This constant is used in retrying the mssql container restart, since
|
|
|
|
// intermittently the container starts but mssql within the container
|
|
|
|
// is unreachable.
|
|
|
|
const numRetries = 3
|
|
|
|
|
2020-05-21 23:07:18 +00:00
|
|
|
func PrepareMSSQLTestContainer(t *testing.T) (cleanup func(), retURL string) {
|
|
|
|
if os.Getenv("MSSQL_URL") != "" {
|
|
|
|
return func() {}, os.Getenv("MSSQL_URL")
|
|
|
|
}
|
|
|
|
|
2020-09-28 16:03:23 +00:00
|
|
|
var err error
|
|
|
|
for i := 0; i < numRetries; i++ {
|
|
|
|
var svc *docker.Service
|
|
|
|
runner, err := docker.NewServiceRunner(docker.RunOptions{
|
|
|
|
ContainerName: "sqlserver",
|
|
|
|
ImageRepo: "mcr.microsoft.com/mssql/server",
|
|
|
|
ImageTag: "2017-latest-ubuntu",
|
|
|
|
Env: []string{"ACCEPT_EULA=Y", "SA_PASSWORD=" + mssqlPassword},
|
|
|
|
Ports: []string{"1433/tcp"},
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("Could not start docker MSSQL: %s", err)
|
|
|
|
}
|
2020-05-21 23:07:18 +00:00
|
|
|
|
2020-09-28 16:03:23 +00:00
|
|
|
svc, err = runner.StartService(context.Background(), connectMSSQL)
|
|
|
|
if err == nil {
|
|
|
|
return svc.Cleanup, svc.Config.URL().String()
|
|
|
|
}
|
2020-05-21 23:07:18 +00:00
|
|
|
}
|
|
|
|
|
2020-09-28 16:03:23 +00:00
|
|
|
t.Fatalf("Could not start docker MSSQL: %s", err)
|
|
|
|
return nil, ""
|
2020-09-15 14:01:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func connectMSSQL(ctx context.Context, host string, port int) (docker.ServiceConfig, error) {
|
|
|
|
u := url.URL{
|
|
|
|
Scheme: "sqlserver",
|
|
|
|
User: url.UserPassword("sa", mssqlPassword),
|
|
|
|
Host: fmt.Sprintf("%s:%d", host, port),
|
2020-05-21 23:07:18 +00:00
|
|
|
}
|
2021-11-05 18:53:37 +00:00
|
|
|
// Attempt to address connection flakiness within tests such as "Failed to initialize: error verifying connection ..."
|
|
|
|
u.Query().Add("Connection Timeout", "30")
|
2020-05-21 23:07:18 +00:00
|
|
|
|
2020-09-15 14:01:26 +00:00
|
|
|
db, err := sql.Open("mssql", u.String())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2020-05-21 23:07:18 +00:00
|
|
|
}
|
2020-09-15 14:01:26 +00:00
|
|
|
defer db.Close()
|
2020-05-21 23:07:18 +00:00
|
|
|
|
2020-09-15 14:01:26 +00:00
|
|
|
err = db.Ping()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return docker.NewServiceURL(u), nil
|
2020-05-21 23:07:18 +00:00
|
|
|
}
|