-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
371 lines (295 loc) · 7.2 KB
/
main.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package main
import (
"bufio"
"context"
"crypto/rand"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"math"
"net"
"os"
"path/filepath"
"time"
"github.com/pojntfx/go-nbd/pkg/backend"
"github.com/pojntfx/go-nbd/pkg/client"
"github.com/pojntfx/panrpc/go/pkg/rpc"
v1frpc "github.com/pojntfx/r3map/pkg/api/frpc/migration/v1"
v1proto "github.com/pojntfx/r3map/pkg/api/proto/migration/v1"
lbackend "github.com/pojntfx/r3map/pkg/backend"
"github.com/pojntfx/r3map/pkg/chunks"
"github.com/pojntfx/r3map/pkg/migration"
"github.com/pojntfx/r3map/pkg/services"
"github.com/pojntfx/r3map/pkg/utils"
"google.golang.org/grpc"
)
const (
backendTypeFile = "file"
backendTypeMemory = "memory"
backendTypeDirectory = "directory"
)
var (
knownBackendTypes = []string{backendTypeFile, backendTypeMemory, backendTypeDirectory}
errUnknownBackend = errors.New("unknown backend")
)
func main() {
laddr := flag.String("laddr", ":1337", "Listen address")
enableGrpc := flag.Bool("grpc", false, "Whether to use gRPC instead of panrpc")
enableFrpc := flag.Bool("frpc", false, "Whether to use fRPC instead of panrpc")
verbose := flag.Bool("verbose", false, "Whether to enable verbose logging")
size := flag.Int64("size", 536870912, "Size of the memory region or file to allocate")
chunkSize := flag.Int64("chunk-size", client.MaximumBlockSize, "Chunk size to use")
maxChunkSize := flag.Int64("max-chunk-size", services.MaxChunkSize, "Maximum chunk size to support")
bck := flag.String(
"backend",
backendTypeFile,
fmt.Sprintf(
"Backend to use (one of %v)",
knownBackendTypes,
),
)
location := flag.String("location", filepath.Join(os.TempDir(), "local"), "Backend's directory (for directory backend)")
chunking := flag.Bool("chunking", false, "Whether the backend requires to be interfaced with in fixed chunks")
slice := flag.Bool("slice", false, "Whether to use the slice frontend instead of the file frontend")
invalidate := flag.Int("invalidate", 0, "Percentage of chunks (0-100) to invalidate in between Track() and Finalize()")
flag.Parse()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var b backend.Backend
switch *bck {
case backendTypeMemory:
b = backend.NewMemoryBackend(make([]byte, *size))
case backendTypeFile:
file, err := os.CreateTemp("", "")
if err != nil {
panic(err)
}
defer os.RemoveAll(file.Name())
if err := file.Truncate(*size); err != nil {
panic(err)
}
b = backend.NewFileBackend(file)
case backendTypeDirectory:
if err := os.MkdirAll(*location, os.ModePerm); err != nil {
panic(err)
}
b = lbackend.NewDirectoryBackend(*location, *size, *chunkSize, 512, false)
default:
panic(errUnknownBackend)
}
if *chunking {
b = lbackend.NewReaderAtBackend(
chunks.NewArbitraryReadWriterAt(
b,
*chunkSize,
),
(b).Size,
(b).Sync,
false,
)
}
var (
svc *services.SeederService
invalidateLeecher func() error
errs = make(chan error)
)
if *slice {
seeder := migration.NewSliceMigrator(
ctx,
b,
&migration.MigratorOptions{
ChunkSize: *chunkSize,
MaxChunkSize: *maxChunkSize,
Verbose: *verbose,
},
nil,
nil,
nil,
)
go func() {
if err := seeder.Wait(); err != nil {
errs <- err
return
}
close(errs)
}()
defer seeder.Close()
deviceSlice, s, err := seeder.Seed()
if err != nil {
panic(err)
}
invalidateLeecher = func() error {
if _, err := io.CopyN(
utils.NewSliceWriter(deviceSlice),
rand.Reader,
int64(math.Floor(
float64(*size)*(float64(*invalidate)/float64(100)),
)),
); err != nil {
return err
}
return nil
}
svc = s
log.Println("Connected to slice")
} else {
seeder := migration.NewFileMigrator(
ctx,
b,
&migration.MigratorOptions{
ChunkSize: *chunkSize,
MaxChunkSize: *maxChunkSize,
Verbose: *verbose,
},
nil,
nil,
nil,
)
go func() {
if err := seeder.Wait(); err != nil {
errs <- err
return
}
close(errs)
}()
defer seeder.Close()
deviceFile, s, err := seeder.Seed()
if err != nil {
panic(err)
}
invalidateLeecher = func() error {
if _, err := io.CopyN(
deviceFile,
rand.Reader,
int64(math.Floor(
float64(*size)*(float64(*invalidate)/float64(100)),
)),
); err != nil {
return err
}
return nil
}
svc = s
log.Println("Connected on", deviceFile.Name())
}
if *enableGrpc {
server := grpc.NewServer()
v1proto.RegisterSeederServer(server, services.NewSeederServiceGrpc(svc))
lis, err := net.Listen("tcp", *laddr)
if err != nil {
panic(err)
}
defer lis.Close()
log.Println("Seeding on", lis.Addr())
go func() {
if err := server.Serve(lis); err != nil {
if !utils.IsClosedErr(err) {
errs <- err
}
return
}
}()
} else if *enableFrpc {
server, err := v1frpc.NewServer(services.NewSeederServiceFrpc(svc), nil, nil)
if err != nil {
panic(err)
}
log.Println("Seeding on", *laddr)
go func() {
if err := server.Start(*laddr); err != nil {
if !utils.IsClosedErr(err) {
errs <- err
}
return
}
}()
} else {
clients := 0
registry := rpc.NewRegistry[struct{}, json.RawMessage](
svc,
&rpc.RegistryHooks{
OnClientConnect: func(remoteID string) {
clients++
log.Printf("%v clients connected", clients)
},
OnClientDisconnect: func(remoteID string) {
clients--
log.Printf("%v clients connected", clients)
},
},
)
lis, err := net.Listen("tcp", *laddr)
if err != nil {
panic(err)
}
defer lis.Close()
log.Println("Seeding on", lis.Addr())
go func() {
for {
conn, err := lis.Accept()
if err != nil {
if !utils.IsClosedErr(err) {
log.Println("could not accept connection, continuing:", err)
}
continue
}
go func() {
defer func() {
_ = conn.Close()
if err := recover(); err != nil {
if !utils.IsClosedErr(err.(error)) {
log.Printf("Client disconnected with error: %v", err)
}
}
}()
linkCtx, cancelLinkCtx := context.WithCancel(ctx)
defer cancelLinkCtx()
encoder := json.NewEncoder(conn)
decoder := json.NewDecoder(conn)
if err := registry.LinkStream(
linkCtx,
func(v rpc.Message[json.RawMessage]) error {
return encoder.Encode(v)
},
func(v *rpc.Message[json.RawMessage]) error {
return decoder.Decode(v)
},
func(v any) (json.RawMessage, error) {
b, err := json.Marshal(v)
if err != nil {
return nil, err
}
return json.RawMessage(b), nil
},
func(data json.RawMessage, v any) error {
return json.Unmarshal([]byte(data), v)
},
&rpc.LinkHooks{},
); err != nil {
panic(err)
}
}()
}
}()
}
go func() {
log.Println("Press <ENTER> to invalidate resource")
bufio.NewScanner(os.Stdin).Scan()
log.Println("Invalidating resource")
beforeInvalidate := time.Now()
if err := invalidateLeecher(); err != nil {
errs <- err
return
}
afterInvalidate := time.Since(beforeInvalidate)
fmt.Printf("Invalidate: %v\n", afterInvalidate)
}()
for err := range errs {
if err != nil {
panic(err)
}
}
}