Files
EdgeNode/internal/caches/open_file_pool.go

99 lines
1.7 KiB
Go
Raw Normal View History

2022-01-12 21:09:00 +08:00
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
package caches
import (
"github.com/TeaOSLab/EdgeNode/internal/utils/fasttime"
2022-01-12 21:09:00 +08:00
"github.com/TeaOSLab/EdgeNode/internal/utils/linkedlist"
)
type OpenFilePool struct {
c chan *OpenFile
linkItem *linkedlist.Item
filename string
version int64
2022-12-05 11:16:04 +08:00
isClosed bool
2022-01-12 21:09:00 +08:00
}
func NewOpenFilePool(filename string) *OpenFilePool {
var pool = &OpenFilePool{
filename: filename,
c: make(chan *OpenFile, 1024),
version: fasttime.Now().UnixMilli(),
2022-01-12 21:09:00 +08:00
}
pool.linkItem = linkedlist.NewItem(pool)
return pool
}
func (this *OpenFilePool) Filename() string {
return this.filename
}
func (this *OpenFilePool) Get() (*OpenFile, bool) {
2022-12-05 11:16:04 +08:00
// 如果已经关闭,直接返回
if this.isClosed {
return nil, false
}
2022-01-12 21:09:00 +08:00
select {
case file := <-this.c:
2022-12-05 10:46:44 +08:00
if file != nil {
err := file.SeekStart()
if err != nil {
_ = file.Close()
return nil, true
}
file.version = this.version
2022-01-12 21:09:00 +08:00
2022-12-05 10:46:44 +08:00
return file, true
}
return nil, false
2022-01-12 21:09:00 +08:00
default:
return nil, false
}
}
func (this *OpenFilePool) Put(file *OpenFile) bool {
2022-12-05 11:16:04 +08:00
// 如果已关闭,则不接受新的文件
if this.isClosed {
_ = file.Close()
return false
}
// 检查文件版本号
if this.version > 0 && file.version > 0 && file.version != this.version {
2022-01-12 21:09:00 +08:00
_ = file.Close()
return false
}
2022-12-05 11:16:04 +08:00
// 加入Pool
2022-01-12 21:09:00 +08:00
select {
case this.c <- file:
return true
default:
// 多余的直接关闭
_ = file.Close()
return false
}
}
func (this *OpenFilePool) Len() int {
return len(this.c)
}
2022-12-05 11:16:04 +08:00
func (this *OpenFilePool) SetClosing() {
this.isClosed = true
}
2022-01-12 21:09:00 +08:00
func (this *OpenFilePool) Close() {
2022-12-05 11:16:04 +08:00
this.isClosed = true
2022-01-12 21:09:00 +08:00
for {
select {
case file := <-this.c:
_ = file.Close()
default:
2022-12-05 11:16:04 +08:00
return
2022-01-12 21:09:00 +08:00
}
}
}