Skip to content

Commit

Permalink
fix: Concurrency issues
Browse files Browse the repository at this point in the history
  • Loading branch information
huhu415 committed Oct 14, 2024
1 parent f7a297e commit 660c779
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 22 deletions.
4 changes: 3 additions & 1 deletion .goreleaser.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ release:
header: |
## 🥳Changes
第一版发布,基本功能完成,已经在寝室开始用3天了。
- 增加统计选项, 可以显示不同设备的修改ua次数
- 删除配置文件, 变得更简洁了
- 已经用了20多天了, 只是晚上人多用的时候随机有点卡, 怀疑是校园网问题
```sh
tar -xzvf uaProxy-linux-xxxxxxx.tar.gz # 解压
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ build:

# debug: debug
debug:
@CompileDaemon -build="make build" -command="./uaProxy --debug"
@CompileDaemon -build="make build" -command="./uaProxy --debug --stats"

clean:
@rm uaProxy
Expand Down
44 changes: 25 additions & 19 deletions bootstrap/bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"

Expand All @@ -28,8 +29,9 @@ const TIMESTAMPFORMAT = "2006-01-02 15:04:05"
var pr *ParserRecord

type ParserRecord struct {
record map[string]*atomic.Int64
filepath string
record sync.Map // [string]*atomic.Int64
filepath string
startTime time.Time
}

func GiveParserRecord() *ParserRecord {
Expand All @@ -38,11 +40,13 @@ func GiveParserRecord() *ParserRecord {

func NewParserRecord(ctx context.Context, filePath string) {
pr = &ParserRecord{
record: make(map[string]*atomic.Int64),
filepath: filePath,
record: sync.Map{},
filepath: filePath,
startTime: time.Now(),
}
go func() {
ticker := time.NewTicker(5 * time.Minute)
logrus.Debug("NewParserRecord finish")
ticker := time.NewTicker(1 * time.Minute)
defer ticker.Stop()
for {
select {
Expand All @@ -59,19 +63,17 @@ func NewParserRecord(ctx context.Context, filePath string) {
func (u *ParserRecord) ParserAndRecord(uaString string) {
ua := useragent.Parse(uaString)

deviceKey := ua.OS + " " + ua.Device
if _, exists := u.record[deviceKey]; !exists {
u.record[deviceKey] = &atomic.Int64{}
}
u.record[deviceKey].Add(1)
deviceKey := ua.OS + "-" + ua.OSVersion + " " + ua.Device
val, _ := u.record.LoadOrStore(deviceKey, &atomic.Int64{})
val.(*atomic.Int64).Add(1)
}

// 使用这个函数定期把统计信息写入日志文件里面
func (u *ParserRecord) WriteLog() {
// 打开或创建文件
file, err := os.Create(u.filepath)
if err != nil {
fmt.Println("Error creating file:", err)
logrus.Errorln("Error creating file:", err)
return
}
defer file.Close()
Expand All @@ -82,23 +84,27 @@ func (u *ParserRecord) WriteLog() {

// 写入表头,并对齐列宽
currentTime := time.Now().Format(TIMESTAMPFORMAT)
_, err = writer.WriteString(fmt.Sprintf("%-50s | %-50s\n", "Current Time", currentTime))
startTime := u.startTime.Format(TIMESTAMPFORMAT)
_, err = writer.WriteString(fmt.Sprintf("%-50s to %-50s\n", startTime, currentTime))
_, err = writer.WriteString(fmt.Sprintf("%-50s | %-50s\n", "Key", "Value"))
_, err = writer.WriteString(fmt.Sprintf("%s\n", strings.Repeat("-", 100)))
if err != nil {
fmt.Println("Error writing to file:", err)
logrus.Errorln("Error writing to file:", err)
return
}

// 遍历 map 并写入键值对,每列宽度固定,左对齐
for key, value := range u.record {
line := fmt.Sprintf("%-50s | %-50d\n", key, value.Load())
// 遍历 sync.Map 并写入键值对,每列宽度固定,左对齐
u.record.Range(func(key, value interface{}) bool {
k := key.(string)
v := value.(*atomic.Int64)
line := fmt.Sprintf("%-50s | %-50d\n", k, v.Load())
_, err := writer.WriteString(line)
if err != nil {
fmt.Println("Error writing to file:", err)
return
logrus.Errorln("Error writing to file:", err)
return false // 返回 false 以停止迭代
}
}
return true // 返回 true 以继续迭代
})

logrus.Debug("Data successfully recorded to file.")
}
Expand Down
1 change: 1 addition & 0 deletions handle/handle.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ func HandleConnection(clientConn net.Conn) {
}

if ua := req.Header.Get("User-Agent"); ua != "" {
logrus.Debug(ua)
bootstrap.GiveParserRecord().ParserAndRecord(ua)
}
req.Header.Set("User-Agent", viper.GetString("User-Agent"))
Expand Down
6 changes: 5 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ func main() {
defer cancel()

bootstrap.LoadConfig()
bootstrap.NewParserRecord(ctx, viper.GetString("stats-config"))
if viper.GetBool("stats") {
p := viper.GetString("stats-config")
fmt.Printf("path: \033[1;34m%s\033[0m, start recording...\n", p)
bootstrap.NewParserRecord(ctx, p)
}

go server()

Expand Down

0 comments on commit 660c779

Please sign in to comment.