Skip to content

Commit 8472539

Browse files
committed
Add read_host_secret builtin and inject network_data at every lifecycle phase
- New `read_host_secret(field)` starlark builtin that resolves BMH spec secret fields (`userData`, `networkData`, `metaData`, `preprovisioningNetworkData`) on demand from any entry point via `KubeHostSecretResolver` backed by `SecretManager.ObtainSecret`. - New `resolve_ironic_network_data()` starlark helper that fetches IPA network config (preprov secret first, `Spec.NetworkData` fallback) and ensures `network_id` is present on each network entry (required by Ironic schema, omitted by CAPM3). - Ironic `node.network_data` is now synced at six lifecycle points: `create_node`, `build_register_patch`, `prepare`, `provision`, `deprovision`, and `delete`. Signed-off-by: s3rj1k <evasive.gyron@gmail.com>
1 parent ec0cd43 commit 8472539

7 files changed

Lines changed: 238 additions & 25 deletions

File tree

main.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -343,7 +343,15 @@ func main() {
343343
provisionerFactory = &demo.Demo{}
344344
} else if starlarkScript != "" {
345345
ctrl.Log.Info("using starlark provisioner", "script", starlarkScript)
346-
provisionerFactory, err = starlarkprov.NewProvisionerFactory(starlarkScript)
346+
secretResolver := &starlarkprov.KubeHostSecretResolver{
347+
Client: mgr.GetClient(),
348+
SecretManager: secretutils.NewSecretManager(
349+
ctrl.Log.WithName("starlark-secret-resolver"),
350+
mgr.GetClient(),
351+
mgr.GetAPIReader(),
352+
),
353+
}
354+
provisionerFactory, err = starlarkprov.NewProvisionerFactory(starlarkScript, secretResolver)
347355
if err != nil {
348356
setupLog.Error(err, "cannot start starlark provisioner")
349357
os.Exit(1)

pkg/provisioner/starlark/scripts/efi-vmedia.star

Lines changed: 46 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,21 @@ def parse_bmc_address(bmc_addr):
343343
"redfish_system_id": system_id,
344344
}
345345

346+
def resolve_ironic_network_data():
347+
"""Resolve Ironic node.network_data for IPA ramdisk: preprov secret first, then Spec.NetworkData."""
348+
nd_raw = read_host_secret("preprovisioningNetworkData")
349+
if not nd_raw:
350+
nd_raw = read_host_secret("networkData")
351+
if not nd_raw:
352+
return None
353+
nd = yaml_decode(nd_raw)
354+
355+
# Ironic schema requires network_id on each network entry; CAPM3 omits it.
356+
for net in nd.get("networks", []):
357+
if "network_id" not in net:
358+
net["network_id"] = net.get("id", "")
359+
return nd
360+
346361
def create_node(bmc_addr, bmc_user, bmc_password, boot_mac, data):
347362
"""Creates a new node in Ironic via POST /v1/nodes."""
348363
bmc = parse_bmc_address(bmc_addr)
@@ -373,9 +388,9 @@ def create_node(bmc_addr, bmc_user, bmc_password, boot_mac, data):
373388
"cpu_arch": cpu_arch,
374389
},
375390
}
376-
nd_raw = data.get("PreprovisioningNetworkData", "")
377-
if nd_raw:
378-
body["network_data"] = yaml_decode(nd_raw)
391+
nd = resolve_ironic_network_data()
392+
if nd:
393+
body["network_data"] = nd
379394
node, status = http_post("/v1/nodes", body)
380395
if status == 409:
381396
return None, status
@@ -432,11 +447,9 @@ def build_register_patch(node, data, _creds_changed):
432447
ops.append(patch_op("add", "/driver_info/deploy_ramdisk", DEPLOY_RAMDISK_URL))
433448

434449
# Network data for IPA (so it can reach Ironic callback endpoint)
435-
nd_raw = data.get("PreprovisioningNetworkData", "")
436-
if nd_raw:
437-
nd = yaml_decode(nd_raw)
438-
if nd != node.get("network_data"):
439-
ops.append(patch_op("add", "/network_data", nd))
450+
nd = resolve_ironic_network_data()
451+
if nd and nd != node.get("network_data"):
452+
ops.append(patch_op("add", "/network_data", nd))
440453

441454
return ops
442455

@@ -759,9 +772,18 @@ def adopt(host, data, restart_on_failure):
759772
return {}
760773

761774
def prepare(host, data, _unprepared, _restart_on_failure):
762-
"""Reject RAID; prepare itself is not implemented."""
775+
"""Reject RAID; sync network_data on the Ironic node for cleaning boots."""
763776
require_redfish_virtualmedia(host)
764777
require_no_raid(data)
778+
779+
prov_id = host[HOST_PROVISIONER_ID]
780+
if prov_id:
781+
nd = resolve_ironic_network_data()
782+
if nd:
783+
node, status = http_get("/v1/nodes/" + prov_id, ignore_statuses = [404])
784+
if status == 200 and node and nd != node.get("network_data"):
785+
http_patch("/v1/nodes/" + prov_id, [patch_op("add", "/network_data", nd)])
786+
765787
return {"started": False}
766788

767789
def service(host, _data, _unprepared, _restart_on_failure):
@@ -778,6 +800,11 @@ def provision(host, data, force_reboot):
778800
if status != 200 or not node:
779801
return {"dirty": True, "error": "provision: cannot get node"}
780802

803+
# Sync network_data so the deploy ramdisk boots with network config.
804+
nd = resolve_ironic_network_data()
805+
if nd and nd != node.get("network_data"):
806+
http_patch("/v1/nodes/" + prov_id, [patch_op("add", "/network_data", nd)])
807+
781808
state = node.get("provision_state", "")
782809

783810
if state == MANAGEABLE:
@@ -926,6 +953,11 @@ def deprovision(host, restart_on_failure, automated_cleaning_mode):
926953
if status != 200 or not node:
927954
return {"dirty": True, "error": "deprovision: cannot get node"}
928955

956+
# Sync network_data so the cleaning ramdisk boots with network config.
957+
nd = resolve_ironic_network_data()
958+
if nd and nd != node.get("network_data"):
959+
http_patch("/v1/nodes/" + prov_id, [patch_op("add", "/network_data", nd)])
960+
929961
state = node.get("provision_state", "")
930962

931963
# Sync automated_clean setting
@@ -980,6 +1012,11 @@ def delete(host):
9801012
if status != 200 or not node:
9811013
return {"dirty": True, "error": "delete: cannot get node"}
9821014

1015+
# Sync network_data so any cleaning triggered by delete has network config.
1016+
nd = resolve_ironic_network_data()
1017+
if nd and nd != node.get("network_data"):
1018+
http_patch("/v1/nodes/" + prov_id, [patch_op("add", "/network_data", nd)])
1019+
9831020
state = node.get("provision_state", "")
9841021

9851022
if state == VERIFYING:
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/*
2+
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
7+
http://www.apache.org/licenses/LICENSE-2.0
8+
9+
Unless required by applicable law or agreed to in writing, software
10+
distributed under the License is distributed on an "AS IS" BASIS,
11+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
See the License for the specific language governing permissions and
13+
limitations under the License.
14+
*/
15+
16+
package starlark
17+
18+
import (
19+
"context"
20+
"fmt"
21+
"strings"
22+
23+
metal3api "github.com/metal3-io/baremetal-operator/apis/metal3.io/v1alpha1"
24+
"github.com/metal3-io/baremetal-operator/pkg/secretutils"
25+
corev1 "k8s.io/api/core/v1"
26+
"k8s.io/apimachinery/pkg/types"
27+
"sigs.k8s.io/controller-runtime/pkg/client"
28+
)
29+
30+
// KubeHostSecretResolver fetches BMH spec secret fields on demand via client.Get + SecretManager.
31+
type KubeHostSecretResolver struct {
32+
Client client.Client
33+
SecretManager secretutils.SecretManager
34+
}
35+
36+
// ReadHostSecret resolves a BMH spec secret field to its string content; "" when unset.
37+
func (r *KubeHostSecretResolver) ReadHostSecret(ctx context.Context, namespace, name, field string) (string, error) {
38+
host := &metal3api.BareMetalHost{}
39+
if err := r.Client.Get(ctx, types.NamespacedName{Namespace: namespace, Name: name}, host); err != nil {
40+
return "", fmt.Errorf("get BareMetalHost: %w", err)
41+
}
42+
43+
var ref *corev1.SecretReference
44+
var dataKey string
45+
46+
switch strings.ToLower(field) {
47+
case "userdata":
48+
ref, dataKey = host.Spec.UserData, "userData"
49+
case "networkdata":
50+
ref, dataKey = host.Spec.NetworkData, "networkData"
51+
case "metadata":
52+
ref, dataKey = host.Spec.MetaData, "metaData"
53+
case "preprovisioningnetworkdata":
54+
if host.Spec.PreprovisioningNetworkDataName != "" {
55+
ref = &corev1.SecretReference{Name: host.Spec.PreprovisioningNetworkDataName}
56+
}
57+
dataKey = "networkData"
58+
default:
59+
return "", fmt.Errorf("unknown field %q", field)
60+
}
61+
62+
if ref == nil {
63+
return "", nil
64+
}
65+
66+
ns := ref.Namespace
67+
if ns == "" {
68+
ns = namespace
69+
}
70+
if ns != namespace {
71+
return "", fmt.Errorf("%s secret must be in BMH namespace %s", dataKey, namespace)
72+
}
73+
74+
sec, err := r.SecretManager.ObtainSecret(ctx, types.NamespacedName{Name: ref.Name, Namespace: ns})
75+
if err != nil {
76+
return "", err
77+
}
78+
79+
if v, ok := sec.Data[dataKey]; ok {
80+
return string(v), nil
81+
}
82+
if v, ok := sec.Data["value"]; ok {
83+
return string(v), nil
84+
}
85+
return "", nil
86+
}

pkg/provisioner/starlark/starlark.go

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -42,21 +42,23 @@ var log = logf.Log.WithName("provisioner").WithName("starlark")
4242

4343
// Frozen script globals shared across per-host provisioner instances.
4444
type starlarkProvisionerFactory struct {
45-
globals starlark.StringDict
46-
scriptPath string
47-
log logr.Logger
45+
globals starlark.StringDict
46+
scriptPath string
47+
log logr.Logger
48+
secretResolver starlib.HostSecretResolver
4849
}
4950

5051
// Per-host state shared by every provisioner.Provisioner method (defined in provisioner.go).
5152
type starlarkProvisioner struct {
52-
globals starlark.StringDict
53-
publisher provisioner.EventPublisher
54-
hostData provisioner.HostData
55-
log logr.Logger
53+
globals starlark.StringDict
54+
publisher provisioner.EventPublisher
55+
hostData provisioner.HostData
56+
log logr.Logger
57+
secretResolver starlib.HostSecretResolver
5658
}
5759

5860
// NewProvisionerFactory loads the Starlark script and validates that every required function is callable.
59-
func NewProvisionerFactory(scriptPath string) (provisioner.Factory, error) {
61+
func NewProvisionerFactory(scriptPath string, secretResolver starlib.HostSecretResolver) (provisioner.Factory, error) {
6062
globals, err := starscript.LoadScript(scriptPath, starlib.Builtins())
6163
if err != nil {
6264
return nil, fmt.Errorf("starlark provisioner: %w", err)
@@ -67,9 +69,10 @@ func NewProvisionerFactory(scriptPath string) (provisioner.Factory, error) {
6769
}
6870

6971
return &starlarkProvisionerFactory{
70-
globals: globals,
71-
scriptPath: scriptPath,
72-
log: log,
72+
globals: globals,
73+
scriptPath: scriptPath,
74+
log: log,
75+
secretResolver: secretResolver,
7376
}, nil
7477
}
7578

@@ -80,10 +83,11 @@ func (f *starlarkProvisionerFactory) NewProvisioner(
8083
publisher provisioner.EventPublisher,
8184
) (provisioner.Provisioner, error) {
8285
return &starlarkProvisioner{
83-
globals: f.globals,
84-
hostData: hostData,
85-
log: f.log.WithValues("host", hostData.ObjectMeta.Name),
86-
publisher: publisher,
86+
globals: f.globals,
87+
hostData: hostData,
88+
log: f.log.WithValues("host", hostData.ObjectMeta.Name),
89+
publisher: publisher,
90+
secretResolver: f.secretResolver,
8791
}, nil
8892
}
8993

@@ -94,6 +98,11 @@ func (p *starlarkProvisioner) CallScriptWithPublisher(ctx context.Context, name
9498
thread.SetLocal(starlib.PublisherThreadLocal, p.publisher)
9599
}
96100
thread.SetLocal(starlib.LoggerThreadLocal, p.log)
101+
if p.secretResolver != nil {
102+
thread.SetLocal(starlib.SecretResolverThreadLocal, p.secretResolver)
103+
}
104+
thread.SetLocal(starlib.HostNamespaceThreadLocal, p.hostData.ObjectMeta.Namespace)
105+
thread.SetLocal(starlib.HostNameThreadLocal, p.hostData.ObjectMeta.Name)
97106

98107
// Per-call ctx so the watcher goroutine exits whenever the call returns.
99108
callCtx, cancel := context.WithCancel(ctx)

pkg/provisioner/starlark/starlib/builtins.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ func Builtins() starlark.StringDict {
5959
"read_file": starlark.NewBuiltin("read_file", builtinReadFile),
6060
"yaml_decode": starlark.NewBuiltin("yaml_decode", builtinYAMLDecode),
6161
"yaml_encode": starlark.NewBuiltin("yaml_encode", builtinYAMLEncode),
62+
"read_host_secret": starlark.NewBuiltin("read_host_secret", builtinReadHostSecret),
6263
}
6364
}
6465

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
7+
http://www.apache.org/licenses/LICENSE-2.0
8+
9+
Unless required by applicable law or agreed to in writing, software
10+
distributed under the License is distributed on an "AS IS" BASIS,
11+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
See the License for the specific language governing permissions and
13+
limitations under the License.
14+
*/
15+
16+
package starlib
17+
18+
import (
19+
"context"
20+
"fmt"
21+
"strings"
22+
23+
"go.starlark.net/starlark"
24+
)
25+
26+
// HostSecretResolver resolves a named BMH spec secret field to its string content; "" when unset.
27+
type HostSecretResolver interface {
28+
ReadHostSecret(ctx context.Context, namespace, name, field string) (string, error)
29+
}
30+
31+
// Starlark read_host_secret(field): resolve a BMH secret ref to its string content.
32+
func builtinReadHostSecret(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, _ []starlark.Tuple) (starlark.Value, error) {
33+
var field starlark.String
34+
if err := starlark.UnpackPositionalArgs("read_host_secret", args, nil, 1, &field); err != nil {
35+
return starlark.None, err
36+
}
37+
38+
switch strings.ToLower(string(field)) {
39+
case "userdata", "networkdata", "metadata", "preprovisioningnetworkdata":
40+
default:
41+
return starlark.None, fmt.Errorf("read_host_secret: unknown field %q (want userData/networkData/metaData/preprovisioningNetworkData)", string(field))
42+
}
43+
44+
resolver, ok := thread.Local(SecretResolverThreadLocal).(HostSecretResolver)
45+
if !ok || resolver == nil {
46+
return starlark.None, fmt.Errorf("read_host_secret: no HostSecretResolver configured (factory constructed without one?)")
47+
}
48+
49+
ns, _ := thread.Local(HostNamespaceThreadLocal).(string)
50+
name, _ := thread.Local(HostNameThreadLocal).(string)
51+
if ns == "" || name == "" {
52+
return starlark.None, fmt.Errorf("read_host_secret: BMH coordinates not set on thread")
53+
}
54+
55+
ctx, _ := thread.Local(CtxThreadLocal).(context.Context)
56+
if ctx == nil {
57+
ctx = context.Background()
58+
}
59+
60+
s, err := resolver.ReadHostSecret(ctx, ns, name, string(field))
61+
if err != nil {
62+
return starlark.None, fmt.Errorf("read_host_secret(%s): %w", string(field), err)
63+
}
64+
65+
return starlark.String(s), nil
66+
}

pkg/provisioner/starlark/starlib/threadlocal.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,10 @@ const (
2323
CtxThreadLocal = "metal3-context"
2424
// Carries the per-host logr.Logger for log_info/log_debug/log_error.
2525
LoggerThreadLocal = "metal3-logger"
26+
// Carries the HostSecretResolver for read_host_secret.
27+
SecretResolverThreadLocal = "metal3-host-secret-resolver"
28+
// Carries the BMH namespace string (coordinates for read_host_secret).
29+
HostNamespaceThreadLocal = "metal3-host-namespace"
30+
// Carries the BMH name string (coordinates for read_host_secret).
31+
HostNameThreadLocal = "metal3-host-name"
2632
)

0 commit comments

Comments
 (0)