summaryrefslogtreecommitdiffstats
path: root/scripts/analog
blob: eb1962e41d6369f79d984e06082a51b12404b048 (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
#! /usr/bin/python
#
# analog: Remote logging manager for the Red Hat Installer
#
# Copyright (C) 2010
# Red Hat, Inc.  All rights reserved.
#
# 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, see <http://www.gnu.org/licenses/>.
#
# Author: Ales Kozumplik <akozumpl@redhat.com>
#

from __future__ import print_function

import getpass
import errno
import optparse
import os
import os.path
import signal
import sys

DEFAULT_PORT = 6080
DEFAULT_ANALOG_DIR = '.analog'
USAGE = "%prog [options] <log directory root>"
HINT = "/sbin/rsyslogd -c 5 -f %(conf)s -i %(pid)s"
PID_LOCATION = "/tmp/%(username)s/rsyslogd_%(unique_id)s.pid"

INPUT_TCP_TEMPLATE = "$InputTCPServerRun %(port)s"
INPUT_SOCKET_TEMPLATE = "$AddUnixListenSocket %(socket)s"

RSYSLOG_TEMPLATE ="""
#### MODULES ####
# Provides TCP syslog reception
$ModLoad imtcp.so
$ModLoad imuxsock
$OmitLocalLogging on
$SystemLogRateLimitInterval 0
%(input_directive)s

#### GLOBAL DIRECTIVES ####

# Use default timestamp format
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat

# File syncing capability is disabled by default. This feature is usually not
# required, not useful and an extreme performance hit.
#$ActionFileEnableSync on


#### RULES ####

$template anaconda_justmsg, "%%msg%%\\n"
$template anaconda_debug, "%%rawmsg%%\\n"
$template anaconda_syslog, "%%timestamp:8:$:date-rfc3164%%,%%timestamp:1:3:date-subseconds%% %%syslogseverity-text:::uppercase%% %%programname%%:%%msg%%\\n"

$template path_syslog, "%(directory)s/%(subdirectory)s/syslog
$template path_anaconda, "%(directory)s/%(subdirectory)s/anaconda.log"
$template path_anaconda_tb, "%(directory)s/%(subdirectory)s/anaconda-tb-all.log"
$template path_program, "%(directory)s/%(subdirectory)s/program.log"
$template path_storage, "%(directory)s/%(subdirectory)s/storage.log"
$template path_xserver, "%(directory)s/%(subdirectory)s/X.log"
$template path_ifcfg, "%(directory)s/%(subdirectory)s/ifcfg.log"
$template path_sysimage, "%(directory)s/%(subdirectory)s/install.log.syslog"

*.*                                                  %(directory)s/debug_all.log;anaconda_debug

kern.*;\\
daemon.*;\\
user.info;\\
authpriv.*                                          ?path_syslog;anaconda_syslog

:programname, isequal, "anaconda"                   ?path_anaconda;anaconda_syslog
:programname, isequal, "anaconda-tb"                ?path_anaconda_tb;anaconda_justmsg
:programname, isequal, "program"                    ?path_program;anaconda_syslog
:programname, isequal, "storage"                    ?path_storage;anaconda_syslog
:programname, isequal, "xserver"                    ?path_xserver;anaconda_justmsg
:programname, isequal, "ifcfg"                      ?path_ifcfg;anaconda_syslog
:hostname, isequal, "sysimage"                      ?path_sysimage;anaconda_syslog

# discard those that we logged
:programname, isequal, "rsyslogd"                    ~
:programname, isequal, "anaconda"                    ~
:programname, isequal, "anaconda-tb"                 ~
:programname, isequal, "program"                     ~
:programname, isequal, "storage"                     ~
:programname, isequal, "xserver"                     ~
:programname, isequal, "ifcfg"                       ~
:hostname, isequal, "sysimage"                       ~
kern.*                                               ~
daemon.*                                             ~
authpriv.*                                           ~
user.info                                            ~
# dump the rest
*.*                                                  %(directory)s/debug_unknown_source.log;anaconda_debug

"""

# option parsing
class OptParserError(Exception):
    def __str__(self):
        return self.args[0]

    @property
    def parser(self):
        return self.args[1]

def absolute_path(input_path):
    """
    If the path doesn't start with a slash, consider it relative to the current
    working directory.

    Returns aboslute path of 'path'.
    """
    path = os.path.join(os.getcwd(), input_path)
    path = os.path.abspath(path)
    return path

def build_unique_id(options):
    unique_id = options.unix_socket or str(options.port)
    # could be full path to the socket, strip everything before the last slash
    unique_id = unique_id.rsplit('/', 2)[-1]
    return unique_id

def get_opts():
    parser = optparse.OptionParser(usage=USAGE,
                                   add_help_option=False)
    parser.add_option ('-h', '--help', action="callback", callback=help_and_exit,
                       help="Display this help")
    parser.add_option ('-o', type="string", dest="output",
                       default=None,
                       help="Output file")
    parser.add_option ('-p', type="int", dest="port",
                       default=DEFAULT_PORT,
                       help="TCP port the rsyslog daemon will listen on")
    parser.add_option ('-s', action="store_true", dest="stdout",
                       default=False,
                       help="Generate bash command to run rsyslogd on stdout (only valid when -o is also specified)")
    parser.add_option ('-u', type="string", dest="unix_socket",
                       default=None,
                       help="Unix socket the rsyslog daemon will listen on. Using this option turns off listening for TCP connections.")

    (options, args) = parser.parse_args()
    if len(args) < 1:
        raise OptParserError("no log root directory given", parser)
    if options.stdout and not options.output:
        raise OptParserError("-s only valid with -o", parser)
    options.log_root = absolute_path(args[0])
    if options.unix_socket:
        options.unix_socket = absolute_path(options.unix_socket)
    args = args[1:]
    return (options, args)

def help_and_exit(option, opt, value, parser):
    parser.print_help()
    sys.exit(0)

def generate_rsyslog_config(options, unique_id):
    values = {
        "input_directive" : INPUT_TCP_TEMPLATE % {'port' : options.port},
        "directory" : options.log_root,
        "subdirectory" : "%FROMHOST-IP%"
        }

    if options.unix_socket:
        values["input_directive"] = INPUT_SOCKET_TEMPLATE % {'socket' : options.unix_socket}
        values["subdirectory"] = unique_id

    config = RSYSLOG_TEMPLATE % values
    return config

def pid_location(unique_id):
    # find the target location
    name = getpass.getuser()
    values = {
        "username" : name,
        "unique_id" : unique_id
        }
    location = PID_LOCATION % values
    # now make sure the directory exists
    directory = os.path.dirname(location)
    if not os.path.exists(directory):
        os.mkdir(directory)
    return location

if __name__ == "__main__":
    try:
        (options, args) = get_opts()
    except OptParserError as exc:
        exc.parser.error(str(exc))
        sys.exit(1)
    unique_id = build_unique_id(options)
    config = generate_rsyslog_config(options, unique_id)
    if options.output:
        options.output = os.path.abspath(options.output)
        try:
            with open(options.output, 'w') as file:
                file.write(config)
        except IOError as e:
            print("Can't write into file %s" % options.output, file=sys.stderr)
            sys.exit(1)
        if options.stdout:
            pid = pid_location(unique_id)
            print(HINT % {
                    "conf" : options.output,
                    "pid" : pid
                    })
    else:
        print(config)