-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
90 lines (75 loc) · 1.59 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
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"os/signal"
"github.com/chrisvdg/nbdserver/nbd"
"github.com/chrisvdg/nbdserver/nbd/backend"
)
const (
listenAddress = ":7777"
exportName = "default"
totalSize = 1024 * 1024 * 1024
)
func main() {
// create backend
files, err := generateFiles(totalSize)
if err != nil {
log.Fatal(err)
}
// capture interrupt
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
<-c
// cleanup files
cleanupFiles(files)
os.Exit(1)
}()
backend := backend.NewMultiFile(files, uint64(totalSize))
// start server
server := nbd.NewServer(backend)
fmt.Printf("NBD server listening on: `%s`\n", listenAddress)
err = server.ListenAndServe(listenAddress)
if err != nil {
log.Fatal(err)
}
}
// generateFiles generates temporary backend files
// returns a list of those files, the total memory and error
func generateFiles(size int) ([]*os.File, error) {
var files []*os.File
done := false
sizeLeft := size
for !done {
fSize := sizeLeft
// detect last iteration
if sizeLeft < backend.MaxSingleFileSize {
done = true
} else {
fSize = backend.MaxSingleFileSize
}
file, err := ioutil.TempFile(os.TempDir(), "nbd-file")
if err != nil {
cleanupFiles(files)
return nil, err
}
// give files their size
_, err = file.Write(make([]byte, fSize))
if err != nil {
cleanupFiles(files)
return nil, err
}
files = append(files, file)
sizeLeft = sizeLeft - fSize
}
return files, nil
}
func cleanupFiles(files []*os.File) {
for _, f := range files {
f.Close()
os.Remove(f.Name())
}
}