
    VhU                        d dl mZmZmZ eZdZdZdZd dl	m
Z
 d dlmZmZ d dlZd dlZd dlZd dlZd dlmZ d d	lmZ d d
lmZ d dlmZ da G d de      Z G d de      Z G d de      Z G d de      Zd Z e!dk(  r e         yy)    )absolute_importdivisionprint_functiona  
module: redhat_subscription
short_description: Manage registration and subscriptions to RHSM using C(subscription-manager)
description:
  - Manage registration and subscription to the Red Hat Subscription Management entitlement platform using the C(subscription-manager)
    command, registering using D-Bus if possible.
author: "Barnaby Court (@barnabycourt)"
notes:
  - 'The module tries to use the D-Bus C(rhsm) service (part of C(subscription-manager)) to register, starting from community.general
    6.5.0: this is done so credentials (username, password, activation keys) can be passed to C(rhsm) in a secure way. C(subscription-manager)
    itself gets credentials only as arguments of command line parameters, which is I(not) secure, as they can be easily stolen
    by checking the process listing on the system. Due to limitations of the D-Bus interface of C(rhsm), the module will I(not)
    use D-Bus for registration when trying either to register using O(token), or when specifying O(environment), or when the
    system is old (typically RHEL 7 older than 7.4, RHEL 6, and older).'
  - In order to register a system, subscription-manager requires either a username and password, or an activationkey and an
    Organization ID.
  - Since 2.5 values for O(server_hostname), O(server_insecure), O(rhsm_baseurl), O(server_proxy_hostname), O(server_proxy_port),
    O(server_proxy_user) and O(server_proxy_password) are no longer taken from the C(/etc/rhsm/rhsm.conf) config file and
    default to V(null).
  - It is possible to interact with C(subscription-manager) only as root, so root permissions are required to successfully
    run this module.
  - Since community.general 6.5.0, credentials (that is, O(username) and O(password), O(activationkey), or O(token)) are needed
    only in case the the system is not registered, or O(force_register) is specified; this makes it possible to use the module
    to tweak an already registered system, for example attaching pools to it (using O(pool_ids)), and modifying the C(syspurpose)
    attributes (using O(syspurpose)).
requirements:
  - subscription-manager
  - Optionally the C(dbus) Python library; this is usually included in the OS as it is used by C(subscription-manager).
extends_documentation_fragment:
  - community.general.attributes
attributes:
  check_mode:
    support: none
  diff_mode:
    support: none
options:
  state:
    description:
      - Whether to register and subscribe (V(present)), or unregister (V(absent)) a system.
    choices: ["present", "absent"]
    default: "present"
    type: str
  username:
    description:
      - Access.redhat.com or Red Hat Satellite or Katello username.
    type: str
  password:
    description:
      - Access.redhat.com or Red Hat Satellite or Katello password.
    type: str
  token:
    description:
      - Sso.redhat.com API access token.
    type: str
    version_added: 6.3.0
  server_hostname:
    description:
      - Specify an alternative Red Hat Subscription Management or Red Hat Satellite or Katello server.
    type: str
  server_insecure:
    description:
      - Enable or disable https server certificate verification when connecting to O(server_hostname).
    type: str
  server_prefix:
    description:
      - Specify the prefix when registering to the Red Hat Subscription Management or Red Hat Satellite or Katello server.
    type: str
    version_added: 3.3.0
  server_port:
    description:
      - Specify the port when registering to the Red Hat Subscription Management or Red Hat Satellite or Katello server.
    type: str
    version_added: 3.3.0
  rhsm_baseurl:
    description:
      - Specify CDN baseurl.
    type: str
  rhsm_repo_ca_cert:
    description:
      - Specify an alternative location for a CA certificate for CDN.
    type: str
  server_proxy_hostname:
    description:
      - Specify an HTTP proxy hostname.
    type: str
  server_proxy_scheme:
    description:
      - Specify an HTTP proxy scheme, for example V(http) or V(https).
    type: str
    version_added: 6.2.0
  server_proxy_port:
    description:
      - Specify an HTTP proxy port.
    type: str
  server_proxy_user:
    description:
      - Specify a user for HTTP proxy with basic authentication.
    type: str
  server_proxy_password:
    description:
      - Specify a password for HTTP proxy with basic authentication.
    type: str
  auto_attach:
    description:
      - Upon successful registration, auto-consume available subscriptions.
      - Please note that the alias O(ignore:autosubscribe) was removed in community.general 9.0.0.
    type: bool
  activationkey:
    description:
      - Supply an activation key for use with registration.
    type: str
  org_id:
    description:
      - Organization ID to use in conjunction with activationkey.
    type: str
  environment:
    description:
      - Register with a specific environment in the destination org. Used with Red Hat Satellite or Katello.
    type: str
  pool_ids:
    description:
      - Specify subscription pool IDs to consume.
      - 'A pool ID may be specified as a C(string) - just the pool ID (for example
        V(0123456789abcdef0123456789abcdef)), or as a C(dict) with the pool ID as the key, and a quantity as the value (for
        example V(0123456789abcdef0123456789abcdef: 2). If the quantity is provided, it is used to consume multiple entitlements
        from a pool (the pool must support this).'
    default: []
    type: list
    elements: raw
  consumer_type:
    description:
      - The type of unit to register, defaults to system.
    type: str
  consumer_name:
    description:
      - Name of the system to register, defaults to the hostname.
    type: str
  consumer_id:
    description:
      - References an existing consumer ID to resume using a previous registration for this system. If the system's identity
        certificate is lost or corrupted, this option allows it to resume using its previous identity and subscriptions. The
        default is to not specify a consumer ID so a new ID is created.
    type: str
  force_register:
    description:
      - Register the system even if it is already registered.
    type: bool
    default: false
  release:
    description:
      - Set a release version.
    type: str
  syspurpose:
    description:
      - Set syspurpose attributes in file C(/etc/rhsm/syspurpose/syspurpose.json) and synchronize these attributes with RHSM
        server. Syspurpose attributes help attach the most appropriate subscriptions to the system automatically. When C(syspurpose.json)
        file already contains some attributes, then new attributes overwrite existing attributes. When some attribute is not
        listed in the new list of attributes, the existing attribute will be removed from C(syspurpose.json) file. Unknown
        attributes are ignored.
    type: dict
    suboptions:
      usage:
        description: Syspurpose attribute usage.
        type: str
      role:
        description: Syspurpose attribute role.
        type: str
      service_level_agreement:
        description: Syspurpose attribute service_level_agreement.
        type: str
      addons:
        description: Syspurpose attribute addons.
        type: list
        elements: str
      sync:
        description:
          - When this option is V(true), then syspurpose attributes are synchronized with RHSM server immediately. When this
            option is V(false), then syspurpose attributes will be synchronized with RHSM server by rhsmcertd daemon.
        type: bool
        default: false
a/  
- name: Register as user (joe_user) with password (somepass) and auto-subscribe to available content.
  community.general.redhat_subscription:
    state: present
    username: joe_user
    password: somepass
    auto_attach: true

- name: Same as above but subscribe to a specific pool by ID.
  community.general.redhat_subscription:
    state: present
    username: joe_user
    password: somepass
    pool_ids: 0123456789abcdef0123456789abcdef

- name: Register and subscribe to multiple pools.
  community.general.redhat_subscription:
    state: present
    username: joe_user
    password: somepass
    pool_ids:
      - 0123456789abcdef0123456789abcdef
      - 1123456789abcdef0123456789abcdef

- name: Same as above but consume multiple entitlements.
  community.general.redhat_subscription:
    state: present
    username: joe_user
    password: somepass
    pool_ids:
      - 0123456789abcdef0123456789abcdef: 2
      - 1123456789abcdef0123456789abcdef: 4

- name: Register and pull existing system data.
  community.general.redhat_subscription:
    state: present
    username: joe_user
    password: somepass
    consumer_id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

- name: Register as user credentials into given environment (against Red Hat Satellite or Katello), and auto-subscribe.
  community.general.redhat_subscription:
    state: present
    username: joe_user
    password: somepass
    environment: Library
    auto_attach: true

- name: Register as user (joe_user) with password (somepass) and a specific release
  community.general.redhat_subscription:
    state: present
    username: joe_user
    password: somepass
    release: 7.4

- name: Register as user (joe_user) with password (somepass), set syspurpose attributes and synchronize them with server
  community.general.redhat_subscription:
    state: present
    username: joe_user
    password: somepass
    auto_attach: true
    syspurpose:
      usage: "Production"
      role: "Red Hat Enterprise Server"
      service_level_agreement: "Premium"
      addons:
        - addon1
        - addon2
      sync: true
z
subscribed_pool_ids:
  description: List of pool IDs to which system is now subscribed.
  returned: success
  type: dict
  sample: {"8a85f9815ab905d3015ab928c7005de4": "1"}
)isfile)getuidunlinkN)AnsibleModule)	to_native)configparser)distroc                   x    e Zd ZdZd ZddZd Zd Zed        Z	d Z
d Zd	 Zd
 Zd ZddZd Zd Zd Zd Zy)Rhsmz/etc/yum.repos.d/redhat.repoc                     || _         y N)module)selfr   s     y/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/general/plugins/modules/redhat_subscription.py__init__zRhsm.__init__&  s	        c                    d|z  }t        |      rt        j                         \  }}t        j                  ||       t        j                         }|j                  |g       |r|j                  ddd       n|j                  ddd       t        |d      5 }|j                  |       d d d        | j                  j                  ||       y y # 1 sw Y   'xY w)Nz/etc/yum/pluginconf.d/%s.confmainenabled10zw+)r   tempfilemkstempshutilcopy2r   ConfigParserreadsetopenwriter   atomic_move)r   pluginr   plugin_conftmpfdtmpfilecfgfds           r   update_plugin_confzRhsm.update_plugin_conf)  s    5>+%--/NE7LLg.++-CHHgY	3/	3/gt$ 		"KK##G[9  s   CCc                     t        | j                        rt        | j                         | j                  dd       | j                  dd       y)z
            Enable the system to receive updates from subscription-manager.
            This involves updating affected yum plugins and removing any
            conflicting yum repositories.
        	rhnpluginFsubscription-managerTN)r   REDHAT_REPOr   r+   r   s    r   enablezRhsm.enable;  sA     $""#4##$U3 6=r   c           	      X   t         dg}g }t        |j                               D ]G  \  }}t        j                  d|      s| |j                  d|j                  ddd      d|       I t        |      d	k(  ry|j                  |       | j                  j                  |d
       y)z
            Configure the system as directed for registration with RHSM
            Raises:
              * Exception - if error occurs while running command
        configz^(server|rhsm)_Nz--_.   =r   Tcheck_rc)
SUBMAN_CMDsorteditemsresearchappendreplacelenextendr   run_command)r   kwargsargsoptionskvs         r   	configurezRhsm.configureG  s     H%
 6<<>* 	HDAqyy+Q/AMAIIc3,BAFG	H w<1Gt4r   c                 b    t         dg}| j                  j                  |d      \  }}}|dk(  ryy)z
            Determine whether the current system
            Returns:
              * Boolean - whether the current system is currently registered to
                          RHSM.
        identityFr8   r   Tr:   r   rC   r   rE   rcstdoutstderrs        r   is_registeredzRhsm.is_registeredb  s;     J'![[44TE4JFF7r   c                     d
dt        j                         }t        fdt        j                         D              }|dk(  ry|d   dk(  xr |d   dk\  xs |d   d	k\  S )z
        Checks whether subscription-manager has a D-Bus interface.

        :returns: bool -- whether subscription-manager has a D-Bus interface.
        r   c                 <    	 t        |       S # t        $ r |cY S w xY wr   int
ValueErrorsdefaults     r   str2intz)Rhsm._has_dbus_interface.<locals>.str2inty  $    1v    
 c              3   .   K   | ]  } |        y wr    .0prZ   s     r   	<genexpr>z+Rhsm._has_dbus_interface.<locals>.<genexpr>  s     JawqzJ   fedoraT   r6         r   )r   idtupleversion_parts)r   	distro_iddistro_versionrZ   s      @r   _has_dbus_interfacezRhsm._has_dbus_interfacer  sp    	 IIK	J63G3G3IJJ   q!Q&A>!+<+A #1"	#r   c                    	 ddl }	 |j	                         }|j
                  j                  ddd      }|j                  |       |j                          | j                  j                  d	       y
# t        $ r | j                  j                  d       Y yw xY w# |j                  j                  $ r(}| j                  j                  d|z         Y d}~yd}~ww xY w)z
        Checks whether it is possible to connect to the system D-Bus bus.

        :returns: bool -- whether it is possible to connect to the system D-Bus bus.
        r   Nz.dbus Python module not available, will use CLIF/zcom.exampletestz7Failed to connect to system D-Bus bus, will use CLI: %sz#Verified system D-Bus bus as usableT)dbusImportErrorr   debug	SystemBuslowlevelSignalMessagesend_messageflush
exceptionsDBusException)r   rr   busmsges        r   _can_connect_to_dbuszRhsm._can_connect_to_dbus  s    	 
	.."C----c=&ICS!IIK 	?@  	KKNO	 ,, 	KKWZ[[\	s)   A1 AB 1$BBC4CCc                     |s?|s=| j                         r-| j                         r| j                  ||||||||	|
|||       y| j                  ||||||||	|
|||       y)z
            Register the current system to the provided RHSM or Red Hat Satellite
            or Katello server

            Raises:
              * Exception - if any error occurs during the registration
        N)rn   r   _register_using_dbus_register_using_cli)r   was_registeredusernamepasswordtokenauto_attachactivationkeyorg_idconsumer_typeconsumer_nameconsumer_idforce_registerenvironmentreleases                 r   registerzRhsm.register  sy     kd.F.F.H$$&%%nh+&3V]&3[&4k7L   8UK!.!.!/g	Gr   c                 N   t         dg}|
r|j                  dg       |r|j                  d|g       |r|j                  d       |r|j                  d|g       |r|j                  d|g       |	r|j                  d|	g       |r|j                  d|g       |r|j                  d	|g       n@|r|j                  d
|g       n*|r|j                  d|g       |r|j                  d|g       |r|j                  d|g       | j                  j	                  |dd      \  }}}y)z
            Register using the 'subscription-manager' command

            Raises:
              * Exception - if error occurs while running command
        r   z--forcez--orgz--auto-attachz--typez--namez--consumeridz--environmentz--activationkeyz--tokenz
--usernamez
--passwordz	--releaseTFr9   expand_user_and_varsN)r:   rB   r?   r   rC   )r   r   r   r   r   r   r   r   r   r   r   r   r   rE   rN   rP   rO   s                    r   r   zRhsm._register_using_cli  s    J' KK$KK&)*KK(KK=12KK=12KK56KK+67KK*M:;KKE*+\845\845KKg./![[44TD_d4eFFr   c           	      r  !"#$ ddl }d}d}d5d$t        j                         !t        j                         #t	        $fd#D              "!dk(  s"d   dk\  r"g d	}| j
                  j                  |d
d       d}!dk(  r*"d   dk(  r"d   dk\  s"d   dk(  r"d   dk\  s"d   dkD  rd
}d}|r!"fd} |       }n!"#fd} |       }|
r|s|r| j                          i }|r!"fd}d} |       rd}|||<   |r||d<   |	r|	|d<   |r!"#fd}d} |       rd}|||<   |
r	|r|rd
|d<   |rd|d<   |j                  |dd       }i }|j                  |dd       }|j                         }|j                  d!d"      }|j                  |d#$      }	 | j
                  j                  d%       |j                  j                  |      }	 |r!||g|||f}|j                  d!d&d'd(d)||*       n$|xs d+|||||f}|j                  d!d&d'd,d-||*       | j
                  j                  d/       |j)                  |d#$       | j
                  j                  t*        d0gd
d       |r't*        d1d2g}| j
                  j                  |d
d       |r)t*        d3d4|g}| j
                  j                  |d
d       yy# |j                   j"                  $ r/} | j%                         d.k(  r| j'                         s  Y d} ~ d} ~ ww xY w# | j
                  j                  d/       |j)                  |d#$       w xY w)6z
            Register using D-Bus (connecting to the rhsm service)

            Raises:
              * Exception - if error occurs during the D-Bus communication
        r   NCiX  c                 <    	 t        |       S # t        $ r |cY S w xY wr   rT   rW   s     r   rZ   z*Rhsm._register_using_dbus.<locals>.str2int  r[   r\   c              3   .   K   | ]  } |        y wr   r^   r_   s     r   rb   z,Rhsm._register_using_dbus.<locals>.<genexpr>	  s     HawqzHrc   rd   re   )	systemctlstoprhsmTFr   rhelrg   r6   	      c                  4     dk(  r	d   dk\  ryd   dk\  ryy)Nrd   r   )   T
   Fr^   rl   rm   s   r   +supports_enable_content_for_activation_keyszNRhsm._register_using_dbus.<locals>.supports_enable_content_for_activation_keys(  s-    (^A->"-D!!$*r   c                       dk(  ry dk(  rd   dk(  rd   dk\  sd   dk\  ry d	k(  r!d   dk(  rd   dk\  sd   d
k(  sd   dk\  ryyNrd   Tr   r   rg   r6      r   centos Fr^   rl   rm   distro_version_partss   r   'supports_enable_content_for_credentialszJRhsm._register_using_dbus.<locals>.supports_enable_content_for_credentials2       (&#A&!+q0AQ0F%a(A-
 (#A&!+&q)Q.2Fq2IR2O%a(A- r   c                  j     dk(  ry dk(  rd   dk(  rd   dk\  sd   dk\  ry d	k(  r	d   dk\  ryy
)Nrd   Tr   r   r   r6   r   r   r   Fr^   r   s   r   supports_option_consumer_typez@Rhsm._register_using_dbus.<locals>.supports_option_consumer_typeT  s_     (&#A&!+q0AQ0F%a(B. (^A->!-C r   typer   name
consumeridc                       dk(  ry dk(  rd   dk(  rd   dk\  sd   dk\  ry d	k(  r!d   dk(  rd   dk\  sd   d
k(  sd   dk\  ryyr   r^   r   s   r   supports_option_environmentsz?Rhsm._register_using_dbus.<locals>.supports_option_environmentst  r   r   r   environmentsforcer   enable_contentsv)	signaturevariant_levelzcom.redhat.RHSM1z /com/redhat/RHSM1/RegisterServerzcom.redhat.RHSM1.RegisterServer)dbus_interfacezConnecting to the private DBusz/com/redhat/RHSM1/Registerzcom.redhat.RHSM1.RegisterRegisterWithActivationKeyszsasa{sv}a{sv}s)timeoutr   Registerzsssa{sv}a{sv}sz"org.freedesktop.DBus.Error.NoReplyz#Shutting down private DBus instancerefreshattachz--autor   z--setrh   )rr   r   ri   rk   rj   r   rC   
unregister
Dictionaryru   
get_objectStartrt   
connection
Connectioncall_blockingrz   r{   get_dbus_namerQ   Stopr:   )%r   r   r   r   r   r   r   r   r   r   r   r   r   rr   SUBSCRIPTION_MANAGER_LOCALEREGISTRATION_TIMEOUTcmddbus_force_option_worksdbus_has_enable_content_optionr   r   register_optsr   consumer_type_keyr   environment_keyconnection_optsr|   register_serveraddressprivate_busrE   r~   rl   rm   r   rZ   s%                                    @@@@r   r   zRhsm._register_using_dbus  s    	&)#  #	 IIK	%335H3GHH  N1$5$:/CKK##C$U#S #(Q1$):a)?Q1$):a)?A"&*#
 */& .Y-Z*, .U-V*"9nOO& !',.$3!/<M+,$1M&!*5M,'
. ,O+-"0-8M/*5.%)M'").1M*+UVW///TYZ/[nn..);)KM!'''< ( 

:	KK>?//44W=K- &%'3D  --*434( 4 .  "  %'3D  --*43"( 4 . , KKCD  +@ !  	Y 7)-E 	  	K (3DKK##D4e#T 	7G<DKK##D4e#T ; ??00  ??$(LL--/	 0	 KKCD  +@ ! s1   6L AJ; ;L%K>9L >LL 0L6Nc                     g }||r|D cg c]  }d|z  	 }}|dg}|r,t         dg|z   }| j                  j                  |d      \  }}}|S c c}w )a  
            Unsubscribe a system from subscribed channels
            Args:
              serials(list or None): list of serials to unsubscribe. If
                                     serials is none or an empty list, then
                                     all subscribed channels will be removed.
            Raises:
              * Exception - if error occurs while running command
        z--serial=%sz--allremoveTr8   rL   )r   serialsr<   rX   rE   rN   rP   rO   s           r   unsubscribezRhsm.unsubscribe  sq     70781]Q&8E8?IE)E1D!%!8!8!8!MB 9s   Ac                     t         dg}| j                  j                  |d      \  }}}| j                  dd       | j                  dd       y)z
            Unregister a currently registered system
            Raises:
              * Exception - if error occurs while running command
        r   Tr8   r-   Fr.   N)r:   r   rC   r+   )r   rE   rN   rP   rO   s        r   r   zRhsm.unregister  sO     L)![[44TD4IFFU3 6>r   c                    t        | j                        }|D cg c]  }|j                          }}t        |j	                               D ]r  \  }}||v rJt
        dd|g}||j                  dt        |      g       | j                  j                  |d      \  }}	}
T| j                  j                  d|z         t |S c c}w )z:
        Try to subscribe to the list of pool IDs
        r   z--poolz
--quantityTr8   z*Pool ID: %s not in list of available poolsr}   )
	RhsmPoolsr   get_pool_idr;   r<   r:   rB   r
   rC   	fail_json)r   pool_idsavailable_poolsra   available_pool_idspool_idquantityrE   rN   rP   rO   s              r   subscribe_by_pool_idszRhsm.subscribe_by_pool_ids  s     $DKK07FG!ammoGG!'(8!9 	bGX,,"Hh@'KKy/B CD%)[[%<%<TD%<%Q"FF%%*VY`*`%a	b  Hs   Cc                    d}t        | j                  d      }i }g }|D ]]  }|j                         }|j                         }|||<   |j	                  |d      }	|	=|	|k7  sC|j                  |j                         _ | j                  |      }
i }t        |j                               D ]+  \  }}	|j	                  |d      }|	|dk(  s|	d d|fvs'|	||<   - | j                  |       |s|
rd}|t        |j                               |
dS )NFT)consumedr   )r   )changedsubscribed_pool_idsunsubscribed_serials)r   r   r   get_quantity_usedgetr?   Serialr   r;   r<   r   listkeys)r   r   r   consumed_poolsexisting_poolsserials_to_removera   r   quantity_usedr   r   missing_poolss               r    update_subscriptions_by_pool_idsz%Rhsm.update_subscriptions_by_pool_ids  s1   "4;;> 	3AmmoG//1M&3N7#||GQ/H#M(A!((2	3 ""+<"=!'(8!9 	2GX*..w:MMQ$6(4QRTaJb:b)1g&	2
 	""=1GG"4@R@R@T;U(/1 	1r   c                 V    t         dg}| j                  j                  |d      \  }}}y)zF
        Try to synchronize syspurpose attributes with server
        statusFr8   NrL   rM   s        r   sync_syspurposezRhsm.sync_syspurpose=  s.     H%![[44TE4JFFr   )Tr   )__name__
__module____qualname__r/   r   r+   r1   rI   propertyrQ   rn   r   r   r   r   r   r   r   r   r   r^   r   r   r   r   "  sh    0K:$
>56  #0:G4.f`zUx*	?$1<Kr   r   c                   .    e Zd ZdZd Zd Zd Zd Zd Zy)RhsmPoolzD
        Convenience class for housing subscription information
    c                 \    || _         |j                         D ]  \  }}t        | ||        y r   )r   r<   setattr)r   r   rD   rG   rH   s        r   r   zRhsmPool.__init__J  s.    LLN 	 DAqD!Q	 r   c                 6    t        | j                  d            S )N_name)str__getattribute__r0   s    r   __str__zRhsmPool.__str__O  s    4((122r   c                 0    t        | dt        | d            S )NPoolIdPoolID)getattrr0   s    r   r   zRhsmPool.get_pool_idR  s    tXwtX'>??r   c                 ,    t        t        | d            S )NQuantityUsed)rU   r  r0   s    r   r   zRhsmPool.get_quantity_usedU  s    74011r   c                 x    d| j                         z  }| j                  j                  |d      \  }}}|dk(  ryy)Nz%subscription-manager attach --pool %sTr8   r   F)r   r   rC   rM   s        r   	subscribezRhsmPool.subscribeX  sB    69I9I9KK![[44TD4IFF7r   N)	r   r   r   __doc__r   r  r   r   r  r^   r   r   r   r   E  s!     
3@2r   r   c                   6    e Zd ZdZddZd ZddZd	dZd	dZy)
r   zO
        This class is used for manipulating pools subscriptions with RHSM
    c                 >    || _         | j                  |      | _        y r   )r   _load_product_listproducts)r   r   r   s      r   r   zRhsmPools.__init__f  s    //9r   c                 6    | j                   j                         S r   )r  __iter__r0   s    r   r  zRhsmPools.__iter__j  s    }}%%''r   c                    d}|r|dz  }n|dz  }t        ddd      }| j                  j                  |d|      \  }}}g }|j                  d      D ]  }|j	                         }t        |      d	k(  r"d
|v s'|j                  d
d      \  }	}
|	j	                         j                  dd      }	|
j	                         }
|	dv r(|j                  t        | j                  |
|
             |s|d   j                  |	|
        |S )z
            Loads list of all available or consumed pools for system in data structure

            Args:
                consumed(bool): if True list consumed  pools, else list available pools (default False)
        zsubscription-manager listz --consumedz --availabler   )LANGLC_ALLLC_MESSAGEST)r9   environ_update
r   :r6    r   )ProductNameSubscriptionName)r   key)
dictr   rC   splitstriprA   r@   r?   r   __setattr__)r   r   rE   lang_envrN   rO   rP   r  liner  values              r   r  zRhsmPools._load_product_listm  s    +M!DN"DS#>![[44TDYa4bFFLL& 	9D::<D4yA~#zz#q1eiik))#r2==OOHT[[5$QRRL,,S%8!	9( r   c              #      K   t        j                  |      }| j                  D ]&  }|j                  |j	                               s#| ( yw)zf
            Return a list of RhsmPools whose pool id matches the provided regular expression
        N)r=   compiler  r>   r   r   regexprproducts       r   filter_poolszRhsmPools.filter_pools  sC      JJv}} 	Gxx++-.	s   AAAc              #      K   t        j                  |      }| j                  D ]"  }|j                  |j                        s| $ yw)zk
            Return a list of RhsmPools whose product name matches the provided regular expression
        N)r=   r'  r  r>   r   r(  s       r   filter_productszRhsmPools.filter_products  s>      JJv}} 	Gxx&	s   A A
A
N)F)z^$)	r   r   r   r  r   r  r  r,  r.  r^   r   r   r   r   a  s!    :($Lr   r   c                   6    e Zd ZdZdZg dZd	dZd Zd Zd Z	y)

SysPurposezL
    This class is used for reading and writing to syspurpose.json file
    z$/etc/rhsm/syspurpose/syspurpose.json)roleusageservice_level_agreementaddonsNc                 .    |xs | j                   | _        y)zH
        Initialize class used for reading syspurpose json file
        N)SYSPURPOSE_FILE_PATHpath)r   r7  s     r   r   zSysPurpose.__init__  s     5D55	r   c                 l   i }d}|j                         D ]<  \  }}|| j                  v r	||||<   |dk(  r#t        d|d| j                         | j                         }||k7  rd}|j	                  |       t        |      D ]  }|| j                  v s||vs||=  | j                  |       |S )zZ
        Try to update current syspurpose with new attributes from new_syspurpose
        FsynczAttribute: z$ not in list of allowed attributes: T)r<   ALLOWED_ATTRIBUTESKeyError_read_syspurposeupdater   _write_syspurpose)r   new_syspurpose
syspurposesyspurpose_changedr  r%  current_syspurposes          r   update_syspurposezSysPurpose.update_syspurpose  s     
"(..0 	?JCd---$&+JsO #T%<%< > ? ?	? "224+!%!!*- *+ 	,Cd---#Z2G&s+	, 	12!!r   c           	          t        | j                  d      5 }|j                  t        j                  |ddd             ddd       y# 1 sw Y   yxY w)zg
        This function tries to update current new_syspurpose attributes to
        json file.
        wr   FT)indentensure_ascii	sort_keysN)r"   r7  r#   jsondumps)r   r?  fps      r   r>  zSysPurpose._write_syspurpose  sI    
 $))S! 	_RHHTZZquX\]^	_ 	_ 	_s   )A		Ac                     i }	 t        | j                  d      5 }|j                         }ddd       t        j                        }|S # 1 sw Y    xY w# t
        $ r Y |S w xY w)z9
        Read current syspurpuse from json file.
        r*  N)r"   r7  r    rI  loadsIOError)r   rB  rK  contents       r   r<  zSysPurpose._read_syspurpose  so      	5dii% $'')$
 "&G!4!!$ $ 	 "!		s'   A A
A 
AA 	A#"A#r   )
r   r   r   r  r6  r:  r   rC  r>  r<  r^   r   r   r0  r0    s+     BO6"8_"r   r0  c                  
   t        i ddddgddi dddid	ddid
i di di di di di dddidddidi di dg ddddi di i dddi i i i ddii di i i ddd ddd!d"d#d$	ddgd%d&gd'd(ggddgdd	gd	dgdd)gddgddggd*dg d+dgg,      } t               d-k7  r| j                  d./       t        |       }| j                  d   }| j                  d   }| j                  d   }| j                  d	   }| j                  d
   }| j                  d   }| j                  d   }| j                  d   }	| j                  d   }
| j                  d   }| j                  d   }| j                  d   }| j                  d   }|r|s| j                  d0/       | j                  d   }i }| j                  d   D ][  }t        |t              r@t        |      d1k7  r| j                  d2/       t        |j                               d-   \  }}n|d }}|||<   ] | j                  d   }| j                  d   }| j                  d)   }| j                  d*   }| j                  d%   }| j                  d&   }| j                  d'   }| j                  d(   }| j                  d3   }| j                  d4   }| j                  d5d      ad}|	 t               j                  |      }|dk(  r-|j                   } | rs|sq|rd7|v r|d7   du r	 |j#                          |r%	 |j%                  |      }" | j&                  dEi |" n|du r| j'                  dd;<       n| j'                  dd=<       n|s|s|s| j                  d>/       	 |j)                           |j*                  dEi | j                   |j-                  | ||||||||||||       |rd7|v r|d7   du r|j#                          |r|j/                  |      }#ng }#| j'                  dd?|z  |#@       |dk(  rH|j                   s| j'                  ddB<       y 	 |j1                          | j'                  ddC|z  <       y y # t        $ r)}| j                  d6t        |      z  /       Y d }~d }~ww xY w# t        $ r)}!| j                  d8t        |!      z  /       Y d }!~!d }!~!ww xY w# t        $ r+}!| j                  d9|d:t        |!      /       Y d }!~!d }!~!ww xY w# t        $ r,}!| j                  dA|d:t        |!      /       Y d }!~!d }!~!ww xY w# t        $ r(}!| j                  dDt        |!      z  /       Y d }!~!y d }!~!ww xY w)FNstatepresentabsent)rY   choicesr   r   no_logTr   server_hostnameserver_insecureserver_prefixserver_portrhsm_baseurlrhsm_repo_ca_certr   r   boolr   r   r   r   r   raw)rY   r   elementsr   r   F)rY   r   r  r  )r   r^  )r   rY   )r1  r2  r3  r4  r9  )r   rF   )	r   r   server_proxy_hostnameserver_proxy_schemeserver_proxy_portserver_proxy_userserver_proxy_passwordr   r@  r_  ra  rb  rc  r   r   )r   r   r   )argument_specrequired_togethermutually_exclusiverequired_ifr   zPInteracting with subscription-manager requires root permissions ('become: true')r   z+org_id is required when using activationkeyr6   z Unable to parse pool_ids option.r   r@  r.   z*Failed to update syspurpose attributes: %sr9  z/Failed to synchronize syspurpose attributes: %sz$Failed to update subscriptions for 'z': zSyspurpose attributes changed.)r   r}   zSystem already registered.zUstate is present but any of the following are missing: username, activationkey, tokenz'System successfully registered to '%s'.)r   r}   r   zFailed to register with 'zSystem already unregistered.z)System successfully unregistered from %s.zFailed to unregister: %sr^   )r	   r   r   r   params
isinstancer  rA   r   r<   get_bin_pathr:   r0  rC  	Exceptionr
   rQ   r   r   	exit_jsonr1   rI   r   r   r   )$r   r   rQ  r   r   r   rV  rW  rX  rY  rZ  r[  r   r   r   r   r   r%  r   r   r   r   r   r   r_  ra  rb  rc  r   r@  rA  errr   r~   resultr   s$                                       r   r   r     s   
 $
	87LM$
$
 4($
 h%	$

 r$
 r$
 R$
 2$
 B$
  $
 FF+$
 h-$
 b$
 2$
 BEJ$
  R!$
" R#$
$ */@%'#%!#!#&.%5/1'-5A%+>	5$
J '
335HI/1HIK -j9,g6$j1,m<,m<,m<> '.TVZ[\_0Fd x1}b 	 	

 <DMM'"E}}Z(H}}Z(HMM'"Emm$56Omm$56OMM/2M--.K==0L&9:--.KMM/2M]]8$FVJK--.KHz* %eT"5zQ  %G H $U[[] 3A 6GX %tXG$% MM/2MMM/2M--.K]]#34N"MM*AB&9:&9:"MM*ABmmI&G|,J $$%;TBJ	`!+!?!?
!K
 	 ++ .f
2z&7IT7Qk((* /!BB8LF %F$$.v.%-$$T7W$X$$U8T$UM%  %| }J//nh%Vcek+]K)74 &J"6:f;MQU;U((**.*D*DX*N'*,'   %NQ`%`5H ! J
 !!U0NOr!   3^ap3p q g  	`!MPYZ]P^!^__	` ! k$$)Z]fgh]i)i$jjk
 ! z$$Ziktuvkw)x$yyz0  k  ?\efg\h%i jjk  P  %?)A,%N OOPsy   Q R S =A<S? 6T7 	R'RR	SS  S	S<!S77S<?	T4!T//T47	U( U##U(__main__)"
__future__r   r   r   r   __metaclass__DOCUMENTATIONEXAMPLESRETURNos.pathr   osr   r   r=   r   r   rI  ansible.module_utils.basicr	   +ansible.module_utils.common.text.convertersr
   ansible.module_utils.six.movesr   ansible.module_utilsr   r:   objectr   r   r   r0  r   r   r^   r   r   <module>r|     s    A @tlEN
   	    4 A 7 ' 
`K6 `KFv 8B BJ?" ?"DfrR zF r   