Skip to content

Commit f031c7f

Browse files
committed
[Starlark] Add host read-access, base64, and network_data sync
- read_host_secret(field): resolves BMH spec secret refs (userData/networkData/metaData/preprovisioningNetworkData) on demand. - read_host_spec(): returns BareMetalHost.Spec as a read-only dict so scripts can branch on fields like spec.architecture. - base64_encode / base64_decode: standard-encoding string helpers. - Ironic example script now re-syncs network_data at every lifecycle phase via resolve_ironic_network_data(), ensuring network_id is present on each entry (Ironic requires it; CAPM3 omits). Signed-off-by: s3rj1k <evasive.gyron@gmail.com>
1 parent 45de2a8 commit f031c7f

7 files changed

Lines changed: 324 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+
hostResolver := &starlarkprov.KubeHostResolver{
347+
Client: mgr.GetClient(),
348+
SecretManager: secretutils.NewSecretManager(
349+
ctrl.Log.WithName("starlark-host-resolver"),
350+
mgr.GetClient(),
351+
mgr.GetAPIReader(),
352+
),
353+
}
354+
provisionerFactory, err = starlarkprov.NewProvisionerFactory(starlarkScript, hostResolver)
347355
if err != nil {
348356
setupLog.Error(err, "cannot start starlark provisioner")
349357
os.Exit(1)
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
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+
"encoding/json"
21+
"fmt"
22+
"strings"
23+
24+
metal3api "github.com/metal3-io/baremetal-operator/apis/metal3.io/v1alpha1"
25+
"github.com/metal3-io/baremetal-operator/pkg/secretutils"
26+
corev1 "k8s.io/api/core/v1"
27+
"k8s.io/apimachinery/pkg/types"
28+
"sigs.k8s.io/controller-runtime/pkg/client"
29+
)
30+
31+
// KubeHostResolver fetches BMH data on demand via client.Get + SecretManager.
32+
type KubeHostResolver struct {
33+
Client client.Client
34+
SecretManager secretutils.SecretManager
35+
}
36+
37+
// ReadHostSecret resolves a BMH spec secret field to its string content; "" when unset.
38+
func (r *KubeHostResolver) ReadHostSecret(ctx context.Context, namespace, name, field string) (string, error) {
39+
host := &metal3api.BareMetalHost{}
40+
if err := r.Client.Get(ctx, types.NamespacedName{Namespace: namespace, Name: name}, host); err != nil {
41+
return "", fmt.Errorf("get BareMetalHost: %w", err)
42+
}
43+
44+
var ref *corev1.SecretReference
45+
var dataKey string
46+
47+
switch strings.ToLower(field) {
48+
case "userdata":
49+
ref, dataKey = host.Spec.UserData, "userData"
50+
case "networkdata":
51+
ref, dataKey = host.Spec.NetworkData, "networkData"
52+
case "metadata":
53+
ref, dataKey = host.Spec.MetaData, "metaData"
54+
case "preprovisioningnetworkdata":
55+
if host.Spec.PreprovisioningNetworkDataName != "" {
56+
ref = &corev1.SecretReference{Name: host.Spec.PreprovisioningNetworkDataName}
57+
}
58+
dataKey = "networkData"
59+
default:
60+
return "", fmt.Errorf("unknown field %q", field)
61+
}
62+
63+
if ref == nil {
64+
return "", nil
65+
}
66+
67+
ns := ref.Namespace
68+
if ns == "" {
69+
ns = namespace
70+
}
71+
if ns != namespace {
72+
return "", fmt.Errorf("%s secret must be in BMH namespace %s", dataKey, namespace)
73+
}
74+
75+
sec, err := r.SecretManager.ObtainSecret(ctx, types.NamespacedName{Name: ref.Name, Namespace: ns})
76+
if err != nil {
77+
return "", err
78+
}
79+
80+
if v, ok := sec.Data[dataKey]; ok {
81+
return string(v), nil
82+
}
83+
if v, ok := sec.Data["value"]; ok {
84+
return string(v), nil
85+
}
86+
return "", nil
87+
}
88+
89+
// ReadHostSpec returns BareMetalHost.Spec as a read-only map[string]any.
90+
func (r *KubeHostResolver) ReadHostSpec(ctx context.Context, namespace, name string) (map[string]any, error) {
91+
host := &metal3api.BareMetalHost{}
92+
if err := r.Client.Get(ctx, types.NamespacedName{Namespace: namespace, Name: name}, host); err != nil {
93+
return nil, fmt.Errorf("get BareMetalHost: %w", err)
94+
}
95+
96+
data, err := json.Marshal(host.Spec)
97+
if err != nil {
98+
return nil, fmt.Errorf("marshal spec: %w", err)
99+
}
100+
101+
var m map[string]any
102+
if err := json.Unmarshal(data, &m); err != nil {
103+
return nil, fmt.Errorf("unmarshal spec: %w", err)
104+
}
105+
106+
return m, nil
107+
}

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:

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.HostResolver
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.HostResolver
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.HostResolver) (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.HostResolverThreadLocal, 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: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919
"context"
2020
"crypto/tls"
2121
"crypto/x509"
22+
"encoding/base64"
2223
"encoding/json"
2324
"errors"
2425
"fmt"
@@ -59,9 +60,42 @@ func Builtins() starlark.StringDict {
5960
"read_file": starlark.NewBuiltin("read_file", builtinReadFile),
6061
"yaml_decode": starlark.NewBuiltin("yaml_decode", builtinYAMLDecode),
6162
"yaml_encode": starlark.NewBuiltin("yaml_encode", builtinYAMLEncode),
63+
"base64_encode": starlark.NewBuiltin("base64_encode", builtinBase64Encode),
64+
"base64_decode": starlark.NewBuiltin("base64_decode", builtinBase64Decode),
65+
"read_host_secret": starlark.NewBuiltin("read_host_secret", builtinReadHostSecret),
66+
"read_host_spec": starlark.NewBuiltin("read_host_spec", builtinReadHostSpec),
6267
}
6368
}
6469

70+
// Starlark base64_encode(string): return standard base64 of the input (UTF-8 / byte string).
71+
func builtinBase64Encode(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, _ []starlark.Tuple) (starlark.Value, error) {
72+
var s starlark.String
73+
74+
err := starlark.UnpackPositionalArgs("base64_encode", args, nil, 1, &s)
75+
if err != nil {
76+
return starlark.None, err
77+
}
78+
79+
return starlark.String(base64.StdEncoding.EncodeToString([]byte(string(s)))), nil
80+
}
81+
82+
// Starlark base64_decode(string): return the raw bytes as a Starlark string; errors on invalid input.
83+
func builtinBase64Decode(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, _ []starlark.Tuple) (starlark.Value, error) {
84+
var s starlark.String
85+
86+
err := starlark.UnpackPositionalArgs("base64_decode", args, nil, 1, &s)
87+
if err != nil {
88+
return starlark.None, err
89+
}
90+
91+
decoded, err := base64.StdEncoding.DecodeString(string(s))
92+
if err != nil {
93+
return starlark.None, fmt.Errorf("base64_decode: %w", err)
94+
}
95+
96+
return starlark.String(string(decoded)), nil
97+
}
98+
6599
// Starlark yaml_decode(string): parse YAML/JSON into a Starlark value.
66100
func builtinYAMLDecode(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, _ []starlark.Tuple) (starlark.Value, error) {
67101
var s starlark.String

0 commit comments

Comments
 (0)