Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Taskfile.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ tasks:
cmds:
- bash hack/local-vm/run.sh

device-power:acceptance:
desc: "DevicePowerOperation end to end: Milo project API, BMC discovery, the dispatcher and worker Jobs against two TLS lab BMCs in a disposable kind cluster (exit 0 pass, 1 fail)."
cmds:
- ./hack/device-power/run.sh {{.CLI_ARGS}}

manifests:validate:
desc: Render and validate the production Fleet and Milo manifest roots.
cmds:
Expand Down
4 changes: 3 additions & 1 deletion build/manager.Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpat
&& CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-registration ./cmd/fleet-registration \
&& CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-simulator ./cmd/fleet-simulator \
&& CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-dhcp-sync ./cmd/fleet-dhcp-sync \
&& CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-bmc-discovery ./cmd/fleet-bmc-discovery
&& CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-bmc-discovery ./cmd/fleet-bmc-discovery \
&& CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-device-power ./cmd/fleet-device-power

FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab
COPY --from=build /out/fleet-manager /fleet-manager
COPY --from=build /out/fleet-registration /fleet-registration
COPY --from=build /out/fleet-simulator /fleet-simulator
COPY --from=build /out/fleet-dhcp-sync /fleet-dhcp-sync
COPY --from=build /out/fleet-bmc-discovery /fleet-bmc-discovery
COPY --from=build /out/fleet-device-power /fleet-device-power
ENTRYPOINT ["/fleet-manager"]
118 changes: 118 additions & 0 deletions cmd/fleet-device-power/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
// fleet-device-power runs staff power operations on unallocated Devices.
//
// fleet-device-power dispatcher --config=FILE
// fleet-device-power worker
//
// The dispatcher runs in a site, next to BMC discovery, for one Milo project.
// It accepts or refuses each DevicePowerOperation, starts one worker Job per
// accepted operation and writes operation status. It holds no BMC credential.
// A worker runs one operation: it reads its mounted credential and its stage
// record, sends at most one ComputerSystem.Reset and records the outcome. It
// holds no Milo credential.
package main

import (
"context"
"errors"
"flag"
"fmt"
"os"
"time"

"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log/zap"

"go.datum.net/fleet/internal/devicepower"
)

func main() {
if len(os.Args) < 2 {
fmt.Fprintln(os.Stderr, "usage: fleet-device-power dispatcher --config=FILE | worker")
os.Exit(64)
}
switch os.Args[1] {
case "dispatcher":
flags := flag.NewFlagSet("dispatcher", flag.ExitOnError)
configPath := flags.String("config", "/etc/fleet/device-power/config.yaml", "dispatcher configuration file")
zapOptions := zap.Options{Development: false}
zapOptions.BindFlags(flags)
_ = flags.Parse(os.Args[2:])
ctrl.SetLogger(zap.New(zap.UseFlagOptions(&zapOptions)))
if err := dispatch(ctrl.SetupSignalHandler(), *configPath); err != nil && !errors.Is(err, context.Canceled) {
fmt.Fprintln(os.Stderr, "fleet-device-power dispatcher:", err)
os.Exit(1)
}
case "worker":
err := work(ctrl.SetupSignalHandler())
switch {
case errors.Is(err, devicepower.ErrNotClaimed):
// A second worker for one operation stops here, having contacted
// no BMC, and leaves the first worker's result in place.
fmt.Fprintln(os.Stderr, "fleet-device-power worker:", err)
case err != nil:
fmt.Fprintln(os.Stderr, "fleet-device-power worker:", err)
os.Exit(1)
}
default:
fmt.Fprintln(os.Stderr, "usage: fleet-device-power dispatcher --config=FILE | worker")
os.Exit(64)
}
}

func dispatch(ctx context.Context, configPath string) error {
config, err := devicepower.LoadConfig(configPath)
if err != nil {
return err
}
milo, err := clientcmd.BuildConfigFromFlags("", config.MiloKubeconfig)
if err != nil {
return fmt.Errorf("Milo project kubeconfig: %w", err)
}
var local *rest.Config
if config.LocalKubeconfig != "" {
local, err = clientcmd.BuildConfigFromFlags("", config.LocalKubeconfig)
} else {
local, err = rest.InClusterConfig()
}
if err != nil {
return fmt.Errorf("local cluster config: %w", err)
}
scheme, err := devicepower.NewScheme()
if err != nil {
return err
}
mgr, err := devicepower.NewManager(config, milo, local, scheme)
if err != nil {
return err
}
return mgr.Start(ctx)
}

func work(ctx context.Context) error {
namespace, name, pod := os.Getenv("POD_NAMESPACE"), os.Getenv(devicepower.RecordEnv), os.Getenv(devicepower.PodUIDEnv)
if namespace == "" || name == "" || pod == "" {
return fmt.Errorf("%s, %s and POD_NAMESPACE are required", devicepower.RecordEnv, devicepower.PodUIDEnv)
}
local, err := rest.InClusterConfig()
if err != nil {
return fmt.Errorf("local cluster config: %w", err)
}
scheme, err := devicepower.NewScheme()
if err != nil {
return err
}
records, err := client.New(local, client.Options{Scheme: scheme})
if err != nil {
return err
}
w := &devicepower.Worker{Records: records, Record: types.NamespacedName{Namespace: namespace, Name: name}, PodUID: pod,
CredentialDir: devicepower.CredentialMount, NewBMC: devicepower.PinnedBMC, Poll: 2 * time.Second,
Log: func(format string, args ...any) {
fmt.Fprintf(os.Stderr, time.Now().UTC().Format(time.RFC3339)+" "+format+"\n", args...)
}}
return w.Run(ctx)
}
10 changes: 10 additions & 0 deletions config/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,16 @@ its namespace, image digest, Milo kubeconfig Secret and configuration.
`examples/` holds a synthetic credential Secret and a sidecar container
snippet. See [BMC discovery](../docs/operations/bmc-discovery.md).

`config/components/device-power` registers `DevicePowerOperation` in Milo: its
CRD, ProtectedResource, power operator and dispatcher roles, and an admission
policy that binds the requester to the creating user. Milo v0.32.5 does not
enforce that policy in a project. No root includes the component.
`config/base/device-power` runs the power dispatcher for one Milo project in
the site namespace that holds BMC credential Secrets, with the site admission
policies that pin every worker Job to one image, one credential and no
privilege. It is in no root either. See
[Device power operations](../docs/operations/device-power.md).

`config/standalone` remains a synthetic, same-cluster test environment. It must
not be referenced by either production root.

Expand Down
4 changes: 3 additions & 1 deletion config/base/bmc-discovery/examples/credential-secret.yaml
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
# Synthetic example of one BMC credential Secret. Not part of the base: create
# one per Device, in the namespace where discovery runs, outside Git.
# Discovery accepts any name; a power operation worker mounts the Secret named
# bmc.<device namespace>.<device name>, so use that form.
apiVersion: v1
kind: Secret
metadata:
name: bmc-example-device-01
name: bmc.default.example-device-01
labels:
fleet.datumapis.com/bmc-credential: "true"
annotations:
Expand Down
14 changes: 14 additions & 0 deletions config/base/device-power/config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Synthetic values; the deploying repository replaces them.
project: example-provider-project
miloKubeconfig: /var/run/fleet/milo/kubeconfig
deviceNamespaces: [default]
# workerNamespace defaults to the pod's namespace ($POD_NAMESPACE). It must
# be the namespace that holds the BMC credential Secrets.
# The image worker Jobs run. Keep it equal to workerImage in
# worker-policy.yaml's parameter, which admission enforces.
workerImage: ghcr.io/datum-cloud/fleet:latest
discoveryMaxAge: 2h
observeTimeout: 3m
requestTimeout: 20s
retention: 24h
healthProbeAddress: ":8081"
68 changes: 68 additions & 0 deletions config/base/device-power/deployment.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: fleet-device-power-dispatcher
spec:
# One replica and no leader election. Acceptance, the per-Device lock, the
# stage record and the worker Job are each written once or optimistically,
# so an accidental second replica starts no second worker.
replicas: 1
strategy:
type: Recreate
selector:
matchLabels:
app.kubernetes.io/name: fleet-device-power-dispatcher
template:
metadata:
labels:
app.kubernetes.io/name: fleet-device-power-dispatcher
spec:
serviceAccountName: fleet-device-power-dispatcher
automountServiceAccountToken: true
securityContext:
runAsNonRoot: true
runAsUser: 65532
runAsGroup: 65532
fsGroup: 65532
seccompProfile:
type: RuntimeDefault
containers:
- name: dispatcher
image: ghcr.io/datum-cloud/fleet:latest
command: [/fleet-device-power, dispatcher]
args:
- --config=/etc/fleet/device-power/config.yaml
env:
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
ports:
- name: probes
containerPort: 8081
livenessProbe:
httpGet: {path: /healthz, port: probes}
readinessProbe:
httpGet: {path: /readyz, port: probes}
resources:
requests: {cpu: 20m, memory: 64Mi}
limits: {memory: 256Mi}
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: [ALL]
volumeMounts:
- {name: config, mountPath: /etc/fleet/device-power, readOnly: true}
- {name: milo, mountPath: /var/run/fleet/milo, readOnly: true}
volumes:
- name: config
configMap:
name: fleet-device-power-config
# A kubeconfig for the one Milo project, bound to the
# fleet.datumapis.com-device-power-dispatcher role. Environment-owned.
- name: milo
secret:
secretName: fleet-device-power-milo-kubeconfig
defaultMode: 0440
items: [{key: kubeconfig, path: kubeconfig}]
17 changes: 17 additions & 0 deletions config/base/device-power/kustomization.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
# The power operation dispatcher for one Milo project, and the site admission
# policies for its workers. Apply it in the namespace that holds BMC
# discovery's credential Secrets; the deploying repository sets that
# namespace, the image digest (in images: and both workerImage values), the
# Milo kubeconfig Secret and the config values. worker-policy.yaml is
# cluster-scoped. See docs/operations/device-power.md.
resources:
- rbac.yaml
- deployment.yaml
- worker-policy.yaml
- worker-policy-params.yaml
configMapGenerator:
- name: fleet-device-power-config
files:
- config.yaml
41 changes: 41 additions & 0 deletions config/base/device-power/rbac.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
apiVersion: v1
kind: ServiceAccount
metadata:
name: fleet-device-power-dispatcher
---
# The dispatcher writes stage records, worker Jobs, their ServiceAccounts and
# Roles, and per-Device Leases in its own namespace. It holds no Secret or
# Pod permission, so it cannot read a BMC credential. It may create a Job
# that mounts one; worker-policy.yaml limits what that Job can be.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: fleet-device-power-dispatcher
rules:
- apiGroups: [""]
resources: [configmaps]
verbs: [get, list, watch, create, update, delete]
- apiGroups: [coordination.k8s.io]
resources: [leases]
verbs: [get, list, watch, create, update, delete]
- apiGroups: [batch]
resources: [jobs]
verbs: [get, list, watch, create]
- apiGroups: [""]
resources: [serviceaccounts]
verbs: [get, create]
- apiGroups: [rbac.authorization.k8s.io]
resources: [roles, rolebindings]
verbs: [get, create]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: fleet-device-power-dispatcher
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: fleet-device-power-dispatcher
subjects:
- kind: ServiceAccount
name: fleet-device-power-dispatcher
9 changes: 9 additions & 0 deletions config/base/device-power/worker-policy-params.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# The image every worker Job must run, read by the dispatcher-writes policy.
# The deploying repository sets it to the same digest as the dispatcher's
# workerImage.
apiVersion: v1
kind: ConfigMap
metadata:
name: fleet-device-power-worker-policy
data:
workerImage: ghcr.io/datum-cloud/fleet:latest
Loading
Loading