file.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. var jsnBuf = new(bytes.Buffer)
  33. var tmpJSON string
  34. Classifier.busy.Lock()
  35. DumpJSON, err := Classifier.bayez.MarshalJSON()
  36. if err != nil {
  37. DumpJSON = []byte(err.Error())
  38. }
  39. Classifier.busy.Unlock()
  40. log.Println("Raw dump of Classifier: ", string(DumpJSON))
  41. jerr := json.Indent(jsnBuf, DumpJSON, "", " ")
  42. if jerr == nil {
  43. tmpJSON = jsnBuf.String()
  44. } else {
  45. tmpJSON = jerr.Error()
  46. }
  47. fmt.Println(time.Now().String())
  48. Classifier.STATS.Range(func(key interface{}, value interface{}) bool {
  49. fmt.Printf("%s : %d\n", key.(string), value.(int64))
  50. return true
  51. })
  52. dumpfile := os.Getenv("DUMPFILE")
  53. if dumpfile == "" {
  54. dumpfile = "bayes.json"
  55. }
  56. if DebugLog {
  57. log.Println(tmpJSON)
  58. } else {
  59. writeToFile(dumpfile, tmpJSON)
  60. log.Println("File saved: ", dumpfile)
  61. }
  62. }
  63. func jsonEngine() {
  64. for {
  65. log.Println("Zardoz Seniority: ", ProxyFlow.seniority)
  66. saveBayesToFile()
  67. time.Sleep(1 * time.Minute)
  68. }
  69. }
  70. func init() {
  71. log.Printf("File Engine Starting")
  72. go jsonEngine()
  73. log.Printf("FIle Engine Started")
  74. }