-
Notifications
You must be signed in to change notification settings - Fork 0
/
sink.go
278 lines (241 loc) · 7.27 KB
/
sink.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// Copyright © 2024 Ken Robertson <[email protected]>
package main
import (
"fmt"
"io"
"log"
"net"
"os"
"path/filepath"
"sync"
"syscall"
"time"
"github.com/brk0v/directio"
"github.com/dustin/go-humanize"
)
type sink struct {
sortedGroups []*plotGroup
sortMutex sync.RWMutex
cacheGroup *plotGroup
listener net.Listener
wg sync.WaitGroup
}
// newSink will create a the sink server process and validate all of
// the provided plot paths. It will return an error if any of the paths do not
// exist, or are not a directory.
func newSink(cfg *config) (*sink, error) {
s := &sink{
sortedGroups: make([]*plotGroup, 0),
}
// populate cache settings
cfg.Cache.name = "cache"
cacheGroup, err := newPlotGroup(cfg.Cache, true)
if err != nil {
return nil, fmt.Errorf("failed to initialize cache group: %v", err)
}
s.cacheGroup = cacheGroup
s.cacheGroup.sortCachePaths()
// populage destination groups
for n, dst := range cfg.Destinations {
dst.name = n
pg, err := newPlotGroup(dst, false)
if err != nil {
return nil, fmt.Errorf("failed to initialize destination group: %v", err)
}
s.sortedGroups = append(s.sortedGroups, pg)
}
// bind to the port
l, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
log.Fatal("Failed to bind to port", err)
}
log.Printf("Listening on %d...", port)
s.listener = l
return s, nil
}
// handleConnection faciliates the transfer of plot files from the plotters to
// the sink. It encapculates a single request and is ran within its own
// goroutine.
func (s *sink) handleConnection(conn net.Conn) {
s.wg.Add(1)
defer s.wg.Done()
// receive the file size bytes
sizeBytes := make([]byte, 8)
_, err := conn.Read(sizeBytes)
if err != nil {
log.Printf("Failed to receive file size: %v", err)
conn.Close()
return
}
size := convertBytesToUInt64(sizeBytes)
// pick a plot. This should return the one with the most free space that
// isn't busy. we want to lock early
pg, plot := s.pickPlot(size)
if plot == nil {
conn.Close()
log.Printf("Request to store plot, but no eligible plot found (%s / %s)", humanize.Bytes(size), humanize.Bytes(plot.freeSpace))
return
}
// try and lock. This is mostly to protect against a hypothetical race
// condition where a second connection could pick the same plot before it is
// locked and marked busy.
//
// Even if this was hit, it would self resolve once the first transfer was
// done, but would cause a slowdown and lower overall throughput.
if !plot.mutex.TryLock() {
conn.Close()
log.Print("Lock race condition hit! Closing and returning.")
return
}
// lock and handle stuff, there is a lot
defer plot.mutex.Unlock()
plot.busy.Store(true)
defer plot.busy.Store(false)
s.cacheGroup.transfers.Add(1)
defer s.cacheGroup.transfers.Add(-1)
pg.transfers.Add(1)
defer s.sortGroups()
defer pg.transfers.Add(-1)
s.sortGroups()
// pick the cache plot
cachePlot := s.cacheGroup.pickPlot(size)
if cachePlot == nil {
conn.Close()
log.Print("Failed to get a cache plot to use")
return
}
cachePlot.transfers.Add(1)
defer s.cacheGroup.sortCachePaths()
defer cachePlot.transfers.Add(-1)
s.cacheGroup.sortCachePaths()
// transfer the file to fast local storage
filename, tmpfile, ok := s.handleTransfer(conn, cachePlot, plot)
if !ok {
// conn already closed
return
}
// move it to final disk
ok = s.handleMove(plot, filename, tmpfile)
if ok {
os.Remove(tmpfile)
}
// update free space
plot.updateFreeSpace()
cachePlot.updateFreeSpace()
pg.sortPaths()
}
// handleTransfer takes care of receiving the plot from the remote host and
// storing on the temporary NVME/SSDs. It returns the filename of the plot, the
// path to the temp storage location, and a bool indicating success. At the end,
// it closes the remote connection regardless of success.
func (s *sink) handleTransfer(conn net.Conn, cachePlot, plot *plotPath) (string, string, bool) {
defer conn.Close()
// send response acknowledging to continue
conn.Write([]byte{1})
// receive filename length
fnlenBytes := make([]byte, 2)
_, err := conn.Read(fnlenBytes)
if err != nil {
log.Printf("Failed to receive filename length: %v", err)
return "", "", false
}
fnlen := convertBytesToInt16(fnlenBytes)
// receive filename
filenameBytes := make([]byte, fnlen)
_, err = conn.Read(filenameBytes)
if err != nil {
log.Printf("Failed to receive filename: %v", err)
return "", "", false
}
filename := string(filenameBytes)
// open the file and transfer
tmpfile := filepath.Join(cachePlot.path, filename+".tmp")
os.Remove(tmpfile)
f, err := os.Create(tmpfile)
if err != nil {
log.Printf("Failed to open file at %s: %v", tmpfile, err)
return "", "", false
}
defer f.Close()
// perform the copy
log.Printf("Receiving plot %s from %s", filename, conn.RemoteAddr().String())
start := time.Now()
bytes, err := io.Copy(f, conn)
if err != nil {
log.Printf("Failure while writing plot %s: %v", tmpfile, err)
f.Close()
os.Remove(tmpfile)
plot.pause()
return "", "", false
}
// rename it so we know it was completed
dstfile := filepath.Join(cachePlot.path, filename)
err = os.Rename(tmpfile, dstfile)
if err != nil {
log.Printf("Failed to rename temp plot %s: %v", tmpfile, err)
f.Close()
os.Remove(tmpfile)
plot.pause()
return "", "", false
}
// log successful and some metrics
seconds := time.Since(start).Seconds()
log.Printf("Successfully stored %s:%s (%s, %f secs, %s/sec)",
conn.RemoteAddr().String(), filename, humanize.IBytes(uint64(bytes)), seconds, humanize.Bytes(uint64(float64(bytes)/seconds)))
cachePlot.updateFreeSpace()
return filename, dstfile, true
}
// handleMove is responsible for moving the plot from the temp location to the
// final hard disk. It returns a bool to indicate success. On success, it will
// remove the temp location. On failure, the file should be moved to a reprocess
// queue to try another disk.
func (s *sink) handleMove(plot *plotPath, filename, tmpfile string) bool {
tf, err := os.Open(tmpfile)
if err != nil {
log.Printf("Failed to open tmpfile: %v", err)
return false
}
defer tf.Close()
dstfile := filepath.Join(plot.path, filename)
tmpdstfile := dstfile + ".tmp"
flags := os.O_WRONLY | os.O_EXCL | os.O_CREATE | syscall.O_DIRECT
f, err := os.OpenFile(tmpdstfile, flags, 0644)
if err != nil {
log.Printf("Failed to open dest file: %v", err)
return false
}
// open directio writter
dio, err := directio.NewSize(f, 1048576) // 1MB buffer
if err != nil {
log.Printf("Failed to create directio writter: %v", err)
return false
}
// TODO: handle errors/failures at this point?
// perform the copy
start := time.Now()
bytes, err := io.Copy(dio, tf)
if err != nil {
log.Printf("Failure while moving plot %s: %v", tmpfile, err)
dio.Flush()
f.Close()
os.Remove(tmpdstfile)
plot.pause()
return false
}
// flush and close before rename
dio.Flush()
f.Close()
// rename it so it can be used by the chia harvester
err = os.Rename(tmpdstfile, dstfile)
if err != nil {
log.Printf("Failed to rename final plot %s: %v", tmpdstfile, err)
os.Remove(tmpdstfile)
plot.pause()
return false
}
// success
seconds := time.Since(start).Seconds()
log.Printf("Moved plot %s (%s, %f secs, %s/sec)",
dstfile, humanize.IBytes(uint64(bytes)), seconds, humanize.Bytes(uint64(float64(bytes)/seconds)))
return true
}