fix(mongodb): change command based on server version (#9674)

This commit is contained in:
Alexander Krantz 2021-08-26 13:32:48 -07:00 committed by GitHub
parent 0ce9c2e9f6
commit 1a59157b91
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 67 additions and 4 deletions

View File

@ -1,5 +1,7 @@
# MongoDB Input Plugin
All MongoDB server versions from 2.6 and higher are supported.
### Configuration:
```toml

View File

@ -4,6 +4,7 @@ import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson/primitive"
"strconv"
"strings"
"time"
@ -126,11 +127,29 @@ func (s *Server) gatherClusterStatus() (*ClusterStatus, error) {
}, nil
}
func (s *Server) gatherShardConnPoolStats() (*ShardStats, error) {
func poolStatsCommand(version string) (string, error) {
majorPart := string(version[0])
major, err := strconv.ParseInt(majorPart, 10, 64)
if err != nil {
return "", err
}
if major == 5 {
return "connPoolStats", nil
}
return "shardConnPoolStats", nil
}
func (s *Server) gatherShardConnPoolStats(version string) (*ShardStats, error) {
command, err := poolStatsCommand(version)
if err != nil {
return nil, err
}
shardStats := &ShardStats{}
err := s.runCommand("admin", bson.D{
err = s.runCommand("admin", bson.D{
{
Key: "shardConnPoolStats",
Key: command,
Value: 1,
},
}, &shardStats)
@ -272,7 +291,7 @@ func (s *Server) gatherData(acc telegraf.Accumulator, gatherClusterStatus bool,
clusterStatus = status
}
shardStats, err := s.gatherShardConnPoolStats()
shardStats, err := s.gatherShardConnPoolStats(serverStatus.Version)
if err != nil {
s.authLog(fmt.Errorf("unable to gather shard connection pool stats: %s", err.Error()))
}

View File

@ -40,3 +40,45 @@ func TestAddDefaultStats(t *testing.T) {
assert.True(t, acc.HasInt64Field("mongodb", key))
}
}
func TestPoolStatsVersionCompatibility(t *testing.T) {
tests := []struct {
name string
version string
expectedCommand string
err bool
}{
{
name: "mongodb v3",
version: "3.0.0",
expectedCommand: "shardConnPoolStats",
},
{
name: "mongodb v4",
version: "4.0.0",
expectedCommand: "shardConnPoolStats",
},
{
name: "mongodb v5",
version: "5.0.0",
expectedCommand: "connPoolStats",
},
{
name: "invalid version",
version: "v4",
err: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
command, err := poolStatsCommand(test.version)
require.Equal(t, test.expectedCommand, command)
if test.err {
require.Error(t, err)
} else {
require.NoError(t, err)
}
})
}
}