Skip to content

Commit

Permalink
[v10] Mongo clients with serverSelectionTimeoutMS set to 5000 (#13860)
Browse files Browse the repository at this point in the history
  • Loading branch information
greedy52 authored Jun 28, 2022
1 parent 71cafa8 commit 57636bd
Show file tree
Hide file tree
Showing 6 changed files with 93 additions and 34 deletions.
65 changes: 54 additions & 11 deletions lib/client/db/dbcmd/dbcmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,24 @@ package dbcmd

import (
"fmt"
"net/url"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"

"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/x/mongo/driver/connstring"

"github.com/gravitational/teleport/lib/client"
"github.com/gravitational/teleport/lib/client/db"
"github.com/gravitational/teleport/lib/client/db/mysql"
"github.com/gravitational/teleport/lib/client/db/postgres"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/tlsca"
"github.com/gravitational/teleport/lib/utils"

"github.com/gravitational/trace"

"github.com/sirupsen/logrus"
)

const (
Expand Down Expand Up @@ -359,10 +361,7 @@ func (c *CLICommandBuilder) getMongoCommand() *exec.Cmd {
// look for `mongosh`
hasMongosh := c.isMongoshBinAvailable()

args := []string{
"--host", c.host,
"--port", strconv.Itoa(c.port),
}
var args []string

if !c.options.noTLS {
// Starting with Mongo 4.2 there is an updated set of flags.
Expand Down Expand Up @@ -400,9 +399,9 @@ func (c *CLICommandBuilder) getMongoCommand() *exec.Cmd {
}
}

if c.db.Database != "" {
args = append(args, c.db.Database)
}
// Add the address at the end. Address contains host, port, database name,
// and other options like server selection timeout.
args = append(args, c.getMongoAddress())

// use `mongosh` if available
if hasMongosh {
Expand All @@ -413,6 +412,33 @@ func (c *CLICommandBuilder) getMongoCommand() *exec.Cmd {
return c.options.exe.Command(mongoBin, args...)
}

func (c *CLICommandBuilder) getMongoAddress() string {
query := make(url.Values)

// Use the same default server selection timeout (5s) that the backend
// engine is using. The environment variable serves as a hidden option to
// force a different timeout for debugging purpose or extreme situations.
serverSelectionTimeoutMS := "5000"
if envValue := os.Getenv(envVarMongoServerSelectionTimeoutMS); envValue != "" {
c.options.log.Infof("Using environment variable %s=%s.", envVarMongoServerSelectionTimeoutMS, envValue)
serverSelectionTimeoutMS = envValue
}
query.Set("serverSelectionTimeoutMS", serverSelectionTimeoutMS)

address := url.URL{
Scheme: connstring.SchemeMongoDB,
Host: fmt.Sprintf("%s:%d", c.host, c.port),
RawQuery: query.Encode(),
Path: fmt.Sprintf("/%s", c.db.Database),
}

// Quote the address for printing as the address contains "?".
if c.options.printFormat {
return fmt.Sprintf(`"%s"`, address.String())
}
return address.String()
}

// getRedisCommand returns redis-cli commands used by 'tsh db connect' when connecting to a Redis instance.
func (c *CLICommandBuilder) getRedisCommand() *exec.Cmd {
// TODO(jakub): Add "-3" when Teleport adds support for Redis RESP3 protocol.
Expand Down Expand Up @@ -520,6 +546,17 @@ func WithNoTLS() ConnectCommandFunc {

// WithPrintFormat is the connect command option that hints the command will be
// printed instead of being executed.
//
// For example, when enabled, a quote will be used for Postgres and MongoDB
// connection strings to avoid "&" getting interpreted by the shell.
//
// WithPrintFormat is known to be used for the following situations:
// - tsh db config --format cmd <database>
// - tsh proxy db --tunnel <database>
// - Teleport Connect where the command is put into a terminal.
//
// WithPrintFormat should NOT be used when the exec.Cmd gets executed by the
// client application.
func WithPrintFormat() ConnectCommandFunc {
return func(opts *connectionCommandOpts) {
opts.printFormat = true
Expand Down Expand Up @@ -557,3 +594,9 @@ func WithExecer(exe Execer) ConnectCommandFunc {
opts.exe = exe
}
}

const (
// envVarMongoServerSelectionTimeoutMS is the environment variable that
// controls the server selection timeout used for MongoDB clients.
envVarMongoServerSelectionTimeoutMS = "TELEPORT_MONGO_SERVER_SELECTION_TIMEOUT_MS"
)
27 changes: 11 additions & 16 deletions lib/client/db/dbcmd/dbcmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -336,11 +336,10 @@ func TestCLICommandBuilderGetConnectCommand(t *testing.T) {
execOutput: map[string][]byte{},
},
cmd: []string{"mongo",
"--host", "localhost",
"--port", "12345",
"--ssl",
"--sslPEMKeyFile", "/tmp/keys/example.com/bob-db/db.example.com/mysql-x509.pem",
"mydb"},
"mongodb://localhost:12345/mydb?serverSelectionTimeoutMS=5000",
},
wantErr: false,
},
{
Expand All @@ -352,13 +351,12 @@ func TestCLICommandBuilderGetConnectCommand(t *testing.T) {
execOutput: map[string][]byte{},
},
cmd: []string{"mongo",
"--host", "localhost",
"--port", "12345",
"mydb"},
"mongodb://localhost:12345/mydb?serverSelectionTimeoutMS=5000",
},
wantErr: false,
},
{
name: "mongosh",
name: "mongosh no CA",
dbProtocol: defaults.ProtocolMongoDB,
databaseName: "mydb",
execer: &fakeExec{
Expand All @@ -367,12 +365,11 @@ func TestCLICommandBuilderGetConnectCommand(t *testing.T) {
},
},
cmd: []string{"mongosh",
"--host", "localhost",
"--port", "12345",
"--tls",
"--tlsCertificateKeyFile", "/tmp/keys/example.com/bob-db/db.example.com/mysql-x509.pem",
"--tlsUseSystemCA",
"mydb"},
"mongodb://localhost:12345/mydb?serverSelectionTimeoutMS=5000",
},
},
{
name: "mongosh",
Expand All @@ -386,12 +383,11 @@ func TestCLICommandBuilderGetConnectCommand(t *testing.T) {
},
},
cmd: []string{"mongosh",
"--host", "localhost",
"--port", "12345",
"--tls",
"--tlsCertificateKeyFile", "/tmp/keys/example.com/bob-db/db.example.com/mysql-x509.pem",
"--tlsCAFile", "/tmp/keys/example.com/cas/example.com.pem",
"mydb"},
"mongodb://localhost:12345/mydb?serverSelectionTimeoutMS=5000",
},
},
{
name: "mongosh no TLS",
Expand All @@ -404,9 +400,8 @@ func TestCLICommandBuilderGetConnectCommand(t *testing.T) {
},
},
cmd: []string{"mongosh",
"--host", "localhost",
"--port", "12345",
"mydb"},
"mongodb://localhost:12345/mydb?serverSelectionTimeoutMS=5000",
},
},
{
name: "sqlserver",
Expand Down
25 changes: 25 additions & 0 deletions lib/srv/db/common/constants.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
Copyright 2022 Gravitational, Inc.
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
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package common

import "time"

const (
// DefaultMongoDBServerSelectionTimeout is the timeout for selecting a
// MongoDB server to connect to.
DefaultMongoDBServerSelectionTimeout = 5 * time.Second
)
8 changes: 1 addition & 7 deletions lib/srv/db/mongodb/connect.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ func (e *Engine) getTopologyOptions(ctx context.Context, sessionCtx *common.Sess
return connString
}),
topology.WithServerSelectionTimeout(func(time.Duration) time.Duration {
return serverSelectionTimeout
return common.DefaultMongoDBServerSelectionTimeout
}),
topology.WithServerOptions(func(so ...topology.ServerOption) []topology.ServerOption {
return serverOptions
Expand Down Expand Up @@ -202,9 +202,3 @@ func (h *handshaker) GetHandshakeInformation(context.Context, address.Address, d
func (h *handshaker) FinishHandshake(context.Context, driver.Connection) error {
return nil
}

const (
// serverSelectionTimeout is the timeout for selecting a MongoDB server
// to connect to.
serverSelectionTimeout = 5 * time.Second
)
1 change: 1 addition & 0 deletions lib/teleterm/clusters/dbcmd_cli_command_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ func (d DbcmdCLICommandProvider) GetCommand(gateway *gateway.Gateway) (string, e
dbcmd.WithLogger(gateway.Log),
dbcmd.WithLocalProxy(gateway.LocalAddress, gateway.LocalPortInt(), ""),
dbcmd.WithNoTLS(),
dbcmd.WithPrintFormat(),
dbcmd.WithTolerateMissingCLIClient(),
dbcmd.WithExecer(d.execer),
).GetConnectCommandNoAbsPath()
Expand Down
1 change: 1 addition & 0 deletions tool/tsh/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,7 @@ func onProxyCommandDB(cf *CLIConf) error {
dbcmd.WithLocalProxy("localhost", addr.Port(0), ""),
dbcmd.WithNoTLS(),
dbcmd.WithLogger(log),
dbcmd.WithPrintFormat(),
).GetConnectCommand()
if err != nil {
return trace.Wrap(err)
Expand Down

0 comments on commit 57636bd

Please sign in to comment.