file.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. package fileacquisition
  2. import (
  3. "bufio"
  4. "compress/gzip"
  5. "fmt"
  6. "io"
  7. "net/url"
  8. "os"
  9. "path"
  10. "path/filepath"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "time"
  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. "github.com/crowdsecurity/go-cs-lib/pkg/trace"
  23. "github.com/crowdsecurity/crowdsec/pkg/acquisition/configuration"
  24. "github.com/crowdsecurity/crowdsec/pkg/types"
  25. )
  26. var linesRead = prometheus.NewCounterVec(
  27. prometheus.CounterOpts{
  28. Name: "cs_filesource_hits_total",
  29. Help: "Total lines that were read.",
  30. },
  31. []string{"source"})
  32. type FileConfiguration struct {
  33. Filenames []string
  34. ExcludeRegexps []string `yaml:"exclude_regexps"`
  35. Filename string
  36. ForceInotify bool `yaml:"force_inotify"`
  37. MaxBufferSize int `yaml:"max_buffer_size"`
  38. PollWithoutInotify bool `yaml:"poll_without_inotify"`
  39. configuration.DataSourceCommonCfg `yaml:",inline"`
  40. }
  41. type FileSource struct {
  42. config FileConfiguration
  43. watcher *fsnotify.Watcher
  44. watchedDirectories map[string]bool
  45. tails map[string]bool
  46. logger *log.Entry
  47. files []string
  48. exclude_regexps []*regexp.Regexp
  49. }
  50. func (f *FileSource) GetUuid() string {
  51. return f.config.UniqueId
  52. }
  53. func (f *FileSource) UnmarshalConfig(yamlConfig []byte) error {
  54. f.config = FileConfiguration{}
  55. err := yaml.UnmarshalStrict(yamlConfig, &f.config)
  56. if err != nil {
  57. return fmt.Errorf("cannot parse FileAcquisition configuration: %w", err)
  58. }
  59. if f.logger != nil {
  60. f.logger.Tracef("FileAcquisition configuration: %+v", f.config)
  61. }
  62. if len(f.config.Filename) != 0 {
  63. f.config.Filenames = append(f.config.Filenames, f.config.Filename)
  64. }
  65. if len(f.config.Filenames) == 0 {
  66. return fmt.Errorf("no filename or filenames configuration provided")
  67. }
  68. if f.config.Mode == "" {
  69. f.config.Mode = configuration.TAIL_MODE
  70. }
  71. if f.config.Mode != configuration.CAT_MODE && f.config.Mode != configuration.TAIL_MODE {
  72. return fmt.Errorf("unsupported mode %s for file source", f.config.Mode)
  73. }
  74. for _, exclude := range f.config.ExcludeRegexps {
  75. re, err := regexp.Compile(exclude)
  76. if err != nil {
  77. return fmt.Errorf("could not compile regexp %s: %w", exclude, err)
  78. }
  79. f.exclude_regexps = append(f.exclude_regexps, re)
  80. }
  81. return nil
  82. }
  83. func (f *FileSource) Configure(yamlConfig []byte, logger *log.Entry) error {
  84. f.logger = logger
  85. err := f.UnmarshalConfig(yamlConfig)
  86. if err != nil {
  87. return err
  88. }
  89. f.watchedDirectories = make(map[string]bool)
  90. f.tails = make(map[string]bool)
  91. f.watcher, err = fsnotify.NewWatcher()
  92. if err != nil {
  93. return fmt.Errorf("could not create fsnotify watcher: %w", err)
  94. }
  95. f.logger.Tracef("Actual FileAcquisition Configuration %+v", f.config)
  96. for _, pattern := range f.config.Filenames {
  97. if f.config.ForceInotify {
  98. directory := filepath.Dir(pattern)
  99. f.logger.Infof("Force add watch on %s", directory)
  100. if !f.watchedDirectories[directory] {
  101. err = f.watcher.Add(directory)
  102. if err != nil {
  103. f.logger.Errorf("Could not create watch on directory %s : %s", directory, err)
  104. continue
  105. }
  106. f.watchedDirectories[directory] = true
  107. }
  108. }
  109. files, err := filepath.Glob(pattern)
  110. if err != nil {
  111. return fmt.Errorf("glob failure: %w", err)
  112. }
  113. if len(files) == 0 {
  114. f.logger.Warnf("No matching files for pattern %s", pattern)
  115. continue
  116. }
  117. for _, file := range files {
  118. //check if file is excluded
  119. excluded := false
  120. for _, pattern := range f.exclude_regexps {
  121. if pattern.MatchString(file) {
  122. excluded = true
  123. f.logger.Infof("Skipping file %s as it matches exclude pattern %s", file, pattern)
  124. break
  125. }
  126. }
  127. if excluded {
  128. continue
  129. }
  130. if files[0] != pattern && f.config.Mode == configuration.TAIL_MODE { //we have a glob pattern
  131. directory := filepath.Dir(file)
  132. f.logger.Debugf("Will add watch to directory: %s", directory)
  133. if !f.watchedDirectories[directory] {
  134. err = f.watcher.Add(directory)
  135. if err != nil {
  136. f.logger.Errorf("Could not create watch on directory %s : %s", directory, err)
  137. continue
  138. }
  139. f.watchedDirectories[directory] = true
  140. } else {
  141. f.logger.Debugf("Watch for directory %s already exists", directory)
  142. }
  143. }
  144. f.logger.Infof("Adding file %s to datasources", file)
  145. f.files = append(f.files, file)
  146. }
  147. }
  148. return nil
  149. }
  150. func (f *FileSource) ConfigureByDSN(dsn string, labels map[string]string, logger *log.Entry, uuid string) error {
  151. if !strings.HasPrefix(dsn, "file://") {
  152. return fmt.Errorf("invalid DSN %s for file source, must start with file://", dsn)
  153. }
  154. f.logger = logger
  155. f.config = FileConfiguration{}
  156. dsn = strings.TrimPrefix(dsn, "file://")
  157. args := strings.Split(dsn, "?")
  158. if len(args[0]) == 0 {
  159. return fmt.Errorf("empty file:// DSN")
  160. }
  161. if len(args) == 2 && len(args[1]) != 0 {
  162. params, err := url.ParseQuery(args[1])
  163. if err != nil {
  164. return fmt.Errorf("could not parse file args: %w", err)
  165. }
  166. for key, value := range params {
  167. switch key {
  168. case "log_level":
  169. if len(value) != 1 {
  170. return errors.New("expected zero or one value for 'log_level'")
  171. }
  172. lvl, err := log.ParseLevel(value[0])
  173. if err != nil {
  174. return fmt.Errorf("unknown level %s: %w", value[0], err)
  175. }
  176. f.logger.Logger.SetLevel(lvl)
  177. case "max_buffer_size":
  178. if len(value) != 1 {
  179. return errors.New("expected zero or one value for 'max_buffer_size'")
  180. }
  181. maxBufferSize, err := strconv.Atoi(value[0])
  182. if err != nil {
  183. return fmt.Errorf("could not parse max_buffer_size %s: %w", value[0], err)
  184. }
  185. f.config.MaxBufferSize = maxBufferSize
  186. default:
  187. return fmt.Errorf("unknown parameter %s", key)
  188. }
  189. }
  190. }
  191. f.config.Labels = labels
  192. f.config.Mode = configuration.CAT_MODE
  193. f.config.UniqueId = uuid
  194. f.logger.Debugf("Will try pattern %s", args[0])
  195. files, err := filepath.Glob(args[0])
  196. if err != nil {
  197. return fmt.Errorf("glob failure: %w", err)
  198. }
  199. if len(files) == 0 {
  200. return fmt.Errorf("no matching files for pattern %s", args[0])
  201. }
  202. if len(files) > 1 {
  203. f.logger.Infof("Will read %d files", len(files))
  204. }
  205. for _, file := range files {
  206. f.logger.Infof("Adding file %s to filelist", file)
  207. f.files = append(f.files, file)
  208. }
  209. return nil
  210. }
  211. func (f *FileSource) GetMode() string {
  212. return f.config.Mode
  213. }
  214. // SupportedModes returns the supported modes by the acquisition module
  215. func (f *FileSource) SupportedModes() []string {
  216. return []string{configuration.TAIL_MODE, configuration.CAT_MODE}
  217. }
  218. // OneShotAcquisition reads a set of file and returns when done
  219. func (f *FileSource) OneShotAcquisition(out chan types.Event, t *tomb.Tomb) error {
  220. f.logger.Debug("In oneshot")
  221. for _, file := range f.files {
  222. fi, err := os.Stat(file)
  223. if err != nil {
  224. return fmt.Errorf("could not stat file %s : %w", file, err)
  225. }
  226. if fi.IsDir() {
  227. f.logger.Warnf("%s is a directory, ignoring it.", file)
  228. continue
  229. }
  230. f.logger.Infof("reading %s at once", file)
  231. err = f.readFile(file, out, t)
  232. if err != nil {
  233. return err
  234. }
  235. }
  236. return nil
  237. }
  238. func (f *FileSource) GetMetrics() []prometheus.Collector {
  239. return []prometheus.Collector{linesRead}
  240. }
  241. func (f *FileSource) GetAggregMetrics() []prometheus.Collector {
  242. return []prometheus.Collector{linesRead}
  243. }
  244. func (f *FileSource) GetName() string {
  245. return "file"
  246. }
  247. func (f *FileSource) CanRun() error {
  248. return nil
  249. }
  250. func (f *FileSource) StreamingAcquisition(out chan types.Event, t *tomb.Tomb) error {
  251. f.logger.Debug("Starting live acquisition")
  252. t.Go(func() error {
  253. return f.monitorNewFiles(out, t)
  254. })
  255. for _, file := range f.files {
  256. //before opening the file, check if we need to specifically avoid it. (XXX)
  257. skip := false
  258. for _, pattern := range f.exclude_regexps {
  259. if pattern.MatchString(file) {
  260. f.logger.Infof("file %s matches exclusion pattern %s, skipping", file, pattern.String())
  261. skip = true
  262. break
  263. }
  264. }
  265. if skip {
  266. continue
  267. }
  268. //cf. https://github.com/crowdsecurity/crowdsec/issues/1168
  269. //do not rely on stat, reclose file immediately as it's opened by Tail
  270. fd, err := os.Open(file)
  271. if err != nil {
  272. f.logger.Errorf("unable to read %s : %s", file, err)
  273. continue
  274. }
  275. if err := fd.Close(); err != nil {
  276. f.logger.Errorf("unable to close %s : %s", file, err)
  277. continue
  278. }
  279. fi, err := os.Stat(file)
  280. if err != nil {
  281. return fmt.Errorf("could not stat file %s : %w", file, err)
  282. }
  283. if fi.IsDir() {
  284. f.logger.Warnf("%s is a directory, ignoring it.", file)
  285. continue
  286. }
  287. tail, err := tail.TailFile(file, tail.Config{ReOpen: true, Follow: true, Poll: f.config.PollWithoutInotify, Location: &tail.SeekInfo{Offset: 0, Whence: io.SeekEnd}, Logger: log.NewEntry(log.StandardLogger())})
  288. if err != nil {
  289. f.logger.Errorf("Could not start tailing file %s : %s", file, err)
  290. continue
  291. }
  292. f.tails[file] = true
  293. t.Go(func() error {
  294. defer trace.CatchPanic("crowdsec/acquis/file/live/fsnotify")
  295. return f.tailFile(out, t, tail)
  296. })
  297. }
  298. return nil
  299. }
  300. func (f *FileSource) Dump() interface{} {
  301. return f
  302. }
  303. func (f *FileSource) monitorNewFiles(out chan types.Event, t *tomb.Tomb) error {
  304. logger := f.logger.WithField("goroutine", "inotify")
  305. for {
  306. select {
  307. case event, ok := <-f.watcher.Events:
  308. if !ok {
  309. return nil
  310. }
  311. if event.Op&fsnotify.Create == fsnotify.Create {
  312. fi, err := os.Stat(event.Name)
  313. if err != nil {
  314. logger.Errorf("Could not stat() new file %s, ignoring it : %s", event.Name, err)
  315. continue
  316. }
  317. if fi.IsDir() {
  318. continue
  319. }
  320. logger.Debugf("Detected new file %s", event.Name)
  321. matched := false
  322. for _, pattern := range f.config.Filenames {
  323. logger.Debugf("Matching %s with %s", pattern, event.Name)
  324. matched, err = path.Match(pattern, event.Name)
  325. if err != nil {
  326. logger.Errorf("Could not match pattern : %s", err)
  327. continue
  328. }
  329. if matched {
  330. break
  331. }
  332. }
  333. if !matched {
  334. continue
  335. }
  336. //before opening the file, check if we need to specifically avoid it. (XXX)
  337. skip := false
  338. for _, pattern := range f.exclude_regexps {
  339. if pattern.MatchString(event.Name) {
  340. f.logger.Infof("file %s matches exclusion pattern %s, skipping", event.Name, pattern.String())
  341. skip = true
  342. break
  343. }
  344. }
  345. if skip {
  346. continue
  347. }
  348. if f.tails[event.Name] {
  349. //we already have a tail on it, do not start a new one
  350. logger.Debugf("Already tailing file %s, not creating a new tail", event.Name)
  351. break
  352. }
  353. //cf. https://github.com/crowdsecurity/crowdsec/issues/1168
  354. //do not rely on stat, reclose file immediately as it's opened by Tail
  355. fd, err := os.Open(event.Name)
  356. if err != nil {
  357. f.logger.Errorf("unable to read %s : %s", event.Name, err)
  358. continue
  359. }
  360. if err := fd.Close(); err != nil {
  361. f.logger.Errorf("unable to close %s : %s", event.Name, err)
  362. continue
  363. }
  364. //Slightly different parameters for Location, as we want to read the first lines of the newly created file
  365. tail, err := tail.TailFile(event.Name, tail.Config{ReOpen: true, Follow: true, Poll: f.config.PollWithoutInotify, Location: &tail.SeekInfo{Offset: 0, Whence: io.SeekStart}})
  366. if err != nil {
  367. logger.Errorf("Could not start tailing file %s : %s", event.Name, err)
  368. break
  369. }
  370. f.tails[event.Name] = true
  371. t.Go(func() error {
  372. defer trace.CatchPanic("crowdsec/acquis/tailfile")
  373. return f.tailFile(out, t, tail)
  374. })
  375. }
  376. case err, ok := <-f.watcher.Errors:
  377. if !ok {
  378. return nil
  379. }
  380. logger.Errorf("Error while monitoring folder: %s", err)
  381. case <-t.Dying():
  382. err := f.watcher.Close()
  383. if err != nil {
  384. return fmt.Errorf("could not remove all inotify watches: %w", err)
  385. }
  386. return nil
  387. }
  388. }
  389. }
  390. func (f *FileSource) tailFile(out chan types.Event, t *tomb.Tomb, tail *tail.Tail) error {
  391. logger := f.logger.WithField("tail", tail.Filename)
  392. logger.Debugf("-> Starting tail of %s", tail.Filename)
  393. for {
  394. select {
  395. case <-t.Dying():
  396. logger.Infof("File datasource %s stopping", tail.Filename)
  397. if err := tail.Stop(); err != nil {
  398. f.logger.Errorf("error in stop : %s", err)
  399. return err
  400. }
  401. return nil
  402. case <-tail.Dying(): //our tailer is dying
  403. logger.Warningf("File reader of %s died", tail.Filename)
  404. t.Kill(fmt.Errorf("dead reader for %s", tail.Filename))
  405. return fmt.Errorf("reader for %s is dead", tail.Filename)
  406. case line := <-tail.Lines:
  407. if line == nil {
  408. logger.Warningf("tail for %s is empty", tail.Filename)
  409. continue
  410. }
  411. if line.Err != nil {
  412. logger.Warningf("fetch error : %v", line.Err)
  413. return line.Err
  414. }
  415. if line.Text == "" { //skip empty lines
  416. continue
  417. }
  418. linesRead.With(prometheus.Labels{"source": tail.Filename}).Inc()
  419. l := types.Line{
  420. Raw: trimLine(line.Text),
  421. Labels: f.config.Labels,
  422. Time: line.Time,
  423. Src: tail.Filename,
  424. Process: true,
  425. Module: f.GetName(),
  426. }
  427. //we're tailing, it must be real time logs
  428. logger.Debugf("pushing %+v", l)
  429. expectMode := types.LIVE
  430. if f.config.UseTimeMachine {
  431. expectMode = types.TIMEMACHINE
  432. }
  433. out <- types.Event{Line: l, Process: true, Type: types.LOG, ExpectMode: expectMode}
  434. }
  435. }
  436. }
  437. func (f *FileSource) readFile(filename string, out chan types.Event, t *tomb.Tomb) error {
  438. var scanner *bufio.Scanner
  439. logger := f.logger.WithField("oneshot", filename)
  440. fd, err := os.Open(filename)
  441. if err != nil {
  442. return fmt.Errorf("failed opening %s: %w", filename, err)
  443. }
  444. defer fd.Close()
  445. if strings.HasSuffix(filename, ".gz") {
  446. gz, err := gzip.NewReader(fd)
  447. if err != nil {
  448. logger.Errorf("Failed to read gz file: %s", err)
  449. return fmt.Errorf("failed to read gz %s: %w", filename, err)
  450. }
  451. defer gz.Close()
  452. scanner = bufio.NewScanner(gz)
  453. } else {
  454. scanner = bufio.NewScanner(fd)
  455. }
  456. scanner.Split(bufio.ScanLines)
  457. if f.config.MaxBufferSize > 0 {
  458. buf := make([]byte, 0, 64*1024)
  459. scanner.Buffer(buf, f.config.MaxBufferSize)
  460. }
  461. for scanner.Scan() {
  462. select {
  463. case <-t.Dying():
  464. logger.Infof("File datasource %s stopping", filename)
  465. return nil
  466. default:
  467. if scanner.Text() == "" {
  468. continue
  469. }
  470. l := types.Line{
  471. Raw: scanner.Text(),
  472. Time: time.Now().UTC(),
  473. Src: filename,
  474. Labels: f.config.Labels,
  475. Process: true,
  476. Module: f.GetName(),
  477. }
  478. logger.Debugf("line %s", l.Raw)
  479. linesRead.With(prometheus.Labels{"source": filename}).Inc()
  480. //we're reading logs at once, it must be time-machine buckets
  481. out <- types.Event{Line: l, Process: true, Type: types.LOG, ExpectMode: types.TIMEMACHINE}
  482. }
  483. }
  484. if err := scanner.Err(); err != nil {
  485. logger.Errorf("Error while reading file: %s", err)
  486. t.Kill(err)
  487. return err
  488. }
  489. t.Kill(nil)
  490. return nil
  491. }