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
|
package grok
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
)
var (
normal = regexp.MustCompile(`%{(\w+(?::\w+(?::\w+)?)?)}`)
)
// A Config structure is used to configure a Grok parser.
type Config struct {
NamedCapturesOnly bool
SkipDefaultPatterns bool
RemoveEmptyValues bool
PatternsDir []string
Patterns map[string]string
}
// Grok object us used to load patterns and deconstruct strings using those
// patterns.
type Grok struct {
rawPattern map[string]string
config *Config
compiledPatterns map[string]*gRegexp
patterns map[string]*gPattern
patternsGuard *sync.RWMutex
compiledGuard *sync.RWMutex
}
type gPattern struct {
expression string
typeInfo semanticTypes
}
type gRegexp struct {
regexp *regexp.Regexp
typeInfo semanticTypes
}
type semanticTypes map[string]string
// New returns a Grok object.
func New() (*Grok, error) {
return NewWithConfig(&Config{})
}
// NewWithConfig returns a Grok object that is configured to behave according
// to the supplied Config structure.
func NewWithConfig(config *Config) (*Grok, error) {
g := &Grok{
config: config,
compiledPatterns: map[string]*gRegexp{},
patterns: map[string]*gPattern{},
rawPattern: map[string]string{},
patternsGuard: new(sync.RWMutex),
compiledGuard: new(sync.RWMutex),
}
if !config.SkipDefaultPatterns {
g.AddPatternsFromMap(patterns)
}
if len(config.PatternsDir) > 0 {
for _, path := range config.PatternsDir {
err := g.AddPatternsFromPath(path)
if err != nil {
return nil, err
}
}
}
if err := g.AddPatternsFromMap(config.Patterns); err != nil {
return nil, err
}
return g, nil
}
// AddPattern adds a new pattern to the list of loaded patterns.
func (g *Grok) addPattern(name, pattern string) error {
dnPattern, ti, err := g.denormalizePattern(pattern, g.patterns)
if err != nil {
return err
}
g.patterns[name] = &gPattern{expression: dnPattern, typeInfo: ti}
return nil
}
// AddPattern adds a named pattern to grok
func (g *Grok) AddPattern(name, pattern string) error {
g.patternsGuard.Lock()
defer g.patternsGuard.Unlock()
g.rawPattern[name] = pattern
g.buildPatterns()
return nil
}
// AddPatternsFromMap loads a map of named patterns
func (g *Grok) AddPatternsFromMap(m map[string]string) error {
g.patternsGuard.Lock()
defer g.patternsGuard.Unlock()
for name, pattern := range m {
g.rawPattern[name] = pattern
}
return g.buildPatterns()
}
// AddPatternsFromMap adds new patterns from the specified map to the list of
// loaded patterns.
func (g *Grok) addPatternsFromMap(m map[string]string) error {
patternDeps := graph{}
for k, v := range m {
keys := []string{}
for _, key := range normal.FindAllStringSubmatch(v, -1) {
names := strings.Split(key[1], ":")
syntax := names[0]
if g.patterns[syntax] == nil {
if _, ok := m[syntax]; !ok {
return fmt.Errorf("no pattern found for %%{%s}", syntax)
}
}
keys = append(keys, syntax)
}
patternDeps[k] = keys
}
order, _ := sortGraph(patternDeps)
for _, key := range reverseList(order) {
g.addPattern(key, m[key])
}
return nil
}
// AddPatternsFromPath adds new patterns from the files in the specified
// directory to the list of loaded patterns.
func (g *Grok) AddPatternsFromPath(path string) error {
if fi, err := os.Stat(path); err == nil {
if fi.IsDir() {
path = path + "/*"
}
} else {
return fmt.Errorf("invalid path : %s", path)
}
// only one error can be raised, when pattern is malformed
// pattern is hard-coded "/*" so we ignore err
files, _ := filepath.Glob(path)
var filePatterns = map[string]string{}
for _, fileName := range files {
file, err := os.Open(fileName)
if err != nil {
return err
}
scanner := bufio.NewScanner(bufio.NewReader(file))
for scanner.Scan() {
l := scanner.Text()
if len(l) > 0 && l[0] != '#' {
names := strings.SplitN(l, " ", 2)
filePatterns[names[0]] = names[1]
}
}
file.Close()
}
return g.AddPatternsFromMap(filePatterns)
}
// Match returns true if the specified text matches the pattern.
func (g *Grok) Match(pattern, text string) (bool, error) {
gr, err := g.compile(pattern)
if err != nil {
return false, err
}
if ok := gr.regexp.MatchString(text); !ok {
return false, nil
}
return true, nil
}
// compiledParse parses the specified text and returns a map with the results.
func (g *Grok) compiledParse(gr *gRegexp, text string) (map[string]string, error) {
captures := make(map[string]string)
if match := gr.regexp.FindStringSubmatch(text); len(match) > 0 {
for i, name := range gr.regexp.SubexpNames() {
if name != "" {
if g.config.RemoveEmptyValues && match[i] == "" {
continue
}
captures[name] = match[i]
}
}
}
return captures, nil
}
// Parse the specified text and return a map with the results.
func (g *Grok) Parse(pattern, text string) (map[string]string, error) {
gr, err := g.compile(pattern)
if err != nil {
return nil, err
}
return g.compiledParse(gr, text)
}
// ParseTyped returns a inteface{} map with typed captured fields based on provided pattern over the text
func (g *Grok) ParseTyped(pattern string, text string) (map[string]interface{}, error) {
gr, err := g.compile(pattern)
if err != nil {
return nil, err
}
match := gr.regexp.FindStringSubmatch(text)
captures := make(map[string]interface{})
if len(match) > 0 {
for i, segmentName := range gr.regexp.SubexpNames() {
if len(segmentName) != 0 {
if g.config.RemoveEmptyValues == true && match[i] == "" {
continue
}
if segmentType, ok := gr.typeInfo[segmentName]; ok {
switch segmentType {
case "int":
captures[segmentName], _ = strconv.Atoi(match[i])
case "float":
captures[segmentName], _ = strconv.ParseFloat(match[i], 64)
default:
return nil, fmt.Errorf("ERROR the value %s cannot be converted to %s", match[i], segmentType)
}
} else {
captures[segmentName] = match[i]
}
}
}
}
return captures, nil
}
// ParseToMultiMap parses the specified text and returns a map with the
// results. Values are stored in an string slice, so values from captures with
// the same name don't get overridden.
func (g *Grok) ParseToMultiMap(pattern, text string) (map[string][]string, error) {
gr, err := g.compile(pattern)
if err != nil {
return nil, err
}
captures := make(map[string][]string)
if match := gr.regexp.FindStringSubmatch(text); len(match) > 0 {
for i, name := range gr.regexp.SubexpNames() {
if name != "" {
if g.config.RemoveEmptyValues == true && match[i] == "" {
continue
}
captures[name] = append(captures[name], match[i])
}
}
}
return captures, nil
}
func (g *Grok) buildPatterns() error {
g.patterns = map[string]*gPattern{}
return g.addPatternsFromMap(g.rawPattern)
}
func (g *Grok) compile(pattern string) (*gRegexp, error) {
g.compiledGuard.RLock()
gr, ok := g.compiledPatterns[pattern]
g.compiledGuard.RUnlock()
if ok {
return gr, nil
}
g.patternsGuard.RLock()
newPattern, ti, err := g.denormalizePattern(pattern, g.patterns)
g.patternsGuard.RUnlock()
if err != nil {
return nil, err
}
compiledRegex, err := regexp.Compile(newPattern)
if err != nil {
return nil, err
}
gr = &gRegexp{regexp: compiledRegex, typeInfo: ti}
g.compiledGuard.Lock()
g.compiledPatterns[pattern] = gr
g.compiledGuard.Unlock()
return gr, nil
}
func (g *Grok) denormalizePattern(pattern string, storedPatterns map[string]*gPattern) (string, semanticTypes, error) {
ti := semanticTypes{}
for _, values := range normal.FindAllStringSubmatch(pattern, -1) {
names := strings.Split(values[1], ":")
syntax, semantic := names[0], names[0]
if len(names) > 1 {
semantic = names[1]
}
// Add type cast information only if type set, and not string
if len(names) == 3 {
if names[2] != "string" {
ti[semantic] = names[2]
}
}
storedPattern, ok := storedPatterns[syntax]
if !ok {
return "", ti, fmt.Errorf("no pattern found for %%{%s}", syntax)
}
var buffer bytes.Buffer
if !g.config.NamedCapturesOnly || (g.config.NamedCapturesOnly && len(names) > 1) {
buffer.WriteString("(?P<")
buffer.WriteString(semantic)
buffer.WriteString(">")
buffer.WriteString(storedPattern.expression)
buffer.WriteString(")")
} else {
buffer.WriteString("(")
buffer.WriteString(storedPattern.expression)
buffer.WriteString(")")
}
//Merge type Informations
for k, v := range storedPattern.typeInfo {
//Lastest type information is the one to keep in memory
if _, ok := ti[k]; !ok {
ti[k] = v
}
}
pattern = strings.Replace(pattern, values[0], buffer.String(), -1)
}
return pattern, ti, nil
}
// ParseStream will match the given pattern on a line by line basis from the reader
// and apply the results to the process function
func (g *Grok) ParseStream(reader *bufio.Reader, pattern string, process func(map[string]string) error) error {
gr, err := g.compile(pattern)
if err != nil {
return err
}
for {
line, err := reader.ReadString('\n')
if err == io.EOF {
return nil
}
if err != nil {
return err
}
values, err := g.compiledParse(gr, line)
if err != nil {
return err
}
if err = process(values); err != nil {
return err
}
}
}
|