file.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "log"
  8. "os"
  9. "time"
  10. )
  11. // WriteToFile will print any string of text to a file safely by
  12. // checking for errors and syncing at the end.
  13. func writeToFile(filename string, data string) error {
  14. file, err := os.Create(filename)
  15. if err != nil {
  16. return err
  17. }
  18. defer file.Close()
  19. _, err = io.WriteString(file, data)
  20. if err != nil {
  21. return err
  22. }
  23. return file.Sync()
  24. }
  25. func handlepanic() {
  26. if a := recover(); a != nil {
  27. fmt.Println("OPS!: Recovering from:", a)
  28. }
  29. }
  30. func saveBayesToFile() {
  31. log.Println("Trying to write json file")
  32. defer handlepanic()
  33. var jsnBuf = new(bytes.Buffer)
  34. var tmpJSON string
  35. Classifier.busy.Lock()
  36. DumpJSON, err := Classifier.bayez.MarshalJSON()
  37. if err != nil {
  38. DumpJSON = []byte(err.Error())
  39. }
  40. Classifier.busy.Unlock()
  41. log.Println("Raw dump of Classifier: ", string(DumpJSON))
  42. jerr := json.Indent(jsnBuf, DumpJSON, "", " ")
  43. if jerr == nil {
  44. tmpJSON = jsnBuf.String()
  45. } else {
  46. tmpJSON = jerr.Error()
  47. }
  48. fmt.Println(time.Now().String())
  49. Classifier.STATS.Range(func(key interface{}, value interface{}) bool {
  50. fmt.Printf("%s : %d\n", key.(string), value.(int64))
  51. return true
  52. })
  53. dumpfile := os.Getenv("DUMPFILE")
  54. if dumpfile == "" {
  55. dumpfile = "bayes.json"
  56. }
  57. if DebugLog {
  58. log.Println(tmpJSON)
  59. } else {
  60. writeToFile(dumpfile, tmpJSON)
  61. log.Println("File saved: ", dumpfile)
  62. }
  63. }
  64. func jsonEngine() {
  65. for {
  66. log.Println("Zardoz Seniority: ", ProxyFlow.seniority)
  67. saveBayesToFile()
  68. time.Sleep(1 * time.Minute)
  69. }
  70. }
  71. func init() {
  72. log.Printf("File Engine Starting")
  73. go jsonEngine()
  74. log.Printf("FIle Engine Started")
  75. }