-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnodes.go
398 lines (347 loc) · 8.71 KB
/
nodes.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package labomatic
import (
"errors"
"fmt"
"hash/maphash"
"iter"
"net/netip"
"path/filepath"
"slices"
"strconv"
"strings"
"go.starlark.net/starlark"
)
var NetBlocks = starlark.StringDict{
"Router": starlark.NewBuiltin("Router", NewRouter),
"CyberSwitch": starlark.NewBuiltin("CyberSwitch", NewSwitch),
"Asset": starlark.NewBuiltin("CyberSwitch", NewAsset),
"Subnet": starlark.NewBuiltin("Subnet", NewSubnet),
"Outnet": starlark.NewBuiltin("Outnet", NewNATLAN),
"dhcp_options": dhcpOptions,
"Addr": starlark.NewBuiltin("Addr", NewAddr),
}
func NewRouter(th *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var (
name string
)
if err := starlark.UnpackArgs("Router", args, kwargs,
"name?", &name,
); err != nil {
return starlark.None, fmt.Errorf("invalid constructor argument: %w", err)
}
switch {
case len(name) > 8:
return starlark.None, fmt.Errorf("node names must be <8 characters")
case name == "":
name = fmt.Sprintf("r%d", routerCount)
routerCount++
}
return &netnode{
name: name,
typ: nodeRouter,
}, nil
}
func NewSwitch(th *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var (
name string
image string
media string
)
if err := starlark.UnpackArgs("CyberSwitch", args, kwargs,
"name?", &name,
"image?", &image,
"media?", &media); err != nil {
return starlark.None, fmt.Errorf("invalid constructor argument: %w", err)
}
switch {
case len(name) > 8:
return starlark.None, fmt.Errorf("node names must be <8 characters")
case name == "":
name = fmt.Sprintf("r%d", routerCount)
routerCount++
}
if !filepath.IsAbs(image) {
wd := th.Local("workdir").(string)
image = filepath.Join(wd, image)
}
return &netnode{
name: name,
typ: nodeSwitch,
uefi: true,
image: image,
media: media,
}, nil
}
func NewAsset(th *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var (
name string
)
if err := starlark.UnpackArgs("CyberSwitch", args, kwargs,
"name?", &name); err != nil {
return starlark.None, fmt.Errorf("invalid constructor argument: %w", err)
}
if len(name) > 8 {
return starlark.None, fmt.Errorf("node names must be <8 characters")
}
if name == "" {
name = fmt.Sprintf("a%d", assetCount)
assetCount++
}
return &netnode{
name: name,
typ: nodeAsset,
uefi: true,
}, nil
}
const (
nodeRouter = iota
nodeSwitch
nodeAsset
)
// TODO check name conflict with user inputs or other modules (starlark threads)
var (
routerCount = 1
assetCount = 1
)
type netnode struct {
name string
typ int
frozen bool
image string // image on disk
uefi bool
media string // additional disk
init string
ifcs []*netiface
}
var hseed = maphash.MakeSeed()
func (r *netnode) Freeze() { r.frozen = true }
func (r netnode) Hash() (uint32, error) { return uint32(maphash.String(hseed, r.name)), nil }
func (r netnode) String() string {
switch r.typ {
default:
panic("invalid host")
case nodeRouter:
return "<router> " + r.name
case nodeSwitch:
return "<switch>" + r.name
case nodeAsset:
return "<asset>" + r.name
}
}
func (netnode) Truth() starlark.Bool { return true }
func (netnode) Type() string { return "netnode" }
func (r *netnode) Attr(name string) (starlark.Value, error) {
switch name {
case "attach_nic":
return attach_iface.BindReceiver(r), nil
case "name":
return starlark.String(r.name), nil
}
if idx := slices.IndexFunc(r.ifcs, func(iface *netiface) bool { return iface.name == name }); idx != -1 {
return r.ifcs[idx], nil
}
return nil, starlark.NoSuchAttrError(name)
}
func (r netnode) AttrNames() (attrs []string) {
for i := range len(r.ifcs) {
attrs = append(attrs, r.ifcs[i].name)
}
return append(attrs,
"name",
"init_script",
"attach_iface",
)
}
var attach_iface = starlark.NewBuiltin("attach_nic", func(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
nd, ok := fn.Receiver().(*netnode)
if !ok {
return starlark.None, fmt.Errorf("attach method called on wrong object")
}
var (
net *subnet
addr Addr
)
if err := starlark.UnpackArgs("attach_nic", args, kwargs,
"net", &net,
"addr?", &addr,
); err != nil {
return starlark.None, err
}
if len(nd.ifcs) == 9 {
return starlark.None, errors.New("only 9 interfaces can be added")
}
if net.nat && !netip.Addr(addr).IsValid() {
return starlark.None, errors.New("Outnet links must be statically addressed")
}
// TODO use MAC address instead
var ifname string
switch nd.typ {
case nodeSwitch, nodeAsset:
const pciOffset = 0
ifname = fmt.Sprintf("eth%d", len(nd.ifcs))
case nodeRouter:
const pciOffset = 2 // but it might differ between laptops ???
ifname = fmt.Sprintf("ether%d", len(nd.ifcs)+pciOffset)
}
ifc := &netiface{name: ifname, host: nd, net: net, addr: addr}
nd.ifcs = append(nd.ifcs, ifc)
net.mbs = append(net.mbs, ifc)
return ifc, nil
})
func parseEther(s string) (int, bool) {
if !strings.HasPrefix(s, "ether") {
return 0, false
}
v, err := strconv.Atoi(s[len("ether"):])
return v, err == nil
}
func (r *netnode) SetField(name string, val starlark.Value) error {
if r.frozen {
return errors.New("modified frozen data")
}
switch name {
default:
return starlark.NoSuchAttrError(name)
case "name":
r.name = val.String()
case "init_script":
ss, ok := val.(starlark.String)
if !ok {
return errors.New("invalid type for init script (want string)")
}
r.init = ss.GoString()
}
return nil
}
func (r *netnode) agent() GuestAgent {
switch r.typ {
case nodeRouter:
return chr{}
case nodeSwitch:
return csw{}
case nodeAsset:
return csw{}
default:
panic("unknown node type")
}
}
type netiface struct {
name string
frozen bool
host *netnode
net *subnet
addr Addr
}
func (r *netiface) Freeze() { r.frozen = true }
func (r netiface) Hash() (uint32, error) { return uint32(maphash.String(hseed, r.name)), nil }
func (r netiface) String() string { return r.name }
func (netiface) Truth() starlark.Bool { return true }
func (netiface) Type() string { return "netiface" }
func (r netiface) AttrNames() []string {
attrs := []string{"host", "name", "net"}
if netip.Addr(r.addr).IsValid() {
attrs = append(attrs, "addr")
}
return attrs
}
func (r netiface) Attr(name string) (starlark.Value, error) {
switch name {
default:
return starlark.None, starlark.NoSuchAttrError(name)
case "addr":
return r.addr, nil
case "host":
return r.host, nil
case "name":
return starlark.String(r.name), nil
case "net":
return r.net, nil
}
}
func OfType(t int) func(n *netnode) bool { return func(n *netnode) bool { return n.typ == t } }
// nodeof returns an iterator over the exported nodes in the configuration script.
// if the well-known boot_order variable is set, then nodes are those in the list, in order.
// if not, all nodes are provided, in random order
func nodesof(globals starlark.StringDict, filters ...func(*netnode) bool) iter.Seq[*netnode] {
order, ok := globals["boot_order"]
if ok {
return func(yield func(*netnode) bool) {
lo, ok := order.(*starlark.List)
if !ok {
}
for n := range lo.Elements() {
n, ok := n.(*netnode)
if !ok || nomatch(filters, n) {
continue
}
if !yield(n) {
return
}
}
}
} else {
return func(yield func(*netnode) bool) {
for _, node := range globals {
n, ok := node.(*netnode)
if !ok || nomatch(filters, n) {
continue
}
if !yield(n) {
return
}
}
}
}
}
func nomatch[T any](fs []func(T) bool, v T) bool {
for _, f := range fs {
if f(v) {
return false
}
}
return true
}
// TemplateNode is the data structure passed to node init templates.
// Fields are populated from the initial Starlark configuration.
type TemplateNode struct {
// Name is the fully qualified name of the
Name string
Image string
// List of network interfaces
Interfaces []struct {
Name string
Address netip.Addr
Network netip.Prefix
LinkOnly bool
NATed bool
}
Host struct {
PubKey string
}
}
func (n *netnode) ToTemplate() TemplateNode {
pub, err := gensshkeypair()
if err != nil {
panic("cannot generate key pair: " + err.Error())
}
t := TemplateNode{
Name: n.name,
Host: struct{ PubKey string }{string(pub)},
}
for _, iface := range n.ifcs {
t.Interfaces = append(t.Interfaces, struct {
Name string
Address netip.Addr
Network netip.Prefix
LinkOnly bool
NATed bool
}{
Name: iface.name,
Address: netip.Addr(iface.addr),
Network: iface.net.network,
LinkOnly: iface.net.linkonly,
NATed: iface.net.nat,
})
}
return t
}