Skip to content

Commit 1dbfc2b

Browse files
gjjjj0101tomsun28
andauthored
[fix] Compatible with MongoDB versions earlier than 3.6 (apache#1988)
Co-authored-by: tomsun28 <[email protected]>
1 parent 0f788b3 commit 1dbfc2b

File tree

2 files changed

+111
-17
lines changed

2 files changed

+111
-17
lines changed

collector/src/main/java/org/apache/hertzbeat/collector/collect/mongodb/MongodbSingleCollectImpl.java

Lines changed: 3 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
import com.mongodb.MongoClientSettings;
2323
import com.mongodb.MongoServerUnavailableException;
2424
import com.mongodb.MongoTimeoutException;
25-
import com.mongodb.client.ClientSession;
2625
import com.mongodb.client.MongoClient;
2726
import com.mongodb.client.MongoClients;
2827
import com.mongodb.client.MongoDatabase;
@@ -112,23 +111,16 @@ public void collect(CollectRep.MetricsData.Builder builder, long monitorId, Stri
112111
builder.setMsg("unsupported mongodb diagnostic command: " + command);
113112
return;
114113
}
115-
ClientSession clientSession = null;
116114
MongoClient mongoClient;
117115
CacheIdentifier identifier = null;
118116
try {
119117
identifier = getIdentifier(metrics.getMongodb());
120118
mongoClient = getClient(metrics, identifier);
121119
MongoDatabase mongoDatabase = mongoClient.getDatabase(metrics.getMongodb().getDatabase());
122-
clientSession = mongoClient.startSession();
123120
CollectRep.ValueRow.Builder valueRowBuilder = CollectRep.ValueRow.newBuilder();
124-
Document document;
125-
if (metricsParts.length == 1) {
126-
document = mongoDatabase.runCommand(clientSession, new Document(command, 1));
127-
} else {
128-
document = mongoDatabase.runCommand(clientSession, new Document(command, 1));
129-
for (int i = 1; i < metricsParts.length; i++) {
130-
document = (Document) document.get(metricsParts[i]);
131-
}
121+
Document document = mongoDatabase.runCommand(new Document(command, 1));
122+
for (int i = 1; i < metricsParts.length; i++) {
123+
document = (Document) document.get(metricsParts[i]);
132124
}
133125
if (document == null) {
134126
throw new RuntimeException("the document get from command " + metrics.getMongodb().getCommand() + " is null.");
@@ -145,12 +137,6 @@ public void collect(CollectRep.MetricsData.Builder builder, long monitorId, Stri
145137
String message = CommonUtil.getMessageFromThrowable(e);
146138
builder.setMsg(message);
147139
log.warn(message, e);
148-
} finally {
149-
if (clientSession != null) {
150-
try {
151-
clientSession.close();
152-
} catch (Exception ignored) {}
153-
}
154140
}
155141
}
156142

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.apache.hertzbeat.collector.collect.mongodb;
19+
20+
import static java.util.concurrent.TimeUnit.MILLISECONDS;
21+
import static org.junit.jupiter.api.Assertions.assertEquals;
22+
import java.net.URLEncoder;
23+
import java.nio.charset.StandardCharsets;
24+
import java.util.List;
25+
import com.mongodb.ConnectionString;
26+
import com.mongodb.MongoClientSettings;
27+
import com.mongodb.client.MongoClient;
28+
import com.mongodb.client.MongoClients;
29+
import com.mongodb.client.MongoDatabase;
30+
import org.apache.hertzbeat.common.entity.job.Metrics;
31+
import org.apache.hertzbeat.common.entity.job.protocol.MongodbProtocol;
32+
import org.apache.hertzbeat.common.entity.message.CollectRep;
33+
import org.bson.Document;
34+
import org.junit.jupiter.api.BeforeEach;
35+
import org.junit.jupiter.api.Test;
36+
import org.junit.jupiter.api.extension.ExtendWith;
37+
import org.mockito.InjectMocks;
38+
import org.mockito.Mock;
39+
import org.mockito.MockedStatic;
40+
import org.mockito.Mockito;
41+
import org.mockito.junit.jupiter.MockitoExtension;
42+
43+
44+
/**
45+
* Test case for {@link MongodbSingleCollectImpl}
46+
*/
47+
@ExtendWith(MockitoExtension.class)
48+
public class MongoCollectImplTest {
49+
50+
@Mock
51+
MongodbProtocol mongodbProtocol;
52+
@Mock
53+
MongoClient mongoClient;
54+
55+
@Mock
56+
MongoDatabase mongoDatabase;
57+
58+
@InjectMocks
59+
MongodbSingleCollectImpl mongodbSingleCollect;
60+
61+
@BeforeEach
62+
void setUp() {
63+
mongodbProtocol = MongodbProtocol.builder()
64+
.host("127.0.0.1")
65+
.port("5000")
66+
.username("Administrator")
67+
.password("Password")
68+
.timeout("5000")
69+
.database("test")
70+
.authenticationDatabase("admin")
71+
.build();
72+
}
73+
74+
@Test
75+
void MockTest() {
76+
CollectRep.MetricsData.Builder builder = CollectRep.MetricsData.newBuilder();
77+
mongodbProtocol.setCommand("hostInfo.os");
78+
Metrics metrics = new Metrics();
79+
metrics.setAliasFields(List.of("type", "name", "version"));
80+
metrics.setMongodb(mongodbProtocol);
81+
String osInfo = """
82+
{
83+
"os" :
84+
{
85+
"type" : "Linux",
86+
"name" : "Ubuntu",
87+
"version" : "22.04"
88+
}
89+
}""";
90+
Mockito.when(mongoDatabase.runCommand(new Document("hostInfo", 1))).thenReturn(Document.parse(osInfo));
91+
Mockito.when(mongoClient.getDatabase("test")).thenReturn(mongoDatabase);
92+
MockedStatic<MongoClients> mongoClientsMockedStatic = Mockito.mockStatic(MongoClients.class);
93+
String url = String.format("mongodb://%s:%s@%s:%s/%s?authSource=%s", mongodbProtocol.getUsername(),
94+
URLEncoder.encode(mongodbProtocol.getPassword(), StandardCharsets.UTF_8), mongodbProtocol.getHost(), mongodbProtocol.getPort(),
95+
mongodbProtocol.getDatabase(), mongodbProtocol.getAuthenticationDatabase());
96+
MongoClientSettings settings = MongoClientSettings.builder()
97+
.applyConnectionString(new ConnectionString(url))
98+
.applyToClusterSettings(b ->
99+
b.serverSelectionTimeout(Long.parseLong(mongodbProtocol.getTimeout()), MILLISECONDS))
100+
.build();
101+
mongoClientsMockedStatic.when(() -> MongoClients.create(settings)).thenReturn(mongoClient);
102+
mongodbSingleCollect.preCheck(metrics);
103+
mongodbSingleCollect.collect(builder, 1L, "test", metrics);
104+
assertEquals("Linux", builder.getValues(0).getColumns(0));
105+
assertEquals("Ubuntu", builder.getValues(0).getColumns(1));
106+
assertEquals("22.04", builder.getValues(0).getColumns(2));
107+
}
108+
}

0 commit comments

Comments
 (0)