| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright: (c) 2021, 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_shard_zone |
| 13 |
short_description: Manage Shard Zones. |
| 14 |
description: |
| 15 |
- Manage Shard Zones. |
| 16 |
- Add and remove shard zones. |
| 17 |
author: Rhys Campbell (@rhysmeister) |
| 18 |
version_added: "1.3.0" |
| 19 |
|
| 20 |
extends_documentation_fragment: |
| 21 |
- community.mongodb.login_options |
| 22 |
- community.mongodb.ssl_options |
| 23 |
|
| 24 |
options: |
| 25 |
name: |
| 26 |
description: |
| 27 |
- The name of the zone. |
| 28 |
required: true |
| 29 |
type: str |
| 30 |
namespace: |
| 31 |
description: |
| 32 |
- The namespace the zone is assigned to |
| 33 |
- Should be given in the form database.collection. |
| 34 |
type: str |
| 35 |
ranges: |
| 36 |
description: |
| 37 |
- The ranges assigned to the Zone. |
| 38 |
type: list |
| 39 |
elements: list |
| 40 |
state: |
| 41 |
description: |
| 42 |
- The state of the zone. |
| 43 |
required: false |
| 44 |
type: str |
| 45 |
choices: |
| 46 |
- "present" |
| 47 |
- "absent" |
| 48 |
default: "present" |
| 49 |
mongos_process: |
| 50 |
description: |
| 51 |
- Provide a custom name for the mongos process. |
| 52 |
- Most users can ignore this setting. |
| 53 |
required: false |
| 54 |
type: str |
| 55 |
default: "mongos" |
| 56 |
notes: |
| 57 |
- Requires the pymongo Python package on the remote host, version 4+.. This |
| 58 |
can be installed using pip or the OS package manager. |
| 59 |
@see U(http://api.mongodb.org/python/current/installation.html) |
| 60 |
requirements: |
| 61 |
- pymongo |
| 62 |
''' |
| 63 |
|
| 64 |
EXAMPLES = r''' |
| 65 |
- name: Add a shard zone for NYC |
| 66 |
community.mongodb.mongodb_shard_zone: |
| 67 |
name: "NYC" |
| 68 |
namespace: "records.users" |
| 69 |
ranges: |
| 70 |
- [{ zipcode: "10001" }, { zipcode: "10281" }] |
| 71 |
- [{ zipcode: "11201" }, { zipcode: "11240" }] |
| 72 |
state: "present" |
| 73 |
|
| 74 |
- name: Remove all zone ranges |
| 75 |
community.mongodb.mongodb_shard_zone: |
| 76 |
name: "NYC" |
| 77 |
namespace: "records.users" |
| 78 |
state: "absent" |
| 79 |
|
| 80 |
- name: Remove a specific zone range |
| 81 |
community.mongodb.mongodb_shard_zone: |
| 82 |
name: "NYC" |
| 83 |
namespace: "records.users" |
| 84 |
ranges: |
| 85 |
- [{ zipcode: "11201" }, { zipcode: "11240" }] |
| 86 |
state: "absent" |
| 87 |
''' |
| 88 |
|
| 89 |
RETURN = r''' |
| 90 |
changed: |
| 91 |
description: True when a change has happened |
| 92 |
returned: success |
| 93 |
type: bool |
| 94 |
msg: |
| 95 |
description: A short description of what happened. |
| 96 |
returned: failure |
| 97 |
type: str |
| 98 |
failed: |
| 99 |
description: If something went wrong |
| 100 |
returned: failed |
| 101 |
type: bool |
| 102 |
''' |
| 103 |
|
| 104 |
from ansible.module_utils.basic import AnsibleModule |
| 105 |
from ansible.module_utils._text import to_native |
| 106 |
from ansible_collections.community.mongodb.plugins.module_utils.mongodb_common import ( |
| 107 |
missing_required_lib, |
| 108 |
mongodb_common_argument_spec, |
| 109 |
mongo_auth, |
| 110 |
PYMONGO_IMP_ERR, |
| 111 |
pymongo_found, |
| 112 |
get_mongodb_client, |
| 113 |
) |
| 114 |
|
| 115 |
has_ordereddict = False |
| 116 |
try: |
| 117 |
from collections import OrderedDict |
| 118 |
has_ordereddict = True |
| 119 |
except ImportError as excep: |
| 120 |
try: |
| 121 |
from ordereddict import OrderedDict |
| 122 |
has_ordereddict = True |
| 123 |
except ImportError as excep: |
| 124 |
pass |
| 125 |
|
| 126 |
|
| 127 |
def zone_range_exists(client, namespace, min, max, tag): |
| 128 |
''' |
| 129 |
Returns true if a particular zone range exists |
| 130 |
Record format seems to be different than the docs state in 4.4.6 |
| 131 |
{ "_id" : ObjectId("60e2e7cff7c9d447440bb114"), |
| 132 |
"ns" : "records.users", |
| 133 |
"min" : { "zipcode" : "10001" }, |
| 134 |
"max" : { "zipcode" : "10281" }, |
| 135 |
"tag" : "NYC" } |
| 136 |
|
| 137 |
@client - MongoDB connection |
| 138 |
@namespace - In the form database.collection |
| 139 |
@min - The min range value |
| 140 |
@max - The max range value |
| 141 |
@tag - The tag or Zone name |
| 142 |
''' |
| 143 |
query = { |
| 144 |
# "_id.ns": namespace, 4.4.X Bug??? ObjectId given as id |
| 145 |
# "_id.min": min, |
| 146 |
'ns': namespace, |
| 147 |
'min': min, |
| 148 |
'max': max, |
| 149 |
'tag': tag |
| 150 |
} |
| 151 |
|
| 152 |
status = None |
| 153 |
result = client["config"].tags.find_one(query) |
| 154 |
if result: |
| 155 |
status = True |
| 156 |
else: |
| 157 |
status = False |
| 158 |
return status |
| 159 |
|
| 160 |
|
| 161 |
def zone_exists(client, tag): |
| 162 |
''' |
| 163 |
Returns True if the given zone exists |
| 164 |
@client - MongoDB connection |
| 165 |
@tag - The zone to check for |
| 166 |
''' |
| 167 |
status = None |
| 168 |
result = client["config"].shards.find_one({"tags": tag}) |
| 169 |
if result: |
| 170 |
status = True |
| 171 |
else: |
| 172 |
status = False |
| 173 |
return status |
| 174 |
|
| 175 |
|
| 176 |
def add_zone_range(client, namespace, min, max, tag): |
| 177 |
''' |
| 178 |
Adds a zone range |
| 179 |
@client - MongoDB connection |
| 180 |
@namespace - In the form database.collection |
| 181 |
@min - The min range value |
| 182 |
@max - The max range value |
| 183 |
@tag - The tag or Zone name |
| 184 |
''' |
| 185 |
cmd_doc = OrderedDict([ |
| 186 |
('updateZoneKeyRange', namespace), |
| 187 |
('min', min), |
| 188 |
('max', max), |
| 189 |
('zone', tag), |
| 190 |
]) |
| 191 |
client['admin'].command(cmd_doc) |
| 192 |
|
| 193 |
|
| 194 |
def remove_zone_range(client, namespace, min, max): |
| 195 |
''' |
| 196 |
Remove a zone range. |
| 197 |
We do this by setting the zone to None |
| 198 |
@client - MongoDB connection |
| 199 |
@namespace - In the form database.collection |
| 200 |
@min - The min range value |
| 201 |
@max - The max range value |
| 202 |
''' |
| 203 |
cmd_doc = OrderedDict([ |
| 204 |
('updateZoneKeyRange', namespace), |
| 205 |
('min', min), |
| 206 |
('max', max), |
| 207 |
('zone', None), |
| 208 |
]) |
| 209 |
client['admin'].command(cmd_doc) |
| 210 |
|
| 211 |
|
| 212 |
def remove_all_zone_range_by_tag(client, tag): |
| 213 |
result = client["config"].tags.find({"tag": tag}) |
| 214 |
for r in result: |
| 215 |
remove_zone_range(client, r['ns'], r['min'], r['max']) |
| 216 |
|
| 217 |
|
| 218 |
def zone_range_count(client, tag): |
| 219 |
''' |
| 220 |
Returns the count of records that exists for the given tag in config.tags |
| 221 |
''' |
| 222 |
return client['config'].tags.count_documents({"tag": tag}) |
| 223 |
|
| 224 |
|
| 225 |
def main(): |
| 226 |
argument_spec = mongodb_common_argument_spec() |
| 227 |
argument_spec.update( |
| 228 |
name=dict(type='str', required=True), |
| 229 |
namespace=dict(type='str'), |
| 230 |
ranges=dict(type='list', elements='list'), |
| 231 |
mongos_process=dict(type='str', required=False, default="mongos"), |
| 232 |
state=dict(type='str', default="present", choices=["present", "absent"]), |
| 233 |
) |
| 234 |
module = AnsibleModule( |
| 235 |
argument_spec=argument_spec, |
| 236 |
supports_check_mode=True, |
| 237 |
required_together=[['login_user', 'login_password']], |
| 238 |
required_if=[("state", "present", ("namespace", "ranges"))] |
| 239 |
) |
| 240 |
|
| 241 |
if not has_ordereddict: |
| 242 |
module.fail_json(msg='Cannot import OrderedDict class. You can probably install with: pip install ordereddict') |
| 243 |
|
| 244 |
if not pymongo_found: |
| 245 |
module.fail_json(msg=missing_required_lib('pymongo'), |
| 246 |
exception=PYMONGO_IMP_ERR) |
| 247 |
|
| 248 |
state = module.params['state'] |
| 249 |
zone_name = module.params['name'] |
| 250 |
namespace = module.params['namespace'] |
| 251 |
ranges = module.params['ranges'] |
| 252 |
|
| 253 |
if ranges is not None: |
| 254 |
if not isinstance(ranges, list) or not isinstance(ranges[0], list) or not isinstance(ranges[0][0], dict): |
| 255 |
module.fail_json(msg="Provided ranges are invalid {0} {1} {2}".format(str(type(ranges)), |
| 256 |
str(type(ranges[0])), |
| 257 |
str(type(ranges[0][0])))) |
| 258 |
|
| 259 |
result = dict( |
| 260 |
changed=False, |
| 261 |
) |
| 262 |
|
| 263 |
try: |
| 264 |
client = get_mongodb_client(module) |
| 265 |
client = mongo_auth(module, client) |
| 266 |
except Exception as excep: |
| 267 |
module.fail_json(msg='Unable to connect to MongoDB: %s' % to_native(excep)) |
| 268 |
|
| 269 |
try: |
| 270 |
if not zone_exists(client, zone_name): |
| 271 |
msg = ("The tag {0} does not exist. You need to associate a tag with" |
| 272 |
" a shard before using this module. You can do that with the" |
| 273 |
" mongodb_shard_tag module.".format(zone_name)) |
| 274 |
module.fail_json(msg=msg) |
| 275 |
else: |
| 276 |
# first check if the ranges exist |
| 277 |
range_count = 0 |
| 278 |
if state == "present": |
| 279 |
for range in ranges: |
| 280 |
if zone_range_exists(client, namespace, range[0], range[1], zone_name): |
| 281 |
range_count += 1 |
| 282 |
result['range_count'] = range_count |
| 283 |
result['ranges'] = len(ranges) |
| 284 |
if range_count == len(ranges): # All ranges are the same |
| 285 |
result['changed'] = False |
| 286 |
result['msg'] = "All Zone Ranges present for {0}".format(zone_name) |
| 287 |
else: |
| 288 |
for range in ranges: |
| 289 |
if not module.check_mode: |
| 290 |
add_zone_range(client, namespace, range[0], range[1], zone_name) |
| 291 |
result['changed'] = True |
| 292 |
result['msg'] = "Added zone ranges for {0}".format(zone_name) |
| 293 |
elif state == "absent": |
| 294 |
range_count = zone_range_count(client, zone_name) |
| 295 |
deleted_count = 0 |
| 296 |
if range_count > 0 and ranges is None: |
| 297 |
if not module.check_mode: |
| 298 |
remove_all_zone_range_by_tag(client, zone_name) |
| 299 |
deleted_count = range_count |
| 300 |
result['changed'] = True |
| 301 |
result['msg'] = "{0} zone ranges for {1} deleted.".format(deleted_count, zone_name) |
| 302 |
elif ranges is not None: |
| 303 |
for range in ranges: |
| 304 |
if zone_range_exists(client, namespace, range[0], range[1], zone_name): |
| 305 |
if not module.check_mode: |
| 306 |
remove_zone_range(client, namespace, range[0], range[1]) |
| 307 |
deleted_count += 1 |
| 308 |
if deleted_count > 0: |
| 309 |
result['changed'] = True |
| 310 |
result['msg'] = "{0} zone ranges for {1} deleted.".format(deleted_count, zone_name) |
| 311 |
else: |
| 312 |
result['changed'] = False |
| 313 |
result['msg'] = "The provided zone ranges are not present for {0}".format(zone_name) |
| 314 |
else: |
| 315 |
result['changed'] = False |
| 316 |
result['msg'] = "No zone ranges present for {0}".format(zone_name) |
| 317 |
except Exception as excep: |
| 318 |
module.fail_json(msg="An error occurred: {0}".format(excep)) |
| 319 |
|
| 320 |
module.exit_json(**result) |
| 321 |
|
| 322 |
|
| 323 |
if __name__ == '__main__': |
| 324 |
main() |