Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🌱 Update CAPI to v1.2.1 #1602

Merged
merged 6 commits into from
Sep 9, 2022
Merged
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
4 changes: 2 additions & 2 deletions .github/workflows/golangci-lint.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ jobs:
- uses: actions/checkout@v3
- uses: actions/setup-go@v3
with:
go-version: 1.17
go-version: 1.18
- name: golangci-lint
uses: golangci/[email protected]
with:
version: v1.44.0
version: v1.47.3
2 changes: 2 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ run:
skip-files:
- ".*zz_generated.*\\.go"
- "contrib/.*"
- "apis/v1alpha3/.*"
- "apis/v1alpha4/.*"
timeout: 5m
issue:
max-same-issues: 0
Expand Down
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
# limitations under the License.

# Build the manager binary
ARG GOLANG_VERSION=golang:1.17.6
ARG GOLANG_VERSION=golang:1.18.5
FROM --platform=${BUILDPLATFORM} ${GOLANG_VERSION} as builder
WORKDIR /workspace

Expand Down
13 changes: 6 additions & 7 deletions apis/v1beta1/vspheredeploymentzone_webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,19 @@ import (
"sigs.k8s.io/controller-runtime/pkg/webhook"
)

func (r *VSphereDeploymentZone) SetupWebhookWithManager(mgr ctrl.Manager) error {
func (z *VSphereDeploymentZone) SetupWebhookWithManager(mgr ctrl.Manager) error {
return ctrl.NewWebhookManagedBy(mgr).
For(r).
For(z).
Complete()
}

// +kubebuilder:webhook:verbs=create;update,path=/mutate-infrastructure-cluster-x-k8s-io-v1beta1-vspheredeploymentzone,mutating=true,failurePolicy=fail,matchPolicy=Equivalent,groups=infrastructure.cluster.x-k8s.io,resources=vspheredeploymentzones,versions=v1beta1,name=default.vspheredeploymentzone.infrastructure.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1beta1

var _ webhook.Defaulter = &VSphereDeploymentZone{}

// Default implements webhook.Defaulter so a webhook will be registered for the type
// nolint:stylecheck
func (r *VSphereDeploymentZone) Default() {
if r.Spec.ControlPlane == nil {
r.Spec.ControlPlane = pointer.BoolPtr(true)
// Default implements webhook.Defaulter so a webhook will be registered for the type.
func (z *VSphereDeploymentZone) Default() {
if z.Spec.ControlPlane == nil {
z.Spec.ControlPlane = pointer.Bool(true)
}
}
58 changes: 43 additions & 15 deletions apis/v1beta1/vspheremachinetemplate_webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,57 +17,85 @@ limitations under the License.
package v1beta1

import (
"context"
"fmt"
"reflect"

apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/validation/field"
"sigs.k8s.io/cluster-api/util/topology"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)

func (r *VSphereMachineTemplate) SetupWebhookWithManager(mgr ctrl.Manager) error {
const machineTemplateImmutableMsg = "VSphereMachineTemplate spec.template.spec field is immutable. Please create a new resource instead."

func (v *VSphereMachineTemplateWebhook) SetupWebhookWithManager(mgr ctrl.Manager) error {
return ctrl.NewWebhookManagedBy(mgr).
For(r).
For(&VSphereMachineTemplate{}).
WithValidator(v).
Complete()
}

// +kubebuilder:webhook:verbs=create;update,path=/validate-infrastructure-cluster-x-k8s-io-v1beta1-vspheremachinetemplate,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,groups=infrastructure.cluster.x-k8s.io,resources=vspheremachinetemplates,versions=v1beta1,name=validation.vspheremachinetemplate.infrastructure.x-k8s.io,sideEffects=None,admissionReviewVersions=v1beta1

var _ webhook.Validator = &VSphereMachineTemplate{}
// VSphereMachineTemplateWebhook implements a custom validation webhook for DockerMachineTemplate.
// +kubebuilder:object:generate=false
type VSphereMachineTemplateWebhook struct{}

var _ webhook.CustomValidator = &VSphereMachineTemplateWebhook{}

// ValidateCreate implements webhook.Validator so a webhook will be registered for the type.
func (r *VSphereMachineTemplate) ValidateCreate() error {
func (v *VSphereMachineTemplateWebhook) ValidateCreate(_ context.Context, raw runtime.Object) error {
obj, ok := raw.(*VSphereMachineTemplate)
if !ok {
return apierrors.NewBadRequest(fmt.Sprintf("expected a VSphereMachineTemplate but got a %T", raw))
}

var allErrs field.ErrorList
spec := r.Spec.Template.Spec
spec := obj.Spec.Template.Spec

if spec.Network.PreferredAPIServerCIDR != "" {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "PreferredAPIServerCIDR"), spec.Network.PreferredAPIServerCIDR, "cannot be set, as it will be removed and is no longer used"))
}

if spec.ProviderID != nil {
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec", "template", "spec", "providerID"), "cannot be set in templates"))
}

for _, device := range spec.Network.Devices {
if len(device.IPAddrs) != 0 {
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec", "template", "spec", "network", "devices", "ipAddrs"), "cannot be set in templates"))
}
}

return aggregateObjErrors(r.GroupVersionKind().GroupKind(), r.Name, allErrs)
return aggregateObjErrors(obj.GroupVersionKind().GroupKind(), obj.Name, allErrs)
}

// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type.
func (r *VSphereMachineTemplate) ValidateUpdate(old runtime.Object) error {
oldVSphereMachineTemplate := old.(*VSphereMachineTemplate) //nolint:forcetypeassert
if !reflect.DeepEqual(r.Spec, oldVSphereMachineTemplate.Spec) {
return field.Forbidden(field.NewPath("spec"), "VSphereMachineTemplateSpec is immutable")
func (v *VSphereMachineTemplateWebhook) ValidateUpdate(ctx context.Context, oldRaw runtime.Object, newRaw runtime.Object) error {
newObj, ok := newRaw.(*VSphereMachineTemplate)
if !ok {
return apierrors.NewBadRequest(fmt.Sprintf("expected a VSphereMachineTemplate but got a %T", newRaw))
}
oldObj, ok := oldRaw.(*VSphereMachineTemplate)
if !ok {
return apierrors.NewBadRequest(fmt.Sprintf("expected a VSphereMachineTemplate but got a %T", oldRaw))
}

return nil
req, err := admission.RequestFromContext(ctx)
if err != nil {
return apierrors.NewBadRequest(fmt.Sprintf("expected a admission.Request inside context: %v", err))
}

var allErrs field.ErrorList
if !topology.ShouldSkipImmutabilityChecks(req, newObj) &&
!reflect.DeepEqual(newObj.Spec.Template.Spec, oldObj.Spec.Template.Spec) {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "template", "spec"), newObj, machineTemplateImmutableMsg))
}
return aggregateObjErrors(newObj.GroupVersionKind().GroupKind(), newObj.Name, allErrs)
}

// ValidateDelete implements webhook.Validator so a webhook will be registered for the type.
func (r *VSphereMachineTemplate) ValidateDelete() error {
func (v *VSphereMachineTemplateWebhook) ValidateDelete(_ context.Context, _ runtime.Object) error {
return nil
}
13 changes: 8 additions & 5 deletions apis/v1beta1/vspheremachinetemplate_webhooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package v1beta1

import (
"context"
"testing"

. "github.com/onsi/gomega"
Expand Down Expand Up @@ -54,7 +55,8 @@ func TestVSphereMachineTemplate_ValidateCreate(t *testing.T) {
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
err := tc.vsphereMachine.ValidateCreate()
webhook := &VSphereMachineTemplateWebhook{}
err := webhook.ValidateCreate(context.Background(), tc.vsphereMachine)
if tc.wantErr {
g.Expect(err).To(HaveOccurred())
} else {
Expand Down Expand Up @@ -96,7 +98,8 @@ func TestVSphereMachineTemplate_ValidateUpdate(t *testing.T) {
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
err := tc.vsphereMachine.ValidateUpdate(tc.oldVSphereMachine)
webhook := &VSphereMachineTemplateWebhook{}
err := webhook.ValidateUpdate(context.Background(), tc.oldVSphereMachine, tc.vsphereMachine)
if tc.wantErr {
g.Expect(err).To(HaveOccurred())
} else {
Expand All @@ -107,7 +110,7 @@ func TestVSphereMachineTemplate_ValidateUpdate(t *testing.T) {
}

func createVSphereMachineTemplate(server string, providerID *string, preferredAPIServerCIDR string, ips []string) *VSphereMachineTemplate {
VSphereMachineTemplate := &VSphereMachineTemplate{
vsphereMachineTemplate := &VSphereMachineTemplate{
Spec: VSphereMachineTemplateSpec{
Template: VSphereMachineTemplateResource{
Spec: VSphereMachineSpec{
Expand All @@ -124,9 +127,9 @@ func createVSphereMachineTemplate(server string, providerID *string, preferredAP
},
}
for _, ip := range ips {
VSphereMachineTemplate.Spec.Template.Spec.Network.Devices = append(VSphereMachineTemplate.Spec.Template.Spec.Network.Devices, NetworkDeviceSpec{
vsphereMachineTemplate.Spec.Template.Spec.Network.Devices = append(vsphereMachineTemplate.Spec.Template.Spec.Network.Devices, NetworkDeviceSpec{
IPAddrs: []string{ip},
})
}
return VSphereMachineTemplate
return vsphereMachineTemplate
}
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,10 @@ spec:
blockOwnerDeletion:
description: If true, AND if the owner has the "foregroundDeletion"
finalizer, then the owner cannot be deleted from the
key-value store until this reference is removed. Defaults
key-value store until this reference is removed. See
https://kubernetes.io/docs/concepts/architecture/garbage-collection/#foreground-deletion
for how the garbage collector interacts with this
field and enforces the foreground deletion. Defaults
to false. To set this field, a user needs "delete"
permission of the owner, otherwise 422 (Unprocessable
Entity) will be returned.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ spec:
to the VM."
properties:
claimName:
description: 'ClaimName is the name of a PersistentVolumeClaim
description: 'claimName is the name of a PersistentVolumeClaim
in the same namespace as the pod using this volume. More
info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims'
type: string
Expand All @@ -339,8 +339,8 @@ spec:
- storageClass
type: object
readOnly:
description: Will force the ReadOnly setting in VolumeMounts.
Default false.
description: readOnly Will force the ReadOnly setting in
VolumeMounts. Default false.
type: boolean
required:
- claimName
Expand Down
2 changes: 2 additions & 0 deletions config/manager/manager.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,5 @@ spec:
tolerations:
- effect: NoSchedule
key: node-role.kubernetes.io/master
srm09 marked this conversation as resolved.
Show resolved Hide resolved
- effect: NoSchedule
key: node-role.kubernetes.io/control-plane
11 changes: 5 additions & 6 deletions controllers/serviceaccount_controller_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,12 @@ const (
testProviderSvcAccountName = "test-pvcsi"

testTargetNS = "test-pvcsi-system"
testTargetSecret = "test-pvcsi-secret" // nolint:gosec
testTargetSecret = "test-pvcsi-secret" //nolint:gosec
testSvcAccountSecretName = testProviderSvcAccountName + "-token-abcdef"
testSystemSvcAcctNs = "test-system-svc-acct-namespace"
testSystemSvcAcctCM = "test-system-svc-acct-cm"

testSecretToken = "ZXlKaGJHY2lPaUpTVXpJMU5pSXNJbXRwWkNJNklp" // nolint:gosec
testSecretToken = "ZXlKaGJHY2lPaUpTVXpJMU5pSXNJbXRwWkNJNklp" //nolint:gosec
)

var truePointer = true
Expand Down Expand Up @@ -109,7 +109,7 @@ func assertServiceAccountAndUpdateSecret(ctx goctx.Context, ctrlClient client.Cl
Expect(ctrlClient.Update(ctx, svcAccount)).To(Succeed())
}

func assertTargetSecret(ctx goctx.Context, guestClient client.Client, namespace, name string) { // nolint
func assertTargetSecret(ctx goctx.Context, guestClient client.Client, namespace, name string) { //nolint
secret := &corev1.Secret{}
assertEventuallyExistsInNamespace(ctx, guestClient, namespace, name, secret)
EventuallyWithOffset(2, func() []byte {
Expand Down Expand Up @@ -163,9 +163,8 @@ func assertRoleBinding(_ *builder.UnitTestContextForController, ctrlClient clien
}))
}

// nolint
func assertProviderServiceAccountsCondition(vCluster *vmwarev1.VSphereCluster, status corev1.ConditionStatus,
message string, reason string, severity clusterv1.ConditionSeverity) {
// assertProviderServiceAccountsCondition asserts the condition on the ProviderServiceAccount CR.
func assertProviderServiceAccountsCondition(vCluster *vmwarev1.VSphereCluster, status corev1.ConditionStatus, message string, reason string, severity clusterv1.ConditionSeverity) { //nolint
c := conditions.Get(vCluster, vmwarev1.ProviderServiceAccountsReadyCondition)
Expect(c).NotTo(BeNil())
Expect(c.Status).To(Equal(status))
Expand Down
3 changes: 1 addition & 2 deletions controllers/svcdiscovery_controller_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,7 @@ func assertHeadlessSvc(ctx context.Context, guestClient client.Client, namespace
Expect(headlessSvc.Spec.Ports[0].TargetPort.IntVal).To(Equal(int32(supervisorAPIServerPort)))
}

// nolint
func assertHeadlessSvcWithNoEndpoints(ctx context.Context, guestClient client.Client, namespace, name string) {
func assertHeadlessSvcWithNoEndpoints(ctx context.Context, guestClient client.Client, namespace, name string) { //nolint
assertHeadlessSvc(ctx, guestClient, namespace, name)
headlessEndpoints := &corev1.Endpoints{}
assertEventuallyDoesNotExistInNamespace(ctx, guestClient, namespace, name, headlessEndpoints)
Expand Down
5 changes: 3 additions & 2 deletions controllers/vmware/test/controllers_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ import (
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/klog/v2"
"k8s.io/klog/v2/klogr"
clusterv1 "sigs.k8s.io/cluster-api/api/v1alpha3"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/envtest"
Expand All @@ -60,7 +60,8 @@ var (
func init() {
klog.InitFlags(nil)
klog.SetOutput(GinkgoWriter)
logf.SetLogger(klogr.New())
ctrl.SetLogger(klog.Background())
logf.SetLogger(klog.Background())
}

func TestAPIs(t *testing.T) {
Expand Down
7 changes: 6 additions & 1 deletion controllers/vspherecluster_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func AddClusterControllerToManager(ctx *context.ControllerManagerContext, mgr ma
}

reconciler := clusterReconciler{ControllerContext: controllerContext}
clusterToInfraFn := clusterutilv1.ClusterToInfrastructureMapFunc(clusterControlledTypeGVK)
clusterToInfraFn := clusterToInfrastructureMapFunc(ctx)
return ctrl.NewControllerManagedBy(mgr).
// Watch the controlled, infrastructure resource.
For(clusterControlledType).
Expand Down Expand Up @@ -157,3 +157,8 @@ func AddClusterControllerToManager(ctx *context.ControllerManagerContext, mgr ma
WithOptions(controller.Options{MaxConcurrentReconciles: ctx.MaxConcurrentReconciles}).
Complete(reconciler)
}

func clusterToInfrastructureMapFunc(managerContext *context.ControllerManagerContext) handler.MapFunc {
gvk := infrav1.GroupVersion.WithKind(reflect.TypeOf(&infrav1.VSphereCluster{}).Elem().Name())
return clusterutilv1.ClusterToInfrastructureMapFunc(managerContext, gvk, managerContext.Client, &infrav1.VSphereCluster{})
}
4 changes: 2 additions & 2 deletions controllers/vspherecluster_reconciler.go
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,7 @@ func (r clusterReconciler) reconcileVSphereClusterWhenAPIServerIsOnline(ctx *con
go func() {
// Block until the target API server is online.
ctx.Logger.Info("start polling API server for online check")
wait.PollImmediateInfinite(time.Second*1, func() (bool, error) { return r.isAPIServerOnline(ctx), nil }) // nolint:errcheck
wait.PollImmediateInfinite(time.Second*1, func() (bool, error) { return r.isAPIServerOnline(ctx), nil }) //nolint:errcheck
ctx.Logger.Info("stop polling API server for online check")
ctx.Logger.Info("triggering GenericEvent", "reason", "api-server-online")
eventChannel := ctx.GetGenericEventChannelFor(ctx.VSphereCluster.GetObjectKind().GroupVersionKind())
Expand All @@ -399,7 +399,7 @@ func (r clusterReconciler) reconcileVSphereClusterWhenAPIServerIsOnline(ctx *con
// remove the key from the map that prevents multiple goroutines from
// polling the API server to see if it is online.
ctx.Logger.Info("start polling for control plane initialized")
wait.PollImmediateInfinite(time.Second*1, func() (bool, error) { return r.isControlPlaneInitialized(ctx), nil }) // nolint:errcheck
wait.PollImmediateInfinite(time.Second*1, func() (bool, error) { return r.isControlPlaneInitialized(ctx), nil }) //nolint:errcheck
ctx.Logger.Info("stop polling for control plane initialized")
apiServerTriggersMu.Lock()
delete(apiServerTriggers, ctx.Cluster.UID)
Expand Down
2 changes: 1 addition & 1 deletion controllers/vspheremachine_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ func (r machineReconciler) reconcileNormal(ctx context.MachineContext) (reconcil
// If the VSphereMachine doesn't have our finalizer, add it.
ctrlutil.AddFinalizer(ctx.GetVSphereMachine(), infrav1.MachineFinalizer)

// nolint:gocritic
//nolint:gocritic
if r.supervisorBased {
err := r.setVMModifiers(ctx)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion feature/gates.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ var (
// Only top-level commands/options setup and the k8s.io/component-base/featuregate/testing package should make use of this.
// Tests that need to modify featuregate gates for the duration of their test should use:
// defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.<FeatureName>, <value>)()
MutableGates featuregate.MutableFeatureGate = feature.MutableGates
MutableGates = feature.MutableGates

// Gates is a shared global FeatureGate.
// Top-level commands/options setup that needs to modify this featuregate gate should use DefaultMutableFeatureGate.
Expand Down
Loading