github.com/kilpkonn/gtm-enhanced@v1.3.5/event/manager.go (about)

     1  // Copyright 2016 Michael Schenk. All rights reserved.
     2  // Use of this source code is governed by a MIT-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package event
     6  
     7  import (
     8  	"io/ioutil"
     9  	"os"
    10  	"path/filepath"
    11  	"strconv"
    12  	"strings"
    13  
    14  	"github.com/git-time-metric/gtm/epoch"
    15  	"github.com/git-time-metric/gtm/util"
    16  )
    17  
    18  // Record creates an event for a source
    19  func Record(file string) error {
    20  	sourcePath, gtmPath, err := pathFromSource(file)
    21  	if err != nil {
    22  		return err
    23  	}
    24  
    25  	return writeEventFile(sourcePath, gtmPath)
    26  }
    27  
    28  // Process scans the gtmPath for event files and processes them.
    29  // If interim is true, event files are not purged.
    30  func Process(gtmPath string, interim bool) (map[int64]map[string]int, error) {
    31  	defer util.Profile()()
    32  
    33  	events := make(map[int64]map[string]int)
    34  
    35  	files, err := ioutil.ReadDir(gtmPath)
    36  	if err != nil {
    37  		return events, err
    38  	}
    39  
    40  	filesToRemove := []string{}
    41  	var prevEpoch int64
    42  	var prevFilePath string
    43  	for i := range files {
    44  
    45  		if !strings.HasSuffix(files[i].Name(), ".event") {
    46  			continue
    47  		}
    48  
    49  		eventFilePath := filepath.Join(gtmPath, files[i].Name())
    50  		filesToRemove = append(filesToRemove, eventFilePath)
    51  
    52  		s := strings.SplitN(files[i].Name(), ".", 2)
    53  		if len(s) != 2 {
    54  			continue
    55  		}
    56  
    57  		fileEpoch, err := strconv.ParseInt(s[0], 10, 64)
    58  		if err != nil {
    59  			continue
    60  		}
    61  		fileEpoch = epoch.Minute(fileEpoch)
    62  
    63  		sourcePath, err := readEventFile(eventFilePath)
    64  		if err != nil {
    65  			// assume it's bad, remove it
    66  			_ = os.Remove(eventFilePath)
    67  			continue
    68  		}
    69  
    70  		if _, ok := events[fileEpoch]; !ok {
    71  			events[fileEpoch] = make(map[string]int)
    72  		}
    73  		events[fileEpoch][sourcePath]++
    74  
    75  		// Add idle events
    76  		if prevEpoch != 0 && prevFilePath != "" {
    77  			for e := prevEpoch + epoch.WindowSize; e < fileEpoch && e <= prevEpoch+epoch.IdleTimeout; e += epoch.WindowSize {
    78  				if _, ok := events[e]; !ok {
    79  					events[e] = make(map[string]int)
    80  				}
    81  				events[e][prevFilePath]++
    82  			}
    83  		}
    84  		prevEpoch = fileEpoch
    85  		prevFilePath = sourcePath
    86  	}
    87  
    88  	if !interim {
    89  		if err := removeFiles(filesToRemove); err != nil {
    90  			return events, err
    91  		}
    92  	}
    93  
    94  	return events, nil
    95  }