1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
|
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package integration
import (
"context"
"crypto/tls"
"io/ioutil"
"os"
"path"
"runtime"
"strings"
"testing"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/internal/assert"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/description"
"go.mongodb.org/mongo-driver/mongo/integration/mtest"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/x/mongo/driver/connstring"
"go.mongodb.org/mongo-driver/x/mongo/driver/topology"
)
const (
seedlistDiscoveryTestsBaseDir = "../../testdata/initial-dns-seedlist-discovery"
)
type seedlistTest struct {
URI string `bson:"uri"`
Seeds []string `bson:"seeds"`
NumSeeds *int `bson:"numSeeds"`
Hosts []string `bson:"hosts"`
NumHosts *int `bson:"numHosts"`
Error bool `bson:"error"`
Options bson.Raw `bson:"options"`
Ping *bool `bson:"ping"`
}
func TestInitialDNSSeedlistDiscoverySpec(t *testing.T) {
mt := mtest.New(t, noClientOpts)
mt.RunOpts("replica set", mtest.NewOptions().Topologies(mtest.ReplicaSet).CreateClient(false), func(mt *mtest.T) {
mt.Parallel()
runSeedlistDiscoveryDirectory(mt, "replica-set")
})
mt.RunOpts("sharded", mtest.NewOptions().Topologies(mtest.Sharded).CreateClient(false), func(mt *mtest.T) {
mt.Parallel()
runSeedlistDiscoveryDirectory(mt, "sharded")
})
mt.RunOpts("load balanced", mtest.NewOptions().Topologies(mtest.LoadBalanced).CreateClient(false), func(mt *mtest.T) {
mt.Parallel()
runSeedlistDiscoveryDirectory(mt, "load-balanced")
})
}
func runSeedlistDiscoveryDirectory(mt *mtest.T, subdirectory string) {
directoryPath := path.Join(seedlistDiscoveryTestsBaseDir, subdirectory)
for _, file := range jsonFilesInDir(mt, directoryPath) {
mt.RunOpts(file, noClientOpts, func(mt *mtest.T) {
runSeedlistDiscoveryTest(mt, path.Join(directoryPath, file))
})
}
}
// runSeedlistDiscoveryPingTest will create a new connection using the test URI and attempt to "ping" the server.
func runSeedlistDiscoveryPingTest(mt *mtest.T, clientOpts *options.ClientOptions) {
ctx := context.Background()
client, err := mongo.Connect(ctx, clientOpts)
assert.Nil(mt, err, "Connect error: %v", err)
defer func() { _ = client.Disconnect(ctx) }()
// Create a context with a timeout to prevent the ping operation from blocking indefinitely.
pingCtx, cancel := context.WithTimeout(ctx, 1*time.Second)
defer cancel()
// Ping the server.
err = client.Ping(pingCtx, readpref.Nearest())
assert.Nil(mt, err, "Ping error: %v", err)
}
func runSeedlistDiscoveryTest(mt *mtest.T, file string) {
content, err := ioutil.ReadFile(file)
assert.Nil(mt, err, "ReadFile error for %v: %v", file, err)
var test seedlistTest
err = bson.UnmarshalExtJSONWithRegistry(specTestRegistry, content, false, &test)
assert.Nil(mt, err, "UnmarshalExtJSONWithRegistry error: %v", err)
if runtime.GOOS == "windows" && strings.HasSuffix(file, "/two-txt-records.json") {
mt.Skip("skipping to avoid windows multiple TXT record lookup bug")
}
if strings.HasPrefix(runtime.Version(), "go1.11") && strings.HasSuffix(file, "/one-txt-record-multiple-strings.json") {
mt.Skip("skipping to avoid go1.11 problem with multiple strings in one TXT record")
}
cs, err := connstring.ParseAndValidate(test.URI)
if test.Error {
assert.NotNil(mt, err, "expected URI parsing error, got nil")
return
}
assert.Nil(mt, err, "ParseAndValidate error: %v", err)
assert.Equal(mt, connstring.SchemeMongoDBSRV, cs.Scheme,
"expected scheme %v, got %v", connstring.SchemeMongoDBSRV, cs.Scheme)
// DNS records may be out of order from the test file's ordering.
actualSeedlist := buildSet(cs.Hosts)
// If NumSeeds is set, check number of seeds in seedlist.
if test.NumSeeds != nil {
assert.Equal(mt, len(actualSeedlist), *test.NumSeeds,
"expected %v seeds, got %v", *test.NumSeeds, len(actualSeedlist))
}
// If Seeds is set, check contents of seedlist.
if test.Seeds != nil {
expectedSeedlist := buildSet(test.Seeds)
assert.Equal(mt, expectedSeedlist, actualSeedlist, "expected seedlist %v, got %v", expectedSeedlist, actualSeedlist)
}
verifyConnstringOptions(mt, test.Options, cs)
tlsConfig := getSSLSettings(mt, test)
// Make a topology from the options.
opts := options.Client().ApplyURI(test.URI)
if tlsConfig != nil {
opts.SetTLSConfig(tlsConfig)
}
cfg, err := topology.NewConfig(opts, nil)
assert.Nil(mt, err, "error constructing toplogy config: %v", err)
topo, err := topology.New(cfg)
assert.Nil(mt, err, "topology.New error: %v", err)
err = topo.Connect()
assert.Nil(mt, err, "topology.Connect error: %v", err)
defer func() { _ = topo.Disconnect(context.Background()) }()
// If NumHosts is set, check number of hosts currently stored on the Topology.
if test.NumHosts != nil {
actualNumHosts := len(topo.Description().Servers)
assert.Equal(mt, *test.NumHosts, actualNumHosts, "expected to find %v hosts, found %v",
*test.NumHosts, actualNumHosts)
}
for _, host := range test.Hosts {
_, err := getServerByAddress(host, topo)
assert.Nil(mt, err, "error finding host %q: %v", host, err)
}
if ping := test.Ping; ping == nil || *ping {
runSeedlistDiscoveryPingTest(mt, opts)
}
}
func buildSet(list []string) map[string]struct{} {
set := make(map[string]struct{})
for _, s := range list {
set[s] = struct{}{}
}
return set
}
func verifyConnstringOptions(mt *mtest.T, expected bson.Raw, cs *connstring.ConnString) {
mt.Helper()
elems, _ := expected.Elements()
for _, elem := range elems {
key := elem.Key()
opt := elem.Value()
switch key {
case "replicaSet":
rs := opt.StringValue()
assert.Equal(mt, rs, cs.ReplicaSet, "expected replicaSet value %v, got %v", rs, cs.ReplicaSet)
case "ssl":
ssl := opt.Boolean()
assert.Equal(mt, ssl, cs.SSL, "expected ssl value %v, got %v", ssl, cs.SSL)
case "authSource":
source := opt.StringValue()
assert.Equal(mt, source, cs.AuthSource, "expected auth source value %v, got %v", source, cs.AuthSource)
case "directConnection":
dc := opt.Boolean()
assert.True(mt, cs.DirectConnectionSet, "expected cs.DirectConnectionSet to be true, got false")
assert.Equal(mt, dc, cs.DirectConnection, "expected cs.DirectConnection to be %v, got %v", dc, cs.DirectConnection)
case "loadBalanced":
lb := opt.Boolean()
assert.True(mt, cs.LoadBalancedSet, "expected cs.LoadBalancedSet set to be true, got false")
assert.Equal(mt, lb, cs.LoadBalanced, "expected cs.LoadBalanced to be %v, got %v", lb, cs.LoadBalanced)
case "srvMaxHosts":
srvMaxHosts := opt.Int32()
assert.Equal(mt, srvMaxHosts, int32(cs.SRVMaxHosts), "expected cs.SRVMaxHosts to be %v, got %v", srvMaxHosts, cs.SRVMaxHosts)
case "srvServiceName":
srvName := opt.StringValue()
assert.Equal(mt, srvName, cs.SRVServiceName, "expected cs.SRVServiceName to be %q, got %q", srvName, cs.SRVServiceName)
default:
mt.Fatalf("unrecognized connstring option %v", key)
}
}
}
// Because the Go driver tests can be run either against a server with SSL enabled or without, a
// number of configurations have to be checked to ensure that the SRV tests are run properly.
//
// First, the "ssl" option in the JSON test description has to be checked. If this option is not
// present, we assume that the test will assert an error, so we proceed with the test as normal.
// If the option is false, then we skip the test if the server is running with SSL enabled.
// If the option is true, then we skip the test if the server is running without SSL enabled; if
// the server is running with SSL enabled, then we return a tls.Config with InsecureSkipVerify
// set to true.
func getSSLSettings(mt *mtest.T, test seedlistTest) *tls.Config {
ssl, err := test.Options.LookupErr("ssl")
if err != nil {
// No "ssl" option is specified
return nil
}
testCaseExpectsSSL := ssl.Boolean()
envSSL := os.Getenv("SSL") == "ssl"
// Skip non-SSL tests if the server is running with SSL.
if !testCaseExpectsSSL && envSSL {
mt.Skip("skipping test that does not expect ssl in an ssl environment")
}
// Skip SSL tests if the server is running without SSL.
if testCaseExpectsSSL && !envSSL {
mt.Skip("skipping test that expects ssl in a non-ssl environment")
}
// If SSL tests are running, set the CA file.
if testCaseExpectsSSL && envSSL {
tlsConfig := new(tls.Config)
tlsConfig.InsecureSkipVerify = true
return tlsConfig
}
return nil
}
func getServerByAddress(address string, topo *topology.Topology) (description.Server, error) {
selectByName := description.ServerSelectorFunc(func(_ description.Topology, servers []description.Server) ([]description.Server, error) {
for _, s := range servers {
if s.Addr.String() == address {
return []description.Server{s}, nil
}
}
return []description.Server{}, nil
})
selectedServer, err := topo.SelectServer(context.Background(), selectByName)
if err != nil {
return description.Server{}, err
}
// If the selected server is a topology.SelectedServer, then we can get the description without creating a
// connect pool.
topologySelectedServer, ok := selectedServer.(*topology.SelectedServer)
if ok {
return topologySelectedServer.Description().Server, nil
}
selectedServerConnection, err := selectedServer.Connection(context.Background())
if err != nil {
return description.Server{}, err
}
defer selectedServerConnection.Close()
return selectedServerConnection.Description(), nil
}
|