utils.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. package types
  2. import (
  3. "bytes"
  4. "encoding/gob"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "path/filepath"
  10. "runtime/debug"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/crowdsecurity/crowdsec/pkg/cwversion"
  15. log "github.com/sirupsen/logrus"
  16. "gopkg.in/natefinch/lumberjack.v2"
  17. )
  18. var logFormatter log.Formatter
  19. var LogOutput *lumberjack.Logger //io.Writer
  20. var logLevel log.Level
  21. func SetDefaultLoggerConfig(cfgMode string, cfgFolder string, cfgLevel log.Level) error {
  22. /*Configure logs*/
  23. if cfgMode == "file" {
  24. LogOutput = &lumberjack.Logger{
  25. Filename: cfgFolder + "/crowdsec.log",
  26. MaxSize: 500, //megabytes
  27. MaxBackups: 3,
  28. MaxAge: 28, //days
  29. Compress: true, //disabled by default
  30. }
  31. log.SetOutput(LogOutput)
  32. } else if cfgMode != "stdout" {
  33. return fmt.Errorf("log mode '%s' unknown", cfgMode)
  34. }
  35. logLevel = cfgLevel
  36. log.SetLevel(logLevel)
  37. logFormatter = &log.TextFormatter{TimestampFormat: "02-01-2006 15:04:05", FullTimestamp: true}
  38. log.SetFormatter(logFormatter)
  39. return nil
  40. }
  41. func ConfigureLogger(clog *log.Logger) error {
  42. /*Configure logs*/
  43. if LogOutput != nil {
  44. clog.SetOutput(LogOutput)
  45. }
  46. if logFormatter != nil {
  47. clog.SetFormatter(logFormatter)
  48. }
  49. clog.SetLevel(logLevel)
  50. return nil
  51. }
  52. func Clone(a, b interface{}) error {
  53. buff := new(bytes.Buffer)
  54. enc := gob.NewEncoder(buff)
  55. dec := gob.NewDecoder(buff)
  56. if err := enc.Encode(a); err != nil {
  57. return fmt.Errorf("failed cloning %T", a)
  58. }
  59. if err := dec.Decode(b); err != nil {
  60. return fmt.Errorf("failed cloning %T", b)
  61. }
  62. return nil
  63. }
  64. func WriteStackTrace(iErr interface{}) string {
  65. tmpfile, err := ioutil.TempFile("/tmp/", "crowdsec-crash.*.txt")
  66. if err != nil {
  67. log.Fatal(err)
  68. }
  69. if _, err := tmpfile.Write([]byte(fmt.Sprintf("error : %+v\n", iErr))); err != nil {
  70. tmpfile.Close()
  71. log.Fatal(err)
  72. }
  73. if _, err := tmpfile.Write([]byte(cwversion.ShowStr())); err != nil {
  74. tmpfile.Close()
  75. log.Fatal(err)
  76. }
  77. if _, err := tmpfile.Write(debug.Stack()); err != nil {
  78. tmpfile.Close()
  79. log.Fatal(err)
  80. }
  81. if err := tmpfile.Close(); err != nil {
  82. log.Fatal(err)
  83. }
  84. return tmpfile.Name()
  85. }
  86. //CatchPanic is a util func that we should call from all go-routines to ensure proper stacktrace handling
  87. func CatchPanic(component string) {
  88. if r := recover(); r != nil {
  89. log.Errorf("crowdsec - goroutine %s crashed : %s", component, r)
  90. log.Errorf("please report this error to https://github.com/crowdsecurity/crowdsec/")
  91. filename := WriteStackTrace(r)
  92. log.Errorf("stacktrace/report is written to %s : please join it to your issue", filename)
  93. log.Fatalf("crowdsec stopped")
  94. }
  95. }
  96. func ParseDuration(d string) (time.Duration, error) {
  97. durationStr := d
  98. if strings.HasSuffix(d, "d") {
  99. days := strings.Split(d, "d")[0]
  100. if len(days) == 0 {
  101. return 0, fmt.Errorf("'%s' can't be parsed as duration", d)
  102. }
  103. daysInt, err := strconv.Atoi(days)
  104. if err != nil {
  105. return 0, err
  106. }
  107. durationStr = strconv.Itoa(daysInt*24) + "h"
  108. }
  109. duration, err := time.ParseDuration(durationStr)
  110. if err != nil {
  111. return 0, err
  112. }
  113. return duration, nil
  114. }
  115. /*help to copy the file, ioutil doesn't offer the feature*/
  116. func copyFileContents(src, dst string) (err error) {
  117. in, err := os.Open(src)
  118. if err != nil {
  119. return
  120. }
  121. defer in.Close()
  122. out, err := os.Create(dst)
  123. if err != nil {
  124. return
  125. }
  126. defer func() {
  127. cerr := out.Close()
  128. if err == nil {
  129. err = cerr
  130. }
  131. }()
  132. if _, err = io.Copy(out, in); err != nil {
  133. return
  134. }
  135. err = out.Sync()
  136. return
  137. }
  138. /*copy the file, ioutile doesn't offer the feature*/
  139. func CopyFile(sourceSymLink, destinationFile string) (err error) {
  140. sourceFile, err := filepath.EvalSymlinks(sourceSymLink)
  141. if err != nil {
  142. log.Infof("Not a symlink : %s", err)
  143. sourceFile = sourceSymLink
  144. }
  145. sourceFileStat, err := os.Stat(sourceFile)
  146. if err != nil {
  147. return
  148. }
  149. if !sourceFileStat.Mode().IsRegular() {
  150. // cannot copy non-regular files (e.g., directories,
  151. // symlinks, devices, etc.)
  152. return fmt.Errorf("copyFile: non-regular source file %s (%q)", sourceFileStat.Name(), sourceFileStat.Mode().String())
  153. }
  154. destinationFileStat, err := os.Stat(destinationFile)
  155. if err != nil {
  156. if !os.IsNotExist(err) {
  157. return
  158. }
  159. } else {
  160. if !(destinationFileStat.Mode().IsRegular()) {
  161. return fmt.Errorf("copyFile: non-regular destination file %s (%q)", destinationFileStat.Name(), destinationFileStat.Mode().String())
  162. }
  163. if os.SameFile(sourceFileStat, destinationFileStat) {
  164. return
  165. }
  166. }
  167. if err = os.Link(sourceFile, destinationFile); err == nil {
  168. return
  169. }
  170. err = copyFileContents(sourceFile, destinationFile)
  171. return
  172. }