Docs HomeNode.js

Cluster Monitoring群集监视

Overview概述

This guide shows you how to monitor topology events in a MongoDB instance, replica set, or sharded cluster. 本指南向您展示如何监控MongoDB实例、副本集或分片集群中的拓扑事件。The driver creates topology events, also known as Server Discovery and Monitoring (SDAM) events, when there is a change in the state of the instance or cluster that you connected to. For example, the driver creates an event when you establish a new connection or if the cluster elects a new primary.当连接到的实例或群集的状态发生更改时,驱动程序会创建拓扑事件,也称为服务器发现和监视(SDAM)事件。例如,当您建立新连接或群集选择新的主连接时,驱动程序会创建一个事件。

Read this guide if you need to record topology changes in your application or want to explore the information provided in these events.如果您需要记录应用程序中的拓扑更改,或者想了解这些事件中提供的信息,请阅读本指南。

Event Subscription Example事件订阅示例

You can access one or more SDAM events using the driver by subscribing to them in your application. 您可以通过在应用程序中订阅驱动程序来访问一个或多个SDAM事件。The following example demonstrates connecting to a replica set and subscribing to one of the SDAM events created by the MongoDB deployment:以下示例演示了连接到副本集并订阅MongoDB部署创建的SDAM事件之一:

const { MongoClient } = require("mongodb");

// Replace the following with your MongoDB deployment's connection string.将以下内容替换为MongoDB部署的连接字符串。
const uri =
"mongodb+srv://<clusterUrl>/?replicaSet=rs&writeConcern=majority";

const client = new MongoClient(uri);

// Replace <event name> with the name of the event you are subscribing to.将<event name>替换为您正在订阅的事件的名称。
const eventName = "<event name>";
client.on(eventName, event => {
console.log(`received ${eventName}: ${JSON.stringify(event, null, 2)}`);
});

async function run() {
try {
// Establish and verify connection建立并验证连接
await client.db("admin").command({ ping: 1 });
console.log("Connected successfully");
} finally {
// Ensures that the client will close when you finish/error确保客户端在您完成/出错时关闭
await client.close();
}
}
run().catch(console.dir);

Event Descriptions事件描述

You can subscribe to any of the following SDAM events:您可以订阅以下任何SDAM事件:

Event Name事件名称Description描述
serverOpeningCreated when a connection to an instance opens.在打开与实例的连接时创建。
serverClosedCreated when a connection to an instance closes.在与实例的连接关闭时创建。
serverDescriptionChangedCreated when an instance state changes (such as from secondary to primary).实例状态更改时创建(例如从次要状态更改为主状态)。
topologyOpeningCreated prior to attempting a connection to an instance.在尝试连接到实例之前创建。
topologyClosedCreated after all instance connections in the topology close.在拓扑中的所有实例连接关闭后创建。
topologyDescriptionChangedCreated when the topology changes, such as an election of a new primary or a mongos proxy disconnecting.当拓扑发生变化时创建,例如选择新的主代理或mongos代理断开连接。
serverHeartbeatStartedCreated prior to issuing a hello command to a MongoDB instance.在向MongoDB实例发出hello命令之前创建。
serverHeartbeatSucceededCreated when the hello command returns successfully from a MongoDB instance.当hello命令从MongoDB实例成功返回时创建。
serverHeartbeatFailedCreated when a hello command issued to a specific MongoDB instance fails to return a successful response.当向特定MongoDB实例发出的hello命令未能返回成功响应时创建。

Example Event Documents事件文档示例

The following sections show sample output for each type of SDAM event.以下部分显示了每种类型的SDAM事件的示例输出。

serverDescriptionChanged

ServerDescriptionChangedEvent {
topologyId: 0,
address: 'localhost:27017',
previousDescription: ServerDescription {
address: 'localhost:27017',
error: null,
roundTripTime: 0,
lastUpdateTime: 1571251089030,
lastWriteDate: null,
opTime: null,
type: 'Unknown',
minWireVersion: 0,
maxWireVersion: 0,
hosts: [],
passives: [],
arbiters: [],
tags: []
},
newDescription: ServerDescription {
address: 'localhost:27017',
error: null,
roundTripTime: 0,
lastUpdateTime: 1571251089051,
lastWriteDate: 2019-10-16T18:38:07.000Z,
opTime: { ts: Timestamp, t: 18 },
type: 'RSPrimary',
minWireVersion: 0,
maxWireVersion: 7,
maxBsonObjectSize: 16777216,
maxMessageSizeBytes: 48000000,
maxWriteBatchSize: 100000,
me: 'localhost:27017',
hosts: [ 'localhost:27017' ],
passives: [],
arbiters: [],
tags: [],
setName: 'rs',
setVersion: 1,
electionId: ObjectID,
primary: 'localhost:27017',
logicalSessionTimeoutMinutes: 30,
'$clusterTime': ClusterTime
}
}

The type field of the ServerDescription object in this event contains one of the following possible values:此事件中ServerDescription对象的type字段包含以下可能的值之一:

Type类型Description描述
UnknownUnknown instance未知实例
StandaloneStandalone instance独立实例
MongosMongos proxy instanceMongos代理实例
PossiblePrimaryAt least one server recognizes this as the primary, but is not yet verified by all instances.至少有一台服务器将其识别为主服务器,但尚未由所有实例验证。
RSPrimaryPrimary instance主要实例
RSSecondarySecondary instance次要实例
RSArbiterArbiter instance仲裁器实例
RSOtherSee the RSGhost specification for more details
RSGhostSee the RSOther specification for more details

serverHeartbeatStarted

ServerHeartbeatStartedEvent {
connectionId: 'localhost:27017'
}

serverHeartbeatSucceeded

ServerHeartbeatSucceededEvent {
duration: 1.939997,
reply:{
hosts: [ 'localhost:27017' ],
setName: 'rs',
setVersion: 1,
isWritablePrimary: true,
secondary: false,
primary: 'localhost:27017',
me: 'localhost:27017',
electionId: ObjectID,
lastWrite: {
opTime: { ts: [Timestamp], t: 18 },
lastWriteDate: 2019-10-16T18:38:17.000Z,
majorityOpTime: { ts: [Timestamp], t: 18 },
majorityWriteDate: 2019-10-16T18:38:17.000Z
},
maxBsonObjectSize: 16777216,
maxMessageSizeBytes: 48000000,
maxWriteBatchSize: 100000,
localTime: 2019-10-16T18:38:19.589Z,
logicalSessionTimeoutMinutes: 30,
minWireVersion: 0,
maxWireVersion: 7,
readOnly: false,
ok: 1,
operationTime: Timestamp,
'$clusterTime': ClusterTime
},
connectionId: 'localhost:27017'
}

serverHeartbeatFailed

ServerHeartbeatFailed {
duration: 20,
failure: MongoError('some error'),
connectionId: 'localhost:27017'
}

serverOpening

ServerOpeningEvent {
topologyId: 0,
address: 'localhost:27017'
}

serverClosed

ServerClosedEvent {
topologyId: 0,
address: 'localhost:27017'
}

topologyOpening

TopologyOpeningEvent {
topologyId: 0
}

topologyClosed

TopologyClosedEvent {
topologyId: 0
}

topologyDescriptionChanged

TopologyDescriptionChangedEvent {
topologyId: 0,
previousDescription: TopologyDescription {
type: 'ReplicaSetNoPrimary',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map {
'localhost:27017' => ServerDescription
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
options: Object,
error: undefined,
commonWireVersion: null
},
newDescription: TopologyDescription {
type: 'ReplicaSetWithPrimary',
setName: 'rs',
maxSetVersion: 1,
maxElectionId: null,
servers: Map {
'localhost:27017' => ServerDescription
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: 30,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
options: Object,
error: undefined,
commonWireVersion: 7
}
}

The type field of the TopologyDescription object in this event contains one of the following possible values:此事件中TopologyDescription对象的type字段包含以下可能值之一:

Type类型Description描述
SingleStandalone instance独立实例
ReplicaSetWithPrimaryReplica set with a primary具有主副本集
ReplicaSetNoPrimaryReplica set with no primary没有主副本的副本集
ShardedSharded cluster分片群集
UnknownUnknown topology未知拓扑