Skip to content

Commit

Permalink
Added mongodb replica metrics and routing logic for multiple mongodb …
Browse files Browse the repository at this point in the history
…instances
  • Loading branch information
chan-tim-sumo committed Jan 27, 2025
1 parent c47c746 commit 0a323c6
Show file tree
Hide file tree
Showing 15 changed files with 832 additions and 21 deletions.
27 changes: 27 additions & 0 deletions .chloggen/mongodbReplicaMetrics.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Use this changelog template to create an entry for release notes.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: enhancement

# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
component: mongodbreceiver

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Added mongodb replica metrics and routing logic for multiple mongodb instances

# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
issues: [37517]

# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext:

# If your change doesn't affect end users or the exported elements of any package,
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.
# Optional: The change log or logs in which this entry should be included.
# e.g. '[user]' or '[user, api]'
# Include 'user' if the change is relevant to end users.
# Include 'api' if there is a change to a library API.
# Default: '[user]'
change_logs: []
6 changes: 3 additions & 3 deletions receiver/mongodbreceiver/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ type client interface {
DBStats(ctx context.Context, DBName string) (bson.M, error)
TopStats(ctx context.Context) (bson.M, error)
IndexStats(ctx context.Context, DBName, collectionName string) ([]bson.M, error)
RunCommand(ctx context.Context, db string, command bson.M) (bson.M, error)
}

// mongodbClient is a mongodb metric scraper client
Expand All @@ -37,12 +38,11 @@ type mongodbClient struct {

// newClient creates a new client to connect and query mongo for the
// mongodbreceiver
func newClient(ctx context.Context, config *Config, logger *zap.Logger) (client, error) {
driver, err := mongo.Connect(ctx, config.ClientOptions())
var newClient = func(ctx context.Context, config *Config, logger *zap.Logger, secondary bool) (client, error) {
driver, err := mongo.Connect(ctx, config.ClientOptions(secondary))
if err != nil {
return nil, err
}

return &mongodbClient{
cfg: config,
logger: logger,
Expand Down
17 changes: 17 additions & 0 deletions receiver/mongodbreceiver/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,23 @@ func (fc *fakeClient) IndexStats(ctx context.Context, dbName, collectionName str
return args.Get(0).([]bson.M), args.Error(1)
}

func (fc *fakeClient) RunCommand(ctx context.Context, db string, command bson.M) (bson.M, error) {
args := fc.Called(ctx, db, command)
if args.Get(0) == nil {
return nil, args.Error(1)
}

result, ok := args.Get(0).(bson.M)
if !ok {
err := errors.New("mock returned invalid type")
zap.L().Error("type assertion failed",
zap.String("expected", "bson.M"))
return nil, err
}

return result, args.Error(1)
}

func TestListDatabaseNames(t *testing.T) {
mont := mtest.New(t, mtest.NewOptions().ClientType(mtest.Mock))

Expand Down
23 changes: 22 additions & 1 deletion receiver/mongodbreceiver/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"time"

"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.opentelemetry.io/collector/config/confignet"
"go.opentelemetry.io/collector/config/configopaque"
"go.opentelemetry.io/collector/config/configtls"
Expand Down Expand Up @@ -59,7 +60,27 @@ func (c *Config) Validate() error {
return err
}

func (c *Config) ClientOptions() *options.ClientOptions {
func (c *Config) ClientOptions(secondary bool) *options.ClientOptions {
if secondary {
// For secondary nodes, create a direct connection
clientOptions := options.Client().
SetHosts(c.hostlist()).
SetDirect(true).
SetReadPreference(readpref.SecondaryPreferred())

if c.Timeout > 0 {
clientOptions.SetConnectTimeout(c.Timeout)
}

if c.Username != "" && c.Password != "" {
clientOptions.SetAuth(options.Credential{
Username: c.Username,
Password: string(c.Password),
})
}

return clientOptions
}
clientOptions := options.Client()
connString := "mongodb://" + strings.Join(c.hostlist(), ",")
clientOptions.ApplyURI(connString)
Expand Down
4 changes: 2 additions & 2 deletions receiver/mongodbreceiver/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ func TestOptions(t *testing.T) {
ReplicaSet: "rs-1",
}

clientOptions := cfg.ClientOptions()
clientOptions := cfg.ClientOptions(false)
require.Equal(t, clientOptions.Auth.Username, cfg.Username)
require.Equal(t,
clientOptions.ConnectTimeout.Milliseconds(),
Expand All @@ -191,7 +191,7 @@ func TestOptionsTLS(t *testing.T) {
},
},
}
opts := cfg.ClientOptions()
opts := cfg.ClientOptions(false)
require.NotNil(t, opts.TLSConfig)
}

Expand Down
48 changes: 48 additions & 0 deletions receiver/mongodbreceiver/documentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,54 @@ The number of replicated operations executed.
| ---- | ----------- | ------ |
| operation | The MongoDB operation being counted. | Str: ``insert``, ``query``, ``update``, ``delete``, ``getmore``, ``command`` |
### mongodb.repl_commands_per_sec
The number of replicated commands executed per second.
| Unit | Metric Type | Value Type |
| ---- | ----------- | ---------- |
| {command}/s | Gauge | Double |
### mongodb.repl_deletes_per_sec
The number of replicated deletes executed per second.
| Unit | Metric Type | Value Type |
| ---- | ----------- | ---------- |
| {delete}/s | Gauge | Double |
### mongodb.repl_getmores_per_sec
The number of replicated getmores executed per second.
| Unit | Metric Type | Value Type |
| ---- | ----------- | ---------- |
| {getmore}/s | Gauge | Double |
### mongodb.repl_inserts_per_sec
The number of replicated insertions executed per second.
| Unit | Metric Type | Value Type |
| ---- | ----------- | ---------- |
| {insert}/s | Gauge | Double |
### mongodb.repl_queries_per_sec
The number of replicated queries executed per second.
| Unit | Metric Type | Value Type |
| ---- | ----------- | ---------- |
| {query}/s | Gauge | Double |
### mongodb.repl_updates_per_sec
The number of replicated updates executed per second.
| Unit | Metric Type | Value Type |
| ---- | ----------- | ---------- |
| {update}/s | Gauge | Double |
### mongodb.uptime
The amount of time that the server has been running.
Expand Down
24 changes: 24 additions & 0 deletions receiver/mongodbreceiver/internal/metadata/generated_config.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 0a323c6

Please sign in to comment.