
    Vh-R                     R   d dl mZmZmZ eZdZdZ	 d dlZd dl	m
Z
  G d dej                  j                  j                        ZdZd dlZd d
lmZ d Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z G d de      Z  G d de      Z!d Z"d Z#e$dk(  r e#        yy# e$ r d	ZY ^w xY w)    )absolute_importdivisionprint_functionaL  
module: consul
short_description: Add, modify & delete services within a Consul cluster
description:
  - Registers services and checks for an agent with a Consul cluster. A service is some process running on the agent node
    that should be advertised by Consul's discovery mechanism. It may optionally supply a check definition, a periodic service
    test to notify the Consul cluster of service's health.
  - Checks may also be registered per node, for example disk usage, or cpu usage and notify the health of the entire node
    to the cluster. Service level checks do not require a check name or ID as these are derived by Consul from the Service
    name and ID respectively by appending V(service:) Node level checks require a O(check_name) and optionally a O(check_id).
  - Currently, there is no complete way to retrieve the script, interval or TTL metadata for a registered check. Without this
    metadata it is not possible to tell if the data supplied with ansible represents a change to a check. As a result this
    does not attempt to determine changes and will always report a changed occurred. An API method is planned to supply this
    metadata so at that stage change management will be added.
  - See U(http://consul.io) for more details.
requirements:
  - python-consul
  - requests
author: "Steve Gargan (@sgargan)"
extends_documentation_fragment:
  - community.general.attributes
attributes:
  check_mode:
    support: none
  diff_mode:
    support: none
options:
  state:
    type: str
    description:
      - Register or deregister the Consul service, defaults to present.
    default: present
    choices: ['present', 'absent']
  service_name:
    type: str
    description:
      - Unique name for the service on a node, must be unique per node, required if registering a service. May be omitted
        if registering a node level check.
  service_id:
    type: str
    description:
      - The ID for the service, must be unique per node. If O(state=absent), defaults to the service name if supplied.
  host:
    type: str
    description:
      - Host of the Consul agent defaults to localhost.
    default: localhost
  port:
    type: int
    description:
      - The port on which the Consul agent is running.
    default: 8500
  scheme:
    type: str
    description:
      - The protocol scheme on which the Consul agent is running.
    default: http
  validate_certs:
    description:
      - Whether to verify the TLS certificate of the Consul agent.
    type: bool
    default: true
  notes:
    type: str
    description:
      - Notes to attach to check when registering it.
  service_port:
    type: int
    description:
      - The port on which the service is listening. Can optionally be supplied for registration of a service, that is if O(service_name)
        or O(service_id) is set.
  service_address:
    type: str
    description:
      - The address to advertise that the service will be listening on. This value will be passed as the C(address) parameter
        to Consul's C(/v1/agent/service/register) API method, so refer to the Consul API documentation for further details.
  tags:
    type: list
    elements: str
    description:
      - Tags that will be attached to the service registration.
  script:
    type: str
    description:
      - The script/command that will be run periodically to check the health of the service.
      - Requires O(interval) to be provided.
      - Mutually exclusive with O(ttl), O(tcp) and O(http).
  interval:
    type: str
    description:
      - The interval at which the service check will be run. This is a number with a V(s) or V(m) suffix to signify the units
        of seconds or minutes, for example V(15s) or V(1m). If no suffix is supplied V(s) will be used by default, for example
        V(10) will be V(10s).
      - Required if one of the parameters O(script), O(http), or O(tcp) is specified.
  check_id:
    type: str
    description:
      - An ID for the service check. If O(state=absent), defaults to O(check_name). Ignored if part of a service definition.
  check_name:
    type: str
    description:
      - Name for the service check. Required if standalone, ignored if part of service definition.
  check_node:
    description:
      - Node name.
    type: str
  check_host:
    description:
      - Host name.
    type: str
  ttl:
    type: str
    description:
      - Checks can be registered with a TTL instead of a O(script) and O(interval) this means that the service will check
        in with the agent before the TTL expires. If it does not the check will be considered failed. Required if registering
        a check and the script an interval are missing Similar to the interval this is a number with a V(s) or V(m) suffix
        to signify the units of seconds or minutes, for example V(15s) or V(1m). If no suffix is supplied V(s) will be used
        by default, for example V(10) will be V(10s).
      - Mutually exclusive with O(script), O(tcp) and O(http).
  tcp:
    type: str
    description:
      - Checks can be registered with a TCP port. This means that Consul will check if the connection attempt to that port
        is successful (that is, the port is currently accepting connections). The format is V(host:port), for example V(localhost:80).
      - Requires O(interval) to be provided.
      - Mutually exclusive with O(script), O(ttl) and O(http).
    version_added: '1.3.0'
  http:
    type: str
    description:
      - Checks can be registered with an HTTP endpoint. This means that Consul will check that the http endpoint returns a
        successful HTTP status.
      - Requires O(interval) to be provided.
      - Mutually exclusive with O(script), O(ttl) and O(tcp).
  timeout:
    type: str
    description:
      - A custom HTTP check timeout. The Consul default is 10 seconds. Similar to the interval this is a number with a V(s)
        or V(m) suffix to signify the units of seconds or minutes, for example V(15s) or V(1m). If no suffix is supplied V(s)
        will be used by default, for example V(10) will be V(10s).
  token:
    type: str
    description:
      - The token key identifying an ACL rule set. May be required to register services.
aV  
- name: Register nginx service with the local Consul agent
  community.general.consul:
    service_name: nginx
    service_port: 80

- name: Register nginx service with curl check
  community.general.consul:
    service_name: nginx
    service_port: 80
    script: curl http://localhost
    interval: 60s

- name: register nginx with a tcp check
  community.general.consul:
    service_name: nginx
    service_port: 80
    interval: 60s
    tcp: localhost:80

- name: Register nginx with an http check
  community.general.consul:
    service_name: nginx
    service_port: 80
    interval: 60s
    http: http://localhost:80/status

- name: Register external service nginx available at 10.1.5.23
  community.general.consul:
    service_name: nginx
    service_port: 80
    service_address: 10.1.5.23

- name: Register nginx with some service tags
  community.general.consul:
    service_name: nginx
    service_port: 80
    tags:
      - prod
      - webservers

- name: Remove nginx service
  community.general.consul:
    service_name: nginx
    state: absent

- name: Register celery worker service
  community.general.consul:
    service_name: celery-worker
    tags:
      - prod
      - worker

- name: Create a node level check to test disk usage
  community.general.consul:
    check_name: Disk usage
    check_id: disk_usage
    script: /opt/disk_usage.py
    interval: 5m

- name: Register an http check against a service that's already registered
  community.general.consul:
    check_name: nginx-check2
    check_id: nginx-check2
    service_id: nginx
    interval: 60s
    http: http://localhost:80/morestatus
N)ConnectionErrorc                       e Zd ZddZy)PatchedConsulAgentServiceNc                     i }|r||d<   | j                   j                  j                  t        j                  j
                  j                         d|z  |      S )Ntokenz/v1/agent/service/deregister/%sparams)agenthttpputconsulbaseCBbool)self
service_idr
   r   s       l/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/general/plugins/modules/consul.py
deregisterz$PatchedConsulAgentService.deregister   sQ    F"'w::??&&v{{~~':':'<'H:'U.4 ' 6 6    N)__name__
__module____qualname__r    r   r   r   r      s    	6r   r   TF)AnsibleModulec                 Z    | j                   d   }|dk(  rt        |        y t        |        y )Nstatepresent)r   addremove)moduler    s     r   register_with_consulr%      s&    MM'"E	Fvr   c                     t        |       }t        |       }|s|s| j                  d       |r |r|j                  |       t	        | |       y|rt        | |       yy)z> adds a service or a check depending on supplied configurationz2a name and port are required to register a servicemsgN)parse_checkparse_service	fail_json	add_checkadd_service)r$   checkservices      r   r"   r"     s]    EF#G5QRe$FG$	&%  
r   c                     | j                   d   xs | j                   d   }| j                   d   xs | j                   d   }|rt        | |       yt        | |       y)z removes a service or a check r   service_namecheck_id
check_nameN)r   remove_serviceremove_check)r$   r   r2   s      r   r#   r#     sQ    |,Mn0MJ}}Z(GFMM,,GHvz*VX&r   c                 z   |j                   s|j                  s| j                  d       t        |       }|j	                  |       | j                  d|j                  |j                   |j                  |j                  |j                  |j                  |j                  |j                  |j                  
       y)z registers a check with the given agent. currently there is no way
    retrieve the full metadata of an existing check  through the consul api.
    Without this we can't compare to the supplied check and so we must assume
    a change. zNa check name is required for a node level check, one not attached to a servicer'   T)
changedr2   r3   scriptintervalttltcpr   timeoutr   N)namer   r+   get_consul_apiregister	exit_jsonr2   r8   r9   r:   r;   r   r<   )r$   r.   
consul_apis      r   r,   r,     s    
 ::e..mn'J	NN:
T#nn %

!LL#nn**"]] % 0 0  	2r   c                     t        |       }||j                  j                         v r8|j                  j                  j	                  |       | j                  d|       | j                  d|       y)z removes a check using its id Tr7   idFN)r>   r   checksr.   r   r@   )r$   r2   rA   s      r   r5   r5   2  sc    'J:##**,,))(3(3
Ux0r   c                    |}d}t        |       }t        ||j                        }|j                         s|r||k(  s-|j	                  |       t        ||j                        }|r|}d}| j                  ||j                  |j                  |j                  |j                         D cg c]  }|j                          c}|j                         yc c}w )z, registers a service with the current agent FT)r7   r   r1   service_portrE   tagsN)r>   get_service_by_id_or_namerD   
has_checksr?   r@   r=   portrE   to_dictrH   )r$   r/   resultr7   rA   existing
registeredr.   s           r   r-   r-   =  s    FG'J(WZZ@H 88w3F$.z7::F
FG
W &		"(++"(++:A..:JKU]]_K ++  ' Ls   )Cc                     t        |       }t        ||      }|rG|j                  j                  j	                  || j
                  d          | j                  d|       | j                  d|       y)z@ deregister a service from the given agent using its service id r
   )r
   TrC   FN)r>   rI   r   r/   r   r   r@   )r$   r   rA   r/   s       r   r4   r4   X  si    'J'
J?G  ++JfmmG>T+U*5
Uz2r   c                     t        j                  | j                  d   | j                  d   | j                  d   | j                  d   | j                  d         }t        |      |j                  _        |S )NhostrK   schemevalidate_certsr
   )rR   rK   rS   verifyr
   )r   Consulr   r   r   r/   )r$   consulClients     r   r>   r>   c  sg    ==fmmF&;&,mmF&;(.h(?(.6F(G'-}}W'=	?L
 ";<!HLr   c                     | j                   j                         j                         D ]  \  }}||d   |d   fv st        |      c S  y)z@ iterate the registered services and find one with the given id IDService)loadedN)r   servicesitemsConsulService)rA   service_id_or_namedummyr/   s       r   rI   rI   m  sN    $**335;;= 1w'$-1C!DD 001r   c                      j                   d   st         fddD              rt         j                   d    j                   d    j                   d    j                   d    j                   d    j                   d    j                   d	    j                   d
    j                   d    j                   d    j                   d    j                   d         S y )Nr2   c              3   @   K   | ]  }j                   |   d u  y wr   r   ).0pr$   s     r   	<genexpr>zparse_check.<locals>.<genexpr>u  s     'oa(8(D'o   r8   r:   r;   r   r3   
check_node
check_hostr8   r9   r:   notesr;   r   r<   r   )r   anyConsulCheckr$   s   `r   r)   r)   t  s    }}Z C'oNn'o$oMM*%MM,'MM,'MM,'MM(#MM*%MM% MM'"MM% MM&!MM)$MM,'
 	
 %pr   c                     t        | j                  d   | j                  d   | j                  d   | j                  d   | j                  d         S )Nr   r1   service_addressrG   rH   )r^   r   rm   s    r   r*   r*     sL    l#n%'(n%f r   c                   B    e Zd Z	 	 d
dZd Zd Zd Zd Zd Zd Z	d	 Z
y)r^   Nc                     |x| _         | _        |r|| _         || _        || _        || _        g | _        |r)|d   | _         |d   | _        |d   | _        |d   | _        y y )NrY   rZ   PortTags)rD   r=   addressrK   rH   _checks)r   r   r=   rt   rK   rH   r[   s          r   __init__zConsulService.__init__  sk    ""$) DG		TlDGy)DIvDIvDI	 r   c                 L   i }| j                   r| j                   |d<   t        | j                        dkD  r| j                  d   j                  |d<    |j                  j
                  j                  | j                  f| j                  | j                  | j                  d| y )NrK   r   r.   )r   rt   rH   )rK   lenru   r.   r   r/   r?   r=   rD   rt   rH   )r   rA   optionals      r   r?   zConsulService.register  s    99#yyHVt||q  $Q 5 5HW)
  ))II	wwLL		
 	r   c                 :    | j                   j                  |       y r   )ru   append)r   r.   s     r   r,   zConsulService.add_check  s    E"r   c                     | j                   S r   )ru   r   s    r   rE   zConsulService.checks  s    ||r   c                 2    t        | j                        dkD  S )Nr   )rx   ru   r}   s    r   rJ   zConsulService.has_checks  s    4<< 1$$r   c                    t        || j                        xrj | j                  |j                  k(  xrO | j                  |j                  k(  xr4 | j                  |j                  k(  xr | j
                  |j
                  k(  S r   )
isinstance	__class__rD   r=   rK   rH   r   others     r   __eq__zConsulService.__eq__  sm    5$..1 (588#(		UZZ'( 		UZZ'( 		UZZ'		)r   c                 &    | j                  |       S r   r   r   s     r   __ne__zConsulService.__ne__      ;;u%%%r   c                 D   | j                   | j                  d}| j                  r| j                  |d<   | j                  r't	        | j                        dkD  r| j                  |d<   t	        | j
                        dkD  r | j
                  d   j                         |d<   |S )N)rD   r=   rK   r   rH   r.   )rD   r=   rK   rH   rx   ru   rL   r   datas     r   rL   zConsulService.to_dict  s{    ggtyy19999DL99TYY!+99DLt||q  LLO335DMr   )NNNNN)r   r   r   rv   r?   r,   rE   rJ   r   r   rL   r   r   r   r^   r^     s0    FH#'' #%)&r   r^   c                   >    e Zd Z	 	 d	dZd Zd Zd Zd Zd Zd
dZ	y)rl   Nc                    |x| _         | _        |r|| _         || _        || _        || _        || _        | j                  d|      | _        | j                  d|      | _        || _	        |	| _
        |
| _        | j                  d|      | _        d | _        |r/t        j                  j                  || j                        | _        |r.t        j                  j                  | j                        | _        |
r:t        j                  j                  |
| j                  | j                        | _        |	rd}t!        j"                  ||	      }|st%        d      t        j                  j                  |j'                  d      j)                  d      t+        |j'                  d            | j                        | _        y y )	Nr9   r:   r<   z"(?P<host>.*):(?P<port>(?:[0-9]+))$z%tcp check must be in host:port formatrR   z[]rK   )r2   r=   r   rj   noderR   validate_durationr9   r:   r8   r;   r   r<   r.   r   Checkrematch	Exceptiongroupstripint)r   r2   r=   r   rR   r8   r9   r:   rj   r;   r   r<   r   regexr   s                  r   rv   zConsulCheck.__init__  s_   $((	$DM$
		..z8D))%5	--iA
,,VT]]CDJ))$((3DJ**4MDJ9EHHUC(E GHH))%++f*=*C*CD*I3u{{[aObKceierersDJ r   c                 ^    r)g d}t        fd|D              sdj                        S )N)nsusmssmhc              3   @   K   | ]  }j                  |        y wr   )endswith)rc   suffixdurations     r   re   z0ConsulCheck.validate_duration.<locals>.<genexpr>  s     NVx((0Nrf   z{0}s)rk   format)r   r=   r   duration_unitss     ` r   r   zConsulCheck.validate_duration  s,    >NN~NN!==2r   c                     |j                   j                  j                  | j                  | j                  | j
                  | j                  | j                         y )N)r2   r   rj   r.   )r   r.   r?   r=   r2   r   rj   )r   rA   s     r   r?   zConsulCheck.register  sD    ''		DMMVZVeVe.2jj.2jj 	( 	:r   c                 <   t        || j                        xr | j                  |j                  k(  xrj | j                  |j                  k(  xrO | j                  |j                  k(  xr4 | j
                  |j
                  k(  xr | j                  |j                  k(  S r   )r   r   r2   r   r=   r8   r9   r   s     r   r   zConsulCheck.__eq__  s    5$..1 0/05#3#330 		UZZ'0 u||+	0
 /	1r   c                 &    | j                  |       S r   r   r   s     r   r   zConsulCheck.__ne__
  r   r   c                    i }| j                  |dd       | j                  |dd       | j                  |d       | j                  |d       | j                  |d       | j                  |d	       | j                  |d
       | j                  |d       | j                  |d       | j                  |d       | j                  |d       | j                  |d       |S )NrD   r2   )attrr=   r3   r8   r   rj   rR   r9   r:   r;   r   r<   r   )_addr   s     r   rL   zConsulCheck.to_dict  s    		$:	.		$\	2		$!		$		$ 		$		$
#		$		$		$		$	"		$%r   c                 J    	 ||}t        | |      ||<   y # t        $ r Y y w xY wr   )getattrr   )r   r   keyr   s       r   r   zConsulCheck._add  s3    	|d+DI 		s    	"")
N	localhostNNNNNNNNr   )
r   r   r   rv   r   r?   r   r   rL   r   r   r   r   rl   rl     s-    7Bqu#tJ:
1& r   rl   c                 6    t         s| j                  d       y y )Nzhpython-consul required for this module. see https://python-consul.readthedocs.io/en/latest/#installationr'   )python_consul_installedr+   rm   s    r   test_dependenciesr   &  s"    "  H  	I #r   c                  
   t        t        d2i dt        d      dt        dd      dt        d	      d
t        dd      dt               dt               dt               dt               dt               dt               dt               dt               dt        d      dt        d      dt        dddg      dt        d      dt        d      dt        d      d	t        d      d t        d      d!t        d"d#      d$t        d%      d&gdddgfddg d'dfgdddd(d)*      } | j                  t        |        d   dk(  r&t	        fd+d,D              r| j                  d-.       	 t        |        y # t        $ r  t        $ r4}| j                  d/d   d0d   d1t        |      .       Y d }~y d }~wt        $ r%}| j                  t        |      .       Y d }~y d }~ww xY w)3NrR   r   )defaultrK   i4!  r   )r   typerS   r   rT   Tr   r2   r3   rh   ri   rj   r8   r   r1   ro   str)r   rG   r    r!   absent)r   choicesr9   r:   r;   r<   rH   list)r   elementsr
   )no_logrg   )r   r1   r2   r3   )r8   r   r;   F)argument_specmutually_exclusiverequired_ifrequired_bysupports_check_modec              3   (   K   | ]	  }|     y wr   r   )rc   xrd   s     r   re   zmain.<locals>.<genexpr>V  s     %aqad%as   )r8   r:   r;   r   r9   zpThe use of parameters 'script', 'ttl', 'tcp', 'http', 'interval' along with 'state=absent' is no longer allowed.r'   z%Could not connect to consul agent at :z, error was r   )r   dictr   r   rk   r+   r%   
SystemExitr   r   r   )r$   erd   s     @r   mainr   +  sS    
k*
d/
 '
  6:	

 V
 v
 v
 v
 &
 6
 v
 
 !e,
 5)
 y9h2GH
  u%!
" % #
$ % %
& 5!'
( e$)
* 6E2+
, d#-
2 -
 i.!12h XZ^_

 !

 "K&FN 	AfzX#%a4`%a"a C 	 	
%V$  z[\]c[dfghnfoqtuvqwxyy %SV$$%s$   F H"*GHG==H__main__)%
__future__r   r   r   r   __metaclass__DOCUMENTATIONEXAMPLESr   requests.exceptionsr   rV   AgentrZ   r   r   ImportErrorr   ansible.module_utils.basicr   r%   r"   r#   r,   r5   r-   r4   r>   rI   r)   r*   objectr^   rl   r   r   r   r   r   r   <module>r      s    A @PdCJ$36FMM$7$7$?$? 6 # 
 4! '2.1'631
$<F <~T& TnI
7%t zF i  $#$s   5B B&%B&