Cluster Monitoring集群监控

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. 当连接到的实例或群集的状态发生更改时,驱动程序将创建拓扑事件,也称为服务器发现和监视(SDAM)事件。For example, the driver creates an event when you establish a new connection or if the cluster elects a new primary.例如,当您建立新连接或群集选择新的主连接时,驱动程序会创建一个事件。

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

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. const eventName = "<event name>"; client.on(eventName, event=> { console.log(`received${eventName}:${JSON.stringify(event,null,2)}`); });
async function run(){ try { await client.connect();
// Establish and verify connection await client.db("admin").command({ ping: 1 }); console.log("Connected successfully"); } finally { // 确保完成/出错时客户端将关闭 await client.close(); } } run().catch(console.dir);

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

Event Name事件名称
Description描述
serverOpening
Created when a connection to an instance opens.在与实例的连接打开时创建。
serverClosed
Created when a connection to an instance closes.在与实例的连接关闭时创建。
serverDescriptionChanged
Created when an instance state changes (such as from secondary to primary).在实例状态更改(例如从辅助状态更改为主状态)时创建。
topologyOpening
Created prior to attempting a connection to an instance.在尝试连接到实例之前创建。
topologyClosed
Created after all instance connections in the topology close.拓扑中的所有实例连接关闭后创建。
topologyDescriptionChanged
Created when the topology changes, such as an election of a new primary or a mongos proxy disconnecting.在拓扑更改时创建,例如选择新的主服务器或mongos代理服务器。
serverHeartbeatStarted
Created prior to issuing an isMaster command to a MongoDB instance.在向MongoDB实例发出isMaster命令之前创建。
serverHeartbeatSucceeded
Created when the isMaster command returns successfully from a MongoDB instance.isMaster命令从MongoDB实例成功返回时创建。
serverHeartbeatFailed
Created when an isMaster command issued to a specific MongoDB instance fails to return a successful response当向特定MongoDB实例发出的isMaster命令未能返回成功响应时创建

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

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描述
Unknown
Unknown instance未知实例
Standalone
Standalone instance独立实例
Mongos
Mongos proxy instanceMongos代理实例
PossiblePrimary
At least one server recognizes this as the primary, but is not yet verified by all instances.至少有一台服务器将其识别为主服务器,但尚未被所有实例验证。
RSPrimary
Primary instance主要实例
RSSecondary
Secondary instance次要实例
RSArbiter
Arbiter instance仲裁实例
RSOther
See the RSGhost specification for more details有关更多详细信息,请参阅RSGhost规范
RSGhost
See the RSOther specification for more details有关更多详细信息,请参阅RSOther规范
ServerHeartbeatStartedEvent {
  connectionId: 'localhost:27017'
}
ServerHeartbeatSucceededEvent {
  duration: 1.939997,
  reply:{
    hosts: [ 'localhost:27017' ],
    setName: 'rs',
    setVersion: 1,
    ismaster: 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 {
  duration: 20,
  failure: MongoError('some error'),
  connectionId: 'localhost:27017'
}
ServerOpeningEvent {
  topologyId: 0,
  address: 'localhost:27017'
}
ServerClosedEvent {
  topologyId: 0,
  address: 'localhost:27017'
}
TopologyOpeningEvent {
  topologyId: 0
}
TopologyClosedEvent {
  topologyId: 0
}
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描述
Single
Standalone instance独立实例
ReplicaSetWithPrimary
Replica set with a primary具有主副本的副本集
ReplicaSetNoPrimary
Replica set with no primary没有主副本的副本集
Sharded
Sharded cluster碎片簇
Unknown
Unknown topology未知拓扑