Documentation
¶
Overview ¶
Package event is a library for monitoring events from the MongoDB Go driver. Monitors can be set for commands sent to the MongoDB cluster, connection pool changes, or changes on the MongoDB cluster.
Monitoring commands requires specifying a CommandMonitor when constructing a mongo.Client. A CommandMonitor can be set to monitor started, succeeded, and/or failed events. A CommandStartedEvent can be correlated to its matching CommandSucceededEvent or CommandFailedEvent through the RequestID field. For example, the following code collects the names of started events:
var commandStarted []string
cmdMonitor := &event.CommandMonitor{
Started: func(_ context.Context, evt *event.CommandStartedEvent) {
commandStarted = append(commandStarted, evt.CommandName)
},
}
clientOpts := options.Client().ApplyURI("mongodb://localhost:27017").SetMonitor(cmdMonitor)
client, err := mongo.Connect( clientOpts)
Monitoring the connection pool requires specifying a PoolMonitor when constructing a mongo.Client. The following code tracks the number of checked out connections:
var int connsCheckedOut
poolMonitor := &event.PoolMonitor{
Event: func(evt *event.PoolEvent) {
switch evt.Type {
case event.ConnectionCheckedOut:
connsCheckedOut++
case event.ConnectionCheckedIn:
connsCheckedOut--
}
},
}
clientOpts := options.Client().ApplyURI("mongodb://localhost:27017").SetPoolMonitor(poolMonitor)
client, err := mongo.Connect( clientOpts)
Monitoring server changes specifying a ServerMonitor object when constructing a mongo.Client. Different functions can be set on the ServerMonitor to monitor different kinds of events. See ServerMonitor for more details. The following code appends ServerHeartbeatStartedEvents to a slice:
var heartbeatStarted []*event.ServerHeartbeatStartedEvent
svrMonitor := &event.ServerMonitor{
ServerHeartbeatStarted: func(e *event.ServerHeartbeatStartedEvent) {
heartbeatStarted = append(heartbeatStarted, e)
}
}
clientOpts := options.Client().ApplyURI("mongodb://localhost:27017").SetServerMonitor(svrMonitor)
client, err := mongo.Connect( clientOpts)
Index ¶
- Constants
- type CommandFailedEvent
- type CommandFinishedEvent
- type CommandMonitor
- type CommandStartedEvent
- type CommandSucceededEvent
- type MonitorPoolOptions
- type PoolEvent
- type PoolMonitor
- type ServerClosedEvent
- type ServerDescription
- type ServerDescriptionChangedEvent
- type ServerHeartbeatFailedEvent
- type ServerHeartbeatStartedEvent
- type ServerHeartbeatSucceededEvent
- type ServerMonitor
- type ServerOpeningEvent
- type TopologyClosedEvent
- type TopologyDescription
- type TopologyDescriptionChangedEvent
- type TopologyOpeningEvent
Examples ¶
Constants ¶
const ( ReasonIdle = "idle" ReasonPoolClosed = "poolClosed" ReasonStale = "stale" ReasonConnectionErrored = "connectionError" ReasonTimedOut = "timeout" ReasonError = "error" )
strings for pool command monitoring reasons
const ( PoolCreated = "ConnectionPoolCreated" PoolReady = "ConnectionPoolReady" PoolCleared = "ConnectionPoolCleared" PoolClosedEvent = "ConnectionPoolClosed" ConnectionCreated = "ConnectionCreated" ConnectionReady = "ConnectionReady" ConnectionClosed = "ConnectionClosed" ConnectionCheckOutStarted = "ConnectionCheckOutStarted" ConnectionCheckOutFailed = "ConnectionCheckOutFailed" ConnectionCheckedOut = "ConnectionCheckedOut" ConnectionCheckedIn = "ConnectionCheckedIn" )
strings for pool command monitoring types
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CommandFailedEvent ¶
type CommandFailedEvent struct {
CommandFinishedEvent
Failure error
}
CommandFailedEvent represents an event generated when a command's execution fails.
type CommandFinishedEvent ¶
type CommandFinishedEvent struct {
Duration time.Duration
CommandName string
DatabaseName string
RequestID int64
ConnectionID string
// ServerConnectionID64 contains the connection ID from the server of the operation. If the server does not
// return this value (e.g. on MDB < 4.2), it is unset.
ServerConnectionID *int64
// ServiceID contains the ID of the server to which the command was sent if it is running behind a load balancer.
// Otherwise, it is unset.
ServiceID *bson.ObjectID
}
CommandFinishedEvent represents a generic command finishing.
type CommandMonitor ¶
type CommandMonitor struct {
Started func(context.Context, *CommandStartedEvent)
Succeeded func(context.Context, *CommandSucceededEvent)
Failed func(context.Context, *CommandFailedEvent)
}
CommandMonitor represents a monitor that is triggered for different events.
Example ¶
CommandMonitor represents a monitor that is triggered for different events.
package main
import (
"context"
"log"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/event"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
func main() {
// If the application makes multiple concurrent requests, it would have to
// use a concurrent map like sync.Map
startedCommands := make(map[int64]bson.Raw)
cmdMonitor := &event.CommandMonitor{
Started: func(_ context.Context, evt *event.CommandStartedEvent) {
startedCommands[evt.RequestID] = evt.Command
},
Succeeded: func(_ context.Context, evt *event.CommandSucceededEvent) {
log.Printf("Command: %v Reply: %v\n",
startedCommands[evt.RequestID],
evt.Reply,
)
// Empty "startedCommands" for the request ID to avoid a memory leak.
delete(startedCommands, evt.RequestID)
},
Failed: func(_ context.Context, evt *event.CommandFailedEvent) {
log.Printf("Command: %v Failure: %v\n",
startedCommands[evt.RequestID],
evt.Failure,
)
// Empty "startedCommands" for the request ID to avoid a memory leak.
delete(startedCommands, evt.RequestID)
},
}
clientOpts := options.Client().ApplyURI("mongodb://localhost:27017").SetMonitor(cmdMonitor)
client, err := mongo.Connect(clientOpts)
if err != nil {
log.Fatal(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
log.Fatal(err)
}
}()
}
type CommandStartedEvent ¶
type CommandStartedEvent struct {
Command bson.Raw
DatabaseName string
CommandName string
RequestID int64
ConnectionID string
// ServerConnectionID64 contains the connection ID from the server of the operation. If the server does not
// return this value (e.g. on MDB < 4.2), it is unset.
ServerConnectionID *int64
// ServiceID contains the ID of the server to which the command was sent if it is running behind a load balancer.
// Otherwise, it is unset.
ServiceID *bson.ObjectID
}
CommandStartedEvent represents an event generated when a command is sent to a server.
type CommandSucceededEvent ¶
type CommandSucceededEvent struct {
CommandFinishedEvent
Reply bson.Raw
}
CommandSucceededEvent represents an event generated when a command's execution succeeds.
type MonitorPoolOptions ¶
type MonitorPoolOptions struct {
MaxPoolSize uint64 `json:"maxPoolSize"`
MinPoolSize uint64 `json:"minPoolSize"`
WaitQueueTimeoutMS uint64 `json:"maxIdleTimeMS"`
}
MonitorPoolOptions contains pool options as formatted in pool events
type PoolEvent ¶
type PoolEvent struct {
Type string `json:"type"`
Address string `json:"address"`
ConnectionID int64 `json:"connectionId"`
PoolOptions *MonitorPoolOptions `json:"options"`
Duration time.Duration `json:"duration"`
Reason string `json:"reason"`
// ServiceID is only set if the Type is PoolCleared and the server is deployed behind a load balancer. This field
// can be used to distinguish between individual servers in a load balanced deployment.
ServiceID *bson.ObjectID `json:"serviceId"`
Interruption bool `json:"interruptInUseConnections"`
Error error `json:"error"`
}
PoolEvent contains all information summarizing a pool event
type PoolMonitor ¶
type PoolMonitor struct {
Event func(*PoolEvent)
}
PoolMonitor is a function that allows the user to gain access to events occurring in the pool
type ServerClosedEvent ¶
type ServerClosedEvent struct {
Address address.Address
TopologyID bson.ObjectID // A unique identifier for the topology this server is a part of
}
ServerClosedEvent is an event generated when the server is closed.
type ServerDescription ¶
type ServerDescription struct {
Addr address.Address
Arbiters []string
Compression []string // compression methods returned by server
CanonicalAddr address.Address
ElectionID bson.ObjectID
IsCryptd bool
HelloOK bool
Hosts []string
Kind string
LastWriteTime time.Time
MaxBatchCount uint32
MaxDocumentSize uint32
MaxMessageSize uint32
MaxWireVersion int32
MinWireVersion int32
Members []address.Address
Passives []string
Passive bool
Primary address.Address
ReadOnly bool
ServiceID *bson.ObjectID // Only set for servers that are deployed behind a load balancer.
SessionTimeoutMinutes *int64
SetName string
SetVersion uint32
Tags tag.Set
TopologyVersionProcessID bson.ObjectID
TopologyVersionCounter int64
}
ServerDescription contains information about a node in a cluster. This is created from hello command responses. If the value of the Kind field is LoadBalancer, only the Addr and Kind fields will be set. All other fields will be set to the zero value of the field's type.
type ServerDescriptionChangedEvent ¶
type ServerDescriptionChangedEvent struct {
Address address.Address
TopologyID bson.ObjectID // A unique identifier for the topology this server is a part of
PreviousDescription ServerDescription
NewDescription ServerDescription
}
ServerDescriptionChangedEvent represents a server description change.
type ServerHeartbeatFailedEvent ¶
type ServerHeartbeatFailedEvent struct {
Duration time.Duration
Failure error
ConnectionID string // The address this heartbeat was sent to with a unique identifier
Awaited bool // If this heartbeat was awaitable
}
ServerHeartbeatFailedEvent is an event generated when the heartbeat fails.
type ServerHeartbeatStartedEvent ¶
type ServerHeartbeatStartedEvent struct {
ConnectionID string // The address this heartbeat was sent to with a unique identifier
Awaited bool // If this heartbeat was awaitable
}
ServerHeartbeatStartedEvent is an event generated when the heartbeat is started.
type ServerHeartbeatSucceededEvent ¶
type ServerHeartbeatSucceededEvent struct {
Duration time.Duration
Reply ServerDescription
ConnectionID string // The address this heartbeat was sent to with a unique identifier
Awaited bool // If this heartbeat was awaitable
}
ServerHeartbeatSucceededEvent is an event generated when the heartbeat succeeds.
type ServerMonitor ¶
type ServerMonitor struct {
ServerDescriptionChanged func(*ServerDescriptionChangedEvent)
ServerOpening func(*ServerOpeningEvent)
ServerClosed func(*ServerClosedEvent)
// TopologyDescriptionChanged is called when the topology is locked, so the callback should
// not attempt any operation that requires server selection on the same client.
TopologyDescriptionChanged func(*TopologyDescriptionChangedEvent)
TopologyOpening func(*TopologyOpeningEvent)
TopologyClosed func(*TopologyClosedEvent)
ServerHeartbeatStarted func(*ServerHeartbeatStartedEvent)
ServerHeartbeatSucceeded func(*ServerHeartbeatSucceededEvent)
ServerHeartbeatFailed func(*ServerHeartbeatFailedEvent)
}
ServerMonitor represents a monitor that is triggered for different server events. The client will monitor changes on the MongoDB deployment it is connected to, and this monitor reports the changes in the client's representation of the deployment. The topology represents the overall deployment, and heartbeats are sent to individual servers to check their current status.
type ServerOpeningEvent ¶
type ServerOpeningEvent struct {
Address address.Address
TopologyID bson.ObjectID // A unique identifier for the topology this server is a part of
}
ServerOpeningEvent is an event generated when the server is initialized.
type TopologyClosedEvent ¶
type TopologyClosedEvent struct {
TopologyID bson.ObjectID // A unique identifier for the topology this server is a part of
}
TopologyClosedEvent is an event generated when the topology is closed.
type TopologyDescription ¶
type TopologyDescription struct {
Servers []ServerDescription
SetName string
Kind string
SessionTimeoutMinutes *int64
CompatibilityErr error
}
TopologyDescription contains information about a MongoDB cluster.
type TopologyDescriptionChangedEvent ¶
type TopologyDescriptionChangedEvent struct {
TopologyID bson.ObjectID // A unique identifier for the topology this server is a part of
PreviousDescription TopologyDescription
NewDescription TopologyDescription
}
TopologyDescriptionChangedEvent represents a topology description change.
type TopologyOpeningEvent ¶
type TopologyOpeningEvent struct {
TopologyID bson.ObjectID // A unique identifier for the topology this server is a part of
}
TopologyOpeningEvent is an event generated when the topology is initialized.