Rhn register misc fixes (#20724)

* Remove monkeypatching of rhn config in rhn_register

rhn_register.Rhn() was doing some complicated monkeypatching of
the up2date_client.config.Config() class to add a default config
value. Since that was only used in one place, remove the monkeypatch
and handle the single default case.

That case was 'server_url' option, so replace it with a Rhn.server_url
property. Also handle the error case when no server url is provided.

* refactoring
* flatten some indention levels
* add 'enable_eus' to module doc
* set enable_eus var and use it directly
* style/pep8/etc cleanups
* some import cleanups

types was unused, os/re were from module_utils * import

* remove * import from module_utils.redhat
* remove * imports from module_utils.base
* remove unused Rhn._subscribe method
* cleanup pep8 style stuff
* remove a unused default mutable arg from Rhn.subscribe

Rhn.subscribe() only gets called in one place, and thats
with channels from module_params which default to [] and
are typed as a list.
pull/19008/head
Adrian Likins 8 years ago committed by GitHub
parent a8c038383e
commit b3b598c835

@ -83,6 +83,11 @@ options:
- Optionally specify a list of comma-separated channels to subscribe to upon successful registration. - Optionally specify a list of comma-separated channels to subscribe to upon successful registration.
required: false required: false
default: [] default: []
enable_eus:
description:
- If true, extended update support will be requested.
required: false
default: false
''' '''
EXAMPLES = ''' EXAMPLES = '''
@ -127,8 +132,8 @@ EXAMPLES = '''
channels: rhel-x86_64-server-6-foo-1,rhel-x86_64-server-6-bar-1 channels: rhel-x86_64-server-6-foo-1,rhel-x86_64-server-6-bar-1
''' '''
import os
import sys import sys
import types
import xmlrpclib import xmlrpclib
import urlparse import urlparse
@ -142,14 +147,14 @@ except ImportError:
HAS_UP2DATE_CLIENT = False HAS_UP2DATE_CLIENT = False
# INSERT REDHAT SNIPPETS # INSERT REDHAT SNIPPETS
from ansible.module_utils.redhat import * from ansible.module_utils import redhat
# INSERT COMMON SNIPPETS from ansible.module_utils.basic import AnsibleModule, get_exception
from ansible.module_utils.basic import *
class Rhn(RegistrationBase): class Rhn(redhat.RegistrationBase):
def __init__(self, username=None, password=None): def __init__(self, module=None, username=None, password=None):
RegistrationBase.__init__(self, username, password) redhat.RegistrationBase.__init__(self, module, username, password)
self.config = self.load_config() self.config = self.load_config()
def load_config(self): def load_config(self):
@ -159,23 +164,13 @@ class Rhn(RegistrationBase):
if not HAS_UP2DATE_CLIENT: if not HAS_UP2DATE_CLIENT:
return None return None
self.config = up2date_client.config.initUp2dateConfig() config = up2date_client.config.initUp2dateConfig()
# Add support for specifying a default value w/o having to standup some
# configuration. Yeah, I know this should be subclassed ... but, oh
# well
def get_option_default(self, key, default=''):
# the class in rhn-client-tools that this comes from didn't
# implement __contains__() until 2.5.x. That's why we check if
# the key is present in the dictionary that is the actual storage
if key in self.dict:
return self[key]
else:
return default
self.config.get_option = types.MethodType(get_option_default, self.config, up2date_client.config.Config) return config
return self.config @property
def server_url(self):
return self.config['serverURL']
@property @property
def hostname(self): def hostname(self):
@ -185,7 +180,7 @@ class Rhn(RegistrationBase):
Returns: str Returns: str
''' '''
url = urlparse.urlparse(self.config['serverURL']) url = urlparse.urlparse(self.server_url)
return url[1].replace('xmlrpc.', '') return url[1].replace('xmlrpc.', '')
@property @property
@ -235,9 +230,9 @@ class Rhn(RegistrationBase):
''' '''
return os.path.isfile(self.config['systemIdPath']) return os.path.isfile(self.config['systemIdPath'])
def configure(self, server_url): def configure_server_url(self, server_url):
''' '''
Configure system for registration Configure server_url for registration
''' '''
self.config.set('serverURL', server_url) self.config.set('serverURL', server_url)
@ -249,7 +244,7 @@ class Rhn(RegistrationBase):
* enabling the rhnplugin yum plugin * enabling the rhnplugin yum plugin
* disabling the subscription-manager yum plugin * disabling the subscription-manager yum plugin
''' '''
RegistrationBase.enable(self) redhat.RegistrationBase.enable(self)
self.update_plugin_conf('rhnplugin', True) self.update_plugin_conf('rhnplugin', True)
self.update_plugin_conf('subscription-manager', False) self.update_plugin_conf('subscription-manager', False)
@ -259,8 +254,8 @@ class Rhn(RegistrationBase):
support will be requested. support will be requested.
''' '''
register_cmd = ['/usr/sbin/rhnreg_ks', '--username', self.username, '--password', self.password, '--force'] register_cmd = ['/usr/sbin/rhnreg_ks', '--username', self.username, '--password', self.password, '--force']
if self.module.params.get('server_url', None): if self.server_url:
register_cmd.extend(['--serverUrl', self.module.params.get('server_url')]) register_cmd.extend(['--serverUrl', self.server_url])
if enable_eus: if enable_eus:
register_cmd.append('--use-eus-channel') register_cmd.append('--use-eus-channel')
if activationkey is not None: if activationkey is not None:
@ -299,9 +294,7 @@ class Rhn(RegistrationBase):
# Remove systemid file # Remove systemid file
os.unlink(self.config['systemIdPath']) os.unlink(self.config['systemIdPath'])
def subscribe(self, channels=[]): def subscribe(self, channels):
if len(channels) <= 0:
return
if self._is_hosted(): if self._is_hosted():
current_channels = self.api('channel.software.listSystemChannels', self.systemid) current_channels = self.api('channel.software.listSystemChannels', self.systemid)
new_channels = [item['channel_label'] for item in current_channels] new_channels = [item['channel_label'] for item in current_channels]
@ -328,20 +321,6 @@ class Rhn(RegistrationBase):
out_childs = self.api('system.setChildChannels', self.systemid, new_childs) out_childs = self.api('system.setChildChannels', self.systemid, new_childs)
return out_base and out_childs return out_base and out_childs
def _subscribe(self, channels=[]):
'''
Subscribe to requested yum repositories using 'rhn-channel' command
'''
rhn_channel_cmd = "rhn-channel --user='%s' --password='%s'" % (self.username, self.password)
rc, stdout, stderr = self.module.run_command(rhn_channel_cmd + " --available-channels", check_rc=True)
# Enable requested repoid's
for wanted_channel in channels:
# Each inserted repo regexp will be matched. If no match, no success.
for available_channel in stdout.rstrip().split('\n'): # .rstrip() because of \n at the end -> empty string at the end
if re.search(wanted_repo, available_channel):
rc, stdout, stderr = self.module.run_command(rhn_channel_cmd + " --add --channel=%s" % available_channel, check_rc=True)
def _is_hosted(self): def _is_hosted(self):
''' '''
Return True if we are running against Hosted (rhn.redhat.com) or Return True if we are running against Hosted (rhn.redhat.com) or
@ -352,10 +331,8 @@ class Rhn(RegistrationBase):
else: else:
return False return False
def main():
# Read system RHN configuration def main():
rhn = Rhn()
module = AnsibleModule( module = AnsibleModule(
argument_spec=dict( argument_spec=dict(
@ -375,19 +352,26 @@ def main():
if not HAS_UP2DATE_CLIENT: if not HAS_UP2DATE_CLIENT:
module.fail_json(msg="Unable to import up2date_client. Is 'rhn-client-tools' installed?") module.fail_json(msg="Unable to import up2date_client. Is 'rhn-client-tools' installed?")
if not module.params['server_url']: server_url = module.params['server_url']
module.params['server_url'] = rhn.config.get_option('serverURL') username = module.params['username']
password = module.params['password']
state = module.params['state'] state = module.params['state']
rhn.username = module.params['username']
rhn.password = module.params['password']
rhn.configure(module.params['server_url'])
activationkey = module.params['activationkey'] activationkey = module.params['activationkey']
profilename = module.params['profilename'] profilename = module.params['profilename']
sslcacert = module.params['sslcacert'] sslcacert = module.params['sslcacert']
systemorgid = module.params['systemorgid'] systemorgid = module.params['systemorgid']
channels = module.params['channels'] channels = module.params['channels']
rhn.module = module enable_eus = module.params['enable_eus']
rhn = Rhn(module=module, username=username, password=password)
# use the provided server url and persist it to the rhn config.
if server_url:
rhn.configure_server_url(server_url)
if not rhn.server_url:
module.fail_json(msg="No serverURL was found (from either the 'server_url' module arg or the config file option 'serverURL' in /etc/sysconfig/rhn/up2date)")
# Ensure system is registered # Ensure system is registered
if state == 'present': if state == 'present':
@ -400,11 +384,11 @@ def main():
# Register system # Register system
if rhn.is_registered: if rhn.is_registered:
module.exit_json(changed=False, msg="System already registered.") return module.exit_json(changed=False, msg="System already registered.")
else:
try: try:
rhn.enable() rhn.enable()
rhn.register(module.params['enable_eus'] == True, activationkey, profilename, sslcacert, systemorgid) rhn.register(enable_eus, activationkey, profilename, sslcacert, systemorgid)
rhn.subscribe(channels) rhn.subscribe(channels)
except Exception: except Exception:
e = get_exception() e = get_exception()
@ -415,8 +399,8 @@ def main():
# Ensure system is *not* registered # Ensure system is *not* registered
if state == 'absent': if state == 'absent':
if not rhn.is_registered: if not rhn.is_registered:
module.exit_json(changed=False, msg="System already unregistered.") return module.exit_json(changed=False, msg="System already unregistered.")
else:
try: try:
rhn.unregister() rhn.unregister()
except Exception: except Exception:

Loading…
Cancel
Save