Debian Codegraph @

ansible_collections/community/mongodb/plugins/modules/mongodb_stepdown.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 __metaclass__ = type
8
9
10 DOCUMENTATION = r'''
11 ---
12 module: mongodb_stepdown
13 short_description: Step down the MongoDB node from a PRIMARY state.
14 description: >
15 Step down the MongoDB node from the PRIMARY state if it has that status.
16 Returns OK immediately if the member is already in the SECONDARY or ARBITER states.
17 Will wait until a timeout for the member state to reach SECONDARY or PRIMARY,
18 if the member state is currently STARTUP, RECOVERING, STARTUP2 or ROLLBACK,
19 before taking any needed action.
20 author: Rhys Campbell (@rhysmeister)
21 version_added: "1.0.0"
22
23 extends_documentation_fragment:
24 - community.mongodb.login_options
25 - community.mongodb.ssl_options
26
27 options:
28 poll:
29 description:
30 - The maximum number of times query for the member status.
31 type: int
32 default: 1
33 interval:
34 description:
35 - The number of seconds to wait between poll executions.
36 type: int
37 default: 30
38 stepdown_seconds:
39 description:
40 - The number of seconds to step down the primary, during which time the stepdown member is ineligible for becoming primary.
41 type: int
42 default: 60
43 secondary_catch_up:
44 description:
45 - The secondaryCatchUpPeriodSecs parameter for the stepDown command.
46 - The number of seconds that mongod will wait for an electable secondary to catch up to the primary.
47 type: int
48 default: 10
49 force:
50 description:
51 - Optional. A boolean that determines whether the primary steps down if no electable and up-to-date secondary exists within the wait period.
52 type: bool
53 default: false
54 notes:
55 - Requires the pymongo Python package on the remote host, version 4+.. This
56 can be installed using pip or the OS package manager.
57 @see U(http://api.mongodb.org/python/current/installation.html)
58 requirements:
59 - pymongo
60 '''
61
62 EXAMPLES = r'''
63 - name: Step down the current MongoDB member
64 community.mongodb.mongodb_stepdown:
65 login_user: admin
66 login_password: secret
67
68 - name: Step down the current MongoDB member, poll a maximum of 5 times if member state is recovering
69 community.mongodb.mongodb_stepdown:
70 login_user: admin
71 login_password: secret
72 poll: 5
73 interval: 10
74 '''
75
76 RETURN = r'''
77 failed:
78 description: If the module had failed or not.
79 returned: always
80 type: bool
81 iteration:
82 description: Number of times the module has queried the replicaset status.
83 returned: always
84 type: int
85 msg:
86 description: Status message.
87 returned: always
88 type: str
89 '''
90
91
92 import time
93
94 from ansible.module_utils.basic import AnsibleModule
95 from ansible.module_utils._text import to_native
96 from ansible_collections.community.mongodb.plugins.module_utils.mongodb_common import (
97 missing_required_lib,
98 mongodb_common_argument_spec,
99 mongo_auth,
100 PYMONGO_IMP_ERR,
101 pymongo_found,
102 get_mongodb_client,
103 )
104
105
106 def member_status(client):
107 """
108 Return the member status string
109 # https://docs.mongodb.com/manual/reference/command/replSetGetStatus/
110 """
111 myStateStr = None
112 rs = client.admin.command('replSetGetStatus')
113 for member in rs["members"]:
114 if "self" in member.keys():
115 myStateStr = member["stateStr"]
116 return myStateStr
117
118
119 def member_stepdown(client, module):
120 """
121 client - MongoDB Client
122 module - Ansible module object
123 """
124
125 try:
126 from collections import OrderedDict
127 except ImportError as excep:
128 try:
129 from ordereddict import OrderedDict
130 except ImportError as excep:
131 module.fail_json(msg='Cannot import OrderedDict class. You can probably install with: pip install ordereddict: %s'
132 % to_native(excep))
133
134 iterations = 0 # How many times we have queried the member
135 failures = 0 # Number of failures when querying the replicaset
136 poll = module.params['poll']
137 interval = module.params['interval']
138 stepdown_seconds = module.params['stepdown_seconds']
139 secondary_catch_up = module.params['secondary_catch_up']
140 force = module.params['force']
141 return_doc = {}
142 status = None
143
144 while iterations < poll:
145 try:
146 iterations += 1
147 return_doc['iterations'] = iterations
148 myStateStr = member_status(client)
149 if myStateStr == "PRIMARY":
150 # Run step down command
151 if module.check_mode:
152 return_doc["msg"] = "member was stepped down"
153 return_doc['changed'] = True
154 status = True
155 break
156 else:
157 cmd_doc = OrderedDict([
158 ('replSetStepDown', stepdown_seconds),
159 ('secondaryCatchUpPeriodSecs', secondary_catch_up),
160 ('force', force)
161 ])
162 try:
163 client.admin.command(cmd_doc) # For now we assume the stepDown was successful
164 except Exception as excep:
165 # 4.0 and below close the connection as part of the stepdown.
166 # This code should be removed once we support 4.2+ onwards
167 # https://tinyurl.com/yc79g9ay
168 if str(excep) == "connection closed":
169 pass
170 else:
171 raise excep
172 return_doc['changed'] = True
173 status = True
174 return_doc["msg"] = "member was stepped down"
175 break
176 elif myStateStr in ["SECONDARY", "ARBITER"]:
177 return_doc["msg"] = "member was already at {0} state".format(myStateStr)
178 return_doc['changed'] = False
179 status = True
180 break
181 elif myStateStr in ["STARTUP", "RECOVERING", "STARTUP2", "ROLLBACK"]:
182 time.sleep(interval) # Wait for interval
183 else:
184 return_doc["msg"] = "Unexpected member state {0}".format(myStateStr)
185 return_doc['changed'] = False
186 status = False
187 break
188 except Exception as e:
189 failures += 1
190 return_doc['failed'] = True
191 return_doc['changed'] = False
192 return_doc['msg'] = str(e)
193 status = False
194 if iterations == poll:
195 break
196 else:
197 time.sleep(interval)
198
199 return status, return_doc['msg'], return_doc
200
201
202 # =========================================
203 # Module execution.
204 #
205
206
207 def main():
208 argument_spec = mongodb_common_argument_spec()
209 argument_spec.update(
210 force=dict(type='bool', default=False),
211 interval=dict(type='int', default=30),
212 poll=dict(type='int', default=1),
213 secondary_catch_up=dict(type='int', default=10),
214 stepdown_seconds=dict(type='int', default=60)
215 )
216 module = AnsibleModule(
217 argument_spec=argument_spec,
218 supports_check_mode=True,
219 required_together=[['login_user', 'login_password']],
220 )
221 if not pymongo_found:
222 module.fail_json(msg=missing_required_lib('pymongo'),
223 exception=PYMONGO_IMP_ERR)
224
225 result = dict(
226 failed=False,
227 )
228
229 try:
230 client = get_mongodb_client(module, directConnection=True)
231 client = mongo_auth(module, client, directConnection=True)
232 except Exception as e:
233 module.fail_json(msg='Unable to connect to database: %s' % to_native(e))
234
235 try:
236 status, msg, return_doc = member_stepdown(client, module)
237 iterations = return_doc['iterations']
238 changed = return_doc['changed']
239 except Exception as e:
240 module.fail_json(msg='Unable to query replica_set info: %s' % str(e))
241
242 if status is False:
243 module.fail_json(msg=msg, iterations=iterations, changed=changed)
244 else:
245 module.exit_json(msg=msg, iterations=iterations, changed=changed)
246
247
248 if __name__ == '__main__':
249 main()