
    Vh!#                         d dl mZmZmZ eZdZdZdZd dl	Z	d dl
mZmZ d dlmZ d dlmZmZmZmZmZmZmZ d	 Zd
 Zd Zd Zd Zd Zd Zedk(  r e        yy)    )absolute_importdivisionprint_functiona  
---
module: mongodb_shard
short_description: Add or remove shards from a MongoDB Cluster
description:
    -  Add or remove shards from a MongoDB Cluster.
author: Rhys Campbell (@rhysmeister)
version_added: "1.0.0"

extends_documentation_fragment:
  - community.mongodb.login_options
  - community.mongodb.ssl_options

options:
  shard:
    description:
      - The shard connection string.
      - Should be supplied in the form <replicaset>/host:port as detailed in U(https://docs.mongodb.com/manual/tutorial/add-shards-to-shard-cluster/).
      - For example rs0/example1.mongodb.com:27017.
    required: true
    type: str
  sharded_databases:
    description:
      - Enable sharding on the listed database.
      - Can be supplied as a string or a list of strings.
      - Sharding cannot be disabled on a database.
      - Starting in MongoDB 6.0, the enableSharding command is no longer required to shard a collection and this parameter is ignored.
    required: false
    type: raw
  mongos_process:
    description:
      - Provide a custom name for the mongos process you are connecting to.
      - Most users can ignore this setting.
    required: false
    type: str
    default: "mongos"
  state:
    description:
      - Whether the shard should be present or absent from the Cluster.
    required: false
    type: str
    default: present
    choices:
      - "absent"
      - "present"

notes:
    - Requires the pymongo Python package on the remote host, version 4+.
requirements: [ pymongo ]
a"  
- name: Add a replicaset shard named rs1 with a member running on port 27018 on mongodb0.example.net
  community.mongodb.mongodb_shard:
    login_user: admin
    login_password: admin
    shard: "rs1/mongodb0.example.net:27018"
    state: present

- name: Add a standalone mongod shard running on port 27018 of mongodb0.example.net
  community.mongodb.mongodb_shard:
    login_user: admin
    login_password: admin
    shard: "mongodb0.example.net:27018"
    state: present

- name: To remove a shard called 'rs1'
  community.mongodb.mongodb_shard:
    login_user: admin
    login_password: admin
    shard: rs1
    state: absent

# Single node shard running on localhost
- name: Ensure shard rs0 exists
  community.mongodb.mongodb_shard:
    login_user: admin
    login_password: secret
    shard: "rs0/localhost:3001"
    state: present

# Single node shard running on localhost
- name: Ensure shard rs1 exists
  community.mongodb.mongodb_shard:
    login_user: admin
    login_password: secret
    shard: "rs1/localhost:3002"
    state: present

# Enable sharding on a few databases when creating the shard
- name: To remove a shard called 'rs1'
  community.mongodb.mongodb_shard:
    login_user: admin
    login_password: admin
    shard: rs1
    sharded_databases:
      - db1
      - db2
    state: present
a  
mongodb_shard:
    description: The name of the shard to create.
    returned: success
    type: str
sharded_enabled:
    description: Databases that have had sharding enabled during module execution.
    returned: success when sharding is enabled
    type: list
N)AnsibleModulemissing_required_lib)	to_native)r   mongodb_common_argument_spec
mongo_authPYMONGO_IMP_ERRpymongo_foundget_mongodb_clientcheck_srv_versionc                     d|v r|j                  d      d   }n|}| d   j                  j                  d|i      D ]  }|c S  y)zCheck if a shard exists.

    Args:
        client (cursor): Mongodb cursor on admin database.
        shard (str): shard to check.

    Returns:
        dict: when user exists, False otherwise.
    /r   config_idF)splitshardsfind)clientshardss      s/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/mongodb/plugins/modules/mongodb_shard.py
shard_findr      sT     e|KKQ!((--uaj9     c                 X    	 | d   j                  d|      }|S # t        $ r}|d }~ww xY w)NadminaddShardcommand	Exceptionr   r   shexceps       r   	shard_addr%      s;    G_$$Z7 I      	)$)c                 X    	 | d   j                  d|      }|S # t        $ r}|d }~ww xY w)Nr   removeShardr   r"   s       r   shard_remover)      s;    G_$$]E: I  r&   c                     g }| d   j                   j                  ddiddi      D ]  }|j                  |d           |S )z
    Returns the sharded databases
    Args:
        client (cursor): Mongodb cursor on admin database.
    Returns:
        a list of database names that are sharded
    r   partitionedTr      )	databasesr   append)r   sharded_databasesentrys      r   sharded_dbsr1      sS     !++00-1FPQ
S /  u./r   c                 <    d}| d   j                  d|      }|rd}|S )z
    Enables sharding on a database
    Args:
        client (cursor): Mongodb cursor on admin database.
    Returns:
        true on success, false on failure
    Fr   enableShardingT)r    )r   databaser   dbs       r   enable_database_shardingr6      s-     	A		 	 !18	<B	Hr   c                 Z    g }t        |       }|D ]  }||vs|j                  |        |S )z
    Return a list of databases that need to have sharding enabled
    sharded_databases - Provided by module
    cluster_sharded_databases - List of sharded dbs from the mongos
    )r1   r.   )r   r/   dbs_to_shardcluster_sharded_databasesr5   s        r   any_dbs_to_shardr:      sB     L +F 3 $..#$ r   c                     t               } | j                  t        ddd      t        dd      t        dd      t        dddd	dg
             t        | dddgg      }t        s |j                  t        d      t               |j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d   }	 t        |      }t        ||      }	 d   j                  d      d   |k7  r#|j                  dj                  |||             g }
|Bt        t!        ||      d         dk  r't#        |t$              rt'        |      }t)        ||      }
|j*                  r;|dk(  rd}t-        ||      rt/        |
      dkD  rd}n|d	k(  rzt-        ||      sd}nkd}nh|dk(  rAt-        ||      st1        ||       d}nd}t/        |
      dkD  r8|
D ]  }t3        ||        d}n"|d	k(  rt-        ||      rt5        ||       d}nd}|d"}t/        
      dkD  r|
|d#<    |j:                  d$i | y # t        $ r)}	|j                  dt        |	      z         Y d }	~	d }	~	ww xY w# t        $ rS}d}|d	k(  rd }|j                  d!j                  |      t        |      z  t7        j8                                Y d }~d }~ww xY w)%NstrFmongos)typerequireddefaultT)r>   r?   rawpresentabsent)r>   r?   r@   choices)mongos_processr   r/   state
login_userlogin_password)argument_specsupports_check_moderequired_togetherpymongo)msg	exception
login_host
login_portr   rF   r/   rE   z Unable to connect to MongoDB: %s)rM   r   serverStatusprocessz'Process running on {0}:{1} is not a {2}r      addremovezUnable to {0} shard: %s)changedr   sharded_enabled )r	   updatedictr   r   	fail_jsonr   r   paramsr   r
   r!   r   r    formatintr   
isinstancer<   listr:   
check_moder   lenr%   r6   r)   	traceback
format_exc	exit_json)rI   modulerO   rP   r   rF   r/   rE   r   r$   r8   rV   r5   eactionresults                   r   mainrj      s'   02MI-EE:y8U^J_`	   # (*:;<F 1)<#2 	 	4 |,J|,JMM'"EMM'"E&9:]]#34NT#F+FF+*x'?"">29=O!J!Q!QR\^hjx!yz(S1B661RST1U-VYZ-Z+S1$():$;!+F4EFL	!!&%0C4E4I"G("!&%0#G"G	!!&%0fe,"G#G|$q(* =0<="G("fe, /"G#G F <1$0 !Fvm  T?)EBRRSSTR  xHF6==fE	RST`i`t`t`vww	xs2   #I ;D2J 	J
!JJ
	K)A	K$$K)__main__)
__future__r   r   r   r>   __metaclass__DOCUMENTATIONEXAMPLESRETURNrc   ansible.module_utils.basicr   r   ansible.module_utils._textr   Iansible_collections.community.mongodb.plugins.module_utils.mongodb_commonr	   r
   r   r   r   r   r   r%   r)   r1   r6   r:   rj   __name__rX   r   r   <module>ru      s}    A @1f0d	
  J 0  &&Rj zF r   