#!/usr/bin/env python """ Q&A based tool for setting up cobbler.conf and modules.conf Copyright 2008, Red Hat, Inc Partha Aji Michael DeHaan This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA """ import cobbler.yaml as yaml import optparse import Cheetah.Template as Template import socket import shutil import os.path import exceptions import sys import os import subprocess # ========================================================= def execute(command, shell=False, ignore_rc=False): if subprocess.call(command, shell = shell) != 0: if not ignore_rc: sys.stderr.write("\n -- ERROR: command '%s' failed. Setup aborted.\n" % command) sys.exit(1); # ========================================================= class AnswerException(exceptions.Exception): """ Custom exceptions class so we only catch exceptions that we know are input related. """ pass # ========================================================= def help_ask(caption, validators=[], transformers =[], default = None, required=True, max_len = None): """ Helper method to gather input from the console. This method has a bunch of useful addons like validators and transformers. Validators are a chain of objects that validate the input and raise an exception in the case of bad data, while transformers are methods that transform the input to int or decimals.. """ default_label = default and (" (default=%s)" % default) or "" label = caption + default_label +": " input = raw_input(label).strip() try: if input or not default: if required: len_check(min_len = 1)(input) if max_len: len_check(max_len = max_len)(input) for validate in validators: validate(input) else: input = default for transform in transformers: input = transform(input) except AnswerException, e: if hasattr(e, "message"): print "Invalid value: %s " % (e.message) elif len(e.args) == 1: print "Invalid value: %s " % e.args[0] else: print e return help_ask(caption, validators = validators, transformers = transformers, default = default, required = required, max_len = max_len) return input # ========================================================= def translator(transdict = {}): def translate (input,transdict = transdict): return transdict[input] return translate # ========================================================= def yes_no_translator(): return translator({ "y": 1, "Y" : 1, "n" : 0, "N" : 0}) # ========================================================= def len_check(min_len = None, max_len = None, exact_len = None): """ Validator method to ensure the input has a max_len, a min_len o an exact len each of these options are used in different instances, for example if we want the state name = 2 characters we would have exact_len = 2... """ def exact(input, length = exact_len): if len(input) != length: raise AnswerException ('Input needs to be exactly %d characters' % length) def min_check(input, length = min_len): if len(input) < length: raise AnswerException('Input needs to be atleast %d characters' % length) def max_check(input, length = max_len): if len(input) > length: raise AnswerException('Input needs to be atmost %d characters' % length) def check_both(input, min_len = min_len, max_len = max_len): if not min_len <= len(input) <= max_len: raise AnswerException('Input needs to be atleast %d and atmost %d characters' % (min_len, max_len)) if exact_len: return exact if min_len and max_len: return check_both if min_len: return min_check if max_len: return max_check # ========================================================= def enum_check(enums): """ Userful validator to ensure that the user's input conforms to a list of enum values. This is particularly useful for Y/N inputs.. """ def check(input, enums = enums): if input not in enums: raise AnswerException('Input needs to be one of (%s)' % '/'.join(enums)) return check # ========================================================= def yes_no_check(): return enum_check(["y","n"]) # ========================================================= def yes_no_params(default = 'y'): return { "default" : default, "validators" : [yes_no_check()], "transformers" : [yes_no_translator()] } # ========================================================= def translation_params(default, translation): return { "default" : default, "validators" : [enum_check(translation.keys())], "transformers" : [translator(translation)] } # ========================================================= def setup_server(answers): hostname = socket.gethostbyname(socket.gethostname()) parameters = { "default" : hostname } ask(answers, 'server', 'What is the resolvable address/ip of this server [leave blank for autodiscover] ?', parameters ) # ========================================================= def setup_dhcp(answers): ask(answers, 'enable_dhcp', "Do you want to enable DHCP management [y/n] ?", yes_no_params()) if answers['enable_dhcp']: answers['next_server'] = answers['server'] else: answers['next_server'] = '127.0.0.1' if answers['enable_dhcp']: # DHCP management is either ISC or dnsmasq translation = { "isc" : "manage_isc", "dnsmasq" : "manage_dnsmasq" } ask( answers, 'dhcp_module', "Which DNS module do you want to use [isc/dnsmasq] ?", translation_params("isc", translation) ) else: answers['dhcp_module'] = "manage_isc" # ========================================================= def setup_dns(answers): # if the user already is using dnsmasq for DHCP, they must use dnsmasq for DNS # if they are not, they get the choice of BIND or no module if answers["enable_dhcp"] and answers["dhcp_module"] == "dnsmasq": answers["enable_dns"] = 1 answers["dns_module"] = "manage_dnsmasq" else: ask(answers, 'enable_dns', "Do you want to enable DNS management with BIND [y/n] ?", yes_no_params() ) if answers["enable_dns"]: answers["dns_module"] = "manage_bind" # ========================================================= def setup_pxe(answers): ask( answers, 'pxe_once', "Enable PXE boot loop prevention feature [y/n] ?", yes_no_params() ) # ========================================================= def setup_mirrors(answers): ask( answers, 'yum_post_install_mirror', "Make cobbler managed yum repos available to installed systems via yum.repos.d [y/n] ?", yes_no_params() ) # ========================================================= def setup_remote_config(answers): ask (answers, "enable_remote_access", "Allow cobbler to be managed by the web and other applications [y/n] ?", yes_no_params() ) if answers['enable_remote_access']: translation = { "testing" : "authn_testing", "passthru" : "authn_passthru", "denyall" : "authn_denyall", "ldap" : "authn_ldap", "configfile" : "authn_configfile", "spacewalk" :"authn_spacewalk" } ask (answers, "authn_module", "Which authentication module do you want to use [%s] ?" % "/".join(translation.keys()), translation_params("denyall", translation)) if answers['authn_module'] == 'authn_configfile': print "* Updating cobbler user's password in user.digest file" execute('htdigest -c users.digest Cobbler cobbler',shell=False) print "* users can run 'htdigest /etc/users.digest Cobbler $username' later to add more users & change cobbler password" translation = { "allowall" : "authz_allowall", "ownership" : "authz_ownership", "configfile" : "authz_configfile" } ask (answers, "authz_module", "Which authorization module do you want to use [%s] ?" % "/".join(translation.keys()), translation_params("allowall", translation)) else: answers['authn_module'] = "authn_denyall" answers['authz_module'] = "authz_allowall" # ========================================================= def setup(parser): parser.add_option("-a", "--answers-file", dest="file", help="pass in a answers file in yaml format") # ========================================================= def ask(answers, key, question, params=None): # code to prevent re-asking the question? #if key in answers: # return answers[key] if params is None: params = {} caption = question answer = help_ask( question, validators = params.get("validators",[]), transformers = params.get("transformers",[]), default = params.get("default",None), required = params.get("required",True), max_len = params.get("max_len",None) ) answers[key] = answer print "\n" # leave some nice whitespace for the humans return answer # ========================================================= def templatify(template, answers, output): t = Template.Template(file=template, searchList=answers) open(output,"w").write(t.respond()) # ========================================================= def copy_settings(): if os.path.exists("users.digest"): shutil.copy("/etc/cobbler/users.digest", "/etc/cobbler/users.digest.old") shutil.copy("/etc/cobbler/settings", "/etc/cobbler/settings.old") shutil.copy("/etc/cobbler/modules.conf", "/etc/cobbler/modules.conf.old") # ========================================================= def main(): try: import readline readline.parse_and_bind("tab: complete") except: pass parser = optparse.OptionParser() setup(parser) (options, args) = parser.parse_args() answers = {} # options.file is the name of the answers file.. if options.file: data = yaml.loadFile(parser.file).next() answers.update(data) print "" print "**********************************************" print "Setting up the Cobbler provisioning server." print "http://fedorahosted.org/cobbler" execute("rpm -q cobbler", shell = True) print "" print "if you have already configured cobbler, Ctrl+C now." print "This script will modify /etc/cobbler/settings" print "and /etc/cobbler/modules.conf." print "Backups are saved as /etc/cobbler/*.backup" print "**********************************************" print "" setup_server(answers) setup_dhcp(answers) setup_dns(answers) setup_remote_config(answers) setup_pxe(answers) setup_mirrors(answers) # copy settings /before/ overwriting them copy_settings() defaults = yaml.loadFile("/usr/share/cobbler/installer_templates/defaults").next() for key in defaults.keys(): if key not in answers: answers[key] = defaults[key] templatify("/usr/share/cobbler/installer_templates/settings.template",answers,"/etc/cobbler/settings") templatify("/usr/share/cobbler/installer_templates/modules.conf.template",answers,"/etc/cobbler/modules.conf") # FIXME: missing code to ensure TFTP is enabled # FIXME: missing code to ensure cobblerd, httpd, xinetd is chkconfig on print "" print "***********************************************" print "Restarting required services prior to running" print "diagnostics on install server configuration" print "***********************************************" print "" execute("/sbin/service cobblerd restart", shell=True) execute("/sbin/service httpd restart", shell=True) print "" print "************************************************************" print "The following information may represent outstanding problems" print "with your install server configuration that probably should " print "be addressed. These may be reviewed at any time by running" print "'cobbler check'. Any other runtime problems may be logged" print "to the Apache error log or /var/log/cobbler.log" print "***********************************************" print "" execute("cobbler check", shell=True, ignore_rc=True) print "" print "***********************************************" print "Install server installation complete. Review" print "messages above and correct any problems that are" print "listed." print "***********************************************" print "" # ========================================================= if __name__=="__main__": if not os.getuid() == 0: sys.stderr.write(" -- WARNING: don't you want to run this as root?\n") main()