| Current File : /home/mmdealscpanel/yummmdeals.com/up2date_client.tar |
pmPlugin.py 0000644 00000005453 15051677404 0006731 0 ustar 00 # Client code for enabling plugin
# Copyright (c) 2000--2016 Red Hat, Inc.
import os
import re
import rpm
# global variables
try:
from dnf import __version__
PM_PLUGIN_CONF = '/etc/dnf/plugins/spacewalk.conf'
PM_PLUGIN_NAME = 'dnf-plugin-spacewalk'
PM_NAME = 'dnf'
except ImportError:
PM_PLUGIN_CONF = '/etc/yum/pluginconf.d/rhnplugin.conf'
PM_PLUGIN_NAME = 'yum-rhn-plugin'
PM_NAME = 'yum'
def pluginEnable():
"""Enables plugin, may throw IOError"""
conf_changed = 0
plugin_present = 0
if PluginPackagePresent():
plugin_present = 1
if PluginConfPresent():
if not PluginEnabled():
enablePlugin()
conf_changed = 1
else:
createDefaultPluginConf()
conf_changed = 1
elif os.path.exists("/usr/lib/zypp/plugins/services/spacewalk"):
"""SUSE zypp plugin is installed"""
plugin_present = 1
return plugin_present, conf_changed
def PluginPackagePresent():
""" Returns positive number if plugin package is installed, otherwise it return 0 """
ts = rpm.TransactionSet()
headers = ts.dbMatch('providename', PM_PLUGIN_NAME)
return headers.count()
def PluginConfPresent():
""" Returns true if PM_PLUGIN_CONF is presented """
try:
os.stat(PM_PLUGIN_CONF)
return True
except OSError:
return False
def createDefaultPluginConf():
""" Create file PM_PLUGIN_CONF, with default values """
f = open(PM_PLUGIN_CONF, 'w')
f.write("""[main]
enabled = 1
gpgcheck = 1""")
f.close()
def PluginEnabled():
""" Returns True if plugin is enabled
Can thrown IOError exception.
"""
f = open(PM_PLUGIN_CONF, 'r')
lines = f.readlines()
f.close()
main_section = False
result = False
for line in lines:
if re.match("^\[.*]", line):
if re.match("^\[main]", line):
main_section = True
else:
main_section = False
if main_section:
m = re.match('^\s*enabled\s*=\s*([0-9])', line)
if m:
if int(m.group(1)):
result = True
else:
result = False
return result
def enablePlugin():
""" enable plugin by setting enabled=1 in file PM_PLUGIN_CONF
Can thrown IOError exception.
"""
f = open(PM_PLUGIN_CONF, 'r')
lines = f.readlines()
f.close()
main_section = False
f = open(PM_PLUGIN_CONF, 'w')
for line in lines:
if re.match("^\[.*]", line):
if re.match("^\[main]", line):
main_section = True
else:
main_section = False
if main_section:
line = re.sub('^(\s*)enabled\s*=.+', r'\1enabled = 1', line)
f.write(line)
f.close()
debUtils.py 0000644 00000005416 15051677404 0006710 0 ustar 00 # Client code for Update Agent
# Copyright (c) 2011--2016 Red Hat, Inc. Distributed under GPLv2.
#
# Author: Simon Lukasik
# Lukas Durfina
#
import os
import apt
import gettext
t = gettext.translation('rhn-client-tools', fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, 'ugettext'):
t.ugettext = t.gettext
_ = t.ugettext
# FIXME: After Debian bug 187019 is resolved
def verifyPackages(packages):
cache = apt.Cache()
missing_packages = []
for package in packages:
pkg = cache[package[0]]
if pkg == None or not pkg.is_installed:
missing_packages.append(package)
return [], missing_packages
def parseVRE(version):
epoch = ''
release = 'X'
if version.find(':') != -1:
epoch, version = version.split(':')
if version.find('-') != -1:
tmp = version.split('-')
version = '-'.join(tmp[:-1])
release = tmp[-1]
return version, release, epoch
def installTime(pkg_name, pkg_arch):
dir = '/var/lib/dpkg/info'
files = [ '%s.list' % pkg_name,
'%s:%s.list' % (pkg_name, pkg_arch) ]
# In edge cases, pkg_name can include the arch but the .list file does not
if ':' in pkg_name:
files.append('%s.list' % (pkg_name[:pkg_name.index(':')]))
for f in files:
path = os.path.join(dir,f)
if os.path.isfile(path):
return os.path.getmtime(path)
return 0
#FIXME: Using Apt cache might not be an ultimate solution.
# It could be better to parse /var/lib/dpkg/status manually.
# Apt cache might not contain all the packages.
def getInstalledPackageList(msgCallback = None, progressCallback = None,
getArch=None, getInfo = None):
""" Return list of packages. Package is dict with following keys:
name, epoch, version, release and optionaly arch.
"""
if msgCallback != None:
msgCallback(_("Getting list of packages installed on the system"))
cache = apt.Cache()
total = 0
for pkg in cache:
if pkg.installed != None:
total += 1
count = 0
pkg_list = []
for pkg in cache:
if pkg.installed == None:
continue
version, release, epoch = parseVRE(pkg.installed.version)
package = {
'name': pkg.name,
'epoch': epoch,
'version': version,
'release': release,
'arch': pkg.installed.architecture + '-deb',
'installtime': installTime(pkg.name, pkg.installed.architecture)
}
pkg_list.append(package)
if progressCallback != None:
progressCallback(count, total)
count = count + 1
pkg_list.sort(key=lambda package: package['version'])
return pkg_list
def setDebugVerbosity():
pass
__init__.py 0000644 00000000000 15051677404 0006654 0 ustar 00 pkgUtils.py 0000644 00000000447 15051677404 0006736 0 ustar 00 # Client code for Update Agent
# Copyright (c) 2011--2016 Red Hat, Inc. Distributed under GPLv2.
#
# Author: Simon Lukasik
from up2date_client.pkgplatform import getPlatform
if getPlatform() == 'deb':
from up2date_client.debUtils import *
else:
from up2date_client.rpmUtils import *
rhnreg_constants.py 0000644 00000044211 15051677404 0010512 0 ustar 00 # -*- coding: utf-8 -*-
#
# String constants for the RHN Register TUI/GUI.
# Copyright (c) 2000--2016 Red Hat, Inc.
#
# Author:
# James Slagle <jslagle@redhat.com>
from up2date_client.pmPlugin import PM_PLUGIN_NAME, PM_NAME
import gettext
t = gettext.translation('rhn-client-tools', fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, 'ugettext'):
t.ugettext = t.gettext
_ = t.ugettext
COPYRIGHT_TEXT = _(u"Copyright © 2006--2014 Red Hat, Inc. All rights reserved.")
# Satellite URL Window
SATELLITE_URL_WINDOW = _("Enter your CloudLinux Network URL.")
SATELLITE_URL_TEXT = _("Please enter the location of your CloudLinux Network "
"server and of its SSL "
"certificate. The SSL certificate is only required "
"if you will be connecting over https (recommended).")
SATELLITE_URL_PROMPT = _("Satellite URL:")
SATELLITE_URL_PROMPT2 = _("SSL certificate:")
SATELLITE_REQUIRED = _("You must enter a valid Satellite URL.")
SSL_REQUIRED = _("If you are using https you must enter the location "
"of a valid SSL certificate.")
# Connect Window
CONNECT_WINDOW = _("Attempting to contact the Spacewalk server.")
CONNECT_WINDOW_TEXT = _("We are attempting to contact the CloudLinux Network "
"Network server at %s.")
CONNECT_WINDOW_TEXT2 = _("A proxy was specified at %s.")
# Start Window
START_REGISTER_WINDOW = _("System Registration")
START_REGISTER_TEXT = _("This assistant will guide you through "
"connecting your system to "
"CloudLinux Network to receive software "
"updates, including "
"security updates, to keep your system supported "
"and compliant. "
"You will need the following at this time:\n\n"
" * A network connection\n"
" * Your CloudLinux Login & password\n"
" * The location of a CloudLinux Network "
"or Proxy\n\n")
# Why Register Window
WHY_REGISTER = _("Why Should I Connect to CLN? ...")
WHY_REGISTER_WINDOW = _("Why Register")
WHY_REGISTER_TEXT = _("Connecting your system to CloudLinux Network allows you to take full "
"advantage of the benefits of a paid subscription, including:")
WHY_REGISTER_SEC = _("Security & Updates:")
WHY_REGISTER_DLD = _("Downloads & Upgrades:")
WHY_REGISTER_SUPP = _("Support:")
WHY_REGISTER_COMP = _("Compliance:")
WHY_REGISTER_SEC_TXT = _("Receive the latest software updates, including security updates, keeping this "
"CloudLinux system updated and secure.")
WHY_REGISTER_DLD_TXT = _("Download installation images for CloudLinux releases, "
"including new releases.")
WHY_REGISTER_SUPP_TXT = _("Access to the technical support experts at CloudLinux for help "
"with any issues you might encounter with this system.")
WHY_REGISTER_COMP_TXT = _("Stay in compliance with your subscription agreement "
"and manage subscriptions "
"for systems connected to your account.")
WHY_REGISTER_TIP = _("Tip: CloudLinux values your privacy: "
"http://www.cloudlinux.com/company/privacy/")
BACK_REGISTER = _("Take me back to the registration")
# Confirm Quit Window
CONFIRM_QUIT = _("Software Update Not Set Up")
CONFIRM_QUIT_SURE = _("Are you sure you don't want to connect your system to CloudLinux Network? "
"You'll miss out on the benefits of a CloudLinux subscription:\n")
CONFIRM_QUIT_WILLNOT = _("You will not be able to take advantage of these subscription privileges without connecting "
"your system to CloudLinux Network.\n")
CONTINUE_REGISTERING = _("Take me back to the setup process.")
REGISTER_LATER2 = _("I'll register later.")
# Info Window
REGISTER_WINDOW = _("CloudLinux Account")
LOGIN_PROMPT = _("Please enter your login information for the %s "
"CloudLinux Network:\n\n")
HOSTED_LOGIN = _("CloudLinux Login:")
LOGIN = _("Login:")
PASSWORD = _("Password:")
LOGIN_TIP = _("Tip: Forgot your login or password? Contact your "
"Satellite's Organization Administrator.")
USER_REQUIRED = _("Please enter a desired login.")
PASSWORD_REQUIRED = _("Please enter and verify a password.")
# OS Release Window
SELECT_OSRELEASE = _("Operating System Release Version")
OS_VERSION = _("Operating System version:")
MINOR_RELEASE = _(" Minor Release: ")
LIMITED_UPDATES = _("Limited Updates Only")
ALL_UPDATES = _("All available updates")
CONFIRM_OS_RELEASE_SELECTION = _("Confirm operating system release selection")
CONFIRM_OS_ALL = _("Your system will be subscribed to the base"
" software channel to receive all available"
" updates.")
# Hardware Window
HARDWARE_WINDOW = _("Create Profile - Hardware")
HARDWARE_WINDOW_DESC1 = _("A Profile Name is a descriptive name that"
" you choose to identify this System Profile"
" on the CloudLinux Network web pages. Optionally,"
" include a computer serial or identification number.")
HARDWARE_WINDOW_DESC2 = _("Additional hardware information including PCI"
" devices, disk sizes and mount points will be"
" included in the profile.")
HARDWARE_WINDOW_CHECKBOX = _("Include the following information about hardware"
" and network:")
# Packages Window
PACKAGES_WINDOW = _("Create Profile - Packages")
PACKAGES_WINDOW_DESC1 = _("RPM information is important to determine what"
" updated software packages are relevant to this"
" system.")
PACKAGES_WINDOW_DESC2 = _("Include RPM packages installed on this system"
" in my System Profile")
PACKAGES_WINDOW_UNCHECK = _("You may deselect individual packages by"
" unchecking them below.")
PACKAGES_WINDOW_PKGLIST = _("Building Package List")
# Product Window
EMAIL = _("*Email Address:")
SYSTEM_ALREADY_SETUP = _("System Already Registered")
SYSTEM_ALREADY_REGISTERED = _("It appears this system has already been set up for software updates:")
SYSTEM_ALREADY_REGISTERED_CONT = _("Are you sure you would like to continue?")
RHSM_SYSTEM_ALREADY_REGISTERED = _("This system has already been registered using CloudLinux Subscription Management.\n\n"
"Your system is being registered again using CloudLinux Network"
" or CloudLinux Network Proxy technology. CloudLinux recommends that customers only register once.\n\n"
"To learn more about RHN Classic/CloudLinux Network registration and technologies please consult this"
" Knowledge Base Article: https://access.redhat.com/kb/docs/DOC-45563")
# Send Window
SEND_WINDOW = _("Send Profile Information to CloudLinux Network")
SEND_WINDOW_DESC = _("We are finished collecting information for the System Profile.\n\n"
"Press \"Next\" to send this System Profile to CloudLinux Network. "
"Click \"Cancel\" and no information will be sent. "
"You can run the registration program later by "
"typing `rhn_register` at the command line.")
# Sending Window
SENDING_WINDOW = _("Sending Profile to CloudLinux Network")
# Finish Window
FINISH_WINDOW = _("Updates Configured")
FINISH_WINDOW_TEXT_TUI = _("You may now run '%s update' from this system's "
"command line to get the latest "
"software updates from CloudLinux Network. You will need to run this "
"periodically to "
"get the latest updates. Alternatively, you may configure this "
"system for automatic software updates (also known as 'auto errata update') "
"via the CloudLinux Network web interface. (Instructions for this are in chapter 6 "
"of the CLN Reference Guide, available from the 'Help' button in the main Red "
"Hat Network Satellite web interface.)") % PM_NAME
# Review Window
REVIEW_WINDOW = _("Review Subscription")
REVIEW_WINDOW_PROMPT = _("Please review the subscription details below:")
SUB_NUM = _("The installation number %s was activated during "
"this system's initial connection to CloudLinux Network.")
SUB_NUM_RESULT = _("Subscriptions have been activated for the following "
"CloudLinux products/services:")
CHANNELS_TITLE = _("Software Channel Subscriptions:")
OK_CHANNELS = _("This system will receive updates from the "
"following software channels:")
CHANNELS_SAT_WARNING = _("Warning: Only installed product listed above will receive "
"updates and support. If you would like "
"to receive updates for additional products, please "
"login to your satellite web interface "
"and subscribe this system to the appropriate "
"software channels. See Kbase article "
"for more details. "
"(http://kbase.redhat.com/faq/docs/DOC-11313)")
PM_PLUGIN_WARNING = _("Warning: %s is not present, could not enable it.\n"
"Automatic updates will not work.") % (PM_PLUGIN_NAME)
PM_PLUGIN_CONF_CHANGED = _("Note: %s has been enabled.") % (PM_PLUGIN_NAME)
PM_PLUGIN_CONF_ERROR = _("Warning: An error occurred during enabling %s.\n"
"%s is not enabled.\n"
"Automatic updates will not work.") % (PM_PLUGIN_NAME, PM_PLUGIN_NAME)
FAILED_CHANNELS = _("You were unable to be subscribed to the following "
"software channels because there were insufficient "
"subscriptions available in your account:")
NO_BASE_CHANNEL = _(
"This system was unable to subscribe to any software channels. Your system "
"will not receive any software updates to keep it secure and supported. "
"Contact your Satellite administrator about this problem. Once you make the "
"appropriate active subscriptions available in your account, you may browse "
"to this system's profile in the CLN web interface and subscribe this system "
"to software channels via the software > software channels tab.")
SLOTS_TITLE = _("Service Level:")
OK_SLOTS = _("Depending on what CloudLinux Network modules are associated with a system, you'll "
"enjoy different benefits. The following are the "
"CloudLinux Network modules associated with this system:")
SLOTS = SLOTS_TITLE + "\n" + OK_SLOTS + "\n%s"
FAILED_SLOTS = _("This system was unable to be associated with the "
"following CLN module(s) because there were "
"insufficient subscriptions available in your account:")
MANAGEMENT = _("Management module: automatic updates, systems "
"grouping, systems permissions, system package profiling, "
"bare-metal provisioning, existing state provisioning, "
"rollbacks, configuration management")
VIRT = _("Virtualization module: software updates for a limited number of "
"virtual guests on this system.")
VIRT_FAILED = _("<b>Warning:</b> Any guest systems you create on this system "
"and register to RHN will consume CloudLinux "
"subscriptions beyond this host system's subscription. You will need "
"to: (1) make a virtualization system entitlement available and "
"(2) apply that system entitlement to this "
"system in CLN's web interface if you do not want virtual guests of "
"this system to consume additional subscriptions.")
NO_SYS_ENTITLEMENT = _("This system was unable to be associated with "
"any CLN service level modules. This system will not receive any software "
"updates to keep it secure and supported. Contace your Satellite administrator "
"about this problem. Once you make the "
"appropriate active subscriptions available in your account, you may browse "
"to this system's profile in the CLN web interface, delete the profile, and "
"re-connect this system to CloudLinux Network.")
ACTIVATION_KEY = _("Universal default activation key detected\n"
"A universal default activation key was detected in your account. "
"This means that a set of properties (software channel subscriptions, "
"package installations, system group memberships, etc.) "
"for your system's connection to CloudLinux Network or CloudLinux Network Proxy"
"have been determined by the activation key rather than your "
"installation number. "
"You may also refer to the RHN Reference Guide, section 6.4.6 for more details "
"about activation keys (http://access.redhat.com/knowledge/docs/Red_Hat_Network/)\n"
"Universal Default activation key: %s")
# Error Messages.
FATAL_ERROR = _("Fatal Error")
WARNING = _("Warning")
HOSTED_CONNECTION_ERROR = _("We can't contact the CloudLinux Network.\n\n"
"Double check the location provided - is '%s' correct?\n"
"If not, you can correct it and try again.\n\n"
"Make sure that the network connection on this system is operational.\n\n"
"This system will not be able to successfully receive software updates "
"from CloudLinux without connecting to a CloudLinux Network server")
BASECHANNELERROR = _("Architecture: %s, OS Release: %s, OS "
"Version: %s")
SERVER_TOO_OLD = _("This server doesn't support functionality "
"needed by this version of the software update"
" setup client. Please try again with a newer "
"server.")
SSL_CERT_ERROR_MSG = _("<b><span size=\"16000\">Incompatible Certificate File</span></b>\n\n"
"The certificate you provided, <b>%s</b>, is not compatible with "
" the CloudLinux Network server at <b>%s</b>. You may want to double-check"
" that you have provided a valid certificate file."
" Are you sure you have provided the correct certificate, and that"
" the certificate file has not been corrupted?\n\n"
"Please try again with a different certificate file.")
SSL_CERT_EXPIRED = _("<b><span size=\"12000\">Incompatible Certificate File</span></b>\n\n"
" The certificate is expired. Please ensure you have the correct "
" certificate and your system time is correct.")
SSL_CERT_FILE_NOT_FOUND_ERRER = _("Please verify the values of sslCACert and serverURL in "
"/etc/sysconfig/rhn/up2date. You can either make the "
"serverURL use http instead of https, or you can "
"download the SSL cert from your Satellite, place it "
"in /usr/share/rhn, and ensure sslCACert points to it.")
ACT_KEY_USAGE_LIMIT_ERROR = _("Problem registering system.\n\n"
"A universal default activation key limits the "
"number of systems which can connect to "
"the CLN organization associated with your "
"login. To allow this system to connect, "
"please contact your CLN organization "
"administrator to increase the number of "
"systems allowed to connect or to disable "
"this universal default activation key. "
"More details can be found in CloudLinux "
"Knowledgebase Article #7924 at "
"http://kbase.redhat.com/faq/FAQ_61_7924.shtm ")
CHANNEL_PAGE_TIP = _("\n Tip: Minor releases with a '*' are currently"
" supported by CloudLinux.\n\n")
CHANNEL_PAGE_WARNING = _("Warning:You will not be able to limit this"
" system to minor release that is older than"
" the recent minor release if you select this"
" option.\n")
CONFIRM_OS_WARNING = _("Your system will be subscribed to %s \n"
"base software channel. You will not be\n"
"able to move this system to an earlier release\n"
"(you will be able to move to a newer release).\n"
"Are you sure you would like to continue?")
# Navigation
OK = _("OK")
ERROR = _("Error")
NEXT = _("Next")
BACK = _("Back")
CANCEL = _("Cancel")
NO_CANCEL = _("No, Cancel")
YES_CONT = _("Yes, Continue")
DESELECT = _("Press <space> to deselect the option.")
hardware_udev.py 0000644 00000031764 15051677404 0007762 0 ustar 00 # Copyright (c) 2010--2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#
import pyudev
import os
import re
from hwdata import PCI, USB
def get_devices():
""" Returns list of dictionaries with keys for every device in system
(values are provide as example):
'bus' : 'pci'
'driver' : 'pcieport-driver'
'pciType' : '1'
'detached' : '0'
'class' : 'OTHER'
'desc' : 'Intel Corporation|5000 Series Chipset PCI Express x4 Port 2'
"""
# listen to uevents on all subsystems
context = pyudev.Context()
devices = context.list_devices()
result = []
for device in devices.match_subsystem("pci").match_subsystem("usb").match_subsystem("block").match_subsystem("ccw").match_subsystem("scsi"):
subsystem = device.subsystem
result_item = {
'bus': subsystem,
'driver': device.driver,
'pciType': _clasify_pci_type(subsystem),
'detached': '0', # always zero?
'class': _clasify_class(device),
'desc': _get_device_desc(device),
}
if result_item['class'] is None:
result_item['class'] = 'OTHER'
if result_item['driver'] is None:
result_item['driver'] = 'unknown'
if subsystem == 'block':
if _get_device_property(device, 'ID_BUS'):
result_item['bus'] = _get_device_property(device, 'ID_BUS')
result_item['device'] = device.sys_name
if device.device_type == 'partition':
# do not report partitions, just whole disks
continue
if _get_device_property(device, 'DM_NAME'):
# LVM device
continue
if _get_device_property(device, 'MAJOR') == '1':
# ram device
continue
if _get_device_property(device, 'MAJOR') == '7':
# character devices for virtual console terminals
continue
# This is interpreted as Physical. But what to do with it?
# result_item['prop1'] = ''
# This is interpreted as Logical. But what to do with it?
# result_item['prop2'] = ''
elif subsystem == 'pci':
pci_class = _get_device_property(device, 'PCI_ID')
if pci_class:
(result_item['prop1'], result_item['prop2']) = pci_class.split(':')
pci_subsys = _get_device_property(device, 'PCI_SUBSYS_ID')
if pci_subsys:
(result_item['prop3'], result_item['prop4']) = pci_subsys.split(':')
elif subsystem == 'usb':
if _get_device_property(device, 'ID_VENDOR_ID'):
result_item['prop1'] = _get_device_property(device, 'ID_VENDOR_ID')
if _get_device_property(device, 'ID_MODEL_ID'):
result_item['prop2'] = _get_device_property(device, 'ID_MODEL_ID')
if _get_device_property(device, 'ID_BUS') and _get_device_property(device, 'ID_BUS') == 'scsi':
if _get_device_property(device, 'ID_PATH') or _get_device_property(device, 'DEVPATH'):
if _get_device_property(device, 'ID_PATH'):
path = _get_device_property(device, 'ID_PATH')
m = re.search('.*scsi-(\d+):(\d+):(\d+):(\d+)', path)
else: # device.has_property('DEVPATH')
path = _get_device_property(device, 'DEVPATH')
m = re.search('.*/(\d+):(\d+):(\d+):(\d+)/block/', path)
if m: # do not fail, if regexp did not match
result_item['prop1'] = m.group(1) # DEV_HOST
result_item['prop2'] = m.group(2) # DEV_ID
result_item['prop3'] = m.group(3) # DEV_CHANNEL
result_item['prop4'] = m.group(4) # DEV_LUN
result.append(result_item)
return result
def get_computer_info():
""" Return dictionaries with keys (values are provided as example):
'system.formfactor': 'unknown'
'system.kernel.version': '2.6.18-128.1.6.el5xen'
'system.kernel.machine': 'i686'
'system.kernel.name': 'Linux'
"""
uname = os.uname()
result = {
'system.kernel.name': uname[0],
'system.kernel.version': uname[2],
'system.kernel.machine': uname[4],
}
return result
#PCI DEVICE DEFINES
# These are taken from pci_ids.h in the linux kernel source and used to
# properly identify the hardware
PCI_BASE_CLASS_STORAGE = '1'
PCI_CLASS_STORAGE_SCSI = '00'
PCI_CLASS_STORAGE_IDE = '01'
PCI_CLASS_STORAGE_FLOPPY = '02'
PCI_CLASS_STORAGE_IPI = '03'
PCI_CLASS_STORAGE_RAID = '04'
PCI_CLASS_STORAGE_OTHER = '80'
PCI_BASE_CLASS_NETWORK = '2'
PCI_CLASS_NETWORK_ETHERNET = '00'
PCI_CLASS_NETWORK_TOKEN_RING = '01'
PCI_CLASS_NETWORK_FDDI = '02'
PCI_CLASS_NETWORK_ATM = '03'
PCI_CLASS_NETWORK_OTHER = '80'
PCI_BASE_CLASS_DISPLAY = '3'
PCI_CLASS_DISPLAY_VGA = '00'
PCI_CLASS_DISPLAY_XGA = '01'
PCI_CLASS_DISPLAY_3D = '02'
PCI_CLASS_DISPLAY_OTHER = '80'
PCI_BASE_CLASS_MULTIMEDIA = '4'
PCI_CLASS_MULTIMEDIA_VIDEO = '00'
PCI_CLASS_MULTIMEDIA_AUDIO = '01'
PCI_CLASS_MULTIMEDIA_PHONE = '02'
PCI_CLASS_MULTIMEDIA_OTHER = '80'
PCI_BASE_CLASS_BRIDGE = '6'
PCI_CLASS_BRIDGE_HOST = '00'
PCI_CLASS_BRIDGE_ISA = '01'
PCI_CLASS_BRIDGE_EISA = '02'
PCI_CLASS_BRIDGE_MC = '03'
PCI_CLASS_BRIDGE_PCI = '04'
PCI_CLASS_BRIDGE_PCMCIA = '05'
PCI_CLASS_BRIDGE_NUBUS = '06'
PCI_CLASS_BRIDGE_CARDBUS = '07'
PCI_CLASS_BRIDGE_RACEWAY = '08'
PCI_CLASS_BRIDGE_OTHER = '80'
PCI_BASE_CLASS_COMMUNICATION = '7'
PCI_CLASS_COMMUNICATION_SERIAL = '00'
PCI_CLASS_COMMUNICATION_PARALLEL = '01'
PCI_CLASS_COMMUNICATION_MULTISERIAL = '02'
PCI_CLASS_COMMUNICATION_MODEM = '03'
PCI_CLASS_COMMUNICATION_OTHER = '80'
PCI_BASE_CLASS_INPUT = '9'
PCI_CLASS_INPUT_KEYBOARD = '00'
PCI_CLASS_INPUT_PEN = '01'
PCI_CLASS_INPUT_MOUSE = '02'
PCI_CLASS_INPUT_SCANNER = '03'
PCI_CLASS_INPUT_GAMEPORT = '04'
PCI_CLASS_INPUT_OTHER = '80'
PCI_BASE_CLASS_SERIAL = 'C'
PCI_CLASS_SERIAL_FIREWIRE = '00'
PCI_CLASS_SERIAL_ACCESS = '01'
PCI_CLASS_SERIAL_SSA = '02'
PCI_CLASS_SERIAL_USB = '03'
PCI_CLASS_SERIAL_FIBER = '04'
PCI_CLASS_SERIAL_SMBUS = '05'
def _clasify_pci_type(subsystem):
""" return 1 if device is PCI, otherwise -1 """
if subsystem == 'pci':
return '1'
else:
return '-1'
def _get_device_property(device, prop):
""" return the property of the given device independent of the implementation version """
try:
return device.properties.get(prop)
except AttributeError:
return device.get(prop)
def _clasify_class(device):
""" Clasify type of device. Returned value is one of following string:
NETWORK, KEYBOARD, MOUSE, VIDEO, USB, IDE, SCSI, RAID, MODEM, SCANNER
CAPTURE, AUDIO, FIREWIRE, SOCKET, CDROM, HD, FLOPPY, TAPE, PRINTER, OTHER
or None if it is neither PCI nor USB device.
"""
(base_class, sub_class) = _parse_pci_class(_get_device_property(device, 'PCI_CLASS'))
subsystem = device.subsystem
# network devices
if base_class == PCI_BASE_CLASS_NETWORK:
return 'OTHER' # if set as 'NETWORK' it will not display in HW tab
# input devices
# pci
if base_class == PCI_BASE_CLASS_INPUT:
if sub_class == PCI_CLASS_INPUT_KEYBOARD:
return 'KEYBOARD'
elif sub_class == PCI_CLASS_INPUT_MOUSE:
return 'MOUSE'
# usb
id_serial = _get_device_property(device, 'ID_SERIAL')
if id_serial:
id_serial = id_serial.lower()
# KEYBOARD <-- do this before mouse, some keyboards have built-in mice
if 'keyboard' in id_serial:
return 'KEYBOARD'
# MOUSE
if 'mouse' in id_serial:
return 'MOUSE'
if base_class: # PCI Devices
if base_class == PCI_BASE_CLASS_DISPLAY:
return 'VIDEO'
elif base_class == PCI_BASE_CLASS_SERIAL:
if sub_class == PCI_CLASS_SERIAL_USB:
return 'USB'
elif sub_class == PCI_CLASS_SERIAL_FIREWIRE:
return 'FIREWIRE'
elif base_class == PCI_BASE_CLASS_STORAGE:
if sub_class == PCI_CLASS_STORAGE_IDE:
return 'IDE'
elif sub_class == PCI_CLASS_STORAGE_SCSI:
return 'SCSI'
elif sub_class == PCI_CLASS_STORAGE_RAID:
return 'RAID'
elif sub_class == PCI_CLASS_STORAGE_FLOPPY:
return 'FLOPPY'
elif base_class == PCI_BASE_CLASS_COMMUNICATION and sub_class == PCI_CLASS_COMMUNICATION_MODEM:
return 'MODEM'
elif base_class == PCI_BASE_CLASS_INPUT and sub_class == PCI_CLASS_INPUT_SCANNER:
return 'SCANNER'
elif base_class == PCI_BASE_CLASS_MULTIMEDIA:
if sub_class == PCI_CLASS_MULTIMEDIA_VIDEO:
return 'CAPTURE'
elif sub_class == PCI_CLASS_MULTIMEDIA_AUDIO:
return 'AUDIO'
elif base_class == PCI_BASE_CLASS_BRIDGE and (
sub_class == PCI_CLASS_BRIDGE_PCMCIA or sub_class == PCI_CLASS_BRIDGE_CARDBUS ):
return 'SOCKET'
if subsystem == 'block':
if _get_device_property(device, 'ID_CDROM') or (
_get_device_property(device, 'ID_TYPE') and _get_device_property(device, 'ID_TYPE') == 'cd'):
return 'CDROM'
else:
return 'HD'
elif subsystem == 'sound':
return 'AUDIO'
if subsystem =='scsi':
if device.device_type =='scsi_device':
dev_type = _get_scsi_dev_type(device)
if dev_type == 0 or dev_type == 14:
return 'HD'
elif dev_type == 1:
return 'TAPE'
elif dev_type == 5:
return 'CDROM'
else:
return 'OTHER'
# PRINTER
m = re.search('.*/lp\d+$', device.sys_path)
if m:
return 'PRINTER'
if subsystem == 'scsi':
return 'SCSI'
# Catchall for specific devices, only do this after all the others
if subsystem == 'pci' or subsystem == 'usb':
return 'OTHER'
# No class found
return None
def _get_device_desc(device):
""" Return human readable description of device. """
subsystem = device.subsystem
command = None
result = None
if subsystem == 'pci':
(vendor_id, device_id) = _get_device_property(device, 'PCI_ID').split(':')
pci = PCI()
result = "%s|%s" % (pci.get_vendor(vendor_id), pci.get_device(vendor_id, device_id))
elif subsystem == 'usb':
vendor_id = _get_device_property(device, 'ID_VENDOR_ID')
usb = USB()
if vendor_id:
result = "%s|%s" % (usb.get_vendor(vendor_id), usb.get_device(vendor_id, _get_device_property(device, 'ID_MODEL_ID')))
elif device.device_type == 'usb_interface':
if device.driver == 'usbhid':
result = 'USB HID Interface'
elif device.driver == 'hub':
result = 'USB Hub Interface'
else:
result = 'USB Interface'
elif device.device_type == 'usb_device' and _get_device_property(device, 'PRODUCT'):
(vendor_id, model_id) = _get_device_property(device, 'PRODUCT').split('/')[:2]
# left pad it with 0 to 4 digits
vendor_id = '%.4x' % int(vendor_id, 16)
model_id = '%.4x' % int(model_id, 16)
result = "%s|%s" % (usb.get_vendor(vendor_id), usb.get_device(vendor_id, model_id))
elif subsystem == 'block':
result = _get_device_property(device, 'ID_MODEL')
if result:
return result
else:
return ''
def _parse_pci_class(pci_class):
""" Parse Class Code. Return touple of
[base class code, sub-class code]
You are usually interested to only first two.
The third - "specific register-level programming interface" is ignored.
For details, see the PCI Local Bus Specification 2.1/2.2 Section 6.2.1 Device Identification
"""
if pci_class is None:
return (None, None)
else:
return (pci_class[-6:-4], pci_class[-4:-2])
def _get_scsi_dev_type(device):
""" Return SCSI type of device in raw format as presented in /sys/...devpath../type """
try:
f = open("%s/type" % device.sys_path, 'r')
except IOError:
return -1
result = f.readline()
f.close()
return result
rhnreg.py 0000644 00000076545 15051677404 0006435 0 ustar 00 #
# RHN Registration Client
# Copyright (c) 2000--2016 Red Hat, Inc.
#
# Authors:
# Adrian Likins <alikins@redhat.com>
# Preston Brown <pbrown@redhat.com>
# Daniel Benamy <dbenamy@redhat.com>
import os
import sys
import dbus
import base64
import libxml2
from up2date_client import up2dateUtils
from up2date_client import up2dateErrors
from up2date_client import up2dateAuth
from up2date_client import rhnserver
from up2date_client import pkgUtils
from up2date_client import up2dateLog
from up2date_client import rhnreg_constants
from up2date_client import hardware
from up2date_client.rhnPackageInfo import convertPackagesFromHashToList
from up2date_client.pkgplatform import getPlatform
from rhn.i18n import ustr, sstr
from rhn.tb import raise_with_tb
try: # python2
import urlparse
import xmlrpclib
from types import ListType, TupleType, StringType, UnicodeType, DictType, DictionaryType
except ImportError: # python3
import urllib.parse as urlparse
import xmlrpc.client as xmlrpclib
ListType = list
TupleType = tuple
StringType = bytes
UnicodeType = str
DictType = dict
DictionaryType = dict
long = int
try:
from virtualization import support
except ImportError:
support = None
import gettext
t = gettext.translation('rhn-client-tools', fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, 'ugettext'):
t.ugettext = t.gettext
_ = t.ugettext
# global variables
#SYSID_DIR = /tmp
SYSID_DIR = "/etc/sysconfig/rhn"
REMIND_FILE = "%s/rhn_register_remind" % SYSID_DIR
HW_CODE_FILE = "%s/hw-activation-code" % SYSID_DIR
RHSM_FILE = "/etc/pki/consumer/cert.pem"
JWT_TOKEN = '/etc/sysconfig/rhn/jwt.token'
_human_readable_to_product = {
'CloudLinux OS Shared Pro': 'shared_pro',
'CloudLinux OS Shared': 'shared',
'CloudLinux OS Solo': 'solo',
'CloudLinux OS Admin': 'admin',
}
_product_to_human_readable = {
v: k for k, v in _human_readable_to_product.items()}
from up2date_client import config
cfg = config.initUp2dateConfig()
log = up2dateLog.initLog()
def startRhnsd():
# successful registration. Try to start rhnsd if it isn't running.
if os.access("/usr/sbin/rhnsd", os.R_OK|os.X_OK):
# test for UsrMerge systemd environment
systemd_system_unitdir = "/usr/lib/systemd/system"
systemd_systemctl = "/usr/bin/systemctl"
if not os.access(systemd_systemctl, os.R_OK|os.X_OK):
if os.access("/bin/systemctl", os.R_OK|os.X_OK):
systemd_systemctl = "/bin/systemctl"
systemd_system_unitdir = "/lib/systemd/system"
if os.access("%s/rhnsd.service" % systemd_system_unitdir, os.R_OK):
# systemd
if os.access(systemd_systemctl, os.R_OK|os.X_OK):
os.system("%s enable rhnsd > /dev/null" % systemd_systemctl);
os.system("%s start rhnsd > /dev/null" % systemd_systemctl);
else:
print(_("Warning: unable to enable rhnsd with systemd"))
else:
# SysV init scripts
if os.access("/sbin/chkconfig", os.R_OK|os.X_OK):
os.system("/sbin/chkconfig rhnsd on > /dev/null");
else:
print(_("Warning: unable to enable rhnsd with chkconfig"))
service_path = "/sbin/service"
if not os.access(service_path, os.R_OK|os.X_OK):
if os.access("/usr/sbin/service", os.R_OK|os.X_OK):
service_path = "/usr/sbin/service"
rc = os.system("%s rhnsd status > /dev/null" % service_path)
if rc:
os.system("%s rhnsd start > /dev/null" % service_path)
def getOemInfo():
configFile = cfg["oemInfoFile"] or "/etc/sysconfig/rhn/oeminfo"
if not os.access(configFile, os.R_OK):
return {}
fd = open(configFile, "r")
L = fd.readlines()
info = {}
for i in L:
i = i.strip()
if i == "":
continue
try:
(key, value) = i.split(':')
except ValueError:
raise_with_tb(up2dateErrors.OemInfoFileError(i))
info[key] = value.strip()
return info
def rhsm_registered():
""" Returns true if system is registred using subscription manager """
if os.access(RHSM_FILE, os.R_OK):
statinfo = os.stat(RHSM_FILE)
return statinfo.st_size > 0
else:
return False
def registered():
return os.access(cfg['systemIdPath'], os.R_OK)
def createSystemRegisterRemindFile():
if not os.access(REMIND_FILE, os.R_OK):
# touch the file to tell the applet it needs to remind
# the user to register
fd = open(REMIND_FILE, "w+")
fd.close()
def removeSystemRegisterRemindFile():
if os.access(REMIND_FILE, os.R_OK):
os.unlink(REMIND_FILE)
def _write_secure_file(secure_file, file_contents):
""" Write a file to disk that is not readable by other users. """
dir_name = os.path.dirname(secure_file)
if not os.access(dir_name, os.W_OK):
return False
if os.access(secure_file, os.F_OK):
# already have file there; let's back it up
try:
os.rename(secure_file, secure_file + '.save')
except:
return False
fd = os.open(secure_file, os.O_WRONLY | os.O_CREAT, int('0600', 8))
fd_file = os.fdopen(fd, 'w')
try:
fd_file.write(sstr(file_contents))
finally:
fd_file.close()
return True
def writeSystemId(systemId):
res = _write_secure_file(cfg['systemIdPath'], systemId)
# newer registratio clients will create a file indicating that
# we need to remind the user to register, this removes it
if res:
removeSystemRegisterRemindFile()
updateRhsmStatus()
return res
def extract_system_id():
xpath_str = "//member[name='system_id']/value/string"
systemId = up2dateAuth.getSystemId()
if systemId is None:
return
try:
result = libxml2.parseDoc(systemId)
context = result.xpathNewContext()
system_id = context.xpathEval(xpath_str)[0].content
# remove `ID-` and convert to integer
system_id = int(system_id[3:])
except (IndexError, libxml2.parserError):
log.log_me('systemID file doesn\'t have system_id field or the file is broken')
return
return system_id
def _execute_pre_jwt_update_hook(token: str, allowTransition: bool):
"""
Execute binary file which we use as hook for jwt token updates
"""
import subprocess, os
# during cldeploy we don't have python or any other packages, so just exit
if not os.path.exists('/opt/cloudlinux/venv/bin/python3'):
return
cmd = ['/usr/sbin/cl-pre-jwt-update', '--new-token', token]
if allowTransition:
cmd.append('--allow-transition')
p = subprocess.Popen(cmd)
stdout, stderr = p.communicate()
if p.returncode != 0:
log.log_me("Pre jwt update hook failed with stdout=%s and stderr=%s" % (stdout, stderr))
def _execute_post_jwt_update_hook(allowTransition: bool):
"""
Execute binary file which we use as hook for jwt token updates
"""
import subprocess, os
# during cldeploy we don't have python or any other packages, so just exit
if not os.path.exists('/opt/cloudlinux/venv/bin/python3'):
return
cmd = ['/usr/sbin/cl-post-jwt-update']
if allowTransition:
cmd.append('--allow-transition')
p = subprocess.Popen(cmd)
stdout, stderr = p.communicate()
if p.returncode != 0:
log.log_me("Post jwt update hook failed with stdout=%s and stderr=%s" % (stdout, stderr))
def getAndWriteJWTTokenToFile(systemId, allowTransition = False):
"""
Get a JWT token from CLN and save it to the file
:param systemId: content of file `/etc/sysconfig/rhn/systemid`
:return: None
"""
xmlrpm_server = rhnserver.RhnServer()
try:
result = xmlrpm_server.up2date.getJWTToken(systemId)
except up2dateErrors.UnknownMethodException:
# if CLN doesn't have this method we do nothing
return
except (up2dateErrors.AuthenticationTicketError,
up2dateErrors.RhnUuidUniquenessError,
up2dateErrors.CommunicationError,
up2dateErrors.AuthenticationOrAccountCreationError):
log.log_exception(*sys.exc_info())
return
_execute_pre_jwt_update_hook(result, allowTransition)
_write_secure_file(JWT_TOKEN, result)
_execute_post_jwt_update_hook(allowTransition)
def writeHWCode(hw_activation_code):
"""Returns True if the write is successful or False if it fails."""
return _write_secure_file(HW_CODE_FILE, hw_activation_code + '\n')
def get_virt_info():
"""
This function returns the UUID and virtualization type of this system, if
it is a guest. Otherwise, it returns None. To figure this out, we'll
use a number of heuristics (list in order of precedence):
1. Check /proc/xen/xsd_port. If exists, we know the system is a
host; exit.
2. Check SMBIOS. If vendor='Xen' and UUID is non-zero, we know the
system is a fully-virt guest; exit.
3. Check /sys/hypervisor/uuid. If exists and is non-zero, we know
the system is a para-virt guest; exit.
4. If non of the above checks worked; we know we have a
non-xen-enabled system; exit.
"""
# First, check whether /proc/xen/xsd_port exists. If so, we know this is
# a host system.
try:
if os.path.exists("/proc/xen/xsd_port"):
# Ok, we know this is *at least* a host system. However, it may
# also be a fully-virt guest. Check for that next. If it is, we'll
# just report that instead since we only support one level of
# virtualization.
(uuid, virt_type) = get_fully_virt_info()
return (uuid, virt_type)
except IOError:
# Failed. Move on to next strategy.
pass
# This is not a virt host system. Check if it's a fully-virt guest.
(uuid, virt_type) = get_fully_virt_info()
if uuid is not None:
return (uuid, virt_type)
# This is not a fully virt guest system. Check if it's a para-virt guest.
(uuid, virt_type) = get_para_virt_info()
if uuid is not None:
return (uuid, virt_type)
# If we got here, we have a system that does not have virtualization
# enabled.
return (None, None)
def get_para_virt_info():
"""
This function checks /sys/hypervisor/uuid to see if the system is a
para-virt guest. It returns a (uuid, virt_type) tuple.
"""
try:
uuid_file = open('/sys/hypervisor/uuid', 'r')
uuid = uuid_file.read()
uuid_file.close()
uuid = uuid.lower().replace('-', '').rstrip("\r\n")
virt_type = "para"
return (uuid, virt_type)
except IOError:
# Failed; must not be para-virt.
pass
return (None, None)
def get_fully_virt_info():
"""
This function looks in the SMBIOS area to determine if this is a
fully-virt guest. It returns a (uuid, virt_type) tuple.
"""
vendor = hardware.dmi_vendor()
uuid = hardware.dmi_system_uuid()
if vendor.lower() == "xen":
uuid = uuid.lower().replace('-', '')
virt_type = "fully"
return (uuid, virt_type)
else:
return (None, None)
def _is_host_uuid(uuid):
uuid = eval('0x%s' % uuid)
return long(uuid) == long(0)
def welcomeText():
s = rhnserver.RegistrationRhnServer()
return s.registration.welcome_message()
def getCaps():
s = rhnserver.RegistrationRhnServer()
# figure out if were missing any needed caps
s.capabilities.validate()
def reserveUser(username, password):
s = rhnserver.RegistrationRhnServer()
return s.registration.reserve_user(username, password)
class RegistrationResult:
def __init__(self, systemId, channels, failedChannels, systemSlots,
failedSystemSlots, universalActivationKey, rawDict=None):
# TODO Get rid of rawDict
self._systemId = systemId
self._channels = channels
self._failedChannels = failedChannels
self._systemSlots = systemSlots
self._failedSystemSlots = failedSystemSlots
if len(universalActivationKey) > 0:
self._universalActivationKey = universalActivationKey
else:
self._universalActivationKey = None
self.rawDict = rawDict
def getSystemId(self):
return self._systemId
def getChannels(self):
return self._channels
def getFailedChannels(self):
return self._failedChannels
def getSystemSlots(self):
return self._systemSlots
def getSystemSlotDescriptions(self):
return [self._getSlotDescription(s) for s in self._systemSlots]
def getFailedSystemSlotDescriptions(self):
return [self._getFailedSlotDescription(s) for s in self._failedSystemSlots]
def getUniversalActivationKey(self):
"""Returns None if no universal activation key was used."""
return self._universalActivationKey
def hasBaseAndUpdates(self):
"""Returns True if the system was subscribed to at least one channel
and was given any type of system slot so it will get updates. In other
words, returns True if the system will be getting at least basic
updates.
"""
# If it was subscribed to at least one channel, that must include a
# base channel.
return len(self._channels) > 0 and len(self._systemSlots) > 0
def _getFailedSlotDescription(self, slot):
if slot == 'virtualization_host':
return rhnreg_constants.VIRT + " " + rhnreg_constants.VIRT_FAILED
else:
return self._getSlotDescription(slot)
def _getSlotDescription(self, slot):
if slot == 'enterprise_entitled':
return rhnreg_constants.MANAGEMENT
elif slot == 'virtualization_host':
return rhnreg_constants.VIRT
else:
return slot
def getServerEdition(human_readable: bool = False):
edition_cache_file = '/opt/cloudlinux/cl_edition'
# edition cache does not exist only in the case when
# we did not register server yet
if not os.path.exists(edition_cache_file):
return 'shared'
with open(edition_cache_file) as f:
raw_edition = f.read().strip('\n')
if human_readable:
return raw_edition
return _human_readable_to_product[raw_edition]
def get_users_count_from_cllib():
from subprocess import Popen, PIPE
if not os.path.exists('/opt/cloudlinux/venv/bin'):
raise ValueError()
cmd = '/opt/cloudlinux/venv/bin/python3 -c "from clcommon.cpapi import cpusers; print(cpusers())"'
process = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
output, errors = [result.decode().strip() for result in process.communicate()]
if errors:
raise ValueError()
return len(output[1:-1].split(', '))
def get_users_count_generic():
from up2date_client.clpwd import ClPwd
pwd = ClPwd()
return len(pwd.get_uid_dict())
def countServerUsers():
try:
users_count = get_users_count_from_cllib()
except Exception:
users_count = get_users_count_generic()
return users_count
def checkLicenseKey(activationKey, strictEdition, silentMigration):
try:
licenseInformation = checkKey(activationKey)
except up2dateErrors.CommunicationError as e:
print("%s" % e.errmsg)
sys.exit(1)
except up2dateErrors.UnknownMethodException:
return
currentEdition = getServerEdition()
licenseEdition = licenseInformation['edition']
if licenseEdition == currentEdition:
return
if strictEdition:
print(
"WARNING: Automatic registration in yum transactions is "
"only available when edition matches the provided license. "
"Your current edition is {current_edition} and your license is {new_edition}.".format(
current_edition=_product_to_human_readable[currentEdition],
new_edition=_product_to_human_readable[licenseEdition]
)
)
print("Run clnreg_ks manually to complete registration.")
sys.exit(1)
if not silentMigration:
if not sys.stdin.isatty():
print('Error: interactive input required for edition migration, but tool '
'is running in non-interactive mode. Please try running the tool again '
'in interactive shell or add `--migrate-silently` flag to accept all'
'questions and perform the edition migration silently.')
exit(1)
message = (f"{_product_to_human_readable[currentEdition]} edition installed on your server "
f"does not match license you are trying to register server with: "
f"{_product_to_human_readable[licenseEdition]}. Migration is required. "
f"You may lose access to the services which are not supported by the new edition.")
edition_to_users_limit = {
'admin': 5,
'solo': 1
}
license_users_limit = edition_to_users_limit.get(licenseEdition)
if license_users_limit is not None:
users_on_server = countServerUsers()
if users_on_server > license_users_limit:
print(f"The license you are trying to register with allows a maximum of "
f"{edition_to_users_limit[licenseEdition]} hosting accounts which is less "
f"than {users_on_server} users detected on this server. Aborting.")
sys.exit(1)
else:
message = (f"{message} Also, the license you are trying to register with allows a maximum of "
f"{edition_to_users_limit[licenseEdition]} hosting accounts. "
f"Make sure that your system complies with this requirement.")
_askConfirmation(message)
def _askConfirmation(confirmationMessage: str):
"""
Prints message and makes sure that client is ready for edition migration.
"""
print(confirmationMessage)
response = input("Do you want to continue? [N/y]: ", )
if response.lower() != 'y':
print('Aborted.')
sys.exit(1)
def registerSystem(username = None, password = None,
profileName = None,
token = None, other = None, edition=None):
"""Wrapper for the old xmlrpc to register a system. Activates subscriptions
if a reg num is given.
"""
assert username is None and password is None, \
"username and password usage is deprecated"
auth_dict = { "profile_name" : profileName,
"os_release" : up2dateUtils.getVersion(),
"release_name" : up2dateUtils.getOSRelease(),
"architecture" : up2dateUtils.getArch()
}
# send information about previous registration
system_id_xml = up2dateAuth.getSystemId()
if system_id_xml is not None:
auth_dict["system_id"] = system_id_xml
# dict of other bits to send
if other:
for (key, item) in other.items():
auth_dict[key] = item
if token:
auth_dict["token"] = token
else:
auth_dict["username"] = username
auth_dict["password"] = password
if edition is not None:
auth_dict['edition'] = edition
else:
auth_dict['edition'] = 'solo' \
if os.path.exists('/etc/cloudlinux-edition-solo') \
else 'admin' if os.path.exists('/etc/cloudlinux-edition-admin') else 'shared'
if cfg['supportsSMBIOS']:
auth_dict["smbios"] = _encode_characters(hardware.get_smbios())
s = rhnserver.RegistrationRhnServer()
ret = s.registration.new_system(auth_dict)
return ret
def checkKey(activationKey):
"""
Check the activation key and return it's edition and customer
"""
s = rhnserver.RegistrationRhnServer()
ret = s.registration.license_check(activationKey)
# {'customerId': 10000327, 'edition': 'solo'}
return ret
def updateRhsmStatus():
try:
bus = dbus.SystemBus()
validity_obj = bus.ProxyObjectClass(bus, 'com.redhat.SubscriptionManager',
'/EntitlementStatus', introspect=False)
validity_iface = dbus.Interface(validity_obj,
dbus_interface='com.redhat.SubscriptionManager.EntitlementStatus')
except dbus.DBusException:
# we can't connect to dbus. it's not running, likely from a minimal
# install. we can't do anything here, so just ignore it.
return
try:
validity_iface.check_status()
except dbus.DBusException:
# the call timed out, or something similar. we don't really care
# about a timely reply or what the result might be, we just want
# the method to run. So we can safely ignore this.
pass
def getAvailableChannels(username, password):
s = rhnserver.RegistrationRhnServer()
server_arch = up2dateUtils.getArch()
server_version = up2dateUtils.getVersion()
server_release = up2dateUtils.getRelease()
availableChannels = None
try:
availableChannels = s.registration.available_eus_channels(
username, password,
server_arch, server_version,
server_release)
except xmlrpclib.Fault:
f = sys.exc_info()[1]
if f.faultCode == 99:
raise_with_tb(up2dateErrors.DelayError(f.faultString))
else:
raise
return availableChannels
def registerSystem2(username = None, password = None,
profileName = None, packages = None,
activationKey = None, other = {}):
"""Uses the new xmlrpcs to register a system. Returns a dict instead of just
system id.
The main differences between this and registerSystem and that this doesn't
do activation and does child channel subscriptions if possible. See the
documentation for the xmlrpc handlers in backend for more detail.
If nothing is going to be in other, it can be {} or None.
New in RHEL 5.
"""
if other is None:
other = {}
if activationKey:
assert username is None
assert password is None
assert activationKey is not None
else:
assert username is not None
assert password is not None
assert activationKey is None
for key in other.keys():
assert key in ['registration_number',
'org_id',
'virt_uuid',
'virt_type',
'channel']
if cfg['supportsSMBIOS']:
other["smbios"] = _encode_characters(hardware.get_smbios())
s = rhnserver.RegistrationRhnServer()
if activationKey:
info = s.registration.new_system_activation_key(profileName,
up2dateUtils.getOSRelease(),
up2dateUtils.getVersion(),
up2dateUtils.getArch(),
activationKey,
other)
else:
info = s.registration.new_system_user_pass(profileName,
up2dateUtils.getOSRelease(),
up2dateUtils.getVersion(),
up2dateUtils.getArch(),
username,
password,
other)
log.log_debug("Returned:\n%s" % info)
result = RegistrationResult(info['system_id'],
info['channels'], info['failed_channels'],
info['system_slots'], info['failed_system_slots'],
info['universal_activation_key'],
rawDict=info)
return result
def server_supports_eus():
return cfg["supportsEUS"]
# pylint: disable=unused-argument
def sendHardware(systemId, hardwareList):
# The endpoint that is called in this function (registration.add_hw_profile)
# is disabled on the CLN side, and does not do anything.
# Therefore, we can safely disable this function.
return
# Original code preserved below in case we ever need to re-enable this function.
# def remove_ip6addr(x):
# if x['class'] == 'NETINFO' and 'ip6addr' in x:
# del x['ip6addr']
# return x
# s = rhnserver.RegistrationRhnServer()
# if not s.capabilities.hasCapability('ipv6', 1):
# hardwareList = [remove_ip6addr(i) for i in hardwareList]
# s.registration.add_hw_profile(systemId, _encode_characters(hardwareList))
# pylint: disable=unused-argument
def sendPackages(systemId, packageList):
# The endpoint that is called in this function (registration.add_packages)
# is disabled on the CLN side, and does not do anything.
# Therefore, we can safely disable this function.
return
# Original code preserved below in case we ever need to re-enable this function.
# s = rhnserver.RegistrationRhnServer()
# if not s.capabilities.hasCapability('xmlrpc.packages.extended_profile', 2):
# # for older satellites and hosted - convert to old format
# packageList = convertPackagesFromHashToList(packageList)
# s.registration.add_packages(systemId, packageList)
def sendVirtInfo(systemId):
if support is not None:
support.refresh()
def listPackages(systemId):
s = rhnserver.RegistrationRhnServer()
print(s.registration.list_packages, systemId())
def makeNiceServerUrl(server):
"""Raises up2dateErrors.InvalidProtocolError if the server url has a
protocol specified and it's not http or https.
"""
protocol, host, path, parameters, query, fragmentIdentifier = urlparse.urlparse(server)
if protocol is None or protocol == '':
server = 'https://' + server
# We must call it again because if there wasn't a protocol the
# host will be in path
protocol, host, path, parameters, query, fragmentIdentifier = urlparse.urlparse(server)
if protocol not in ['https', 'http']:
raise up2dateErrors.InvalidProtocolError("You specified an invalid "
"protocol. Only https and "
"http are allowed.")
if path is None or path == '' or path == '/':
path = '/XMLRPC'
server = urlparse.urlunparse((protocol, host, path, parameters, query,
fragmentIdentifier))
# TODO Raise an exception if url isn't valid
return server
def getServerType(serverUrl=None):
"""Returns 'hosted' if the url points to a known hosted server. Otherwise
returns 'satellite'.
"""
return 'satellite'
class ActivationResult:
ACTIVATED_NOW = 0
ALREADY_USED = 1
def __init__(self, status, registrationNumber, channels={}, systemSlots={}):
"""channels and systemSlots are dicts where the key/value pairs are
label (string) / quantity (int).
"""
self._status = status
# TODO Validate reg num
self._regNum = registrationNumber
self._channels = channels
self._systemSlots = systemSlots
def getStatus(self):
return self._status
def getRegistrationNumber(self):
return self._regNum
def getChannelsActivated(self):
"""Returns a dict- the key/value pairs are label/quantity."""
return self._channels
def getSystemSlotsActivated(self):
"""Returns a dict- the key/value pairs are label/quantity."""
return self._systemSlots
def _encode_characters(*args):
""" All the data we gathered from dmi, bios, gudev are in utf-8,
we need to convert characters beyond ord(127) - e.g \xae to unicode.
"""
result=[]
for item in args:
item_type = type(item)
if item_type == StringType:
item = ustr(item)
elif item_type == TupleType:
item = tuple(_encode_characters(i) for i in item)
elif item_type == ListType:
item = [_encode_characters(i) for i in item]
elif item_type == DictType or item_type == DictionaryType:
item = dict([(_encode_characters(name, val)) for name, val in item.items()])
# else: numbers or UnicodeType - are safe
result.append(item)
if len(result) == 1:
return result[0]
else:
return tuple(result)
def _activate_hardware(login, password):
# Read the asset code from the hardware.
activateHWResult = None
hardwareInfo = None
hw_activation_code = None
try:
hardwareInfo = hardware.get_hal_system_and_smbios()
hardwareInfo = _encode_characters(hardwareInfo)
except:
log.log_me("There was an error while reading the hardware "
"info from the bios. Traceback:\n")
log.log_exception(*sys.exc_info())
if hardwareInfo is not None:
try:
activateHWResult = activateHardwareInfo(
login, password, hardwareInfo)
if activateHWResult.getStatus() == ActivationResult.ACTIVATED_NOW:
hw_activation_code = activateHWResult.getRegistrationNumber()
writeHWCode(hw_activation_code)
except up2dateErrors.NotEntitlingError:
log.log_debug('There are are no entitlements associated '
'with this hardware.')
except up2dateErrors.InvalidRegistrationNumberError:
log.log_debug('The hardware id was not recognized as valid.')
return hw_activation_code
def activateHardwareInfo(username, password, hardwareInfo, orgId=None):
"""Tries to activate an entitlement linked to the hardware info that we
read from the bios.
Returns an ActivationResult.
Can raise:
Invalid number.
Hardware info is not entitling.
Communication errors, etc
"""
## import pprint
## pprint.pprint(hardwareInfo)
other = {}
if orgId:
other = {'org_id': orgId}
server = rhnserver.RegistrationRhnServer()
result = server.registration.activate_hardware_info(username, password,
hardwareInfo, other)
statusCode = result['status_code']
regNum = result['registration_number']
log.log_debug('Server returned status code %s' % statusCode)
if statusCode == 0:
return ActivationResult(ActivationResult.ACTIVATED_NOW, regNum)
elif statusCode == 1:
return ActivationResult(ActivationResult.ALREADY_USED, regNum)
else:
message = "The server returned unknown status code %s while activating" \
" the hardware info." % statusCode
raise up2dateErrors.CommunicationError(message)
def spawnRhnCheckForUI():
if os.access("/usr/sbin/rhn_check", os.R_OK|os.X_OK):
from subprocess import Popen, PIPE
p = Popen(["/usr/sbin/rhn_check"], stdin=PIPE, stdout=PIPE, \
stderr=PIPE)
map(lambda x:log.log_me(x), p.stdout.readlines() + \
p.stderr.readlines())
else:
log.log_me("Warning: unable to run rhn_check")
if getPlatform() == 'deb':
def pluginEnable():
"""On Debian no extra action for plugin is needed"""
return 1, 0
else:
from up2date_client.pmPlugin import pluginEnable
capabilities.py 0000644 00000016434 15051677404 0007570 0 ustar 00
from up2date_client import config
from up2date_client import up2dateErrors
try: # python2
import UserDict
except ImportError: # python3
import collections as UserDict
import gettext
t = gettext.translation('rhn-client-tools', fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, 'ugettext'):
t.ugettext = t.gettext
_ = t.ugettext
# a dict with "capability name" as the key, and the version
# as the value.
neededCaps = {"caneatCheese": {'version':"21"},
"supportsAutoUp2dateOption": {'version': "1"},
"registration.finish_message": {'version': "1"},
"xmlrpc.packages.extended_profile": {'version':"1"},
"registration.delta_packages": {'version':"1"},
"registration.update_contact_info": {'version': "1"},
"registration.extended_update_support": {"version" : "1"},
"registration.smbios": {"version" : "1"}}
def parseCap(capstring):
value = None
caps = capstring.split(',')
capslist = []
for cap in caps:
try:
(key_version, value) = [i.strip() for i in cap.split("=", 1)]
except ValueError:
# Bad directive: not in 'a = b' format
continue
# parse out the version
# lets give it a shot sans regex's first...
(key,version) = key_version.split("(", 1)
# just to be paranoid
if version[-1] != ")":
print("something broke in parsing the capabilited headers")
#FIXME: raise an approriate exception here...
# trim off the trailing paren
version = version[:-1]
data = {'version': version, 'value': value}
capslist.append((key, data))
return capslist
class Capabilities(UserDict.UserDict):
def __init__(self):
UserDict.UserDict.__init__(self)
self.missingCaps = {}
#self.populate()
# self.validate()
self.neededCaps = neededCaps
self.cfg = config.initUp2dateConfig()
def populate(self, headers):
for key, val in headers.items():
if key.lower() == "x-rhn-server-capability":
capslist = parseCap(val)
for (cap,data) in capslist:
self.data[cap] = data
def parseCapVersion(self, versionString):
index = versionString.find('-')
# version of "-" is bogus, ditto for "1-"
if index > 0:
rng = versionString.split("-")
start = rng[0]
end = rng[1]
versions = range(int(start), int(end)+1)
return versions
vers = versionString.split(':')
if len(vers) > 1:
versions = [int(a) for a in vers]
return versions
return [int(versionString)]
def validateCap(self, cap, capvalue):
if not cap in self.data:
errstr = _("This client requires the server to support %s, which the current " \
"server does not support") % cap
self.missingCaps[cap] = None
else:
data = self.data[cap]
# DOES the server have the version we need
if int(capvalue['version']) not in self.parseCapVersion(data['version']):
self.missingCaps[cap] = self.neededCaps[cap]
def validate(self):
for key in self.neededCaps.keys():
self.validateCap(key, self.neededCaps[key])
self.workaroundMissingCaps()
def setConfig(self, key, configItem):
if key in self.tmpCaps:
self.cfg[configItem] = 0
del self.tmpCaps[key]
else:
self.cfg[configItem] = 1
def workaroundMissingCaps(self):
# if we have caps that we know we want, but we can
# can work around, setup config variables here so
# that we know to do just that
self.tmpCaps = self.missingCaps
# this is an example of how to work around it
key = 'caneatCheese'
if key in self.tmpCaps:
# do whatevers needed to workaround
del self.tmpCaps[key]
else:
# we support this, set a config option to
# indicate that possibly
pass
# dict of key to configItem, and the config item that
# corresponds with it
capsConfigMap = {'supportsAutoUp2dateOption': 'supportsAutoUp2dateOption',
'registration.finish_message': 'supportsFinishMessage',
"registration.update_contact_info" : 'supportsUpdateContactInfo',
"registration.delta_packages" : 'supportsDeltaPackages',
"xmlrpc.packages.extended_profile" : 'supportsExtendedPackageProfile',
"registration.extended_update_support" : "supportsEUS",
"registration.smbios" : "supportsSMBIOS"}
for key in capsConfigMap.keys():
self.setConfig(key, capsConfigMap[key])
# if we want to blow up on missing caps we cant eat around
missingCaps = []
wrongVersionCaps = []
if len(self.tmpCaps):
for cap in self.tmpCaps:
capInfo = self.tmpCaps[cap]
if capInfo == None:
# it's completly mssing
missingCaps.append((cap, capInfo))
else:
wrongVersionCaps.append((cap, capInfo))
errString = ""
errorList = []
if len(wrongVersionCaps):
for (cap, capInfo) in wrongVersionCaps:
errString = errString + "Needs %s of version: %s but server has version: %s\n" % (cap,
capInfo['version'],
self.data[cap]['version'])
errorList.append({"capName":cap, "capInfo":capInfo, "serverVersion":self.data[cap]})
if len(missingCaps):
for (cap, capInfo) in missingCaps:
errString = errString + "Needs %s but server does not support that capability\n" % (cap)
errorList.append({"capName":cap, "capInfo":capInfo, "serverVersion":""})
if len(errString):
raise up2dateErrors.ServerCapabilityError(errString, errorList)
def hasCapability(self, capability, version=None):
"""Checks if the server supports a capability and optionally a version.
Returns True or False.
This complements the neededCaps mechanism provided by this module.
Using hasCapability makes it easier to do something only if the server
supports it or to put workaround code in the user of this class. The
neededCaps mechanism makes it easier to put workaround code in this
module, which makes sense if it is to be shared.
'capability' should be a string such as 'registration.foobar'. It can
be a capability in 'neededCaps' above or one that isn't there. 'version'
can be a string (where isdigit() is True) or an int.
"""
assert version is None or str(version).isdigit()
if not capability in self.data:
return False
if version:
data = self.data[capability]
if int(version) not in self.parseCapVersion(data['version']):
return False
return True
tui.py 0000644 00000127315 15051677404 0005741 0 ustar 00 #
# TUI for RHN Registration
# Copyright (c) 2000--2020 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#
from os import geteuid
import sys
import gettext
t = gettext.translation('rhn-client-tools', fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, 'ugettext'):
t.ugettext = t.gettext
_ = t.ugettext
import snack
import signal
from up2date_client import rhnreg, hardware
from up2date_client import up2dateErrors
from up2date_client import up2dateUtils
from up2date_client import pkgUtils
from up2date_client import up2dateLog
from up2date_client import config
from up2date_client.config import convert_url_from_puny
from up2date_client import up2dateAuth
from rhn import rpclib
from rhn.connections import idn_puny_to_unicode
from rhn.i18n import sstr
from up2date_client.pmPlugin import PM_PLUGIN_NAME, PM_PLUGIN_CONF
from up2date_client.rhnreg_constants import *
log = up2dateLog.initLog()
cfg = config.initUp2dateConfig()
def ErrorWindow(screen, errmsg):
snack.ButtonChoiceWindow(screen, sstr(ERROR), sstr(u"%s" % errmsg),
[sstr(BACK)])
def FatalErrorWindow(screen, errmsg):
snack.ButtonChoiceWindow(screen, sstr(FATAL_ERROR), sstr(u"%s" % errmsg),
[sstr(OK)])
screen.finish()
sys.exit(1)
def WarningWindow(screen, errmsg):
snack.ButtonChoiceWindow(screen, sstr(WARNING), sstr("%s" % errmsg),
[sstr(OK)])
screen.finish()
def ConfirmQuitWindow(screen):
button = snack.ButtonChoiceWindow(screen, sstr(CONFIRM_QUIT),
sstr(CONFIRM_QUIT_SURE) + "\n" + \
sstr(WHY_REGISTER_SEC) + "\n" + \
sstr(WHY_REGISTER_SEC_TXT) + "\n\n" + \
sstr(WHY_REGISTER_DLD) + "\n" + \
sstr(WHY_REGISTER_DLD_TXT) + "\n\n" + \
sstr(WHY_REGISTER_SUPP) + "\n" + \
sstr(WHY_REGISTER_SUPP_TXT) + "\n\n" + \
sstr(WHY_REGISTER_COMP) + "\n" + \
sstr(WHY_REGISTER_COMP_TXT) + "\n\n" + \
sstr(CONFIRM_QUIT_WILLNOT) + "\n" + \
sstr(WHY_REGISTER_TIP),
[sstr(CONTINUE_REGISTERING), sstr(REGISTER_LATER2)],
width = 70)
if button == sstr(REGISTER_LATER2).lower():
screen.finish()
return 1
else:
return 0
def tui_call_wrapper(screen, func, *params):
try:
results = func(*params)
except up2dateErrors.CommunicationError:
ErrorWindow(screen, HOSTED_CONNECTION_ERROR % config.getServerURL()[0])
raise sys.exc_info()[1]
except up2dateErrors.SSLCertificateVerifyFailedError:
ErrorWindow(screen, e.errmsg)
raise sys.exc_info()[1]
except up2dateErrors.NoBaseChannelError:
e = sys.exc_info()[1]
FatalErrorWindow(screen, e.errmsg + '\n' +
BASECHANNELERROR % (up2dateUtils.getArch(),
up2dateUtils.getOSRelease(),
up2dateUtils.getVersion()))
except up2dateErrors.SSLCertificateFileNotFound:
e = sys.exc_info()[1]
ErrorWindow(screen, e.errmsg + '\n\n' +
SSL_CERT_FILE_NOT_FOUND_ERRER)
raise e
return results
class WindowSkipException(Exception):
pass
class AlreadyRegisteredWindow:
name = "AlreadyRegisteredWindow"
def __init__(self, screen, tui):
if not rhnreg.registered() or tui.test:
raise WindowSkipException()
self.screen = screen
self.tui = tui
size = snack._snack.size()
systemIdXml = rpclib.xmlrpclib.loads(up2dateAuth.getSystemId())
oldUsername = systemIdXml[0][0]['username']
oldsystemId = systemIdXml[0][0]['system_id']
toplevel = snack.GridForm(self.screen, sstr(SYSTEM_ALREADY_SETUP), 1, 2)
self.bb = snack.ButtonBar(self.screen,
[(sstr(YES_CONT), "next"),
(sstr(NO_CANCEL), "exit")])
toplevel.add(self.bb, 0, 1, growx = 1)
tb = snack.Textbox(size[0]-30, size[1]-20,
sstr(SYSTEM_ALREADY_REGISTERED + "\n\n"
+ _("Spacewalk Location:") + " " + convert_url_from_puny(self.tui.serverURL) + "\n"
+ _("Login:") + " " + oldUsername + "\n"
+ _("System ID:") + " " + oldsystemId + "\n\n"
+ SYSTEM_ALREADY_REGISTERED_CONT + "\n"),
1, 1)
toplevel.add(tb, 0, 0, padding = (0, 0, 0, 1))
self.g = toplevel
def saveResults(self):
pass
def run(self):
log.log_debug("Running %s" % self.name)
result = self.g.runOnce()
button = self.bb.buttonPressed(result)
if result == "F12":
return "next"
return button
class SatelliteUrlWindow:
name = "SatelliteUrlWindow"
def __init__(self, screen, tui):
self.screen = screen
self.tui = tui
self.tui.alreadyRegistered = 0
self.server = convert_url_from_puny(self.tui.serverURL)
fixed_server_url = rhnreg.makeNiceServerUrl(self.server)
#Save the config only if the url is different
if fixed_server_url != self.server:
self.server = fixed_server_url
config.setServerURL(self.server)
cfg.save()
size = snack._snack.size()
toplevel = snack.GridForm(screen, sstr(SATELLITE_URL_WINDOW),
1, 4)
prompt_text = SATELLITE_URL_TEXT
url_label = SATELLITE_URL_PROMPT
ssl_label = SATELLITE_URL_PROMPT2
label = snack.Textbox(size[0]-10, 3,
sstr(prompt_text),
scroll = 0, wrap = 1)
toplevel.add(label, 0, 0, anchorLeft = 1)
# spacer
label = snack.Label(sstr(""))
toplevel.add(label, 0, 1)
grid = snack.Grid(2, 3)
label = snack.Label(sstr(url_label))
grid.setField(label, 0, 0, padding = (0, 0, 1, 0),
anchorRight = 1)
self.urlEntry = snack.Entry(40)
self.urlEntry.set(self.server)
grid.setField(self.urlEntry, 1, 0, anchorLeft = 1)
label = snack.Label(sstr(ssl_label))
grid.setField(label, 0, 1, padding = (0, 0, 1, 0),
anchorRight = 1)
self.sslEntry = snack.Entry(40)
self.sslEntry.set(tui.sslCACert)
grid.setField(self.sslEntry, 1, 1, anchorLeft = 1)
toplevel.add(grid, 0, 2)
# BUTTON BAR
self.bb = snack.ButtonBar(screen,
[(sstr(NEXT), "next"),
(sstr(BACK), "back"),
(sstr(CANCEL), "cancel")])
toplevel.add(self.bb, 0, 3, padding = (0, 1, 0, 0),
growx = 1)
self.g = toplevel
def validateFields(self):
if self.urlEntry.value() == "":
snack.ButtonChoiceWindow(self.screen, sstr(ERROR),
sstr(SATELLITE_REQUIRED),
buttons = [sstr(OK)])
self.g.setCurrent(self.urlEntry)
return 0
if (self.urlEntry.value()[:5] == 'https' and
self.sslEntry.value() == ""):
snack.ButtonChoiceWindow(self.screen, sstr(ERROR),
sstr(SSL_REQUIRED),
buttons = [sstr(OK)])
self.g.setCurrent(self.sslEntry)
return 0
return 1
def saveResults(self):
serverEntry = self.urlEntry.value()
# fix up the server url, E.G. if someone left off /XMLRPC
fixed_server_url = rhnreg.makeNiceServerUrl(serverEntry)
if fixed_server_url != serverEntry:
serverEntry = fixed_server_url
self.tui.serverURL = serverEntry
self.tui.sslCACert = self.sslEntry.value()
config.setServerURL(serverEntry)
config.setSSLCACert(self.sslEntry.value())
cfg.save()
def run(self):
log.log_debug("Running %s" % self.name)
self.screen.refresh()
valid = 0
while not valid:
result = self.g.run()
button = self.bb.buttonPressed(result)
if result == "F12":
button = "next"
if button == "next":
valid = self.validateFields()
else:
break
self.screen.popWindow()
return button
class AlreadyRegisteredSubscriptionManagerWindow:
name = "AlreadyRegisteredSubscriptionManagerWindow"
def __init__(self, screen, tui):
if not rhnreg.rhsm_registered() or tui.test:
raise WindowSkipException()
self.screen = screen
self.tui = tui
size = snack._snack.size()
toplevel = snack.GridForm(self.screen, sstr(SYSTEM_ALREADY_SETUP), 1, 2)
self.bb = snack.ButtonBar(self.screen,
[(sstr(YES_CONT), "next"),
(sstr(NO_CANCEL), "exit")])
toplevel.add(self.bb, 0, 1, growx = 1)
tb = snack.Textbox(size[0]-30, size[1]-20,
sstr(WARNING + "\n\n"
+ RHSM_SYSTEM_ALREADY_REGISTERED + "\n\n"
+ SYSTEM_ALREADY_REGISTERED_CONT + "\n"),
1, 1)
toplevel.add(tb, 0, 0, padding = (0, 0, 0, 1))
self.g = toplevel
def saveResults(self):
pass
def run(self):
log.log_debug("Running %s" % self.name)
result = self.g.runOnce()
button = self.bb.buttonPressed(result)
if result == "F12":
return "next"
return button
class ConnectWindow:
name = "ConnectWindow"
def __init__(self, screen, tui):
self.screen = screen
self.tui = tui
size = snack._snack.size()
self.server = convert_url_from_puny(self.tui.serverURL)
self.proxy = cfg['httpProxy']
toplevel = snack.GridForm(self.screen, sstr(CONNECT_WINDOW), 1, 1)
text = CONNECT_WINDOW_TEXT % self.server + "\n\n"
if self.proxy:
text += CONNECT_WINDOW_TEXT2 % self.proxy
tb = snack.Textbox(size[0]-30, size[1]-20,
sstr(text),
1, 1)
toplevel.add(tb, 0, 0, padding = (0, 0, 0, 1))
self.g = toplevel
def run(self):
log.log_debug("Running %s" % self.name)
# We draw and display the window. The window gets displayed as
# long as we are attempting to connect to the server. Once we
# connect the window is gone.
result = self.g.draw()
self.screen.refresh()
# try to connect given the server url and ssl cert provided. If
# unsuccessful, return to previous screen to allow user to fix.
try:
tui_call_wrapper(self.screen, rhnreg.getCaps)
except:
return "back"
self.screen.popWindow()
# Just return next, although the user wouldn't have actually pressed
# anything.
return "next"
def saveResults(self):
pass
class StartWindow:
name = "StartWindow"
def __init__(self, screen, tui):
self.screen = screen
self.tui = tui
size = snack._snack.size()
toplevel = snack.GridForm(self.screen, sstr(START_REGISTER_WINDOW),
1, 2)
start_register_text = sstr(START_REGISTER_TEXT)
tb = snack.Textbox(size[0]-10, size[1]-14, start_register_text, 1, 1)
toplevel.add(tb, 0, 0, padding = (0, 0, 0, 1))
self.bb = snack.ButtonBar(self.screen,
[(sstr(WHY_REGISTER), "why_register"),
(sstr(NEXT), "next"),
(sstr(CANCEL), "cancel")])
toplevel.add(self.bb, 0, 1, growx = 1)
self.g = toplevel
def saveResults(self):
pass
def run(self):
log.log_debug("Running %s" % self.name)
result = self.g.runOnce()
button = self.bb.buttonPressed(result)
if result == "F12":
return "next"
elif button == "why_register":
why_reg_win = WhyRegisterWindow(self.screen, self.tui)
why_reg_win.run()
return button
return button
class WhyRegisterWindow:
name = "WhyRegisterWindow"
def __init__(self, screen, tui):
self.screen = screen
self.tui = tui
size = snack._snack.size()
toplevel = snack.GridForm(self.screen, sstr(WHY_REGISTER_WINDOW),
1, 2)
why_register_text = WHY_REGISTER_TEXT + "\n\n" + \
WHY_REGISTER_SEC + "\n" + \
WHY_REGISTER_SEC_TXT + "\n\n" + \
WHY_REGISTER_DLD + "\n" + \
WHY_REGISTER_DLD_TXT + "\n\n" + \
WHY_REGISTER_SUPP + "\n" + \
WHY_REGISTER_SUPP_TXT + "\n\n" + \
WHY_REGISTER_COMP + "\n" + \
WHY_REGISTER_COMP_TXT + "\n\n" + \
WHY_REGISTER_TIP
tb = snack.Textbox(size[0]-10, size[1]-14, sstr(why_register_text), 1, 1)
toplevel.add(tb, 0, 0, padding = (0, 0, 0, 1))
self.bb = snack.ButtonBar(self.screen,
[(sstr(BACK_REGISTER), "back")])
toplevel.add(self.bb, 0, 1, growx = 1)
self.g = toplevel
def run(self):
log.log_debug("Running %s" % self.name)
result = self.g.runOnce()
button = self.bb.buttonPressed(result)
return button
class InfoWindow:
name = "InfoWindow"
def __init__(self, screen, tui):
self.screen = screen
self.tui = tui
self.tui.alreadyRegistered = 0
self.server = self.tui.serverURL
size = snack._snack.size()
toplevel = snack.GridForm(screen, sstr(REGISTER_WINDOW), 1, 4)
decoded_server = convert_url_from_puny(self.server)
url = self.server
if decoded_server != self.server:
url += " (%s)" % decoded_server
login_prompt = LOGIN_PROMPT % url
login_label = LOGIN
login_tip = LOGIN_TIP
label = snack.Textbox(size[0]-10, 3,
sstr(login_prompt),
scroll = 0, wrap = 1)
toplevel.add(label, 0, 0, anchorLeft = 1)
grid = snack.Grid(2, 3)
label = snack.Label(sstr(login_label))
grid.setField(label, 0, 0, padding = (0, 0, 1, 0),
anchorRight = 1)
self.userNameEntry = snack.Entry(20)
self.userNameEntry.set(tui.userName)
grid.setField(self.userNameEntry, 1, 0, anchorLeft = 1)
label = snack.Label(sstr(PASSWORD))
grid.setField(label, 0, 1, padding = (0, 0, 1, 0),
anchorRight = 1)
try:
self.passwordEntry = snack.Entry(20, password = 1)
except TypeError:
self.passwordEntry = snack.Entry(20, hidden = 1)
self.passwordEntry.set(tui.password)
grid.setField(self.passwordEntry, 1, 1, anchorLeft = 1)
toplevel.add(grid, 0, 1)
label = snack.TextboxReflowed(size[0]-10, sstr(login_tip))
toplevel.add(label, 0, 2, anchorLeft=1)
# BUTTON BAR
self.bb = snack.ButtonBar(screen,
[(sstr(NEXT), "next"),
(sstr(BACK), "back"),
(sstr(CANCEL), "cancel")])
toplevel.add(self.bb, 0, 3, padding = (0, 1, 0, 0),
growx = 1)
self.g = toplevel
def validateFields(self):
if self.userNameEntry.value() == "":
snack.ButtonChoiceWindow(self.screen, sstr(ERROR),
sstr(USER_REQUIRED),
buttons = [sstr(OK)])
self.g.setCurrent(self.userNameEntry)
return 0
if self.passwordEntry.value() == "":
snack.ButtonChoiceWindow(self.screen, sstr(ERROR),
sstr(PASSWORD_REQUIRED),
buttons = [sstr(OK)])
self.g.setCurrent(self.passwordEntry)
return 0
try:
self.tui.alreadyRegistered = rhnreg.reserveUser(self.userNameEntry.value(), self.passwordEntry.value())
except up2dateErrors.ValidationError:
e = sys.exc_info()[1]
snack.ButtonChoiceWindow(self.screen, sstr(_("Error")), sstr(_("The server indicated an error:\n")) + sstr(e.errmsg), buttons = [sstr(_("OK"))])
self.g.setCurrent(self.userNameEntry)
return 0
except up2dateErrors.CommunicationError:
e = sys.exc_info()[1]
FatalErrorWindow(self.screen, _("There was an error communicating with the registration server:\n") + e.errmsg)
return 1
def saveResults(self):
self.tui.userName = self.userNameEntry.value()
self.tui.password = self.passwordEntry.value()
def run(self):
log.log_debug("Running %s" % self.name)
self.screen.refresh()
valid = 0
while not valid:
result = self.g.run()
button = self.bb.buttonPressed(result)
if result == "F12":
button = "next"
if button == "next":
valid = self.validateFields()
else:
break
self.screen.popWindow()
return button
class OSReleaseWindow:
name = "OSReleaseWindow"
def __init__(self, screen, tui):
self.tui = tui
if not rhnreg.server_supports_eus():
log.log_debug("Server does not support EUS, skipping OSReleaseWindow")
raise WindowSkipException()
self.available_channels = rhnreg.getAvailableChannels(
tui.userName, tui.password)
if len(self.available_channels['channels']) < 1:
log.log_debug("No available EUS channels, skipping OSReleaseWindow")
raise WindowSkipException()
self.screen = screen
self.size = snack._snack.size()
self.selectChannel = False
toplevel = snack.GridForm(self.screen, sstr(SELECT_OSRELEASE), 1, 7)
self.g = toplevel
self.ostext = snack.TextboxReflowed(self.size[0]-10, sstr(OS_VERSION))
toplevel.add(self.ostext, 0, 0, anchorLeft = 1)
optiontext1 = sstr(LIMITED_UPDATES)
if self.tui.limited_updates_button:
self.limited_updates_button = snack.SingleRadioButton(optiontext1,
None, isOn = 1)
else:
self.limited_updates_button = snack.SingleRadioButton(optiontext1,
None)
toplevel.add(self.limited_updates_button, 0, 1, padding = (0, 1, 0, 1),
anchorLeft = 1)
self.sublabel = snack.Label(sstr(MINOR_RELEASE))
toplevel.add(self.sublabel, 0, 2, anchorLeft = 1)
self.channelList = snack.Listbox(self.size[1]-22, 1,
width = self.size[0]-10)
toplevel.add(self.channelList, 0, 3)
for key, value in sorted(self.available_channels['channels'].items(), key=lambda a:a[0]):
if key in self.available_channels['receiving_updates']:
value = value + "*"
self.channelList.append(" " + value, key)
self.tip = snack.TextboxReflowed(self.size[0]-10, sstr(CHANNEL_PAGE_TIP))
toplevel.add(self.tip, 0, 4, anchorLeft = 1)
optiontext2 = sstr(ALL_UPDATES)
if self.tui.all_updates_button:
self.all_updates_button = snack.SingleRadioButton(optiontext2,
self.limited_updates_button, isOn=1)
else:
self.all_updates_button = snack.SingleRadioButton(optiontext2,
self.limited_updates_button)
toplevel.add(self.all_updates_button, 0, 5, padding = (0, 0, 0, 1),
anchorLeft = 1)
#self.warning = snack.TextboxReflowed(self.size[0]-10,
# sstr(CHANNEL_PAGE_WARNING))
#toplevel.add(self.warning, 0, 9, anchorLeft = 1)
self.bb = snack.ButtonBar(screen,
[(sstr(NEXT), "next"),
(sstr(BACK), "back"),
(sstr(CANCEL), "cancel")])
toplevel.add(self.bb, 0, 6, growx = 1)
self.screen.refresh()
def run(self):
log.log_debug("Running %s" % self.name)
self.screen.refresh()
valid = "cancel"
while valid == "cancel":
result = self.g.run()
button = self.bb.buttonPressed(result)
if result == "F12":
button = "next"
if button == "next":
valid = self.validateFields()
else:
break
self.screen.popWindow()
return button
def validateFields(self):
msgbox = "ok"
later_release = False
if self.limited_updates_button.selected():
later_release = self.channelList.current() != \
self.available_channels['default_channel']
title = sstr(CONFIRM_OS_RELEASE_SELECTION)
if later_release:
msgbox = snack.ButtonChoiceWindow(self.screen, title,
sstr(CONFIRM_OS_WARNING) % self.channelList.current(),
buttons =[sstr(OK), sstr(CANCEL)])
return msgbox
if self.all_updates_button.selected() or later_release:
msgbox = snack.ButtonChoiceWindow(self.screen, title,
sstr(CONFIRM_OS_ALL), buttons =[sstr(OK), sstr(CANCEL)])
return msgbox
return msgbox
def saveResults(self):
# if limited updates save the channel and selction
# for future use
self.tui.other.pop('channel', None)
if self.limited_updates_button.selected():
log.log_debug("Selected Channel %s" % self.channelList.current())
self.tui.other['channel'] = self.channelList.current()
self.tui.limited_updates_button = self.limited_updates_button.selected()
self.tui.all_updates_button = 0
# saving data for all updates button
if self.all_updates_button.selected():
self.tui.all_updates_button = self.all_updates_button.selected()
self.tui.limited_updates_button = 0
class HardwareWindow:
name = "HardwareWindow"
def __init__(self, screen, tui):
self.screen = screen
self.tui = tui
size = snack._snack.size()
#get the virtualization uuid and set it to other.
(virt_uuid, virt_type) = rhnreg.get_virt_info()
if not virt_uuid is None:
self.tui.other['virt_uuid'] = virt_uuid
self.tui.other['virt_type'] = virt_type
# read all hardware in
tui.hardware = hardware.Hardware()
toplevel = snack.GridForm(screen, sstr(HARDWARE_WINDOW), 1, 7)
text = snack.TextboxReflowed(70, sstr(HARDWARE_WINDOW_DESC1))
toplevel.add(text, 0, 0, anchorLeft = 1)
grid = snack.Grid(2, 2)
label = snack.Label(sstr(_("Profile name:")))
grid.setField(label, 0, 0, padding = (0, 0, 1, 0), anchorRight = 1)
self.profileEntry = snack.Entry(40)
grid.setField(self.profileEntry, 1, 0, anchorLeft = 1)
toplevel.add(grid, 0, 1, anchorLeft = 1)
if tui.includeHardware:
self.hardwareButton = snack.Checkbox(sstr(HARDWARE_WINDOW_CHECKBOX), isOn = 1)
else:
self.hardwareButton = snack.Checkbox(sstr(HARDWARE_WINDOW_CHECKBOX))
toplevel.add(self.hardwareButton, 0, 2, padding = (0, 1, 0, 0),
anchorLeft = 1)
label = snack.Label(sstr(DESELECT))
toplevel.add(label, 0, 3, anchorLeft = 1, padding = (0, 0, 0, 1))
grid = snack.Grid(4, 3)
hardware_text = ''
hardware_text += _("Version: ") + sstr(up2dateUtils.getVersion()) + " "
self.versionLabel = snack.Label(sstr(_("Version: ")))
grid.setField(self.versionLabel, 0, 0, padding = (0, 0, 1, 0), anchorLeft = 1)
self.versionLabel2 = snack.Label(sstr(up2dateUtils.getVersion()))
grid.setField(self.versionLabel2, 1, 0, anchorLeft = 1)
hardware_text += _("CPU model: ")
for hw in tui.hardware:
if hw['class'] == 'CPU':
hardware_text += hw['model'] +"\n"
hardware_text += _("Hostname: ")
for hw in tui.hardware:
if hw['class'] == 'NETINFO':
unicode_hostname = idn_puny_to_unicode(hw['hostname'])
hardware_text += unicode_hostname + "\n"
if tui.profileName != "":
self.profileEntry.set(tui.profileName)
else:
self.profileEntry.set(sstr(unicode_hostname))
hardware_text += _("CPU speed: ")
for hw in tui.hardware:
if hw['class'] == 'CPU':
hardware_text += _("%d MHz") % hw['speed'] + " "
hardware_text += _("IP Address: ")
for hw in tui.hardware:
if hw['class'] == 'NETINFO':
if hw['ipaddr']:
hardware_text += hw['ipaddr'] + " "
elif hw['ip6addr']:
hardware_text += hw['ip6addr'] + " "
hardware_text += _("Memory: ")
for hw in tui.hardware:
if hw['class'] == 'MEMORY':
hardware_text += _("%s megabytes") % hw['ram']
tb = snack.TextboxReflowed(80, sstr(hardware_text))
toplevel.add(tb, 0, 4)
self.additionalHWLabel = snack.TextboxReflowed(size[0]-10, sstr(HARDWARE_WINDOW_DESC2))
toplevel.add(self.additionalHWLabel, 0, 5, padding = (0, 1, 0, 0),
anchorLeft = 1)
# BUTTON BAR
self.bb = snack.ButtonBar(screen,
[(sstr(NEXT), "next"),
(sstr(BACK), "back"),
(sstr(CANCEL), "cancel")])
toplevel.add(self.bb, 0, 6, padding = (0, 1, 0, 0),
growx = 1)
self.g = toplevel
# self.screen.gridWrappedWindow(toplevel, 'HardwareWindow', 80, 14)
def saveResults(self):
self.tui.profileName = self.profileEntry.value()
self.tui.includeHardware = self.hardwareButton.selected()
def run(self):
log.log_debug("Running %s" % self.name)
result = self.g.runOnce()
button = self.bb.buttonPressed(result)
if result == "F12":
return "next"
return button
class PackagesWindow:
name = "PackagesWindow"
def __init__(self, screen, tui):
self.screen = screen
self.tui = tui
size = snack._snack.size()
toplevel = snack.GridForm(screen, sstr(PACKAGES_WINDOW), 1, 5)
self.g = toplevel
text = snack.TextboxReflowed(size[0]-10, sstr(PACKAGES_WINDOW_DESC1))
toplevel.add(text, 0, 0, anchorLeft = 1)
self.packagesButton = snack.Checkbox(sstr(PACKAGES_WINDOW_DESC2), 1)
toplevel.add(self.packagesButton, 0, 1, padding = (0, 1, 0, 1),
anchorLeft = 1)
label = snack.Label(sstr(PACKAGES_WINDOW_UNCHECK))
toplevel.add(label, 0, 2, anchorLeft = 1)
#self.packageList = snack.Listbox(size[1]-18, 1, width = size[0]-10)
self.packageList = snack.CheckboxTree(size[1]-18, 1)
toplevel.add(self.packageList, 0, 3)
# do we need to read the packages from disk?
if tui.packageList == []:
self.pwin = snack.GridForm(screen, sstr(PACKAGES_WINDOW_PKGLIST), 1, 1)
self.scale = snack.Scale(40, 100)
self.pwin.add(self.scale, 0, 0)
self.pwin.draw()
self.screen.refresh()
getArch = 0
if rhnreg.cfg['supportsExtendedPackageProfile']:
getArch = 1
tui.packageList = pkgUtils.getInstalledPackageList(getArch=getArch)
self.screen.popWindow()
for package in tui.packageList:
self.packageList.append("%s-%s-%s" % (sstr(package['name']),
sstr(package['version']),
sstr(package['release'])),
item = sstr(package['name']),
selected = 1)
# BUTTON BAR
self.bb = snack.ButtonBar(screen,
[(sstr(NEXT), "next"),
(sstr(BACK), "back"),
(sstr(CANCEL), "cancel")])
toplevel.add(self.bb, 0, 4, padding = (0, 1, 0, 0),
growx = 1)
def setScale(self, amount, total):
self.scale.set(int(((amount * 1.0)/ total) * 100))
self.pwin.draw()
self.screen.refresh()
def saveResults(self):
self.tui.includePackages = self.packagesButton.selected()
selection = self.packageList.getSelection()
for pkg in self.tui.packageList:
if pkg['name'] in selection:
self.tui.selectedPackages.append(pkg)
def run(self):
log.log_debug("Running %s" % self.name)
result = self.g.runOnce()
button = self.bb.buttonPressed(result)
if result == "F12":
return "next"
return button
class SendWindow:
name = "SendWindow"
def __init__(self, screen, tui):
self.screen = screen
self.tui = tui
size = snack._snack.size()
toplevel = snack.GridForm(screen, sstr(SEND_WINDOW), 1, 2)
text = snack.TextboxReflowed(size[0]-15, sstr(SEND_WINDOW_DESC))
toplevel.add(text, 0, 0)
# BUTTON BAR
self.bb = snack.ButtonBar(screen,
[(sstr(NEXT), "next"),
(sstr(BACK), "back"),
(sstr(CANCEL), "cancel")])
toplevel.add(self.bb, 0, 1, padding = (0, 1, 0, 0),
growx = 1)
self.g = toplevel
def saveResults(self):
pass
def run(self):
log.log_debug("Running %s" % self.name)
result = self.g.runOnce()
button = self.bb.buttonPressed(result)
if result == "F12":
return "next"
return button
class SendingWindow:
name = "SendingWindow"
def __init__(self, screen, tui):
self.screen = screen
self.tui = tui
size = snack._snack.size()
self.pwin = snack.GridForm(screen, sstr(SENDING_WINDOW), 1, 1)
self.scale = snack.Scale(40, 100)
self.pwin.add(self.scale, 0, 0)
def run(self):
log.log_debug("Running %s" % self.name)
self.pwin.draw()
self.screen.refresh()
reg_info = None
try:
# reg_info dict contains: 'system_id', 'channels',
# 'failed_channels', 'slots', 'failed_slots'
log.log_debug('other is %s' % str(self.tui.other))
reg_info = rhnreg.registerSystem2(self.tui.userName, self.tui.password,
self.tui.profileName,
other = self.tui.other)
reg_info = reg_info.rawDict
systemId = sstr(reg_info['system_id'])
except up2dateErrors.CommunicationError:
e = sys.exc_info()[1]
FatalErrorWindow(self.screen,
_("Problem registering system:\n") + e.errmsg)
except up2dateErrors.RhnUuidUniquenessError:
e = sys.exc_info()[1]
FatalErrorWindow(self.screen,
_("Problem registering system:\n") + e.errmsg)
except up2dateErrors.InsuffMgmntEntsError:
e = sys.exc_info()[1]
FatalErrorWindow(self.screen,
_("Problem registering system:\n") + e.errmsg)
except up2dateErrors.RegistrationDeniedError:
e = sys.exc_info()[1]
FatalErrorWindow(self.screen,
_("Problem registering system:\n") + e.errmsg)
except up2dateErrors.ActivationKeyUsageLimitError:
FatalErrorWindow(self.screen,
ACT_KEY_USAGE_LIMIT_ERROR)
except:
log.log_exception(*sys.exc_info())
FatalErrorWindow(self.screen, _("Problem registering system."))
# write the system id out.
if not rhnreg.writeSystemId(systemId):
FatalErrorWindow(self.screen,
_("Problem writing out system id to disk."))
self.setScale(1, 4)
# include the info from the oeminfo file as well
self.oemInfo = rhnreg.getOemInfo()
self.setScale(2, 4)
# maybe upload hardware profile
if self.tui.includeHardware:
try:
rhnreg.sendHardware(systemId, self.tui.hardware)
except up2dateErrors.CommunicationError:
e = sys.exc_info()[1]
FatalErrorWindow(self.screen,
_("Problem sending hardware profile:\n") + e.errmsg)
except:
log.log_exception(*sys.exc_info())
FatalErrorWindow(self.screen,
_("Problem sending hardware profile."))
self.setScale(3, 4)
# build up package list if necessary
if self.tui.includePackages:
try:
rhnreg.sendPackages(systemId, self.tui.selectedPackages)
except up2dateErrors.CommunicationError:
e = sys.exc_info()[1]
FatalErrorWindow(self.screen, _("Problem sending package list:\n") + e.errmsg)
except:
log.log_exception(*sys.exc_info())
FatalErrorWindow(self.screen, _("Problem sending package list."))
li = None
try:
li = up2dateAuth.updateLoginInfo()
except up2dateErrors.InsuffMgmntEntsError:
FatalErrorWindow(self.screen, sys.exc_info()[1])
# Send virtualization information to the server.
rhnreg.sendVirtInfo(systemId)
# enable yum-rhn-plugin / dnf-plugin-spacewalk
try:
self.tui.pm_plugin_present, self.tui.pm_plugin_conf_changed = rhnreg.pluginEnable()
except IOError:
e = sys.exc_info()[1]
WarningWindow(self.screen, _("Could not open %s\n%s is not enabled.\n") % (PM_PLUGIN_CONF, PM_PLUGIN_NAME) + e.errmsg)
self.tui.pm_plugin_conf_error = 1
rhnreg.spawnRhnCheckForUI()
self.setScale(4, 4)
# Pop the pwin (Progress bar window)
self.screen.popWindow()
self.tui.reg_info = reg_info
return "next"
def saveResults(self):
pass
def setScale(self, amount, total):
self.scale.set(int(((amount * 1.0)/ total) * 100))
self.pwin.draw()
self.screen.refresh()
class FinishWindow:
name = "FinishWindow"
def __init__(self, screen, tui):
self.screen = screen
self.tui = tui
size = snack._snack.size()
toplevel = snack.GridForm(screen, sstr(FINISH_WINDOW),
1, 2)
text = snack.TextboxReflowed(size[0]-11, sstr(FINISH_WINDOW_TEXT_TUI))
toplevel.add(text, 0, 0)
# BUTTON BAR
self.bb = snack.ButtonBar(screen,
[(sstr(_("Finish")), "next")])
toplevel.add(self.bb, 0, 1, padding = (0, 1, 0, 0),
growx = 1)
self.g = toplevel
def saveResults(self):
pass
def run(self):
log.log_debug("Running %s" % self.name)
result = self.g.runOnce()
button = self.bb.buttonPressed(result)
if result == "F12":
return "next"
return button
class ReviewWindow:
name = "ReviewWindow"
def __init__(self, screen, tui):
self.screen = screen
self.tui = tui
self.reg_info = tui.reg_info
size = snack._snack.size()
toplevel = snack.GridForm(screen, sstr(REVIEW_WINDOW), 1, 2)
review_window_text = ''
if not self.tui.pm_plugin_present:
review_window_text += PM_PLUGIN_WARNING + "\n\n"
if self.tui.pm_plugin_conf_error:
review_window_text += PM_PLUGIN_CONF_ERROR + "\n\n"
if self.tui.pm_plugin_conf_changed:
review_window_text += PM_PLUGIN_CONF_CHANGED + "\n\n"
# Build up the review_window_text based on the data in self.reg_info
review_window_text += REVIEW_WINDOW_PROMPT + "\n\n"
# Create and add the text for what channels the system was
# subscribed to.
if len(self.reg_info['channels']) > 0:
channel_list = ""
for channel in self.reg_info['channels']:
channel_list += channel + "\n"
channels = CHANNELS_TITLE + "\n" + \
OK_CHANNELS + "\n" + \
"%s\n"
log.log_debug("server type is %s " % self.tui.serverType)
channels += CHANNELS_SAT_WARNING
review_window_text += channels % channel_list + "\n\n"
if len(self.reg_info['system_slots']) > 0:
slot_list = ""
for slot in self.reg_info['system_slots']:
if slot == 'enterprise_entitled':
slot_list += MANAGEMENT + "\n"
elif slot == 'virtualization_host':
slot_list += VIRT + "\n"
else:
slot_list += slot + "\n"
review_window_text += SLOTS % slot_list + "\n\n"
if len(self.reg_info['universal_activation_key']) > 0:
act_key_list = ""
for act_key in self.reg_info['universal_activation_key']:
act_key_list += act_key
review_window_text += ACTIVATION_KEY % (act_key_list)
self.review_window = snack.Textbox(size[0]-10, size[1]-14, sstr(review_window_text), 1, 1)
toplevel.add(self.review_window, 0, 0, padding = (0, 1, 0, 0))
# BUTTON BAR
self.bb = snack.ButtonBar(screen, [(sstr(OK), "next")])
toplevel.add(self.bb, 0, 1, padding = (0, 1, 0, 0),
growx = 1)
self.g = toplevel
def saveResults(self):
return 1
def run(self):
log.log_debug("Running %s" % self.name)
result = self.g.runOnce()
button = self.bb.buttonPressed(result)
if result == "F12":
button = "next"
if not self.tui.pm_plugin_present:
button = "exit"
if self.tui.pm_plugin_conf_error:
button = "exit"
return button
class Tui:
name = "RHN_REGISTER_TUI"
def __init__(self, screen, test):
self.screen = screen
self.test = test
self.size = snack._snack.size()
self.drawFrame()
self.alreadyRegistered = 0
try:
self.serverType = rhnreg.getServerType()
except up2dateErrors.InvalidProtocolError:
FatalErrorWindow(screen, _("You specified an invalid protocol." +
"Only https and http are allowed."))
self.windows = [
AlreadyRegisteredSubscriptionManagerWindow,
AlreadyRegisteredWindow,
StartWindow,
SatelliteUrlWindow,
ConnectWindow,
InfoWindow,
OSReleaseWindow,
HardwareWindow,
PackagesWindow,
SendWindow,
SendingWindow,
ReviewWindow,
FinishWindow
]
self.serverURL = config.getServerURL()[0]
if not cfg['sslCACert']:
cfg.set('sslCACert', '/usr/share/rhn/CLN-ORG-TRUSTED-SSL-CERT')
self.sslCACert = cfg['sslCACert']
def __del__(self):
self.screen.finish()
def drawFrame(self):
self.welcomeText = COPYRIGHT_TEXT
self.screen.drawRootText(0, 0, sstr(self.welcomeText))
self.screen.pushHelpLine(sstr(_(" <Tab>/<Alt-Tab> between elements | <Space> selects | <F12> next screen")))
def initResults(self):
self.userName = ""
self.password = ""
self.oemInfo = {}
self.productInfo = {
"entitlement_num" : "",
"registration_num" : "",
"first_name" : "",
"last_name" : "",
"company" : "",
"address" : "",
"city" : "",
"state" : "",
"zip" : "",
"country" : "",
}
self.other = {}
self.other['registration_number'] = ''
self.profileName = ""
self.includeHardware = 1
self.limited_updates_button = 1
self.all_updates_button = 0
self.includePackages = 0
self.packageList = []
self.selectedPackages = []
self.pm_plugin_present = 1
self.pm_plugin_conf_error = 0
self.pm_plugin_conf_changed = 0
def run(self):
log.log_debug("Running %s" % self.name)
self.initResults()
direction = "forward"
try:
index = 0
while index < len(self.windows):
win = None
try:
win = self.windows[index](self.screen, self)
except WindowSkipException:
if direction == "forward":
index = index + 1
else:
index = index - 1
continue
log.log_debug("index is %s" % index)
result = win.run()
log.log_debug("Result %s" % result)
if result == "back":
if index > 0:
index = index - 1
# If we're on the info window, "back" means go back
# to the satellite url window, not back to the
# temporary connection test window.
if (index > 0 and
self.windows[index].name == ConnectWindow.name):
index -= 1
direction = "backward"
elif result == "exit":
return
elif result == "cancel":
log.log_debug("Caught a cancel request")
# Show the confirm quit window
if ConfirmQuitWindow(self.screen) == 1:
return
elif result == "next":
index = index + 1
win.saveResults()
direction = "forward"
finally:
self.screen.finish()
def main():
test = 0
signal.signal(signal.SIGINT, signal.SIG_IGN)
if len(sys.argv) > 1:
if sys.argv[1] == "-t" or sys.argv[1] == "--test":
test = 1
screen = snack.SnackScreen()
if geteuid() != 0 and not test:
FatalErrorWindow(screen, _("You must run the RHN registration program as root."))
tui = Tui(screen, test)
tui.run()
if __name__ == "__main__":
main()
__pycache__/hardware.cpython-36.pyc 0000644 00000044657 15051677404 0013230 0 ustar 00 3
c8h� � D @ sJ d Z ddlmZmZmZmZ ddlZddlZddlZddlZddl m
Z
ddl mZ ddl mZ ddl
mZ ye W n ek
r� eZY nX yddlZdZW n ek
r� d ZY nX yddlZddlZdZW n ek
r� d ZY nX ddlZejd
dd�Zeed��seje_ejZddlZejd
dg�� ddl Z W dQ R X ddl m!Z! yddl"m#Z#m$Z$ dZ%W n^ ek
�r� yddl&m#Z#m$Z$ dZ%W n. ek
�r� ddl'm(Z(m)Z)m*Z* dZ%Y nX Y nX yddl+Z+W n ek
�r� dZ+Y nX ej,j-d� yddl.m/Z0 dZ1W n ek
�r* d Z1Y nX da2da3dd� Z4e4� Z5e5�rfe j6� e!j7� Z8e8j9de5 � dd� Z:dd� Z;dd� Z<dd� Z=d d!� Z>d"d#� Z?d$d%� Z@d&d'� ZAd(d)� ZBd*d+� ZCd,d-� ZDd.d/� ZEd0d1� ZFd2d3� ZGd4d5� ZHd6d7� ZId8d9� ZJd:d;� ZKd<d=� Z/eLd>k�rFx<e/� D ]2ZMx&eMjN� D ]ZOePd?eOeMeO f � �qW eP �qW dS )@z1Used to read hardware info from kudzu, /proc, etc� )�gethostname�getaddrinfo�AF_INET�AF_INET6N)�config)� rhnserver)�up2dateUtils)�ustrTFzrhn-client-tools)Zfallback�ugettextzFailed to save log entryzSMBIOS.*: entry point at)�
up2dateLog)�get_devices�get_computer_info� )�check_hal_dbus_status�get_hal_computer�read_halz/usr/share/rhsm)�Hardwarec C s t td�sd S tj� S )N�get_warnings)�hasattr� dmidecoder � r r �/usr/lib/python3.6/hardware.py�dmi_warnings[ s
r z.Warnings collected during dmidecode import: %sc C s� t dkr�trdS tj� } | jtj� y6| jd�}t� }|rXtj� t j
� }|jd| � W n dat� }|rxtj� dS |j� a t S )z= Initialize _dmi_data unless it already exist and returns it N�allzdmidecode warnings: %sr )
� _dmi_data�_dmi_not_availabler ZdmidecodeXMLZ
SetResultTypeZ
DMIXML_DOCZQuerySectionr �clear_warningsr �initLog� log_debugZxpathNewContext)Zdmixml�data�dmi_warn�logr r r �_initialize_dmi_datag s(
r"