clear_logs_job.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package job
  2. import (
  3. "io"
  4. "os"
  5. "path/filepath"
  6. "x-ui/logger"
  7. "x-ui/xray"
  8. )
  9. type ClearLogsJob struct{}
  10. func NewClearLogsJob() *ClearLogsJob {
  11. return new(ClearLogsJob)
  12. }
  13. // ensureFileExists creates the necessary directories and file if they don't exist
  14. func ensureFileExists(path string) error {
  15. dir := filepath.Dir(path)
  16. if err := os.MkdirAll(dir, 0755); err != nil {
  17. return err
  18. }
  19. file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0644)
  20. if err != nil {
  21. return err
  22. }
  23. file.Close()
  24. return nil
  25. }
  26. // Here Run is an interface method of the Job interface
  27. func (j *ClearLogsJob) Run() {
  28. logFiles := []string{xray.GetIPLimitLogPath(), xray.GetIPLimitBannedLogPath(), xray.GetAccessPersistentLogPath()}
  29. logFilesPrev := []string{xray.GetIPLimitBannedPrevLogPath(), xray.GetAccessPersistentPrevLogPath()}
  30. // Ensure all log files and their paths exist
  31. for _, path := range append(logFiles, logFilesPrev...) {
  32. if err := ensureFileExists(path); err != nil {
  33. logger.Warning("Failed to ensure log file exists:", path, "-", err)
  34. }
  35. }
  36. // Clear log files and copy to previous logs
  37. for i := 0; i < len(logFiles); i++ {
  38. if i > 0 {
  39. // Copy to previous logs
  40. logFilePrev, err := os.OpenFile(logFilesPrev[i-1], os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
  41. if err != nil {
  42. logger.Warning("Failed to open previous log file for writing:", logFilesPrev[i-1], "-", err)
  43. continue
  44. }
  45. logFile, err := os.OpenFile(logFiles[i], os.O_RDONLY, 0644)
  46. if err != nil {
  47. logger.Warning("Failed to open current log file for reading:", logFiles[i], "-", err)
  48. logFilePrev.Close()
  49. continue
  50. }
  51. _, err = io.Copy(logFilePrev, logFile)
  52. if err != nil {
  53. logger.Warning("Failed to copy log file:", logFiles[i], "to", logFilesPrev[i-1], "-", err)
  54. }
  55. logFile.Close()
  56. logFilePrev.Close()
  57. }
  58. err := os.Truncate(logFiles[i], 0)
  59. if err != nil {
  60. logger.Warning("Failed to truncate log file:", logFiles[i], "-", err)
  61. }
  62. }
  63. }