Use the print function

In Python 3, `print` is no longer a statement. Call it as a function
everywhere, and include the future import to remove the statement
in Python 2 code as well.

Reviewed-By: Christian Heimes <cheimes@redhat.com>
Reviewed-By: Jan Cholasta <jcholast@redhat.com>
This commit is contained in:
Petr Viktorin
2015-08-12 13:44:11 +02:00
committed by Jan Cholasta
parent fb7943dab4
commit 8de13bd7dd
68 changed files with 954 additions and 838 deletions

View File

@@ -30,6 +30,7 @@ server. I don't exactly remember the steps, so ping him for help.
--jderose 2009-02-13 --jderose 2009-02-13
""" """
from __future__ import print_function
from os import path from os import path
import sys import sys
@@ -90,14 +91,14 @@ def assert_equal(trial, reference):
api.log.info('******** Testing ra.request_certificate() ********') api.log.info('******** Testing ra.request_certificate() ********')
request_result = ra.request_certificate(csr, ra.DEFAULT_PROFILE) request_result = ra.request_certificate(csr, ra.DEFAULT_PROFILE)
if verbose: print "request_result=\n%s" % request_result if verbose: print("request_result=\n%s" % request_result)
assert_equal(request_result, assert_equal(request_result,
{'subject' : subject, {'subject' : subject,
}) })
api.log.info('******** Testing ra.check_request_status() ********') api.log.info('******** Testing ra.check_request_status() ********')
status_result = ra.check_request_status(request_result['request_id']) status_result = ra.check_request_status(request_result['request_id'])
if verbose: print "status_result=\n%s" % status_result if verbose: print("status_result=\n%s" % status_result)
assert_equal(status_result, assert_equal(status_result,
{'serial_number' : request_result['serial_number'], {'serial_number' : request_result['serial_number'],
'request_id' : request_result['request_id'], 'request_id' : request_result['request_id'],
@@ -106,7 +107,7 @@ assert_equal(status_result,
api.log.info('******** Testing ra.get_certificate() ********') api.log.info('******** Testing ra.get_certificate() ********')
get_result = ra.get_certificate(request_result['serial_number']) get_result = ra.get_certificate(request_result['serial_number'])
if verbose: print "get_result=\n%s" % get_result if verbose: print("get_result=\n%s" % get_result)
assert_equal(get_result, assert_equal(get_result,
{'serial_number' : request_result['serial_number'], {'serial_number' : request_result['serial_number'],
'certificate' : request_result['certificate'], 'certificate' : request_result['certificate'],
@@ -115,7 +116,7 @@ assert_equal(get_result,
api.log.info('******** Testing ra.revoke_certificate() ********') api.log.info('******** Testing ra.revoke_certificate() ********')
revoke_result = ra.revoke_certificate(request_result['serial_number'], revoke_result = ra.revoke_certificate(request_result['serial_number'],
revocation_reason=6) # Put on hold revocation_reason=6) # Put on hold
if verbose: print "revoke_result=\n%s" % revoke_result if verbose: print("revoke_result=\n%s" % revoke_result)
assert_equal(revoke_result, assert_equal(revoke_result,
{'revoked' : True {'revoked' : True
}) })
@@ -123,7 +124,7 @@ assert_equal(revoke_result,
api.log.info('******** Testing ra.take_certificate_off_hold() ********') api.log.info('******** Testing ra.take_certificate_off_hold() ********')
unrevoke_result = ra.take_certificate_off_hold(request_result['serial_number']) unrevoke_result = ra.take_certificate_off_hold(request_result['serial_number'])
if verbose: print "unrevoke_result=\n%s" % unrevoke_result if verbose: print("unrevoke_result=\n%s" % unrevoke_result)
assert_equal(unrevoke_result, assert_equal(unrevoke_result,
{'unrevoked' : True {'unrevoked' : True
}) })

View File

@@ -14,6 +14,7 @@ first command line argument.
Purpose of this replacement is to upload keys generated by OpenDNSSEC to LDAP. Purpose of this replacement is to upload keys generated by OpenDNSSEC to LDAP.
""" """
from __future__ import print_function
from binascii import hexlify from binascii import hexlify
from datetime import datetime from datetime import datetime
@@ -468,7 +469,7 @@ log.addHandler(systemd.journal.JournalHandler())
log.setLevel(level=logging.DEBUG) log.setLevel(level=logging.DEBUG)
if len(sys.argv) > 2: if len(sys.argv) > 2:
print __doc__ print(__doc__)
sys.exit(1) sys.exit(1)
# program was likely invoked from console, log to it # program was likely invoked from console, log to it
elif len(sys.argv) == 2: elif len(sys.argv) == 2:

View File

@@ -43,5 +43,5 @@ else:
# Now that you're connected, you can make calls to api.Command.whatever(): # Now that you're connected, you can make calls to api.Command.whatever():
print 'The admin user:' print('The admin user:')
print api.Command.user_show(u'admin') print(api.Command.user_show(u'admin'))

View File

@@ -19,6 +19,8 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import os import os
# Prevent garbage from readline on standard output # Prevent garbage from readline on standard output
# (see https://fedorahosted.org/freeipa/ticket/4064) # (see https://fedorahosted.org/freeipa/ticket/4064)
@@ -456,7 +458,7 @@ def main():
res = call_handler(handler) res = call_handler(handler)
for item in res[1:]: for item in res[1:]:
print item print(item)
return res[0] return res[0]
finally: finally:
certs.renewal_lock.release() certs.renewal_lock.release()
@@ -466,5 +468,5 @@ try:
sys.exit(main()) sys.exit(main())
except Exception as e: except Exception as e:
syslog.syslog(syslog.LOG_ERR, traceback.format_exc()) syslog.syslog(syslog.LOG_ERR, traceback.format_exc())
print "Internal error" print("Internal error")
sys.exit(UNREACHABLE) sys.exit(UNREACHABLE)

View File

@@ -19,6 +19,8 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import os import os
# Prevent garbage from readline on standard output # Prevent garbage from readline on standard output
# (see https://fedorahosted.org/freeipa/ticket/4064) # (see https://fedorahosted.org/freeipa/ticket/4064)
@@ -51,5 +53,5 @@ try:
sys.exit(main()) sys.exit(main())
except Exception as e: except Exception as e:
syslog.syslog(syslog.LOG_ERR, traceback.format_exc()) syslog.syslog(syslog.LOG_ERR, traceback.format_exc())
print "Internal error" print("Internal error")
sys.exit(3) sys.exit(3)

View File

@@ -21,7 +21,10 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
import gssapi import gssapi
from ipaserver.install import adtrustinstance from ipaserver.install import adtrustinstance
from ipaserver.install.installutils import * from ipaserver.install.installutils import *
from ipaserver.install import service from ipaserver.install import service
@@ -74,22 +77,22 @@ def parse_options():
return safe_options, options return safe_options, options
def netbios_name_error(name): def netbios_name_error(name):
print "\nIllegal NetBIOS name [%s].\n" % name print("\nIllegal NetBIOS name [%s].\n" % name)
print "Up to 15 characters and only uppercase ASCII letter and digits are allowed." print("Up to 15 characters and only uppercase ASCII letter and digits are allowed.")
def read_netbios_name(netbios_default): def read_netbios_name(netbios_default):
netbios_name = "" netbios_name = ""
print "Enter the NetBIOS name for the IPA domain." print("Enter the NetBIOS name for the IPA domain.")
print "Only up to 15 uppercase ASCII letters and digits are allowed." print("Only up to 15 uppercase ASCII letters and digits are allowed.")
print "Example: EXAMPLE." print("Example: EXAMPLE.")
print "" print("")
print "" print("")
if not netbios_default: if not netbios_default:
netbios_default = "EXAMPLE" netbios_default = "EXAMPLE"
while True: while True:
netbios_name = ipautil.user_input("NetBIOS domain name", netbios_default, allow_empty = False) netbios_name = ipautil.user_input("NetBIOS domain name", netbios_default, allow_empty = False)
print "" print("")
if adtrustinstance.check_netbios_name(netbios_name): if adtrustinstance.check_netbios_name(netbios_name):
break break
@@ -98,9 +101,9 @@ def read_netbios_name(netbios_default):
return netbios_name return netbios_name
def read_admin_password(admin_name): def read_admin_password(admin_name):
print "Configuring cross-realm trusts for IPA server requires password for user '%s'." % (admin_name) print("Configuring cross-realm trusts for IPA server requires password for user '%s'." % (admin_name))
print "This user is a regular system account used for IPA server administration." print("This user is a regular system account used for IPA server administration.")
print "" print("")
admin_password = read_password(admin_name, confirm=False, validate=None) admin_password = read_password(admin_name, confirm=False, validate=None)
return admin_password return admin_password
@@ -139,17 +142,17 @@ def set_and_check_netbios_name(netbios_name, unattended):
reset_netbios_name = False reset_netbios_name = False
elif cur_netbios_name and cur_netbios_name != netbios_name: elif cur_netbios_name and cur_netbios_name != netbios_name:
# change the NetBIOS name # change the NetBIOS name
print "Current NetBIOS domain name is %s, new name is %s.\n" % \ print("Current NetBIOS domain name is %s, new name is %s.\n" % \
(cur_netbios_name, netbios_name) (cur_netbios_name, netbios_name))
print "Please note that changing the NetBIOS name might " \ print("Please note that changing the NetBIOS name might " \
"break existing trust relationships." "break existing trust relationships.")
if unattended: if unattended:
reset_netbios_name = True reset_netbios_name = True
print "NetBIOS domain name will be changed to %s.\n" % \ print("NetBIOS domain name will be changed to %s.\n" % \
netbios_name netbios_name)
else: else:
print "Say 'yes' if the NetBIOS shall be changed and " \ print("Say 'yes' if the NetBIOS shall be changed and " \
"'no' if the old one shall be kept." "'no' if the old one shall be kept.")
reset_netbios_name = ipautil.user_input( reset_netbios_name = ipautil.user_input(
'Do you want to reset the NetBIOS domain name?', 'Do you want to reset the NetBIOS domain name?',
default = False, allow_empty = False) default = False, allow_empty = False)
@@ -164,8 +167,8 @@ def set_and_check_netbios_name(netbios_name, unattended):
if entry is not None: if entry is not None:
# Fix existing trust configuration # Fix existing trust configuration
print "Trust is configured but no NetBIOS domain name found, " \ print("Trust is configured but no NetBIOS domain name found, " \
"setting it now." "setting it now.")
reset_netbios_name = True reset_netbios_name = True
else: else:
# initial trust configuration # initial trust configuration
@@ -195,16 +198,16 @@ def ensure_admin_kinit(admin_name, admin_password):
try: try:
ipautil.run(['kinit', admin_name], stdin=admin_password+'\n') ipautil.run(['kinit', admin_name], stdin=admin_password+'\n')
except ipautil.CalledProcessError as e: except ipautil.CalledProcessError as e:
print "There was error to automatically re-kinit your admin user ticket." print("There was error to automatically re-kinit your admin user ticket.")
return False return False
return True return True
def enable_compat_tree(): def enable_compat_tree():
print "Do you want to enable support for trusted domains in Schema Compatibility plugin?" print("Do you want to enable support for trusted domains in Schema Compatibility plugin?")
print "This will allow clients older than SSSD 1.9 and non-Linux clients to work with trusted users." print("This will allow clients older than SSSD 1.9 and non-Linux clients to work with trusted users.")
print "" print("")
enable_compat = ipautil.user_input("Enable trusted domains support in slapi-nis?", default = False, allow_empty = False) enable_compat = ipautil.user_input("Enable trusted domains support in slapi-nis?", default = False, allow_empty = False)
print "" print("")
return enable_compat return enable_compat
@@ -215,7 +218,7 @@ def main():
sys.exit("Must be root to setup AD trusts on server") sys.exit("Must be root to setup AD trusts on server")
standard_logging_setup(log_file_name, debug=options.debug, filemode='a') standard_logging_setup(log_file_name, debug=options.debug, filemode='a')
print "\nThe log file for this installation can be found in %s" % log_file_name print("\nThe log file for this installation can be found in %s" % log_file_name)
root_logger.debug('%s was invoked with options: %s' % (sys.argv[0], safe_options)) root_logger.debug('%s was invoked with options: %s' % (sys.argv[0], safe_options))
root_logger.debug("missing options might be asked for interactively later\n") root_logger.debug("missing options might be asked for interactively later\n")
@@ -226,18 +229,18 @@ def main():
global fstore global fstore
fstore = sysrestore.FileStore(paths.SYSRESTORE) fstore = sysrestore.FileStore(paths.SYSRESTORE)
print "==============================================================================" print("==============================================================================")
print "This program will setup components needed to establish trust to AD domains for" print("This program will setup components needed to establish trust to AD domains for")
print "the FreeIPA Server." print("the FreeIPA Server.")
print "" print("")
print "This includes:" print("This includes:")
print " * Configure Samba" print(" * Configure Samba")
print " * Add trust related objects to FreeIPA LDAP server" print(" * Add trust related objects to FreeIPA LDAP server")
#TODO: #TODO:
#print " * Add a SID to all users and Posix groups" #print " * Add a SID to all users and Posix groups"
print "" print("")
print "To accept the default shown in brackets, press the Enter key." print("To accept the default shown in brackets, press the Enter key.")
print "" print("")
# Check if samba packages are installed # Check if samba packages are installed
if not adtrustinstance.check_inst(): if not adtrustinstance.check_inst():
@@ -272,7 +275,7 @@ def main():
if adtrustinstance.ipa_smb_conf_exists(): if adtrustinstance.ipa_smb_conf_exists():
if not options.unattended: if not options.unattended:
print "IPA generated smb.conf detected." print("IPA generated smb.conf detected.")
if not ipautil.user_input("Overwrite smb.conf?", if not ipautil.user_input("Overwrite smb.conf?",
default = False, default = False,
allow_empty = False): allow_empty = False):
@@ -299,7 +302,7 @@ def main():
if admin_password: if admin_password:
admin_kinited = ensure_admin_kinit(options.admin_name, admin_password) admin_kinited = ensure_admin_kinit(options.admin_name, admin_password)
if not admin_kinited: if not admin_kinited:
print "Proceeding with credentials that existed before" print("Proceeding with credentials that existed before")
try: try:
principal = krb_utils.get_principal() principal = krb_utils.get_principal()
@@ -343,32 +346,32 @@ def main():
# All objects have SIDs assigned # All objects have SIDs assigned
pass pass
except (errors.DatabaseError, errors.NetworkError) as e: except (errors.DatabaseError, errors.NetworkError) as e:
print "Could not retrieve a list of objects that need a SID identifier assigned:" print("Could not retrieve a list of objects that need a SID identifier assigned:")
print unicode(e) print(unicode(e))
else: else:
object_count = len(entries) object_count = len(entries)
if object_count > 0: if object_count > 0:
print "" print("")
print "WARNING: %d existing users or groups do not have a SID identifier assigned." \ print("WARNING: %d existing users or groups do not have a SID identifier assigned." \
% len(entries) % len(entries))
print "Installer can run a task to have ipa-sidgen Directory Server plugin generate" print("Installer can run a task to have ipa-sidgen Directory Server plugin generate")
print "the SID identifier for all these users. Please note, the in case of a high" print("the SID identifier for all these users. Please note, the in case of a high")
print "number of users and groups, the operation might lead to high replication" print("number of users and groups, the operation might lead to high replication")
print "traffic and performance degradation. Refer to ipa-adtrust-install(1) man page" print("traffic and performance degradation. Refer to ipa-adtrust-install(1) man page")
print "for details." print("for details.")
print "" print("")
if options.unattended: if options.unattended:
print "Unattended mode was selected, installer will NOT run ipa-sidgen task!" print("Unattended mode was selected, installer will NOT run ipa-sidgen task!")
else: else:
if ipautil.user_input("Do you want to run the ipa-sidgen task?", default=False, if ipautil.user_input("Do you want to run the ipa-sidgen task?", default=False,
allow_empty=False): allow_empty=False):
options.add_sids = True options.add_sids = True
if not options.unattended: if not options.unattended:
print "" print("")
print "The following operations may take some minutes to complete." print("The following operations may take some minutes to complete.")
print "Please wait until the prompt is returned." print("Please wait until the prompt is returned.")
print "" print("")
smb = adtrustinstance.ADTRUSTInstance(fstore) smb = adtrustinstance.ADTRUSTInstance(fstore)
smb.realm = api.env.realm smb.realm = api.env.realm
@@ -399,8 +402,8 @@ def main():
except errors.NotFound: except errors.NotFound:
pass pass
except (errors.DatabaseError, errors.NetworkError) as e: except (errors.DatabaseError, errors.NetworkError) as e:
print "Could not retrieve a list of existing IPA masters:" print("Could not retrieve a list of existing IPA masters:")
print unicode(e) print(unicode(e))
try: try:
(entries_a, truncated) = smb.admin_conn.find_entries(filter="", (entries_a, truncated) = smb.admin_conn.find_entries(filter="",
@@ -408,8 +411,8 @@ def main():
except errors.NotFound: except errors.NotFound:
pass pass
except (errors.DatabaseError, errors.NetworkError) as e: except (errors.DatabaseError, errors.NetworkError) as e:
print "Could not retrieve a list of adtrust agents:" print("Could not retrieve a list of adtrust agents:")
print unicode(e) print(unicode(e))
if len(entries_m) > 0: if len(entries_m) > 0:
existing_masters = [x['cn'][0] for x in entries_m] existing_masters = [x['cn'][0] for x in entries_m]
@@ -427,18 +430,18 @@ def main():
object_count = len(potential_agents) object_count = len(potential_agents)
if object_count > 0: if object_count > 0:
print "" print("")
print "WARNING: %d IPA masters are not yet able to serve information about users from trusted forests." \ print("WARNING: %d IPA masters are not yet able to serve information about users from trusted forests." \
% (object_count) % (object_count))
print "Installer can add them to the list of IPA masters allowed to access infromation about trusts." print("Installer can add them to the list of IPA masters allowed to access infromation about trusts.")
print "If you choose to do so, you also need to restart LDAP service on those masters." print("If you choose to do so, you also need to restart LDAP service on those masters.")
print "Refer to ipa-adtrust-install(1) man page for details." print("Refer to ipa-adtrust-install(1) man page for details.")
print "" print("")
if options.unattended: if options.unattended:
print "Unattended mode was selected, installer will NOT add other IPA masters to the list of allowed to" print("Unattended mode was selected, installer will NOT add other IPA masters to the list of allowed to")
print "access information about trusted forests!" print("access information about trusted forests!")
else: else:
print "Do you want to allow following IPA masters to serve information about users from trusted forests?" print("Do you want to allow following IPA masters to serve information about users from trusted forests?")
for (name, dn) in potential_agents: for (name, dn) in potential_agents:
if name == api.env.host: if name == api.env.host:
# Don't add this host here # Don't add this host here
@@ -453,13 +456,13 @@ def main():
# the principal's proper dn as defined in self.cifs_agent # the principal's proper dn as defined in self.cifs_agent
service.add_principals_to_group(smb.admin_conn, agents_dn, "member", service.add_principals_to_group(smb.admin_conn, agents_dn, "member",
[x[1] for x in new_agents]) [x[1] for x in new_agents])
print """ print("""
WARNING: you MUST restart (e.g. ipactl restart) the following IPA masters in order WARNING: you MUST restart (e.g. ipactl restart) the following IPA masters in order
to activate them to serve information about users from trusted forests:""" to activate them to serve information about users from trusted forests:""")
for x in new_agents: for x in new_agents:
print x[0] print(x[0])
print """ print("""
============================================================================= =============================================================================
Setup complete Setup complete
@@ -475,15 +478,15 @@ You must make sure these network ports are open:
\t * 445: microsoft-ds \t * 445: microsoft-ds
============================================================================= =============================================================================
""" """)
if admin_password: if admin_password:
admin_kinited = ensure_admin_kinit(options.admin_name, admin_password) admin_kinited = ensure_admin_kinit(options.admin_name, admin_password)
if not admin_kinited: if not admin_kinited:
print """ print("""
WARNING: you MUST re-kinit admin user before using 'ipa trust-*' commands WARNING: you MUST re-kinit admin user before using 'ipa trust-*' commands
family in order to re-generate Kerberos tickets to include AD-specific family in order to re-generate Kerberos tickets to include AD-specific
information""" information""")
return 0 return 0

View File

@@ -19,6 +19,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
import sys import sys
from ipaplatform.paths import paths from ipaplatform.paths import paths
try: try:
@@ -31,12 +33,12 @@ try:
from ipapython.ipa_log_manager import * from ipapython.ipa_log_manager import *
from ipapython.dn import DN from ipapython.dn import DN
except ImportError as e: except ImportError as e:
print >> sys.stderr, """\ print("""\
There was a problem importing one of the required Python modules. The There was a problem importing one of the required Python modules. The
error was: error was:
%s %s
""" % e """ % e, file=sys.stderr)
sys.exit(1) sys.exit(1)
compat_dn = DN(('cn', 'Schema Compatibility'), ('cn', 'plugins'), ('cn', 'config')) compat_dn = DN(('cn', 'Schema Compatibility'), ('cn', 'plugins'), ('cn', 'config'))
@@ -121,34 +123,34 @@ def main():
try: try:
entry = get_entry(compat_dn, conn) entry = get_entry(compat_dn, conn)
if entry is not None and entry.get('nsslapd-pluginenabled', [''])[0].lower() == 'on': if entry is not None and entry.get('nsslapd-pluginenabled', [''])[0].lower() == 'on':
print "Plugin Enabled" print("Plugin Enabled")
else: else:
print "Plugin Disabled" print("Plugin Disabled")
except errors.LDAPError as lde: except errors.LDAPError as lde:
print "An error occurred while talking to the server." print("An error occurred while talking to the server.")
print lde print(lde)
if args[0] == "enable": if args[0] == "enable":
entry = None entry = None
try: try:
entry = get_entry(compat_dn, conn) entry = get_entry(compat_dn, conn)
if entry is not None and entry.get('nsslapd-pluginenabled', [''])[0].lower() == 'on': if entry is not None and entry.get('nsslapd-pluginenabled', [''])[0].lower() == 'on':
print "Plugin already Enabled" print("Plugin already Enabled")
retval = 2 retval = 2
else: else:
print "Enabling plugin" print("Enabling plugin")
if entry is None: if entry is None:
ld = LDAPUpdate(dm_password=dirman_password, sub_dict={}) ld = LDAPUpdate(dm_password=dirman_password, sub_dict={})
if not ld.update(files): if not ld.update(files):
print "Updating Directory Server failed." print("Updating Directory Server failed.")
retval = 1 retval = 1
else: else:
entry['nsslapd-pluginenabled'] = ['on'] entry['nsslapd-pluginenabled'] = ['on']
conn.update_entry(entry) conn.update_entry(entry)
except errors.ExecutionError as lde: except errors.ExecutionError as lde:
print "An error occurred while talking to the server." print("An error occurred while talking to the server.")
print lde print(lde)
retval = 1 retval = 1
elif args[0] == "disable": elif args[0] == "disable":
@@ -157,12 +159,12 @@ def main():
entry = get_entry(nis_config_dn, conn) entry = get_entry(nis_config_dn, conn)
# We can't disable schema compat if the NIS plugin is enabled # We can't disable schema compat if the NIS plugin is enabled
if entry is not None and entry.get('nsslapd-pluginenabled', [''])[0].lower() == 'on': if entry is not None and entry.get('nsslapd-pluginenabled', [''])[0].lower() == 'on':
print >>sys.stderr, "The NIS plugin is configured, cannot disable compatibility." print("The NIS plugin is configured, cannot disable compatibility.", file=sys.stderr)
print >>sys.stderr, "Run 'ipa-nis-manage disable' first." print("Run 'ipa-nis-manage disable' first.", file=sys.stderr)
retval = 2 retval = 2
except errors.ExecutionError as lde: except errors.ExecutionError as lde:
print "An error occurred while talking to the server." print("An error occurred while talking to the server.")
print lde print(lde)
retval = 1 retval = 1
if retval == 0: if retval == 0:
@@ -170,27 +172,27 @@ def main():
try: try:
entry = get_entry(compat_dn, conn) entry = get_entry(compat_dn, conn)
if entry is None or entry.get('nsslapd-pluginenabled', [''])[0].lower() == 'off': if entry is None or entry.get('nsslapd-pluginenabled', [''])[0].lower() == 'off':
print "Plugin is already disabled" print("Plugin is already disabled")
retval = 2 retval = 2
else: else:
print "Disabling plugin" print("Disabling plugin")
entry['nsslapd-pluginenabled'] = ['off'] entry['nsslapd-pluginenabled'] = ['off']
conn.update_entry(entry) conn.update_entry(entry)
except errors.DatabaseError as dbe: except errors.DatabaseError as dbe:
print "An error occurred while talking to the server." print("An error occurred while talking to the server.")
print dbe print(dbe)
retval = 1 retval = 1
except errors.ExecutionError as lde: except errors.ExecutionError as lde:
print "An error occurred while talking to the server." print("An error occurred while talking to the server.")
print lde print(lde)
retval = 1 retval = 1
else: else:
retval = 1 retval = 1
if retval == 0: if retval == 0:
print "This setting will not take effect until you restart Directory Server." print("This setting will not take effect until you restart Directory Server.")
finally: finally:
if conn and conn.isconnected(): if conn and conn.isconnected():

View File

@@ -19,6 +19,9 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
import sys import sys
import os import os
@@ -112,7 +115,7 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose):
if not replica: if not replica:
for k, p in peers.items(): for k, p in peers.items():
print '%s: %s' % (k, p[0]) print('%s: %s' % (k, p[0]))
return return
try: try:
@@ -123,19 +126,19 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose):
entries = repl.find_replication_agreements() entries = repl.find_replication_agreements()
for entry in entries: for entry in entries:
print '%s' % entry.single_value.get('nsds5replicahost') print('%s' % entry.single_value.get('nsds5replicahost'))
if verbose: if verbose:
print " last init status: %s" % entry.single_value.get( print(" last init status: %s" % entry.single_value.get(
'nsds5replicalastinitstatus') 'nsds5replicalastinitstatus'))
print " last init ended: %s" % str( print(" last init ended: %s" % str(
ipautil.parse_generalized_time( ipautil.parse_generalized_time(
entry.single_value['nsds5replicalastinitend'])) entry.single_value['nsds5replicalastinitend'])))
print " last update status: %s" % entry.single_value.get( print(" last update status: %s" % entry.single_value.get(
'nsds5replicalastupdatestatus') 'nsds5replicalastupdatestatus'))
print " last update ended: %s" % str( print(" last update ended: %s" % str(
ipautil.parse_generalized_time( ipautil.parse_generalized_time(
entry.single_value['nsds5replicalastupdateend'])) entry.single_value['nsds5replicalastupdateend'])))
def del_link(realm, replica1, replica2, dirman_passwd, force=False): def del_link(realm, replica1, replica2, dirman_passwd, force=False):
@@ -175,13 +178,13 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
# Now that we've confirmed that both hostnames are vaild, make sure # Now that we've confirmed that both hostnames are vaild, make sure
# that we aren't removing the last link from either side. # that we aren't removing the last link from either side.
if not force and len(repl_list) <= 1: if not force and len(repl_list) <= 1:
print "Cannot remove the last replication link of '%s'" % replica2 print("Cannot remove the last replication link of '%s'" % replica2)
print "Please use the 'del' command to remove it from the domain" print("Please use the 'del' command to remove it from the domain")
sys.exit(1) sys.exit(1)
if not force and len(repl_list1) <= 1: if not force and len(repl_list1) <= 1:
print "Cannot remove the last replication link of '%s'" % replica1 print("Cannot remove the last replication link of '%s'" % replica1)
print "Please use the 'del' command to remove it from the domain" print("Please use the 'del' command to remove it from the domain")
sys.exit(1) sys.exit(1)
# Find the DN of the replication agreement to remove # Find the DN of the replication agreement to remove
@@ -196,11 +199,11 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
sys.exit("'%s' has no replication agreement for '%s'" % (replica1, replica2)) sys.exit("'%s' has no replication agreement for '%s'" % (replica1, replica2))
except errors.NotFound: except errors.NotFound:
print "'%s' has no replication agreement for '%s'" % (replica2, replica1) print("'%s' has no replication agreement for '%s'" % (replica2, replica1))
if not force: if not force:
return return
except Exception as e: except Exception as e:
print "Failed to get data from '%s': %s" % (replica2, e) print("Failed to get data from '%s': %s" % (replica2, e))
if not force: if not force:
sys.exit(1) sys.exit(1)
@@ -210,22 +213,22 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
repl2.delete_agreement(replica1, replica2_dn) repl2.delete_agreement(replica1, replica2_dn)
repl2.delete_referral(replica1, repl1.port) repl2.delete_referral(replica1, repl1.port)
except Exception as e: except Exception as e:
print "Unable to remove agreement on %s: %s" % (replica2, e) print("Unable to remove agreement on %s: %s" % (replica2, e))
failed = True failed = True
if failed: if failed:
if force: if force:
print "Forcing removal on '%s'" % replica1 print("Forcing removal on '%s'" % replica1)
else: else:
sys.exit(1) sys.exit(1)
if not repl2 and force: if not repl2 and force:
print "Forcing removal on '%s'" % replica1 print("Forcing removal on '%s'" % replica1)
repl1.delete_agreement(replica2, replica1_dn) repl1.delete_agreement(replica2, replica1_dn)
repl1.delete_referral(replica2, repl2.port) repl1.delete_referral(replica2, repl2.port)
print "Deleted replication agreement from '%s' to '%s'" % (replica1, replica2) print("Deleted replication agreement from '%s' to '%s'" % (replica1, replica2))
def del_master(realm, hostname, options): def del_master(realm, hostname, options):
@@ -250,10 +253,10 @@ def del_master(realm, hostname, options):
options.dirman_passwd) options.dirman_passwd)
except Exception as e: except Exception as e:
if not options.force: if not options.force:
print "Unable to delete replica %s: %s" % (hostname, e) print("Unable to delete replica %s: %s" % (hostname, e))
sys.exit(1) sys.exit(1)
else: else:
print "Unable to connect to replica %s, forcing removal" % hostname print("Unable to connect to replica %s, forcing removal" % hostname)
force_del = True force_del = True
# 4. Get list of agreements. # 4. Get list of agreements.
@@ -286,8 +289,8 @@ def del_master(realm, hostname, options):
bind = bindinstance.BindInstance() bind = bindinstance.BindInstance()
bind.remove_ipa_ca_dns_records(hostname, realm.lower()) bind.remove_ipa_ca_dns_records(hostname, realm.lower())
except Exception as e: except Exception as e:
print "Failed to cleanup %s DNS entries: %s" % (hostname, e) print("Failed to cleanup %s DNS entries: %s" % (hostname, e))
print "You may need to manually remove them from the tree" print("You may need to manually remove them from the tree")
def add_link(realm, replica1, replica2, dirman_passwd, options): def add_link(realm, replica1, replica2, dirman_passwd, options):
try: try:
@@ -331,7 +334,7 @@ def add_link(realm, replica1, replica2, dirman_passwd, options):
repl1.setup_replication( repl1.setup_replication(
replica2, repl2.port, 0, DN(('cn', 'Directory Manager')), replica2, repl2.port, 0, DN(('cn', 'Directory Manager')),
dirman_passwd, is_cs_replica=True, local_port=repl1.port) dirman_passwd, is_cs_replica=True, local_port=repl1.port)
print "Connected '%s' to '%s'" % (replica1, replica2) print("Connected '%s' to '%s'" % (replica1, replica2))
def re_initialize(realm, options): def re_initialize(realm, options):
@@ -387,7 +390,7 @@ def set_renewal_master(realm, replica):
except Exception as e: except Exception as e:
sys.exit("Failed to set renewal master to %s: %s" % (replica, e)) sys.exit("Failed to set renewal master to %s: %s" % (replica, e))
print "%s is now the renewal master" % replica print("%s is now the renewal master" % replica)
def main(): def main():
options, args = parse_options() options, args = parse_options()

View File

@@ -19,6 +19,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
from optparse import OptionGroup, SUPPRESS_HELP from optparse import OptionGroup, SUPPRESS_HELP
from ipaserver.install import bindinstance, httpinstance from ipaserver.install import bindinstance, httpinstance
@@ -102,7 +104,7 @@ def main():
sys.exit("Must be root to setup server") sys.exit("Must be root to setup server")
standard_logging_setup(log_file_name, debug=options.debug, filemode='a') standard_logging_setup(log_file_name, debug=options.debug, filemode='a')
print "\nThe log file for this installation can be found in %s" % log_file_name print("\nThe log file for this installation can be found in %s" % log_file_name)
root_logger.debug('%s was invoked with options: %s' % (sys.argv[0], safe_options)) root_logger.debug('%s was invoked with options: %s' % (sys.argv[0], safe_options))
root_logger.debug("missing options might be asked for interactively later\n") root_logger.debug("missing options might be asked for interactively later\n")

View File

@@ -18,6 +18,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
import re import re
import sys import sys
from optparse import OptionParser from optparse import OptionParser
@@ -117,9 +119,9 @@ def main():
sys.exit("Unable to find managed entries at %s" % managed_entry_definitions_dn) sys.exit("Unable to find managed entries at %s" % managed_entry_definitions_dn)
managed_entries = [entry.single_value['cn'] for entry in entries] managed_entries = [entry.single_value['cn'] for entry in entries]
if managed_entries: if managed_entries:
print "Available Managed Entry Definitions:" print("Available Managed Entry Definitions:")
for managed_entry in managed_entries: for managed_entry in managed_entries:
print managed_entry print(managed_entry)
retval = 0 retval = 0
sys.exit() sys.exit()
@@ -141,20 +143,20 @@ def main():
except errors.NotFound: except errors.NotFound:
sys.exit("%s is not a valid Managed Entry" % def_dn) sys.exit("%s is not a valid Managed Entry" % def_dn)
except errors.ExecutionError as lde: except errors.ExecutionError as lde:
print "An error occurred while talking to the server." print("An error occurred while talking to the server.")
print lde print(lde)
if args[0] == "status": if args[0] == "status":
if not disabled: if not disabled:
print "Plugin Enabled" print("Plugin Enabled")
else: else:
print "Plugin Disabled" print("Plugin Disabled")
return 0 return 0
if args[0] == "enable": if args[0] == "enable":
try: try:
if not disabled: if not disabled:
print "Plugin already Enabled" print("Plugin already Enabled")
retval = 2 retval = 2
else: else:
# Remove disable_attr from filter # Remove disable_attr from filter
@@ -162,13 +164,13 @@ def main():
#enable_attr = {'originfilter': enable_attr} #enable_attr = {'originfilter': enable_attr}
entry['originfilter'] = [enable_attr] entry['originfilter'] = [enable_attr]
conn.update_entry(entry) conn.update_entry(entry)
print "Enabling Plugin" print("Enabling Plugin")
retval = 0 retval = 0
except errors.NotFound: except errors.NotFound:
print "Enabling Plugin" print("Enabling Plugin")
except errors.ExecutionError as lde: except errors.ExecutionError as lde:
print "An error occurred while talking to the server." print("An error occurred while talking to the server.")
print lde print(lde)
retval = 1 retval = 1
elif args[0] == "disable": elif args[0] == "disable":
@@ -177,7 +179,7 @@ def main():
# disabling. # disabling.
try: try:
if disabled: if disabled:
print "Plugin already disabled" print("Plugin already disabled")
retval = 2 retval = 2
else: else:
if org_filter[:2] == '(&' and org_filter[-1] == ')': if org_filter[:2] == '(&' and org_filter[-1] == ')':
@@ -186,17 +188,17 @@ def main():
disable_attr = '(&%s(%s))' % (disable_attr, org_filter) disable_attr = '(&%s(%s))' % (disable_attr, org_filter)
entry['originfilter'] = [disable_attr] entry['originfilter'] = [disable_attr]
conn.update_entry(entry) conn.update_entry(entry)
print "Disabling Plugin" print("Disabling Plugin")
except errors.NotFound: except errors.NotFound:
print "Plugin is already disabled" print("Plugin is already disabled")
retval = 2 retval = 2
except errors.DatabaseError as dbe: except errors.DatabaseError as dbe:
print "An error occurred while talking to the server." print("An error occurred while talking to the server.")
print dbe print(dbe)
retval = 1 retval = 1
except errors.ExecutionError as lde: except errors.ExecutionError as lde:
print "An error occurred while talking to the server." print("An error occurred while talking to the server.")
print lde print(lde)
retval = 1 retval = 1
else: else:

View File

@@ -19,6 +19,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
import sys import sys
import os import os
from ipaplatform.paths import paths from ipaplatform.paths import paths
@@ -33,12 +35,12 @@ try:
from ipapython.dn import DN from ipapython.dn import DN
from ipaplatform import services from ipaplatform import services
except ImportError as e: except ImportError as e:
print >> sys.stderr, """\ print("""\
There was a problem importing one of the required Python modules. The There was a problem importing one of the required Python modules. The
error was: error was:
%s %s
""" % e """ % e, file=sys.stderr)
sys.exit(1) sys.exit(1)
nis_config_dn = DN(('cn', 'NIS Server'), ('cn', 'plugins'), ('cn', 'config')) nis_config_dn = DN(('cn', 'NIS Server'), ('cn', 'plugins'), ('cn', 'config'))
@@ -137,8 +139,8 @@ def main():
try: try:
entry = get_entry(nis_config_dn, conn) entry = get_entry(nis_config_dn, conn)
except errors.ExecutionError as lde: except errors.ExecutionError as lde:
print "An error occurred while talking to the server." print("An error occurred while talking to the server.")
print lde print(lde)
retval = 1 retval = 1
# Enable either the portmap or rpcbind service # Enable either the portmap or rpcbind service
@@ -153,23 +155,23 @@ def main():
rpcbind.enable() rpcbind.enable()
servicemsg = rpcbind.service_name servicemsg = rpcbind.service_name
except ipautil.CalledProcessError as cpe: except ipautil.CalledProcessError as cpe:
print "Unable to enable either %s or %s" % (portmap.service_name, rpcbind.service_name) print("Unable to enable either %s or %s" % (portmap.service_name, rpcbind.service_name))
retval = 3 retval = 3
# The cn=config entry for the plugin may already exist but it # The cn=config entry for the plugin may already exist but it
# could be turned off, handle both cases. # could be turned off, handle both cases.
if entry is None: if entry is None:
print "Enabling plugin" print("Enabling plugin")
ld = LDAPUpdate(dm_password=dirman_password, sub_dict={}, ldapi=True) ld = LDAPUpdate(dm_password=dirman_password, sub_dict={}, ldapi=True)
if ld.update(files) != True: if ld.update(files) != True:
retval = 1 retval = 1
elif entry.get('nsslapd-pluginenabled', [''])[0].lower() == 'off': elif entry.get('nsslapd-pluginenabled', [''])[0].lower() == 'off':
print "Enabling plugin" print("Enabling plugin")
# Already configured, just enable the plugin # Already configured, just enable the plugin
entry['nsslapd-pluginenabled'] = ['on'] entry['nsslapd-pluginenabled'] = ['on']
conn.update_entry(entry) conn.update_entry(entry)
else: else:
print "Plugin already Enabled" print("Plugin already Enabled")
retval = 2 retval = 2
elif args[0] == "disable": elif args[0] == "disable":
@@ -178,21 +180,21 @@ def main():
entry['nsslapd-pluginenabled'] = ['off'] entry['nsslapd-pluginenabled'] = ['off']
conn.update_entry(entry) conn.update_entry(entry)
except (errors.NotFound, errors.EmptyModlist): except (errors.NotFound, errors.EmptyModlist):
print "Plugin is already disabled" print("Plugin is already disabled")
retval = 2 retval = 2
except errors.LDAPError as lde: except errors.LDAPError as lde:
print "An error occurred while talking to the server." print("An error occurred while talking to the server.")
print lde print(lde)
retval = 1 retval = 1
else: else:
retval = 1 retval = 1
if retval == 0: if retval == 0:
print "This setting will not take effect until you restart Directory Server." print("This setting will not take effect until you restart Directory Server.")
if args[0] == "enable": if args[0] == "enable":
print "The %s service may need to be started." % servicemsg print("The %s service may need to be started." % servicemsg)
finally: finally:
if conn and conn.isconnected(): if conn and conn.isconnected():

View File

@@ -18,6 +18,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
from ipapython.config import IPAOptionParser from ipapython.config import IPAOptionParser
from ipapython import version from ipapython import version
from ipapython import ipautil from ipapython import ipautil
@@ -54,7 +56,7 @@ class SshExec(object):
def __call__(self, command, verbose=False): def __call__(self, command, verbose=False):
# Bail if ssh is not installed # Bail if ssh is not installed
if self.cmd is None: if self.cmd is None:
print "WARNING: ssh not installed, skipping ssh test" print("WARNING: ssh not installed, skipping ssh test")
return ('', '', 0) return ('', '', 0)
tmpf = tempfile.NamedTemporaryFile() tmpf = tempfile.NamedTemporaryFile()
@@ -91,7 +93,7 @@ BASE_PORTS = [
def print_info(msg): def print_info(msg):
if not QUIET: if not QUIET:
print msg print(msg)
def parse_options(): def parse_options():
parser = IPAOptionParser(version=version.VERSION) parser = IPAOptionParser(version=version.VERSION)
@@ -285,10 +287,10 @@ def port_check(host, port_list):
print_info(" %s (%d): %s" % (port.description, port.port, result)) print_info(" %s (%d): %s" % (port.description, port.port, result))
if ports_udp_warning: if ports_udp_warning:
print "The following UDP ports could not be verified as open: %s" \ print("The following UDP ports could not be verified as open: %s" \
% ", ".join(str(port.port) for port in ports_udp_warning) % ", ".join(str(port.port) for port in ports_udp_warning))
print "This can happen if they are already bound to an application" print("This can happen if they are already bound to an application")
print "and ipa-replica-conncheck cannot attach own UDP responder." print("and ipa-replica-conncheck cannot attach own UDP responder.")
if ports_failed: if ports_failed:
msg_ports = [] msg_ports = []
@@ -394,9 +396,9 @@ def main():
print_info("Check SSH connection to remote master") print_info("Check SSH connection to remote master")
stdout, stderr, returncode = ssh('echo OK', verbose=True) stdout, stderr, returncode = ssh('echo OK', verbose=True)
if returncode != 0: if returncode != 0:
print 'Could not SSH into remote host. Error output:' print('Could not SSH into remote host. Error output:')
for line in stderr.splitlines(): for line in stderr.splitlines():
print ' %s' % line print(' %s' % line)
raise RuntimeError('Could not SSH to remote host.') raise RuntimeError('Could not SSH to remote host.')
print_info("Execute check on remote master") print_info("Execute check on remote master")

View File

@@ -17,6 +17,9 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
import sys import sys
import os import os
@@ -159,14 +162,14 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose, nolookup=False):
else: else:
conn.do_sasl_gssapi_bind() conn.do_sasl_gssapi_bind()
except Exception as e: except Exception as e:
print "Failed to connect to host '%s': %s" % (host, str(e)) print("Failed to connect to host '%s': %s" % (host, str(e)))
return return
dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), ipautil.realm_to_suffix(realm)) dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), ipautil.realm_to_suffix(realm))
try: try:
entries = conn.get_entries(dn, conn.SCOPE_ONELEVEL) entries = conn.get_entries(dn, conn.SCOPE_ONELEVEL)
except Exception: except Exception:
print "Failed to read master data from '%s': %s" % (host, str(e)) print("Failed to read master data from '%s': %s" % (host, str(e)))
return return
else: else:
for ent in entries: for ent in entries:
@@ -184,7 +187,7 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose, nolookup=False):
if not replica: if not replica:
for k, p in peers.items(): for k, p in peers.items():
print '%s: %s' % (k, p[0]) print('%s: %s' % (k, p[0]))
return return
# ok we are being ask for info about a specific replica # ok we are being ask for info about a specific replica
@@ -195,7 +198,7 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose, nolookup=False):
winsync_peer = p[1] winsync_peer = p[1]
if not is_replica: if not is_replica:
print "Cannot find %s in public server list" % replica print("Cannot find %s in public server list" % replica)
return return
try: try:
@@ -213,22 +216,22 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose, nolookup=False):
entries = repl.find_replication_agreements() entries = repl.find_replication_agreements()
ent_type = 'replica' ent_type = 'replica'
except Exception as e: except Exception as e:
print "Failed to get data from '%s': %s" % (replica, e) print("Failed to get data from '%s': %s" % (replica, e))
return return
for entry in entries: for entry in entries:
print '%s: %s' % (entry.single_value.get('nsds5replicahost'), ent_type) print('%s: %s' % (entry.single_value.get('nsds5replicahost'), ent_type))
if verbose: if verbose:
print " last init status: %s" % entry.single_value.get( print(" last init status: %s" % entry.single_value.get(
'nsds5replicalastinitstatus') 'nsds5replicalastinitstatus'))
print " last init ended: %s" % str(ipautil.parse_generalized_time( print(" last init ended: %s" % str(ipautil.parse_generalized_time(
entry.single_value['nsds5replicalastinitend'])) entry.single_value['nsds5replicalastinitend'])))
print " last update status: %s" % entry.single_value.get( print(" last update status: %s" % entry.single_value.get(
'nsds5replicalastupdatestatus') 'nsds5replicalastupdatestatus'))
print " last update ended: %s" % str( print(" last update ended: %s" % str(
ipautil.parse_generalized_time( ipautil.parse_generalized_time(
entry.single_value['nsds5replicalastupdateend'])) entry.single_value['nsds5replicalastupdateend'])))
def del_link(realm, replica1, replica2, dirman_passwd, force=False): def del_link(realm, replica1, replica2, dirman_passwd, force=False):
""" """
@@ -253,21 +256,21 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
# the new topology plugin naming convention: <A>-to-<B> instead of # the new topology plugin naming convention: <A>-to-<B> instead of
# meTo<B>. # meTo<B>.
if managed_topology: if managed_topology:
print "'%s' has no winsync replication agreement for '%s'" % (replica1, replica2) print("'%s' has no winsync replication agreement for '%s'" % (replica1, replica2))
exit_on_managed_topology(what) exit_on_managed_topology(what)
else: else:
print "'%s' has no replication agreement for '%s'" % (replica1, replica2) print("'%s' has no replication agreement for '%s'" % (replica1, replica2))
return False return False
except Exception as e: except Exception as e:
print "Failed to determine agreement type for '%s': %s" % (replica2, e) print("Failed to determine agreement type for '%s': %s" % (replica2, e))
if type1 == replication.IPA_REPLICA and managed_topology: if type1 == replication.IPA_REPLICA and managed_topology:
exit_on_managed_topology(what) exit_on_managed_topology(what)
repl_list = repl1.find_ipa_replication_agreements() repl_list = repl1.find_ipa_replication_agreements()
if not force and len(repl_list) <= 1 and type1 == replication.IPA_REPLICA: if not force and len(repl_list) <= 1 and type1 == replication.IPA_REPLICA:
print "Cannot remove the last replication link of '%s'" % replica1 print("Cannot remove the last replication link of '%s'" % replica1)
print "Please use the 'del' command to remove it from the domain" print("Please use the 'del' command to remove it from the domain")
return False return False
if type1 == replication.IPA_REPLICA: if type1 == replication.IPA_REPLICA:
@@ -276,16 +279,16 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
repl_list = repl2.find_ipa_replication_agreements() repl_list = repl2.find_ipa_replication_agreements()
if not force and len(repl_list) <= 1: if not force and len(repl_list) <= 1:
print "Cannot remove the last replication link of '%s'" % replica2 print("Cannot remove the last replication link of '%s'" % replica2)
print "Please use the 'del' command to remove it from the domain" print("Please use the 'del' command to remove it from the domain")
return False return False
except errors.NotFound: except errors.NotFound:
print "'%s' has no replication agreement for '%s'" % (replica2, replica1) print("'%s' has no replication agreement for '%s'" % (replica2, replica1))
if not force: if not force:
return False return False
except Exception as e: except Exception as e:
print "Failed to get list of agreements from '%s': %s" % (replica2, e) print("Failed to get list of agreements from '%s': %s" % (replica2, e))
if not force: if not force:
return False return False
@@ -300,28 +303,28 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
(next_start, next_max) = repl2.get_DNA_next_range(repl2.conn.host) (next_start, next_max) = repl2.get_DNA_next_range(repl2.conn.host)
if range_start is not None: if range_start is not None:
if not store_DNA_range(repl1, range_start, range_max, repl2.conn.host, realm, dirman_passwd): if not store_DNA_range(repl1, range_start, range_max, repl2.conn.host, realm, dirman_passwd):
print "Unable to save DNA range %d-%d" % (range_start, range_max) print("Unable to save DNA range %d-%d" % (range_start, range_max))
if next_start is not None: if next_start is not None:
if not store_DNA_range(repl1, next_start, next_max, repl2.conn.host, realm, dirman_passwd): if not store_DNA_range(repl1, next_start, next_max, repl2.conn.host, realm, dirman_passwd):
print "Unable to save DNA range %d-%d" % (next_start, next_max) print("Unable to save DNA range %d-%d" % (next_start, next_max))
repl2.set_readonly(readonly=False) repl2.set_readonly(readonly=False)
repl2.delete_agreement(replica1) repl2.delete_agreement(replica1)
repl2.delete_referral(replica1) repl2.delete_referral(replica1)
repl2.set_readonly(readonly=False) repl2.set_readonly(readonly=False)
except Exception as e: except Exception as e:
print "Unable to remove agreement on %s: %s" % (replica2, e) print("Unable to remove agreement on %s: %s" % (replica2, e))
failed = True failed = True
if failed: if failed:
if force: if force:
print "Forcing removal on '%s'" % replica1 print("Forcing removal on '%s'" % replica1)
print "Any DNA range on '%s' will be lost" % replica2 print("Any DNA range on '%s' will be lost" % replica2)
else: else:
return False return False
if not repl2 and force: if not repl2 and force:
print "Forcing removal on '%s'" % replica1 print("Forcing removal on '%s'" % replica1)
print "Any DNA range on '%s' will be lost" % replica2 print("Any DNA range on '%s' will be lost" % replica2)
repl1.delete_agreement(replica2) repl1.delete_agreement(replica2)
repl1.delete_referral(replica2) repl1.delete_referral(replica2)
@@ -336,9 +339,9 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
for entry in entries: for entry in entries:
repl1.conn.delete_entry(entry) repl1.conn.delete_entry(entry)
except Exception as e: except Exception as e:
print "Error deleting winsync replica shared info: %s" % e print("Error deleting winsync replica shared info: %s" % e)
print "Deleted replication agreement from '%s' to '%s'" % (replica1, replica2) print("Deleted replication agreement from '%s' to '%s'" % (replica1, replica2))
return True return True
@@ -353,7 +356,7 @@ def get_ruv(realm, host, dirman_passwd, nolookup=False):
try: try:
thisrepl = replication.ReplicationManager(realm, host, dirman_passwd) thisrepl = replication.ReplicationManager(realm, host, dirman_passwd)
except Exception as e: except Exception as e:
print "Failed to connect to server %s: %s" % (host, e) print("Failed to connect to server %s: %s" % (host, e))
sys.exit(1) sys.exit(1)
search_filter = '(&(nsuniqueid=ffffffff-ffffffff-ffffffff-ffffffff)(objectclass=nstombstone))' search_filter = '(&(nsuniqueid=ffffffff-ffffffff-ffffffff-ffffffff)(objectclass=nstombstone))'
@@ -362,7 +365,7 @@ def get_ruv(realm, host, dirman_passwd, nolookup=False):
api.env.basedn, thisrepl.conn.SCOPE_SUBTREE, search_filter, api.env.basedn, thisrepl.conn.SCOPE_SUBTREE, search_filter,
['nsds50ruv']) ['nsds50ruv'])
except errors.NotFound: except errors.NotFound:
print "No RUV records found." print("No RUV records found.")
sys.exit(0) sys.exit(0)
servers = [] servers = []
@@ -376,7 +379,7 @@ def get_ruv(realm, host, dirman_passwd, nolookup=False):
(scheme, netloc, path, params, query, fragment) = urlparse.urlparse(data.group(2)) (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(data.group(2))
servers.append((netloc, rid)) servers.append((netloc, rid))
else: else:
print "unable to decode: %s" % ruv print("unable to decode: %s" % ruv)
return servers return servers
@@ -388,7 +391,7 @@ def list_ruv(realm, host, dirman_passwd, verbose, nolookup=False):
servers = get_ruv(realm, host, dirman_passwd, nolookup) servers = get_ruv(realm, host, dirman_passwd, nolookup)
for (netloc, rid) in servers: for (netloc, rid) in servers:
print "%s: %s" % (netloc, rid) print("%s: %s" % (netloc, rid))
def get_rid_by_host(realm, sourcehost, host, dirman_passwd, nolookup=False): def get_rid_by_host(realm, sourcehost, host, dirman_passwd, nolookup=False):
""" """
@@ -420,18 +423,18 @@ def clean_ruv(realm, ruv, options):
if not found: if not found:
sys.exit("Replica ID %s not found" % ruv) sys.exit("Replica ID %s not found" % ruv)
print "Clean the Replication Update Vector for %s" % hostname print("Clean the Replication Update Vector for %s" % hostname)
print print()
print "Cleaning the wrong replica ID will cause that server to no" print("Cleaning the wrong replica ID will cause that server to no")
print "longer replicate so it may miss updates while the process" print("longer replicate so it may miss updates while the process")
print "is running. It would need to be re-initialized to maintain" print("is running. It would need to be re-initialized to maintain")
print "consistency. Be very careful." print("consistency. Be very careful.")
if not options.force and not ipautil.user_input("Continue to clean?", False): if not options.force and not ipautil.user_input("Continue to clean?", False):
sys.exit("Aborted") sys.exit("Aborted")
thisrepl = replication.ReplicationManager(realm, options.host, thisrepl = replication.ReplicationManager(realm, options.host,
options.dirman_passwd) options.dirman_passwd)
thisrepl.cleanallruv(ruv) thisrepl.cleanallruv(ruv)
print "Cleanup task created" print("Cleanup task created")
def abort_clean_ruv(realm, ruv, options): def abort_clean_ruv(realm, ruv, options):
""" """
@@ -466,13 +469,13 @@ def abort_clean_ruv(realm, ruv, options):
if not found: if not found:
sys.exit("Replica ID %s not found" % ruv) sys.exit("Replica ID %s not found" % ruv)
print "Aborting the clean Replication Update Vector task for %s" % hostname print("Aborting the clean Replication Update Vector task for %s" % hostname)
print print()
thisrepl = replication.ReplicationManager(realm, options.host, thisrepl = replication.ReplicationManager(realm, options.host,
options.dirman_passwd) options.dirman_passwd)
thisrepl.abortcleanallruv(ruv, options.force) thisrepl.abortcleanallruv(ruv, options.force)
print "Cleanup task stopped" print("Cleanup task stopped")
def list_clean_ruv(realm, host, dirman_passwd, verbose, nolookup=False): def list_clean_ruv(realm, host, dirman_passwd, verbose, nolookup=False):
""" """
@@ -487,33 +490,33 @@ def list_clean_ruv(realm, host, dirman_passwd, verbose, nolookup=False):
try: try:
entries = repl.conn.get_entries(dn, repl.conn.SCOPE_ONELEVEL) entries = repl.conn.get_entries(dn, repl.conn.SCOPE_ONELEVEL)
except errors.NotFound: except errors.NotFound:
print "No CLEANALLRUV tasks running" print("No CLEANALLRUV tasks running")
else: else:
print "CLEANALLRUV tasks" print("CLEANALLRUV tasks")
for entry in entries: for entry in entries:
name = entry.single_value['cn'].replace('clean ', '') name = entry.single_value['cn'].replace('clean ', '')
status = entry.single_value.get('nsTaskStatus') status = entry.single_value.get('nsTaskStatus')
print "RID %s: %s" % (name, status) print("RID %s: %s" % (name, status))
if verbose: if verbose:
print str(dn) print(str(dn))
print entry.single_value.get('nstasklog') print(entry.single_value.get('nstasklog'))
print print()
dn = DN(('cn', 'abort cleanallruv'),('cn', 'tasks'), ('cn', 'config')) dn = DN(('cn', 'abort cleanallruv'),('cn', 'tasks'), ('cn', 'config'))
try: try:
entries = repl.conn.get_entries(dn, repl.conn.SCOPE_ONELEVEL) entries = repl.conn.get_entries(dn, repl.conn.SCOPE_ONELEVEL)
except errors.NotFound: except errors.NotFound:
print "No abort CLEANALLRUV tasks running" print("No abort CLEANALLRUV tasks running")
else: else:
print "Abort CLEANALLRUV tasks" print("Abort CLEANALLRUV tasks")
for entry in entries: for entry in entries:
name = entry.single_value['cn'].replace('abort ', '') name = entry.single_value['cn'].replace('abort ', '')
status = entry.single_value.get('nsTaskStatus') status = entry.single_value.get('nsTaskStatus')
print "RID %s: %s" % (name, status) print("RID %s: %s" % (name, status))
if verbose: if verbose:
print str(dn) print(str(dn))
print entry.single_value.get('nstasklog') print(entry.single_value.get('nstasklog'))
def check_last_link(delrepl, realm, dirman_passwd, force): def check_last_link(delrepl, realm, dirman_passwd, force):
""" """
@@ -547,7 +550,7 @@ def check_last_link(delrepl, realm, dirman_passwd, force):
try: try:
repl = replication.ReplicationManager(realm, replica, dirman_passwd) repl = replication.ReplicationManager(realm, replica, dirman_passwd)
except errors.NetworkError: except errors.NetworkError:
print "Unable to validate that '%s' will not be orphaned." % replica print("Unable to validate that '%s' will not be orphaned." % replica)
if not force and not ipautil.user_input("Continue to delete?", False): if not force and not ipautil.user_input("Continue to delete?", False):
sys.exit("Aborted") sys.exit("Aborted")
@@ -579,9 +582,9 @@ def check_last_link_managed(api, masters, hostname, force):
# check topology before removal # check topology before removal
orig_errors = get_topology_connection_errors(graph) orig_errors = get_topology_connection_errors(graph)
if orig_errors: if orig_errors:
print "Current topology is disconnected:" print("Current topology is disconnected:")
print "Changes are not replicated to all servers and data are probably inconsistent." print("Changes are not replicated to all servers and data are probably inconsistent.")
print "You need to add segments to reconnect the topology." print("You need to add segments to reconnect the topology.")
print_connect_errors(orig_errors) print_connect_errors(orig_errors)
# after removal # after removal
@@ -592,25 +595,25 @@ def check_last_link_managed(api, masters, hostname, force):
new_errors = get_topology_connection_errors(graph) new_errors = get_topology_connection_errors(graph)
if new_errors: if new_errors:
print "WARNING: Topology after removal of %s will be disconnected." % hostname print("WARNING: Topology after removal of %s will be disconnected." % hostname)
print "Changes will not be replicated to all servers and data will become inconsistent." print("Changes will not be replicated to all servers and data will become inconsistent.")
print "You need to add segments to prevent disconnection of the topology." print("You need to add segments to prevent disconnection of the topology.")
print "Errors in topology after removal:" print("Errors in topology after removal:")
print_connect_errors(new_errors) print_connect_errors(new_errors)
if orig_errors or new_errors: if orig_errors or new_errors:
if not force: if not force:
sys.exit("Aborted") sys.exit("Aborted")
else: else:
print "Forcing removal of %s" % hostname print("Forcing removal of %s" % hostname)
return (orig_errors, new_errors) return (orig_errors, new_errors)
def print_connect_errors(errors): def print_connect_errors(errors):
for error in errors: for error in errors:
print "Topology does not allow server %s to replicate with servers:" % error[0] print("Topology does not allow server %s to replicate with servers:" % error[0])
for srv in error[2]: for srv in error[2]:
print " %s" % srv print(" %s" % srv)
def enforce_host_existence(host, message=None): def enforce_host_existence(host, message=None):
if host is not None and not ipautil.host_exists(host): if host is not None and not ipautil.host_exists(host):
@@ -647,13 +650,13 @@ def ensure_last_services(conn, hostname, masters, options):
ca_hostname = master_cn ca_hostname = master_cn
if 'CA' in this_services and not any(['CA' in o for o in other_services]): if 'CA' in this_services and not any(['CA' in o for o in other_services]):
print "Deleting this server is not allowed as it would leave your installation without a CA." print("Deleting this server is not allowed as it would leave your installation without a CA.")
sys.exit(1) sys.exit(1)
other_dns = True other_dns = True
if 'DNS' in this_services and not any(['DNS' in o for o in other_services]): if 'DNS' in this_services and not any(['DNS' in o for o in other_services]):
other_dns = False other_dns = False
print "Deleting this server will leave your installation without a DNS." print("Deleting this server will leave your installation without a DNS.")
if not options.force and not ipautil.user_input("Continue to delete?", False): if not options.force and not ipautil.user_input("Continue to delete?", False):
sys.exit("Deletion aborted") sys.exit("Deletion aborted")
@@ -662,8 +665,8 @@ def ensure_last_services(conn, hostname, masters, options):
if 'DNS' in this_services and other_dns and not options.force: if 'DNS' in this_services and other_dns and not options.force:
dnssec_masters = opendnssecinstance.get_dnssec_key_masters(conn) dnssec_masters = opendnssecinstance.get_dnssec_key_masters(conn)
if hostname in dnssec_masters: if hostname in dnssec_masters:
print "Replica is active DNSSEC key master. Uninstall could break your DNS system." print("Replica is active DNSSEC key master. Uninstall could break your DNS system.")
print "Please disable or replace DNSSEC key master first." print("Please disable or replace DNSSEC key master first.")
sys.exit("Deletion aborted") sys.exit("Deletion aborted")
ca = cainstance.CAInstance(api.env.realm, certs.NSS_DIR) ca = cainstance.CAInstance(api.env.realm, certs.NSS_DIR)
@@ -688,8 +691,8 @@ def cleanup_server_dns_entries(realm, hostname, suffix, options):
keysyncd = dnskeysyncinstance.DNSKeySyncInstance() keysyncd = dnskeysyncinstance.DNSKeySyncInstance()
keysyncd.remove_replica_public_keys(hostname) keysyncd.remove_replica_public_keys(hostname)
except Exception as e: except Exception as e:
print "Failed to cleanup %s DNS entries: %s" % (hostname, e) print("Failed to cleanup %s DNS entries: %s" % (hostname, e))
print "You may need to manually remove them from the tree" print("You may need to manually remove them from the tree")
def del_master(realm, hostname, options): def del_master(realm, hostname, options):
@@ -706,7 +709,7 @@ def del_master_managed(realm, hostname, options):
hostname_u = unicode(hostname) hostname_u = unicode(hostname)
if hostname == options.host: if hostname == options.host:
print "Can't remove itself: %s" % (options.host) print("Can't remove itself: %s" % (options.host))
sys.exit(1) sys.exit(1)
# 1. Connect to the local server # 1. Connect to the local server
@@ -714,7 +717,7 @@ def del_master_managed(realm, hostname, options):
thisrepl = replication.ReplicationManager(realm, options.host, thisrepl = replication.ReplicationManager(realm, options.host,
options.dirman_passwd) options.dirman_passwd)
except Exception as e: except Exception as e:
print "Failed to connect to server %s: %s" % (options.host, e) print("Failed to connect to server %s: %s" % (options.host, e))
sys.exit(1) sys.exit(1)
# 2. Get all masters # 2. Get all masters
@@ -735,14 +738,14 @@ def del_master_managed(realm, hostname, options):
try: try:
api.Command.server_del(hostname_u) api.Command.server_del(hostname_u)
except errors.NotFound: except errors.NotFound:
print "Server entry already deleted: %s" % (hostname) print("Server entry already deleted: %s" % (hostname))
# 6. Cleanup # 6. Cleanup
try: try:
thisrepl.replica_cleanup(hostname, realm, force=True) thisrepl.replica_cleanup(hostname, realm, force=True)
except Exception as e: except Exception as e:
print "Failed to cleanup %s entries: %s" % (hostname, e) print("Failed to cleanup %s entries: %s" % (hostname, e))
print "You may need to manually remove them from the tree" print("You may need to manually remove them from the tree")
# 7. Clean RUV for the deleted master # 7. Clean RUV for the deleted master
# Wait for topology plugin to delete segments # Wait for topology plugin to delete segments
@@ -757,7 +760,7 @@ def del_master_managed(realm, hostname, options):
# If the server was already deleted, we can expect that all removals # If the server was already deleted, we can expect that all removals
# had been done in previous run and dangling segments were not deleted. # had been done in previous run and dangling segments were not deleted.
if hostname not in m_cns: if hostname not in m_cns:
print "Skipping replication agreement deletion check" print("Skipping replication agreement deletion check")
break break
# Relax check if topology was or is disconnected. Disconnected topology # Relax check if topology was or is disconnected. Disconnected topology
@@ -778,18 +781,18 @@ def del_master_managed(realm, hostname, options):
right = [s for s in right if s['iparepltoposegmentleftnode'][0] in can_contact_me] right = [s for s in right if s['iparepltoposegmentleftnode'][0] in can_contact_me]
if not left and not right: if not left and not right:
print "Agreements deleted" print("Agreements deleted")
break break
time.sleep(2) time.sleep(2)
if i == 2: # taking too long, something is wrong, report if i == 2: # taking too long, something is wrong, report
print "Waiting for removal of replication agreements" print("Waiting for removal of replication agreements")
if i > 90: if i > 90:
print "Taking too long, skipping" print("Taking too long, skipping")
print "Following segments were not deleted:" print("Following segments were not deleted:")
for s in left: for s in left:
print " %s" % s['cn'][0] print(" %s" % s['cn'][0])
for s in right: for s in right:
print " %s" % s['cn'][0] print(" %s" % s['cn'][0])
break break
i += 1 i += 1
@@ -798,7 +801,7 @@ def del_master_managed(realm, hostname, options):
try: try:
thisrepl.cleanallruv(rid) thisrepl.cleanallruv(rid)
except KeyboardInterrupt: except KeyboardInterrupt:
print "Wait for task interrupted. It will continue to run in the background" print("Wait for task interrupted. It will continue to run in the background")
# 8. And clean up the removed replica DNS entries if any. # 8. And clean up the removed replica DNS entries if any.
cleanup_server_dns_entries(realm, hostname, thisrepl.suffix, options) cleanup_server_dns_entries(realm, hostname, thisrepl.suffix, options)
@@ -816,7 +819,7 @@ def del_master_direct(realm, hostname, options):
thisrepl = replication.ReplicationManager(realm, options.host, thisrepl = replication.ReplicationManager(realm, options.host,
options.dirman_passwd) options.dirman_passwd)
except Exception as e: except Exception as e:
print "Failed to connect to server %s: %s" % (options.host, e) print("Failed to connect to server %s: %s" % (options.host, e))
sys.exit(1) sys.exit(1)
# 2. Ensure we have an agreement with the master # 2. Ensure we have an agreement with the master
@@ -829,8 +832,8 @@ def del_master_direct(realm, hostname, options):
removes that master from the list of masters. If the master removes that master from the list of masters. If the master
were to try to come back online it wouldn't work at all. were to try to come back online it wouldn't work at all.
""" """
print "Cleaning a master is irreversible." print("Cleaning a master is irreversible.")
print "This should not normally be require, so use cautiously." print("This should not normally be require, so use cautiously.")
if not ipautil.user_input("Continue to clean master?", False): if not ipautil.user_input("Continue to clean master?", False):
sys.exit("Cleanup aborted") sys.exit("Cleanup aborted")
thisrepl.replica_cleanup(hostname, realm, force=True) thisrepl.replica_cleanup(hostname, realm, force=True)
@@ -845,12 +848,12 @@ def del_master_direct(realm, hostname, options):
try: try:
delrepl = replication.ReplicationManager(realm, hostname, options.dirman_passwd) delrepl = replication.ReplicationManager(realm, hostname, options.dirman_passwd)
except Exception as e: except Exception as e:
print "Connection to '%s' failed: %s" % (hostname, e) print("Connection to '%s' failed: %s" % (hostname, e))
if not options.force: if not options.force:
print "Unable to delete replica '%s'" % hostname print("Unable to delete replica '%s'" % hostname)
sys.exit(1) sys.exit(1)
else: else:
print "Forcing removal of %s" % hostname print("Forcing removal of %s" % hostname)
force_del = True force_del = True
if force_del: if force_del:
@@ -877,10 +880,10 @@ def del_master_direct(realm, hostname, options):
replica_names = [options.host] replica_names = [options.host]
if not winsync and not options.force: if not winsync and not options.force:
print "Deleting a master is irreversible." print("Deleting a master is irreversible.")
print "To reconnect to the remote master you will need to prepare " \ print("To reconnect to the remote master you will need to prepare " \
"a new replica file" "a new replica file")
print "and re-install." print("and re-install.")
if not ipautil.user_input("Continue to delete?", False): if not ipautil.user_input("Continue to delete?", False):
sys.exit("Deletion aborted") sys.exit("Deletion aborted")
@@ -890,9 +893,9 @@ def del_master_direct(realm, hostname, options):
masters = api.Command.server_find('', sizelimit=0)['result'] masters = api.Command.server_find('', sizelimit=0)['result']
except Exception as e: except Exception as e:
masters = [] masters = []
print "Failed to read masters data from '%s': %s" % ( print("Failed to read masters data from '%s': %s" % (
delrepl.hostname, e) delrepl.hostname, e))
print "Skipping calculation to determine if one or more masters would be orphaned." print("Skipping calculation to determine if one or more masters would be orphaned.")
if not options.force: if not options.force:
sys.exit(1) sys.exit(1)
@@ -901,15 +904,15 @@ def del_master_direct(realm, hostname, options):
if len(masters) > 2: if len(masters) > 2:
orphaned_server = check_last_link(delrepl, realm, options.dirman_passwd, options.force) orphaned_server = check_last_link(delrepl, realm, options.dirman_passwd, options.force)
if orphaned_server is not None: if orphaned_server is not None:
print "Deleting this server will orphan '%s'. " % orphaned_server print("Deleting this server will orphan '%s'. " % orphaned_server)
print "You will need to reconfigure your replication topology to delete this server." print("You will need to reconfigure your replication topology to delete this server.")
sys.exit(1) sys.exit(1)
# 4. Check that we are not leaving the installation without CA and/or DNS # 4. Check that we are not leaving the installation without CA and/or DNS
# And pick new CA master. # And pick new CA master.
ensure_last_services(thisrepl.conn, hostname, masters, options) ensure_last_services(thisrepl.conn, hostname, masters, options)
else: else:
print "Skipping calculation to determine if one or more masters would be orphaned." print("Skipping calculation to determine if one or more masters would be orphaned.")
# Save the RID value before we start deleting # Save the RID value before we start deleting
if repltype == replication.IPA_REPLICA: if repltype == replication.IPA_REPLICA:
@@ -918,28 +921,28 @@ def del_master_direct(realm, hostname, options):
# 4. Remove each agreement # 4. Remove each agreement
print "Deleting replication agreements between %s and %s" % (hostname, ', '.join(replica_names)) print("Deleting replication agreements between %s and %s" % (hostname, ', '.join(replica_names)))
for r in replica_names: for r in replica_names:
try: try:
if not del_link(realm, r, hostname, options.dirman_passwd, force=True): if not del_link(realm, r, hostname, options.dirman_passwd, force=True):
print "Unable to remove replication agreement for %s from %s." % (hostname, r) print("Unable to remove replication agreement for %s from %s." % (hostname, r))
except Exception as e: except Exception as e:
print ("There were issues removing a connection for %s " print(("There were issues removing a connection for %s "
"from %s: %s" % (hostname, r, e)) "from %s: %s" % (hostname, r, e)))
# 5. Clean RUV for the deleted master # 5. Clean RUV for the deleted master
if repltype == replication.IPA_REPLICA and rid is not None: if repltype == replication.IPA_REPLICA and rid is not None:
try: try:
thisrepl.cleanallruv(rid) thisrepl.cleanallruv(rid)
except KeyboardInterrupt: except KeyboardInterrupt:
print "Wait for task interrupted. It will continue to run in the background" print("Wait for task interrupted. It will continue to run in the background")
# 6. Finally clean up the removed replica common entries. # 6. Finally clean up the removed replica common entries.
try: try:
thisrepl.replica_cleanup(hostname, realm, force=True) thisrepl.replica_cleanup(hostname, realm, force=True)
except Exception as e: except Exception as e:
print "Failed to cleanup %s entries: %s" % (hostname, e) print("Failed to cleanup %s entries: %s" % (hostname, e))
print "You may need to manually remove them from the tree" print("You may need to manually remove them from the tree")
# 7. And clean up the removed replica DNS entries if any. # 7. And clean up the removed replica DNS entries if any.
cleanup_server_dns_entries(realm, hostname, thisrepl.suffix, options) cleanup_server_dns_entries(realm, hostname, thisrepl.suffix, options)
@@ -963,10 +966,10 @@ def add_link(realm, replica1, replica2, dirman_passwd, options):
try: try:
repl = replication.ReplicationManager(realm, replica1, dirman_passwd) repl = replication.ReplicationManager(realm, replica1, dirman_passwd)
except errors.NotFound: except errors.NotFound:
print "Cannot find replica '%s'" % replica1 print("Cannot find replica '%s'" % replica1)
return return
except Exception as e: except Exception as e:
print "Failed to connect to '%s': %s" % (replica1, e) print("Failed to connect to '%s': %s" % (replica1, e))
return return
# See if we already have an agreement with this host # See if we already have an agreement with this host
@@ -985,20 +988,20 @@ def add_link(realm, replica1, replica2, dirman_passwd, options):
ds = dsinstance.DsInstance(realm_name = realm, ds = dsinstance.DsInstance(realm_name = realm,
dm_password = dirman_passwd) dm_password = dirman_passwd)
if not ds.add_ca_cert(options.cacert): if not ds.add_ca_cert(options.cacert):
print "Could not load the required CA certificate file [%s]" % options.cacert print("Could not load the required CA certificate file [%s]" % options.cacert)
return return
else: else:
print "Added CA certificate %s to certificate database for %s" % (options.cacert, replica1) print("Added CA certificate %s to certificate database for %s" % (options.cacert, replica1))
# need to wait until cacert is installed as that command may restart # need to wait until cacert is installed as that command may restart
# the directory server and kill the connection # the directory server and kill the connection
try: try:
repl1 = replication.ReplicationManager(realm, replica1, dirman_passwd) repl1 = replication.ReplicationManager(realm, replica1, dirman_passwd)
except errors.NotFound: except errors.NotFound:
print "Cannot find replica '%s'" % replica1 print("Cannot find replica '%s'" % replica1)
return return
except Exception as e: except Exception as e:
print "Failed to connect to '%s': %s" % (replica1, e) print("Failed to connect to '%s': %s" % (replica1, e))
return return
if options.winsync: if options.winsync:
@@ -1040,7 +1043,7 @@ def add_link(realm, replica1, replica2, dirman_passwd, options):
sys.exit("Connection to %s unsuccessful." % replica2) sys.exit("Connection to %s unsuccessful." % replica2)
repl1.setup_gssapi_replication(replica2, DN(('cn', 'Directory Manager')), dirman_passwd) repl1.setup_gssapi_replication(replica2, DN(('cn', 'Directory Manager')), dirman_passwd)
print "Connected '%s' to '%s'" % (replica1, replica2) print("Connected '%s' to '%s'" % (replica1, replica2))
def re_initialize(realm, thishost, fromhost, dirman_passwd, nolookup=False): def re_initialize(realm, thishost, fromhost, dirman_passwd, nolookup=False):
@@ -1132,28 +1135,28 @@ def show_DNA_ranges(hostname, master, realm, dirman_passwd, nextrange=False,
try: try:
repl2 = replication.ReplicationManager(realm, remote, dirman_passwd) repl2 = replication.ReplicationManager(realm, remote, dirman_passwd)
except Exception as e: except Exception as e:
print "%s: Connection failed: %s" % (remote, e) print("%s: Connection failed: %s" % (remote, e))
continue continue
if not nextrange: if not nextrange:
try: try:
(start, max) = repl2.get_DNA_range(remote) (start, max) = repl2.get_DNA_range(remote)
except errors.NotFound: except errors.NotFound:
print "%s: No permission to read DNA configuration" % remote print("%s: No permission to read DNA configuration" % remote)
continue continue
if start is None: if start is None:
print "%s: No range set" % remote print("%s: No range set" % remote)
else: else:
print "%s: %s-%s" % (remote, start, max) print("%s: %s-%s" % (remote, start, max))
else: else:
try: try:
(next_start, next_max) = repl2.get_DNA_next_range(remote) (next_start, next_max) = repl2.get_DNA_next_range(remote)
except errors.NotFound: except errors.NotFound:
print "%s: No permission to read DNA configuration" % remote print("%s: No permission to read DNA configuration" % remote)
continue continue
if next_start is None: if next_start is None:
print "%s: No on-deck range set" % remote print("%s: No on-deck range set" % remote)
else: else:
print "%s: %s-%s" % (remote, next_start, next_max) print("%s: %s-%s" % (remote, next_start, next_max))
return False return False
@@ -1188,14 +1191,14 @@ def store_DNA_range(repl, range_start, range_max, deleted_master, realm,
try: try:
repl2 = replication.ReplicationManager(realm, candidate, dirman_passwd) repl2 = replication.ReplicationManager(realm, candidate, dirman_passwd)
except Exception as e: except Exception as e:
print "Connection failed: %s" % e print("Connection failed: %s" % e)
continue continue
(next_start, next_max) = repl2.get_DNA_next_range(candidate) (next_start, next_max) = repl2.get_DNA_next_range(candidate)
if next_start is None: if next_start is None:
try: try:
return repl2.save_DNA_next_range(range_start, range_max) return repl2.save_DNA_next_range(range_start, range_max)
except Exception as e: except Exception as e:
print '%s: %s' % (candidate, e) print('%s: %s' % (candidate, e))
return False return False
@@ -1280,13 +1283,13 @@ def set_DNA_range(hostname, range, realm, dirman_passwd, next_range=False,
try: try:
repl2 = replication.ReplicationManager(realm, master, dirman_passwd) repl2 = replication.ReplicationManager(realm, master, dirman_passwd)
except Exception as e: except Exception as e:
print "Connection to %s failed: %s" % (master, e) print("Connection to %s failed: %s" % (master, e))
print "Overlap not checked." print("Overlap not checked.")
continue continue
try: try:
(entry_start, entry_max) = repl2.get_DNA_range(master) (entry_start, entry_max) = repl2.get_DNA_range(master)
except errors.NotFound: except errors.NotFound:
print "%s: No permission to read DNA configuration" % master print("%s: No permission to read DNA configuration" % master)
continue continue
if (entry_start is not None and if (entry_start is not None and
range_intersection(entry_start, entry_max, range_intersection(entry_start, entry_max,
@@ -1418,13 +1421,13 @@ def main():
del_master(realm, args[1], options) del_master(realm, args[1], options)
elif args[0] == "re-initialize": elif args[0] == "re-initialize":
if not options.fromhost: if not options.fromhost:
print "re-initialize requires the option --from <host name>" print("re-initialize requires the option --from <host name>")
sys.exit(1) sys.exit(1)
re_initialize(realm, host, options.fromhost, dirman_passwd, re_initialize(realm, host, options.fromhost, dirman_passwd,
options.nolookup) options.nolookup)
elif args[0] == "force-sync": elif args[0] == "force-sync":
if not options.fromhost: if not options.fromhost:
print "force-sync requires the option --from <host name>" print("force-sync requires the option --from <host name>")
sys.exit(1) sys.exit(1)
force_sync(realm, host, options.fromhost, options.dirman_passwd, force_sync(realm, host, options.fromhost, options.dirman_passwd,
options.nolookup) options.nolookup)
@@ -1481,8 +1484,8 @@ except SystemExit as e:
except RuntimeError as e: except RuntimeError as e:
sys.exit(e) sys.exit(e)
except socket.timeout: except socket.timeout:
print "Connection timed out." print("Connection timed out.")
sys.exit(1) sys.exit(1)
except Exception as e: except Exception as e:
print "unexpected error: %s" % str(e) print("unexpected error: %s" % str(e))
sys.exit(1) sys.exit(1)

View File

@@ -18,6 +18,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
import sys import sys
import os import os
import json import json
@@ -87,7 +89,7 @@ def get_capture_output(service, debug):
tons and tons of information. tons and tons of information.
""" """
if service == 'dirsrv' and not debug and is_dirsrv_debugging_enabled(): if service == 'dirsrv' and not debug and is_dirsrv_debugging_enabled():
print ' debugging enabled, suppressing output.' print(' debugging enabled, suppressing output.')
return True return True
else: else:
return False return False
@@ -254,7 +256,7 @@ def ipa_start(options):
if not options.skip_version_check: if not options.skip_version_check:
version_check() version_check()
else: else:
print "Skipping version check" print("Skipping version check")
if os.path.isfile(tasks.get_svc_list_file()): if os.path.isfile(tasks.get_svc_list_file()):
emit_err("Existing service file detected!") emit_err("Existing service file detected!")
@@ -268,7 +270,7 @@ def ipa_start(options):
dirsrv = services.knownservices.dirsrv dirsrv = services.knownservices.dirsrv
try: try:
print "Starting Directory Service" print("Starting Directory Service")
dirsrv.start(capture_output=get_capture_output('dirsrv', options.debug)) dirsrv.start(capture_output=get_capture_output('dirsrv', options.debug))
except Exception as e: except Exception as e:
raise IpactlError("Failed to start Directory Service: " + str(e)) raise IpactlError("Failed to start Directory Service: " + str(e))
@@ -297,7 +299,7 @@ def ipa_start(options):
for svc in svc_list: for svc in svc_list:
svchandle = services.service(svc) svchandle = services.service(svc)
try: try:
print "Starting %s Service" % svc print("Starting %s Service" % svc)
svchandle.start(capture_output=get_capture_output(svc, options.debug)) svchandle.start(capture_output=get_capture_output(svc, options.debug))
except Exception: except Exception:
emit_err("Failed to start %s Service" % svc) emit_err("Failed to start %s Service" % svc)
@@ -336,13 +338,13 @@ def ipa_stop(options):
for svc in reversed(svc_list): for svc in reversed(svc_list):
svchandle = services.service(svc) svchandle = services.service(svc)
try: try:
print "Stopping %s Service" % svc print("Stopping %s Service" % svc)
svchandle.stop(capture_output=False) svchandle.stop(capture_output=False)
except: except:
emit_err("Failed to stop %s Service" % svc) emit_err("Failed to stop %s Service" % svc)
try: try:
print "Stopping Directory Service" print("Stopping Directory Service")
dirsrv.stop(capture_output=False) dirsrv.stop(capture_output=False)
except: except:
raise IpactlError("Failed to stop Directory Service") raise IpactlError("Failed to stop Directory Service")
@@ -358,14 +360,14 @@ def ipa_restart(options):
if not options.skip_version_check: if not options.skip_version_check:
version_check() version_check()
else: else:
print "Skipping version check" print("Skipping version check")
dirsrv = services.knownservices.dirsrv dirsrv = services.knownservices.dirsrv
new_svc_list = [] new_svc_list = []
dirsrv_restart = True dirsrv_restart = True
if not dirsrv.is_running(): if not dirsrv.is_running():
try: try:
print "Starting Directory Service" print("Starting Directory Service")
dirsrv.start(capture_output=get_capture_output('dirsrv', options.debug)) dirsrv.start(capture_output=get_capture_output('dirsrv', options.debug))
dirsrv_restart = False dirsrv_restart = False
except Exception as e: except Exception as e:
@@ -414,14 +416,14 @@ def ipa_restart(options):
for svc in reversed(old_svc_list): for svc in reversed(old_svc_list):
svchandle = services.service(svc) svchandle = services.service(svc)
try: try:
print "Stopping %s Service" % svc print("Stopping %s Service" % svc)
svchandle.stop(capture_output=False) svchandle.stop(capture_output=False)
except: except:
emit_err("Failed to stop %s Service" % svc) emit_err("Failed to stop %s Service" % svc)
try: try:
if dirsrv_restart: if dirsrv_restart:
print "Restarting Directory Service" print("Restarting Directory Service")
dirsrv.restart(capture_output=get_capture_output('dirsrv', options.debug)) dirsrv.restart(capture_output=get_capture_output('dirsrv', options.debug))
except Exception as e: except Exception as e:
emit_err("Failed to restart Directory Service: " + str(e)) emit_err("Failed to restart Directory Service: " + str(e))
@@ -439,7 +441,7 @@ def ipa_restart(options):
for svc in svc_list: for svc in svc_list:
svchandle = services.service(svc) svchandle = services.service(svc)
try: try:
print "Restarting %s Service" % svc print("Restarting %s Service" % svc)
svchandle.restart(capture_output=get_capture_output(svc, options.debug)) svchandle.restart(capture_output=get_capture_output(svc, options.debug))
except Exception: except Exception:
emit_err("Failed to restart %s Service" % svc) emit_err("Failed to restart %s Service" % svc)
@@ -461,7 +463,7 @@ def ipa_restart(options):
for svc in new_svc_list: for svc in new_svc_list:
svchandle = services.service(svc) svchandle = services.service(svc)
try: try:
print "Starting %s Service" % svc print("Starting %s Service" % svc)
svchandle.start(capture_output=get_capture_output(svc, options.debug)) svchandle.start(capture_output=get_capture_output(svc, options.debug))
except Exception: except Exception:
emit_err("Failed to start %s Service" % svc) emit_err("Failed to start %s Service" % svc)
@@ -496,12 +498,12 @@ def ipa_status(options):
dirsrv = services.knownservices.dirsrv dirsrv = services.knownservices.dirsrv
try: try:
if dirsrv.is_running(): if dirsrv.is_running():
print "Directory Service: RUNNING" print("Directory Service: RUNNING")
else: else:
print "Directory Service: STOPPED" print("Directory Service: STOPPED")
if len(svc_list) == 0: if len(svc_list) == 0:
print ("Directory Service must be running in order to " + print(("Directory Service must be running in order to " +
"obtain status of other services") "obtain status of other services"))
except: except:
raise IpactlError("Failed to get Directory Service status") raise IpactlError("Failed to get Directory Service status")
@@ -513,9 +515,9 @@ def ipa_status(options):
svchandle = services.service(svc) svchandle = services.service(svc)
try: try:
if svchandle.is_running(): if svchandle.is_running():
print "%s Service: RUNNING" % svc print("%s Service: RUNNING" % svc)
else: else:
print "%s Service: STOPPED" % svc print("%s Service: STOPPED" % svc)
except: except:
emit_err("Failed to get %s Service status" % svc) emit_err("Failed to get %s Service status" % svc)

View File

@@ -21,6 +21,8 @@
# #
# Configure the automount client for ldap. # Configure the automount client for ldap.
from __future__ import print_function
import sys import sys
import os import os
import urlparse import urlparse
@@ -86,8 +88,8 @@ def wait_for_sssd():
err_msg = ("Unable to find 'admin' user with " err_msg = ("Unable to find 'admin' user with "
"'getent passwd admin@%s'!" % api.env.realm) "'getent passwd admin@%s'!" % api.env.realm)
root_logger.debug(err_msg) root_logger.debug(err_msg)
print err_msg print(err_msg)
print "This may mean that sssd didn't re-start properly after the configuration changes." print("This may mean that sssd didn't re-start properly after the configuration changes.")
def configure_xml(fstore): def configure_xml(fstore):
from lxml import etree from lxml import etree
@@ -122,8 +124,8 @@ def configure_xml(fstore):
root.write(newconf, pretty_print=True, xml_declaration=True, encoding='UTF-8') root.write(newconf, pretty_print=True, xml_declaration=True, encoding='UTF-8')
newconf.close() newconf.close()
except IOError as e: except IOError as e:
print "Unable to write %s: %s" % (paths.AUTOFS_LDAP_AUTH_CONF, e) print("Unable to write %s: %s" % (paths.AUTOFS_LDAP_AUTH_CONF, e))
print "Configured %s" % paths.AUTOFS_LDAP_AUTH_CONF print("Configured %s" % paths.AUTOFS_LDAP_AUTH_CONF)
def configure_nsswitch(fstore, options): def configure_nsswitch(fstore, options):
""" """
@@ -142,7 +144,7 @@ def configure_nsswitch(fstore, options):
conf.changeConf(paths.NSSWITCH_CONF, opts) conf.changeConf(paths.NSSWITCH_CONF, opts)
print "Configured %s" % paths.NSSWITCH_CONF print("Configured %s" % paths.NSSWITCH_CONF)
def configure_autofs_sssd(fstore, statestore, autodiscover, options): def configure_autofs_sssd(fstore, statestore, autodiscover, options):
try: try:
@@ -191,7 +193,7 @@ def configure_autofs_sssd(fstore, statestore, autodiscover, options):
sssd = services.service('sssd') sssd = services.service('sssd')
sssd.restart() sssd.restart()
print "Restarting sssd, waiting for it to become available." print("Restarting sssd, waiting for it to become available.")
wait_for_sssd() wait_for_sssd()
def configure_autofs(fstore, statestore, autodiscover, server, options): def configure_autofs(fstore, statestore, autodiscover, server, options):
@@ -221,7 +223,7 @@ def configure_autofs(fstore, statestore, autodiscover, server, options):
tasks.restore_context(paths.SYSCONFIG_AUTOFS) tasks.restore_context(paths.SYSCONFIG_AUTOFS)
statestore.backup_state('autofs', 'sssd', False) statestore.backup_state('autofs', 'sssd', False)
print "Configured %s" % paths.SYSCONFIG_AUTOFS print("Configured %s" % paths.SYSCONFIG_AUTOFS)
def configure_autofs_common(fstore, statestore, options): def configure_autofs_common(fstore, statestore, options):
autofs = services.knownservices.autofs autofs = services.knownservices.autofs
@@ -229,17 +231,17 @@ def configure_autofs_common(fstore, statestore, options):
statestore.backup_state('autofs', 'running', autofs.is_running()) statestore.backup_state('autofs', 'running', autofs.is_running())
try: try:
autofs.restart() autofs.restart()
print "Started %s" % autofs.service_name print("Started %s" % autofs.service_name)
except Exception as e: except Exception as e:
root_logger.error("%s failed to restart: %s", autofs.service_name, e) root_logger.error("%s failed to restart: %s", autofs.service_name, e)
try: try:
autofs.enable() autofs.enable()
except Exception as e: except Exception as e:
print "Failed to configure automatic startup of the %s daemon" % (autofs.service_name) print("Failed to configure automatic startup of the %s daemon" % (autofs.service_name))
root_logger.error("Failed to enable automatic startup of the %s daemon: %s" % (autofs.service_name, str(e))) root_logger.error("Failed to enable automatic startup of the %s daemon: %s" % (autofs.service_name, str(e)))
def uninstall(fstore, statestore): def uninstall(fstore, statestore):
print "Restoring configuration" print("Restoring configuration")
if fstore.has_file(paths.SYSCONFIG_AUTOFS): if fstore.has_file(paths.SYSCONFIG_AUTOFS):
fstore.restore_file(paths.SYSCONFIG_AUTOFS) fstore.restore_file(paths.SYSCONFIG_AUTOFS)
if fstore.has_file(paths.NSSWITCH_CONF): if fstore.has_file(paths.NSSWITCH_CONF):
@@ -281,7 +283,7 @@ def uninstall(fstore, statestore):
sssd.restart() sssd.restart()
wait_for_sssd() wait_for_sssd()
except Exception as e: except Exception as e:
print 'Unable to restore SSSD configuration: %s' % str(e) print('Unable to restore SSSD configuration: %s' % str(e))
root_logger.debug('Unable to restore SSSD configuration: %s' % str(e)) root_logger.debug('Unable to restore SSSD configuration: %s' % str(e))
if statestore.has_state('rpcidmapd'): if statestore.has_state('rpcidmapd'):
enabled = statestore.restore_state('rpcidmapd', 'enabled') enabled = statestore.restore_state('rpcidmapd', 'enabled')
@@ -313,7 +315,7 @@ def configure_nfs(fstore, statestore):
paths.SYSCONFIG_NFS, replacevars=replacevars) paths.SYSCONFIG_NFS, replacevars=replacevars)
tasks.restore_context(paths.SYSCONFIG_NFS) tasks.restore_context(paths.SYSCONFIG_NFS)
print "Configured %s" % paths.SYSCONFIG_NFS print("Configured %s" % paths.SYSCONFIG_NFS)
replacevars = { replacevars = {
'Domain': api.env.domain, 'Domain': api.env.domain,
@@ -322,20 +324,20 @@ def configure_nfs(fstore, statestore):
paths.IDMAPD_CONF, replacevars=replacevars) paths.IDMAPD_CONF, replacevars=replacevars)
tasks.restore_context(paths.IDMAPD_CONF) tasks.restore_context(paths.IDMAPD_CONF)
print "Configured %s" % paths.IDMAPD_CONF print("Configured %s" % paths.IDMAPD_CONF)
rpcidmapd = services.knownservices.rpcidmapd rpcidmapd = services.knownservices.rpcidmapd
statestore.backup_state('rpcidmapd', 'enabled', rpcidmapd.is_enabled()) statestore.backup_state('rpcidmapd', 'enabled', rpcidmapd.is_enabled())
statestore.backup_state('rpcidmapd', 'running', rpcidmapd.is_running()) statestore.backup_state('rpcidmapd', 'running', rpcidmapd.is_running())
try: try:
rpcidmapd.restart() rpcidmapd.restart()
print "Started %s" % rpcidmapd.service_name print("Started %s" % rpcidmapd.service_name)
except Exception as e: except Exception as e:
root_logger.error("%s failed to restart: %s", rpcidmapd.service_name, e) root_logger.error("%s failed to restart: %s", rpcidmapd.service_name, e)
try: try:
rpcidmapd.enable() rpcidmapd.enable()
except Exception as e: except Exception as e:
print "Failed to configure automatic startup of the %s daemon" % (rpcidmapd.service_name) print("Failed to configure automatic startup of the %s daemon" % (rpcidmapd.service_name))
root_logger.error("Failed to enable automatic startup of the %s daemon: %s" % (rpcidmapd.service_name, str(e))) root_logger.error("Failed to enable automatic startup of the %s daemon: %s" % (rpcidmapd.service_name, str(e)))
rpcgssd = services.knownservices.rpcgssd rpcgssd = services.knownservices.rpcgssd
@@ -343,13 +345,13 @@ def configure_nfs(fstore, statestore):
statestore.backup_state('rpcgssd', 'running', rpcgssd.is_running()) statestore.backup_state('rpcgssd', 'running', rpcgssd.is_running())
try: try:
rpcgssd.restart() rpcgssd.restart()
print "Started %s" % rpcgssd.service_name print("Started %s" % rpcgssd.service_name)
except Exception as e: except Exception as e:
root_logger.error("%s failed to restart: %s", rpcgssd.service_name, e) root_logger.error("%s failed to restart: %s", rpcgssd.service_name, e)
try: try:
rpcgssd.enable() rpcgssd.enable()
except Exception as e: except Exception as e:
print "Failed to configure automatic startup of the %s daemon" % (rpcgssd.service_name) print("Failed to configure automatic startup of the %s daemon" % (rpcgssd.service_name))
root_logger.error("Failed to enable automatic startup of the %s daemon: %s" % (rpcgssd.service_name, str(e))) root_logger.error("Failed to enable automatic startup of the %s daemon: %s" % (rpcgssd.service_name, str(e)))
def main(): def main():
@@ -389,7 +391,7 @@ def main():
servers = [] servers = []
ds = ipadiscovery.IPADiscovery() ds = ipadiscovery.IPADiscovery()
if not options.server: if not options.server:
print "Searching for IPA server..." print("Searching for IPA server...")
ret = ds.search(ca_cert_path=ca_cert_path) ret = ds.search(ca_cert_path=ca_cert_path)
root_logger.debug('Executing DNS discovery') root_logger.debug('Executing DNS discovery')
if ret == ipadiscovery.NO_LDAP_SERVER: if ret == ipadiscovery.NO_LDAP_SERVER:
@@ -408,23 +410,23 @@ def main():
root_logger.debug("Verifying that %s is an IPA server" % server) root_logger.debug("Verifying that %s is an IPA server" % server)
ldapret = ds.ipacheckldap(server, api.env.realm, ca_cert_path) ldapret = ds.ipacheckldap(server, api.env.realm, ca_cert_path)
if ldapret[0] == ipadiscovery.NO_ACCESS_TO_LDAP: if ldapret[0] == ipadiscovery.NO_ACCESS_TO_LDAP:
print "Anonymous access to the LDAP server is disabled." print("Anonymous access to the LDAP server is disabled.")
print "Proceeding without strict verification." print("Proceeding without strict verification.")
print "Note: This is not an error if anonymous access has been explicitly restricted." print("Note: This is not an error if anonymous access has been explicitly restricted.")
elif ldapret[0] == ipadiscovery.NO_TLS_LDAP: elif ldapret[0] == ipadiscovery.NO_TLS_LDAP:
root_logger.warning("Unencrypted access to LDAP is not supported.") root_logger.warning("Unencrypted access to LDAP is not supported.")
elif ldapret[0] != 0: elif ldapret[0] != 0:
sys.exit('Unable to confirm that %s is an IPA server' % server) sys.exit('Unable to confirm that %s is an IPA server' % server)
if not autodiscover: if not autodiscover:
print "IPA server: %s" % server print("IPA server: %s" % server)
root_logger.debug('Using fixed server %s' % server) root_logger.debug('Using fixed server %s' % server)
else: else:
print "IPA server: DNS discovery" print("IPA server: DNS discovery")
root_logger.debug('Configuring to use DNS discovery') root_logger.debug('Configuring to use DNS discovery')
search_base = str(DN(('cn', options.location), api.env.container_automount, api.env.basedn)) search_base = str(DN(('cn', options.location), api.env.container_automount, api.env.basedn))
print "Location: %s" % options.location print("Location: %s" % options.location)
root_logger.debug('Using automount location %s' % options.location) root_logger.debug('Using automount location %s' % options.location)
ccache_dir = tempfile.mkdtemp() ccache_dir = tempfile.mkdtemp()
@@ -473,7 +475,7 @@ def main():
configure_autofs_common(fstore, statestore, options) configure_autofs_common(fstore, statestore, options)
except Exception as e: except Exception as e:
root_logger.debug('Raised exception %s' % e) root_logger.debug('Raised exception %s' % e)
print "Installation failed. Rolling back changes." print("Installation failed. Rolling back changes.")
uninstall(fstore, statestore) uninstall(fstore, statestore)
return 1 return 1

View File

@@ -19,6 +19,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
try: try:
import sys import sys
@@ -58,12 +60,12 @@ try:
from ipalib.rpc import delete_persistent_client_session_data from ipalib.rpc import delete_persistent_client_session_data
except ImportError as e: except ImportError as e:
print >> sys.stderr, """\ print("""\
There was a problem importing one of the required Python modules. The There was a problem importing one of the required Python modules. The
error was: error was:
%s %s
""" % e """ % e, file=sys.stderr)
sys.exit(1) sys.exit(1)
SUCCESS = 0 SUCCESS = 0
@@ -2226,12 +2228,12 @@ def install(options, env, fstore, statestore):
try: try:
ipaclient.ntpconf.check_timedate_services() ipaclient.ntpconf.check_timedate_services()
except ipaclient.ntpconf.NTPConflictingService as e: except ipaclient.ntpconf.NTPConflictingService as e:
print "WARNING: ntpd time&date synchronization service will not" \ print("WARNING: ntpd time&date synchronization service will not" \
" be configured as" " be configured as")
print "conflicting service (%s) is enabled" % e.conflicting_service print("conflicting service (%s) is enabled" % e.conflicting_service)
print "Use --force-ntpd option to disable it and force configuration" \ print("Use --force-ntpd option to disable it and force configuration" \
" of ntpd" " of ntpd")
print "" print("")
# configuration of ntpd is disabled in this case # configuration of ntpd is disabled in this case
options.conf_ntp = False options.conf_ntp = False
@@ -2475,13 +2477,13 @@ def install(options, env, fstore, statestore):
is_ipaddr = False is_ipaddr = False
if is_ipaddr: if is_ipaddr:
print print()
root_logger.warning("It seems that you are using an IP address " root_logger.warning("It seems that you are using an IP address "
"instead of FQDN as an argument to --server. The " "instead of FQDN as an argument to --server. The "
"installation may fail.") "installation may fail.")
break break
print print()
if not options.unattended and not user_input("Continue to configure the system with these values?", False): if not options.unattended and not user_input("Continue to configure the system with these values?", False):
return CLIENT_INSTALL_ERROR return CLIENT_INSTALL_ERROR

View File

@@ -20,6 +20,7 @@
""" """
Functionality for Command Line Interface. Functionality for Command Line Interface.
""" """
from __future__ import print_function
import textwrap import textwrap
import sys import sys
@@ -175,7 +176,7 @@ class textui(backend.Backend):
""" """
Print exactly like ``print`` statement would. Print exactly like ``print`` statement would.
""" """
print unicode(string) print(unicode(string))
def print_line(self, text, width=None): def print_line(self, text, width=None):
""" """
@@ -197,7 +198,7 @@ class textui(backend.Backend):
width = self.get_tty_width() width = self.get_tty_width()
if width is not None and width < len(text): if width is not None and width < len(text):
text = text[:width - 3] + '...' text = text[:width - 3] + '...'
print unicode(text) print(unicode(text))
def print_paragraph(self, text, width=None): def print_paragraph(self, text, width=None):
""" """
@@ -226,7 +227,7 @@ class textui(backend.Backend):
if width is None: if width is None:
width = self.get_tty_width() width = self.get_tty_width()
for line in textwrap.wrap(text.strip(), width): for line in textwrap.wrap(text.strip(), width):
print line print(line)
def print_indented(self, text, indent=1): def print_indented(self, text, indent=1):
""" """
@@ -242,7 +243,7 @@ class textui(backend.Backend):
>>> ui.print_indented('No indentation.', indent=0) >>> ui.print_indented('No indentation.', indent=0)
No indentation. No indentation.
""" """
print (CLI_TAB * indent + text) print((CLI_TAB * indent + text))
def print_keyval(self, rows, indent=1): def print_keyval(self, rows, indent=1):
""" """
@@ -354,7 +355,7 @@ class textui(backend.Backend):
first = True first = True
for entry in entries: for entry in entries:
if not first: if not first:
print '' print('')
first = False first = False
self.print_entry(entry, order, labels, flags, print_all, format, indent) self.print_entry(entry, order, labels, flags, print_all, format, indent)
@@ -526,7 +527,7 @@ class textui(backend.Backend):
) )
def print_error(self, text): def print_error(self, text):
print ' ** %s **' % unicode(text) print(' ** %s **' % unicode(text))
def prompt_helper(self, prompt, label, prompt_func=input): def prompt_helper(self, prompt, label, prompt_func=input):
"""Prompt user for input """Prompt user for input
@@ -537,7 +538,7 @@ class textui(backend.Backend):
try: try:
return self.decode(prompt_func(self.encode(prompt))) return self.decode(prompt_func(self.encode(prompt)))
except (KeyboardInterrupt, EOFError): except (KeyboardInterrupt, EOFError):
print print()
raise PromptFailed(name=label) raise PromptFailed(name=label)
def print_prompt_attribute_error(self, attribute, error): def print_prompt_attribute_error(self, attribute, error):
@@ -804,7 +805,7 @@ class help(frontend.Local):
def _writer(self, outfile): def _writer(self, outfile):
def writer(string=''): def writer(string=''):
try: try:
print >> outfile, unicode(string) print(unicode(string), file=outfile)
except IOError: except IOError:
pass pass
return writer return writer
@@ -882,7 +883,7 @@ class show_mappings(frontend.Command):
out.append((param.cli_name, param.param_spec)) out.append((param.cli_name, param.param_spec))
mcl = max(mcl,len(param.cli_name)) mcl = max(mcl,len(param.cli_name))
for item in out: for item in out:
print to_cli(item[0]).ljust(mcl)+' : '+item[1] print(to_cli(item[0]).ljust(mcl)+' : '+item[1])
class console(frontend.Command): class console(frontend.Command):
@@ -934,14 +935,14 @@ class show_api(frontend.Command):
first = True first = True
for line in lines: for line in lines:
if line[0] == 0 and not first: if line[0] == 0 and not first:
print '' print('')
if first: if first:
first = False first = False
print '%s%s %r' % ( print('%s%s %r' % (
' ' * line[0], ' ' * line[0],
line[1].ljust(ml), line[1].ljust(ml),
line[2], line[2],
) ))
if len(lines) == 1: if len(lines) == 1:
s = '1 attribute shown.' s = '1 attribute shown.'
else: else:
@@ -1060,8 +1061,8 @@ class cli(backend.Executioner):
""" """
if len(argv) == 0: if len(argv) == 0:
self.Command.help(outfile=sys.stderr) self.Command.help(outfile=sys.stderr)
print >>sys.stderr print(file=sys.stderr)
print >>sys.stderr, 'Error: Command not specified' print('Error: Command not specified', file=sys.stderr)
exit(2) exit(2)
(key, argv) = (argv[0], argv[1:]) (key, argv) = (argv[0], argv[1:])
name = from_cli(key) name = from_cli(key)
@@ -1342,7 +1343,7 @@ def run(api):
raise NotConfiguredError() raise NotConfiguredError()
sys.exit(api.Backend.cli.run(argv)) sys.exit(api.Backend.cli.run(argv))
except KeyboardInterrupt: except KeyboardInterrupt:
print '' print('')
api.log.info('operation aborted') api.log.info('operation aborted')
except PublicError as e: except PublicError as e:
error = e error = e

View File

@@ -29,6 +29,7 @@ range, so that it does not clash with PublicError numbers.
Messages also have the 'type' argument, set to one of 'debug', 'info', Messages also have the 'type' argument, set to one of 'debug', 'info',
'warning', 'error'. This determines the severity of themessage. 'warning', 'error'. This determines the severity of themessage.
""" """
from __future__ import print_function
from inspect import isclass from inspect import isclass
@@ -258,8 +259,8 @@ public_messages = tuple(sorted(
def print_report(label, classes): def print_report(label, classes):
for cls in classes: for cls in classes:
print '%d\t%s' % (cls.errno, cls.__name__) print('%d\t%s' % (cls.errno, cls.__name__))
print '(%d %s)' % (len(classes), label) print('(%d %s)' % (len(classes), label))
if __name__ == '__main__': if __name__ == '__main__':
print_report('public messages', public_messages) print_report('public messages', public_messages)

View File

@@ -17,6 +17,8 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import os import os
import sys import sys
import base64 import base64
@@ -256,7 +258,7 @@ if __name__ == '__main__':
csrlines = sys.stdin.readlines() csrlines = sys.stdin.readlines()
csr = ''.join(csrlines) csr = ''.join(csrlines)
print load_certificate_request(csr) print(load_certificate_request(csr))
print get_subject(csr) print(get_subject(csr))
print get_subjectaltname(csr) print(get_subjectaltname(csr))
print get_friendlyname(csr) print(get_friendlyname(csr))

View File

@@ -19,6 +19,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import print_function
import netaddr import netaddr
import time import time
@@ -4471,7 +4472,7 @@ class dnsforwardzone_add(DNSZoneBase_add):
result = super(dnsforwardzone_add, self).execute(*keys, **options) result = super(dnsforwardzone_add, self).execute(*keys, **options)
self.obj._warning_fw_zone_is_not_effective(result, *keys, **options) self.obj._warning_fw_zone_is_not_effective(result, *keys, **options)
if options.get('idnsforwarders'): if options.get('idnsforwarders'):
print result, keys, options print(result, keys, options)
self.obj._warning_if_forwarders_do_not_work( self.obj._warning_if_forwarders_do_not_work(
result, True, *keys, **options) result, True, *keys, **options)
return result return result

View File

@@ -22,6 +22,7 @@
""" """
Plugins not accessible directly through the CLI, commands used internally Plugins not accessible directly through the CLI, commands used internally
""" """
from __future__ import print_function
import json import json
@@ -138,7 +139,7 @@ class json_metadata(Command):
return retval return retval
def output_for_cli(self, textui, result, *args, **options): def output_for_cli(self, textui, result, *args, **options):
print json.dumps(result, default=json_serialize) print(json.dumps(result, default=json_serialize))
@register() @register()
@@ -856,6 +857,6 @@ class i18n_messages(Command):
return dict(texts=json_serialize(self.messages)) return dict(texts=json_serialize(self.messages))
def output_for_cli(self, textui, result, *args, **options): def output_for_cli(self, textui, result, *args, **options):
print json.dumps(result, default=json_serialize) print(json.dumps(result, default=json_serialize))

View File

@@ -17,6 +17,8 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
from ipalib.plugins.baseldap import DN, LDAPObject, LDAPAddMember, LDAPRemoveMember from ipalib.plugins.baseldap import DN, LDAPObject, LDAPAddMember, LDAPRemoveMember
from ipalib.plugins.baseldap import LDAPCreate, LDAPDelete, LDAPUpdate, LDAPSearch, LDAPRetrieve from ipalib.plugins.baseldap import LDAPCreate, LDAPDelete, LDAPUpdate, LDAPSearch, LDAPRetrieve
from ipalib import api, Int, Str, Bool, DateTime, Flag, Bytes, IntEnum, StrEnum, Password, _, ngettext from ipalib import api, Int, Str, Bool, DateTime, Flag, Bytes, IntEnum, StrEnum, Password, _, ngettext
@@ -352,12 +354,12 @@ class otptoken_add(LDAPCreate):
# Print QR code to terminal if specified # Print QR code to terminal if specified
if uri and not options.get('no_qrcode', False): if uri and not options.get('no_qrcode', False):
print "\n" print("\n")
qr = qrcode.QRCode() qr = qrcode.QRCode()
qr.add_data(uri) qr.add_data(uri)
qr.make() qr.make()
qr.print_ascii(tty=True) qr.print_ascii(tty=True)
print "\n" print("\n")
return rv return rv

View File

@@ -17,6 +17,8 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import base64 import base64
import getpass import getpass
import io import io
@@ -482,7 +484,7 @@ class vault(LDAPObject):
if password == password2: if password == password2:
return password return password
print ' ** Passwords do not match! **' print(' ** Passwords do not match! **')
def get_existing_password(self): def get_existing_password(self):
""" """

View File

@@ -31,6 +31,8 @@
# nsscert: the certificate is an NSS Certificate object # nsscert: the certificate is an NSS Certificate object
# rawcert: the cert is in an unknown format # rawcert: the cert is in an unknown format
from __future__ import print_function
import os import os
import sys import sys
import base64 import base64
@@ -407,4 +409,4 @@ if __name__ == '__main__':
nsscert = load_certificate(cert) nsscert = load_certificate(cert)
print nsscert print(nsscert)

View File

@@ -23,6 +23,7 @@
This module contains default Red Hat OS family-specific implementations of This module contains default Red Hat OS family-specific implementations of
system tasks. system tasks.
''' '''
from __future__ import print_function
import os import os
import stat import stat
@@ -304,8 +305,8 @@ class RedHatTaskNamespace(BaseTaskNamespace):
try: try:
ipautil.run([paths.BIN_HOSTNAME, hostname]) ipautil.run([paths.BIN_HOSTNAME, hostname])
except ipautil.CalledProcessError as e: except ipautil.CalledProcessError as e:
print >>sys.stderr, ("Failed to set this machine hostname to " print(("Failed to set this machine hostname to "
"%s (%s)." % (hostname, str(e))) "%s (%s)." % (hostname, str(e))), file=sys.stderr)
filepath = paths.ETC_HOSTNAME filepath = paths.ETC_HOSTNAME
if os.path.exists(filepath): if os.path.exists(filepath):
@@ -341,8 +342,8 @@ class RedHatTaskNamespace(BaseTaskNamespace):
# in /etc/sysconfig/network # in /etc/sysconfig/network
old_filepath_restore = paths.SYSCONFIG_NETWORK_IPABKP old_filepath_restore = paths.SYSCONFIG_NETWORK_IPABKP
fstore.restore_file(old_filepath, old_filepath_restore) fstore.restore_file(old_filepath, old_filepath_restore)
print "Deprecated configuration file '%s' was restored to '%s'" \ print("Deprecated configuration file '%s' was restored to '%s'" \
% (old_filepath, old_filepath_restore) % (old_filepath, old_filepath_restore))
hostname_was_configured = True hostname_was_configured = True
filepath = paths.ETC_HOSTNAME filepath = paths.ETC_HOSTNAME

View File

@@ -22,6 +22,8 @@
# This is used so we can add tracking to the Apache and 389-ds # This is used so we can add tracking to the Apache and 389-ds
# server certificates created during the IPA server installation. # server certificates created during the IPA server installation.
from __future__ import print_function
import os import os
import sys import sys
import time import time
@@ -548,5 +550,5 @@ if __name__ == '__main__':
"cn=tiger.example.com,O=IPA", "cn=tiger.example.com,O=IPA",
"HTTP/tiger.example.com@EXAMPLE.COM") "HTTP/tiger.example.com@EXAMPLE.COM")
csr = get_request_value(request_id, 'csr') csr = get_request_value(request_id, 'csr')
print csr print(csr)
stop_tracking(request_id) stop_tracking(request_id)

View File

@@ -417,6 +417,7 @@ It is possible to "copy" an object by passing an object of the same type
to the constructor. The result may share underlying structure. to the constructor. The result may share underlying structure.
''' '''
from __future__ import print_function
import sys import sys
@@ -1121,8 +1122,8 @@ class DN(object):
try: try:
return dn2str(self.rdns) return dn2str(self.rdns)
except Exception, e: except Exception, e:
print len(self.rdns) print(len(self.rdns))
print self.rdns print(self.rdns)
raise raise
def __repr__(self): def __repr__(self):

View File

@@ -3,6 +3,8 @@
# Copyright (C) 2014 FreeIPA Contributors see COPYING for license # Copyright (C) 2014 FreeIPA Contributors see COPYING for license
# #
from __future__ import print_function
from binascii import hexlify from binascii import hexlify
import collections import collections
import logging import logging
@@ -192,36 +194,36 @@ if __name__ == '__main__':
localhsm = LocalHSM(paths.LIBSOFTHSM2_SO, 0, localhsm = LocalHSM(paths.LIBSOFTHSM2_SO, 0,
open(paths.DNSSEC_SOFTHSM_PIN).read()) open(paths.DNSSEC_SOFTHSM_PIN).read())
print 'replica public keys: CKA_WRAP = TRUE' print('replica public keys: CKA_WRAP = TRUE')
print '====================================' print('====================================')
for pubkey_id, pubkey in localhsm.replica_pubkeys_wrap.items(): for pubkey_id, pubkey in localhsm.replica_pubkeys_wrap.items():
print hexlify(pubkey_id) print(hexlify(pubkey_id))
pprint(pubkey) pprint(pubkey)
print '' print('')
print 'replica public keys: all' print('replica public keys: all')
print '========================' print('========================')
for pubkey_id, pubkey in localhsm.replica_pubkeys.items(): for pubkey_id, pubkey in localhsm.replica_pubkeys.items():
print hexlify(pubkey_id) print(hexlify(pubkey_id))
pprint(pubkey) pprint(pubkey)
print '' print('')
print 'master keys' print('master keys')
print '===========' print('===========')
for mkey_id, mkey in localhsm.master_keys.items(): for mkey_id, mkey in localhsm.master_keys.items():
print hexlify(mkey_id) print(hexlify(mkey_id))
pprint(mkey) pprint(mkey)
print '' print('')
print 'zone public keys' print('zone public keys')
print '================' print('================')
for key_id, key in localhsm.zone_pubkeys.items(): for key_id, key in localhsm.zone_pubkeys.items():
print hexlify(key_id) print(hexlify(key_id))
pprint(key) pprint(key)
print '' print('')
print 'zone private keys' print('zone private keys')
print '=================' print('=================')
for key_id, key in localhsm.zone_privkeys.items(): for key_id, key in localhsm.zone_privkeys.items():
print hexlify(key_id) print(hexlify(key_id))
pprint(key) pprint(key)

View File

@@ -17,6 +17,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
import string import string
import tempfile import tempfile
import subprocess import subprocess
@@ -1326,7 +1328,7 @@ def restore_hostname(statestore):
try: try:
run([paths.BIN_HOSTNAME, old_hostname]) run([paths.BIN_HOSTNAME, old_hostname])
except CalledProcessError as e: except CalledProcessError as e:
print >>sys.stderr, "Failed to set this machine hostname back to %s: %s" % (old_hostname, str(e)) print("Failed to set this machine hostname back to %s: %s" % (old_hostname, str(e)), file=sys.stderr)
@contextmanager @contextmanager

View File

@@ -500,6 +500,7 @@ bewildering difficult to get it do what I wanted.
John Dennis <jdennis@redhat.com> John Dennis <jdennis@redhat.com>
''' '''
from __future__ import print_function
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
import sys import sys
@@ -1242,7 +1243,7 @@ class LogManager(object):
try: try:
level = parse_log_level(level) level = parse_log_level(level)
except Exception as e: except Exception as e:
print >>sys.stderr, 'could not set handler log level "%s" (%s)' % (level, e) print('could not set handler log level "%s" (%s)' % (level, e), file=sys.stderr)
level = None level = None
if level is None: if level is None:
level = self.default_level level = self.default_level

View File

@@ -18,6 +18,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
import sys import sys
import httplib import httplib
import getpass import getpass
@@ -340,9 +342,9 @@ if __name__ == "__main__":
conn.connect() conn.connect()
conn.request("GET", "/") conn.request("GET", "/")
response = conn.getresponse() response = conn.getresponse()
print response.status print(response.status)
#print response.msg #print response.msg
print response.getheaders() print(response.getheaders())
data = response.read() data = response.read()
#print data #print data
conn.close() conn.close()
@@ -353,8 +355,8 @@ if __name__ == "__main__":
h.putrequest('GET', '/') h.putrequest('GET', '/')
h.endheaders() h.endheaders()
http_status, http_reason, headers = h.getreply() http_status, http_reason, headers = h.getreply()
print "status = %s %s" % (http_status, http_reason) print("status = %s %s" % (http_status, http_reason))
print "headers:\n%s" % headers print("headers:\n%s" % headers)
f = h.getfile() f = h.getfile()
data = f.read() # Get the raw HTML data = f.read() # Get the raw HTML
f.close() f.close()

View File

@@ -17,12 +17,15 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
import os import os
from textwrap import wrap
from ipalib import api from ipalib import api
from ipalib.plugable import Plugin, API from ipalib.plugable import Plugin, API
from ipalib.errors import ValidationError from ipalib.errors import ValidationError
from ipapython import admintool from ipapython import admintool
from textwrap import wrap
from ipapython.ipa_log_manager import log_mgr from ipapython.ipa_log_manager import log_mgr
@@ -174,11 +177,11 @@ class IpaAdvise(admintool.AdminTool):
wrapped_description = wrap(description, 80 - len(prefix)) wrapped_description = wrap(description, 80 - len(prefix))
# Print the first line with the prefix (keyword) # Print the first line with the prefix (keyword)
print prefix + wrapped_description[0] print(prefix + wrapped_description[0])
# Print the rest wrapped behind the colon # Print the rest wrapped behind the colon
for line in wrapped_description[1:]: for line in wrapped_description[1:]:
print "{off}{line}".format(off=' ' * len(prefix), line=line) print("{off}{line}".format(off=' ' * len(prefix), line=line))
def print_header(self, header, print_shell=False): def print_header(self, header, print_shell=False):
header_size = len(header) header_size = len(header)
@@ -186,14 +189,14 @@ class IpaAdvise(admintool.AdminTool):
prefix = '' prefix = ''
if print_shell: if print_shell:
prefix = '# ' prefix = '# '
print '#!/bin/sh' print('#!/bin/sh')
# Do not print out empty header # Do not print out empty header
if header_size > 0: if header_size > 0:
print(prefix + '-' * 70) print((prefix + '-' * 70))
for line in wrap(header, 70): for line in wrap(header, 70):
print(prefix + line) print((prefix + line))
print(prefix + '-' * 70) print((prefix + '-' * 70))
def print_advice(self, keyword): def print_advice(self, keyword):
advice = getattr(advise_api.Advice, keyword, None) advice = getattr(advise_api.Advice, keyword, None)
@@ -224,7 +227,7 @@ class IpaAdvise(admintool.AdminTool):
advice.get_info() advice.get_info()
api.Backend.rpcclient.disconnect() api.Backend.rpcclient.disconnect()
for line in advice.log.content: for line in advice.log.content:
print line print(line)
def run(self): def run(self):
super(IpaAdvise, self).run() super(IpaAdvise, self).run()

View File

@@ -17,6 +17,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
import os import os
import errno import errno
import ldap import ldap
@@ -59,9 +61,9 @@ SELINUX_BOOLEAN_SETTINGS = {'samba_portmapper': 'on'}
def check_inst(): def check_inst():
for smbfile in [paths.SMBD, paths.NET]: for smbfile in [paths.SMBD, paths.NET]:
if not os.path.exists(smbfile): if not os.path.exists(smbfile):
print "%s was not found on this system" % smbfile print("%s was not found on this system" % smbfile)
print "Please install the 'samba' packages and " \ print("Please install the 'samba' packages and " \
"start the installation again" "start the installation again")
return False return False
#TODO: Add check for needed samba4 libraries #TODO: Add check for needed samba4 libraries

View File

@@ -17,6 +17,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
import tempfile import tempfile
import os import os
import pwd import pwd
@@ -289,7 +291,7 @@ def read_reverse_zone(default, ip_address):
if verify_reverse_zone(zone, ip_address): if verify_reverse_zone(zone, ip_address):
break break
else: else:
print "Invalid reverse zone %s for IP address %s" % (zone, ip_address) print("Invalid reverse zone %s for IP address %s" % (zone, ip_address))
return normalize_zone(zone) return normalize_zone(zone)
@@ -447,7 +449,7 @@ def check_reverse_zones(ip_addresses, reverse_zones, options, unattended, search
return ret_reverse_zones return ret_reverse_zones
def check_forwarders(dns_forwarders, logger): def check_forwarders(dns_forwarders, logger):
print "Checking DNS forwarders, please wait ..." print("Checking DNS forwarders, please wait ...")
forwarders_dnssec_valid = True forwarders_dnssec_valid = True
for forwarder in dns_forwarders: for forwarder in dns_forwarders:
logger.debug("Checking DNS server: %s", forwarder) logger.debug("Checking DNS server: %s", forwarder)
@@ -459,17 +461,17 @@ def check_forwarders(dns_forwarders, logger):
forwarder, e) forwarder, e)
logger.warning("Please fix forwarder configuration to enable DNSSEC support.\n" logger.warning("Please fix forwarder configuration to enable DNSSEC support.\n"
"(For BIND 9 add directive \"dnssec-enable yes;\" to \"options {}\")") "(For BIND 9 add directive \"dnssec-enable yes;\" to \"options {}\")")
print "DNS server %s: %s" % (forwarder, e) print("DNS server %s: %s" % (forwarder, e))
print "Please fix forwarder configuration to enable DNSSEC support." print("Please fix forwarder configuration to enable DNSSEC support.")
print "(For BIND 9 add directive \"dnssec-enable yes;\" to \"options {}\")" print("(For BIND 9 add directive \"dnssec-enable yes;\" to \"options {}\")")
except EDNS0UnsupportedError as e: except EDNS0UnsupportedError as e:
forwarders_dnssec_valid = False forwarders_dnssec_valid = False
logger.warning("DNS server %s does not support ENDS0 " logger.warning("DNS server %s does not support ENDS0 "
"(RFC 6891): %s", forwarder, e) "(RFC 6891): %s", forwarder, e)
logger.warning("Please fix forwarder configuration. " logger.warning("Please fix forwarder configuration. "
"DNSSEC support cannot be enabled without EDNS0") "DNSSEC support cannot be enabled without EDNS0")
print ("WARNING: DNS server %s does not support EDNS0 " print(("WARNING: DNS server %s does not support EDNS0 "
"(RFC 6891): %s" % (forwarder, e)) "(RFC 6891): %s" % (forwarder, e)))
except UnresolvableRecordError as e: except UnresolvableRecordError as e:
logger.error("DNS server %s: %s", forwarder, e) logger.error("DNS server %s: %s", forwarder, e)
raise RuntimeError("DNS server %s: %s" % (forwarder, e)) raise RuntimeError("DNS server %s: %s" % (forwarder, e))
@@ -602,7 +604,7 @@ class BindInstance(service.Service):
[bind_fd, bind_name] = tempfile.mkstemp(".db","sample.zone.") [bind_fd, bind_name] = tempfile.mkstemp(".db","sample.zone.")
os.write(bind_fd, bind_txt) os.write(bind_fd, bind_txt)
os.close(bind_fd) os.close(bind_fd)
print "Sample zone file for bind has been created in "+bind_name print("Sample zone file for bind has been created in "+bind_name)
def create_instance(self): def create_instance(self):
@@ -658,7 +660,7 @@ class BindInstance(service.Service):
self.restart() self.restart()
except Exception as e: except Exception as e:
root_logger.error("Named service failed to start (%s)", e) root_logger.error("Named service failed to start (%s)", e)
print "named service failed to start" print("named service failed to start")
def __enable(self): def __enable(self):
if self.get_state("enabled") is None: if self.get_state("enabled") is None:
@@ -1155,14 +1157,14 @@ class BindInstance(service.Service):
param in api.Object['dnsconfig'].params) param in api.Object['dnsconfig'].params)
if not global_conf_set: if not global_conf_set:
print "Global DNS configuration in LDAP server is empty" print("Global DNS configuration in LDAP server is empty")
print "You can use 'dnsconfig-mod' command to set global DNS options that" print("You can use 'dnsconfig-mod' command to set global DNS options that")
print "would override settings in local named.conf files" print("would override settings in local named.conf files")
return return
print "Global DNS configuration in LDAP server is not empty" print("Global DNS configuration in LDAP server is not empty")
print "The following configuration options override local settings in named.conf:" print("The following configuration options override local settings in named.conf:")
print "" print("")
textui = ipalib.cli.textui(api) textui = ipalib.cli.textui(api)
api.Command.dnsconfig_show.output_for_cli(textui, result, None, reverse=False) api.Command.dnsconfig_show.output_for_cli(textui, result, None, reverse=False)

View File

@@ -2,6 +2,8 @@
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license # Copyright (C) 2015 FreeIPA Contributors see COPYING for license
# #
from __future__ import print_function
import sys import sys
import os.path import os.path
@@ -30,7 +32,7 @@ def install_check(standalone, replica_config, options):
sys.exit('A selfsign CA can not be added') sys.exit('A selfsign CA can not be added')
if not ipautil.file_exists(replica_config.dir + "/cacert.p12"): if not ipautil.file_exists(replica_config.dir + "/cacert.p12"):
print 'CA cannot be installed in CA-less setup.' print('CA cannot be installed in CA-less setup.')
sys.exit(1) sys.exit(1)
if standalone and not options.skip_conncheck: if standalone and not options.skip_conncheck:
@@ -73,9 +75,9 @@ def install_check(standalone, replica_config, options):
"--external-cert-file.") "--external-cert-file.")
sys.exit(1) sys.exit(1)
if ipautil.file_exists(paths.ROOT_IPA_CSR): if ipautil.file_exists(paths.ROOT_IPA_CSR):
print("CA CSR file %s already exists.\nIn order to continue " print(("CA CSR file %s already exists.\nIn order to continue "
"remove the file and run the installer again." % "remove the file and run the installer again." %
paths.ROOT_IPA_CSR) paths.ROOT_IPA_CSR))
sys.exit(1) sys.exit(1)
if not options.external_cert_files: if not options.external_cert_files:
@@ -94,8 +96,8 @@ def install_check(standalone, replica_config, options):
if nickname in (certdb.get_ca_nickname(realm_name), if nickname in (certdb.get_ca_nickname(realm_name),
'ipaCert', 'ipaCert',
'Signing-Cert'): 'Signing-Cert'):
print ("Certificate with nickname %s is present in %s, " print(("Certificate with nickname %s is present in %s, "
"cannot continue." % (nickname, db.secdir)) "cannot continue." % (nickname, db.secdir)))
sys.exit(1) sys.exit(1)
cert = db.get_cert_from_db(nickname) cert = db.get_cert_from_db(nickname)
@@ -105,8 +107,8 @@ def install_check(standalone, replica_config, options):
if subject in (DN('CN=Certificate Authority', subject_base), if subject in (DN('CN=Certificate Authority', subject_base),
DN('CN=IPA RA', subject_base), DN('CN=IPA RA', subject_base),
DN('CN=Object Signing Cert', subject_base)): DN('CN=Object Signing Cert', subject_base)):
print ("Certificate with subject %s is present in %s, " print(("Certificate with subject %s is present in %s, "
"cannot continue." % (subject, db.secdir)) "cannot continue." % (subject, db.secdir)))
sys.exit(1) sys.exit(1)
@@ -249,7 +251,7 @@ def install_step_1(standalone, replica_config, options):
with open(paths.IPA_DEFAULT_CONF, 'w') as f: with open(paths.IPA_DEFAULT_CONF, 'w') as f:
parser.write(f) parser.write(f)
except IOError as e: except IOError as e:
print "Failed to update /etc/ipa/default.conf" print("Failed to update /etc/ipa/default.conf")
root_logger.error(str(e)) root_logger.error(str(e))
sys.exit(1) sys.exit(1)

View File

@@ -19,6 +19,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
import array import array
import base64 import base64
import binascii import binascii
@@ -616,8 +618,8 @@ class CAInstance(DogtagInstance):
os.remove(cfg_file) os.remove(cfg_file)
if self.external == 1: if self.external == 1:
print "The next step is to get %s signed by your CA and re-run %s as:" % (self.csr_file, sys.argv[0]) print("The next step is to get %s signed by your CA and re-run %s as:" % (self.csr_file, sys.argv[0]))
print "%s --external-cert-file=/path/to/signed_certificate --external-cert-file=/path/to/external_ca_certificate" % sys.argv[0] print("%s --external-cert-file=/path/to/signed_certificate --external-cert-file=/path/to/external_ca_certificate" % sys.argv[0])
sys.exit(0) sys.exit(0)
else: else:
shutil.move(paths.CA_BACKUP_KEYS_P12, shutil.move(paths.CA_BACKUP_KEYS_P12,
@@ -756,8 +758,8 @@ class CAInstance(DogtagInstance):
self.handle_setup_error(e) self.handle_setup_error(e)
if self.external == 1: if self.external == 1:
print "The next step is to get %s signed by your CA and re-run %s as:" % (self.csr_file, sys.argv[0]) print("The next step is to get %s signed by your CA and re-run %s as:" % (self.csr_file, sys.argv[0]))
print "%s --external-cert-file=/path/to/signed_certificate --external-cert-file=/path/to/external_ca_certificate" % sys.argv[0] print("%s --external-cert-file=/path/to/signed_certificate --external-cert-file=/path/to/external_ca_certificate" % sys.argv[0])
sys.exit(0) sys.exit(0)
# pkisilent makes a copy of the CA PKCS#12 file for us but gives # pkisilent makes a copy of the CA PKCS#12 file for us but gives

View File

@@ -2,6 +2,8 @@
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license # Copyright (C) 2015 FreeIPA Contributors see COPYING for license
# #
from __future__ import print_function
import sys import sys
from subprocess import CalledProcessError from subprocess import CalledProcessError
@@ -102,37 +104,37 @@ def install_check(standalone, replica, options, hostname):
constants.IPA_DNS_PACKAGE_NAME) constants.IPA_DNS_PACKAGE_NAME)
if standalone: if standalone:
print "==============================================================================" print("==============================================================================")
print "This program will setup DNS for the FreeIPA Server." print("This program will setup DNS for the FreeIPA Server.")
print "" print("")
print "This includes:" print("This includes:")
print " * Configure DNS (bind)" print(" * Configure DNS (bind)")
print " * Configure SoftHSM (required by DNSSEC)" print(" * Configure SoftHSM (required by DNSSEC)")
print " * Configure ipa-dnskeysyncd (required by DNSSEC)" print(" * Configure ipa-dnskeysyncd (required by DNSSEC)")
if options.dnssec_master: if options.dnssec_master:
print " * Configure ipa-ods-exporter (required by DNSSEC key master)" print(" * Configure ipa-ods-exporter (required by DNSSEC key master)")
print " * Configure OpenDNSSEC (required by DNSSEC key master)" print(" * Configure OpenDNSSEC (required by DNSSEC key master)")
print " * Generate DNSSEC master key (required by DNSSEC key master)" print(" * Generate DNSSEC master key (required by DNSSEC key master)")
elif options.disable_dnssec_master: elif options.disable_dnssec_master:
print " * Unconfigure ipa-ods-exporter" print(" * Unconfigure ipa-ods-exporter")
print " * Unconfigure OpenDNSSEC" print(" * Unconfigure OpenDNSSEC")
print "" print("")
print "No new zones will be signed without DNSSEC key master IPA server." print("No new zones will be signed without DNSSEC key master IPA server.")
print "" print("")
print ("Please copy file from %s after uninstallation. This file is needed " print(("Please copy file from %s after uninstallation. This file is needed "
"on new DNSSEC key " % paths.IPA_KASP_DB_BACKUP) "on new DNSSEC key " % paths.IPA_KASP_DB_BACKUP))
print "master server" print("master server")
print "" print("")
print "NOTE: DNSSEC zone signing is not enabled by default" print("NOTE: DNSSEC zone signing is not enabled by default")
print "" print("")
if options.dnssec_master: if options.dnssec_master:
print "DNSSEC support is experimental!" print("DNSSEC support is experimental!")
print "" print("")
print "Plan carefully, replacing DNSSEC key master is not recommended" print("Plan carefully, replacing DNSSEC key master is not recommended")
print "" print("")
print "" print("")
print "To accept the default shown in brackets, press the Enter key." print("To accept the default shown in brackets, press the Enter key.")
print "" print("")
if (options.dnssec_master and not options.unattended and not if (options.dnssec_master and not options.unattended and not
ipautil.user_input( ipautil.user_input(
@@ -177,7 +179,7 @@ def install_check(standalone, replica, options, hostname):
dnssec_masters = ods.get_masters() dnssec_masters = ods.get_masters()
# we can reinstall current server if it is dnssec master # we can reinstall current server if it is dnssec master
if dnssec_masters and api.env.host not in dnssec_masters: if dnssec_masters and api.env.host not in dnssec_masters:
print "DNSSEC key master(s):", u','.join(dnssec_masters) print("DNSSEC key master(s):", u','.join(dnssec_masters))
sys.exit("Only one DNSSEC key master is supported in current " sys.exit("Only one DNSSEC key master is supported in current "
"version.") "version.")
@@ -242,7 +244,7 @@ def install_check(standalone, replica, options, hostname):
if (not bindinstance.check_forwarders(dns_forwarders, root_logger) and if (not bindinstance.check_forwarders(dns_forwarders, root_logger) and
not options.no_dnssec_validation): not options.no_dnssec_validation):
options.no_dnssec_validation = True options.no_dnssec_validation = True
print "WARNING: DNSSEC validation will be disabled" print("WARNING: DNSSEC validation will be disabled")
root_logger.debug("will use dns_forwarders: %s\n", dns_forwarders) root_logger.debug("will use dns_forwarders: %s\n", dns_forwarders)
@@ -262,7 +264,7 @@ def install_check(standalone, replica, options, hostname):
) )
if reverse_zones: if reverse_zones:
print "Using reverse zone(s) %s" % ', '.join(reverse_zones) print("Using reverse zone(s) %s" % ', '.join(reverse_zones))
def install(standalone, replica, options): def install(standalone, replica, options):
@@ -287,10 +289,10 @@ def install(standalone, replica, options):
ca_configured=options.setup_ca) ca_configured=options.setup_ca)
if standalone and not options.unattended: if standalone and not options.unattended:
print "" print("")
print "The following operations may take some minutes to complete." print("The following operations may take some minutes to complete.")
print "Please wait until the prompt is returned." print("Please wait until the prompt is returned.")
print "" print("")
bind.create_instance() bind.create_instance()
@@ -312,33 +314,33 @@ def install(standalone, replica, options):
bind.start_named() bind.start_named()
if standalone: if standalone:
print "==============================================================================" print("==============================================================================")
print "Setup complete" print("Setup complete")
print "" print("")
bind.check_global_configuration() bind.check_global_configuration()
print "" print("")
print "" print("")
print "\tYou must make sure these network ports are open:" print("\tYou must make sure these network ports are open:")
print "\t\tTCP Ports:" print("\t\tTCP Ports:")
print "\t\t * 53: bind" print("\t\t * 53: bind")
print "\t\tUDP Ports:" print("\t\tUDP Ports:")
print "\t\t * 53: bind" print("\t\t * 53: bind")
elif not standalone and replica: elif not standalone and replica:
print "" print("")
bind.check_global_configuration() bind.check_global_configuration()
print "" print("")
def uninstall_check(options): def uninstall_check(options):
# test if server is DNSSEC key master # test if server is DNSSEC key master
masters = opendnssecinstance.get_dnssec_key_masters(api.Backend.ldap2) masters = opendnssecinstance.get_dnssec_key_masters(api.Backend.ldap2)
if api.env.host in masters: if api.env.host in masters:
print "This server is active DNSSEC key master. Uninstall could break your DNS system." print("This server is active DNSSEC key master. Uninstall could break your DNS system.")
if not (options.unattended or user_input( if not (options.unattended or user_input(
"Are you sure you want to continue with the uninstall " "Are you sure you want to continue with the uninstall "
"procedure?", False)): "procedure?", False)):
print "" print("")
print "Aborting uninstall operation." print("Aborting uninstall operation.")
sys.exit(1) sys.exit(1)

View File

@@ -2,6 +2,8 @@
# Copyright (C) 2014 FreeIPA Contributors see COPYING for license # Copyright (C) 2014 FreeIPA Contributors see COPYING for license
# #
from __future__ import print_function
import os import os
import pwd import pwd
import grp import grp
@@ -111,7 +113,7 @@ class DNSKeySyncInstance(service.Service):
ldap.delete_entry(entry) ldap.delete_entry(entry)
def start_dnskeysyncd(self): def start_dnskeysyncd(self):
print "Restarting ipa-dnskeysyncd" print("Restarting ipa-dnskeysyncd")
self.__start() self.__start()
def create_instance(self, fqdn, realm_name): def create_instance(self, fqdn, realm_name):
@@ -464,7 +466,7 @@ class DNSKeySyncInstance(service.Service):
try: try:
self.restart() self.restart()
except Exception as e: except Exception as e:
print "Failed to start ipa-dnskeysyncd" print("Failed to start ipa-dnskeysyncd")
self.logger.debug("Failed to start ipa-dnskeysyncd: %s", e) self.logger.debug("Failed to start ipa-dnskeysyncd: %s", e)

View File

@@ -18,6 +18,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
import shutil import shutil
import pwd import pwd
import sys import sys
@@ -506,7 +508,7 @@ class DsInstance(service.Service):
self.__restart_instance() self.__restart_instance()
root_logger.debug("done restarting ds instance") root_logger.debug("done restarting ds instance")
except ipautil.CalledProcessError as e: except ipautil.CalledProcessError as e:
print "failed to restart ds instance", e print("failed to restart ds instance", e)
root_logger.debug("failed to restart ds instance %s" % e) root_logger.debug("failed to restart ds instance %s" % e)
inf_fd.close() inf_fd.close()
os.remove(paths.DIRSRV_BOOT_LDIF) os.remove(paths.DIRSRV_BOOT_LDIF)
@@ -832,7 +834,7 @@ class DsInstance(service.Service):
ipautil.run(args, env=env) ipautil.run(args, env=env)
root_logger.debug("ldappasswd done") root_logger.debug("ldappasswd done")
except ipautil.CalledProcessError as e: except ipautil.CalledProcessError as e:
print "Unable to set admin password", e print("Unable to set admin password", e)
root_logger.debug("Unable to set admin password %s" % e) root_logger.debug("Unable to set admin password %s" % e)
finally: finally:

View File

@@ -17,6 +17,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
import os import os
import os.path import os.path
import tempfile import tempfile
@@ -213,7 +215,7 @@ class HTTPInstance(service.Service):
def __set_mod_nss_port(self): def __set_mod_nss_port(self):
self.fstore.backup_file(paths.HTTPD_NSS_CONF) self.fstore.backup_file(paths.HTTPD_NSS_CONF)
if installutils.update_file(paths.HTTPD_NSS_CONF, '8443', '443') != 0: if installutils.update_file(paths.HTTPD_NSS_CONF, '8443', '443') != 0:
print "Updating port in %s failed." % paths.HTTPD_NSS_CONF print("Updating port in %s failed." % paths.HTTPD_NSS_CONF)
def __set_mod_nss_nickname(self, nickname): def __set_mod_nss_nickname(self, nickname):
installutils.set_directive(paths.HTTPD_NSS_CONF, 'NSSNickname', nickname) installutils.set_directive(paths.HTTPD_NSS_CONF, 'NSSNickname', nickname)
@@ -231,7 +233,7 @@ class HTTPInstance(service.Service):
def __add_include(self): def __add_include(self):
"""This should run after __set_mod_nss_port so is already backed up""" """This should run after __set_mod_nss_port so is already backed up"""
if installutils.update_file(paths.HTTPD_NSS_CONF, '</VirtualHost>', 'Include conf.d/ipa-rewrite.conf\n</VirtualHost>') != 0: if installutils.update_file(paths.HTTPD_NSS_CONF, '</VirtualHost>', 'Include conf.d/ipa-rewrite.conf\n</VirtualHost>') != 0:
print "Adding Include conf.d/ipa-rewrite to %s failed." % paths.HTTPD_NSS_CONF print("Adding Include conf.d/ipa-rewrite to %s failed." % paths.HTTPD_NSS_CONF)
def configure_certmonger_renewal_guard(self): def configure_certmonger_renewal_guard(self):
certmonger = services.knownservices.certmonger certmonger = services.knownservices.certmonger

View File

@@ -18,6 +18,7 @@
# #
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import print_function
import socket import socket
import getpass import getpass
@@ -161,7 +162,7 @@ def verify_fqdn(host_name, no_host_dns=False, local_hostname=True):
root_logger.debug('socket.gethostbyaddr() error: %d: %s' % (e.errno, e.strerror)) root_logger.debug('socket.gethostbyaddr() error: %d: %s' % (e.errno, e.strerror))
if no_host_dns: if no_host_dns:
print "Warning: skipping DNS resolution of host", host_name print("Warning: skipping DNS resolution of host", host_name)
return return
try: try:
@@ -239,7 +240,7 @@ def record_in_hosts(ip, host_name=None, conf_file=paths.HOSTS):
return None return None
return (hosts_ip, names) return (hosts_ip, names)
except IndexError: except IndexError:
print "Warning: Erroneous line '%s' in %s" % (line, conf_file) print("Warning: Erroneous line '%s' in %s" % (line, conf_file))
continue continue
return None return None
@@ -257,7 +258,7 @@ def read_ip_address(host_name, fstore):
try: try:
ip_parsed = ipautil.CheckedIPAddress(ip, match_local=True) ip_parsed = ipautil.CheckedIPAddress(ip, match_local=True)
except Exception as e: except Exception as e:
print "Error: Invalid IP Address %s: %s" % (ip, e) print("Error: Invalid IP Address %s: %s" % (ip, e))
continue continue
else: else:
break break
@@ -266,7 +267,7 @@ def read_ip_address(host_name, fstore):
def read_ip_addresses(host_name, fstore): def read_ip_addresses(host_name, fstore):
ips = [] ips = []
print "Enter the IP address to use, or press Enter to finish." print("Enter the IP address to use, or press Enter to finish.")
while True: while True:
ip = ipautil.user_input("Please provide the IP address to be used for this host name", allow_empty = True) ip = ipautil.user_input("Please provide the IP address to be used for this host name", allow_empty = True)
if not ip: if not ip:
@@ -274,7 +275,7 @@ def read_ip_addresses(host_name, fstore):
try: try:
ip_parsed = ipautil.CheckedIPAddress(ip, match_local=True) ip_parsed = ipautil.CheckedIPAddress(ip, match_local=True)
except Exception as e: except Exception as e:
print "Error: Invalid IP Address %s: %s" % (ip, e) print("Error: Invalid IP Address %s: %s" % (ip, e))
continue continue
ips.append(ip_parsed) ips.append(ip_parsed)
@@ -292,15 +293,15 @@ def read_dns_forwarders():
try: try:
ip_parsed = ipautil.CheckedIPAddress(ip, parse_netmask=False) ip_parsed = ipautil.CheckedIPAddress(ip, parse_netmask=False)
except Exception as e: except Exception as e:
print "Error: Invalid IP Address %s: %s" % (ip, e) print("Error: Invalid IP Address %s: %s" % (ip, e))
print "DNS forwarder %s not added." % ip print("DNS forwarder %s not added." % ip)
continue continue
print "DNS forwarder %s added. You may add another." % ip print("DNS forwarder %s added. You may add another." % ip)
addrs.append(str(ip_parsed)) addrs.append(str(ip_parsed))
if not addrs: if not addrs:
print "No DNS forwarders configured" print("No DNS forwarders configured")
return addrs return addrs
@@ -334,7 +335,7 @@ def read_password(user, confirm=True, validate=True, retry=True, validator=_read
try: try:
validator(pwd) validator(pwd)
except ValueError as e: except ValueError as e:
print str(e) print(str(e))
pwd = None pwd = None
continue continue
if not confirm: if not confirm:
@@ -342,15 +343,15 @@ def read_password(user, confirm=True, validate=True, retry=True, validator=_read
continue continue
pwd_confirm = get_password("Password (confirm): ") pwd_confirm = get_password("Password (confirm): ")
if pwd != pwd_confirm: if pwd != pwd_confirm:
print "Password mismatch!" print("Password mismatch!")
print "" print("")
pwd = None pwd = None
else: else:
correct = True correct = True
except EOFError: except EOFError:
return None return None
finally: finally:
print "" print("")
return pwd return pwd
def update_file(filename, orig, subst): def update_file(filename, orig, subst):
@@ -367,7 +368,7 @@ def update_file(filename, orig, subst):
os.chown(filename, st.st_uid, st.st_gid) # reset perms os.chown(filename, st.st_uid, st.st_gid) # reset perms
return 0 return 0
else: else:
print "File %s doesn't exist." % filename print("File %s doesn't exist." % filename)
return 1 return 1
def set_directive(filename, directive, value, quotes=True, separator=' '): def set_directive(filename, directive, value, quotes=True, separator=' '):
@@ -475,12 +476,12 @@ def get_server_ip_address(host_name, fstore, unattended, setup_dns, ip_addresses
try: try:
hostaddr = resolve_host(host_name) hostaddr = resolve_host(host_name)
except HostnameLocalhost: except HostnameLocalhost:
print >> sys.stderr, "The hostname resolves to the localhost address (127.0.0.1/::1)" print("The hostname resolves to the localhost address (127.0.0.1/::1)", file=sys.stderr)
print >> sys.stderr, "Please change your /etc/hosts file so that the hostname" print("Please change your /etc/hosts file so that the hostname", file=sys.stderr)
print >> sys.stderr, "resolves to the ip address of your network interface." print("resolves to the ip address of your network interface.", file=sys.stderr)
print >> sys.stderr, "The KDC service does not listen on localhost" print("The KDC service does not listen on localhost", file=sys.stderr)
print >> sys.stderr, "" print("", file=sys.stderr)
print >> sys.stderr, "Please fix your /etc/hosts file and restart the setup program" print("Please fix your /etc/hosts file and restart the setup program", file=sys.stderr)
sys.exit(1) sys.exit(1)
ip_add_to_hosts = False ip_add_to_hosts = False
@@ -505,16 +506,16 @@ def get_server_ip_address(host_name, fstore, unattended, setup_dns, ip_addresses
if set(ip_addresses) <= set(ips): if set(ip_addresses) <= set(ips):
ips = ip_addresses ips = ip_addresses
else: else:
print >>sys.stderr, "Error: the hostname resolves to IP address(es) that are different" print("Error: the hostname resolves to IP address(es) that are different", file=sys.stderr)
print >>sys.stderr, "from those provided on the command line. Please fix your DNS" print("from those provided on the command line. Please fix your DNS", file=sys.stderr)
print >>sys.stderr, "or /etc/hosts file and restart the installation." print("or /etc/hosts file and restart the installation.", file=sys.stderr)
print >>sys.stderr, "Provided but not resolved address(es): %s" % \ print("Provided but not resolved address(es): %s" % \
", ".join(str(ip) for ip in (set(ip_addresses) - set(ips))) ", ".join(str(ip) for ip in (set(ip_addresses) - set(ips))), file=sys.stderr)
sys.exit(1) sys.exit(1)
ip_add_to_hosts = True ip_add_to_hosts = True
if not ips: if not ips:
print >> sys.stderr, "No usable IP address provided nor resolved." print("No usable IP address provided nor resolved.", file=sys.stderr)
sys.exit(1) sys.exit(1)
for ip_address in ips: for ip_address in ips:
@@ -523,18 +524,18 @@ def get_server_ip_address(host_name, fstore, unattended, setup_dns, ip_addresses
if hosts_record is None: if hosts_record is None:
if ip_add_to_hosts or setup_dns: if ip_add_to_hosts or setup_dns:
print "Adding ["+str(ip_address)+" "+host_name+"] to your /etc/hosts file" print("Adding ["+str(ip_address)+" "+host_name+"] to your /etc/hosts file")
fstore.backup_file(paths.HOSTS) fstore.backup_file(paths.HOSTS)
add_record_to_hosts(str(ip_address), host_name) add_record_to_hosts(str(ip_address), host_name)
else: else:
primary_host = hosts_record[1][0] primary_host = hosts_record[1][0]
if primary_host != host_name: if primary_host != host_name:
print >>sys.stderr, "Error: there is already a record in /etc/hosts for IP address %s:" \ print("Error: there is already a record in /etc/hosts for IP address %s:" \
% ip_address % ip_address, file=sys.stderr)
print >>sys.stderr, hosts_record[0], " ".join(hosts_record[1]) print(hosts_record[0], " ".join(hosts_record[1]), file=sys.stderr)
print >>sys.stderr, "Chosen hostname %s does not match configured canonical hostname %s" \ print("Chosen hostname %s does not match configured canonical hostname %s" \
% (host_name, primary_host) % (host_name, primary_host), file=sys.stderr)
print >>sys.stderr, "Please fix your /etc/hosts file and restart the installation." print("Please fix your /etc/hosts file and restart the installation.", file=sys.stderr)
sys.exit(1) sys.exit(1)
return ips return ips
@@ -597,8 +598,8 @@ def create_replica_config(dirman_password, filename, options):
top_dir, dir = expand_replica_info(filename, dirman_password) top_dir, dir = expand_replica_info(filename, dirman_password)
except Exception as e: except Exception as e:
root_logger.error("Failed to decrypt or open the replica file.") root_logger.error("Failed to decrypt or open the replica file.")
print "ERROR: Failed to decrypt or open the replica file." print("ERROR: Failed to decrypt or open the replica file.")
print "Verify you entered the correct Directory Manager password." print("Verify you entered the correct Directory Manager password.")
sys.exit(1) sys.exit(1)
config = ReplicaConfig(top_dir) config = ReplicaConfig(top_dir)
read_replica_info(dir, config) read_replica_info(dir, config)
@@ -618,7 +619,7 @@ def create_replica_config(dirman_password, filename, options):
sys.exit(1) sys.exit(1)
if config.host_name != host: if config.host_name != host:
try: try:
print "This replica was created for '%s' but this machine is named '%s'" % (config.host_name, host) print("This replica was created for '%s' but this machine is named '%s'" % (config.host_name, host))
if not ipautil.user_input("This may cause problems. Continue?", False): if not ipautil.user_input("This may cause problems. Continue?", False):
root_logger.debug( root_logger.debug(
"Replica was created for %s but machine is named %s " "Replica was created for %s but machine is named %s "
@@ -626,7 +627,7 @@ def create_replica_config(dirman_password, filename, options):
config.host_name, host) config.host_name, host)
sys.exit(0) sys.exit(0)
config.host_name = host config.host_name = host
print "" print("")
except KeyboardInterrupt: except KeyboardInterrupt:
root_logger.debug("Keyboard Interrupt") root_logger.debug("Keyboard Interrupt")
sys.exit(0) sys.exit(0)
@@ -734,7 +735,7 @@ def run_script(main_function, operation_name, log_file_name=None,
root_logger.debug('The %s command failed, exception: %s: %s', root_logger.debug('The %s command failed, exception: %s: %s',
operation_name, type(e).__name__, e) operation_name, type(e).__name__, e)
if fail_message and not isinstance(e, SystemExit): if fail_message and not isinstance(e, SystemExit):
print fail_message print(fail_message)
raise raise
else: else:
if return_value: if return_value:
@@ -748,7 +749,7 @@ def run_script(main_function, operation_name, log_file_name=None,
except BaseException as error: except BaseException as error:
message, exitcode = handle_error(error, log_file_name) message, exitcode = handle_error(error, log_file_name)
if message: if message:
print >> sys.stderr, message print(message, file=sys.stderr)
sys.exit(exitcode) sys.exit(exitcode)

View File

@@ -17,6 +17,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
import os import os
import time import time
from optparse import OptionGroup from optparse import OptionGroup
@@ -178,7 +180,7 @@ class CACertManage(admintool.AdminTool):
return self.renew_external_step_1(ca) return self.renew_external_step_1(ca)
def renew_self_signed(self, ca): def renew_self_signed(self, ca):
print "Renewing CA certificate, please wait" print("Renewing CA certificate, please wait")
try: try:
ca.set_renewal_master() ca.set_renewal_master()
@@ -187,21 +189,21 @@ class CACertManage(admintool.AdminTool):
self.resubmit_request(ca, 'caCACert') self.resubmit_request(ca, 'caCACert')
print "CA certificate successfully renewed" print("CA certificate successfully renewed")
def renew_external_step_1(self, ca): def renew_external_step_1(self, ca):
print "Exporting CA certificate signing request, please wait" print("Exporting CA certificate signing request, please wait")
self.resubmit_request(ca, 'ipaCSRExport') self.resubmit_request(ca, 'ipaCSRExport')
print("The next step is to get %s signed by your CA and re-run " print(("The next step is to get %s signed by your CA and re-run "
"ipa-cacert-manage as:" % paths.IPA_CA_CSR) "ipa-cacert-manage as:" % paths.IPA_CA_CSR))
print("ipa-cacert-manage renew " print("ipa-cacert-manage renew "
"--external-cert-file=/path/to/signed_certificate " "--external-cert-file=/path/to/signed_certificate "
"--external-cert-file=/path/to/external_ca_certificate") "--external-cert-file=/path/to/external_ca_certificate")
def renew_external_step_2(self, ca, old_cert): def renew_external_step_2(self, ca, old_cert):
print "Importing the renewed CA certificate, please wait" print("Importing the renewed CA certificate, please wait")
options = self.options options = self.options
cert_file, ca_file = installutils.load_external_cert( cert_file, ca_file = installutils.load_external_cert(
@@ -297,7 +299,7 @@ class CACertManage(admintool.AdminTool):
self.resubmit_request(ca, 'ipaRetrieval') self.resubmit_request(ca, 'ipaRetrieval')
print "CA certificate successfully renewed" print("CA certificate successfully renewed")
def resubmit_request(self, ca, profile): def resubmit_request(self, ca, profile):
timeout = api.env.startup_timeout + 60 timeout = api.env.startup_timeout + 60
@@ -320,7 +322,7 @@ class CACertManage(admintool.AdminTool):
certmonger.modify(self.request_id, profile='ipaCACertRenewal') certmonger.modify(self.request_id, profile='ipaCACertRenewal')
def install(self): def install(self):
print "Installing CA certificate, please wait" print("Installing CA certificate, please wait")
options = self.options options = self.options
cert_filename = self.args[1] cert_filename = self.args[1]
@@ -366,4 +368,4 @@ class CACertManage(admintool.AdminTool):
raise admintool.ScriptError( raise admintool.ScriptError(
"Failed to install the certificate: %s" % e) "Failed to install the certificate: %s" % e)
print "CA certificate successfully installed" print("CA certificate successfully installed")

View File

@@ -18,6 +18,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
from textwrap import dedent from textwrap import dedent
from ipalib import api from ipalib import api
from ipaplatform import services from ipaplatform import services
@@ -156,7 +158,7 @@ class KRAInstaller(KRAInstall):
def _run(self): def _run(self):
super(KRAInstaller, self).run() super(KRAInstaller, self).run()
print dedent(self.INSTALLER_START_MESSAGE) print(dedent(self.INSTALLER_START_MESSAGE))
if not self.installing_replica: if not self.installing_replica:
replica_config = None replica_config = None

View File

@@ -23,6 +23,8 @@
# TODO # TODO
# save undo files? # save undo files?
from __future__ import print_function
import os import os
import sys import sys
@@ -75,7 +77,7 @@ class LDAPUpdater(admintool.AdminTool):
try: try:
installutils.check_server_configuration() installutils.check_server_configuration()
except RuntimeError as e: except RuntimeError as e:
print unicode(e) print(unicode(e))
sys.exit(1) sys.exit(1)
def setup_logging(self): def setup_logging(self):

View File

@@ -19,6 +19,7 @@
# #
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import print_function
import os import os
import shutil import shutil
@@ -545,7 +546,7 @@ class ReplicaPrepare(admintool.AdminTool):
self.log.info('Waiting for %s A or AAAA record to be resolvable', self.log.info('Waiting for %s A or AAAA record to be resolvable',
replica_fqdn) replica_fqdn)
print 'This can be safely interrupted (Ctrl+C)' print('This can be safely interrupted (Ctrl+C)')
try: try:
while not self.check_dns(replica_fqdn): while not self.check_dns(replica_fqdn):

View File

@@ -18,6 +18,7 @@
# #
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import print_function
import shutil import shutil
import fileinput import fileinput
@@ -276,7 +277,7 @@ class KrbInstance(service.Service):
try: try:
ipautil.run(args, nolog=(self.master_password,), stdin=''.join(dialogue)) ipautil.run(args, nolog=(self.master_password,), stdin=''.join(dialogue))
except ipautil.CalledProcessError as e: except ipautil.CalledProcessError as e:
print "Failed to initialize the realm container" print("Failed to initialize the realm container")
def __configure_instance(self): def __configure_instance(self):
self.__template_file(paths.KRB5KDC_KDC_CONF, chmod=None) self.__template_file(paths.KRB5KDC_KDC_CONF, chmod=None)

View File

@@ -17,6 +17,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
import time import time
import datetime import datetime
import sys import sys
@@ -69,7 +71,7 @@ def replica_conn_check(master_host, host_name, realm, check_ca,
Does not return a value, will sys.exit() on failure. Does not return a value, will sys.exit() on failure.
""" """
print "Run connection check to master" print("Run connection check to master")
args = [paths.IPA_REPLICA_CONNCHECK, "--master", master_host, args = [paths.IPA_REPLICA_CONNCHECK, "--master", master_host,
"--auto-master-check", "--realm", realm, "--auto-master-check", "--realm", realm,
"--principal", "admin", "--principal", "admin",
@@ -90,7 +92,7 @@ def replica_conn_check(master_host, host_name, realm, check_ca,
"\nPlease fix your network settings according to error messages above." + "\nPlease fix your network settings according to error messages above." +
"\nIf the check results are not valid it can be skipped with --skip-conncheck parameter.") "\nIf the check results are not valid it can be skipped with --skip-conncheck parameter.")
else: else:
print "Connection check OK" print("Connection check OK")
def enable_replication_version_checking(hostname, realm, dirman_passwd): def enable_replication_version_checking(hostname, realm, dirman_passwd):
""" """
@@ -158,7 +160,7 @@ def wait_for_entry(connection, entry, timeout=7200, attr='', quiet=True):
except errors.NotFound: except errors.NotFound:
pass # no entry yet pass # no entry yet
except Exception as e: # badness except Exception as e: # badness
print "\nError reading entry", dn, e print("\nError reading entry", dn, e)
break break
if not entry: if not entry:
if not quiet: if not quiet:
@@ -167,11 +169,11 @@ def wait_for_entry(connection, entry, timeout=7200, attr='', quiet=True):
time.sleep(1) time.sleep(1)
if not entry and int(time.time()) > timeout: if not entry and int(time.time()) > timeout:
print "\nwait_for_entry timeout for %s for %s" % (connection, dn) print("\nwait_for_entry timeout for %s for %s" % (connection, dn))
elif entry and not quiet: elif entry and not quiet:
print "\nThe waited for entry is:", entry print("\nThe waited for entry is:", entry)
elif not entry: elif not entry:
print "\nError: could not read entry %s from %s" % (dn, connection) print("\nError: could not read entry %s from %s" % (dn, connection))
class ReplicationManager(object): class ReplicationManager(object):
@@ -501,7 +503,7 @@ class ReplicationManager(object):
except errors.DuplicateEntry: except errors.DuplicateEntry:
benum += 1 benum += 1
except errors.ExecutionError as e: except errors.ExecutionError as e:
print "Could not add backend entry " + dn, e print("Could not add backend entry " + dn, e)
raise raise
return cn return cn
@@ -556,13 +558,13 @@ class ReplicationManager(object):
def add_passsync_user(self, conn, password): def add_passsync_user(self, conn, password):
pass_dn = DN(('uid', 'passsync'), ('cn', 'sysaccounts'), ('cn', 'etc'), self.suffix) pass_dn = DN(('uid', 'passsync'), ('cn', 'sysaccounts'), ('cn', 'etc'), self.suffix)
print "The user for the Windows PassSync service is %s" % pass_dn print("The user for the Windows PassSync service is %s" % pass_dn)
try: try:
conn.get_entry(pass_dn) conn.get_entry(pass_dn)
print "Windows PassSync system account exists, not resetting password" print("Windows PassSync system account exists, not resetting password")
except errors.NotFound: except errors.NotFound:
# The user doesn't exist, add it # The user doesn't exist, add it
print "Adding Windows PassSync system account" print("Adding Windows PassSync system account")
entry = conn.make_entry( entry = conn.make_entry(
pass_dn, pass_dn,
objectclass=["account", "simplesecurityobject"], objectclass=["account", "simplesecurityobject"],
@@ -855,7 +857,7 @@ class ReplicationManager(object):
'nsds5ReplicaLastInitEnd'] 'nsds5ReplicaLastInitEnd']
entry = conn.get_entry(agmtdn, attrlist) entry = conn.get_entry(agmtdn, attrlist)
if not entry: if not entry:
print "Error reading status from agreement", agmtdn print("Error reading status from agreement", agmtdn)
hasError = 1 hasError = 1
else: else:
refresh = entry.single_value.get('nsds5BeginReplicaRefresh') refresh = entry.single_value.get('nsds5BeginReplicaRefresh')
@@ -863,18 +865,18 @@ class ReplicationManager(object):
status = entry.single_value.get('nsds5ReplicaLastInitStatus') status = entry.single_value.get('nsds5ReplicaLastInitStatus')
if not refresh: # done - check status if not refresh: # done - check status
if not status: if not status:
print "No status yet" print("No status yet")
elif status.find("replica busy") > -1: elif status.find("replica busy") > -1:
print "[%s] reports: Replica Busy! Status: [%s]" % (conn.host, status) print("[%s] reports: Replica Busy! Status: [%s]" % (conn.host, status))
done = True done = True
hasError = 2 hasError = 2
elif status.find("Total update succeeded") > -1: elif status.find("Total update succeeded") > -1:
print "\nUpdate succeeded" print("\nUpdate succeeded")
done = True done = True
elif inprogress.lower() == 'true': elif inprogress.lower() == 'true':
print "\nUpdate in progress yet not in progress" print("\nUpdate in progress yet not in progress")
else: else:
print "\n[%s] reports: Update failed! Status: [%s]" % (conn.host, status) print("\n[%s] reports: Update failed! Status: [%s]" % (conn.host, status))
hasError = 1 hasError = 1
done = True done = True
else: else:
@@ -895,7 +897,7 @@ class ReplicationManager(object):
'nsds5ReplicaLastUpdateEnd'] 'nsds5ReplicaLastUpdateEnd']
entry = conn.get_entry(agmtdn, attrlist) entry = conn.get_entry(agmtdn, attrlist)
if not entry: if not entry:
print "Error reading status from agreement", agmtdn print("Error reading status from agreement", agmtdn)
hasError = 1 hasError = 1
else: else:
inprogress = entry.single_value.get('nsds5replicaUpdateInProgress') inprogress = entry.single_value.get('nsds5replicaUpdateInProgress')
@@ -930,7 +932,7 @@ class ReplicationManager(object):
while not done and not haserror: while not done and not haserror:
time.sleep(1) # give it a few seconds to get going time.sleep(1) # give it a few seconds to get going
done, haserror = self.check_repl_init(conn, agmtdn, start) done, haserror = self.check_repl_init(conn, agmtdn, start)
print "" print("")
return haserror return haserror
def wait_for_repl_update(self, conn, agmtdn, maxtries=600): def wait_for_repl_update(self, conn, agmtdn, maxtries=600):
@@ -942,12 +944,12 @@ class ReplicationManager(object):
done, haserror, error_message = self.check_repl_update(conn, agmtdn) done, haserror, error_message = self.check_repl_update(conn, agmtdn)
maxtries -= 1 maxtries -= 1
if maxtries == 0: # too many tries if maxtries == 0: # too many tries
print "Error: timeout: could not determine agreement status: please check your directory server logs for possible errors" print("Error: timeout: could not determine agreement status: please check your directory server logs for possible errors")
haserror = 1 haserror = 1
return haserror, error_message return haserror, error_message
def start_replication(self, conn, hostname=None, master=None): def start_replication(self, conn, hostname=None, master=None):
print "Starting replication, please wait until this has completed." print("Starting replication, please wait until this has completed.")
if hostname == None: if hostname == None:
hostname = self.conn.host hostname = self.conn.host
cn, dn = self.agreement_dn(hostname, master) cn, dn = self.agreement_dn(hostname, master)
@@ -1443,11 +1445,11 @@ class ReplicationManager(object):
try: try:
self.conn.add_entry(e) self.conn.add_entry(e)
except errors.DuplicateEntry: except errors.DuplicateEntry:
print "CLEANALLRUV task for replica id %d already exists." % replicaId print("CLEANALLRUV task for replica id %d already exists." % replicaId)
else: else:
print "Background task created to clean replication data. This may take a while." print("Background task created to clean replication data. This may take a while.")
print "This may be safely interrupted with Ctrl+C" print("This may be safely interrupted with Ctrl+C")
wait_for_task(self.conn, dn) wait_for_task(self.conn, dn)
@@ -1471,11 +1473,11 @@ class ReplicationManager(object):
try: try:
self.conn.add_entry(e) self.conn.add_entry(e)
except errors.DuplicateEntry: except errors.DuplicateEntry:
print "An abort CLEANALLRUV task for replica id %d already exists." % replicaId print("An abort CLEANALLRUV task for replica id %d already exists." % replicaId)
else: else:
print "Background task created. This may take a while." print("Background task created. This may take a while.")
print "This may be safely interrupted with Ctrl+C" print("This may be safely interrupted with Ctrl+C")
wait_for_task(self.conn, dn) wait_for_task(self.conn, dn)

View File

@@ -2,6 +2,8 @@
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license # Copyright (C) 2015 FreeIPA Contributors see COPYING for license
# #
from __future__ import print_function
import os import os
import pickle import pickle
import pwd import pwd
@@ -150,35 +152,35 @@ def write_cache(options):
def read_host_name(host_default, no_host_dns=False): def read_host_name(host_default, no_host_dns=False):
host_name = "" host_name = ""
print "Enter the fully qualified domain name of the computer" print("Enter the fully qualified domain name of the computer")
print "on which you're setting up server software. Using the form" print("on which you're setting up server software. Using the form")
print "<hostname>.<domainname>" print("<hostname>.<domainname>")
print "Example: master.example.com." print("Example: master.example.com.")
print "" print("")
print "" print("")
if host_default == "": if host_default == "":
host_default = "master.example.com" host_default = "master.example.com"
host_name = user_input("Server host name", host_default, allow_empty=False) host_name = user_input("Server host name", host_default, allow_empty=False)
print "" print("")
verify_fqdn(host_name, no_host_dns) verify_fqdn(host_name, no_host_dns)
return host_name return host_name
def read_domain_name(domain_name, unattended): def read_domain_name(domain_name, unattended):
print "The domain name has been determined based on the host name." print("The domain name has been determined based on the host name.")
print "" print("")
if not unattended: if not unattended:
domain_name = str(user_input("Please confirm the domain name", domain_name = str(user_input("Please confirm the domain name",
domain_name)) domain_name))
print "" print("")
return domain_name return domain_name
def read_realm_name(domain_name, unattended): def read_realm_name(domain_name, unattended):
print "The kerberos protocol requires a Realm name to be defined." print("The kerberos protocol requires a Realm name to be defined.")
print "This is typically the domain name converted to uppercase." print("This is typically the domain name converted to uppercase.")
print "" print("")
if unattended: if unattended:
return domain_name.upper() return domain_name.upper()
@@ -186,27 +188,27 @@ def read_realm_name(domain_name, unattended):
domain_name.upper())) domain_name.upper()))
upper_dom = realm_name.upper() upper_dom = realm_name.upper()
if upper_dom != realm_name: if upper_dom != realm_name:
print "An upper-case realm name is required." print("An upper-case realm name is required.")
if not user_input("Do you want to use " + upper_dom + if not user_input("Do you want to use " + upper_dom +
" as realm name?", True): " as realm name?", True):
print "" print("")
print "An upper-case realm name is required. Unable to continue." print("An upper-case realm name is required. Unable to continue.")
sys.exit(1) sys.exit(1)
else: else:
realm_name = upper_dom realm_name = upper_dom
print "" print("")
return realm_name return realm_name
def read_dm_password(): def read_dm_password():
print "Certain directory server operations require an administrative user." print("Certain directory server operations require an administrative user.")
print("This user is referred to as the Directory Manager and has full " print("This user is referred to as the Directory Manager and has full "
"access") "access")
print("to the Directory for system management tasks and will be added to " print("to the Directory for system management tasks and will be added to "
"the") "the")
print "instance of directory server created for IPA." print("instance of directory server created for IPA.")
print "The password must be at least 8 characters long." print("The password must be at least 8 characters long.")
print "" print("")
# TODO: provide the option of generating a random password # TODO: provide the option of generating a random password
dm_password = read_password("Directory Manager", dm_password = read_password("Directory Manager",
validator=validate_dm_password) validator=validate_dm_password)
@@ -214,10 +216,10 @@ def read_dm_password():
def read_admin_password(): def read_admin_password():
print "The IPA server requires an administrative user, named 'admin'." print("The IPA server requires an administrative user, named 'admin'.")
print("This user is a regular system account used for IPA server " print("This user is a regular system account used for IPA server "
"administration.") "administration.")
print "" print("")
# TODO: provide the option of generating a random password # TODO: provide the option of generating a random password
admin_password = read_password("IPA admin", admin_password = read_password("IPA admin",
validator=validate_admin_password) validator=validate_admin_password)
@@ -227,12 +229,12 @@ def read_admin_password():
def check_dirsrv(unattended): def check_dirsrv(unattended):
(ds_unsecure, ds_secure) = dsinstance.check_ports() (ds_unsecure, ds_secure) = dsinstance.check_ports()
if not ds_unsecure or not ds_secure: if not ds_unsecure or not ds_secure:
print "IPA requires ports 389 and 636 for the Directory Server." print("IPA requires ports 389 and 636 for the Directory Server.")
print "These are currently in use:" print("These are currently in use:")
if not ds_unsecure: if not ds_unsecure:
print "\t389" print("\t389")
if not ds_secure: if not ds_secure:
print "\t636" print("\t636")
sys.exit(1) sys.exit(1)
@@ -264,9 +266,9 @@ def common_cleanup(func):
success = True success = True
except KeyboardInterrupt: except KeyboardInterrupt:
ds = installer._ds ds = installer._ds
print "\nCleaning up..." print("\nCleaning up...")
if ds: if ds:
print "Removing configuration for %s instance" % ds.serverid print("Removing configuration for %s instance" % ds.serverid)
ds.stop() ds.stop()
if ds.serverid: if ds.serverid:
try: try:
@@ -310,7 +312,7 @@ def install_check(installer):
"KDC master password of sufficient strength is autogenerated " "KDC master password of sufficient strength is autogenerated "
"during IPA server installation and should not be set " "during IPA server installation and should not be set "
"manually.") "manually.")
print textwrap.fill(msg, width=79, replace_whitespace=False) print(textwrap.fill(msg, width=79, replace_whitespace=False))
installer._installation_cleanup = True installer._installation_cleanup = True
@@ -368,31 +370,31 @@ def install_check(installer):
print("=======================================" print("======================================="
"=======================================") "=======================================")
print "This program will set up the FreeIPA Server." print("This program will set up the FreeIPA Server.")
print "" print("")
print "This includes:" print("This includes:")
if setup_ca: if setup_ca:
print(" * Configure a stand-alone CA (dogtag) for certificate " print(" * Configure a stand-alone CA (dogtag) for certificate "
"management") "management")
if setup_kra: if setup_kra:
print " * Configure a stand-alone KRA (dogtag) for key storage" print(" * Configure a stand-alone KRA (dogtag) for key storage")
if not options.no_ntp: if not options.no_ntp:
print " * Configure the Network Time Daemon (ntpd)" print(" * Configure the Network Time Daemon (ntpd)")
print " * Create and configure an instance of Directory Server" print(" * Create and configure an instance of Directory Server")
print " * Create and configure a Kerberos Key Distribution Center (KDC)" print(" * Create and configure a Kerberos Key Distribution Center (KDC)")
print " * Configure Apache (httpd)" print(" * Configure Apache (httpd)")
if options.setup_dns: if options.setup_dns:
print " * Configure DNS (bind)" print(" * Configure DNS (bind)")
if not options.no_pkinit: if not options.no_pkinit:
print " * Configure the KDC to enable PKINIT" print(" * Configure the KDC to enable PKINIT")
if options.no_ntp: if options.no_ntp:
print "" print("")
print "Excluded by options:" print("Excluded by options:")
print " * Configure the Network Time Daemon (ntpd)" print(" * Configure the Network Time Daemon (ntpd)")
if installer.interactive: if installer.interactive:
print "" print("")
print "To accept the default shown in brackets, press the Enter key." print("To accept the default shown in brackets, press the Enter key.")
print "" print("")
if not options.external_cert_files: if not options.external_cert_files:
# Make sure the 389-ds ports are available # Make sure the 389-ds ports are available
@@ -402,10 +404,10 @@ def install_check(installer):
try: try:
ipaclient.ntpconf.check_timedate_services() ipaclient.ntpconf.check_timedate_services()
except ipaclient.ntpconf.NTPConflictingService as e: except ipaclient.ntpconf.NTPConflictingService as e:
print("WARNING: conflicting time&date synchronization service '%s'" print(("WARNING: conflicting time&date synchronization service '%s'"
" will be disabled" % e.conflicting_service) " will be disabled" % e.conflicting_service))
print "in favor of ntpd" print("in favor of ntpd")
print "" print("")
except ipaclient.ntpconf.NTPConfigurationError: except ipaclient.ntpconf.NTPConfigurationError:
pass pass
@@ -417,7 +419,7 @@ def install_check(installer):
if ipautil.user_input("Do you want to configure integrated DNS " if ipautil.user_input("Do you want to configure integrated DNS "
"(BIND)?", False): "(BIND)?", False):
options.setup_dns = True options.setup_dns = True
print "" print("")
# check bind packages are installed # check bind packages are installed
if options.setup_dns: if options.setup_dns:
@@ -449,13 +451,13 @@ def install_check(installer):
system_hostname = get_fqdn() system_hostname = get_fqdn()
if host_name != system_hostname: if host_name != system_hostname:
print >>sys.stderr print(file=sys.stderr)
print >>sys.stderr, ("Warning: hostname %s does not match system " print(("Warning: hostname %s does not match system "
"hostname %s." % (host_name, system_hostname)) "hostname %s." % (host_name, system_hostname)), file=sys.stderr)
print >>sys.stderr, ("System hostname will be updated during the " print(("System hostname will be updated during the "
"installation process") "installation process"), file=sys.stderr)
print >>sys.stderr, "to prevent service failures." print("to prevent service failures.", file=sys.stderr)
print >>sys.stderr print(file=sys.stderr)
if not options.domain_name: if not options.domain_name:
domain_name = read_domain_name(host_name[host_name.find(".")+1:], domain_name = read_domain_name(host_name[host_name.find(".")+1:],
@@ -601,7 +603,7 @@ def install_check(installer):
try: try:
kra.install_check(api, None, options) kra.install_check(api, None, options)
except RuntimeError as e: except RuntimeError as e:
print str(e) print(str(e))
sys.exit(1) sys.exit(1)
if options.setup_dns: if options.setup_dns:
@@ -612,25 +614,25 @@ def install_check(installer):
not installer.interactive, False, not installer.interactive, False,
options.ip_addresses) options.ip_addresses)
print print()
print "The IPA Master Server will be configured with:" print("The IPA Master Server will be configured with:")
print "Hostname: %s" % host_name print("Hostname: %s" % host_name)
print "IP address(es): %s" % ", ".join(str(ip) for ip in ip_addresses) print("IP address(es): %s" % ", ".join(str(ip) for ip in ip_addresses))
print "Domain name: %s" % domain_name print("Domain name: %s" % domain_name)
print "Realm name: %s" % realm_name print("Realm name: %s" % realm_name)
print print()
if options.setup_dns: if options.setup_dns:
print "BIND DNS server will be configured to serve IPA domain with:" print("BIND DNS server will be configured to serve IPA domain with:")
print "Forwarders: %s" % ( print("Forwarders: %s" % (
"No forwarders" if not dns.dns_forwarders "No forwarders" if not dns.dns_forwarders
else ", ".join([str(ip) for ip in dns.dns_forwarders]) else ", ".join([str(ip) for ip in dns.dns_forwarders])
) ))
print "Reverse zone(s): %s" % ( print("Reverse zone(s): %s" % (
"No reverse zone" if options.no_reverse or not dns.reverse_zones "No reverse zone" if options.no_reverse or not dns.reverse_zones
else ", ".join(str(rz) for rz in dns.reverse_zones) else ", ".join(str(rz) for rz in dns.reverse_zones)
) ))
print print()
# If domain name and realm does not match, IPA server will not be able # If domain name and realm does not match, IPA server will not be able
# to estabilish trust with Active Directory. Print big fat warning. # to estabilish trust with Active Directory. Print big fat warning.
@@ -700,10 +702,10 @@ def install(installer):
installer._installation_cleanup = False installer._installation_cleanup = False
if installer.interactive: if installer.interactive:
print "" print("")
print "The following operations may take some minutes to complete." print("The following operations may take some minutes to complete.")
print "Please wait until the prompt is returned." print("Please wait until the prompt is returned.")
print "" print("")
system_hostname = get_fqdn() system_hostname = get_fqdn()
if host_name != system_hostname: if host_name != system_hostname:
@@ -891,45 +893,45 @@ def install(installer):
print("=======================================" print("======================================="
"=======================================") "=======================================")
print "Setup complete" print("Setup complete")
print "" print("")
print "Next steps:" print("Next steps:")
print "\t1. You must make sure these network ports are open:" print("\t1. You must make sure these network ports are open:")
print "\t\tTCP Ports:" print("\t\tTCP Ports:")
print "\t\t * 80, 443: HTTP/HTTPS" print("\t\t * 80, 443: HTTP/HTTPS")
print "\t\t * 389, 636: LDAP/LDAPS" print("\t\t * 389, 636: LDAP/LDAPS")
print "\t\t * 88, 464: kerberos" print("\t\t * 88, 464: kerberos")
if options.setup_dns: if options.setup_dns:
print "\t\t * 53: bind" print("\t\t * 53: bind")
print "\t\tUDP Ports:" print("\t\tUDP Ports:")
print "\t\t * 88, 464: kerberos" print("\t\t * 88, 464: kerberos")
if options.setup_dns: if options.setup_dns:
print "\t\t * 53: bind" print("\t\t * 53: bind")
if not options.no_ntp: if not options.no_ntp:
print "\t\t * 123: ntp" print("\t\t * 123: ntp")
print "" print("")
print("\t2. You can now obtain a kerberos ticket using the command: " print("\t2. You can now obtain a kerberos ticket using the command: "
"'kinit admin'") "'kinit admin'")
print("\t This ticket will allow you to use the IPA tools (e.g., ipa " print("\t This ticket will allow you to use the IPA tools (e.g., ipa "
"user-add)") "user-add)")
print "\t and the web user interface." print("\t and the web user interface.")
if not services.knownservices.ntpd.is_running(): if not services.knownservices.ntpd.is_running():
print "\t3. Kerberos requires time synchronization between clients" print("\t3. Kerberos requires time synchronization between clients")
print("\t and servers for correct operation. You should consider " print("\t and servers for correct operation. You should consider "
"enabling ntpd.") "enabling ntpd.")
print "" print("")
if setup_ca: if setup_ca:
print("Be sure to back up the CA certificates stored in " + print(("Be sure to back up the CA certificates stored in " +
paths.CACERT_P12) paths.CACERT_P12))
if setup_kra: if setup_kra:
print "and the KRA certificates stored in " + paths.KRACERT_P12 print("and the KRA certificates stored in " + paths.KRACERT_P12)
print("These files are required to create replicas. The password for " print("These files are required to create replicas. The password for "
"these") "these")
print "files is the Directory Manager password" print("files is the Directory Manager password")
else: else:
print "In order for Firefox autoconfiguration to work you will need to" print("In order for Firefox autoconfiguration to work you will need to")
print("use a SSL signing certificate. See the IPA documentation for " print("use a SSL signing certificate. See the IPA documentation for "
"more details.") "more details.")
@@ -948,7 +950,7 @@ def uninstall_check(installer):
"KDC master password of sufficient strength is autogenerated " "KDC master password of sufficient strength is autogenerated "
"during IPA server installation and should not be set " "during IPA server installation and should not be set "
"manually.") "manually.")
print textwrap.fill(msg, width=79, replace_whitespace=False) print(textwrap.fill(msg, width=79, replace_whitespace=False))
installer._installation_cleanup = False installer._installation_cleanup = False
@@ -972,8 +974,8 @@ def uninstall_check(installer):
"and configuration!\n") "and configuration!\n")
if not user_input("Are you sure you want to continue with the " if not user_input("Are you sure you want to continue with the "
"uninstall procedure?", False): "uninstall procedure?", False):
print "" print("")
print "Aborting uninstall operation." print("Aborting uninstall operation.")
sys.exit(1) sys.exit(1)
try: try:
@@ -988,7 +990,7 @@ def uninstall_check(installer):
"information about replication agreements. Uninstallation " "information about replication agreements. Uninstallation "
"will continue despite the possible existing replication " "will continue despite the possible existing replication "
"agreements.\n\n") "agreements.\n\n")
print textwrap.fill(msg, width=80, replace_whitespace=False) print(textwrap.fill(msg, width=80, replace_whitespace=False))
else: else:
api.Backend.ldap2.connect(autobind=True) api.Backend.ldap2.connect(autobind=True)
dns.uninstall_check(options) dns.uninstall_check(options)
@@ -1012,13 +1014,13 @@ def uninstall_check(installer):
other_masters) other_masters)
) )
cmd = "$ ipa-replica-manage del %s\n" % api.env.host cmd = "$ ipa-replica-manage del %s\n" % api.env.host
print textwrap.fill(msg, width=80, replace_whitespace=False) print(textwrap.fill(msg, width=80, replace_whitespace=False))
print cmd print(cmd)
if (installer.interactive and if (installer.interactive and
not user_input("Are you sure you want to continue with the " not user_input("Are you sure you want to continue with the "
"uninstall procedure?", False)): "uninstall procedure?", False)):
print "" print("")
print "Aborting uninstall operation." print("Aborting uninstall operation.")
sys.exit(1) sys.exit(1)
installer._fstore = fstore installer._fstore = fstore
@@ -1032,7 +1034,7 @@ def uninstall(installer):
rv = 0 rv = 0
print "Shutting down all IPA services" print("Shutting down all IPA services")
try: try:
(stdout, stderr, rc) = run([paths.IPACTL, "stop"], raiseonerr=False) (stdout, stderr, rc) = run([paths.IPACTL, "stop"], raiseonerr=False)
except Exception as e: except Exception as e:
@@ -1041,7 +1043,7 @@ def uninstall(installer):
# Need to get dogtag info before /etc/ipa/default.conf is removed # Need to get dogtag info before /etc/ipa/default.conf is removed
dogtag_constants = dogtag.configured_constants() dogtag_constants = dogtag.configured_constants()
print "Removing IPA client configuration" print("Removing IPA client configuration")
try: try:
(stdout, stderr, rc) = run([paths.IPA_CLIENT_INSTALL, "--on-master", (stdout, stderr, rc) = run([paths.IPA_CLIENT_INSTALL, "--on-master",
"--unattended", "--uninstall"], "--unattended", "--uninstall"],
@@ -1051,8 +1053,8 @@ def uninstall(installer):
raise RuntimeError(stdout) raise RuntimeError(stdout)
except Exception as e: except Exception as e:
rv = 1 rv = 1
print "Uninstall of client side components failed!" print("Uninstall of client side components failed!")
print "ipa-client-install returned: " + str(e) print("ipa-client-install returned: " + str(e))
ntpinstance.NTPInstance(fstore).uninstall() ntpinstance.NTPInstance(fstore).uninstall()

View File

@@ -2,6 +2,8 @@
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license # Copyright (C) 2015 FreeIPA Contributors see COPYING for license
# #
from __future__ import print_function
import dns.exception as dnsexception import dns.exception as dnsexception
import dns.name as dnsname import dns.name as dnsname
import dns.resolver as dnsresolver import dns.resolver as dnsresolver
@@ -107,7 +109,7 @@ def install_ca_cert(ldap, base_dn, realm, cafile):
os.chmod(constants.CACERT, 0o444) os.chmod(constants.CACERT, 0o444)
except Exception as e: except Exception as e:
print "error copying files: " + str(e) print("error copying files: " + str(e))
sys.exit(1) sys.exit(1)
@@ -138,7 +140,7 @@ def install_http(config, auto_redirect):
shutil.copy(config.dir + "/configure.jar", shutil.copy(config.dir + "/configure.jar",
paths.CONFIGURE_JAR) paths.CONFIGURE_JAR)
except Exception as e: except Exception as e:
print "error copying files: " + str(e) print("error copying files: " + str(e))
sys.exit(1) sys.exit(1)
http.setup_firefox_extension(config.realm_name, config.domain_name) http.setup_firefox_extension(config.realm_name, config.domain_name)
@@ -180,12 +182,12 @@ def install_dns_records(config, options, remote_api):
def check_dirsrv(): def check_dirsrv():
(ds_unsecure, ds_secure) = dsinstance.check_ports() (ds_unsecure, ds_secure) = dsinstance.check_ports()
if not ds_unsecure or not ds_secure: if not ds_unsecure or not ds_secure:
print "IPA requires ports 389 and 636 for the Directory Server." print("IPA requires ports 389 and 636 for the Directory Server.")
print "These are currently in use:" print("These are currently in use:")
if not ds_unsecure: if not ds_unsecure:
print "\t389" print("\t389")
if not ds_secure: if not ds_secure:
print "\t636" print("\t636")
sys.exit(1) sys.exit(1)
@@ -334,10 +336,10 @@ def install_check(installer):
try: try:
ipaclient.ntpconf.check_timedate_services() ipaclient.ntpconf.check_timedate_services()
except ipaclient.ntpconf.NTPConflictingService as e: except ipaclient.ntpconf.NTPConflictingService as e:
print("WARNING: conflicting time&date synchronization service '%s'" print(("WARNING: conflicting time&date synchronization service '%s'"
" will" % e.conflicting_service) " will" % e.conflicting_service))
print "be disabled in favor of ntpd" print("be disabled in favor of ntpd")
print "" print("")
except ipaclient.ntpconf.NTPConfigurationError: except ipaclient.ntpconf.NTPConfigurationError:
pass pass
@@ -416,9 +418,9 @@ def install_check(installer):
'host already exists.') 'host already exists.')
print('A replication agreement for this host already exists. ' print('A replication agreement for this host already exists. '
'It needs to be removed.') 'It needs to be removed.')
print "Run this on the master that generated the info file:" print("Run this on the master that generated the info file:")
print(" %% ipa-replica-manage del %s --force" % print((" %% ipa-replica-manage del %s --force" %
config.host_name) config.host_name))
sys.exit(3) sys.exit(3)
# Detect the current domain level # Detect the current domain level
@@ -455,10 +457,10 @@ def install_check(installer):
else: else:
root_logger.info('Error: Host %s already exists on the master ' root_logger.info('Error: Host %s already exists on the master '
'server.' % config.host_name) 'server.' % config.host_name)
print('The host %s already exists on the master server.' % print(('The host %s already exists on the master server.' %
config.host_name) config.host_name))
print "You should remove it before proceeding:" print("You should remove it before proceeding:")
print " %% ipa host-del %s" % config.host_name print(" %% ipa host-del %s" % config.host_name)
sys.exit(3) sys.exit(3)
dns_masters = remote_api.Object['dnsrecord'].get_dns_masters() dns_masters = remote_api.Object['dnsrecord'].get_dns_masters()
@@ -486,7 +488,7 @@ def install_check(installer):
try: try:
kra.install_check(remote_api, config, options) kra.install_check(remote_api, config, options)
except RuntimeError as e: except RuntimeError as e:
print str(e) print(str(e))
sys.exit(1) sys.exit(1)
except errors.ACIError: except errors.ACIError:
sys.exit("\nThe password provided is incorrect for LDAP server " sys.exit("\nThe password provided is incorrect for LDAP server "
@@ -629,8 +631,8 @@ def install(installer):
args.append("--mkhomedir") args.append("--mkhomedir")
ipautil.run(args) ipautil.run(args)
except Exception as e: except Exception as e:
print "Configuration of client side components failed!" print("Configuration of client side components failed!")
print "ipa-client-install returned: " + str(e) print("ipa-client-install returned: " + str(e))
raise RuntimeError("Failed to configure the client") raise RuntimeError("Failed to configure the client")
ds.replica_populate() ds.replica_populate()

View File

@@ -2,6 +2,8 @@
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license # Copyright (C) 2015 FreeIPA Contributors see COPYING for license
# #
from __future__ import print_function
import re import re
import os import os
import shutil import shutil
@@ -1540,7 +1542,7 @@ def upgrade_check(options):
try: try:
installutils.check_server_configuration() installutils.check_server_configuration()
except RuntimeError as e: except RuntimeError as e:
print unicode(e) print(unicode(e))
sys.exit(1) sys.exit(1)
if not services.knownservices.certmonger.is_running(): if not services.knownservices.certmonger.is_running():
@@ -1587,7 +1589,7 @@ def upgrade():
# store new data version after upgrade # store new data version after upgrade
installutils.store_version() installutils.store_version()
print 'Upgrading IPA services' print('Upgrading IPA services')
root_logger.info('Upgrading the configuration of the IPA services') root_logger.info('Upgrading the configuration of the IPA services')
upgrade_configuration() upgrade_configuration()
root_logger.info('The IPA services were upgraded') root_logger.info('The IPA services were upgraded')

View File

@@ -19,6 +19,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from __future__ import print_function
# WARNING: Do not import ipa modules, this is also used as a # WARNING: Do not import ipa modules, this is also used as a
# stand-alone script (invoked from install/po Makefile). # stand-alone script (invoked from install/po Makefile).
import optparse import optparse
@@ -387,12 +389,12 @@ def validate_file(file_path, validation_mode, reference_pot=None):
if n_warnings: if n_warnings:
warning_lines.insert(0, section_seperator) warning_lines.insert(0, section_seperator)
warning_lines.insert(1, "%d validation warnings in %s" % (n_warnings, file_path)) warning_lines.insert(1, "%d validation warnings in %s" % (n_warnings, file_path))
print '\n'.join(warning_lines) print('\n'.join(warning_lines))
if n_errors: if n_errors:
error_lines.insert(0, section_seperator) error_lines.insert(0, section_seperator)
error_lines.insert(1, "%d validation errors in %s" % (n_errors, file_path)) error_lines.insert(1, "%d validation errors in %s" % (n_errors, file_path))
print '\n'.join(error_lines) print('\n'.join(error_lines))
Result = namedtuple('ValidateFileResult', ['n_entries', 'n_msgids', 'n_msgstrs', 'n_warnings', 'n_errors']) Result = namedtuple('ValidateFileResult', ['n_entries', 'n_msgids', 'n_msgstrs', 'n_warnings', 'n_errors'])
@@ -524,12 +526,12 @@ def validate_file(file_path, validation_mode, reference_pot=None):
def create_po(pot_file, po_file, mo_file): def create_po(pot_file, po_file, mo_file):
if not os.path.isfile(pot_file): if not os.path.isfile(pot_file):
print >>sys.stderr, 'file does not exist "%s"' % (pot_file) print('file does not exist "%s"' % (pot_file), file=sys.stderr)
return 1 return 1
try: try:
po = polib.pofile(pot_file) po = polib.pofile(pot_file)
except Exception as e: except Exception as e:
print >>sys.stderr, 'Unable to parse file "%s": %s' % (pot_file, e) print('Unable to parse file "%s": %s' % (pot_file, e), file=sys.stderr)
return 1 return 1
# Update the metadata in the po file header # Update the metadata in the po file header
@@ -559,10 +561,10 @@ def create_po(pot_file, po_file, mo_file):
# Write out the po and mo files # Write out the po and mo files
po.save(po_file) po.save(po_file)
print "Wrote: %s" % (po_file) print("Wrote: %s" % (po_file))
po.save_as_mofile(mo_file) po.save_as_mofile(mo_file)
print "Wrote: %s" % (mo_file) print("Wrote: %s" % (mo_file))
return 0 return 0
@@ -587,7 +589,7 @@ def validate_unicode_edit(msgid, msgstr):
if verbose: if verbose:
msg = 'Success: message string "%s" maps to translated string "%s"' % (msgid, msgstr) msg = 'Success: message string "%s" maps to translated string "%s"' % (msgid, msgstr)
print msg.encode('utf-8') print(msg.encode('utf-8'))
def test_translations(po_file, lang, domain, locale_dir): def test_translations(po_file, lang, domain, locale_dir):
@@ -615,12 +617,12 @@ def po_file_iterate(po_file, get_msgstr, get_msgstr_plural):
try: try:
# Iterate over the msgid's # Iterate over the msgid's
if not os.path.isfile(po_file): if not os.path.isfile(po_file):
print >>sys.stderr, 'file does not exist "%s"' % (po_file) print('file does not exist "%s"' % (po_file), file=sys.stderr)
return 1 return 1
try: try:
po = polib.pofile(po_file) po = polib.pofile(po_file)
except Exception as e: except Exception as e:
print >>sys.stderr, 'Unable to parse file "%s": %s' % (po_file, e) print('Unable to parse file "%s": %s' % (po_file, e), file=sys.stderr)
return 1 return 1
n_entries = 0 n_entries = 0
@@ -642,7 +644,7 @@ def po_file_iterate(po_file, get_msgstr, get_msgstr_plural):
n_fail += 1 n_fail += 1
if print_traceback: if print_traceback:
traceback.print_exc() traceback.print_exc()
print >> sys.stderr, "ERROR: %s" % e print("ERROR: %s" % e, file=sys.stderr)
try: try:
n_translations += 1 n_translations += 1
@@ -652,7 +654,7 @@ def po_file_iterate(po_file, get_msgstr, get_msgstr_plural):
n_fail += 1 n_fail += 1
if print_traceback: if print_traceback:
traceback.print_exc() traceback.print_exc()
print >> sys.stderr, "ERROR: %s" % e print("ERROR: %s" % e, file=sys.stderr)
else: else:
@@ -667,25 +669,25 @@ def po_file_iterate(po_file, get_msgstr, get_msgstr_plural):
n_fail += 1 n_fail += 1
if print_traceback: if print_traceback:
traceback.print_exc() traceback.print_exc()
print >> sys.stderr, "ERROR: %s" % e print("ERROR: %s" % e, file=sys.stderr)
n_entries += 1 n_entries += 1
except Exception as e: except Exception as e:
if print_traceback: if print_traceback:
traceback.print_exc() traceback.print_exc()
print >> sys.stderr, "ERROR: %s" % e print("ERROR: %s" % e, file=sys.stderr)
return 1 return 1
if not n_entries: if not n_entries:
print >> sys.stderr, "ERROR: no translations found in %s" % (po_file) print("ERROR: no translations found in %s" % (po_file), file=sys.stderr)
return 1 return 1
if n_fail: if n_fail:
print >> sys.stderr, "ERROR: %d failures out of %d translations" % (n_fail, n_entries) print("ERROR: %d failures out of %d translations" % (n_fail, n_entries), file=sys.stderr)
return 1 return 1
print "%d translations in %d messages successfully tested" % (n_translations, n_entries) print("%d translations in %d messages successfully tested" % (n_translations, n_entries))
return 0 return 0
#---------------------------------------------------------------------- #----------------------------------------------------------------------
@@ -751,7 +753,7 @@ def main():
show_strings = options.show_strings show_strings = options.show_strings
if not options.mode: if not options.mode:
print >> sys.stderr, 'ERROR: no mode specified' print('ERROR: no mode specified', file=sys.stderr)
return 1 return 1
if options.mode == 'validate_pot' or options.mode == 'validate_po': if options.mode == 'validate_pot' or options.mode == 'validate_po':
@@ -764,12 +766,12 @@ def main():
elif options.mode == 'validate_po': elif options.mode == 'validate_po':
files = args files = args
if not files: if not files:
print >> sys.stderr, 'ERROR: no po files specified' print('ERROR: no po files specified', file=sys.stderr)
return 1 return 1
validation_mode = 'po' validation_mode = 'po'
reference_pot = polib.pofile(options.pot_file) reference_pot = polib.pofile(options.pot_file)
else: else:
print >> sys.stderr, 'ERROR: unknown validation mode "%s"' % (options.mode) print('ERROR: unknown validation mode "%s"' % (options.mode), file=sys.stderr)
return 1 return 1
total_entries = 0 total_entries = 0
@@ -785,11 +787,11 @@ def main():
total_msgstrs += result.n_msgstrs total_msgstrs += result.n_msgstrs
total_warnings += result.n_warnings total_warnings += result.n_warnings
total_errors += result.n_errors total_errors += result.n_errors
print "%s: %d entries, %d msgid, %d msgstr, %d warnings %d errors" % \ print("%s: %d entries, %d msgid, %d msgstr, %d warnings %d errors" % \
(f, result.n_entries, result.n_msgids, result.n_msgstrs, result.n_warnings, result.n_errors) (f, result.n_entries, result.n_msgids, result.n_msgstrs, result.n_warnings, result.n_errors))
if total_errors: if total_errors:
print section_seperator print(section_seperator)
print "%d errors in %d files" % (total_errors, len(files)) print("%d errors in %d files" % (total_errors, len(files)))
return 1 return 1
else: else:
return 0 return 0
@@ -831,7 +833,7 @@ def main():
return test_translations(po_file, lang, domain, locale_dir) return test_translations(po_file, lang, domain, locale_dir)
else: else:
print >> sys.stderr, 'ERROR: unknown mode "%s"' % (options.mode) print('ERROR: unknown mode "%s"' % (options.mode), file=sys.stderr)
return 1 return 1
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -19,6 +19,8 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import sys import sys
import os import os
import argparse import argparse
@@ -154,4 +156,4 @@ def get_object(conf, args):
if __name__ == '__main__': if __name__ == '__main__':
print main(sys.argv[1:]), print(main(sys.argv[1:]), end=' ')

View File

@@ -19,6 +19,7 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import sys import sys
import os import os
@@ -388,7 +389,7 @@ class TaskRunner(object):
def list_topos(self, args): def list_topos(self, args):
for name, topo in tasks.topologies.items(): for name, topo in tasks.topologies.items():
print '%s: %s' % (name, topo.__doc__) print('%s: %s' % (name, topo.__doc__))
def install_topo(self, args): def install_topo(self, args):
master = self.get_host(args.master, default=args.domain.master) master = self.get_host(args.master, default=args.domain.master)

View File

@@ -19,6 +19,8 @@
"""Pytest plugin for IPA Integration tests""" """Pytest plugin for IPA Integration tests"""
from __future__ import print_function
import os import os
import tempfile import tempfile
import shutil import shutil
@@ -192,7 +194,7 @@ def mh(request, class_integration_logs):
(host.external_hostname, filename)) (host.external_hostname, filename))
class_integration_logs.setdefault(host, []).append(filename) class_integration_logs.setdefault(host, []).append(filename)
print mh.config print(mh.config)
for host in mh.config.get_all_hosts(): for host in mh.config.get_all_hosts():
host.add_log_collector(collect_log) host.add_log_collector(collect_log)
cls.log.info('Preparing host %s', host.hostname) cls.log.info('Preparing host %s', host.hostname)

View File

@@ -17,6 +17,8 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import os import os
import re import re
import contextlib import contextlib
@@ -50,7 +52,7 @@ def check_admin_in_ldap(host):
basedn = host.domain.basedn basedn = host.domain.basedn
user_dn = DN(('uid', 'admin'), ('cn', 'users'), ('cn', 'accounts'), basedn) user_dn = DN(('uid', 'admin'), ('cn', 'users'), ('cn', 'accounts'), basedn)
entry = ldap.get_entry(user_dn) entry = ldap.get_entry(user_dn)
print entry print(entry)
assert entry.dn == user_dn assert entry.dn == user_dn
assert entry['uid'] == ['admin'] assert entry['uid'] == ['admin']

View File

@@ -17,6 +17,8 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
from ipapython.dn import DN from ipapython.dn import DN
from ipatests.test_integration.base import IntegrationTest from ipatests.test_integration.base import IntegrationTest
from ipatests.test_integration import tasks from ipatests.test_integration import tasks
@@ -47,7 +49,7 @@ class TestSimpleReplication(IntegrationTest):
user_dn = DN(('uid', login), ('cn', 'users'), ('cn', 'accounts'), user_dn = DN(('uid', login), ('cn', 'users'), ('cn', 'accounts'),
basedn) basedn)
entry = ldap.get_entry(user_dn) entry = ldap.get_entry(user_dn)
print entry print(entry)
assert entry.dn == user_dn assert entry.dn == user_dn
assert entry['uid'] == [login] assert entry['uid'] == [login]

View File

@@ -21,13 +21,14 @@
""" """
Test the `ipalib.aci` module. Test the `ipalib.aci` module.
""" """
from __future__ import print_function
from ipalib.aci import ACI from ipalib.aci import ACI
def check_aci_parsing(source, expected): def check_aci_parsing(source, expected):
a = ACI(source) a = ACI(source)
print 'ACI was: ', a print('ACI was: ', a)
print 'Expected:', expected print('Expected:', expected)
assert str(ACI(source)) == expected assert str(ACI(source)) == expected
def test_aci_parsing_1(): def test_aci_parsing_1():
@@ -76,7 +77,7 @@ def make_test_aci():
def test_aci_equality(): def test_aci_equality():
a = make_test_aci() a = make_test_aci()
print a print(a)
b = ACI() b = ACI()
b.name ="foo" b.name ="foo"
@@ -85,7 +86,7 @@ def test_aci_equality():
b.set_bindrule_operator("=") b.set_bindrule_operator("=")
b.set_bindrule_expression("\"ldap:///cn=foo,cn=groups,cn=accounts,dc=example,dc=com\"") b.set_bindrule_expression("\"ldap:///cn=foo,cn=groups,cn=accounts,dc=example,dc=com\"")
b.permissions = ['add','read','write'] b.permissions = ['add','read','write']
print b print(b)
assert a.isequal(b) assert a.isequal(b)
assert a == b assert a == b
@@ -94,8 +95,8 @@ def test_aci_equality():
def check_aci_inequality(b): def check_aci_inequality(b):
a = make_test_aci() a = make_test_aci()
print a print(a)
print b print(b)
assert not a.isequal(b) assert not a.isequal(b)
assert not a == b assert not a == b

View File

@@ -20,6 +20,7 @@
""" """
Test the `ipalib.backend` module. Test the `ipalib.backend` module.
""" """
from __future__ import print_function
# FIXME: Pylint errors # FIXME: Pylint errors
# pylint: disable=no-member # pylint: disable=no-member
@@ -223,11 +224,11 @@ class test_Executioner(ClassChecker):
# Test that CommandError is raised: # Test that CommandError is raised:
conn = Connection('The connection.', Disconnect('someconn')) conn = Connection('The connection.', Disconnect('someconn'))
context.someconn = conn context.someconn = conn
print str(list(context.__dict__)) print(str(list(context.__dict__)))
e = raises(errors.CommandError, o.execute, 'nope') e = raises(errors.CommandError, o.execute, 'nope')
assert e.name == 'nope' assert e.name == 'nope'
assert conn.disconnect.called is True # Make sure destroy_context() was called assert conn.disconnect.called is True # Make sure destroy_context() was called
print str(list(context.__dict__)) print(str(list(context.__dict__)))
assert list(context.__dict__) == [] assert list(context.__dict__) == []
# Test with echo command: # Test with echo command:
@@ -239,10 +240,10 @@ class test_Executioner(ClassChecker):
conn = Connection('The connection.', Disconnect('someconn')) conn = Connection('The connection.', Disconnect('someconn'))
context.someconn = conn context.someconn = conn
print o.execute('echo', arg1, arg2, **options) print(o.execute('echo', arg1, arg2, **options))
print dict( print(dict(
result=(arg1, arg2, options) result=(arg1, arg2, options)
) ))
assert o.execute('echo', arg1, arg2, **options) == dict( assert o.execute('echo', arg1, arg2, **options) == dict(
result=(arg1, arg2, options) result=(arg1, arg2, options)
) )

View File

@@ -20,6 +20,7 @@
""" """
Test the `ipalib.rpc` module. Test the `ipalib.rpc` module.
""" """
from __future__ import print_function
from xmlrpclib import Binary, Fault, dumps, loads from xmlrpclib import Binary, Fault, dumps, loads
@@ -275,7 +276,7 @@ class test_xml_introspection(object):
try: try:
result = api.Backend.xmlclient.conn.system.listMethods('foo') result = api.Backend.xmlclient.conn.system.listMethods('foo')
except Fault as f: except Fault as f:
print f print(f)
assert f.faultCode == 3003 assert f.faultCode == 3003
assert f.faultString == ( assert f.faultString == (
"command 'system.listMethods' takes no arguments") "command 'system.listMethods' takes no arguments")
@@ -295,7 +296,7 @@ class test_xml_introspection(object):
try: try:
result = api.Backend.xmlclient.conn.system.methodSignature() result = api.Backend.xmlclient.conn.system.methodSignature()
except Fault as f: except Fault as f:
print f print(f)
assert f.faultCode == 3007 assert f.faultCode == 3007
assert f.faultString == "'method name' is required" assert f.faultString == "'method name' is required"
else: else:
@@ -305,7 +306,7 @@ class test_xml_introspection(object):
try: try:
result = api.Backend.xmlclient.conn.system.methodSignature('a', 'b') result = api.Backend.xmlclient.conn.system.methodSignature('a', 'b')
except Fault as f: except Fault as f:
print f print(f)
assert f.faultCode == 3004 assert f.faultCode == 3004
assert f.faultString == ( assert f.faultString == (
"command 'system.methodSignature' takes at most 1 argument") "command 'system.methodSignature' takes at most 1 argument")
@@ -316,7 +317,7 @@ class test_xml_introspection(object):
try: try:
result = api.Backend.xmlclient.conn.system.methodHelp() result = api.Backend.xmlclient.conn.system.methodHelp()
except Fault as f: except Fault as f:
print f print(f)
assert f.faultCode == 3007 assert f.faultCode == 3007
assert f.faultString == "'method name' is required" assert f.faultString == "'method name' is required"
else: else:
@@ -326,7 +327,7 @@ class test_xml_introspection(object):
try: try:
result = api.Backend.xmlclient.conn.system.methodHelp('a', 'b') result = api.Backend.xmlclient.conn.system.methodHelp('a', 'b')
except Fault as f: except Fault as f:
print f print(f)
assert f.faultCode == 3004 assert f.faultCode == 3004
assert f.faultString == ( assert f.faultString == (
"command 'system.methodHelp' takes at most 1 argument") "command 'system.methodHelp' takes at most 1 argument")

View File

@@ -20,6 +20,7 @@
""" """
Test the `ipalib.text` module. Test the `ipalib.text` module.
""" """
from __future__ import print_function
import os import os
import shutil import shutil
@@ -93,7 +94,7 @@ class test_TestLang(object):
shutil.rmtree(self.tmp_dir) shutil.rmtree(self.tmp_dir)
def test_test_lang(self): def test_test_lang(self):
print "test_test_lang" print("test_test_lang")
# The test installs the test message catalog under the xh_ZA # The test installs the test message catalog under the xh_ZA
# (e.g. Zambia Xhosa) language by default. It would be nice to # (e.g. Zambia Xhosa) language by default. It would be nice to
# use a dummy language not associated with any real language, # use a dummy language not associated with any real language,

View File

@@ -22,6 +22,7 @@ Base class for UI integration tests.
Contains browser driver and common tasks. Contains browser driver and common tasks.
""" """
from __future__ import print_function
import nose import nose
from datetime import datetime from datetime import datetime
@@ -934,7 +935,7 @@ class UI_driver(object):
checkbox = self.find(input_s, By.CSS_SELECTOR, parent, strict=True) checkbox = self.find(input_s, By.CSS_SELECTOR, parent, strict=True)
checkbox_id = checkbox.get_attribute('id') checkbox_id = checkbox.get_attribute('id')
label_s = s + " tbody td label[for='%s']" % checkbox_id label_s = s + " tbody td label[for='%s']" % checkbox_id
print label_s print(label_s)
label = self.find(label_s, By.CSS_SELECTOR, parent, strict=True) label = self.find(label_s, By.CSS_SELECTOR, parent, strict=True)
try: try:
ActionChains(self.driver).move_to_element(label).click().perform() ActionChains(self.driver).move_to_element(label).click().perform()

View File

@@ -5,6 +5,7 @@
""" """
Implements a base class to track changes to an LDAP object. Implements a base class to track changes to an LDAP object.
""" """
from __future__ import print_function
import functools import functools
@@ -126,11 +127,11 @@ class Tracker(object):
try: try:
result = cmd(*args, **options) result = cmd(*args, **options)
except Exception as e: except Exception as e:
print 'Ran command: %s(%s): %s: %s' % (cmd, args_repr, print('Ran command: %s(%s): %s: %s' % (cmd, args_repr,
type(e).__name__, e) type(e).__name__, e))
raise raise
else: else:
print 'Ran command: %s(%s): OK' % (cmd, args_repr) print('Ran command: %s(%s): OK' % (cmd, args_repr))
return result return result
def make_command(self, name, *args, **options): def make_command(self, name, *args, **options):

View File

@@ -22,6 +22,7 @@
""" """
Test the `ipalib.plugins.host` module. Test the `ipalib.plugins.host` module.
""" """
from __future__ import print_function
import os import os
import tempfile import tempfile
@@ -689,7 +690,7 @@ class TestHostFalsePwdChange(XMLRPC_test):
except ipautil.CalledProcessError as e: except ipautil.CalledProcessError as e:
# join operation may fail on 'adding key into keytab', but # join operation may fail on 'adding key into keytab', but
# the keytab is not necessary for further tests # the keytab is not necessary for further tests
print e print(e)
host.attrs['has_keytab'] = True host.attrs['has_keytab'] = True
host.attrs['has_password'] = False host.attrs['has_password'] = False

View File

@@ -21,6 +21,7 @@
""" """
Test the `ipalib/plugins/permission.py` module. Test the `ipalib/plugins/permission.py` module.
""" """
from __future__ import print_function
import os import os
@@ -2847,7 +2848,7 @@ def check_legacy_results(results):
"""Check that the expected number of legacy permissions are in $SUFFIX""" """Check that the expected number of legacy permissions are in $SUFFIX"""
legacy_permissions = [p for p in results legacy_permissions = [p for p in results
if not p.get('ipapermissiontype')] if not p.get('ipapermissiontype')]
print legacy_permissions print(legacy_permissions)
assert len(legacy_permissions) == 8, len(legacy_permissions) assert len(legacy_permissions) == 8, len(legacy_permissions)
return True return True

View File

@@ -20,6 +20,7 @@
""" """
Base class for all XML-RPC tests Base class for all XML-RPC tests
""" """
from __future__ import print_function
import datetime import datetime
@@ -274,7 +275,7 @@ class Declarative(XMLRPC_test):
@classmethod @classmethod
def cleanup(cls, command): def cleanup(cls, command):
(cmd, args, options) = command (cmd, args, options) = command
print 'Cleanup:', cmd, args, options print('Cleanup:', cmd, args, options)
if cmd not in api.Command: if cmd not in api.Command:
raise nose.SkipTest( raise nose.SkipTest(
'cleanup command %r not in api.Command' % cmd 'cleanup command %r not in api.Command' % cmd
@@ -282,7 +283,7 @@ class Declarative(XMLRPC_test):
try: try:
api.Command[cmd](*args, **options) api.Command[cmd](*args, **options)
except (errors.NotFound, errors.EmptyModlist) as e: except (errors.NotFound, errors.EmptyModlist) as e:
print e print(e)
pass pass
def test_command(self, index, declarative_test_definition): def test_command(self, index, declarative_test_definition):

View File

@@ -20,6 +20,8 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import os import os
import sys import sys
from optparse import OptionParser from optparse import OptionParser
@@ -33,7 +35,7 @@ try:
from astroid import Class, Instance, Module, InferenceError, Function from astroid import Class, Instance, Module, InferenceError, Function
from pylint.reporters.text import TextReporter from pylint.reporters.text import TextReporter
except ImportError: except ImportError:
print >> sys.stderr, "To use {0}, please install pylint.".format(sys.argv[0]) print("To use {0}, please install pylint.".format(sys.argv[0]), file=sys.stderr)
sys.exit(32) sys.exit(32)
# File names to ignore when searching for python source files # File names to ignore when searching for python source files
@@ -249,25 +251,25 @@ def main():
linter.check(files) linter.check(files)
if linter.msg_status != 0: if linter.msg_status != 0:
print >> sys.stderr, """ print("""
=============================================================================== ===============================================================================
Errors were found during the static code check. Errors were found during the static code check.
""" """, file=sys.stderr)
if len(linter.missing) > 0: if len(linter.missing) > 0:
print >> sys.stderr, "There are some missing imports:" print("There are some missing imports:", file=sys.stderr)
for mod in sorted(linter.missing): for mod in sorted(linter.missing):
print >> sys.stderr, " " + mod print(" " + mod, file=sys.stderr)
print >> sys.stderr, """ print("""
Please make sure all of the required and optional (python-gssapi, python-rhsm) Please make sure all of the required and optional (python-gssapi, python-rhsm)
python packages are installed. python packages are installed.
""" """, file=sys.stderr)
print >> sys.stderr, """\ print("""\
If you are certain that any of the reported errors are false positives, please If you are certain that any of the reported errors are false positives, please
mark them in the source code according to the pylint documentation. mark them in the source code according to the pylint documentation.
=============================================================================== ===============================================================================
""" """, file=sys.stderr)
if options.fail: if options.fail:
return linter.msg_status return linter.msg_status

10
makeaci
View File

@@ -24,6 +24,8 @@
# to ensure that changes aren't made lightly. # to ensure that changes aren't made lightly.
# Can either regenerate ACI.txt, or validate against it. # Can either regenerate ACI.txt, or validate against it.
from __future__ import print_function
import sys import sys
import difflib import difflib
from argparse import ArgumentParser from argparse import ArgumentParser
@@ -112,10 +114,10 @@ def main(options):
tofile='new result', tofile='new result',
)) ))
for line in diff: for line in diff:
print line, print(line, end=' ')
print>>sys.stderr print(file=sys.stderr)
print>>sys.stderr, 'Managed permission ACI validation failed.' print('Managed permission ACI validation failed.', file=sys.stderr)
print>>sys.stderr, 'Re-check permission changes and run `makeaci`.' print('Re-check permission changes and run `makeaci`.', file=sys.stderr)
exit('%s validation failed' % options.filename) exit('%s validation failed' % options.filename)
else: else:
with open(options.filename, 'w') as file: with open(options.filename, 'w') as file:

94
makeapi
View File

@@ -23,6 +23,8 @@
# Test the API against a known-good API to ensure that changes aren't made # Test the API against a known-good API to ensure that changes aren't made
# lightly. # lightly.
from __future__ import print_function
import sys import sys
import os import os
import re import re
@@ -153,21 +155,21 @@ def validate_doc():
if not is_i18n(topic[1]): if not is_i18n(topic[1]):
src_file = inspect.getsourcefile(cmd_class) src_file = inspect.getsourcefile(cmd_class)
n_missing_mod_i18n += 1 n_missing_mod_i18n += 1
print "%s: topic in module \"%s\" is not internationalized" % \ print("%s: topic in module \"%s\" is not internationalized" % \
(src_file, cmd.module) (src_file, cmd.module))
# Does the module have documentation? # Does the module have documentation?
if mod.__doc__ is None: if mod.__doc__ is None:
src_file = inspect.getsourcefile(mod) src_file = inspect.getsourcefile(mod)
n_missing_mod_doc += 1 n_missing_mod_doc += 1
print "%s: module \"%s\" has no doc" % \ print("%s: module \"%s\" has no doc" % \
(src_file, cmd.module) (src_file, cmd.module))
# Yes the module has doc, but is it internationalized? # Yes the module has doc, but is it internationalized?
elif not is_i18n(mod.__doc__): elif not is_i18n(mod.__doc__):
src_file = inspect.getsourcefile(cmd_class) src_file = inspect.getsourcefile(cmd_class)
n_missing_mod_i18n += 1 n_missing_mod_i18n += 1
print "%s: module \"%s\" doc is not internationalized" % \ print("%s: module \"%s\" doc is not internationalized" % \
(src_file, cmd.module) (src_file, cmd.module))
# Increment the count of how many commands in this module # Increment the count of how many commands in this module
modules[cmd.module] = modules[cmd.module] + 1 modules[cmd.module] = modules[cmd.module] + 1
@@ -177,24 +179,24 @@ def validate_doc():
src_file = inspect.getsourcefile(cmd_class) src_file = inspect.getsourcefile(cmd_class)
line_num = inspect.getsourcelines(cmd_class)[1] line_num = inspect.getsourcelines(cmd_class)[1]
n_missing_cmd_doc += 1 n_missing_cmd_doc += 1
print "%s:%d command \"%s\" has no doc" % (src_file, line_num, cmd.name) print("%s:%d command \"%s\" has no doc" % (src_file, line_num, cmd.name))
# Yes the command has doc, but is it internationalized? # Yes the command has doc, but is it internationalized?
elif not is_i18n(cmd.__doc__): elif not is_i18n(cmd.__doc__):
src_file = inspect.getsourcefile(cmd_class) src_file = inspect.getsourcefile(cmd_class)
line_num = inspect.getsourcelines(cmd_class)[1] line_num = inspect.getsourcelines(cmd_class)[1]
n_missing_cmd_i18n += 1 n_missing_cmd_i18n += 1
print "%s:%d command \"%s\" doc is not internationalized" % (src_file, line_num, cmd.name) print("%s:%d command \"%s\" doc is not internationalized" % (src_file, line_num, cmd.name))
# If any errors, emit summary information and adjust return value # If any errors, emit summary information and adjust return value
if n_missing_cmd_doc > 0 or n_missing_cmd_i18n > 0: if n_missing_cmd_doc > 0 or n_missing_cmd_i18n > 0:
rval = API_DOC_ERROR rval = API_DOC_ERROR
print "%d commands without doc, %d commands whose doc is not i18n" % \ print("%d commands without doc, %d commands whose doc is not i18n" % \
(n_missing_cmd_doc, n_missing_cmd_i18n) (n_missing_cmd_doc, n_missing_cmd_i18n))
if n_missing_mod_doc > 0 or n_missing_mod_i18n > 0: if n_missing_mod_doc > 0 or n_missing_mod_i18n > 0:
rval = API_DOC_ERROR rval = API_DOC_ERROR
print "%d modules without doc, %d modules whose doc is not i18n" % \ print("%d modules without doc, %d modules whose doc is not i18n" % \
(n_missing_mod_doc, n_missing_mod_i18n) (n_missing_mod_doc, n_missing_mod_i18n))
return rval return rval
@@ -229,7 +231,7 @@ def find_name(line):
if m: if m:
name = m.group(1) name = m.group(1)
else: else:
print "Couldn't find name in: %s" % line print("Couldn't find name in: %s" % line)
name = '' name = ''
return name return name
@@ -239,33 +241,33 @@ def _finalize_command_validation(cmd, found_args, expected_args,
passed = True passed = True
# Check the args of the previous command. # Check the args of the previous command.
if len(found_args) != expected_args: if len(found_args) != expected_args:
print 'Argument count in %s of %d doesn\'t match expected: %d' % ( print('Argument count in %s of %d doesn\'t match expected: %d' % (
cmd.name, len(found_args), expected_args) cmd.name, len(found_args), expected_args))
passed = False passed = False
if len(found_options) != expected_options: if len(found_options) != expected_options:
print 'Options count in %s of %d doesn\'t match expected: %d' % ( print('Options count in %s of %d doesn\'t match expected: %d' % (
cmd.name, len(found_options), expected_options) cmd.name, len(found_options), expected_options))
passed = False passed = False
if len(found_output) != expected_output: if len(found_output) != expected_output:
print 'Output count in %s of %d doesn\'t match expected: %d' % ( print('Output count in %s of %d doesn\'t match expected: %d' % (
cmd.name, len(found_output), expected_output) cmd.name, len(found_output), expected_output))
passed = False passed = False
# Check if there is not a new arg/opt/output in previous command # Check if there is not a new arg/opt/output in previous command
for a in cmd.args(): for a in cmd.args():
if a.param_spec not in found_args: if a.param_spec not in found_args:
print 'Argument %s of command %s in ipalib, not in API file:\n%s' % ( print('Argument %s of command %s in ipalib, not in API file:\n%s' % (
a.param_spec, cmd.name, param_repr(a)) a.param_spec, cmd.name, param_repr(a)))
passed = False passed = False
for o in cmd.options(): for o in cmd.options():
if o.param_spec not in found_options: if o.param_spec not in found_options:
print 'Option %s of command %s in ipalib, not in API file:\n%s' % ( print('Option %s of command %s in ipalib, not in API file:\n%s' % (
o.param_spec, cmd.name, param_repr(o)) o.param_spec, cmd.name, param_repr(o)))
passed = False passed = False
for o in cmd.output(): for o in cmd.output():
if o.name not in found_output: if o.name not in found_output:
print 'Output %s of command %s in ipalib, not in API file:\n%s' % ( print('Output %s of command %s in ipalib, not in API file:\n%s' % (
o.name, cmd.name, param_repr(o)) o.name, cmd.name, param_repr(o)))
passed = False passed = False
return passed return passed
@@ -305,7 +307,7 @@ def validate_api():
(arg, name) = line.split(': ', 1) (arg, name) = line.split(': ', 1)
if name not in api.Command: if name not in api.Command:
print "Command %s in API file, not in ipalib" % name print("Command %s in API file, not in ipalib" % name)
rval |= API_FILE_DIFFERENCE rval |= API_FILE_DIFFERENCE
cmd = None cmd = None
else: else:
@@ -330,14 +332,14 @@ def validate_api():
else: else:
if a.name == arg: if a.name == arg:
found = True found = True
print 'Arg in %s doesn\'t match.\nGot %s\nExpected %s' % ( print('Arg in %s doesn\'t match.\nGot %s\nExpected %s' % (
name, param_repr(a), line) name, param_repr(a), line))
rval |= API_FILE_DIFFERENCE rval |= API_FILE_DIFFERENCE
if found: if found:
found_args.append(arg) found_args.append(arg)
else: else:
arg = find_name(line) arg = find_name(line)
print "Argument '%s' in command '%s' in API file not found" % (arg, name) print("Argument '%s' in command '%s' in API file not found" % (arg, name))
rval |= API_FILE_DIFFERENCE rval |= API_FILE_DIFFERENCE
if line.startswith('option:') and cmd: if line.startswith('option:') and cmd:
line = line.replace('option: ', '') line = line.replace('option: ', '')
@@ -349,13 +351,13 @@ def validate_api():
else: else:
if o.name == option: if o.name == option:
found = True found = True
print 'Option in %s doesn\'t match. Got %s Expected %s' % (name, o, line) print('Option in %s doesn\'t match. Got %s Expected %s' % (name, o, line))
rval |= API_FILE_DIFFERENCE rval |= API_FILE_DIFFERENCE
if found: if found:
found_options.append(option) found_options.append(option)
else: else:
option = find_name(line) option = find_name(line)
print "Option '%s' in command '%s' in API file not found" % (option, name) print("Option '%s' in command '%s' in API file not found" % (option, name))
rval |= API_FILE_DIFFERENCE rval |= API_FILE_DIFFERENCE
if line.startswith('output:') and cmd: if line.startswith('output:') and cmd:
line = line.replace('output: ', '') line = line.replace('output: ', '')
@@ -367,13 +369,13 @@ def validate_api():
else: else:
if o.name == output: if o.name == output:
found = True found = True
print 'Output in %s doesn\'t match. Got %s Expected %s' % (name, o, line) print('Output in %s doesn\'t match. Got %s Expected %s' % (name, o, line))
rval |= API_FILE_DIFFERENCE rval |= API_FILE_DIFFERENCE
if found: if found:
found_output.append(output) found_output.append(output)
else: else:
output = find_name(line) output = find_name(line)
print "Option '%s' in command '%s' in API file not found" % (output, name) print("Option '%s' in command '%s' in API file not found" % (output, name))
rval |= API_FILE_DIFFERENCE rval |= API_FILE_DIFFERENCE
if line.startswith('capability:'): if line.startswith('capability:'):
cap, version = line.replace('capability: ', '').split(' ', 1) cap, version = line.replace('capability: ', '').split(' ', 1)
@@ -381,13 +383,13 @@ def validate_api():
try: try:
expected_version = str(capabilities[cap]) expected_version = str(capabilities[cap])
except KeyError: except KeyError:
print "Capability '%s' in API file not found" % cap print("Capability '%s' in API file not found" % cap)
rval |= API_FILE_DIFFERENCE rval |= API_FILE_DIFFERENCE
else: else:
if version != expected_version: if version != expected_version:
print ( print((
"Capability '%s' in API file doesn't match. Got %s, " "Capability '%s' in API file doesn't match. Got %s, "
"expected %s.") % (cap, version, expected_version) "expected %s.") % (cap, version, expected_version))
rval |= API_FILE_DIFFERENCE rval |= API_FILE_DIFFERENCE
if cmd: if cmd:
@@ -399,12 +401,12 @@ def validate_api():
# Now look for new commands not in the current API # Now look for new commands not in the current API
for cmd in api.Command(): for cmd in api.Command():
if cmd.name not in existing_cmds: if cmd.name not in existing_cmds:
print "Command %s in ipalib, not in API" % cmd.name print("Command %s in ipalib, not in API" % cmd.name)
rval |= API_NEW_COMMAND rval |= API_NEW_COMMAND
for cap in capabilities: for cap in capabilities:
if cap not in existing_capabilities: if cap not in existing_capabilities:
print "Capability %s in ipalib, not in API" % cap print("Capability %s in ipalib, not in API" % cap)
rval |= API_FILE_DIFFERENCE rval |= API_FILE_DIFFERENCE
return rval return rval
@@ -432,25 +434,25 @@ def main():
if options.validate: if options.validate:
if not os.path.exists(API_FILE): if not os.path.exists(API_FILE):
print 'No %s to validate' % API_FILE print('No %s to validate' % API_FILE)
rval |= API_NO_FILE rval |= API_NO_FILE
else: else:
rval |= validate_api() rval |= validate_api()
else: else:
print "Writing API to API.txt" print("Writing API to API.txt")
rval |= make_api() rval |= make_api()
if rval & API_FILE_DIFFERENCE: if rval & API_FILE_DIFFERENCE:
print '' print('')
print 'There are one or more changes to the API.\nEither undo the API changes or update API.txt and increment the major version in VERSION.' print('There are one or more changes to the API.\nEither undo the API changes or update API.txt and increment the major version in VERSION.')
if rval & API_NEW_COMMAND: if rval & API_NEW_COMMAND:
print '' print('')
print 'There are one or more new commands defined.\nUpdate API.txt and increment the minor version in VERSION.' print('There are one or more new commands defined.\nUpdate API.txt and increment the minor version in VERSION.')
if rval & API_DOC_ERROR: if rval & API_DOC_ERROR:
print '' print('')
print 'There are one or more documentation problems.\nYou must fix these before preceeding' print('There are one or more documentation problems.\nYou must fix these before preceeding')
return rval return rval