Reorganize subscription_manager module.

Also ...
 * When unregistering, first unsubscribe from all content
pull/3148/head
James Laska 12 years ago
parent a2cbcec328
commit 65993e8f35

@ -100,67 +100,52 @@ def run_command(args):
return (stdout, stderr, returncode)
class RhsmPool(object):
def __init__(self, **kwargs):
for k,v in kwargs.items():
setattr(self, k, v)
def __str__(self):
return str(self.__getattribute__('_name'))
def subscribe(self):
(stdout, stderr, retcode) = run_command("subscription-manager subscribe --pool %s" % self.PoolId)
return True
class RhsmPools(object):
"""
This class is used for manipulating pools subscriptions with RHSM
"""
def __init__(self):
self.products = self._load_product_list()
def __iter__(self):
return self.products.__iter__()
def _load_product_list(self):
"""
Loads list of all availaible pools for system in data structure
"""
(stdout, stderr, retval) = run_command("subscription-manager list --available")
class RegistrationBase (object):
def __init__(self, username=None, password=None):
self.username = username
self.password = password
def configure(self):
raise NotImplementedError("Must be implemented by a sub-class")
def enable(self):
# Remove any existing redhat.repo
redhat_repo = '/etc/yum.repos.d/redhat.repo'
if os.path.isfile(redhat_repo):
os.unlink(redhat_repo)
def register(self):
raise NotImplementedError("Must be implemented by a sub-class")
def unregister(self):
raise NotImplementedError("Must be implemented by a sub-class")
def unsubscribe(self):
raise NotImplementedError("Must be implemented by a sub-class")
def update_plugin_conf(self, plugin, enabled=True):
plugin_conf = '/etc/yum/pluginconf.d/%s.conf' % plugin
if os.path.isfile(plugin_conf):
cfg = ConfigParser.ConfigParser()
cfg.read([plugin_conf])
if enabled:
cfg.set('main', 'enabled', 1)
else:
cfg.set('main', 'enabled', 0)
fd = open(plugin_conf, 'rwa+')
cfg.write(fd)
fd.close()
products = []
for line in stdout.split('\n'):
# Remove leading+trailing whitespace
line = line.strip()
# An empty line implies the end of a output group
if len(line) == 0:
continue
# If a colon ':' is found, parse
elif ':' in line:
(key, value) = line.split(':',1)
key = key.strip().replace(" ", "") # To unify
value = value.strip()
if key in ['ProductName', 'SubscriptionName']:
# Remember the name for later processing
products.append(RhsmPool(_name=value, key=value))
elif products:
# Associate value with most recently recorded product
products[-1].__setattr__(key, value)
# FIXME - log some warning?
#else:
# warnings.warn("Unhandled subscription key/value: %s/%s" % (key,value))
return products
def subscribe(self, **kwargs):
raise NotImplementedError("Must be implemented by a sub-class")
def filter(self, regexp='^$'):
'''
Return a list of RhsmPools whose name matches the provided regular expression
'''
r = re.compile(regexp)
for product in self.products:
if r.search(product._name):
yield product
class Rhsm(RegistrationBase):
def __init__(self, username=None, password=None):
RegistrationBase.__init__(self, username, password)
self.config = self._read_config()
def read_rhsm_config(rhsm_conf='/etc/rhsm/rhsm.conf'):
def _read_config(rhsm_conf='/etc/rhsm/rhsm.conf'):
'''
Load RHSM configuration from /etc/rhsm/rhsm.conf.
Returns:
@ -185,8 +170,35 @@ def read_rhsm_config(rhsm_conf='/etc/rhsm/rhsm.conf'):
return cp
def enable(self):
'''
Enable the system to receive updates from subscription-manager.
This involves updating affected yum plugins and removing any
conflicting yum repositories.
'''
RegistrationBase.enable(self)
self.update_plugin_conf('rhnplugin', False)
self.update_plugin_conf('subscription-manager', True)
def configure(self, **kwargs):
'''
Configure the system as directed for registration with RHN
Raises:
* Exception - if error occurs while running command
'''
args = ['subscription-manager', 'config']
# Pass supplied **kwargs as parameters to subscription-manager. Ignore
# non-configuration parameters and replace '_' with '.'. For example,
# 'server_hostname' becomes '--system.hostname'.
for k,v in kwargs.items():
if re.search(r'^(system|rhsm)_', k):
args.append('--%s=%s' % (k.replace('_','.'), v))
def is_registered():
run_command(args)
@property
def is_registered(self):
'''
Determine whether the current system
Returns:
@ -207,26 +219,7 @@ def is_registered():
# Display some debug output
return True
def configure(**kwargs):
'''
Configure the system as directed for registration with RHN
Raises:
* Exception - if error occurs while running command
'''
args = ['subscription-manager', 'config']
# Pass supplied **kwargs as parameters to subscription-manager. Ignore
# non-configuration parameters and replace '_' with '.'. For example,
# 'server_hostname' becomes '--system.hostname'.
for k,v in kwargs.items():
if re.search(r'^(system|rhsm)_', k):
args.append('--%s=%s' % (k.replace('_','.'), v))
run_command(args)
def register(username, password, autosubscribe, activationkey):
def register(self, username, password, autosubscribe, activationkey):
'''
Register the current system to the provided RHN server
Raises:
@ -248,8 +241,25 @@ def register(username, password, autosubscribe, activationkey):
# Do the needful...
run_command(args)
def unsubscribe(self):
'''
Unsubscribe a system from all subscribed channels
Raises:
* Exception - if error occurs while running command
'''
args = ['subscription-manager', 'unsubscribe', '--all']
run_command(args)
def unregister(self):
'''
Unregister a currently registered system
Raises:
* Exception - if error occurs while running command
'''
args = ['subscription-manager', 'unregister']
run_command(args)
def subscribe(regexp):
def subscribe(self, regexp):
'''
Subscribe current system to available pools matching the specified
regular expression
@ -264,29 +274,82 @@ def subscribe(regexp):
pool.subscribe()
def unregister():
class RhsmPool(object):
'''
Unregister a currently registered system
Raises:
* Exception - if error occurs while running command
Convenience class for housing subscription information
'''
args = ['subscription-manager', 'unregister']
return run_command(args)
def __init__(self, **kwargs):
for k,v in kwargs.items():
setattr(self, k, v)
def __str__(self):
return str(self.__getattribute__('_name'))
def subscribe(self):
(stdout, stderr, retcode) = run_command("subscription-manager subscribe --pool %s" % self.PoolId)
return True
class RhsmPools(object):
"""
This class is used for manipulating pools subscriptions with RHSM
"""
def __init__(self):
self.products = self._load_product_list()
def __iter__(self):
return self.products.__iter__()
def _load_product_list(self):
"""
Loads list of all availaible pools for system in data structure
"""
(stdout, stderr, retval) = run_command("subscription-manager list --available")
products = []
for line in stdout.split('\n'):
# Remove leading+trailing whitespace
line = line.strip()
# An empty line implies the end of a output group
if len(line) == 0:
continue
# If a colon ':' is found, parse
elif ':' in line:
(key, value) = line.split(':',1)
key = key.strip().replace(" ", "") # To unify
value = value.strip()
if key in ['ProductName', 'SubscriptionName']:
# Remember the name for later processing
products.append(RhsmPool(_name=value, key=value))
elif products:
# Associate value with most recently recorded product
products[-1].__setattr__(key, value)
# FIXME - log some warning?
#else:
# warnings.warn("Unhandled subscription key/value: %s/%s" % (key,value))
return products
def filter(self, regexp='^$'):
'''
Return a list of RhsmPools whose name matches the provided regular expression
'''
r = re.compile(regexp)
for product in self.products:
if r.search(product._name):
yield product
def main():
# Load RHSM configuration from file
cp = read_rhsm_config()
rhn = Rhsm()
module = AnsibleModule(
argument_spec = dict(
state = dict(default='present', choices=['present', 'absent']),
username = dict(default=None, required=False),
password = dict(default=None, required=False),
server_hostname = dict(default=cp.get_option('server.hostname'), required=False),
server_insecure = dict(default=cp.get_option('server.insecure'), required=False),
rhsm_baseurl = dict(default=cp.get_option('rhsm.baseurl'), required=False),
server_hostname = dict(default=rhn.config.get_option('server.hostname'), required=False),
server_insecure = dict(default=rhn.config.get_option('server.insecure'), required=False),
rhsm_baseurl = dict(default=rhn.config.get_option('rhsm.baseurl'), required=False),
autosubscribe = dict(default=False, type='bool'),
activationkey = dict(default=None, required=False),
pool = dict(default='^$', required=False, type='str'),
@ -313,13 +376,14 @@ def main():
module.fail_json(msg="Missing arguments, If registering without an activationkey, must supply username or password")
# Register system
if is_registered():
if rhn.is_registered:
module.exit_json(changed=False, msg="System already registered.")
else:
try:
configure(**module.params)
register(username, password, autosubscribe, activationkey)
subscribe(pool)
rhn.enable()
rhn.configure(**module.params)
rhn.register(username, password, autosubscribe, activationkey)
rhn.subscribe(pool)
except CommandException, e:
module.fail_json(msg="Failed to register with '%s': %s" % (server_hostname, e))
else:
@ -327,11 +391,12 @@ def main():
# Ensure system is *not* registered
if state == 'absent':
if not is_registered():
if not rhn.is_registered:
module.exit_json(changed=False, msg="System already unregistered.")
else:
try:
unregister()
rhn.unsubscribe()
rhn.unregister()
except CommandException, e:
module.fail_json(msg="Failed to unregister: %s" % e)
else:

Loading…
Cancel
Save