file.go 9.4 KB

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