-
Notifications
You must be signed in to change notification settings - Fork 2
/
netlink.go
123 lines (104 loc) · 2.46 KB
/
netlink.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
package nbd
import (
"github.com/mdlayher/genetlink"
"github.com/mdlayher/netlink"
)
type NetlinkConn struct {
conn *genetlink.Conn
family genetlink.Family
index int
fd int
sizeBytes uint64
blockSizeBytes uint64
readOnly bool
supportsTrim bool
supportsFlush bool
}
func NewNetlinkConn(index int) (*NetlinkConn, error) {
conn, err := genetlink.Dial(&netlink.Config{Strict: true})
if err != nil {
return nil, err
}
family, err := conn.GetFamily(nbdNlFamilyName)
if err != nil {
conn.Close()
return nil, err
}
return &NetlinkConn{conn: conn, family: family, index: index}, nil
}
func (c *NetlinkConn) SetFd(fd int) {
c.fd = fd
}
func (c *NetlinkConn) SetSize(size uint64) {
c.sizeBytes = size
}
func (c *NetlinkConn) SetBlockSize(size uint64) {
c.blockSizeBytes = size
}
func (c *NetlinkConn) SetReadonly(ro bool) {
c.readOnly = ro
}
func (c *NetlinkConn) SetSupportsTrim(trim bool) {
c.supportsTrim = trim
}
func (c *NetlinkConn) SetSupportsFlush(flush bool) {
c.supportsFlush = flush
}
func (c *NetlinkConn) Connect() error {
enc := netlink.NewAttributeEncoder()
enc.Uint32(nbdNlAttrIndex, uint32(c.index))
enc.Uint64(nbdNlAttrSizeBytes, c.sizeBytes)
enc.Uint64(nbdNlAttrBlockSizeBytes, c.blockSizeBytes)
enc.Uint64(nbdNlAttrClientFlags, nbdClientFlagDestroyOnDisconnect)
var flags uint64
if c.readOnly {
flags |= nbdFlagReadOnly
}
if c.supportsTrim {
flags |= nbdFlagSendTrim
}
if c.supportsFlush {
flags |= nbdFlagSendFlush
}
if flags != 0 {
enc.Uint64(nbdNlAttrServerFlags, flags)
}
enc.Nested(nbdNlAttrSockets, func(nae *netlink.AttributeEncoder) error {
nae.Nested(nbdNlSockItem, func(nae *netlink.AttributeEncoder) error {
nae.Uint32(nbdNlSockFd, uint32(c.fd))
return nil
})
return nil
})
buf, err := enc.Encode()
if err != nil {
return err
}
req := genetlink.Message{
Header: genetlink.Header{
Command: nbdNlCmdConnect,
Version: c.family.Version,
},
Data: buf,
}
_, err = c.conn.Execute(req, c.family.ID, netlink.Request)
return err
}
func (c *NetlinkConn) Disconnect() error {
enc := netlink.NewAttributeEncoder()
// TODO: Use correct index if auto-discovered
enc.Uint32(nbdNlAttrIndex, uint32(c.index))
buf, err := enc.Encode()
if err != nil {
return err
}
req := genetlink.Message{
Header: genetlink.Header{
Command: nbdNlCmdDisconnect,
Version: c.family.Version,
},
Data: buf,
}
_, err = c.conn.Send(req, c.family.ID, netlink.Request)
return err
}