-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnsaction.go
253 lines (233 loc) · 7.43 KB
/
nsaction.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
package neslink
import (
"errors"
"fmt"
"os"
"path"
"github.com/vishvananda/netlink"
"github.com/willfantom/nescript"
"github.com/willfantom/nescript/local"
"golang.org/x/sys/unix"
)
// NsAction represents an action that should be executed in a namespace via
// NsDo. The action should have a relevant name as to give context to errors (as
// multiple actions are executed in a single NsDo call). Also the action itself
// should be a function that takes no parameters and returns an error (or nil in
// the event of success). Also noteworthy, if an action function executes logic
// in any other goroutines (either my channel interaction or spawning a new
// goroutine), that logic will not be executed within the expected network
// namespace.
type NsAction struct {
actionName string
f func() error
}
// name simply returns the name of the netns action.
func (nsA NsAction) name() string {
return nsA.actionName
}
// act will execute the given action. This mainly exists to make the source code
// for this package more readable.
func (nsA NsAction) act() error {
return nsA.f()
}
// NAGeneric allows for a custom action (function) to be performed in a given
// network namespace. A name should be given to describe the custom function in
// a couple of words to give context to NsDo errors.
func NAGeneric(name string, function func() error) NsAction {
if name == "" {
name = "unnamed-action"
}
return NsAction{
actionName: name,
f: function,
}
}
// NANewNsAt will create a new network namespace and bind it to a named file in
// a given directory. Note that this will likely result in the netns not being
// visible in the iproute command line. Any action that is performed after this
// action executes successfully will be executed within the new netns.
func NANewNsAt(mountdir, name string) NsAction {
return NsAction{
actionName: "new-ns-at",
f: func() error {
// 1. create the mounting dir if required
if _, err := os.Stat(mountdir); os.IsNotExist(err) {
if err := os.MkdirAll(mountdir, 0o755); err != nil {
return err
}
}
// 2. create the mount file (error if already exists)
mountpath := path.Join(mountdir, name)
if _, err := os.Stat(mountpath); os.IsNotExist(err) {
mf, err := os.OpenFile(mountpath, os.O_CREATE|os.O_EXCL, 0o444)
if err != nil {
return fmt.Errorf("failed to create namespace mount file: %w", err)
}
mf.Close()
} else {
return fmt.Errorf("namespace mount file already exists")
}
// 3. create new ns and move current pid/tid to it
if err := unix.Unshare(unix.CLONE_NEWNET); err != nil {
return fmt.Errorf("failed to create and switch to newnets: %w", err)
}
// 4. bind the new ns to the mount file
ns, _ := NPNow().Provide()
if err := unix.Mount(ns.String(), mountpath, "bind", unix.MS_BIND, ""); err != nil {
return fmt.Errorf("failed to mount new netns to mount file: %w", err)
}
return nil
},
}
}
// NANewNs will create a new network namespace and bind it to a named file. Any
// action that is performed after this action executes successfully will be
// executed within the new netns.
func NANewNs(name string) NsAction {
return NsAction{
actionName: "new-ns-at",
f: func() error {
return NANewNsAt(DefaultMountPath, name).act()
},
}
}
// NASetLinkNs moves a link provided by the given link provider to the namespace
// provided by the ns provider. The link itself should br present in the
// namespace in which the wrapping NsDo is set to execute in.
func NASetLinkNs(lP LinkProvider, nsP NsProvider) NsAction {
return NsAction{
actionName: "set-link-ns",
f: func() error {
link, err := lP.Provide()
if err != nil {
return errors.Join(errNoLink, err)
}
ns, err := nsP.Provide()
if err != nil {
return fmt.Errorf("failed to get target netns for link from provider: %w", err)
}
nsfd, err := ns.open()
if err != nil {
return fmt.Errorf("failed to open target netns for link from provider: %w", err)
}
defer nsfd.close()
return netlink.LinkSetNsFd(link, nsfd.Int())
},
}
}
// NAGetNsFd provides an open file descriptor for the network namespace it is
// called in. This fd is separate from that of the one in the enclosing NsDo, so
// it is up to the user to close the fd when it is no longer needed.
func NAGetNsFd(nsfd *NsFd) NsAction {
return NsAction{
actionName: "get-ns-fd",
f: func() error {
ns, err := NPNow().Provide()
if err != nil {
return fmt.Errorf("failed to get netns from provider: %w", err)
}
fd, err := ns.open()
if err != nil {
return err
}
*nsfd = NsFd(fd)
return nil
},
}
}
// NAExecNescript will execute a NEScript in the netns it is called in, most
// likely the netns of the wrapping NsDo. This opens up extensive custom
// options. Provided should be the already compiled NEScript, a subcommand to
// use for the script such as ["sh" "-c"] (or nil to use the nescript package's
// deafult), and a nescript.Process for the resulting process to be stored in.
func NAExecNescript(script nescript.Script, subcommand []string, process *nescript.Process) NsAction {
return NsAction{
actionName: "exec-nescript",
f: func() error {
p, err := script.Exec(local.Executor("", subcommand))
if err != nil {
return err
}
*process = p
return nil
},
}
}
// NALinks returns a list of all the links in the namespace obtained via the
// given provider. Any errors are returned and a boolean to express if the the
// network namespace has returned back to the origin successfully.
func NALinks(links *[]netlink.Link) NsAction {
return NsAction{
actionName: "get-ns-links",
f: func() error {
l, err := netlink.LinkList()
if err != nil {
return err
}
*links = l
return nil
},
}
}
// NADeleteNamedAt when executed removes the named netns if it exists.
// Importantly, the netns is not removed until the tread exists (at the end of
// the do call).
func NADeleteNamedAt(mountdir, name string) NsAction {
return NsAction{
actionName: "delete-named-ns-at",
f: func() error {
mountpath := path.Join(mountdir, name)
if err := unix.Unmount(mountpath, unix.MNT_DETACH); err != nil {
return fmt.Errorf("failed to unmount netns: %w", err)
}
if err := os.Remove(mountpath); err != nil {
return fmt.Errorf("failed to remove netns mount file: %w", err)
}
return nil
},
}
}
// NADeleteNamed when executed removes the named netns if it exists.
// Importantly, the netns is not removed until the tread exists (at the end of
// the do call).
func NADeleteNamed(name string) NsAction {
return NsAction{
actionName: "delete-named-ns-at",
f: func() error {
return NADeleteNamedAt(DefaultMountPath, name).act()
},
}
}
// NAGetLink gets a specific link from the given link provider when the action
// is called. The result is stored within the given link parameter. An error is
// returned if any occurred.
func NAGetLink(provider LinkProvider, link *netlink.Link) NsAction {
return NsAction{
actionName: "get-ns-link",
f: func() error {
l, err := provider.Provide()
if err != nil {
return err
}
*link = l
return nil
},
}
}
// func NADumpFilepath() NsAction {
// return NsAction{
// actionName: "dump-file-path",
// f: func() error {
// nsfd, err := netns.Get()
// if err != nil {
// return err
// }
// name, err := os.Readlink(fmt.Sprintf("/proc/self/fd/%d", int(nsfd)))
// if err != nil {
// return err
// }
// fmt.Println(name)
// return nil
// },
// }
// }