Skip to content

Commit 2cf9110

Browse files
Add NamingStrategy to MachineDeployment
Signed-off-by: Muhammad Adil Ghaffar <[email protected]>
1 parent 6c04105 commit 2cf9110

10 files changed

+364
-52
lines changed

api/v1beta1/machinedeployment_types.go

+22
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,11 @@ type MachineDeploymentSpec struct {
127127
// +optional
128128
Strategy *MachineDeploymentStrategy `json:"strategy,omitempty"`
129129

130+
// MachineNamingStrategy allows changing the naming pattern used when creating Machines.
131+
// Note: InfraMachines will use the same name as the corresponding Machines.
132+
// +optional
133+
MachineNamingStrategy *MachineNamingStrategy `json:"machineNamingStrategy,omitempty"`
134+
130135
// MinReadySeconds is the minimum number of seconds for which a Node for a newly created machine should be ready before considering the replica available.
131136
// Defaults to 0 (machine will be considered available as soon as the Node is ready)
132137
// +optional
@@ -250,6 +255,23 @@ type RemediationStrategy struct {
250255

251256
// ANCHOR_END: RemediationStrategy
252257

258+
// MachineNamingStrategy allows changing the naming pattern used when creating Machines.
259+
// Note: InfraMachines will use the same name as the corresponding Machines.
260+
type MachineNamingStrategy struct {
261+
// Template defines the template to use for generating the names of the Machine objects.
262+
// If not defined, it will fallback to `{{ .machineDeployment.name }}-{{ .random }}`.
263+
// If the generated name string exceeds 63 characters, it will be trimmed to 58 characters and will
264+
// get concatenated with a random suffix of length 5.
265+
// Length of the template string must not exceed 256 characters.
266+
// The template allows the following variables `.cluster.name`, `.machineDeployment.name` and `.random`.
267+
// The variable `.cluster.name` retrieves the name of the cluster object that owns the Machines being created.
268+
// The variable `.machineDeployment.name` retrieves the name of the MachineDeployment object that owns the Machines being created.
269+
// The variable `.random` is substituted with random alphanumeric string, without vowels, of length 5.
270+
// +optional
271+
// +kubebuilder:validation:MaxLength=256
272+
Template string `json:"template,omitempty"`
273+
}
274+
253275
// ANCHOR: MachineDeploymentStatus
254276

255277
// MachineDeploymentStatus defines the observed state of MachineDeployment.

api/v1beta1/zz_generated.deepcopy.go

+20
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

api/v1beta1/zz_generated.openapi.go

+28-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

config/crd/bases/cluster.x-k8s.io_machinedeployments.yaml

+19
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

internal/apis/core/v1alpha3/zz_generated.conversion.go

+1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

internal/apis/core/v1alpha4/zz_generated.conversion.go

+1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

internal/controllers/machineset/machineset_controller.go

+35-6
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ import (
5050
"sigs.k8s.io/cluster-api/controllers/noderefutil"
5151
"sigs.k8s.io/cluster-api/internal/contract"
5252
"sigs.k8s.io/cluster-api/internal/controllers/machine"
53+
topologynames "sigs.k8s.io/cluster-api/internal/topology/names"
5354
"sigs.k8s.io/cluster-api/internal/util/ssa"
5455
"sigs.k8s.io/cluster-api/util"
5556
"sigs.k8s.io/cluster-api/util/collections"
@@ -518,8 +519,11 @@ func (r *Reconciler) syncMachines(ctx context.Context, s *scope) (ctrl.Result, e
518519
}
519520

520521
// Update Machine to propagate in-place mutable fields from the MachineSet.
521-
updatedMachine := r.computeDesiredMachine(machineSet, m)
522-
err := ssa.Patch(ctx, r.Client, machineSetManagerName, updatedMachine, ssa.WithCachingProxy{Cache: r.ssaCache, Original: m})
522+
updatedMachine, err := r.computeDesiredMachine(ctx, machineSet, m)
523+
if err != nil {
524+
return ctrl.Result{}, errors.Wrap(err, "failed to update Machine: failed to compute desired Machine")
525+
}
526+
err = ssa.Patch(ctx, r.Client, machineSetManagerName, updatedMachine, ssa.WithCachingProxy{Cache: r.ssaCache, Original: m})
523527
if err != nil {
524528
log.Error(err, "Failed to update Machine", "Machine", klog.KObj(updatedMachine))
525529
return ctrl.Result{}, errors.Wrapf(err, "failed to update Machine %q", klog.KObj(updatedMachine))
@@ -612,7 +616,10 @@ func (r *Reconciler) syncReplicas(ctx context.Context, s *scope) (ctrl.Result, e
612616
for i := range diff {
613617
// Create a new logger so the global logger is not modified.
614618
log := log
615-
machine := r.computeDesiredMachine(ms, nil)
619+
machine, computeMachineErr := r.computeDesiredMachine(ctx, ms, nil)
620+
if computeMachineErr != nil {
621+
return ctrl.Result{}, errors.Wrap(computeMachineErr, "failed to create Machine: failed to compute desired Machine")
622+
}
616623
// Clone and set the infrastructure and bootstrap references.
617624
var (
618625
infraRef, bootstrapRef *corev1.ObjectReference
@@ -747,14 +754,36 @@ func (r *Reconciler) syncReplicas(ctx context.Context, s *scope) (ctrl.Result, e
747754
// There are small differences in how we calculate the Machine depending on if it
748755
// is a create or update. Example: for a new Machine we have to calculate a new name,
749756
// while for an existing Machine we have to use the name of the existing Machine.
750-
func (r *Reconciler) computeDesiredMachine(machineSet *clusterv1.MachineSet, existingMachine *clusterv1.Machine) *clusterv1.Machine {
757+
func (r *Reconciler) computeDesiredMachine(ctx context.Context, machineSet *clusterv1.MachineSet, existingMachine *clusterv1.Machine) (*clusterv1.Machine, error) {
758+
machineName := names.SimpleNameGenerator.GenerateName(fmt.Sprintf("%s-", machineSet.Name))
759+
// If the MachineSet is part of a MachineDeployment, check MachineNamingStrategy
760+
// and name Machine accordingly.
761+
if isDeploymentChild(machineSet) {
762+
owner, err := r.getOwnerMachineDeployment(ctx, machineSet)
763+
if err != nil {
764+
return nil, err
765+
}
766+
nameTemplate := "{{ .machineDeployment.name }}-{{ .random }}"
767+
if owner.Spec.MachineNamingStrategy != nil && owner.Spec.MachineNamingStrategy.Template != "" {
768+
nameTemplate = owner.Spec.MachineNamingStrategy.Template
769+
if !strings.Contains(nameTemplate, "{{ .random }}") {
770+
return nil, errors.New("cannot generate MachineDeployment machine name: {{ .random }} is missing in machineNamingStrategy.template")
771+
}
772+
}
773+
generatedMachineName, err := topologynames.MachineDeploymentMachineNameGenerator(nameTemplate, machineSet.Spec.ClusterName, owner.Name).GenerateName()
774+
if err != nil {
775+
return nil, errors.Wrap(err, "failed to generate name for MachineDeployment machine")
776+
}
777+
machineName = generatedMachineName
778+
}
779+
751780
desiredMachine := &clusterv1.Machine{
752781
TypeMeta: metav1.TypeMeta{
753782
APIVersion: clusterv1.GroupVersion.String(),
754783
Kind: "Machine",
755784
},
756785
ObjectMeta: metav1.ObjectMeta{
757-
Name: names.SimpleNameGenerator.GenerateName(fmt.Sprintf("%s-", machineSet.Name)),
786+
Name: machineName,
758787
Namespace: machineSet.Namespace,
759788
// Note: By setting the ownerRef on creation we signal to the Machine controller that this is not a stand-alone Machine.
760789
OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(machineSet, machineSetKind)},
@@ -812,7 +841,7 @@ func (r *Reconciler) computeDesiredMachine(machineSet *clusterv1.MachineSet, exi
812841
desiredMachine.Spec.NodeDeletionTimeout = machineSet.Spec.Template.Spec.NodeDeletionTimeout
813842
desiredMachine.Spec.NodeVolumeDetachTimeout = machineSet.Spec.Template.Spec.NodeVolumeDetachTimeout
814843

815-
return desiredMachine
844+
return desiredMachine, nil
816845
}
817846

818847
// updateExternalObject updates the external object passed in with the

0 commit comments

Comments
 (0)