|
| 1 | +//go:build linux |
| 2 | + |
| 3 | +package agent |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "os" |
| 8 | + "strings" |
| 9 | + |
| 10 | + apierrors "k8s.io/apimachinery/pkg/api/errors" |
| 11 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 12 | + logf "sigs.k8s.io/controller-runtime/pkg/log" |
| 13 | + |
| 14 | + impv1alpha1 "github.com/syscode-labs/imp/api/v1alpha1" |
| 15 | +) |
| 16 | + |
| 17 | +// detectAndPatchCPUModel reads /proc/cpuinfo, extracts the CPU model string, |
| 18 | +// and patches it onto the ClusterImpNodeProfile for this node. |
| 19 | +// This is best-effort — errors are logged at V(1) and do not affect agent startup. |
| 20 | +func detectAndPatchCPUModel(ctx context.Context, c client.Client, nodeName string) { |
| 21 | + log := logf.FromContext(ctx) |
| 22 | + data, err := os.ReadFile("/proc/cpuinfo") |
| 23 | + if err != nil { |
| 24 | + log.V(1).Info("could not read /proc/cpuinfo", "err", err) |
| 25 | + return |
| 26 | + } |
| 27 | + model := parseCPUModelFromProcInfo(string(data)) |
| 28 | + if model == "" { |
| 29 | + log.V(1).Info("could not parse CPU model from /proc/cpuinfo") |
| 30 | + return |
| 31 | + } |
| 32 | + |
| 33 | + profile := &impv1alpha1.ClusterImpNodeProfile{} |
| 34 | + err = c.Get(ctx, client.ObjectKey{Name: nodeName}, profile) |
| 35 | + if apierrors.IsNotFound(err) { |
| 36 | + log.V(1).Info("no ClusterImpNodeProfile for node, skipping CPU model patch", "node", nodeName) |
| 37 | + return |
| 38 | + } |
| 39 | + if err != nil { |
| 40 | + log.Error(err, "failed to get ClusterImpNodeProfile for CPU model patch", "node", nodeName) |
| 41 | + return |
| 42 | + } |
| 43 | + |
| 44 | + if profile.Spec.CPUModel == model { |
| 45 | + return // already up to date |
| 46 | + } |
| 47 | + |
| 48 | + base := profile.DeepCopy() |
| 49 | + profile.Spec.CPUModel = model |
| 50 | + if err := c.Patch(ctx, profile, client.MergeFrom(base)); err != nil { |
| 51 | + log.Error(err, "failed to patch CPUModel onto ClusterImpNodeProfile", "node", nodeName) |
| 52 | + return |
| 53 | + } |
| 54 | + log.Info("patched CPU model onto ClusterImpNodeProfile", "node", nodeName, "model", model) |
| 55 | +} |
| 56 | + |
| 57 | +// parseCPUModelFromProcInfo extracts the "model name" line from /proc/cpuinfo content. |
| 58 | +func parseCPUModelFromProcInfo(content string) string { |
| 59 | + for _, line := range strings.Split(content, "\n") { |
| 60 | + if strings.HasPrefix(line, "model name") { |
| 61 | + parts := strings.SplitN(line, ":", 2) |
| 62 | + if len(parts) == 2 { |
| 63 | + return strings.TrimSpace(parts[1]) |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + return "" |
| 68 | +} |
0 commit comments