explain.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. package main
  2. import (
  3. "bufio"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. log "github.com/sirupsen/logrus"
  11. "github.com/spf13/cobra"
  12. "github.com/crowdsecurity/crowdsec/pkg/dumps"
  13. "github.com/crowdsecurity/crowdsec/pkg/hubtest"
  14. )
  15. func getLineCountForFile(filepath string) (int, error) {
  16. f, err := os.Open(filepath)
  17. if err != nil {
  18. return 0, err
  19. }
  20. defer f.Close()
  21. lc := 0
  22. fs := bufio.NewReader(f)
  23. for {
  24. input, err := fs.ReadBytes('\n')
  25. if len(input) > 1 {
  26. lc++
  27. }
  28. if err != nil && err == io.EOF {
  29. break
  30. }
  31. }
  32. return lc, nil
  33. }
  34. type cliExplain struct {
  35. cfg configGetter
  36. flags struct {
  37. logFile string
  38. dsn string
  39. logLine string
  40. logType string
  41. details bool
  42. skipOk bool
  43. onlySuccessfulParsers bool
  44. noClean bool
  45. crowdsec string
  46. labels string
  47. }
  48. }
  49. func NewCLIExplain(cfg configGetter) *cliExplain {
  50. return &cliExplain{
  51. cfg: cfg,
  52. }
  53. }
  54. func (cli *cliExplain) NewCommand() *cobra.Command {
  55. cmd := &cobra.Command{
  56. Use: "explain",
  57. Short: "Explain log pipeline",
  58. Long: `
  59. Explain log pipeline
  60. `,
  61. Example: `
  62. cscli explain --file ./myfile.log --type nginx
  63. cscli explain --log "Sep 19 18:33:22 scw-d95986 sshd[24347]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=1.2.3.4" --type syslog
  64. cscli explain --dsn "file://myfile.log" --type nginx
  65. tail -n 5 myfile.log | cscli explain --type nginx -f -
  66. `,
  67. Args: cobra.ExactArgs(0),
  68. DisableAutoGenTag: true,
  69. RunE: func(_ *cobra.Command, _ []string) error {
  70. return cli.run()
  71. },
  72. PersistentPreRunE: func(_ *cobra.Command, _ []string) error {
  73. fileInfo, _ := os.Stdin.Stat()
  74. if cli.flags.logFile == "-" && ((fileInfo.Mode() & os.ModeCharDevice) == os.ModeCharDevice) {
  75. return fmt.Errorf("the option -f - is intended to work with pipes")
  76. }
  77. return nil
  78. },
  79. }
  80. flags := cmd.Flags()
  81. flags.StringVarP(&cli.flags.logFile, "file", "f", "", "Log file to test")
  82. flags.StringVarP(&cli.flags.dsn, "dsn", "d", "", "DSN to test")
  83. flags.StringVarP(&cli.flags.logLine, "log", "l", "", "Log line to test")
  84. flags.StringVarP(&cli.flags.logType, "type", "t", "", "Type of the acquisition to test")
  85. flags.StringVar(&cli.flags.labels, "labels", "", "Additional labels to add to the acquisition format (key:value,key2:value2)")
  86. flags.BoolVarP(&cli.flags.details, "verbose", "v", false, "Display individual changes")
  87. flags.BoolVar(&cli.flags.skipOk, "failures", false, "Only show failed lines")
  88. flags.BoolVar(&cli.flags.onlySuccessfulParsers, "only-successful-parsers", false, "Only show successful parsers")
  89. flags.StringVar(&cli.flags.crowdsec, "crowdsec", "crowdsec", "Path to crowdsec")
  90. flags.BoolVar(&cli.flags.noClean, "no-clean", false, "Don't clean runtime environment after tests")
  91. cmd.MarkFlagRequired("type")
  92. cmd.MarkFlagsOneRequired("log", "file", "dsn")
  93. return cmd
  94. }
  95. func (cli *cliExplain) run() error {
  96. logFile := cli.flags.logFile
  97. logLine := cli.flags.logLine
  98. logType := cli.flags.logType
  99. dsn := cli.flags.dsn
  100. labels := cli.flags.labels
  101. crowdsec := cli.flags.crowdsec
  102. opts := dumps.DumpOpts{
  103. Details: cli.flags.details,
  104. SkipOk: cli.flags.skipOk,
  105. ShowNotOkParsers: !cli.flags.onlySuccessfulParsers,
  106. }
  107. var f *os.File
  108. // using empty string fallback to /tmp
  109. dir, err := os.MkdirTemp("", "cscli_explain")
  110. if err != nil {
  111. return fmt.Errorf("couldn't create a temporary directory to store cscli explain result: %w", err)
  112. }
  113. defer func() {
  114. if cli.flags.noClean {
  115. return
  116. }
  117. if _, err := os.Stat(dir); !os.IsNotExist(err) {
  118. if err := os.RemoveAll(dir); err != nil {
  119. log.Errorf("unable to delete temporary directory '%s': %s", dir, err)
  120. }
  121. }
  122. }()
  123. // we create a temporary log file if a log line/stdin has been provided
  124. if logLine != "" || logFile == "-" {
  125. tmpFile := filepath.Join(dir, "cscli_test_tmp.log")
  126. f, err = os.Create(tmpFile)
  127. if err != nil {
  128. return err
  129. }
  130. if logLine != "" {
  131. _, err = f.WriteString(logLine)
  132. if err != nil {
  133. return err
  134. }
  135. } else if logFile == "-" {
  136. reader := bufio.NewReader(os.Stdin)
  137. errCount := 0
  138. for {
  139. input, err := reader.ReadBytes('\n')
  140. if err != nil && errors.Is(err, io.EOF) {
  141. break
  142. }
  143. if len(input) > 1 {
  144. _, err = f.Write(input)
  145. }
  146. if err != nil || len(input) <= 1 {
  147. errCount++
  148. }
  149. }
  150. if errCount > 0 {
  151. log.Warnf("Failed to write %d lines to %s", errCount, tmpFile)
  152. }
  153. }
  154. f.Close()
  155. // this is the file that was going to be read by crowdsec anyway
  156. logFile = tmpFile
  157. }
  158. if logFile != "" {
  159. absolutePath, err := filepath.Abs(logFile)
  160. if err != nil {
  161. return fmt.Errorf("unable to get absolute path of '%s', exiting", logFile)
  162. }
  163. dsn = fmt.Sprintf("file://%s", absolutePath)
  164. lineCount, err := getLineCountForFile(absolutePath)
  165. if err != nil {
  166. return err
  167. }
  168. log.Debugf("file %s has %d lines", absolutePath, lineCount)
  169. if lineCount == 0 {
  170. return fmt.Errorf("the log file is empty: %s", absolutePath)
  171. }
  172. if lineCount > 100 {
  173. log.Warnf("%s contains %d lines. This may take a lot of resources.", absolutePath, lineCount)
  174. }
  175. }
  176. if dsn == "" {
  177. return fmt.Errorf("no acquisition (--file or --dsn) provided, can't run cscli test")
  178. }
  179. cmdArgs := []string{"-c", ConfigFilePath, "-type", logType, "-dsn", dsn, "-dump-data", dir, "-no-api"}
  180. if labels != "" {
  181. log.Debugf("adding labels %s", labels)
  182. cmdArgs = append(cmdArgs, "-label", labels)
  183. }
  184. crowdsecCmd := exec.Command(crowdsec, cmdArgs...)
  185. output, err := crowdsecCmd.CombinedOutput()
  186. if err != nil {
  187. fmt.Println(string(output))
  188. return fmt.Errorf("fail to run crowdsec for test: %w", err)
  189. }
  190. parserDumpFile := filepath.Join(dir, hubtest.ParserResultFileName)
  191. bucketStateDumpFile := filepath.Join(dir, hubtest.BucketPourResultFileName)
  192. parserDump, err := dumps.LoadParserDump(parserDumpFile)
  193. if err != nil {
  194. return fmt.Errorf("unable to load parser dump result: %w", err)
  195. }
  196. bucketStateDump, err := dumps.LoadBucketPourDump(bucketStateDumpFile)
  197. if err != nil {
  198. return fmt.Errorf("unable to load bucket dump result: %w", err)
  199. }
  200. dumps.DumpTree(*parserDump, *bucketStateDump, opts)
  201. return nil
  202. }