summaryrefslogtreecommitdiff
path: root/pykolab/setup/services.py
blob: ae4eecdde666582bd6694c1a19309fe22523141b (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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
# -*- coding: utf-8 -*-
# Copyright 2010-2013 Kolab Systems AG (http://www.kolabsys.com)
# Copyright 2013, 2014 Paul Boddie <paul@boddie.org.uk>
#
# Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen a kolabsys.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 3 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, see <http://www.gnu.org/licenses/>.
#

from augeas import Augeas
from Cheetah.Template import Template
from subprocess import call, Popen, PIPE
from os.path import isdir, isfile, abspath, join, exists
from urllib import splitport
from urlparse import urlsplit

from pykolab import utils
from pykolab.translate import _

import pykolab
import sys
import os

conf = pykolab.getConf()

# Commands with service suffix usage and argument ordering "format".

commands_and_options = {
    '/bin/systemctl'        : (True,  ('cmd', 'operation', 'service')),
    '/sbin/service'         : (False, ('cmd', 'service', 'operation')),
    '/usr/sbin/service'     : (False, ('cmd', 'service', 'operation')),
    '/sbin/chkconfig'       : (False, ('cmd', 'service', 'operation')),
    '/usr/sbin/update-rc.d' : (False, ('cmd', 'service', 'operation')),
    }

# Configuration options corresponding to false and true values.

configuration_options = {
    '/bin/systemctl'        : ('disable', 'enable'),
    '/sbin/chkconfig'       : ('off', 'on'),
    '/usr/sbin/update-rc.d' : ('disable', 'defaults'),
    }

configuration_commands = configuration_options.keys()
control_commands = '/bin/systemctl', '/sbin/service', '/usr/sbin/service'

configuration_command_details = None
control_command_details = None

def get_command_options(commands):
    """
        Check for the presence of the given commands, returning the first one
        found along with option details.
    """
    for name in commands:
        if isfile(name):
            return name, commands_and_options[name]
    return None, None

def get_control_command_details():
    """
        Obtain and cache the control command details.
    """
    global control_command_details
    if control_command_details is None:
        control_command_details = get_command_options(control_commands)
    return control_command_details

def get_configuration_command_details():
    """
        Obtain and cache the configuration command details.
    """
    global configuration_command_details
    if configuration_command_details is None:
        configuration_command_details = get_command_options(configuration_commands)
    return configuration_command_details

def apply_command(name, suffix, format, service_name, operation):
    """
        Call the given command, adding the applicable service name suffix to the
        service name argument, using the "format" to determine the argument
        ordering, and employing the service name and operation specified.
    """
    cmd = []
    for arg in format:
        if arg == "cmd":
            cmd.append(name)
        elif arg == "operation":
            cmd.append(operation)
        elif arg == "service":
            cmd.append('%s%s' % (service_name, suffix))
    call(cmd, stdout=PIPE, stderr=PIPE)

def control_service(service_name, operation, suffix=".service"):
    """
        Perform a service control operation on the service with the given name.
        Where a service command employs a suffix on the service name, any
        provided suffix will be added.
    """
    name, (use_suffix, format) = get_control_command_details()
    if not name:
        return False
    apply_command(name, use_suffix and suffix or "", format, service_name, operation)
    return True

def configure_service(service_name, operation, suffix=".service"):
    """
        Perform a service configuration operation on the service with the given
        name. Where a service command employs a suffix on the service name, any
        provided suffix will be added.
    """
    name, (use_suffix, format) = get_configuration_command_details()
    if not name:
        return False
    options = configuration_options[name]
    operation = options[operation and 1 or 0]
    apply_command(name, use_suffix and suffix or "", format, service_name, operation)
    return True

def is_debian():
    """
        Special test to deal with inconsistencies in package naming and file
        locations.
    """
    return exists("/etc/debian_version")

def find_file(name, paths):
    for path in paths:
        full_path = join(path, name)
        if isfile(full_path):
            return full_path
    return None

def find_path(paths):
    for path in paths:
        if exists(path):
            return path
    return None

def readfile(filename):
    f = open(filename)
    try:
        return f.read()
    finally:
        f.close()

def writefile(filename, s):
    f = open(filename, "w")
    try:
        f.write(s)
    finally:
        f.close()

def file_contains_data(filename, data, exact=False):
    if not exists(filename):
        return False
    s = readfile(filename)
    if exact:
        return s == data
    else:
        return s.find(data) != -1

def have_command(tokens):
    try:
        Popen(tokens, stdout=PIPE, stderr=PIPE)
    except OSError:
        return False
    else:
        return True

def get_host_from_url(url):
    return splitport(urlsplit(url)[1])[0]

def get_host_and_port_from_url(url):
    host, port = splitport(urlsplit(url)[1])
    return "%s:%s" % (host, port or "80")

# Message and input handling.

# These functions wrap the existing utils functions and provide for debconf
# usage instead of using the plain console. The principal additions to the
# existing functions involve message keys (to template definitions accessed by
# debconf, provided by Debian packages) and the messages that are displayed
# before each question.

debconf = None
db = None
db_passwords = set()

def use_debconf():
    return is_debian() and conf.use_system_config

def start_interaction(message_key):
    global db, debconf
    if use_debconf():
        try:
            import debconf
        except ImportError:
            return
        debconf.runFrontEnd()
        db = debconf.Debconf()
        db.settitle(message_key)

def ask_question(message_key, message, question=None, default="", password=False, confirm=False):
    """
        Use the given message key to retrieve a question from any
        system-supplied configuration system, otherwise using the given message
        and question to prompt the user for an answer. Where no question is
        actually given, this function just displays a message.
    """
    if db is not None:
        if password:
            db_passwords.add(message_key)
        if default:
            db.set(message_key, default)
            db.fset(message_key, "seen", False)
        try:
            db.input("high", message_key)
            db.go()
            return db.getString(message_key)
        except debconf.DebconfError:
            return not password and default or ""
    else:
        print >> sys.stderr, utils.multiline_message(message)
        if question:
            return utils.ask_question(question, default, password, confirm)
        else:
            return None

def ask_confirmation(message_key, message, question, default=True, all_inclusive_no=True):
    """
        Use the given message key to retrieve a confirmation question from any
        system-supplied configuration system, otherwise using the given message
        and question to prompt the user for an answer. Where no question is
        actually given, this function just displays a message.

        The default may be given as a boolean value with True representing "yes"
        or a positive response, and False representing "no" or a negative
        response.
    """
    if db is not None:
        if default:
            db.set(message_key, default)
            db.fset(message_key, "seen", False)
        try:
            db.input("high", message_key)
            db.go()
            return db.getBoolean(message_key)
        except debconf.DebconfError:
            return None
    else:
        print >> sys.stderr, utils.multiline_message(message)
        if question:
            return utils.ask_confirmation(question, default and "yes" or "no", all_inclusive_no)
        else:
            return None

def stop_interaction():
    if db is not None:

        # Erase password information from debconf as suggested by...
        # http://www.debian.org/doc/manuals/developers-reference/best-pkging-practices.html#s6.5.3

        for message_key in db_passwords:
            db.set(message_key, "")
        db.stop()

# MTA-related functions.

def have_postfix():
    return have_command(['postfix', 'status'])

# Certificate-related functions.

def get_certificate_path(name):
    if is_debian():
        return '/etc/ssl/certs/%s.pem' % name
    else:
        return '/etc/pki/tls/certs/%s.pem' % name

def get_private_key_path(name):
    if is_debian():
        return '/etc/ssl/private/%s.key' % name
    else:
        return '/etc/pki/tls/private/%s.pem' % name

def make_ssl_certificate(key_filename):
    for program in ['/etc/pki/tls/certs/make-dummy-cert']:
        if isfile(program):
            call([program, key_filename])
            return True
    return False

# Apache-related functions.

def get_apache_site_dir():
    if is_debian():
        return '/etc/apache2/sites-available'
    else:
        return '/etc/httpd/conf.d'

def enable_apache_site(name):
    if is_debian():
        call(['a2ensite', name])
    # NOTE: Equivalents for other systems required.

def disable_apache_site(name):
    if is_debian():
        call(['a2dissite', name])
    # NOTE: Equivalents for other systems required.

def enable_apache_module(name):
    if is_debian():
        call(['a2enmod', name])
    # NOTE: Equivalents for other systems required.

def disable_apache_module(name):
    if is_debian():
        call(['a2dismod', name])
    # NOTE: Equivalents for other systems required.

# PHP-related functions.

php_paths = ['/etc', '/etc/php5/apache2']

def get_php_path(name):
    return find_file(name, php_paths)

def get_php_ini_file():
    if conf.php_ini_path:
        if not isfile(conf.php_ini_path):
            return None
        else:
            return conf.php_ini_path
    else:
        return get_php_path("php.ini")

# Roundcube-related functions.

def get_roundcube_config():
    for dir in '/etc/roundcubemail', '/etc/roundcube':
        if isdir(dir):
            return dir
    return None

def get_roundcube_resources():
    for dir in '/usr/share/roundcubemail', '/usr/share/roundcube/':
        if isdir(dir):
            return dir
    return None

# Template-related functions.

template_paths = ['/etc/kolab/templates', '/usr/share/kolab/templates']

def get_template_path(name):
    """
        Return the full path to the template with the given name.
    """
    relative_path = abspath(join(__file__, '..', '..', '..', 'share', 'templates', name))
    return find_file(name, template_paths + [relative_path])

def instantiate_template(template_file, output_file, search_list, check_only=False):
    """
        Instantiate the template from the given file, producing the indicated
        output file. The search list provides a collection of definition
        mappings for substitutions.

        When only checking template instantiation, the output file is not
        produced, but instead an indication of whether the output file exists
        and matches is returned.
    """
    template_definition = readfile(template_file)

    t = Template(template_definition, searchList=search_list)
    data = str(t)
    if check_only:
        return file_contains_data(output_file, data, exact=True)
    else:
        writefile(output_file, data)
        return False

# Defaults-related functions.

def get_system_timezone():
    if not exists("/etc/timezone"):
        return None
    return readfile("/etc/timezone").strip()

def set_service_default(name, setting_name, setting_value):
    if isfile(join('/etc/default', name)):
        myaugeas = Augeas()
        setting = join('/files/etc/default/%s' % name, setting_name)

        if myaugeas.get(setting) != setting_value:
            myaugeas.set(setting, setting_value)
            myaugeas.save()

        myaugeas.close()

# Database-related functions.

def grep_for_expression(preceding, expr):
    p = Popen(['/bin/grep', expr], stdin=preceding.stdout, stdout=PIPE, stderr=PIPE)
    return p.wait() == 0

def get_mysql_defaults():
    if is_debian(): 
        return '/etc/mysql/debian.cnf'
    else:
        return '/tmp/kolab-setup-my.cnf'

def need_mysql_root():
    return not is_debian()

def have_mysql():
    return have_command(['mysql', '--version'])

def have_mysql_database(config, name):
    p = Popen(['mysql'] + (config and ['--defaults-file=%s' % config] or []) + [
        '-e', 'show databases',
        '--batch', '--skip-column-names'],
        stdout=PIPE,
        stderr=PIPE
        )
    return grep_for_expression(p, name)

def have_mysql_user(config, name):
    return have_mysql_data(config, "mysql",
        "select User from user where User = '%s' and Host = 'localhost'" % name,
        name)

def have_mysql_data(config, database, query, expected):
    p = Popen(['mysql'] + (config and ['--defaults-file=%s' % config] or []) + [
        '-D', database,
        '-e', query,
        '--batch', '--skip-column-names'],
        stdout=PIPE,
        stderr=PIPE
        )
    return grep_for_expression(p, expected)

def have_mysql_process():
    pidfile = '/var/run/mysqld/mysqld.pid'
    return have_process_with_file(pidfile)

def get_mysql_defaults():
    return find_path(['/etc/mysql/debian.cnf', '/etc/mysql/my.cnf', '/etc/my.cnf'])

def make_mysql_defaults_file(defaults_file):
    utils.multiline_message(
            _("Please supply the MySQL root password")
        )

    mysql_root_password = utils.ask_question(
            _("MySQL root password"),
            password=True
        )

    data = """
[mysql]
user=root
password='%s'
""" % mysql_root_password

    fp = open(defaults_file, 'w')
    try:
        os.chmod(defaults_file, 0600)
        fp.write(data)
    finally:
        fp.close()

# IMAP-related functions.

def have_local_imap_server():
    return have_cyrus_imapd() and 'cyrus-imap' or have_dovecot_imapd() and 'dovecot-imap' or None

def have_cyrus_imapd():
    return exists('/etc/imapd.conf')

def have_dovecot_imapd():
    return exists('/etc/dovecot')

def get_cyrus_config_base():
    return find_path(['/var/lib/imap', '/var/lib/cyrus'])

def get_cyrus_spool_base():
    return find_path(['/var/spool/imap', '/var/spool/cyrus'])

def get_cyrus_sieve_base():
    return find_path(['/var/lib/imap/sieve', '/var/spool/sieve'])

def get_cyrus_socket_base():
    return find_path(['/var/lib/imap/socket', '/var/run/cyrus/socket'])

# LDAP-related functions.

def have_slapd():
    return exists('/etc/dirsrv')

def get_slapd_configuration():
    for path, directories, files in os.walk('/etc/dirsrv/'):
        for dir in directories:
            if dir.startswith('slapd-'):
                return dir
    return None

def have_slapd_process(instance):
    pidfile = '/var/run/dirsrv/slapd-%s.pid' % instance
    return have_process_with_file(pidfile)

# Process-related functions.

def have_process_with_file(pidfile):
    if not exists(pidfile):
        return False
    pid = readfile(pidfile).strip()
    return have_process(pid)

def have_process(pid):
    return call(['/bin/ps', '-p', pid], stdout=PIPE, stderr=PIPE) == 0