-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathdistributed_lock_node.go
134 lines (111 loc) · 2.35 KB
/
distributed_lock_node.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
package main
import (
"bufio"
"fmt"
"io"
"strings"
"sync"
"github.com/reconquest/hierr-go"
"github.com/reconquest/lineflushwriter-go"
"github.com/reconquest/prefixwriter-go"
"github.com/reconquest/runcmd"
)
const (
lockAcquiredString = `acquired`
lockLockedString = `locked`
)
type distributedLockNode struct {
address address
runner runcmd.Runner
connection *distributedLockConnection
}
func (node *distributedLockNode) String() string {
return node.address.String()
}
type distributedLockConnection struct {
stdin io.WriteCloser
stdout io.Reader
}
func (node *distributedLockNode) lock(
filename string,
) error {
lockCommandLine := []string{
"sh", "-c", fmt.Sprintf(
`flock -nx %s -c 'printf "%s\n" && cat' || printf "%s\n"`,
filename, lockAcquiredString, lockLockedString,
),
}
logMutex := &sync.Mutex{}
traceln(hierr.Errorf(
lockCommandLine,
`%s running lock command`,
node,
))
lockCommand := node.runner.Command(
lockCommandLine[0],
lockCommandLine[1:]...,
)
stdout, err := lockCommand.StdoutPipe()
if err != nil {
return hierr.Errorf(
err,
`can't get control stdout pipe from lock process`,
)
}
stderr := lineflushwriter.New(
prefixwriter.New(
newDebugWriter(logger),
fmt.Sprintf("%s {flock} <stderr> ", node.String()),
),
logMutex,
true,
)
lockCommand.SetStderr(stderr)
stdin, err := lockCommand.StdinPipe()
if err != nil {
return hierr.Errorf(
err,
`can't get control stdin pipe to lock process`,
)
}
err = lockCommand.Start()
if err != nil {
return hierr.Errorf(
err,
`%s can't start lock command: '%s`,
node, lockCommandLine,
)
}
line, err := bufio.NewReader(stdout).ReadString('\n')
if err != nil {
return hierr.Errorf(
err,
`%s can't read lock status line from lock process`,
node,
)
}
switch strings.TrimSpace(line) {
case lockAcquiredString:
// pass
case lockLockedString:
return fmt.Errorf(
`%s can't acquire lock, `+
`lock already obtained by another process `+
`or unavailable`,
node,
)
default:
return fmt.Errorf(
`%s unexpected reply string encountered `+
`instead of '%s' or '%s': '%s'`,
node, lockAcquiredString, lockLockedString,
line,
)
}
tracef(`lock acquired: '%s' on '%s'`, node, filename)
node.connection = &distributedLockConnection{
stdin: stdin,
stdout: stdout,
}
return nil
}