file.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. "strings"
  12. "time"
  13. "github.com/crowdsecurity/crowdsec/pkg/acquisition/configuration"
  14. leaky "github.com/crowdsecurity/crowdsec/pkg/leakybucket"
  15. "github.com/crowdsecurity/crowdsec/pkg/types"
  16. "github.com/fsnotify/fsnotify"
  17. "github.com/nxadm/tail"
  18. "github.com/pkg/errors"
  19. "github.com/prometheus/client_golang/prometheus"
  20. log "github.com/sirupsen/logrus"
  21. "gopkg.in/tomb.v2"
  22. "gopkg.in/yaml.v2"
  23. )
  24. var linesRead = prometheus.NewCounterVec(
  25. prometheus.CounterOpts{
  26. Name: "cs_filesource_hits_total",
  27. Help: "Total lines that were read.",
  28. },
  29. []string{"source"})
  30. type FileConfiguration struct {
  31. Filenames []string
  32. Filename string
  33. ForceInotify bool `yaml:"force_inotify"`
  34. configuration.DataSourceCommonCfg `yaml:",inline"`
  35. }
  36. type FileSource struct {
  37. config FileConfiguration
  38. watcher *fsnotify.Watcher
  39. watchedDirectories map[string]bool
  40. tails map[string]bool
  41. logger *log.Entry
  42. files []string
  43. }
  44. func (f *FileSource) Configure(Config []byte, logger *log.Entry) error {
  45. fileConfig := FileConfiguration{}
  46. f.logger = logger
  47. f.watchedDirectories = make(map[string]bool)
  48. f.tails = make(map[string]bool)
  49. err := yaml.UnmarshalStrict(Config, &fileConfig)
  50. if err != nil {
  51. return errors.Wrap(err, "Cannot parse FileAcquisition configuration")
  52. }
  53. f.logger.Tracef("FileAcquisition configuration: %+v", fileConfig)
  54. if len(fileConfig.Filename) != 0 {
  55. fileConfig.Filenames = append(fileConfig.Filenames, fileConfig.Filename)
  56. }
  57. if len(fileConfig.Filenames) == 0 {
  58. return fmt.Errorf("no filename or filenames configuration provided")
  59. }
  60. f.config = fileConfig
  61. if f.config.Mode == "" {
  62. f.config.Mode = configuration.TAIL_MODE
  63. }
  64. if f.config.Mode != configuration.CAT_MODE && f.config.Mode != configuration.TAIL_MODE {
  65. return fmt.Errorf("unsupported mode %s for file source", f.config.Mode)
  66. }
  67. f.watcher, err = fsnotify.NewWatcher()
  68. if err != nil {
  69. return errors.Wrapf(err, "Could not create fsnotify watcher")
  70. }
  71. f.logger.Tracef("Actual FileAcquisition Configuration %+v", f.config)
  72. for _, pattern := range f.config.Filenames {
  73. if f.config.ForceInotify {
  74. directory := path.Dir(pattern)
  75. f.logger.Infof("Force add watch on %s", directory)
  76. if !f.watchedDirectories[directory] {
  77. err = f.watcher.Add(directory)
  78. if err != nil {
  79. f.logger.Errorf("Could not create watch on directory %s : %s", directory, err)
  80. continue
  81. }
  82. f.watchedDirectories[directory] = true
  83. }
  84. }
  85. files, err := filepath.Glob(pattern)
  86. if err != nil {
  87. return errors.Wrap(err, "Glob failure")
  88. }
  89. if len(files) == 0 {
  90. f.logger.Warnf("No matching files for pattern %s", pattern)
  91. continue
  92. }
  93. for _, file := range files {
  94. if files[0] != pattern && f.config.Mode == configuration.TAIL_MODE { //we have a glob pattern
  95. directory := path.Dir(file)
  96. if !f.watchedDirectories[directory] {
  97. err = f.watcher.Add(directory)
  98. if err != nil {
  99. f.logger.Errorf("Could not create watch on directory %s : %s", directory, err)
  100. continue
  101. }
  102. f.watchedDirectories[directory] = true
  103. }
  104. }
  105. f.logger.Infof("Adding file %s to datasources", file)
  106. f.files = append(f.files, file)
  107. }
  108. }
  109. return nil
  110. }
  111. func (f *FileSource) ConfigureByDSN(dsn string, labels map[string]string, logger *log.Entry) error {
  112. if !strings.HasPrefix(dsn, "file://") {
  113. return fmt.Errorf("invalid DSN %s for file source, must start with file://", dsn)
  114. }
  115. f.logger = logger
  116. dsn = strings.TrimPrefix(dsn, "file://")
  117. args := strings.Split(dsn, "?")
  118. if len(args[0]) == 0 {
  119. return fmt.Errorf("empty file:// DSN")
  120. }
  121. if len(args) == 2 && len(args[1]) != 0 {
  122. params, err := url.ParseQuery(args[1])
  123. if err != nil {
  124. return fmt.Errorf("could not parse file args : %s", err)
  125. }
  126. for key, value := range params {
  127. if key != "log_level" {
  128. return fmt.Errorf("unsupported key %s in file DSN", key)
  129. }
  130. if len(value) != 1 {
  131. return fmt.Errorf("expected zero or one value for 'log_level'")
  132. }
  133. lvl, err := log.ParseLevel(value[0])
  134. if err != nil {
  135. return errors.Wrapf(err, "unknown level %s", value[0])
  136. }
  137. f.logger.Logger.SetLevel(lvl)
  138. }
  139. }
  140. f.config = FileConfiguration{}
  141. f.config.Labels = labels
  142. f.config.Mode = configuration.CAT_MODE
  143. f.logger.Debugf("Will try pattern %s", args[0])
  144. files, err := filepath.Glob(args[0])
  145. if err != nil {
  146. return errors.Wrap(err, "Glob failure")
  147. }
  148. if len(files) == 0 {
  149. return fmt.Errorf("no matching files for pattern %s", args[0])
  150. }
  151. if len(files) > 1 {
  152. f.logger.Infof("Will read %d files", len(files))
  153. }
  154. for _, file := range files {
  155. f.logger.Infof("Adding file %s to filelist", file)
  156. f.files = append(f.files, file)
  157. }
  158. return nil
  159. }
  160. func (f *FileSource) GetMode() string {
  161. return f.config.Mode
  162. }
  163. //SupportedModes returns the supported modes by the acquisition module
  164. func (f *FileSource) SupportedModes() []string {
  165. return []string{configuration.TAIL_MODE, configuration.CAT_MODE}
  166. }
  167. //OneShotAcquisition reads a set of file and returns when done
  168. func (f *FileSource) OneShotAcquisition(out chan types.Event, t *tomb.Tomb) error {
  169. f.logger.Debug("In oneshot")
  170. for _, file := range f.files {
  171. fi, err := os.Stat(file)
  172. if err != nil {
  173. return fmt.Errorf("could not stat file %s : %w", file, err)
  174. }
  175. if fi.IsDir() {
  176. f.logger.Warnf("%s is a directory, ignoring it.", file)
  177. continue
  178. }
  179. f.logger.Infof("reading %s at once", file)
  180. err = f.readFile(file, out, t)
  181. if err != nil {
  182. return err
  183. }
  184. }
  185. return nil
  186. }
  187. func (f *FileSource) GetMetrics() []prometheus.Collector {
  188. return []prometheus.Collector{linesRead}
  189. }
  190. func (f *FileSource) GetAggregMetrics() []prometheus.Collector {
  191. return []prometheus.Collector{linesRead}
  192. }
  193. func (f *FileSource) GetName() string {
  194. return "file"
  195. }
  196. func (f *FileSource) CanRun() error {
  197. return nil
  198. }
  199. func (f *FileSource) StreamingAcquisition(out chan types.Event, t *tomb.Tomb) error {
  200. f.logger.Debug("Starting live acquisition")
  201. t.Go(func() error {
  202. return f.monitorNewFiles(out, t)
  203. })
  204. for _, file := range f.files {
  205. //cf. https://github.com/crowdsecurity/crowdsec/issues/1168
  206. //do not rely on stat, reclose file immediately as it's opened by Tail
  207. fd, err := os.Open(file)
  208. if err != nil {
  209. f.logger.Errorf("unable to read %s : %s", file, err)
  210. continue
  211. }
  212. if err := fd.Close(); err != nil {
  213. f.logger.Errorf("unable to close %s : %s", file, err)
  214. continue
  215. }
  216. fi, err := os.Stat(file)
  217. if err != nil {
  218. return fmt.Errorf("could not stat file %s : %w", file, err)
  219. }
  220. if fi.IsDir() {
  221. f.logger.Warnf("%s is a directory, ignoring it.", file)
  222. continue
  223. }
  224. tail, err := tail.TailFile(file, tail.Config{ReOpen: true, Follow: true, Poll: true, Location: &tail.SeekInfo{Offset: 0, Whence: io.SeekEnd}})
  225. if err != nil {
  226. f.logger.Errorf("Could not start tailing file %s : %s", file, err)
  227. continue
  228. }
  229. f.tails[file] = true
  230. t.Go(func() error {
  231. defer types.CatchPanic("crowdsec/acquis/file/live/fsnotify")
  232. return f.tailFile(out, t, tail)
  233. })
  234. }
  235. return nil
  236. }
  237. func (f *FileSource) Dump() interface{} {
  238. return f
  239. }
  240. func (f *FileSource) monitorNewFiles(out chan types.Event, t *tomb.Tomb) error {
  241. logger := f.logger.WithField("goroutine", "inotify")
  242. for {
  243. select {
  244. case event, ok := <-f.watcher.Events:
  245. if !ok {
  246. return nil
  247. }
  248. if event.Op&fsnotify.Create == fsnotify.Create {
  249. fi, err := os.Stat(event.Name)
  250. if err != nil {
  251. logger.Errorf("Could not stat() new file %s, ignoring it : %s", event.Name, err)
  252. continue
  253. }
  254. if fi.IsDir() {
  255. continue
  256. }
  257. logger.Debugf("Detected new file %s", event.Name)
  258. matched := false
  259. for _, pattern := range f.config.Filenames {
  260. logger.Debugf("Matching %s with %s", pattern, event.Name)
  261. matched, err = path.Match(pattern, event.Name)
  262. if err != nil {
  263. logger.Errorf("Could not match pattern : %s", err)
  264. continue
  265. }
  266. if matched {
  267. break
  268. }
  269. }
  270. if !matched {
  271. continue
  272. }
  273. if f.tails[event.Name] {
  274. //we already have a tail on it, do not start a new one
  275. logger.Debugf("Already tailing file %s, not creating a new tail", event.Name)
  276. break
  277. }
  278. //cf. https://github.com/crowdsecurity/crowdsec/issues/1168
  279. //do not rely on stat, reclose file immediately as it's opened by Tail
  280. fd, err := os.Open(event.Name)
  281. if err != nil {
  282. f.logger.Errorf("unable to read %s : %s", event.Name, err)
  283. continue
  284. }
  285. if err := fd.Close(); err != nil {
  286. f.logger.Errorf("unable to close %s : %s", event.Name, err)
  287. continue
  288. }
  289. //Slightly different parameters for Location, as we want to read the first lines of the newly created file
  290. tail, err := tail.TailFile(event.Name, tail.Config{ReOpen: true, Follow: true, Poll: true, Location: &tail.SeekInfo{Offset: 0, Whence: io.SeekStart}})
  291. if err != nil {
  292. logger.Errorf("Could not start tailing file %s : %s", event.Name, err)
  293. break
  294. }
  295. f.tails[event.Name] = true
  296. t.Go(func() error {
  297. defer types.CatchPanic("crowdsec/acquis/tailfile")
  298. return f.tailFile(out, t, tail)
  299. })
  300. }
  301. case err, ok := <-f.watcher.Errors:
  302. if !ok {
  303. return nil
  304. }
  305. logger.Errorf("Error while monitoring folder: %s", err)
  306. case <-t.Dying():
  307. err := f.watcher.Close()
  308. if err != nil {
  309. return errors.Wrapf(err, "could not remove all inotify watches")
  310. }
  311. return nil
  312. }
  313. }
  314. }
  315. func (f *FileSource) tailFile(out chan types.Event, t *tomb.Tomb, tail *tail.Tail) error {
  316. logger := f.logger.WithField("tail", tail.Filename)
  317. logger.Debugf("-> Starting tail of %s", tail.Filename)
  318. for {
  319. l := types.Line{}
  320. select {
  321. case <-t.Dying():
  322. logger.Infof("File datasource %s stopping", tail.Filename)
  323. if err := tail.Stop(); err != nil {
  324. f.logger.Errorf("error in stop : %s", err)
  325. return err
  326. }
  327. return nil
  328. case <-tail.Tomb.Dying(): //our tailer is dying
  329. logger.Warningf("File reader of %s died", tail.Filename)
  330. t.Kill(fmt.Errorf("dead reader for %s", tail.Filename))
  331. return fmt.Errorf("reader for %s is dead", tail.Filename)
  332. case line := <-tail.Lines:
  333. if line == nil {
  334. logger.Debugf("Nil line")
  335. return fmt.Errorf("tail for %s is empty", tail.Filename)
  336. }
  337. if line.Err != nil {
  338. logger.Warningf("fetch error : %v", line.Err)
  339. return line.Err
  340. }
  341. if line.Text == "" { //skip empty lines
  342. continue
  343. }
  344. linesRead.With(prometheus.Labels{"source": tail.Filename}).Inc()
  345. l.Raw = line.Text
  346. l.Labels = f.config.Labels
  347. l.Time = line.Time
  348. l.Src = tail.Filename
  349. l.Process = true
  350. l.Module = f.GetName()
  351. //we're tailing, it must be real time logs
  352. logger.Debugf("pushing %+v", l)
  353. out <- types.Event{Line: l, Process: true, Type: types.LOG, ExpectMode: leaky.LIVE}
  354. }
  355. }
  356. }
  357. func (f *FileSource) readFile(filename string, out chan types.Event, t *tomb.Tomb) error {
  358. var scanner *bufio.Scanner
  359. logger := f.logger.WithField("oneshot", filename)
  360. fd, err := os.Open(filename)
  361. if err != nil {
  362. return errors.Wrapf(err, "failed opening %s", filename)
  363. }
  364. defer fd.Close()
  365. if strings.HasSuffix(filename, ".gz") {
  366. gz, err := gzip.NewReader(fd)
  367. if err != nil {
  368. logger.Errorf("Failed to read gz file: %s", err)
  369. return errors.Wrapf(err, "failed to read gz %s", filename)
  370. }
  371. defer gz.Close()
  372. scanner = bufio.NewScanner(gz)
  373. } else {
  374. scanner = bufio.NewScanner(fd)
  375. }
  376. scanner.Split(bufio.ScanLines)
  377. for scanner.Scan() {
  378. if scanner.Text() == "" {
  379. continue
  380. }
  381. logger.Debugf("line %s", scanner.Text())
  382. l := types.Line{}
  383. l.Raw = scanner.Text()
  384. l.Time = time.Now().UTC()
  385. l.Src = filename
  386. l.Labels = f.config.Labels
  387. l.Process = true
  388. l.Module = f.GetName()
  389. linesRead.With(prometheus.Labels{"source": filename}).Inc()
  390. //we're reading logs at once, it must be time-machine buckets
  391. out <- types.Event{Line: l, Process: true, Type: types.LOG, ExpectMode: leaky.TIMEMACHINE}
  392. }
  393. t.Kill(nil)
  394. return nil
  395. }