-
Notifications
You must be signed in to change notification settings - Fork 0
/
commit_ctx.go
124 lines (100 loc) · 2.37 KB
/
commit_ctx.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
package gopaxos
import (
"bytes"
"math"
"time"
)
type commitCtx struct {
conf *config
instanceID uint64
commitRet int32
isCommitEnd bool
timeoutMs int
value []byte
smCtx *SMCtx
slock *serialLock
}
func newCommitCtx(conf *config) *commitCtx {
ret := &commitCtx{}
ret.conf = conf
ret.slock = newSerialLock()
ret.newCommit(nil, nil, 0)
return ret
}
func (c *commitCtx) newCommit(value []byte, ctx *SMCtx, timeoutMs int) {
c.slock.lock()
defer c.slock.unlock()
c.instanceID = math.MaxUint64
c.commitRet = -1
c.isCommitEnd = false
c.timeoutMs = timeoutMs
c.value = value
c.smCtx = ctx
if value != nil {
lPLGHead(c.conf.groupIdx, "OK, valuesize %d", len(c.value))
}
}
func (c *commitCtx) isNewCommit() bool {
return c.instanceID == math.MaxUint64 && c.value != nil
}
func (c *commitCtx) getCommitValue() []byte {
return c.value
}
func (c *commitCtx) startCommit(instanceID uint64) {
c.slock.lock()
defer c.slock.unlock()
c.instanceID = instanceID
}
func (c *commitCtx) isMyCommit(instanceID uint64, learnValue []byte) (*SMCtx, bool) {
c.slock.lock()
defer c.slock.unlock()
isMyCommit := false
if !c.isCommitEnd && c.instanceID == instanceID {
isMyCommit = bytes.Equal(learnValue, c.value)
}
if isMyCommit {
return c.smCtx, true
}
return nil, isMyCommit
}
func (c *commitCtx) setResultOnlyRet(commitRet int32) {
c.setResult(commitRet, math.MaxUint64, nil)
}
func (c *commitCtx) setResult(commitRet int32, instanceID uint64, learnValue []byte) {
c.slock.lock()
if c.isCommitEnd || c.instanceID != instanceID {
c.slock.unlock()
return
}
c.commitRet = commitRet
if c.commitRet == 0 {
if !bytes.Equal(learnValue, c.value) {
c.commitRet = int32(paxosTryCommitRet_Conflict)
}
}
c.isCommitEnd = true
c.value = nil
c.slock.unlock()
c.slock.interrupt()
}
func (c *commitCtx) getResult() (uint64, int32) {
c.slock.lock()
defer c.slock.unlock()
var succInstanceID uint64
for !c.isCommitEnd {
c.slock.waitTime(time.Millisecond * 1000)
}
if c.commitRet == 0 {
succInstanceID = c.instanceID
lPLGImp(c.conf.groupIdx, "commit success, instanceid %d", succInstanceID)
} else {
lPLGErr(c.conf.groupIdx, "commit fail, error: %d", c.commitRet)
}
return succInstanceID, c.commitRet
}
func (c *commitCtx) setCommitValue(value []byte) {
c.value = value
}
func (c *commitCtx) getTimeoutMs() int {
return c.timeoutMs
}