PageRenderTime 67ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/rhn-client-tools-1.7.14/src/bin/spacewalk-channel.py

#
Python | 162 lines | 132 code | 11 blank | 19 comment | 13 complexity | 79939c90069e2818ba7c093ad71dd5bf MD5 | raw file
Possible License(s): GPL-2.0
  1. #!/usr/bin/python
  2. #
  3. # Copyright (c) 2009--2012 Red Hat, Inc.
  4. #
  5. # This software is licensed to you under the GNU General Public License,
  6. # version 2 (GPLv2). There is NO WARRANTY for this software, express or
  7. # implied, including the implied warranties of MERCHANTABILITY or FITNESS
  8. # FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
  9. # along with this software; if not, see
  10. # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
  11. #
  12. # Red Hat trademarks are not licensed under GPLv2. No permission is
  13. # granted to use or replicate Red Hat trademarks that are incorporated
  14. # in this software or its documentation.
  15. #
  16. import getpass
  17. import os
  18. import re
  19. import socket
  20. import sys
  21. import urlparse
  22. import xmlrpclib
  23. from rhn import rpclib
  24. from optparse import Option, OptionParser
  25. import gettext
  26. t = gettext.translation('rhn-client-tools', fallback=True)
  27. _ = t.ugettext
  28. _LIBPATH = "/usr/share/rhn"
  29. # add to the path if need be
  30. if _LIBPATH not in sys.path:
  31. sys.path.append(_LIBPATH)
  32. from up2date_client.rhnChannel import subscribeChannels, unsubscribeChannels, getChannels
  33. from up2date_client import up2dateAuth, config, up2dateErrors, rhncli
  34. def systemExit(code, msgs=None):
  35. "Exit with a code and optional message(s). Saved a few lines of code."
  36. if msgs:
  37. if type(msgs) not in [type([]), type(())]:
  38. msgs = (msgs, )
  39. for msg in msgs:
  40. sys.stderr.write(rhncli.utf8_encode(msg)+'\n')
  41. sys.exit(code)
  42. # quick check to see if you are a super-user.
  43. if os.getuid() != 0:
  44. systemExit(8, _('ERROR: must be root to execute\n'))
  45. def processCommandline():
  46. "process the commandline, setting the OPTIONS object"
  47. optionsTable = [
  48. Option('-c', '--channel', action='append',
  49. help=_('name of channel you want to (un)subscribe')),
  50. Option('-a', '--add', action='store_true',
  51. help=_('subscribe to channel')),
  52. Option('-r', '--remove', action='store_true',
  53. help=_('unsubscribe from channel')),
  54. Option('-l', '--list', action='store_true',
  55. help=_('list channels')),
  56. Option('-L', '--available-channels', action='store_true',
  57. help=_('list all available child channels')),
  58. Option('-v', '--verbose', action='store_true',
  59. help=_('verbose output')),
  60. Option('-u', '--user', action='store',
  61. help=_('your user name')),
  62. Option('-p', '--password', action='store',
  63. help=_('your password')),
  64. ]
  65. optionParser = OptionParser(option_list=optionsTable)
  66. global OPTIONS
  67. OPTIONS, args = optionParser.parse_args()
  68. # we take no extra commandline arguments that are not linked to an option
  69. if args:
  70. systemExit(1, _("ERROR: these arguments make no sense in this context (try --help)"))
  71. if not OPTIONS.user and not OPTIONS.list:
  72. print _("Username: "),
  73. OPTIONS.user = sys.stdin.readline().rstrip('\n')
  74. if not OPTIONS.password and not OPTIONS.list:
  75. OPTIONS.password = getpass.getpass()
  76. def get_available_channels(user, password):
  77. """ return list of available child channels """
  78. cfg = config.initUp2dateConfig()
  79. satellite_url = config.getServerlURL()[0]
  80. scheme, netloc, path, query, fragment = urlparse.urlsplit(satellite_url)
  81. satellite_url = urlparse.urlunsplit((scheme, netloc, '/rpc/api', query, fragment))
  82. client = xmlrpclib.Server(satellite_url, verbose=0)
  83. try:
  84. key = client.auth.login(user, password)
  85. except xmlrpclib.Fault, exc:
  86. systemExit(1, "Error during client authentication: %s" % exc.faultString)
  87. system_id = re.sub('^ID-', '', rpclib.xmlrpclib.loads(up2dateAuth.getSystemId())[0][0]['system_id'])
  88. result = []
  89. try:
  90. channels = client.system.listChildChannels(key, int(system_id))
  91. except xmlrpclib.Fault, exc:
  92. systemExit(1, "Error when listing child channels: %s" % exc.faultString)
  93. for channel in channels:
  94. if 'LABEL' in channel:
  95. result.extend([channel['LABEL']])
  96. else:
  97. result.extend([channel['label']])
  98. return result
  99. def need_channel(channel):
  100. """ die gracefuly if channel is empty """
  101. if not channel:
  102. systemExit(4, _("ERROR: you have to specify at least one channel"))
  103. def main():
  104. if OPTIONS.add:
  105. need_channel(OPTIONS.channel)
  106. result = subscribeChannels(OPTIONS.channel, OPTIONS.user, OPTIONS.password)
  107. if OPTIONS.verbose:
  108. if result == 0:
  109. print _("Channel(s): %s successfully added") % ', '.join(OPTIONS.channel)
  110. else:
  111. sys.stderr.write(rhncli.utf8_encode(_("Error during adding channel(s) %s") % ', '.join(OPTIONS.channel)))
  112. if result != 0:
  113. sys.exit(result)
  114. elif OPTIONS.remove:
  115. need_channel(OPTIONS.channel)
  116. result = unsubscribeChannels(OPTIONS.channel, OPTIONS.user, OPTIONS.password)
  117. if OPTIONS.verbose:
  118. if result == 0:
  119. print _("Channel(s): %s successfully removed") % ', '.join(OPTIONS.channel)
  120. else:
  121. sys.stderr.write(rhncli.utf8_encode(_("Error during removal of channel(s) %s") % ', '.join(OPTIONS.channel)))
  122. if result != 0:
  123. sys.exit(result)
  124. elif OPTIONS.list:
  125. try:
  126. channels = map(lambda x: x['label'], getChannels().channels())
  127. except up2dateErrors.NoChannelsError:
  128. systemExit(1, _('This system is not associated with any channel.'))
  129. except up2dateErrors.NoSystemIdError:
  130. systemExit(1, _('Unable to locate SystemId file. Is this system registered?'))
  131. channels.sort()
  132. print '\n'.join(channels)
  133. elif OPTIONS.available_channels:
  134. channels = get_available_channels(OPTIONS.user, OPTIONS.password)
  135. channels.sort()
  136. print '\n'.join(channels)
  137. else:
  138. systemExit(3, _("ERROR: you may want to specify --add, --remove or --list"))
  139. try:
  140. sys.excepthook = rhncli.exceptionHandler
  141. processCommandline()
  142. main()
  143. except KeyboardInterrupt:
  144. systemExit(0, "\n" + _("User interrupted process."))
  145. except up2dateErrors.RhnServerException, e:
  146. # do not print traceback, it will scare people
  147. systemExit(1, e)