Debian Codegraph @

ansible_collections/community/mongodb/plugins/modules/mongodb_status.py

raw
1 #!/usr/bin/python
2
3 # Copyright: (c) 2018, Rhys Campbell <[email protected]>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7 __metaclass__ = type
8
9
10 DOCUMENTATION = r'''
11 ---
12 module: mongodb_status
13 short_description: Validates the status of the replicaset.
14 description:
15 - Validates the status of the replicaset.
16 - The module expects all replicaset nodes to be PRIMARY, SECONDARY or ARBITER.
17 - Will wait until a timeout for the replicaset state to converge if required.
18 - Can also be used to lookup the current PRIMARY member (see examples).
19 author: Rhys Campbell (@rhysmeister)
20 version_added: "1.0.0"
21
22 extends_documentation_fragment:
23 - community.mongodb.login_options
24 - community.mongodb.ssl_options
25
26 options:
27 replica_set:
28 description:
29 - Replicaset name.
30 type: str
31 default: rs0
32 poll:
33 description:
34 - The maximum number of times to query for the replicaset status before the set converges or we fail.
35 type: int
36 default: 1
37 interval:
38 description:
39 - The number of seconds to wait between polling executions.
40 type: int
41 default: 30
42 validate:
43 description:
44 - The type of validate to perform on the replicaset.
45 - default, Suitable for most purposes. Validate that there are an odd
46 number of servers and one is PRIMARY and the remainder are in a SECONDARY
47 or ARBITER state.
48 - votes, Check the number of votes is odd and one is a PRIMARY and the
49 remainder are in a SECONDARY or ARBITER state. Authentication is
50 required here to get the replicaset configuration.
51 - minimal, Just checks that one server is in a PRIMARY state with the
52 remainder being SECONDARY or ARBITER.
53 type: str
54 choices:
55 - default
56 - votes
57 - minimal
58 default: default
59 notes:
60 - Requires the pymongo Python package on the remote host, version 4+.. This
61 can be installed using pip or the OS package manager.
62 @see U(http://api.mongodb.org/python/current/installation.html)
63 requirements:
64 - pymongo
65 '''
66
67 EXAMPLES = r'''
68 - name: Check replicaset is healthy, fail if not after first attempt
69 community.mongodb.mongodb_status:
70 replica_set: rs0
71 when: ansible_hostname == "mongodb1"
72
73 - name: Wait for the replicaset rs0 to converge, check 5 times, 10 second interval between checks
74 community.mongodb.mongodb_status:
75 replica_set: rs0
76 poll: 5
77 interval: 10
78 when: ansible_hostname == "mongodb1"
79
80 # Get the replicaset status and then lookup the primary's hostname and save to a variable
81 - name: Ensure replicaset is stable before beginning
82 community.mongodb.mongodb_status:
83 login_user: "{{ admin_user }}"
84 login_password: "{{ admin_user_password }}"
85 poll: 3
86 interval: 10
87 register: rs
88
89 - name: Lookup PRIMARY replicaset member
90 set_fact:
91 primary: "{{ item.key.split('.')[0] }}"
92 loop: "{{ lookup('dict', rs.replicaset) }}"
93 when: "'PRIMARY' in item.value"
94 '''
95
96 RETURN = r'''
97 failed:
98 description: If the module has failed or not.
99 returned: always
100 type: bool
101 iterations:
102 description: Number of times the module has queried the replicaset status.
103 returned: always
104 type: int
105 msg:
106 description: Status message.
107 returned: always
108 type: str
109 replicaset:
110 description: The last queried status of all the members of the replicaset if obtainable.
111 returned: always
112 type: dict
113 '''
114
115
116 import time
117
118 from ansible.module_utils.basic import AnsibleModule
119 from ansible.module_utils._text import to_native
120 from ansible_collections.community.mongodb.plugins.module_utils.mongodb_common import (
121 missing_required_lib,
122 mongodb_common_argument_spec,
123 mongo_auth,
124 PYMONGO_IMP_ERR,
125 pymongo_found,
126 get_mongodb_client,
127 )
128
129
130 def replicaset_config(client):
131 """
132 Return the replicaset config document
133 https://docs.mongodb.com/manual/reference/command/replSetGetConfig/
134 """
135 rs = client.admin.command('replSetGetConfig')
136 return rs
137
138
139 def replicaset_votes(config_document):
140 """
141 Return the number of votes in the replicaset
142 """
143 votes = 0
144 for member in config_document["config"]['members']:
145 votes += member['votes']
146 return votes
147
148
149 def replicaset_status(client, module):
150 """
151 Return the replicaset status document from MongoDB
152 # https://docs.mongodb.com/manual/reference/command/replSetGetStatus/
153 """
154 rs = client.admin.command('replSetGetStatus')
155 return rs
156
157
158 def replicaset_members(replicaset_document):
159 """
160 Returns the members section of the MongoDB replicaset document
161 """
162 return replicaset_document["members"]
163
164
165 def replicaset_friendly_document(members_document):
166 """
167 Returns a version of the members document with
168 only the info this module requires: name & stateStr
169 """
170 friendly_document = {}
171
172 for member in members_document:
173 friendly_document[member["name"]] = member["stateStr"]
174 return friendly_document
175
176
177 def replicaset_statuses(members_document, module):
178 """
179 Return a list of the statuses
180 """
181 statuses = []
182 for member in members_document:
183 statuses.append(members_document[member])
184 return statuses
185
186
187 def replicaset_good(statuses, module, votes):
188 """
189 Returns true if the replicaset is in a "good" condition.
190 Good is defined as an odd number of servers >= 3, with
191 max one primary, and any even amount of
192 secondary and arbiter servers
193 """
194 msg = "Unset"
195 status = None
196 valid_statuses = ["PRIMARY", "SECONDARY", "ARBITER"]
197 validate = module.params['validate']
198
199 if validate == "default":
200 if len(statuses) % 2 == 1:
201 if (statuses.count("PRIMARY") == 1
202 and ((statuses.count("SECONDARY")
203 + statuses.count("ARBITER")) % 2 == 0)
204 and len(set(statuses) - set(valid_statuses)) == 0):
205 status = True
206 msg = "replicaset is in a converged state"
207 else:
208 status = False
209 msg = "replicaset is not currently in a converged state"
210 else:
211 msg = "Even number of servers in replicaset."
212 status = False
213 elif validate == "votes":
214 # Need to validate the number of votes in the replicaset
215 if votes % 2 == 1: # We have a good number of votes
216 if (statuses.count("PRIMARY") == 1
217 and len(set(statuses) - set(valid_statuses)) == 0):
218 status = True
219 msg = "replicaset is in a converged state"
220 else:
221 status = False
222 msg = "replicaset is not currently in a converged state"
223 else:
224 msg = "Even number of votes in replicaset."
225 status = False
226 elif validate == "minimal":
227 if (statuses.count("PRIMARY") == 1
228 and len(set(statuses) - set(valid_statuses)) == 0):
229 status = True
230 msg = "replicaset is in a converged state"
231 else:
232 status = False
233 msg = "replicaset is not currently in a converged state"
234 else:
235 module.fail_json(msg="Invalid value for validate has been provided: {0}".format(validate))
236 return status, msg
237
238
239 def replicaset_status_poll(client, module):
240 """
241 client - MongoDB Client
242 poll - Number of times to poll
243 interval - interval between polling attempts
244 """
245 iterations = 0 # How many times we have queried the cluster
246 failures = 0 # Number of failures when querying the replicaset
247 poll = module.params['poll']
248 interval = module.params['interval']
249 status = None
250 return_doc = {}
251 votes = None
252 config = None
253
254 while iterations < poll:
255 try:
256 iterations += 1
257 replicaset_document = replicaset_status(client, module)
258 members = replicaset_members(replicaset_document)
259 friendly_document = replicaset_friendly_document(members)
260 statuses = replicaset_statuses(friendly_document, module)
261
262 if module.params['validate'] == "votes": # Requires auth
263 config = replicaset_config(client)
264 votes = replicaset_votes(config)
265
266 status, msg = replicaset_good(statuses, module, votes)
267
268 if status: # replicaset looks good
269 return_doc = {"failures": failures,
270 "poll": poll,
271 "iterations": iterations,
272 "msg": msg,
273 "replicaset": friendly_document}
274 break
275 else:
276 failures += 1
277 return_doc = {"failures": failures,
278 "poll": poll,
279 "iterations": iterations,
280 "msg": msg,
281 "replicaset": friendly_document,
282 "failed": True}
283 if iterations == poll:
284 break
285 else:
286 time.sleep(interval)
287 except Exception as e:
288 failures += 1
289 return_doc['failed'] = True
290 return_doc['msg'] = str(e)
291 status = False
292 if iterations == poll:
293 break
294 else:
295 time.sleep(interval)
296
297 return_doc['failures'] = failures
298 return status, return_doc['msg'], return_doc
299
300
301 # =========================================
302 # Module execution.
303 #
304
305
306 def main():
307 argument_spec = mongodb_common_argument_spec()
308 argument_spec.update(
309 interval=dict(type='int', default=30),
310 poll=dict(type='int', default=1),
311 replica_set=dict(type='str', default="rs0"),
312 validate=dict(type='str', choices=['default', 'votes', 'minimal'], default='default'),
313 )
314 module = AnsibleModule(
315 argument_spec=argument_spec,
316 supports_check_mode=False,
317 required_together=[['login_user', 'login_password']],
318 )
319 if not pymongo_found:
320 module.fail_json(msg=missing_required_lib('pymongo'),
321 exception=PYMONGO_IMP_ERR)
322
323 replica_set = module.params['replica_set']
324 msg = None
325
326 result = dict(
327 failed=False,
328 replica_set=replica_set,
329 )
330
331 try:
332 client = get_mongodb_client(module, directConnection=True)
333 client = mongo_auth(module, client, directConnection=True)
334 except Exception as e:
335 module.fail_json(msg='Unable to connect to database: %s' % to_native(e))
336
337 if len(replica_set) == 0:
338 module.fail_json(msg="Parameter 'replica_set' must not be an empty string")
339
340 try:
341 status, msg, return_doc = replicaset_status_poll(client, module) # Sort out the return doc
342 replicaset = return_doc['replicaset']
343 iterations = return_doc['iterations']
344 except Exception as e:
345 module.fail_json(msg='Unable to query replica_set info: {0}: {1}'.format(str(e), msg))
346
347 if status is False:
348 module.fail_json(msg=msg, replicaset=replicaset, iterations=iterations)
349 else:
350 module.exit_json(msg=msg, replicaset=replicaset, iterations=iterations)
351
352
353 if __name__ == '__main__':
354 main()