-
Notifications
You must be signed in to change notification settings - Fork 902
/
Copy pathcomponent.go
317 lines (272 loc) · 11.3 KB
/
component.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// Copyright (C) MongoDB, Inc. 2023-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package logger
import (
"os"
"strconv"
"go.mongodb.org/mongo-driver/bson/primitive"
)
const (
CommandFailed = "Command failed"
CommandStarted = "Command started"
CommandSucceeded = "Command succeeded"
ConnectionPoolCreated = "Connection pool created"
ConnectionPoolReady = "Connection pool ready"
ConnectionPoolCleared = "Connection pool cleared"
ConnectionPoolClosed = "Connection pool closed"
ConnectionCreated = "Connection created"
ConnectionReady = "Connection ready"
ConnectionClosed = "Connection closed"
ConnectionCheckoutStarted = "Connection checkout started"
ConnectionCheckoutFailed = "Connection checkout failed"
ConnectionCheckedOut = "Connection checked out"
ConnectionCheckedIn = "Connection checked in"
ConnectionPendingReadStarted = "Pending read started"
ConnectionPendingReadSucceeded = "Pending read succeeded"
ConnectionPendingReadFailed = "Pending read failed"
ServerSelectionFailed = "Server selection failed"
ServerSelectionStarted = "Server selection started"
ServerSelectionSucceeded = "Server selection succeeded"
ServerSelectionWaiting = "Waiting for suitable server to become available"
TopologyClosed = "Stopped topology monitoring"
TopologyDescriptionChanged = "Topology description changed"
TopologyOpening = "Starting topology monitoring"
TopologyServerClosed = "Stopped server monitoring"
TopologyServerHeartbeatFailed = "Server heartbeat failed"
TopologyServerHeartbeatStarted = "Server heartbeat started"
TopologyServerHeartbeatSucceeded = "Server heartbeat succeeded"
TopologyServerOpening = "Starting server monitoring"
)
const (
KeyAwaited = "awaited"
KeyCommand = "command"
KeyCommandName = "commandName"
KeyDatabaseName = "databaseName"
KeyDriverConnectionID = "driverConnectionId"
KeyDurationMS = "durationMS"
KeyError = "error"
KeyFailure = "failure"
KeyMaxConnecting = "maxConnecting"
KeyMaxIdleTimeMS = "maxIdleTimeMS"
KeyMaxPoolSize = "maxPoolSize"
KeyMessage = "message"
KeyMinPoolSize = "minPoolSize"
KeyNewDescription = "newDescription"
KeyOperation = "operation"
KeyOperationID = "operationId"
KeyPreviousDescription = "previousDescription"
KeyRemainingTimeMS = "remainingTimeMS"
KeyReason = "reason"
KeyReply = "reply"
KeyRequestID = "requestId"
KeySelector = "selector"
KeyServerConnectionID = "serverConnectionId"
KeyServerHost = "serverHost"
KeyServerPort = "serverPort"
KeyServiceID = "serviceId"
KeyTimestamp = "timestamp"
KeyTopologyDescription = "topologyDescription"
KeyTopologyID = "topologyId"
)
// KeyValues is a list of key-value pairs.
type KeyValues []interface{}
// Add adds a key-value pair to an instance of a KeyValues list.
func (kvs *KeyValues) Add(key string, value interface{}) {
*kvs = append(*kvs, key, value)
}
const (
ReasonConnClosedStale = "Connection became stale because the pool was cleared"
ReasonConnClosedIdle = "Connection has been available but unused for longer than the configured max idle time"
ReasonConnClosedError = "An error occurred while using the connection"
ReasonConnClosedPoolClosed = "Connection pool was closed"
ReasonConnCheckoutFailedTimout = "Wait queue timeout elapsed without a connection becoming available"
ReasonConnCheckoutFailedError = "An error occurred while trying to establish a new connection"
ReasonConnCheckoutFailedPoolClosed = "Connection pool was closed"
)
// Component is an enumeration representing the "components" which can be
// logged against. A LogLevel can be configured on a per-component basis.
type Component int
const (
// ComponentAll enables logging for all components.
ComponentAll Component = iota
// ComponentCommand enables command monitor logging.
ComponentCommand
// ComponentTopology enables topology logging.
ComponentTopology
// ComponentServerSelection enables server selection logging.
ComponentServerSelection
// ComponentConnection enables connection services logging.
ComponentConnection
)
const (
mongoDBLogAllEnvVar = "MONGODB_LOG_ALL"
mongoDBLogCommandEnvVar = "MONGODB_LOG_COMMAND"
mongoDBLogTopologyEnvVar = "MONGODB_LOG_TOPOLOGY"
mongoDBLogServerSelectionEnvVar = "MONGODB_LOG_SERVER_SELECTION"
mongoDBLogConnectionEnvVar = "MONGODB_LOG_CONNECTION"
)
var componentEnvVarMap = map[string]Component{
mongoDBLogAllEnvVar: ComponentAll,
mongoDBLogCommandEnvVar: ComponentCommand,
mongoDBLogTopologyEnvVar: ComponentTopology,
mongoDBLogServerSelectionEnvVar: ComponentServerSelection,
mongoDBLogConnectionEnvVar: ComponentConnection,
}
// EnvHasComponentVariables returns true if the environment contains any of the
// component environment variables.
func EnvHasComponentVariables() bool {
for envVar := range componentEnvVarMap {
if os.Getenv(envVar) != "" {
return true
}
}
return false
}
// Command is a struct defining common fields that must be included in all
// commands.
type Command struct {
// TODO(GODRIVER-2824): change the DriverConnectionID type to int64.
DriverConnectionID uint64 // Driver's ID for the connection
Name string // Command name
DatabaseName string // Database name
Message string // Message associated with the command
OperationID int32 // Driver-generated operation ID
RequestID int64 // Driver-generated request ID
ServerConnectionID *int64 // Server's ID for the connection used for the command
ServerHost string // Hostname or IP address for the server
ServerPort string // Port for the server
ServiceID *primitive.ObjectID // ID for the command in load balancer mode
}
// SerializeCommand takes a command and a variable number of key-value pairs and
// returns a slice of interface{} that can be passed to the logger for
// structured logging.
func SerializeCommand(cmd Command, extraKeysAndValues ...interface{}) KeyValues {
// Initialize the boilerplate keys and values.
keysAndValues := KeyValues{
KeyCommandName, cmd.Name,
KeyDatabaseName, cmd.DatabaseName,
KeyDriverConnectionID, cmd.DriverConnectionID,
KeyMessage, cmd.Message,
KeyOperationID, cmd.OperationID,
KeyRequestID, cmd.RequestID,
KeyServerHost, cmd.ServerHost,
}
// Add the extra keys and values.
for i := 0; i < len(extraKeysAndValues); i += 2 {
keysAndValues.Add(extraKeysAndValues[i].(string), extraKeysAndValues[i+1])
}
port, err := strconv.ParseInt(cmd.ServerPort, 10, 32)
if err == nil {
keysAndValues.Add(KeyServerPort, port)
}
// Add the "serverConnectionId" if it is not nil.
if cmd.ServerConnectionID != nil {
keysAndValues.Add(KeyServerConnectionID, *cmd.ServerConnectionID)
}
// Add the "serviceId" if it is not nil.
if cmd.ServiceID != nil {
keysAndValues.Add(KeyServiceID, cmd.ServiceID.Hex())
}
return keysAndValues
}
// Connection contains data that all connection log messages MUST contain.
type Connection struct {
Message string // Message associated with the connection
ServerHost string // Hostname or IP address for the server
ServerPort string // Port for the server
}
// SerializeConnection serializes a Connection message into a slice of keys and
// values that can be passed to a logger.
func SerializeConnection(conn Connection, extraKeysAndValues ...interface{}) KeyValues {
// Initialize the boilerplate keys and values.
keysAndValues := KeyValues{
KeyMessage, conn.Message,
KeyServerHost, conn.ServerHost,
}
// Add the optional keys and values.
for i := 0; i < len(extraKeysAndValues); i += 2 {
keysAndValues.Add(extraKeysAndValues[i].(string), extraKeysAndValues[i+1])
}
port, err := strconv.ParseInt(conn.ServerPort, 10, 32)
if err == nil {
keysAndValues.Add(KeyServerPort, port)
}
return keysAndValues
}
// Server contains data that all server messages MAY contain.
type Server struct {
DriverConnectionID uint64 // Driver's ID for the connection
TopologyID primitive.ObjectID // Driver's unique ID for this topology
Message string // Message associated with the topology
ServerConnectionID *int64 // Server's ID for the connection
ServerHost string // Hostname or IP address for the server
ServerPort string // Port for the server
}
// SerializeServer serializes a Server message into a slice of keys and
// values that can be passed to a logger.
func SerializeServer(srv Server, extraKV ...interface{}) KeyValues {
// Initialize the boilerplate keys and values.
keysAndValues := KeyValues{
KeyDriverConnectionID, srv.DriverConnectionID,
KeyMessage, srv.Message,
KeyServerHost, srv.ServerHost,
KeyTopologyID, srv.TopologyID.Hex(),
}
if connID := srv.ServerConnectionID; connID != nil {
keysAndValues.Add(KeyServerConnectionID, *connID)
}
port, err := strconv.ParseInt(srv.ServerPort, 10, 32)
if err == nil {
keysAndValues.Add(KeyServerPort, port)
}
// Add the optional keys and values.
for i := 0; i < len(extraKV); i += 2 {
keysAndValues.Add(extraKV[i].(string), extraKV[i+1])
}
return keysAndValues
}
// ServerSelection contains data that all server selection messages MUST
// contain.
type ServerSelection struct {
Selector string
OperationID *int32
Operation string
TopologyDescription string
}
// SerializeServerSelection serializes a Topology message into a slice of keys
// and values that can be passed to a logger.
func SerializeServerSelection(srvSelection ServerSelection, extraKV ...interface{}) KeyValues {
keysAndValues := KeyValues{
KeySelector, srvSelection.Selector,
KeyOperation, srvSelection.Operation,
KeyTopologyDescription, srvSelection.TopologyDescription,
}
if srvSelection.OperationID != nil {
keysAndValues.Add(KeyOperationID, *srvSelection.OperationID)
}
// Add the optional keys and values.
for i := 0; i < len(extraKV); i += 2 {
keysAndValues.Add(extraKV[i].(string), extraKV[i+1])
}
return keysAndValues
}
// Topology contains data that all topology messages MAY contain.
type Topology struct {
ID primitive.ObjectID // Driver's unique ID for this topology
Message string // Message associated with the topology
}
// SerializeTopology serializes a Topology message into a slice of keys and
// values that can be passed to a logger.
func SerializeTopology(topo Topology, extraKV ...interface{}) KeyValues {
keysAndValues := KeyValues{
KeyTopologyID, topo.ID.Hex(),
}
// Add the optional keys and values.
for i := 0; i < len(extraKV); i += 2 {
keysAndValues.Add(extraKV[i].(string), extraKV[i+1])
}
return keysAndValues
}