forked from sipt/shuttle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.go
More file actions
138 lines (128 loc) · 2.21 KB
/
Copy pathstorage.go
File metadata and controls
138 lines (128 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package shuttle
import (
"time"
"sync"
)
const (
RecordStatus = 1
RecordUp = 2
RecordDown = 3
RecordStatusActive = "Active"
RecordStatusCompleted = "Completed"
RecordStatusReject = "Reject"
)
var maxCount = 1000
var recordChan chan *Record
var storage *LinkedList
func init() {
recordChan = make(chan *Record, 16)
storage = &LinkedList{}
go func() {
for {
storage.Append(<-recordChan)
}
}()
}
func GetRecords() []Record {
return storage.List()
}
func ClearRecords() {
storage.Clear()
}
func GetRecord(id int64) *Record {
return storage.Get(id)
}
type Record struct {
ID int64
Protocol string
Created time.Time
Proxy *Server
Rule *Rule
Status string
Up int
Down int
URL string
Dumped bool
}
type LinkedList struct {
sync.RWMutex
head, tail *node
count int
}
type node struct {
record *Record
next *node
sync.RWMutex
}
func (l *LinkedList) Get(id int64) *Record {
l.RLock()
index := l.head
for index != nil {
if index.record.ID == id {
l.RUnlock()
return index.record
}
index = index.next
}
l.RUnlock()
return nil
}
func (l *LinkedList) List() []Record {
if l.count == 0 {
return []Record{}
}
l.Lock()
list := make([]Record, l.count)
index := l.head
for i := range list {
list[i] = *index.record
index = index.next
}
l.Unlock()
return list
}
func (l *LinkedList) Append(r *Record) {
l.Lock()
Logger.Debugf("[Storage] Policy:[%s(%s,%s)] URL:[%s]", r.Proxy.Name, r.Rule.Type, r.Rule.Value, r.URL)
if l.head == nil {
l.head = &node{record: r}
l.tail = l.head
} else {
l.tail.next = &node{record: r}
l.tail = l.tail.next
}
l.count ++
for l.count > maxCount {
// 收缩
l.head.next, l.head = nil, l.head.next
l.count --
}
l.Unlock()
}
func (l *LinkedList) Put(id int64, op int, v interface{}) {
index := l.head
for index != nil {
if index.record.ID == id {
index.Put(op, v)
}
index = index.next
}
}
func (l *LinkedList) Clear() {
l.Lock()
l.head = nil
l.count = 0
l.Unlock()
}
func (n *node) Put(op int, v interface{}) {
n.Lock()
switch op {
case RecordStatus:
n.record.Status = v.(string)
case RecordUp:
n.record.Up += v.(int)
case RecordDown:
n.record.Down += v.(int)
}
n.Unlock()
}