file.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "log"
  7. "os"
  8. "time"
  9. )
  10. // WriteToFile will print any string of text to a file safely by
  11. // checking for errors and syncing at the end.
  12. func writeToFile(filename string, data string) error {
  13. file, err := os.Create(filename)
  14. if err != nil {
  15. return err
  16. }
  17. defer file.Close()
  18. _, err = io.WriteString(file, data)
  19. if err != nil {
  20. return err
  21. }
  22. return file.Sync()
  23. }
  24. func handlepanic() {
  25. if a := recover(); a != nil {
  26. fmt.Println("OPS!: Recovering from:", a)
  27. }
  28. }
  29. func saveBayesToFile() {
  30. log.Println("Trying to write json file")
  31. defer handlepanic()
  32. dumpfile := os.Getenv("DUMPFILE")
  33. if dumpfile == "" {
  34. dumpfile = "bayes.json"
  35. }
  36. ZClassifier.STATS.busy.Lock()
  37. defer ZClassifier.STATS.busy.Unlock()
  38. statsREPORT, err := json.MarshalIndent(ZClassifier.STATS.stats, "", " ")
  39. if err != nil {
  40. statsREPORT = []byte(err.Error())
  41. }
  42. ZClassifier.Working.busy.Lock()
  43. defer ZClassifier.Working.busy.Unlock()
  44. wScores, err := json.MarshalIndent(ZClassifier.Working.sMap, "", " ")
  45. if err != nil {
  46. wScores = []byte(err.Error())
  47. }
  48. ZClassifier.Learning.busy.Lock()
  49. defer ZClassifier.Learning.busy.Unlock()
  50. lScores, err := json.MarshalIndent(ZClassifier.Learning.sMap, "", " ")
  51. if err != nil {
  52. lScores = []byte(err.Error())
  53. }
  54. report := fmt.Sprintf("STATS: %s\n WORKING: %s\n LEARNING: %s\n", statsREPORT, wScores, lScores)
  55. writeToFile(dumpfile, report)
  56. log.Println(report)
  57. }
  58. func jsonEngine() {
  59. for {
  60. log.Println("Zardoz Seniority: ", ProxyFlow.seniority)
  61. saveBayesToFile()
  62. time.Sleep(1 * time.Minute)
  63. }
  64. }
  65. func init() {
  66. log.Printf("File Engine Starting")
  67. go jsonEngine()
  68. log.Printf("FIle Engine Started")
  69. }