file.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. package file_acquisition
  2. import (
  3. "bufio"
  4. "compress/gzip"
  5. "fmt"
  6. "io"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "strings"
  11. "time"
  12. "github.com/crowdsecurity/crowdsec/pkg/acquisition/configuration"
  13. leaky "github.com/crowdsecurity/crowdsec/pkg/leakybucket"
  14. "github.com/crowdsecurity/crowdsec/pkg/types"
  15. "github.com/fsnotify/fsnotify"
  16. "github.com/nxadm/tail"
  17. "github.com/pkg/errors"
  18. "github.com/prometheus/client_golang/prometheus"
  19. log "github.com/sirupsen/logrus"
  20. "gopkg.in/tomb.v2"
  21. "gopkg.in/yaml.v2"
  22. )
  23. type FileConfiguration struct {
  24. Filenames []string
  25. Filename string
  26. ForceInotify bool `yaml:"force_inotify"`
  27. configuration.DataSourceCommonCfg `yaml:",inline"`
  28. }
  29. type FileSource struct {
  30. config FileConfiguration
  31. watcher *fsnotify.Watcher
  32. watchedDirectories map[string]bool
  33. tails map[string]bool
  34. logger *log.Entry
  35. files []string
  36. }
  37. func (f *FileSource) SupportedDSN() []string {
  38. return []string{"file://"}
  39. }
  40. func (f *FileSource) Configure(Config []byte, logger *log.Entry) error {
  41. fileConfig := FileConfiguration{}
  42. f.logger = logger
  43. f.watchedDirectories = make(map[string]bool)
  44. f.tails = make(map[string]bool)
  45. err := yaml.UnmarshalStrict(Config, &fileConfig)
  46. if err != nil {
  47. return errors.Wrap(err, "Cannot parse FileAcquisition configuration")
  48. }
  49. f.logger.Tracef("FileAcquisition configuration: %+v", fileConfig)
  50. if len(fileConfig.Filename) != 0 {
  51. fileConfig.Filenames = append(fileConfig.Filenames, fileConfig.Filename)
  52. }
  53. if len(fileConfig.Filenames) == 0 {
  54. return fmt.Errorf("no filename or filenames configuration provided")
  55. }
  56. f.config = fileConfig
  57. f.watcher, err = fsnotify.NewWatcher()
  58. if err != nil {
  59. return errors.Wrapf(err, "Could not create fsnotify watcher")
  60. }
  61. f.logger.Tracef("Actual FileAcquisition Configuration %+v", f.config)
  62. for _, pattern := range f.config.Filenames {
  63. if f.config.ForceInotify {
  64. directory := path.Dir(pattern)
  65. f.logger.Infof("Force add watch on %s", directory)
  66. if !f.watchedDirectories[directory] {
  67. err = f.watcher.Add(directory)
  68. if err != nil {
  69. f.logger.Errorf("Could not create watch on directory %s : %s", directory, err)
  70. continue
  71. }
  72. f.watchedDirectories[directory] = true
  73. }
  74. }
  75. files, err := filepath.Glob(pattern)
  76. if err != nil {
  77. return errors.Wrap(err, "Glob failure")
  78. }
  79. if len(files) == 0 {
  80. f.logger.Infof("No matching files for pattern %s", pattern)
  81. continue
  82. }
  83. f.logger.Infof("Will read %d files", len(files))
  84. for _, file := range files {
  85. if files[0] != pattern && f.config.Mode == configuration.TAIL_MODE { //we have a glob pattern
  86. directory := path.Dir(file)
  87. if !f.watchedDirectories[directory] {
  88. err = f.watcher.Add(directory)
  89. if err != nil {
  90. f.logger.Errorf("Could not create watch on directory %s : %s", directory, err)
  91. continue
  92. }
  93. f.watchedDirectories[directory] = true
  94. }
  95. }
  96. f.logger.Infof("Adding file %s to filelist", file)
  97. f.files = append(f.files, file)
  98. }
  99. }
  100. return nil
  101. }
  102. func (f *FileSource) ConfigureByDSN(dsn string, logger *log.Entry) error {
  103. if !strings.HasPrefix(dsn, "file://") {
  104. return fmt.Errorf("invalid DSN %s for file source, must start with file://", dsn)
  105. }
  106. pattern := strings.TrimPrefix(dsn, "file://")
  107. if len(pattern) == 0 {
  108. return fmt.Errorf("empty file:// DSN")
  109. }
  110. f.logger = logger
  111. files, err := filepath.Glob(pattern)
  112. if err != nil {
  113. return errors.Wrap(err, "Glob failure")
  114. }
  115. if len(files) == 0 {
  116. return fmt.Errorf("no matching files for pattern %s", pattern)
  117. }
  118. f.logger.Infof("Will read %d files", len(files))
  119. for _, file := range files {
  120. f.logger.Infof("Adding file %s to filelist", file)
  121. f.files = append(f.files, file)
  122. }
  123. return nil
  124. }
  125. func (f *FileSource) GetMode() string {
  126. return f.config.Mode
  127. }
  128. //SupportedModes returns the supported modes by the acquisition module
  129. func (f *FileSource) SupportedModes() []string {
  130. return []string{configuration.TAIL_MODE, configuration.CAT_MODE}
  131. }
  132. //OneShotAcquisition reads a set of file and returns when done
  133. func (f *FileSource) OneShotAcquisition(out chan types.Event, t *tomb.Tomb) error {
  134. for _, file := range f.files {
  135. fi, err := os.Stat(file)
  136. if err != nil {
  137. return fmt.Errorf("could not stat file %s : %w", file, err)
  138. }
  139. if fi.IsDir() {
  140. f.logger.Warnf("%s is a directory, ignoring it.", file)
  141. continue
  142. }
  143. f.logger.Infof("reading %s at once", file)
  144. err = f.readFile(file, out, t)
  145. if err != nil {
  146. return err
  147. }
  148. }
  149. return nil
  150. }
  151. func (f *FileSource) GetMetrics() []prometheus.Collector {
  152. return nil
  153. }
  154. func (f *FileSource) CanRun() error {
  155. return nil
  156. }
  157. func (f *FileSource) LiveAcquisition(out chan types.Event, t *tomb.Tomb) error {
  158. f.logger.Debugf("Starting live acquisition")
  159. t.Go(func() error {
  160. return f.monitorNewFiles(out, t)
  161. })
  162. for _, file := range f.files {
  163. tail, err := tail.TailFile(file, tail.Config{ReOpen: true, Follow: true, Poll: true, Location: &tail.SeekInfo{Offset: 0, Whence: io.SeekEnd}})
  164. if err != nil {
  165. f.logger.Errorf("Could not start tailing file %s : %s", file, err)
  166. continue
  167. }
  168. f.tails[file] = true
  169. t.Go(func() error {
  170. defer types.CatchPanic("crowdsec/acquis/file/live/fsnotify")
  171. return f.tailFile(out, t, tail)
  172. })
  173. }
  174. return nil
  175. }
  176. func (f *FileSource) Dump() interface{} {
  177. return f
  178. }
  179. func (f *FileSource) monitorNewFiles(out chan types.Event, t *tomb.Tomb) error {
  180. for {
  181. select {
  182. case event, ok := <-f.watcher.Events:
  183. if !ok {
  184. return nil
  185. }
  186. if event.Op&fsnotify.Create == fsnotify.Create {
  187. fi, err := os.Stat(event.Name)
  188. if err != nil {
  189. f.logger.Errorf("Could not stat() new file %s, ignoring it : %s", event.Name, err)
  190. }
  191. if fi.IsDir() {
  192. continue
  193. }
  194. f.logger.Infof("Detected new file %s", event.Name)
  195. matched := false
  196. for _, pattern := range f.config.Filenames {
  197. f.logger.Debugf("Matching %s with %s", pattern, event.Name)
  198. matched, err = path.Match(pattern, event.Name)
  199. if err != nil {
  200. f.logger.Errorf("Could not match pattern : %s", err)
  201. continue
  202. }
  203. if matched {
  204. break
  205. }
  206. }
  207. if !matched {
  208. continue
  209. }
  210. if f.tails[event.Name] {
  211. //we already have a tail on it, do not start a new one
  212. f.logger.Debugf("Already tailing file %s, not creating a new tail", event.Name)
  213. break
  214. }
  215. //Slightly different parameters for Location, as we want to read the first lines of the newly created file
  216. tail, err := tail.TailFile(event.Name, tail.Config{ReOpen: true, Follow: true, Poll: true, Location: &tail.SeekInfo{Offset: 0, Whence: io.SeekStart}})
  217. if err != nil {
  218. f.logger.Errorf("Could not start tailing file %s : %s", event.Name, err)
  219. break
  220. }
  221. f.tails[event.Name] = true
  222. t.Go(func() error {
  223. defer types.CatchPanic("crowdsec/acquis/tailfile")
  224. return f.tailFile(out, t, tail)
  225. })
  226. }
  227. case err, ok := <-f.watcher.Errors:
  228. if !ok {
  229. return nil
  230. }
  231. f.logger.Errorf("Error while monitoring folder: %s", err)
  232. }
  233. }
  234. }
  235. func (f *FileSource) tailFile(out chan types.Event, t *tomb.Tomb, tail *tail.Tail) error {
  236. //lint:ignore SA1015 as it is an infinite loop
  237. timeout := time.Tick(1 * time.Second)
  238. f.logger.Debugf("-> Starting tail of %s", tail.Filename)
  239. for {
  240. l := types.Line{}
  241. select {
  242. case <-t.Dying():
  243. f.logger.Infof("File datasource %s stopping", tail.Filename)
  244. if err := tail.Stop(); err != nil {
  245. f.logger.Errorf("error in stop : %s", err)
  246. }
  247. case <-tail.Tomb.Dying(): //our tailer is dying
  248. f.logger.Warningf("File reader of %s died", tail.Filename)
  249. t.Kill(fmt.Errorf("dead reader for %s", tail.Filename))
  250. return fmt.Errorf("reader for %s is dead", tail.Filename)
  251. case line := <-tail.Lines:
  252. if line == nil {
  253. f.logger.Debugf("Nil line")
  254. return fmt.Errorf("tail for %s is empty", tail.Filename)
  255. }
  256. if line.Err != nil {
  257. log.Warningf("fetch error : %v", line.Err)
  258. return line.Err
  259. }
  260. if line.Text == "" { //skip empty lines
  261. continue
  262. }
  263. //FIXME: prometheus metrics
  264. //ReaderHits.With(prometheus.Labels{"source": tail.Filename}).Inc()
  265. l.Raw = line.Text
  266. l.Labels = f.config.Labels
  267. l.Time = line.Time
  268. l.Src = tail.Filename
  269. l.Process = true
  270. //we're tailing, it must be real time logs
  271. f.logger.Debugf("pushing %+v", l)
  272. out <- types.Event{Line: l, Process: true, Type: types.LOG, ExpectMode: leaky.LIVE}
  273. case <-timeout:
  274. //time out, shall we do stuff ?
  275. f.logger.Trace("timeout")
  276. }
  277. }
  278. }
  279. func (f *FileSource) readFile(filename string, out chan types.Event, t *tomb.Tomb) error {
  280. var scanner *bufio.Scanner
  281. fd, err := os.Open(filename)
  282. if err != nil {
  283. return errors.Wrapf(err, "failed opening %s", filename)
  284. }
  285. defer fd.Close()
  286. if strings.HasSuffix(filename, ".gz") {
  287. gz, err := gzip.NewReader(fd)
  288. if err != nil {
  289. f.logger.Errorf("Failed to read gz file: %s", err)
  290. return errors.Wrapf(err, "failed to read gz %s", filename)
  291. }
  292. defer gz.Close()
  293. scanner = bufio.NewScanner(gz)
  294. } else {
  295. scanner = bufio.NewScanner(fd)
  296. }
  297. scanner.Split(bufio.ScanLines)
  298. for scanner.Scan() {
  299. f.logger.Debugf("line %s", scanner.Text())
  300. l := types.Line{}
  301. l.Raw = scanner.Text()
  302. l.Time = time.Now()
  303. l.Src = filename
  304. l.Labels = f.config.Labels
  305. l.Process = true
  306. //we're reading logs at once, it must be time-machine buckets
  307. out <- types.Event{Line: l, Process: true, Type: types.LOG, ExpectMode: leaky.TIMEMACHINE}
  308. }
  309. t.Kill(nil)
  310. return nil
  311. }