-
Notifications
You must be signed in to change notification settings - Fork 548
/
equinix.go
470 lines (384 loc) · 12.6 KB
/
equinix.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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// Package equinixmetal contains the Equinix Metal implementation of the [platform.Platform].
package equinixmetal
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/netip"
"slices"
"time"
"github.com/cosi-project/runtime/pkg/safe"
"github.com/cosi-project/runtime/pkg/state"
"github.com/siderolabs/gen/maps"
"github.com/siderolabs/go-procfs/procfs"
"github.com/siderolabs/go-retry/retry"
networkadapter "github.com/siderolabs/talos/internal/app/machined/pkg/adapters/network"
"github.com/siderolabs/talos/internal/app/machined/pkg/runtime"
"github.com/siderolabs/talos/internal/app/machined/pkg/runtime/v1alpha1/platform/errors"
"github.com/siderolabs/talos/internal/app/machined/pkg/runtime/v1alpha1/platform/internal/netutils"
"github.com/siderolabs/talos/pkg/download"
"github.com/siderolabs/talos/pkg/machinery/constants"
"github.com/siderolabs/talos/pkg/machinery/nethelpers"
"github.com/siderolabs/talos/pkg/machinery/resources/network"
runtimeres "github.com/siderolabs/talos/pkg/machinery/resources/runtime"
)
// Event holds data to pass to the Equinix Metal event URL.
type Event struct {
Type string `json:"type"`
Message string `json:"msg"`
}
// Network holds network info from the equinixmetal metadata.
type Network struct {
Bonding Bonding `json:"bonding"`
Interfaces []Interface `json:"interfaces"`
Addresses []Address `json:"addresses"`
}
// Bonding holds bonding info from the equinixmetal metadata.
type Bonding struct {
Mode int `json:"mode"`
}
// Interface holds interface info from the equinixmetal metadata.
type Interface struct {
Name string `json:"name"`
MAC string `json:"mac"`
Bond string `json:"bond"`
}
// Address holds address info from the equinixmetal metadata.
type Address struct {
Public bool `json:"public"`
Management bool `json:"management"`
Enabled bool `json:"enabled"`
CIDR int `json:"cidr"`
Family int `json:"address_family"`
Netmask string `json:"netmask"`
Network string `json:"network"`
Address string `json:"address"`
Gateway string `json:"gateway"`
}
// BGPNeighbor holds BGP neighbor info from the equinixmetal metadata.
type BGPNeighbor struct {
AddressFamily int `json:"address_family"`
PeerIPs []string `json:"peer_ips"`
}
const (
// EquinixMetalUserDataEndpoint is the local metadata endpoint for Equinix.
EquinixMetalUserDataEndpoint = "https://metadata.platformequinix.com/userdata"
// EquinixMetalMetaDataEndpoint is the local endpoint for machine info like networking.
EquinixMetalMetaDataEndpoint = "https://metadata.platformequinix.com/metadata"
)
// EquinixMetal is a platform for EquinixMetal Metal cloud.
type EquinixMetal struct{}
// Name implements the platform.Platform interface.
func (p *EquinixMetal) Name() string {
return "equinixMetal"
}
// Configuration implements the platform.Platform interface.
func (p *EquinixMetal) Configuration(ctx context.Context, r state.State) ([]byte, error) {
if err := netutils.Wait(ctx, r); err != nil {
return nil, err
}
log.Printf("fetching machine config from: %q", EquinixMetalUserDataEndpoint)
return download.Download(ctx, EquinixMetalUserDataEndpoint,
download.WithErrorOnNotFound(errors.ErrNoConfigSource),
download.WithErrorOnEmptyResponse(errors.ErrNoConfigSource))
}
// Mode implements the platform.Platform interface.
func (p *EquinixMetal) Mode() runtime.Mode {
return runtime.ModeMetal
}
// KernelArgs implements the runtime.Platform interface.
func (p *EquinixMetal) KernelArgs(arch string) procfs.Parameters {
switch arch {
case "amd64":
return []*procfs.Parameter{
procfs.NewParameter("console").Append("ttyS1,115200n8"),
}
case "arm64":
return []*procfs.Parameter{
procfs.NewParameter("console").Append("ttyAMA0,115200"),
}
default:
return nil
}
}
// ParseMetadata converts Equinix Metal metadata into Talos network configuration.
//
//nolint:gocyclo,cyclop
func (p *EquinixMetal) ParseMetadata(ctx context.Context, equinixMetadata *MetadataConfig, st state.State) (*runtime.PlatformNetworkConfig, error) {
networkConfig := &runtime.PlatformNetworkConfig{}
// 1. Links
// translate the int returned from bond mode metadata to the type needed by network resources
bondMode := nethelpers.BondMode(uint8(equinixMetadata.Network.Bonding.Mode))
hostInterfaces, err := safe.StateListAll[*network.LinkStatus](ctx, st)
if err != nil {
return nil, fmt.Errorf("error listing host interfaces: %w", err)
}
bondSlaveIndexes := map[string]int{}
firstBond := ""
for _, iface := range equinixMetadata.Network.Interfaces {
if iface.Bond == "" {
continue
}
if firstBond == "" {
firstBond = iface.Bond
}
found := false
for hostInterface := range hostInterfaces.All() {
// match using permanent MAC address:
// - bond interfaces don't have permanent addresses set, so we skip them this way
// - if the bond is already configured, regular hardware address is overwritten with bond address
if hostInterface.TypedSpec().PermanentAddr.String() == iface.MAC {
found = true
slaveIndex := bondSlaveIndexes[iface.Bond]
networkConfig.Links = append(networkConfig.Links,
network.LinkSpecSpec{
Name: hostInterface.Metadata().ID(),
Up: true,
BondSlave: network.BondSlave{
MasterName: iface.Bond,
SlaveIndex: slaveIndex,
},
ConfigLayer: network.ConfigPlatform,
})
bondSlaveIndexes[iface.Bond]++
break
}
}
if !found {
log.Printf("interface with MAC %q wasn't found on the host, adding with the name from metadata", iface.MAC)
slaveIndex := bondSlaveIndexes[iface.Bond]
networkConfig.Links = append(networkConfig.Links,
network.LinkSpecSpec{
ConfigLayer: network.ConfigPlatform,
Name: iface.Name,
Up: true,
BondSlave: network.BondSlave{
MasterName: iface.Bond,
SlaveIndex: slaveIndex,
},
})
bondSlaveIndexes[iface.Bond]++
}
}
bondNames := maps.Keys(bondSlaveIndexes)
slices.Sort(bondNames)
for _, bondName := range bondNames {
bondLink := network.LinkSpecSpec{
ConfigLayer: network.ConfigPlatform,
Name: bondName,
Logical: true,
Up: true,
Kind: network.LinkKindBond,
Type: nethelpers.LinkEther,
BondMaster: network.BondMasterSpec{
Mode: bondMode,
DownDelay: 200,
MIIMon: 100,
UpDelay: 200,
HashPolicy: nethelpers.BondXmitPolicyLayer34,
},
}
networkadapter.BondMasterSpec(&bondLink.BondMaster).FillDefaults()
networkConfig.Links = append(networkConfig.Links, bondLink)
}
// 2. addresses
var publicIPs []string
for _, addr := range equinixMetadata.Network.Addresses {
if !(addr.Enabled && addr.Management) {
continue
}
if addr.Public {
publicIPs = append(publicIPs, addr.Address)
}
ipAddr, err := netip.ParsePrefix(fmt.Sprintf("%s/%d", addr.Address, addr.CIDR))
if err != nil {
return nil, err
}
family := nethelpers.FamilyInet4
if ipAddr.Addr().Is6() {
family = nethelpers.FamilyInet6
}
networkConfig.Addresses = append(networkConfig.Addresses,
network.AddressSpecSpec{
ConfigLayer: network.ConfigPlatform,
LinkName: firstBond,
Address: ipAddr,
Scope: nethelpers.ScopeGlobal,
Flags: nethelpers.AddressFlags(nethelpers.AddressPermanent),
Family: family,
},
)
}
for _, ipStr := range publicIPs {
if ip, err := netip.ParseAddr(ipStr); err == nil {
networkConfig.ExternalIPs = append(networkConfig.ExternalIPs, ip)
}
}
// 3. routes
var privateGateway netip.Addr
for _, addr := range equinixMetadata.Network.Addresses {
if !(addr.Enabled && addr.Management) {
continue
}
ipAddr, err := netip.ParsePrefix(fmt.Sprintf("%s/%d", addr.Address, addr.CIDR))
if err != nil {
return nil, err
}
family := nethelpers.FamilyInet4
if ipAddr.Addr().Is6() {
family = nethelpers.FamilyInet6
}
if addr.Public {
// for "Public" address add the default route
gw, err := netip.ParseAddr(addr.Gateway)
if err != nil {
return nil, err
}
route := network.RouteSpecSpec{
ConfigLayer: network.ConfigPlatform,
Gateway: gw,
OutLinkName: firstBond,
Table: nethelpers.TableMain,
Protocol: nethelpers.ProtocolStatic,
Type: nethelpers.TypeUnicast,
Family: family,
Priority: network.DefaultRouteMetric,
}
if addr.Family == 6 {
route.Priority = 2 * network.DefaultRouteMetric
}
route.Normalize()
networkConfig.Routes = append(networkConfig.Routes, route)
} else {
// for "Private" addresses, we add a route that goes out the gateway for the private subnets.
for _, privSubnet := range equinixMetadata.PrivateSubnets {
gw, err := netip.ParseAddr(addr.Gateway)
if err != nil {
return nil, err
}
privateGateway = gw
dest, err := netip.ParsePrefix(privSubnet)
if err != nil {
return nil, err
}
route := network.RouteSpecSpec{
ConfigLayer: network.ConfigPlatform,
Gateway: gw,
Destination: dest,
OutLinkName: firstBond,
Table: nethelpers.TableMain,
Protocol: nethelpers.ProtocolStatic,
Type: nethelpers.TypeUnicast,
Family: family,
}
route.Normalize()
networkConfig.Routes = append(networkConfig.Routes, route)
}
}
}
// 4. hostname
if equinixMetadata.Hostname != "" {
hostnameSpec := network.HostnameSpecSpec{
ConfigLayer: network.ConfigPlatform,
}
if err := hostnameSpec.ParseFQDN(equinixMetadata.Hostname); err != nil {
return nil, err
}
networkConfig.Hostnames = append(networkConfig.Hostnames, hostnameSpec)
}
// 5. platform metadata
networkConfig.Metadata = &runtimeres.PlatformMetadataSpec{
Platform: p.Name(),
Hostname: equinixMetadata.Hostname,
Region: equinixMetadata.Metro,
Zone: equinixMetadata.Facility,
InstanceType: equinixMetadata.Plan,
InstanceID: equinixMetadata.ID,
ProviderID: fmt.Sprintf("equinixmetal://%s", equinixMetadata.ID),
}
// 6. BGP neighbors
for _, bgpNeighbor := range equinixMetadata.BGPNeighbors {
if bgpNeighbor.AddressFamily != 4 {
continue
}
for _, peerIP := range bgpNeighbor.PeerIPs {
peer, err := netip.ParseAddr(peerIP)
if err != nil {
return nil, err
}
route := network.RouteSpecSpec{
ConfigLayer: network.ConfigPlatform,
Gateway: privateGateway,
Destination: netip.PrefixFrom(peer, 32),
OutLinkName: firstBond,
Table: nethelpers.TableMain,
Protocol: nethelpers.ProtocolStatic,
Type: nethelpers.TypeUnicast,
Family: nethelpers.FamilyInet4,
}
route.Normalize()
networkConfig.Routes = append(networkConfig.Routes, route)
}
}
return networkConfig, nil
}
// NetworkConfiguration implements the runtime.Platform interface.
func (p *EquinixMetal) NetworkConfiguration(ctx context.Context, st state.State, ch chan<- *runtime.PlatformNetworkConfig) error {
log.Printf("fetching equinix network config from: %q", EquinixMetalMetaDataEndpoint)
metadataConfig, err := download.Download(ctx, EquinixMetalMetaDataEndpoint)
if err != nil {
return err
}
var meta MetadataConfig
if err = json.Unmarshal(metadataConfig, &meta); err != nil {
return err
}
networkConfig, err := p.ParseMetadata(ctx, &meta, st)
if err != nil {
return err
}
select {
case <-ctx.Done():
return ctx.Err()
case ch <- networkConfig:
}
return nil
}
// FireEvent will take an event and pass it to an events server.
// nb: This is currently only used with Equinix Metal but we may find interesting ways
// to extend it for other event servers (Azure may have something similar?)
func (p *EquinixMetal) FireEvent(ctx context.Context, event Event) error {
var eventURL *string
if eventURL = procfs.ProcCmdline().Get(constants.KernelParamEquinixMetalEvents).First(); eventURL == nil {
return errors.ErrNoEventURL
}
eventData, err := json.Marshal(event)
if err != nil {
return err
}
err = retry.Constant(5*time.Minute,
retry.WithUnits(time.Second),
retry.WithErrorLogging(true)).RetryWithContext(
ctx,
func(ctx context.Context) error {
req, reqErr := http.NewRequestWithContext(ctx, http.MethodPost, *eventURL, bytes.NewReader(eventData))
if reqErr != nil {
return reqErr
}
resp, reqErr := http.DefaultClient.Do(req)
if resp != nil {
io.Copy(io.Discard, io.LimitReader(resp.Body, 4*1024*1024)) //nolint:errcheck
resp.Body.Close() //nolint:errcheck
}
return retry.ExpectedError(reqErr)
},
)
return err
}