|
| 1 | +/* |
| 2 | + * Copyright 2013-2021 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.springframework.data.mongodb.observability; |
| 18 | + |
| 19 | +import java.util.Arrays; |
| 20 | +import java.util.LinkedHashSet; |
| 21 | +import java.util.Set; |
| 22 | + |
| 23 | +import com.mongodb.RequestContext; |
| 24 | +import com.mongodb.connection.ConnectionDescription; |
| 25 | +import com.mongodb.connection.ConnectionId; |
| 26 | +import com.mongodb.event.CommandFailedEvent; |
| 27 | +import com.mongodb.event.CommandListener; |
| 28 | +import com.mongodb.event.CommandStartedEvent; |
| 29 | +import com.mongodb.event.CommandSucceededEvent; |
| 30 | +import io.micrometer.core.instrument.MeterRegistry; |
| 31 | +import io.micrometer.core.instrument.Tag; |
| 32 | +import io.micrometer.core.instrument.Tags; |
| 33 | +import io.micrometer.core.instrument.Timer; |
| 34 | +import org.apache.commons.logging.Log; |
| 35 | +import org.apache.commons.logging.LogFactory; |
| 36 | +import org.bson.BsonDocument; |
| 37 | +import org.bson.BsonValue; |
| 38 | + |
| 39 | +import org.springframework.lang.Nullable; |
| 40 | + |
| 41 | +/** |
| 42 | + * Altered the Brave MongoDb instrumentation code. The code is available here: |
| 43 | + * https://github.com/openzipkin/brave/blob/release-5.13.0/instrumentation/mongodb/src/main/java/brave/mongodb/TraceMongoCommandListener.java |
| 44 | + * |
| 45 | + * @author OpenZipkin Brave Authors |
| 46 | + * @author Marcin Grzejszczak |
| 47 | + * @since 3.0.0 |
| 48 | + */ |
| 49 | +public final class MicrometerMongoCommandListener implements CommandListener { |
| 50 | + |
| 51 | + private static final Log log = LogFactory.getLog(MicrometerMongoCommandListener.class); |
| 52 | + |
| 53 | + // See https://docs.mongodb.com/manual/reference/command for the command reference |
| 54 | + static final Set<String> COMMANDS_WITH_COLLECTION_NAME = new LinkedHashSet<>( |
| 55 | + Arrays.asList("aggregate", "count", "distinct", "mapReduce", "geoSearch", "delete", "find", "findAndModify", |
| 56 | + "insert", "update", "collMod", "compact", "convertToCapped", "create", "createIndexes", "drop", |
| 57 | + "dropIndexes", "killCursors", "listIndexes", "reIndex")); |
| 58 | + |
| 59 | + private final MeterRegistry registry; |
| 60 | + |
| 61 | + MicrometerMongoCommandListener(MeterRegistry registry) { |
| 62 | + this.registry = registry; |
| 63 | + } |
| 64 | + |
| 65 | + @Override |
| 66 | + public void commandStarted(CommandStartedEvent event) { |
| 67 | + if (log.isDebugEnabled()) { |
| 68 | + log.debug("Instrumenting the command started event"); |
| 69 | + } |
| 70 | + String databaseName = event.getDatabaseName(); |
| 71 | + if ("admin".equals(databaseName)) { |
| 72 | + return; // don't trace commands like "endSessions" |
| 73 | + } |
| 74 | + RequestContext requestContext = event.getRequestContext(); |
| 75 | + if (requestContext == null) { |
| 76 | + return; |
| 77 | + } |
| 78 | + Timer.Sample parent = sampleFromContext(requestContext); |
| 79 | + if (log.isDebugEnabled()) { |
| 80 | + log.debug("Found the following sample passed from the mongo context [" + parent + "]"); |
| 81 | + } |
| 82 | + if (parent == null) { |
| 83 | + return; |
| 84 | + } |
| 85 | + setupObservability(event, requestContext); |
| 86 | + } |
| 87 | + |
| 88 | + private void setupObservability(CommandStartedEvent event, RequestContext requestContext) { |
| 89 | + String commandName = event.getCommandName(); |
| 90 | + BsonDocument command = event.getCommand(); |
| 91 | + String collectionName = getCollectionName(command, commandName); |
| 92 | + String metricName = getMetricName(commandName, collectionName); |
| 93 | + Timer.Builder timerBuilder = Timer.builder(metricName); |
| 94 | + MongoHandlerContext mongoHandlerContext = new MongoHandlerContext(event) { |
| 95 | + @Override public Tags getLowCardinalityTags() { |
| 96 | + Tags tags = Tags.empty(); |
| 97 | + if (collectionName != null) { |
| 98 | + tags = tags.and(Tag.of("mongodb.collection", collectionName)); |
| 99 | + } |
| 100 | + Tag tag = connectionTag(event); |
| 101 | + if (tag == null) { |
| 102 | + return tags; |
| 103 | + } |
| 104 | + return tags.and(tag); |
| 105 | + } |
| 106 | + |
| 107 | + @Override public Tags getHighCardinalityTags() { |
| 108 | + return Tags.of(Tag.of("mongodb.command", commandName)); |
| 109 | + } |
| 110 | + }; |
| 111 | + Timer.Sample child = Timer.start(this.registry, mongoHandlerContext); |
| 112 | + requestContext.put(mongoHandlerContext, MongoHandlerContext.class); |
| 113 | + requestContext.put(Timer.Builder.class, timerBuilder); |
| 114 | + if (log.isDebugEnabled()) { |
| 115 | + log.debug("Created a child sample [" + child |
| 116 | + + "] for mongo instrumentation and put it in mongo context"); |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + private Tag connectionTag(CommandStartedEvent event) { |
| 121 | + ConnectionDescription connectionDescription = event.getConnectionDescription(); |
| 122 | + if (connectionDescription != null) { |
| 123 | + ConnectionId connectionId = connectionDescription.getConnectionId(); |
| 124 | + if (connectionId != null) { |
| 125 | + return Tag.of("mongodb.cluster_id", connectionId.getServerId().getClusterId().getValue()); |
| 126 | + } |
| 127 | + } |
| 128 | + return null; |
| 129 | + } |
| 130 | + |
| 131 | + private static Timer.Sample sampleFromContext(RequestContext context) { |
| 132 | + Timer.Sample sample = context.getOrDefault(Timer.Sample.class, null); |
| 133 | + if (sample != null) { |
| 134 | + if (log.isDebugEnabled()) { |
| 135 | + log.debug("Found a sample in mongo context [" + sample + "]"); |
| 136 | + } |
| 137 | + return sample; |
| 138 | + } |
| 139 | + if (log.isDebugEnabled()) { |
| 140 | + log.debug("No sample was found - will not create any child spans"); |
| 141 | + } |
| 142 | + return null; |
| 143 | + } |
| 144 | + |
| 145 | + @Override |
| 146 | + public void commandSucceeded(CommandSucceededEvent event) { |
| 147 | + RequestContext requestContext = event.getRequestContext(); |
| 148 | + if (requestContext == null) { |
| 149 | + return; |
| 150 | + } |
| 151 | + Timer.Sample sample = requestContext.getOrDefault(Timer.Sample.class, null); |
| 152 | + if (sample == null) { |
| 153 | + return; |
| 154 | + } |
| 155 | + MongoHandlerContext context = requestContext.get(MongoHandlerContext.class); |
| 156 | + context.setCommandSucceededEvent(event); |
| 157 | + if (log.isDebugEnabled()) { |
| 158 | + log.debug("Command succeeded - will stop sample [" + sample + "]"); |
| 159 | + } |
| 160 | + Timer.Builder builder = requestContext.get(Timer.Builder.class); |
| 161 | + sample.stop(builder); |
| 162 | + requestContext.delete(Timer.Sample.class); |
| 163 | + requestContext.delete(MongoHandlerContext.class); |
| 164 | + } |
| 165 | + |
| 166 | + @Override |
| 167 | + public void commandFailed(CommandFailedEvent event) { |
| 168 | + RequestContext requestContext = event.getRequestContext(); |
| 169 | + if (requestContext == null) { |
| 170 | + return; |
| 171 | + } |
| 172 | + Timer.Sample sample = requestContext.getOrDefault(Timer.Sample.class, null); |
| 173 | + if (sample == null) { |
| 174 | + return; |
| 175 | + } |
| 176 | + MongoHandlerContext context = requestContext.get(MongoHandlerContext.class); |
| 177 | + context.setCommandFailedEvent(event); |
| 178 | + if (log.isDebugEnabled()) { |
| 179 | + log.debug("Command failed - will stop sample [" + sample + "]"); |
| 180 | + } |
| 181 | + sample.error(event.getThrowable()); |
| 182 | + Timer.Builder builder = requestContext.get(Timer.Builder.class); |
| 183 | + sample.stop(builder); |
| 184 | + requestContext.delete(Timer.Sample.class); |
| 185 | + requestContext.delete(MongoHandlerContext.class); |
| 186 | + } |
| 187 | + |
| 188 | + @Nullable |
| 189 | + String getCollectionName(BsonDocument command, String commandName) { |
| 190 | + if (COMMANDS_WITH_COLLECTION_NAME.contains(commandName)) { |
| 191 | + String collectionName = getNonEmptyBsonString(command.get(commandName)); |
| 192 | + if (collectionName != null) { |
| 193 | + return collectionName; |
| 194 | + } |
| 195 | + } |
| 196 | + // Some other commands, like getMore, have a field like {"collection": |
| 197 | + // collectionName}. |
| 198 | + return getNonEmptyBsonString(command.get("collection")); |
| 199 | + } |
| 200 | + |
| 201 | + /** |
| 202 | + * @return trimmed string from {@code bsonValue} or null if the trimmed string was |
| 203 | + * empty or the value wasn't a string |
| 204 | + */ |
| 205 | + @Nullable |
| 206 | + static String getNonEmptyBsonString(BsonValue bsonValue) { |
| 207 | + if (bsonValue == null || !bsonValue.isString()) { |
| 208 | + return null; |
| 209 | + } |
| 210 | + String stringValue = bsonValue.asString().getValue().trim(); |
| 211 | + return stringValue.isEmpty() ? null : stringValue; |
| 212 | + } |
| 213 | + |
| 214 | + static String getMetricName(String commandName, @Nullable String collectionName) { |
| 215 | + if (collectionName == null) { |
| 216 | + return commandName; |
| 217 | + } |
| 218 | + return commandName + " " + collectionName; |
| 219 | + } |
| 220 | + |
| 221 | +} |
0 commit comments