Skip to content

Commit

Permalink
improved - message logs
Browse files Browse the repository at this point in the history
  • Loading branch information
MHSanaei committed Jul 8, 2024
1 parent c9a218d commit f1500a5
Show file tree
Hide file tree
Showing 13 changed files with 167 additions and 119 deletions.
92 changes: 46 additions & 46 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (
)

func runWebServer() {
log.Printf("%v %v", config.GetName(), config.GetVersion())
log.Printf("Starting %v %v", config.GetName(), config.GetVersion())

switch config.GetLogLevel() {
case config.Debug:
Expand All @@ -35,31 +35,29 @@ func runWebServer() {
case config.Error:
logger.InitLogger(logging.ERROR)
default:
log.Fatal("unknown log level:", config.GetLogLevel())
log.Fatalf("Unknown log level: %v", config.GetLogLevel())
}

err := database.InitDB(config.GetDBPath())
if err != nil {
log.Fatal(err)
log.Fatalf("Error initializing database: %v", err)
}

var server *web.Server

server = web.NewServer()
global.SetWebServer(server)
err = server.Start()
if err != nil {
log.Println(err)
log.Fatalf("Error starting web server: %v", err)
return
}

var subServer *sub.Server
subServer = sub.NewServer()
global.SetSubServer(subServer)

err = subServer.Start()
if err != nil {
log.Println(err)
log.Fatalf("Error starting sub server: %v", err)
return
}

Expand All @@ -71,34 +69,39 @@ func runWebServer() {

switch sig {
case syscall.SIGHUP:
logger.Info("Received SIGHUP signal. Restarting servers...")

err := server.Stop()
if err != nil {
logger.Warning("stop server err:", err)
logger.Warning("Error stopping web server:", err)
}
err = subServer.Stop()
if err != nil {
logger.Warning("stop server err:", err)
logger.Warning("Error stopping sub server:", err)
}

server = web.NewServer()
global.SetWebServer(server)
err = server.Start()
if err != nil {
log.Println(err)
log.Fatalf("Error restarting web server: %v", err)
return
}
log.Println("Web server restarted successfully.")

subServer = sub.NewServer()
global.SetSubServer(subServer)

err = subServer.Start()
if err != nil {
log.Println(err)
log.Fatalf("Error restarting sub server: %v", err)
return
}
log.Println("Sub server restarted successfully.")

default:
server.Stop()
subServer.Stop()
log.Println("Shutting down servers.")
return
}
}
Expand All @@ -107,16 +110,16 @@ func runWebServer() {
func resetSetting() {
err := database.InitDB(config.GetDBPath())
if err != nil {
fmt.Println(err)
fmt.Println("Failed to initialize database:", err)
return
}

settingService := service.SettingService{}
err = settingService.ResetSettings()
if err != nil {
fmt.Println("reset setting failed:", err)
fmt.Println("Failed to reset settings:", err)
} else {
fmt.Println("reset setting success")
fmt.Println("Settings successfully reset.")
}
}

Expand Down Expand Up @@ -179,7 +182,7 @@ func updateTgbotEnableSts(status bool) {
func updateTgbotSetting(tgBotToken string, tgBotChatid string, tgBotRuntime string) {
err := database.InitDB(config.GetDBPath())
if err != nil {
fmt.Println(err)
fmt.Println("Error initializing database:", err)
return
}

Expand All @@ -188,68 +191,65 @@ func updateTgbotSetting(tgBotToken string, tgBotChatid string, tgBotRuntime stri
if tgBotToken != "" {
err := settingService.SetTgBotToken(tgBotToken)
if err != nil {
fmt.Println(err)
fmt.Printf("Error setting Telegram bot token: %v\n", err)
return
} else {
logger.Info("updateTgbotSetting tgBotToken success")
}
logger.Info("Successfully updated Telegram bot token.")
}

if tgBotRuntime != "" {
err := settingService.SetTgbotRuntime(tgBotRuntime)
if err != nil {
fmt.Println(err)
fmt.Printf("Error setting Telegram bot runtime: %v\n", err)
return
} else {
logger.Infof("updateTgbotSetting tgBotRuntime[%s] success", tgBotRuntime)
}
logger.Infof("Successfully updated Telegram bot runtime to [%s].", tgBotRuntime)
}

if tgBotChatid != "" {
err := settingService.SetTgBotChatId(tgBotChatid)
if err != nil {
fmt.Println(err)
fmt.Printf("Error setting Telegram bot chat ID: %v\n", err)
return
} else {
logger.Info("updateTgbotSetting tgBotChatid success")
}
logger.Info("Successfully updated Telegram bot chat ID.")
}
}

func updateSetting(port int, username string, password string, webBasePath string) {
err := database.InitDB(config.GetDBPath())
if err != nil {
fmt.Println(err)
fmt.Println("Database initialization failed:", err)
return
}

settingService := service.SettingService{}
userService := service.UserService{}

if port > 0 {
err := settingService.SetPort(port)
if err != nil {
fmt.Println("set port failed:", err)
fmt.Println("Failed to set port:", err)
} else {
fmt.Printf("set port %v success", port)
fmt.Printf("Port set successfully: %v\n", port)
}
}

if username != "" || password != "" {
userService := service.UserService{}
err := userService.UpdateFirstUser(username, password)
if err != nil {
fmt.Println("set username and password failed:", err)
fmt.Println("Failed to update username and password:", err)
} else {
fmt.Println("set username and password success")
fmt.Println("Username and password updated successfully")
}
}

if webBasePath != "" {
err := settingService.SetBasePath(webBasePath)
if err != nil {
fmt.Println("set base URI path failed:", err)
fmt.Println("Failed to set base URI path:", err)
} else {
fmt.Println("set base URI path success")
fmt.Println("Base URI path set successfully")
}
}
}
Expand Down Expand Up @@ -348,19 +348,19 @@ func main() {
var reset bool
var show bool
var remove_secret bool
settingCmd.BoolVar(&reset, "reset", false, "reset all settings")
settingCmd.BoolVar(&show, "show", false, "show current settings")
settingCmd.BoolVar(&remove_secret, "remove_secret", false, "remove secret")
settingCmd.IntVar(&port, "port", 0, "set panel port")
settingCmd.StringVar(&username, "username", "", "set login username")
settingCmd.StringVar(&password, "password", "", "set login password")
settingCmd.StringVar(&webBasePath, "webBasePath", "", "set web base path")
settingCmd.StringVar(&webCertFile, "webCert", "", "set web public key path")
settingCmd.StringVar(&webKeyFile, "webCertKey", "", "set web private key path")
settingCmd.StringVar(&tgbottoken, "tgbottoken", "", "set telegram bot token")
settingCmd.StringVar(&tgbotRuntime, "tgbotRuntime", "", "set telegram bot cron time")
settingCmd.StringVar(&tgbotchatid, "tgbotchatid", "", "set telegram bot chat id")
settingCmd.BoolVar(&enabletgbot, "enabletgbot", false, "enable telegram bot notify")
settingCmd.BoolVar(&reset, "reset", false, "Reset all settings")
settingCmd.BoolVar(&show, "show", false, "Display current settings")
settingCmd.BoolVar(&remove_secret, "remove_secret", false, "Remove secret key")
settingCmd.IntVar(&port, "port", 0, "Set panel port number")
settingCmd.StringVar(&username, "username", "", "Set login username")
settingCmd.StringVar(&password, "password", "", "Set login password")
settingCmd.StringVar(&webBasePath, "webBasePath", "", "Set base path for Panel")
settingCmd.StringVar(&webCertFile, "webCert", "", "Set path to public key file for panel")
settingCmd.StringVar(&webKeyFile, "webCertKey", "", "Set path to private key file for panel")
settingCmd.StringVar(&tgbottoken, "tgbottoken", "", "Set token for Telegram bot")
settingCmd.StringVar(&tgbotRuntime, "tgbotRuntime", "", "Set cron time for Telegram bot notifications")
settingCmd.StringVar(&tgbotchatid, "tgbotchatid", "", "Set chat ID for Telegram bot notifications")
settingCmd.BoolVar(&enabletgbot, "enabletgbot", false, "Enable notifications via Telegram bot")

oldUsage := flag.Usage
flag.Usage = func() {
Expand Down
8 changes: 4 additions & 4 deletions sub/sub.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,13 +163,13 @@ func (s *Server) Start() (err error) {
}
listener = network.NewAutoHttpsListener(listener)
listener = tls.NewListener(listener, c)
logger.Info("sub server run https on", listener.Addr())
logger.Info("Sub server running HTTPS on", listener.Addr())
} else {
logger.Error("error in loading certificates: ", err)
logger.Info("sub server run http on", listener.Addr())
logger.Error("Error loading certificates:", err)
logger.Info("Sub server running HTTP on", listener.Addr())
}
} else {
logger.Info("sub server run http on", listener.Addr())
logger.Info("Sub server running HTTP on", listener.Addr())
}
s.listener = listener

Expand Down
8 changes: 4 additions & 4 deletions web/controller/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,25 +76,25 @@ func (a *IndexController) login(c *gin.Context) {

sessionMaxAge, err := a.settingService.GetSessionMaxAge()
if err != nil {
logger.Warningf("Unable to get session's max age from DB")
logger.Warning("Unable to get session's max age from DB")
}

if sessionMaxAge > 0 {
err = session.SetMaxAge(c, sessionMaxAge*60)
if err != nil {
logger.Warningf("Unable to set session's max age")
logger.Warning("Unable to set session's max age")
}
}

err = session.SetLoginUser(c, user)
logger.Info(user.Username, " logged in successfully")
logger.Infof("%s logged in successfully", user.Username)
jsonMsg(c, I18nWeb(c, "pages.login.toasts.successLogin"), err)
}

func (a *IndexController) logout(c *gin.Context) {
user := session.GetLoginUser(c)
if user != nil {
logger.Info(user.Username, " logged out successfully")
logger.Infof("%s logged out successfully", user.Username)
}
session.ClearSession(c)
c.Redirect(http.StatusTemporaryRedirect, c.GetString("base_path"))
Expand Down
36 changes: 24 additions & 12 deletions web/job/check_client_ip_job.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,46 +252,55 @@ func (j *CheckClientIpJob) addInboundClientIps(clientEmail string, ips []string)

func (j *CheckClientIpJob) updateInboundClientIps(inboundClientIps *model.InboundClientIps, clientEmail string, ips []string) bool {
jsonIps, err := json.Marshal(ips)
j.checkError(err)
if err != nil {
logger.Error("failed to marshal IPs to JSON:", err)
return false
}

inboundClientIps.ClientEmail = clientEmail
inboundClientIps.Ips = string(jsonIps)

// check inbound limitation
// Fetch inbound settings by client email
inbound, err := j.getInboundByEmail(clientEmail)
j.checkError(err)
if err != nil {
logger.Errorf("failed to fetch inbound settings for email %s: %s", clientEmail, err)
return false
}

if inbound.Settings == "" {
logger.Debug("wrong data ", inbound)
logger.Debug("wrong data:", inbound)
return false
}

// Unmarshal settings to get client limits
settings := map[string][]model.Client{}
json.Unmarshal([]byte(inbound.Settings), &settings)
clients := settings["clients"]
shouldCleanLog := false
j.disAllowedIps = []string{}

// create iplimit log file channel
logIpFile, err := os.OpenFile(xray.GetIPLimitLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
// Open log file for IP limits
logIpFile, err := os.OpenFile(xray.GetIPLimitLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
logger.Errorf("failed to create or open ip limit log file: %s", err)
logger.Errorf("failed to open IP limit log file: %s", err)
return false
}
defer logIpFile.Close()
log.SetOutput(logIpFile)
log.SetFlags(log.LstdFlags)

// Check client IP limits
for _, client := range clients {
if client.Email == clientEmail {
limitIp := client.LimitIP

if limitIp != 0 {
if limitIp > 0 && inbound.Enable {
shouldCleanLog = true

if limitIp < len(ips) && inbound.Enable {
if limitIp < len(ips) {
j.disAllowedIps = append(j.disAllowedIps, ips[limitIp:]...)
for i := limitIp; i < len(ips); i++ {
log.Printf("[LIMIT_IP] Email = %s || SRC = %s", clientEmail, ips[i])
logger.Debugf("[LIMIT_IP] Email = %s || SRC = %s", clientEmail, ips[i])
}
}
}
Expand All @@ -301,12 +310,15 @@ func (j *CheckClientIpJob) updateInboundClientIps(inboundClientIps *model.Inboun
sort.Strings(j.disAllowedIps)

if len(j.disAllowedIps) > 0 {
logger.Debug("disAllowedIps ", j.disAllowedIps)
logger.Debug("disAllowedIps:", j.disAllowedIps)
}

db := database.GetDB()
err = db.Save(inboundClientIps).Error
j.checkError(err)
if err != nil {
logger.Error("failed to save inboundClientIps:", err)
return false
}

return shouldCleanLog
}
Expand Down
2 changes: 0 additions & 2 deletions web/job/xray_traffic_job.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,8 @@ func (j *XrayTrafficJob) Run() {
if !j.xrayService.IsXrayRunning() {
return
}

traffics, clientTraffics, err := j.xrayService.GetXrayTraffic()
if err != nil {
logger.Warning("get xray traffic failed:", err)
return
}
err, needRestart0 := j.inboundService.AddTraffic(traffics, clientTraffics)
Expand Down
Loading

0 comments on commit f1500a5

Please sign in to comment.