-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmember.go
163 lines (126 loc) · 2.51 KB
/
member.go
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package streammux
import (
"io"
"syscall"
)
type memberOptions struct {
spares *SparePool
}
type MemberOption func(*memberOptions)
func WithSparePool(sp *SparePool) MemberOption {
return func(o *memberOptions) {
o.spares = sp
}
}
type Member struct {
rwc io.ReadWriteCloser
currentSegment int
pos int
upto int
state State
opts memberOptions
segments []*segment
}
type segment struct {
rwc io.ReadWriteCloser
upto int
}
// rwT represents an I/O request
type rwT struct {
idx int
p []byte
n int
err error
}
func NewMember(rwc io.ReadWriteCloser, opts ...MemberOption) *Member {
m := &Member{
rwc: rwc,
segments: make([]*segment, 0),
}
m.segments = append(m.segments, &segment{
rwc: rwc,
upto: -1,
})
for _, opt := range opts {
opt(&m.opts)
}
return m
}
func (m *Member) State() State {
return m.state
}
func (m *Member) SetState(state State) {
m.state = state
}
func (m *Member) Open() State {
m.rwc = m.segments[0].rwc
m.pos = 0
m.upto = m.segments[0].upto
m.currentSegment = 0
if opener, ok := m.rwc.(Opener); ok {
// call the underlying member and record the state
m.state = opener.Open()
}
return m.state
}
func (m *Member) Close() error {
return m.rwc.Close()
}
func (m *Member) write(idx int, p []byte, ch chan rwT) {
if m.state == FAILED {
ch <- rwT{idx, p, 0, syscall.EIO}
return
}
for {
n, err := m.rwc.Write(p)
m.pos += n
if err != nil && err != io.EOF {
spare, err := m.opts.spares.Get()
if err != nil {
m.state = FAILED
} else {
m.segments[m.currentSegment].upto = m.pos
m.currentSegment++
// m.rwc holds up to m.pos
m.segments = append(m.segments, &segment{
rwc: spare,
upto: -1,
})
// close the old device
m.rwc.Close()
// update the current device
m.rwc = spare
// rest of write on new spare
p = p[n:]
continue
}
}
ch <- rwT{idx, p, n, err}
break
}
}
func (m *Member) read(idx int, p []byte, ch chan rwT) {
if m.state == FAILED {
ch <- rwT{idx, p, 0, syscall.EIO}
return
}
if m.upto != -1 && m.pos+len(p) > m.upto {
m.currentSegment++
m.rwc = m.segments[m.currentSegment].rwc
if m.segments[m.currentSegment].upto != -1 {
m.upto = m.upto + m.segments[m.currentSegment].upto
} else {
m.upto = -1
}
// open the device if needed
if opener, ok := m.rwc.(Opener); ok {
opener.Open()
}
}
n, err := m.rwc.Read(p)
if err != nil && err != io.EOF {
m.state = FAILED
}
m.pos += n
ch <- rwT{idx, p, n, err}
}