summaryrefslogtreecommitdiffstats
path: root/scripts/cobbler-setup
blob: 926fec37eb605ae13d671871e3f2100527f93ca2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
#!/usr/bin/env python

"""
Q&A based tool for setting up cobbler.conf and modules.conf

Copyright 2008, Red Hat, Inc
Partha Aji <paji@redhat.com>
Michael DeHaan <mdehaan@redhat.com>

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()