Skip to content

Commit

Permalink
Rewrite with linter (#15)
Browse files Browse the repository at this point in the history
- Fix formatting issues
- Resolve linting errors and warnings
- Update code to follow linter recommendations
- Re-enable linter

---------

Co-authored-by: alperencelik <alp.celik@axon-networks.com>
  • Loading branch information
alperencelik and alperencelik authored Jan 26, 2024
1 parent d85a08b commit 65d7f78
Show file tree
Hide file tree
Showing 20 changed files with 276 additions and 315 deletions.
40 changes: 20 additions & 20 deletions .github/workflows/golangci-lint.yaml
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
# name: GolangCI-Lint
name: GolangCI-Lint

# on:
# pull_request:
# types: [opened, edited, synchronize, reopened]
on:
pull_request:
types: [opened, edited, synchronize, reopened]

# jobs:
# lint:
# name: Lint
# runs-on: ubuntu-latest
jobs:
lint:
name: Lint
runs-on: ubuntu-latest

# steps:
# - name: Checkout Repository
# uses: actions/checkout@v2
steps:
- name: Checkout Repository
uses: actions/checkout@v2

# - name: Set Up Go
# uses: actions/setup-go@v2
# with:
# go-version: 1.20.5 # Replace with the Go version you're using
- name: Set Up Go
uses: actions/setup-go@v2
with:
go-version: 1.20.5 # Replace with the Go version you're using

# - name: Install golangci-lint
# run: |
# curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.54.2
- name: Install golangci-lint
run: |
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.54.2
# - name: Run Linter
# run: golangci-lint run --timeout 10m --verbose
- name: Run Linter
run: golangci-lint run --timeout 10m --verbose
4 changes: 2 additions & 2 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,10 @@ linters:
- dupl
- errcheck
- exportloopref
- gochecknoinits
# - gochecknoinits
- goconst
- gocritic
- gocyclo
# - gocyclo
- gofmt
- goimports
- goprintffuncname
Expand Down
2 changes: 1 addition & 1 deletion api/proxmox/v1alpha1/container_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,6 @@ type ContainerList struct {
Items []Container `json:"items"`
}

func init() {
func init() { //nolint:gochecknoinits // This is required by kubebuilder
SchemeBuilder.Register(&Container{}, &ContainerList{})
}
19 changes: 3 additions & 16 deletions api/proxmox/v1alpha1/managedvirtualmachine_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,19 +36,6 @@ type ManagedVirtualMachineSpec struct {
Disk int `json:"disk"`
}

// ManagedVirtualMachineStatus defines the observed state of ManagedVirtualMachine
type ManagedVirtualMachineStatus struct {
// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
// Important: Run "make" to regenerate code after modifying this file
State string `json:"state,omitempty"`
Node string `json:"node,omitempty"`
Name string `json:"name,omitempty"`
Uptime string `json:"uptime,omitempty"`
ID int `json:"id,omitempty"`
IPAddress string `json:"IPAddress,omitempty"`
OSInfo string `json:"OSInfo,omitempty"`
}

//+kubebuilder:object:root=true
//+kubebuilder:subresource:status

Expand All @@ -57,8 +44,8 @@ type ManagedVirtualMachine struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`

Spec ManagedVirtualMachineSpec `json:"spec,omitempty"`
Status ManagedVirtualMachineStatus `json:"status,omitempty"`
Spec ManagedVirtualMachineSpec `json:"spec,omitempty"`
Status VirtualMachineStatus `json:"status,omitempty"`
}

//+kubebuilder:object:root=true
Expand All @@ -70,6 +57,6 @@ type ManagedVirtualMachineList struct {
Items []ManagedVirtualMachine `json:"items"`
}

func init() {
func init() { //nolint:gochecknoinits // This is required by kubebuilder
SchemeBuilder.Register(&ManagedVirtualMachine{}, &ManagedVirtualMachineList{})
}
4 changes: 2 additions & 2 deletions api/proxmox/v1alpha1/virtualmachine_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ type VirtualMachineSpec struct {
// TemplateSpec of the source VM
Template VirtualMachineTemplate `json:"template,omitempty"`
// This field should be modified further
VmSpec NewVMSpec `json:"vmSpec,omitempty"`
VMSpec NewVMSpec `json:"vmSpec,omitempty"`
}

type NewVMSpec struct {
Expand Down Expand Up @@ -132,6 +132,6 @@ type VirtualMachineList struct {
Items []VirtualMachine `json:"items"`
}

func init() {
func init() { //nolint:gochecknoinits // This is required by kubebuilder
SchemeBuilder.Register(&VirtualMachine{}, &VirtualMachineList{})
}
2 changes: 1 addition & 1 deletion api/proxmox/v1alpha1/virtualmachineset_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,6 @@ type VirtualMachineSetList struct {
Items []VirtualMachineSet `json:"items"`
}

func init() {
func init() { //nolint:gochecknoinits // This is required by kubebuilder
SchemeBuilder.Register(&VirtualMachineSet{}, &VirtualMachineSetList{})
}
2 changes: 1 addition & 1 deletion api/proxmox/v1alpha1/virtualmachinesnapshot_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,6 @@ type VirtualMachineSnapshotList struct {
Items []VirtualMachineSnapshot `json:"items"`
}

func init() {
func init() { //nolint:gochecknoinits // This is required by kubebuilder
SchemeBuilder.Register(&VirtualMachineSnapshot{}, &VirtualMachineSnapshotList{})
}
2 changes: 1 addition & 1 deletion api/proxmox/v1alpha1/virtualmachinesnapshotpolicy_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,6 @@ type VirtualMachineSnapshotPolicyList struct {
Items []VirtualMachineSnapshotPolicy `json:"items"`
}

func init() {
func init() { //nolint:gochecknoinits // This is required by kubebuilder
SchemeBuilder.Register(&VirtualMachineSnapshotPolicy{}, &VirtualMachineSnapshotPolicyList{})
}
17 changes: 1 addition & 16 deletions api/proxmox/v1alpha1/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ var (
setupLog = ctrl.Log.WithName("setup")
)

func init() {
func init() { //nolint:gochecknoinits // This is required by kubebuilder
utilruntime.Must(clientgoscheme.AddToScheme(scheme))

utilruntime.Must(proxmoxv1alpha1.AddToScheme(scheme))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,7 @@ spec:
- nodeName
type: object
status:
description: ManagedVirtualMachineStatus defines the observed state of
ManagedVirtualMachine
description: VirtualMachineStatus defines the observed state of VirtualMachine
properties:
IPAddress:
type: string
Expand Down
5 changes: 2 additions & 3 deletions internal/controller/proxmox/container_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ func (r *ContainerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (
// The object is not being deleted, so if it does not have our finalizer, then lets add the finalizer and update the object.
if !controllerutil.ContainsFinalizer(container, containerFinalizerName) {
controllerutil.AddFinalizer(container, containerFinalizerName)
if err := r.Update(ctx, container); err != nil {
if err = r.Update(ctx, container); err != nil {
log.Log.Error(err, "Error updating Container")
return ctrl.Result{}, client.IgnoreNotFound(err)
}
Expand All @@ -97,7 +97,7 @@ func (r *ContainerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (
}
// Remove finalizer
controllerutil.RemoveFinalizer(container, containerFinalizerName)
if err := r.Update(ctx, container); err != nil {
if err = r.Update(ctx, container); err != nil {
Log.Error(err, "Error updating Container")
}
}
Expand Down Expand Up @@ -137,7 +137,6 @@ func (r *ContainerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (
Log.Error(err, "Failed to update Container")
return ctrl.Result{}, client.IgnoreNotFound(err)
}

}
} else {
// Create Container
Expand Down
13 changes: 5 additions & 8 deletions internal/controller/proxmox/managedvirtualmachine_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func (r *ManagedVirtualMachineReconciler) Reconcile(ctx context.Context, req ctr

// Remove finalizer
controllerutil.RemoveFinalizer(managedVM, managedvirtualMachineFinalizerName)
if err := r.Update(ctx, managedVM); err != nil {
if err = r.Update(ctx, managedVM); err != nil {
log.Log.Info(fmt.Sprintf("Error updatin ManagedVirtualMachine %s", managedVM.Name))
}
return ctrl.Result{}, nil
Expand All @@ -105,22 +105,19 @@ func (r *ManagedVirtualMachineReconciler) Reconcile(ctx context.Context, req ctr
return ctrl.Result{}, client.IgnoreNotFound(err)
}
// Update ManagedVMStatus
var managedVMStatus proxmoxv1alpha1.ManagedVirtualMachineStatus
nodeName := proxmox.GetNodeOfVM(managedVM.Name)
managedVMStatus.State, managedVMStatus.ID, managedVMStatus.Uptime, managedVMStatus.Node, managedVMStatus.Name, managedVMStatus.IPAddress, managedVMStatus.OSInfo = proxmox.UpdateVMStatus(managedVM.Name, nodeName)
managedVM.Status = managedVMStatus
managedVMName := managedVM.Name
nodeName := proxmox.GetNodeOfVM(managedVMName)
ManagedVMStatus, _ := proxmox.UpdateVMStatus(managedVMName, nodeName)
managedVM.Status = *ManagedVMStatus
err = r.Status().Update(context.Background(), managedVM)
if err != nil {
log.Log.Info(fmt.Sprintf("ManagedVMStatus %v could not be updated", managedVM.Name))
}

return ctrl.Result{Requeue: true, RequeueAfter: ManagedVMreconcilationPeriod * time.Second}, nil

}

// SetupWithManager sets up the controller with the Manager.
func (r *ManagedVirtualMachineReconciler) SetupWithManager(mgr ctrl.Manager) error {

// Get all VMs with Proxmox API
AllVMs := proxmox.GetProxmoxVMs()
ControllerVMs := proxmox.GetControllerVMs()
Expand Down
37 changes: 16 additions & 21 deletions internal/controller/proxmox/virtualmachine_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,15 +67,15 @@ func (r *VirtualMachineReconciler) Reconcile(ctx context.Context, req ctrl.Reque
vm := &proxmoxv1alpha1.VirtualMachine{}
err := r.Get(ctx, req.NamespacedName, vm)
if err != nil {
// Log.Error(err, "unable to fetch VirtualMachine")
Log.Error(err, "unable to fetch VirtualMachine")
return ctrl.Result{}, client.IgnoreNotFound(err)
}

// Check if the VirtualMachine instance is marked to be deleted, which is indicated by the deletion timestamp being set.
if vm.ObjectMeta.DeletionTimestamp.IsZero() {
if !controllerutil.ContainsFinalizer(vm, virtualMachineFinalizerName) {
controllerutil.AddFinalizer(vm, virtualMachineFinalizerName)
if err := r.Update(ctx, vm); err != nil {
if err = r.Update(ctx, vm); err != nil {
log.Log.Error(err, "Error updating VirtualMachine")
}
}
Expand All @@ -93,10 +93,9 @@ func (r *VirtualMachineReconciler) Reconcile(ctx context.Context, req ctrl.Reque
}
// Remove finalizer
controllerutil.RemoveFinalizer(vm, virtualMachineFinalizerName)
if err := r.Update(ctx, vm); err != nil {
if err = r.Update(ctx, vm); err != nil {
fmt.Printf("Error updating VirtualMachine %s", vm.Spec.Name)
}

}
// Stop reconciliation as the item is being deleted
return ctrl.Result{}, client.IgnoreNotFound(err)
Expand Down Expand Up @@ -131,55 +130,51 @@ func (r *VirtualMachineReconciler) Reconcile(ctx context.Context, req ctrl.Reque
// If not exists, create the VM
Log.Info(fmt.Sprintf("VirtualMachine %s doesn't exist", vmName))
vmType := proxmox.CheckVMType(vm)
if vmType == "template" {
switch vmType {
case "template":
kubernetes.CreateVMKubernetesEvent(vm, Clientset, "Creating")
proxmox.CreateVMFromTemplate(vm)
proxmox.StartVM(vmName, nodeName)
kubernetes.CreateVMKubernetesEvent(vm, Clientset, "Created")
// metrics.SetVirtualMachineCPUCores(vmName, vm.Namespace, float64(vm.Spec.Template.Cores))
// metrics.SetVirtualMachineMemory(vmName, vm.Namespace, float64(vm.Spec.Template.Memory))
} else if vmType == "scratch" {
case "scratch":
kubernetes.CreateVMKubernetesEvent(vm, Clientset, "Creating")
proxmox.CreateVMFromScratch(vm)
proxmox.StartVM(vmName, nodeName)
kubernetes.CreateVMKubernetesEvent(vm, Clientset, "Created")
// metrics.SetVirtualMachineCPUCores(vmName, vm.Namespace, float64(vm.Spec.VmSpec.Cores))
// metrics.SetVirtualMachineMemory(vmName, vm.Namespace, float64(vm.Spec.VmSpec.Memory))
} else {
default:
Log.Info(fmt.Sprintf("VM %s doesn't have any template or vmSpec defined", vmName))
}
}
// If template and created VM has different resources then update the VM with new resources the function itself decides if VM restart needed or not
// If template and created VM has different resources then update the VM with new resources the function itself
// decides if VM restart needed or not
proxmox.UpdateVM(vmName, nodeName, vm)
err = r.Update(context.Background(), vm)
if err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
// Update the status of VirtualMachine resource
var Status proxmoxv1alpha1.VirtualMachineStatus
Status.State, Status.ID, Status.Uptime, Status.Node, Status.Name, Status.IPAddress, Status.OSInfo = proxmox.UpdateVMStatus(vmName, nodeName)
vm.Status = Status
Status, _ := proxmox.UpdateVMStatus(vmName, nodeName)
vm.Status = *Status
err = r.Status().Update(ctx, vm)
if err != nil {
Log.Error(err, "Error updating VirtualMachine status")
}

return ctrl.Result{Requeue: true, RequeueAfter: VMreconcilationPeriod * time.Second}, client.IgnoreNotFound(err)

}

// SetupWithManager sets up the controller with the Manager.
func (r *VirtualMachineReconciler) SetupWithManager(mgr ctrl.Manager) error {

log := log.FromContext(context.Background())
logger := log.FromContext(context.Background())
version, err := proxmox.GetProxmoxVersion()
if err != nil {
log.Error(err, "Error getting Proxmox version")
logger.Error(err, "Error getting Proxmox version")
}
log.Info(fmt.Sprintf("Connected to the Proxmox, version is: %s", version))
logger.Info(fmt.Sprintf("Connected to the Proxmox, version is: %s", version))
return ctrl.NewControllerManagedBy(mgr).
For(&proxmoxv1alpha1.VirtualMachine{}).
WithEventFilter(predicate.GenerationChangedPredicate{}). // --> This was needed for reconcile loop to work properly, otherwise it was reconciling 3-4 times every 10 seconds
// --> This was needed for reconcile loop to work properly, otherwise it was reconciling 3-4 times every 10 seconds
WithEventFilter(predicate.GenerationChangedPredicate{}).
WithOptions(controller.Options{MaxConcurrentReconciles: VMmaxConcurrentReconciles}).
Complete(&VirtualMachineReconciler{
Client: mgr.GetClient(),
Expand Down
Loading

0 comments on commit 65d7f78

Please sign in to comment.