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.
required: false
default: []
enable_eus:
description:
- If true, extended update support will be requested.
required: false
default: false
'''
EXAMPLES = '''
@ -127,8 +132,8 @@ EXAMPLES = '''
channels: rhel-x86_64-server-6-foo-1,rhel-x86_64-server-6-bar-1
'''
import os
import sys
import types
import xmlrpclib
import urlparse
@ -142,14 +147,14 @@ except ImportError:
HAS_UP2DATE_CLIENT = False
# INSERT REDHAT SNIPPETS
from ansible.module_utils.redhat import *
# INSERT COMMON SNIPPETS
from ansible.module_utils.basic import *
from ansible.module_utils import redhat
from ansible.module_utils.basic import AnsibleModule, get_exception
class Rhn(RegistrationBase):
class Rhn(redhat.RegistrationBase):
def __init__(self, username=None, password=None):
RegistrationBase.__init__(self, username, password)
def __init__(self, module=None, username=None, password=None):
redhat.RegistrationBase.__init__(self, module, username, password)
self.config = self.load_config()
def load_config(self):
@ -159,23 +164,13 @@ class Rhn(RegistrationBase):
if not HAS_UP2DATE_CLIENT:
return None
self.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
config = up2date_client.config.initUp2dateConfig()
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
def hostname(self):
@ -185,7 +180,7 @@ class Rhn(RegistrationBase):
Returns: str
'''
url = urlparse.urlparse(self.config['serverURL'])
url = urlparse.urlparse(self.server_url)
return url[1].replace('xmlrpc.', '')
@property
@ -235,9 +230,9 @@ class Rhn(RegistrationBase):
'''
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)
@ -249,7 +244,7 @@ class Rhn(RegistrationBase):
* enabling the rhnplugin 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('subscription-manager', False)
@ -259,8 +254,8 @@ class Rhn(RegistrationBase):
support will be requested.
'''
register_cmd = ['/usr/sbin/rhnreg_ks', '--username', self.username, '--password', self.password, '--force']
if self.module.params.get('server_url', None):
register_cmd.extend(['--serverUrl', self.module.params.get('server_url')])
if self.server_url:
register_cmd.extend(['--serverUrl', self.server_url])
if enable_eus:
register_cmd.append('--use-eus-channel')
if activationkey is not None:
@ -299,9 +294,7 @@ class Rhn(RegistrationBase):
# Remove systemid file
os.unlink(self.config['systemIdPath'])
def subscribe(self, channels=[]):
if len(channels) <= 0:
return
def subscribe(self, channels):
if self._is_hosted():
current_channels = self.api('channel.software.listSystemChannels', self.systemid)
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)
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):
'''
Return True if we are running against Hosted (rhn.redhat.com) or
@ -352,10 +331,8 @@ class Rhn(RegistrationBase):
else:
return False
def main():
# Read system RHN configuration
rhn = Rhn()
def main():
module = AnsibleModule(
argument_spec=dict(
@ -375,19 +352,26 @@ def main():
if not HAS_UP2DATE_CLIENT:
module.fail_json(msg="Unable to import up2date_client. Is 'rhn-client-tools' installed?")
if not module.params['server_url']:
module.params['server_url'] = rhn.config.get_option('serverURL')
server_url = module.params['server_url']
username = module.params['username']
password = module.params['password']
state = module.params['state']
rhn.username = module.params['username']
rhn.password = module.params['password']
rhn.configure(module.params['server_url'])
activationkey = module.params['activationkey']
profilename = module.params['profilename']
sslcacert = module.params['sslcacert']
systemorgid = module.params['systemorgid']
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
if state == 'present':
@ -400,11 +384,11 @@ def main():
# Register system
if rhn.is_registered:
module.exit_json(changed=False, msg="System already registered.")
else:
return module.exit_json(changed=False, msg="System already registered.")
try:
rhn.enable()
rhn.register(module.params['enable_eus'] == True, activationkey, profilename, sslcacert, systemorgid)
rhn.register(enable_eus, activationkey, profilename, sslcacert, systemorgid)
rhn.subscribe(channels)
except Exception:
e = get_exception()
@ -415,8 +399,8 @@ def main():
# Ensure system is *not* registered
if state == 'absent':
if not rhn.is_registered:
module.exit_json(changed=False, msg="System already unregistered.")
else:
return module.exit_json(changed=False, msg="System already unregistered.")
try:
rhn.unregister()
except Exception:

Loading…
Cancel
Save