summaryrefslogtreecommitdiffstats
path: root/awx/main/utils/formatters.py
blob: 783278bd9eb7b2cd3e5131161f8513d84af4f974 (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
# Copyright (c) 2017 Ansible Tower by Red Hat
# All Rights Reserved.

from copy import copy
import json
import json_log_formatter
import logging
import traceback
import socket
from datetime import datetime

from dateutil.tz import tzutc
from django.utils.timezone import now
from django.core.serializers.json import DjangoJSONEncoder
from django.conf import settings


class JobLifeCycleFormatter(json_log_formatter.JSONFormatter):
    def json_record(self, message: str, extra: dict, record: logging.LogRecord):
        if 'time' not in extra:
            extra['time'] = now()
        if record.exc_info:
            extra['exc_info'] = self.formatException(record.exc_info)
        return extra


class TimeFormatter(logging.Formatter):
    """
    Custom log formatter used for inventory imports
    """

    def __init__(self, start_time=None, **kwargs):
        if start_time is None:
            self.job_start = now()
        else:
            self.job_start = start_time
        super(TimeFormatter, self).__init__(**kwargs)

    def format(self, record):
        record.relativeSeconds = (now() - self.job_start).total_seconds()
        return logging.Formatter.format(self, record)


class LogstashFormatterBase(logging.Formatter):
    """Base class taken from python-logstash=0.4.6
    modified here since that version

    For compliance purposes, this was the license at the point of divergence:

    The MIT License (MIT)

    Copyright (c) 2013, Volodymyr Klochan

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
    """

    def __init__(self, message_type='Logstash', fqdn=False):
        self.message_type = message_type

        if fqdn:
            self.host = socket.getfqdn()
        else:
            self.host = socket.gethostname()

    def get_extra_fields(self, record):
        # The list contains all the attributes listed in
        # http://docs.python.org/library/logging.html#logrecord-attributes
        skip_list = (
            'args',
            'asctime',
            'created',
            'exc_info',
            'exc_text',
            'filename',
            'funcName',
            'id',
            'levelname',
            'levelno',
            'lineno',
            'module',
            'msecs',
            'msecs',
            'message',
            'msg',
            'name',
            'pathname',
            'process',
            'processName',
            'relativeCreated',
            'thread',
            'threadName',
            'extra',
        )

        easy_types = (str, bool, dict, float, int, list, type(None))

        fields = {}

        for key, value in record.__dict__.items():
            if key not in skip_list:
                if isinstance(value, easy_types):
                    fields[key] = value
                else:
                    fields[key] = repr(value)

        return fields

    def get_debug_fields(self, record):
        return {
            'stack_trace': self.format_exception(record.exc_info),
            'lineno': record.lineno,
            'process': record.process,
            'thread_name': record.threadName,
            'funcName': record.funcName,
            'processName': record.processName,
        }

    @classmethod
    def format_exception(cls, exc_info):
        return ''.join(traceback.format_exception(*exc_info)) if exc_info else ''

    @classmethod
    def serialize(cls, message):
        return json.dumps(message, cls=DjangoJSONEncoder) + '\n'


class LogstashFormatter(LogstashFormatterBase):
    def __init__(self, *args, **kwargs):
        self.cluster_host_id = settings.CLUSTER_HOST_ID
        self.tower_uuid = None
        uuid = getattr(settings, 'LOG_AGGREGATOR_TOWER_UUID', None) or getattr(settings, 'INSTALL_UUID', None)
        if uuid:
            self.tower_uuid = uuid
        super(LogstashFormatter, self).__init__(*args, **kwargs)

    def reformat_data_for_log(self, raw_data, kind=None):
        """
        Process dictionaries from various contexts (job events, activity stream
        changes, etc.) to give meaningful information
        Output a dictionary which will be passed in logstash or syslog format
        to the logging receiver
        """
        if kind == 'activity_stream':
            try:
                raw_data['changes'] = json.loads(raw_data.get('changes', '{}'))
            except Exception:
                pass  # best effort here, if it's not valid JSON, then meh
            return raw_data
        elif kind == 'system_tracking':
            data = copy(raw_data.get('ansible_facts', {}))
        else:
            data = copy(raw_data)
        if isinstance(data, str):
            data = json.loads(data)
        data_for_log = {}

        if kind == 'job_events' and raw_data.get('python_objects', {}).get('job_event'):
            job_event = raw_data['python_objects']['job_event']
            guid = job_event.event_data.pop('guid', None)
            if guid:
                data_for_log['guid'] = guid
            for field_object in job_event._meta.fields:
                if not field_object.__class__ or not field_object.__class__.__name__:
                    field_class_name = ''
                else:
                    field_class_name = field_object.__class__.__name__
                if field_class_name in ['ManyToOneRel', 'ManyToManyField']:
                    continue

                fd = field_object.name
                key = fd
                if field_class_name == 'ForeignKey':
                    fd = '{}_id'.format(field_object.name)

                try:
                    data_for_log[key] = getattr(job_event, fd)
                except Exception as e:
                    data_for_log[key] = 'Exception `{}` producing field'.format(e)

            data_for_log['event_display'] = job_event.get_event_display2()
            if hasattr(job_event, 'workflow_job_id'):
                data_for_log['workflow_job_id'] = job_event.workflow_job_id

        elif kind == 'system_tracking':
            data.pop('ansible_python_version', None)
            if 'ansible_python' in data:
                data['ansible_python'].pop('version_info', None)

            data_for_log['ansible_facts'] = data
            data_for_log['ansible_facts_modified'] = raw_data.get('ansible_facts_modified')
            data_for_log['inventory_id'] = raw_data.get('inventory_id')
            data_for_log['host_name'] = raw_data.get('host_name')
            data_for_log['job_id'] = raw_data.get('job_id')
        elif kind == 'performance':

            def convert_to_type(t, val):
                if t is float:
                    val = val[:-1] if val.endswith('s') else val
                    try:
                        return float(val)
                    except ValueError:
                        return val
                elif t is int:
                    try:
                        return int(val)
                    except ValueError:
                        return val
                elif t is str:
                    return val

            request = raw_data['python_objects']['request']
            response = raw_data['python_objects']['response']

            # Note: All of the below keys may not be in the response "dict"
            # For example, X-API-Query-Time and X-API-Query-Count will only
            # exist if SQL_DEBUG is turned on in settings.
            headers = [
                (float, 'X-API-Time'),  # may end with an 's' "0.33s"
                (float, 'X-API-Total-Time'),
                (int, 'X-API-Query-Count'),
                (float, 'X-API-Query-Time'),  # may also end with an 's'
                (str, 'X-API-Node'),
            ]
            data_for_log['x_api'] = {k: convert_to_type(t, response[k]) for (t, k) in headers if k in response}

            data_for_log['request'] = {
                'method': request.method,
                'path': request.path,
                'path_info': request.path_info,
                'query_string': request.META['QUERY_STRING'],
            }

            if hasattr(request, 'data'):
                data_for_log['request']['data'] = request.data

        return data_for_log

    def get_extra_fields(self, record):
        fields = super(LogstashFormatter, self).get_extra_fields(record)
        if record.name.startswith('awx.analytics'):
            log_kind = record.name[len('awx.analytics.') :]
            fields = self.reformat_data_for_log(fields, kind=log_kind)
        # General AWX metadata
        fields['cluster_host_id'] = self.cluster_host_id
        fields['tower_uuid'] = self.tower_uuid
        return fields

    def format(self, record):
        stamp = datetime.utcfromtimestamp(record.created)
        stamp = stamp.replace(tzinfo=tzutc())
        message = {
            # Field not included, but exist in related logs
            # 'path': record.pathname
            '@timestamp': stamp,
            'message': record.getMessage(),
            'host': self.host,
            # Extra Fields
            'level': record.levelname,
            'logger_name': record.name,
        }

        # Add extra fields
        message.update(self.get_extra_fields(record))

        # If exception, add debug info
        if record.exc_info:
            message.update(self.get_debug_fields(record))

        if settings.LOG_AGGREGATOR_TYPE == 'splunk':
            # splunk messages must have a top level "event" key
            message = {'event': message}
        return self.serialize(message)