summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/modules/weblog/parser.go
blob: b152e41295249fe5d573c7da64d1a9babe505f10 (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
// SPDX-License-Identifier: GPL-3.0-or-later

package weblog

import (
	"errors"
	"fmt"
	"regexp"
	"strings"

	"github.com/netdata/netdata/go/go.d.plugin/pkg/logs"
)

/*
Default apache log format:
 - "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
 - "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
 - "%h %l %u %t \"%r\" %>s %O" common
 - "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\" %I %O" Combined I/O (https://httpd.apache.org/docs/2.4/mod/mod_logio.html)

Default nginx log format:
 - '$remote_addr - $remote_user [$time_local] '
   '"$request" $status $body_bytes_sent '
   '"$http_referer" "$http_user_agent"' combined

Netdata recommends:
 Nginx:
  - '$remote_addr - $remote_user [$time_local] '
    '"$request" $status $body_bytes_sent '
    '$request_length $request_time $upstream_response_time '
    '"$http_referer" "$http_user_agent"'

 Apache:
  - "%h %l %u %t \"%r\" %>s %B %I %D \"%{Referer}i\" \"%{User-Agent}i\""
*/

var (
	csvCommon       = `                   $remote_addr - - [$time_local] "$request" $status $body_bytes_sent`
	csvCustom1      = `                   $remote_addr - - [$time_local] "$request" $status $body_bytes_sent     $request_length $request_time`
	csvCustom2      = `                   $remote_addr - - [$time_local] "$request" $status $body_bytes_sent     $request_length $request_time $upstream_response_time`
	csvCustom3      = `                   $remote_addr - - [$time_local] "$request" $status $body_bytes_sent - - $request_length $request_time`
	csvCustom4      = `                   $remote_addr - - [$time_local] "$request" $status $body_bytes_sent - - $request_length $request_time $upstream_response_time`
	csvVhostCommon  = `$host:$server_port $remote_addr - - [$time_local] "$request" $status $body_bytes_sent`
	csvVhostCustom1 = `$host:$server_port $remote_addr - - [$time_local] "$request" $status $body_bytes_sent     $request_length $request_time`
	csvVhostCustom2 = `$host:$server_port $remote_addr - - [$time_local] "$request" $status $body_bytes_sent     $request_length $request_time $upstream_response_time`
	csvVhostCustom3 = `$host:$server_port $remote_addr - - [$time_local] "$request" $status $body_bytes_sent - - $request_length $request_time`
	csvVhostCustom4 = `$host:$server_port $remote_addr - - [$time_local] "$request" $status $body_bytes_sent - - $request_length $request_time $upstream_response_time`

	guessOrder = []string{
		csvVhostCustom4,
		csvVhostCustom3,
		csvVhostCustom2,
		csvVhostCustom1,
		csvVhostCommon,
		csvCustom4,
		csvCustom3,
		csvCustom2,
		csvCustom1,
		csvCommon,
	}
)

func cleanCSVFormat(format string) string       { return strings.Join(strings.Fields(format), " ") }
func cleanApacheLogFormat(format string) string { return strings.ReplaceAll(format, `\`, "") }

const (
	typeAuto = "auto"
)

var (
	reLTSV = regexp.MustCompile(`^[a-zA-Z0-9]+:[^\t]*(\t[a-zA-Z0-9]+:[^\t]*)*$`)
	reJSON = regexp.MustCompile(`^[[:space:]]*{.*}[[:space:]]*$`)
)

func (w *WebLog) newParser(record []byte) (logs.Parser, error) {
	if w.ParserConfig.LogType == typeAuto {
		w.Debugf("log_type is %s, will try format auto-detection", typeAuto)
		if len(record) == 0 {
			return nil, fmt.Errorf("empty line, can't auto-detect format (%s)", w.file.CurrentFilename())
		}
		return w.guessParser(record)
	}

	w.ParserConfig.CSV.Format = cleanApacheLogFormat(w.ParserConfig.CSV.Format)
	w.Debugf("log_type is %s, skipping auto-detection", w.ParserConfig.LogType)
	switch w.ParserConfig.LogType {
	case logs.TypeCSV:
		w.Debugf("config: %+v", w.ParserConfig.CSV)
	case logs.TypeLTSV:
		w.Debugf("config: %+v", w.ParserConfig.LogType)
	case logs.TypeRegExp:
		w.Debugf("config: %+v", w.ParserConfig.RegExp)
	case logs.TypeJSON:
		w.Debugf("config: %+v", w.ParserConfig.JSON)
	}
	return logs.NewParser(w.ParserConfig, w.file)
}

func (w *WebLog) guessParser(record []byte) (logs.Parser, error) {
	w.Debug("starting log type auto-detection")
	if reLTSV.Match(record) {
		w.Debug("log type is LTSV")
		return logs.NewLTSVParser(w.ParserConfig.LTSV, w.file)
	}
	if reJSON.Match(record) {
		w.Debug("log type is JSON")
		return logs.NewJSONParser(w.ParserConfig.JSON, w.file)
	}
	w.Debug("log type is CSV")
	return w.guessCSVParser(record)
}

func (w *WebLog) guessCSVParser(record []byte) (logs.Parser, error) {
	w.Debug("starting csv log format auto-detection")
	w.Debugf("config: %+v", w.ParserConfig.CSV)
	for _, format := range guessOrder {
		format = cleanCSVFormat(format)
		cfg := w.ParserConfig.CSV
		cfg.Format = format

		w.Debugf("trying format: '%s'", format)
		parser, err := logs.NewCSVParser(cfg, w.file)
		if err != nil {
			return nil, err
		}

		line := newEmptyLogLine()
		if err := parser.Parse(record, line); err != nil {
			w.Debug("parse: ", err)
			continue
		}

		if err = line.verify(); err != nil {
			w.Debug("verify: ", err)
			continue
		}
		return parser, nil
	}
	return nil, errors.New("cannot auto-detect log format, use custom log format")
}

func checkCSVFormatField(field string) (newName string, offset int, valid bool) {
	if isTimeField(field) {
		return "", 1, false
	}
	if !isFieldValid(field) {
		return "", 0, false
	}
	// remove `$` and `%` to have same field names with regexp parser,
	// these symbols aren't allowed in sub exp names
	return field[1:], 0, true
}

func isTimeField(field string) bool {
	return field == "[$time_local]" || field == "$time_local" || field == "%t"
}

func isFieldValid(field string) bool {
	return len(field) > 1 && (isNginxField(field) || isApacheField(field))
}
func isNginxField(field string) bool {
	return strings.HasPrefix(field, "$")
}

func isApacheField(field string) bool {
	return strings.HasPrefix(field, "%")
}