Skip to content

Commit 36f8098

Browse files
authored
Merge pull request #170 from wanyufe/k8s-nodename
Use capi machine name as hostname and k8s node name
2 parents 65749d4 + 45d7a18 commit 36f8098

File tree

5 files changed

+51
-4
lines changed

5 files changed

+51
-4
lines changed

controllers/cloudstackmachine_controller.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"fmt"
2222
"math/rand"
2323
"reflect"
24+
"regexp"
2425

2526
"github.com/pkg/errors"
2627
corev1 "k8s.io/api/core/v1"
@@ -40,6 +41,11 @@ import (
4041
clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
4142
)
4243

44+
var (
45+
hostnameMatcher = regexp.MustCompile(`\{\{\s*ds\.meta_data\.hostname\s*\}\}`)
46+
failuredomainMatcher = regexp.MustCompile(`\{\{\s*ds\.meta_data\.failuredomain\s*\}\}`)
47+
)
48+
4349
// +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=cloudstackmachines,verbs=get;list;watch;create;update;patch;delete
4450
// +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=cloudstackmachines/status,verbs=get;update;patch
4551
// +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=cloudstackmachines/finalizers,verbs=update
@@ -169,7 +175,8 @@ func (r *CloudStackMachineReconciliationRunner) GetOrCreateVMInstance() (retRes
169175
return ctrl.Result{}, errors.New("bootstrap secret data not yet set")
170176
}
171177

172-
err := r.CSUser.GetOrCreateVMInstance(r.ReconciliationSubject, r.CAPIMachine, r.CSCluster, r.FailureDomain, r.AffinityGroup, string(data))
178+
userData := processCustomMetadata(data, r)
179+
err := r.CSUser.GetOrCreateVMInstance(r.ReconciliationSubject, r.CAPIMachine, r.CSCluster, r.FailureDomain, r.AffinityGroup, userData)
173180

174181
if err == nil && !controllerutil.ContainsFinalizer(r.ReconciliationSubject, infrav1.MachineFinalizer) { // Fetched or Created?
175182
r.Log.Info("CloudStack instance Created", "instanceStatus", r.ReconciliationSubject.Status)
@@ -179,6 +186,14 @@ func (r *CloudStackMachineReconciliationRunner) GetOrCreateVMInstance() (retRes
179186
return ctrl.Result{}, err
180187
}
181188

189+
func processCustomMetadata(data []byte, r *CloudStackMachineReconciliationRunner) string {
190+
// since cloudstack metadata does not allow custom data added into meta_data, following line is a workaround to specify a hostname name
191+
// {{ ds.meta_data.hostname }} is expected to be used as a node name when kubelet register a node
192+
userData := hostnameMatcher.ReplaceAllString(string(data), r.CAPIMachine.Name)
193+
userData = failuredomainMatcher.ReplaceAllString(userData, r.FailureDomain.Spec.Name)
194+
return userData
195+
}
196+
182197
// ConfirmVMStatus checks the Instance's status for running state and requeues otherwise.
183198
func (r *CloudStackMachineReconciliationRunner) RequeueIfInstanceNotRunning() (retRes ctrl.Result, reterr error) {
184199
if r.ReconciliationSubject.Status.InstanceState == "Running" {

controllers/cloudstackmachine_controller_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,32 @@ var _ = Describe("CloudStackMachineReconciler", func() {
7272
return false
7373
}, timeout).WithPolling(pollInterval).Should(BeTrue())
7474
})
75+
76+
It("Should replace ds.meta_data.hostname with capi machine name.", func() {
77+
// Mock a call to GetOrCreateVMInstance and set the machine to running.
78+
mockCloudClient.EXPECT().GetOrCreateVMInstance(
79+
gomock.Any(), gomock.Any(), gomock.Any(),
80+
gomock.Any(), gomock.Any(), gomock.Any()).Do(
81+
func(arg1, _, _, _, _, userdata interface{}) {
82+
Ω(userdata == dummies.CAPIMachine.Name).Should(BeTrue())
83+
arg1.(*infrav1.CloudStackMachine).Status.InstanceState = "Running"
84+
}).AnyTimes()
85+
86+
// Have to do this here or the reconcile call to GetOrCreateVMInstance may happen too early.
87+
setupMachineCRDs()
88+
89+
// Eventually the machine should set ready to true.
90+
Eventually(func() bool {
91+
tempMachine := &infrav1.CloudStackMachine{}
92+
key := client.ObjectKey{Namespace: dummies.ClusterNameSpace, Name: dummies.CSMachine1.Name}
93+
if err := k8sClient.Get(ctx, key, tempMachine); err == nil {
94+
if tempMachine.Status.Ready == true {
95+
return true
96+
}
97+
}
98+
return false
99+
}, timeout).WithPolling(pollInterval).Should(BeTrue())
100+
})
75101
})
76102

77103
Context("With a fake ctrlRuntimeClient and no test Env at all.", func() {

pkg/cloud/instance.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -237,7 +237,7 @@ func (c *client) GetOrCreateVMInstance(
237237
p := c.cs.VirtualMachine.NewDeployVirtualMachineParams(offeringID, templateID, fd.Spec.Zone.ID)
238238
p.SetNetworkids([]string{fd.Spec.Zone.Network.ID})
239239
setIfNotEmpty(csMachine.Name, p.SetName)
240-
setIfNotEmpty(csMachine.Name, p.SetDisplayname)
240+
setIfNotEmpty(capiMachine.Name, p.SetDisplayname)
241241
setIfNotEmpty(diskOfferingID, p.SetDiskofferingid)
242242
setIntIfPositive(csMachine.Spec.DiskOffering.CustomSize, p.SetSize)
243243

pkg/cloud/instance_test.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,12 @@ var _ = Describe("Instance", func() {
263263
Return(&cloudstack.DeployVirtualMachineParams{})
264264

265265
deploymentResp := &cloudstack.DeployVirtualMachineResponse{Id: *dummies.CSMachine1.Spec.InstanceID}
266-
vms.EXPECT().DeployVirtualMachine(gomock.Any()).Return(deploymentResp, nil)
266+
267+
vms.EXPECT().DeployVirtualMachine(gomock.Any()).Do(
268+
func(p interface{}) {
269+
displayName, _ := p.(*cloudstack.DeployVirtualMachineParams).GetDisplayname()
270+
Ω(displayName == dummies.CAPIMachine.Name).Should(BeTrue())
271+
}).Return(deploymentResp, nil)
267272

268273
Ω(client.GetOrCreateVMInstance(
269274
dummies.CSMachine1, dummies.CAPIMachine, dummies.CSCluster, dummies.CSFailureDomain1, dummies.CSAffinityGroup, "")).

test/dummies/v1beta2/vars.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -398,11 +398,12 @@ func SetDummyIsoNetToNameOnly() {
398398

399399
func SetDummyBootstrapSecretVar() {
400400
BootstrapSecretName := "such-secret-much-wow"
401+
BootstrapSecretValue := "{{ ds.meta_data.hostname }}"
401402
BootstrapSecret = &corev1.Secret{
402403
ObjectMeta: metav1.ObjectMeta{
403404
Namespace: ClusterNameSpace,
404405
Name: BootstrapSecretName},
405-
Data: map[string][]byte{"value": make([]byte, 0)}}
406+
Data: map[string][]byte{"value": []byte(BootstrapSecretValue)}}
406407
}
407408

408409
// Sets cluster spec to specified network.

0 commit comments

Comments
 (0)