Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright: (c) 2020, 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
8 __metaclass__ = type
9
10
11 DOCUMENTATION = r'''
12 ---
13 module: mongodb_balancer
14 short_description: Manages the MongoDB Sharded Cluster Balancer.
15 description:
16 - Manages the MongoDB Sharded Cluster Balancer.
17 - Start or stop the balancer.
18 - Adjust the cluster chunksize.
19 - Enable or disable autosplit.
20 - Add or remove a balancer window.
21 author: Rhys Campbell (@rhysmeister)
22 version_added: "1.0.0"
23
24 extends_documentation_fragment:
25 - community.mongodb.login_options
26 - community.mongodb.ssl_options
27
28 options:
29 autosplit:
30 description:
31 - Disable or enable the autosplit flag in the config.settings collection.
32 - From MongoDB 6.1 automatic chunk splitting is not performed so this parameter is not valid in this and later versions. See more see [enableAutoSplit](https://www.mongodb.com/docs/manual/reference/method/sh.enableAutoSplit/). # noqa: E501
33 - This parameter is deprecated and will be removed in a future release.
34 required: false
35 type: bool
36 chunksize:
37 description:
38 - Control the size of chunks in the sharded cluster.
39 - Value should be given in MB.
40 required: false
41 type: int
42 state:
43 description:
44 - Manage the Balancer for the Cluster
45 required: false
46 type: str
47 choices:
48 - "started"
49 - "stopped"
50 default: "started"
51 mongos_process:
52 description:
53 - Provide a custom name for the mongos process.
54 - Most users can ignore this setting.
55 required: false
56 type: str
57 default: "mongos"
58 window:
59 description:
60 - Schedule the balancer window.
61 - Provide the following dictionary keys start, stop, state
62 - The state key should be "present" or "absent".
63 - The start and stop keys are ignored when state is "absent".
64 - start and stop should be strings in "HH:MM" format indicating the time bounds of the window.
65 type: raw
66 required: false
67 notes:
68 - Requires the pymongo Python package on the remote host, version 4+. This
69 can be installed using pip or the OS package manager. @see U(https://www.mongodb.com/docs/languages/python/pymongo-driver/current/get-started/download-and-install/)
70 requirements:
71 - pymongo
72 '''
73
74 EXAMPLES = r'''
75 - name: Start the balancer
76 community.mongodb.mongodb_balancer:
77 state: started
78
79 - name: Stop the balancer and disable autosplit
80 community.mongodb.mongodb_balancer:
81 state: stopped
82 autosplit: false
83
84 - name: Enable autosplit
85 community.mongodb.mongodb_balancer:
86 autosplit: true
87
88 - name: Change the default chunksize to 128MB
89 community.mongodb.mongodb_balancer:
90 chunksize: 128
91
92 - name: Add or update a balancing window
93 community.mongodb.mongodb_balancer:
94 window:
95 start: "23:00"
96 stop: "06:00"
97 state: "present"
98
99 - name: Remove a balancing window
100 community.mongodb.mongodb_balancer:
101 window:
102 state: "absent"
103 '''
104
105 RETURN = r'''
106 changed:
107 description: Whether the balancer state or autosplit changed.
108 returned: success
109 type: bool
110 old_balancer_state:
111 description: The previous state of the balancer
112 returned: When balancer state is changed
113 type: str
114 new_balancer_state:
115 description: The new state of the balancer.
116 returned: When balancer state is changed
117 type: str
118 old_autosplit:
119 description: The previous state of autosplit.
120 returned: When autosplit is changed.
121 type: str
122 new_autosplit:
123 description: The new state of autosplit.
124 returned: When autosplit is changed.
125 type: str
126 old_chunksize:
127 description: The previous value for chunksize.
128 returned: When chunksize is changed.
129 type: int
130 new_chunksize:
131 description: The new value for chunksize.
132 returned: When chunksize is changed.
133 type: int
134 msg:
135 description: A short description of what happened.
136 returned: failure
137 type: str
138 failed:
139 description: If something went wrong
140 returned: failed
141 type: bool
142 '''
143
144 import time
145
146 from ansible.module_utils.basic import AnsibleModule
147 from ansible.module_utils._text import to_native
148 from ansible_collections.community.mongodb.plugins.module_utils.mongodb_common import (
149 missing_required_lib,
150 mongodb_common_argument_spec,
151 mongo_auth,
152 PYMONGO_IMP_ERR,
153 pymongo_found,
154 get_mongodb_client,
155 )
156
157 has_ordereddict = False
158 try:
159 from collections import OrderedDict
160 has_ordereddict = True
161 except ImportError as excep:
162 try:
163 from ordereddict import OrderedDict
164 has_ordereddict = True
165 except ImportError as excep:
166 pass
167
168
169 def get_balancer_state(client):
170 '''
171 Gets the state of the MongoDB balancer. The config.settings collection does
172 not exist until the balancer has been started for the first time
173 { "_id" : "balancer", "mode" : "full", "stopped" : false }
174 { "_id" : "autosplit", "enabled" : true }
175 '''
176 balancer_state = None
177 result = client["config"].settings.find_one({"_id": "balancer"})
178 if not result:
179 balancer_state = "stopped"
180 else:
181 if result['stopped'] is False:
182 balancer_state = "started"
183 else:
184 balancer_state = "stopped"
185 return balancer_state
186
187
188 def stop_balancer(client):
189 '''
190 Stops MongoDB balancer
191 '''
192 cmd_doc = OrderedDict([
193 ('balancerStop', 1),
194 ('maxTimeMS', 60000)
195 ])
196 client['admin'].command(cmd_doc)
197 time.sleep(1)
198
199
200 def start_balancer(client):
201 '''
202 Starts MongoDB balancer
203 '''
204 cmd_doc = OrderedDict([
205 ('balancerStart', 1),
206 ('maxTimeMS', 60000)
207 ])
208 client['admin'].command(cmd_doc)
209 time.sleep(1)
210
211
212 def enable_autosplit(client):
213 client["config"].settings.update_one({"_id": "autosplit"},
214 {"$set": {"enabled": True}},
215 upsert=True)
216
217
218 def disable_autosplit(client):
219 client["config"].settings.update_one({"_id": "autosplit"},
220 {"$set": {"enabled": False}},
221 upsert=True)
222
223
224 def get_autosplit(client):
225 autosplit = False
226 result = client["config"].settings.find_one({"_id": "autosplit"})
227 if result is not None:
228 autosplit = result['enabled']
229 return autosplit
230
231
232 def get_chunksize(client):
233 '''
234 Default chunksize is 64MB
235 '''
236 chunksize = None
237 result = client["config"].settings.find_one({"_id": "chunksize"})
238 if not result:
239 chunksize = 64
240 else:
241 chunksize = result['value']
242 return chunksize
243
244
245 def set_chunksize(client, chunksize):
246 client["config"].settings.update_one({"_id": "chunksize"},
247 {"$set": {"value": chunksize}},
248 upsert=True)
249
250
251 def set_balancing_window(client, start, stop):
252 s = False
253 result = client["config"].settings.update_one({"_id": "balancer"},
254 {"$set": {
255 "activeWindow": {
256 "start": start,
257 "stop": stop}}},
258 upsert=True)
259 if result.modified_count == 1 or result.upserted_id is not None:
260 s = True
261 return s
262
263
264 def remove_balancing_window(client):
265 s = False
266 result = client["config"].settings.update_one({"_id": "balancer"},
267 {"$unset": {"activeWindow": True}})
268 if result.modified_count == 1:
269 s = True
270 return s
271
272
273 def balancing_window(client, start, stop):
274 s = False
275 if start is not None and stop is not None:
276 result = client["config"].settings.find_one({"_id": "balancer",
277 "activeWindow.start": start,
278 "activeWindow.stop": stop})
279 else:
280 result = client["config"].settings.find_one({"_id": "balancer", "activeWindow": {"$exists": True}})
281 if result:
282 s = True
283 return s
284
285
286 def validate_window(window, module):
287 if window is not None:
288 if 'state' not in window.keys():
289 module.fail_json(msg="Balancing window state must be specified")
290 elif window['state'] not in ['present', 'absent']:
291 module.fail_json(msg="Balancing window state must be present or absent")
292 elif window['state'] == "present" \
293 and ("start" not in window.keys()
294 or "stop" not in window.keys()):
295 module.fail_json(msg="Balancing window start and stop values must be specified")
296 return True
297
298
299 def main():
300 argument_spec = mongodb_common_argument_spec()
301 argument_spec.update(
302 autosplit=dict(type='bool', default=None),
303 chunksize=dict(type='int', default=None),
304 mongos_process=dict(type='str', required=False, default="mongos"),
305 state=dict(type='str', default="started", choices=["started", "stopped"]),
306 window=dict(type='raw', default=None)
307 )
308 module = AnsibleModule(
309 argument_spec=argument_spec,
310 supports_check_mode=True,
311 required_together=[['login_user', 'login_password']],
312 )
313
314 if not has_ordereddict:
315 module.fail_json(msg='Cannot import OrderedDict class. You can probably install with: pip install ordereddict')
316
317 if not pymongo_found:
318 module.fail_json(msg=missing_required_lib('pymongo'),
319 exception=PYMONGO_IMP_ERR)
320
321 login_host = module.params['login_host']
322 login_port = module.params['login_port']
323 balancer_state = module.params['state']
324 autosplit = module.params['autosplit']
325 chunksize = module.params['chunksize']
326 mongos_process = module.params['mongos_process']
327 window = module.params['window']
328
329 # Validate window
330 validate_window(window, module)
331
332 result = dict(
333 changed=False,
334 )
335
336 try:
337 client = get_mongodb_client(module)
338 client = mongo_auth(module, client)
339 except Exception as excep:
340 module.fail_json(msg='Unable to connect to MongoDB: %s' % to_native(excep))
341
342 changed = False
343 cluster_balancer_state = None
344 cluster_autosplit = None
345 cluster_chunksize = None
346 old_balancer_state = None
347 new_balancer_state = None
348 old_autosplit = None
349 new_autosplit = None
350 old_chunksize = None
351 new_chunksize = None
352
353 try:
354
355 if client["admin"].command("serverStatus")["process"] != mongos_process:
356 module.fail_json(msg="Process running on {0}:{1} is not a {2}".format(login_host, login_port, mongos_process))
357
358 cluster_balancer_state = get_balancer_state(client)
359 if autosplit is not None:
360 cluster_autosplit = get_autosplit(client)
361 if chunksize is not None:
362 cluster_chunksize = get_chunksize(client)
363
364 if module.check_mode:
365 if balancer_state != cluster_balancer_state:
366 old_balancer_state = cluster_balancer_state
367 new_balancer_state = balancer_state
368 changed = True
369 if (autosplit is not None
370 and autosplit != cluster_autosplit):
371 old_autosplit = cluster_autosplit
372 new_autosplit = autosplit
373 changed = True
374 if (chunksize is not None
375 and chunksize != cluster_chunksize):
376 old_chunksize = cluster_chunksize
377 new_chunksize = chunksize
378 changed = True
379 if window is not None:
380 if balancing_window(client, window.get('start'), window.get('stop')):
381 if window['state'] == "present":
382 pass
383 else:
384 changed = True
385 else:
386 if window['state'] == "present":
387 changed = True
388 else:
389 pass
390 else:
391 if balancer_state is not None \
392 and balancer_state != cluster_balancer_state:
393 if balancer_state == "started":
394 start_balancer(client)
395 old_balancer_state = cluster_balancer_state
396 new_balancer_state = get_balancer_state(client)
397 changed = True
398 else:
399 stop_balancer(client)
400 old_balancer_state = cluster_balancer_state
401 new_balancer_state = get_balancer_state(client)
402 changed = True
403 if autosplit is not None \
404 and autosplit != cluster_autosplit:
405 if autosplit:
406 enable_autosplit(client)
407 old_autosplit = cluster_autosplit
408 new_autosplit = autosplit
409 changed = True
410 else:
411 disable_autosplit(client)
412 old_autosplit = cluster_autosplit
413 new_autosplit = autosplit
414 changed = True
415 if (chunksize is not None
416 and chunksize != cluster_chunksize):
417 set_chunksize(client, chunksize)
418 old_chunksize = cluster_chunksize
419 new_chunksize = chunksize
420 changed = True
421 if window is not None:
422 if balancing_window(client, window.get('start'), window.get('stop')):
423 if window['state'] == "present":
424 pass
425 else:
426 remove_balancing_window(client)
427 changed = True
428 else:
429 if window['state'] == "present":
430 set_balancing_window(client,
431 window['start'],
432 window['stop'])
433 changed = True
434 else:
435 pass
436 except Exception as excep:
437 result["msg"] = "An error occurred: {0}".format(excep)
438
439 result['changed'] = changed
440 if old_balancer_state is not None:
441 result['old_balancer_state'] = old_balancer_state
442 result['new_balancer_state'] = new_balancer_state
443 if old_autosplit is not None:
444 result['old_autosplit'] = old_autosplit
445 result['new_autosplit'] = new_autosplit
446 if old_chunksize is not None:
447 result['old_chunksize'] = old_chunksize
448 result['new_chunksize'] = new_chunksize
449
450 module.exit_json(**result)
451
452
453 if __name__ == '__main__':
454 main()