1 | // |
---|---|
2 | // ReplicaSet.cpp |
3 | // |
4 | // Library: MongoDB |
5 | // Package: MongoDB |
6 | // Module: ReplicaSet |
7 | // |
8 | // Copyright (c) 2012, Applied Informatics Software Engineering GmbH. |
9 | // and Contributors. |
10 | // |
11 | // SPDX-License-Identifier: BSL-1.0 |
12 | // |
13 | |
14 | |
15 | #include "Poco/MongoDB/ReplicaSet.h" |
16 | #include "Poco/MongoDB/QueryRequest.h" |
17 | #include "Poco/MongoDB/ResponseMessage.h" |
18 | |
19 | |
20 | namespace Poco { |
21 | namespace MongoDB { |
22 | |
23 | |
24 | ReplicaSet::ReplicaSet(const std::vector<Net::SocketAddress> &addresses): |
25 | _addresses(addresses) |
26 | { |
27 | } |
28 | |
29 | |
30 | ReplicaSet::~ReplicaSet() |
31 | { |
32 | } |
33 | |
34 | |
35 | Connection::Ptr ReplicaSet::findMaster() |
36 | { |
37 | Connection::Ptr master; |
38 | |
39 | for (std::vector<Net::SocketAddress>::iterator it = _addresses.begin(); it != _addresses.end(); ++it) |
40 | { |
41 | master = isMaster(*it); |
42 | if (!master.isNull()) |
43 | { |
44 | break; |
45 | } |
46 | } |
47 | |
48 | return master; |
49 | } |
50 | |
51 | |
52 | Connection::Ptr ReplicaSet::isMaster(const Net::SocketAddress& address) |
53 | { |
54 | Connection::Ptr conn = new Connection(); |
55 | |
56 | try |
57 | { |
58 | conn->connect(address); |
59 | |
60 | QueryRequest request("admin.$cmd"); |
61 | request.setNumberToReturn(1); |
62 | request.selector().add("isMaster", 1); |
63 | |
64 | ResponseMessage response; |
65 | conn->sendRequest(request, response); |
66 | |
67 | if (response.documents().size() > 0) |
68 | { |
69 | Document::Ptr doc = response.documents()[0]; |
70 | if (doc->get<bool>("ismaster")) |
71 | { |
72 | return conn; |
73 | } |
74 | else if (doc->exists("primary")) |
75 | { |
76 | return isMaster(Net::SocketAddress(doc->get<std::string>("primary"))); |
77 | } |
78 | } |
79 | } |
80 | catch (...) |
81 | { |
82 | conn = 0; |
83 | } |
84 | |
85 | return 0; |
86 | } |
87 | |
88 | |
89 | } } // namespace Poco::MongoDB |
90 |