Passed
Push — master ( 3babf7...1b2ce9 )
by P.R.
03:06
created

DaemonCommand.handle_daemon()   B

Complexity

Conditions 3

Size

Total Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
c 1
b 0
f 0
dl 0
loc 43
ccs 0
cts 27
cp 0
crap 12
rs 8.8571
1
"""
2
Enarksh
3
4
Copyright 2013-2016 Set Based IT Consultancy
5
6
Licence MIT
7
"""
8
import logging
9
import logging.handlers
10
import os
11
import sys
12
13
from cleo import Command
14
from daemon import DaemonContext
15
from lockfile.pidlockfile import PIDLockFile
16
17
import enarksh
18
from enarksh.style.EnarkshStyle import EnarkshStyle
19
20
21
class DaemonCommand(Command):
22
    """
23
    Base class for commands for daemons.
24
    """
25
26
    # ------------------------------------------------------------------------------------------------------------------
27
    def handle_daemon(self, name, daemon):
28
        """
29
        Executes the daemon command.
30
31
        :param str name: The name of the daemon.
32
        :param * daemon: The daemon, i.e. object with main method.
33
        """
34
        self.output = EnarkshStyle(self.input, self.output)
35
36
        log = logging.getLogger('enarksh')
37
        log.setLevel(logging.INFO)
38
        log_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
39
40
        if self.option('daemonize'):
41
            log_file_name = os.path.join(enarksh.HOME, 'var/log', name + '.log')
42
            pid_file_name = os.path.join(enarksh.HOME, 'var/lock', name + '.pid')
43
44
            log_handler = logging.handlers.RotatingFileHandler(log_file_name,
45
                                                               maxBytes=1024*1024,
46
                                                               backupCount=10)
47
            log_handler.setLevel(logging.DEBUG)
48
            log_handler.setFormatter(log_formatter)
49
            log.addHandler(log_handler)
50
51
            output = open(log_file_name, 'ab', 0)
52
53
            context = DaemonContext()
54
            context.working_directory = enarksh.HOME
55
            context.umask = 0o002
56
            context.pidfile = PIDLockFile(pid_file_name, False)
57
            context.stdout = output
58
            context.stderr = output
59
            context.files_preserve = [log_handler.stream]
60
61
            with context:
62
                daemon.main()
63
        else:
64
            log_handler = logging.StreamHandler(sys.stdout)
65
            log_handler.setLevel(logging.DEBUG)
66
            log_handler.setFormatter(log_formatter)
67
            log.addHandler(log_handler)
68
69
            daemon.main()
70
71
# ----------------------------------------------------------------------------------------------------------------------
72