-
Notifications
You must be signed in to change notification settings - Fork 1
/
stripe.go
162 lines (119 loc) · 2.41 KB
/
stripe.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
package streammux
import (
"io"
"strconv"
"sync"
"syscall"
)
type StripeBuffer []byte
type StripeBufferList []StripeBuffer
func split(p StripeBuffer, stripeWidth int) StripeBufferList {
if len(p)%wordSize != 0 {
panic("buffer must be a multiple of the architecture wordSize (" + strconv.Itoa(wordSize) + ")")
}
stripeSize := len(p) / stripeWidth
lst := make(StripeBufferList, stripeWidth)
for i := 0; i < stripeWidth; i++ {
lst[i] = p[i*stripeSize : i*stripeSize+stripeSize]
}
return lst
}
func (src StripeBufferList) XOR() StripeBuffer {
if len(src) < 2 {
panic("cannot xor less than two byte arrays")
}
dst := make(StripeBuffer, len(src[0]))
a := src[0]
for i := 1; i < len(src); i++ {
xorWords(dst, a, src[i])
a = dst
}
return dst
}
type Stripe struct {
seq int
sync.Mutex
ios []*Member
state State
}
func (s *Stripe) Health() State {
return s.state
}
func NewStripe(rwcs []io.ReadWriteCloser, opts ...MemberOption) *Stripe {
stripe := &Stripe{
ios: make([]*Member, len(rwcs)),
}
for i, rwc := range rwcs {
stripe.ios[i] = NewMember(rwc, opts...)
}
return stripe
}
func (s *Stripe) Open() State {
s.Lock()
for _, rwc := range s.ios {
state := rwc.Open()
switch state {
case FAILED:
// we're done for
s.state = FAILED
case DEGRADED:
if s.state == FAILED {
break
}
s.state = DEGRADED
}
}
return s.state
}
func (s *Stripe) Close() (err error) {
defer s.Unlock()
for _, closer := range s.ios {
err = closer.Close()
}
return
}
func (s *Stripe) Read(p []byte) (n int, err error) {
if s.state != OK {
return 0, syscall.EIO
}
ch := make(chan rwT)
stripe := split(p, len(s.ios))
for i, reader := range s.ios {
go reader.read(i, stripe[i], ch)
}
for range s.ios {
rc := <-ch
n += rc.n
err = rc.err
if err != nil && err != io.EOF {
s.state = FAILED
}
}
return
}
func (s *Stripe) Write(p []byte) (n int, err error) {
s.seq++
if s.state != OK {
return 0, syscall.EIO
}
ch := make(chan rwT)
stripe := split(p, len(s.ios))
for i, writer := range s.ios {
go writer.write(i, stripe[i], ch)
}
for range s.ios {
rc := <-ch
//log.Printf("[s] seq=%d, rc.n=%d, rc.err=%v", s.seq, rc.n, rc.err)
if rc.err != nil && rc.err != io.EOF {
s.state = FAILED
err = rc.err
continue
}
if rc.err != nil {
err = rc.err
}
n += rc.n
}
//log.Printf("[s return] seq=%d, n=%d, err=%v", s.seq, n, err)
return
}