Package up2date_client :: Module rhncli
[hide private]
[frames] | no frames]

Source Code for Module up2date_client.rhncli

  1  # 
  2  # Common cli related functions for RHN Client Tools 
  3  # Copyright (c) 1999--2016 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  # Authors: 
 17  #       Adrian Likins <alikins@redhat.com> 
 18  #       Preston Brown <pbrown@redhat.com> 
 19  #       James Bowes <jbowes@redhat.com> 
 20  # 
 21  # In addition, as a special exception, the copyright holders give 
 22  # permission to link the code of portions of this program with the 
 23  # OpenSSL library under certain conditions as described in each 
 24  # individual source file, and distribute linked combinations 
 25  # including the two. 
 26  # You must obey the GNU General Public License in all respects 
 27  # for all of the code used other than OpenSSL.  If you modify 
 28  # file(s) with this exception, you may extend this exception to your 
 29  # version of the file(s), but you are not obligated to do so.  If you 
 30  # do not wish to do so, delete this exception statement from your 
 31  # version.  If you delete this exception statement from all source 
 32  # files in the program, then also delete it here. 
 33   
 34  import sys 
 35  import os 
 36  import socket 
 37   
 38  from optparse import Option 
 39  from optparse import OptionParser 
 40   
 41  from OpenSSL import SSL 
 42  from OpenSSL import crypto 
 43   
 44  from rhn import rpclib 
 45  from rhn.i18n import sstr 
 46   
 47  try: # python2 
 48      import xmlrpclib 
 49  except ImportError: # python3 
 50      import xmlrpc.client as xmlrpclib 
 51   
 52  import gettext 
 53  t = gettext.translation('rhn-client-tools', fallback=True) 
 54  # Python 3 translations don't have a ugettext method 
 55  if not hasattr(t, 'ugettext'): 
 56      t.ugettext = t.gettext 
 57  _ = t.ugettext 
 58   
 59  from up2date_client import config 
 60  from up2date_client import up2dateAuth 
 61  from up2date_client import up2dateErrors 
 62  from up2date_client import up2dateLog 
 63  from up2date_client import up2dateUtils 
 64  from up2date_client import pkgUtils 
 65   
 66  _optionsTable = [ 
 67      Option("-v", "--verbose", action="count", default=0, 
 68          help=_("Show additional output")), 
 69      Option("--proxy", action="store", 
 70        help=_("Specify an http proxy to use")), 
 71      Option("--proxyUser", action="store", 
 72        help=_("Specify a username to use with an authenticated http proxy")), 
 73      Option("--proxyPassword", action="store", 
 74        help=_("Specify a password to use with an authenticated http proxy")), 
 75     ] 
76 77 -class RhnCli(object):
78
79 - def __init__(self):
80 self.optparser = OptionParser(option_list = _optionsTable, 81 version = RhnCli.__versionString()) 82 83 self.options = None 84 self.args = None 85 86 self.hasGui = False
87
88 - def run(self):
89 # catch any uncaught exceptions and handle them nicely 90 sys.excepthook = exceptionHandler 91 # main loop call 92 try: 93 self.initialize() 94 sys.exit(self.main() or 0) 95 except KeyboardInterrupt: 96 sys.stderr.write(sstr(_("\nAborted.\n"))) 97 sys.exit(1) 98 except OSError: 99 sys.stderr.write(sstr(_("An unexpected OS error occurred: %s\n") % sys.exc_info()[1])) 100 sys.exit(1) 101 except rpclib.MalformedURIError: # Subclass of IOError so must come 1st? 102 e = sys.exc_info()[1] 103 if e is None or len(str(e)) == 0: 104 sys.stderr.write(sstr(_("A connection was attempted with a malformed URI.\n"))) 105 else: 106 sys.stderr.write(sstr(_("A connection was attempted with a malformed URI: %s.\n") % e)) 107 except IOError: 108 sys.stderr.write(sstr(_("There was some sort of I/O error: %s\n") % sys.exc_info()[1])) 109 sys.exit(1) 110 except SSL.Error: 111 sys.stderr.write(sstr(_("There was an SSL error: %s\n") % sys.exc_info()[1])) 112 sys.stderr.write(sstr(_("A common cause of this error is the system time being incorrect. " \ 113 "Verify that the time on this system is correct.\n"))) 114 sys.exit(1) 115 except (SSL.SysCallError, socket.error): 116 sys.stderr.write(sstr("OpenSSL.SSL.SysCallError: %s\n" % str(sys.exc_info()[1]))) 117 sys.exit(2) 118 except crypto.Error: 119 sys.stderr.write(sstr(_("There was a SSL crypto error: %s\n") % sys.exc_info()[1])) 120 except SystemExit: 121 raise 122 except up2dateErrors.AuthenticationError: 123 sys.stderr.write(sstr(_("There was an authentication error: %s\n") % sys.exc_info()[1])) 124 sys.exit(1) 125 except up2dateErrors.RpmError: 126 sys.stderr.write(sstr("%s\n" % sys.exc_info()[1])) 127 sys.exit(1) 128 except xmlrpclib.ProtocolError: 129 sys.stderr.write(sstr("XMLRPC ProtocolError: %s\n" % str(sys.exc_info()[1]))) 130 sys.exit(3)
131
132 - def initialize(self):
133 (self.options, self.args) = self.optparser.parse_args() 134 135 RhnCli.__setDebugLevel(self.options.verbose) 136 137 # see if were running as root 138 if os.geteuid() != 0: 139 rootWarningMsg = _("You must be root to run %s") % sys.argv[0] 140 self._warning_dialog(rootWarningMsg) 141 sys.exit(1) 142 143 self.__updateProxyConfig()
144
145 - def main(self):
146 raise NotImplementedError
147
148 - def _testRhnLogin(self):
149 try: 150 up2dateAuth.updateLoginInfo() 151 return True 152 except up2dateErrors.ServerCapabilityError: 153 print(sys.exc_info()[1]) 154 return False 155 except up2dateErrors.AuthenticationError: 156 return False 157 except up2dateErrors.RhnServerException: 158 log = up2dateLog.initLog() 159 log.log_me('There was a RhnServerException while testing login:\n') 160 log.log_exception(*sys.exc_info()) 161 return False
162
163 - def _warning_dialog(self, message):
164 if self.hasGui: 165 try: 166 from up2date_client import gui 167 gui.errorWindow(message) 168 except: 169 print(_("Unable to open gui. Try `up2date --nox`")) 170 print(message) 171 else: 172 print(message)
173
174 - def __updateProxyConfig(self):
175 """Update potential proxy configuration. 176 Note: this will _not_ save the info to up2date's configuration file 177 A separate call to config.initUp2dateConfig.save() is needed. 178 """ 179 cfg = config.initUp2dateConfig() 180 181 if self.options.proxy: 182 cfg.set("httpProxy", self.options.proxy) 183 cfg.set("enableProxy", 1) 184 if self.options.proxyUser: 185 cfg.set("proxyUser", self.options.proxyUser) 186 cfg.set("enableProxyAuth", 1) 187 if self.options.proxyPassword: 188 cfg.set("proxyPassword", self.options.proxyPassword) 189 cfg.set("enableProxyAuth", 1)
190
191 - def saveConfig(self):
192 """ 193 Saves the current up2date configuration being used to disk. 194 """ 195 cfg = config.initUp2dateConfig() 196 cfg.save()
197
198 - def __faultError(self, errMsg):
199 if self.hasGui: 200 try: 201 from up2date_client import gui 202 gui.errorWindow(errMsg) 203 except: 204 print(_("Unable to open gui. Try `up2date --nox`")) 205 print(errMsg) 206 else: 207 print(errMsg)
208 209 @staticmethod
210 - def __versionString():
211 versionString = _("%%prog (Spacewalk Client Tools) %s\n" 212 "Copyright (C) 1999--2014 Red Hat, Inc.\n" 213 "Licensed under the terms of the GPLv2.") % up2dateUtils.version() 214 return versionString
215 216 @staticmethod
217 - def __setDebugLevel(level):
218 cfg = config.initUp2dateConfig() 219 # figure out the debug level 220 cfg["debug"] = cfg["debug"] + level 221 if cfg["debug"] > 2: 222 pkgUtils.setDebugVerbosity()
223
224 -def exceptionHandler(type, value, tb):
225 log = up2dateLog.initLog() 226 sys.stderr.write(sstr(_("An error has occurred:") + "\n")) 227 if hasattr(value, "errmsg"): 228 sys.stderr.write(sstr(value.errmsg) + "\n") 229 log.log_exception(type, value, tb) 230 else: 231 sys.stderr.write(sstr(str(type) + "\n")) 232 log.log_exception(type, value, tb) 233 234 sys.stderr.write(sstr(_("See /var/log/up2date for more information") + "\n"))
235