Skip to content

Commit

Permalink
Wrap long lines to 140 characters (#951)
Browse files Browse the repository at this point in the history
All lines > 140 characters are now wrapped.
As a consequence, also lll linter warnings are fixed.

Signed-off-by: Tomas Psota <tpsota@redhat.com>
  • Loading branch information
tompsota committed Jan 18, 2022
1 parent bfb2de7 commit 2af503d
Show file tree
Hide file tree
Showing 41 changed files with 680 additions and 268 deletions.
2 changes: 1 addition & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ linters:
- gosimple
#- govet
- ineffassign
#- lll
- lll
- misspell
- nakedret
- noctx
Expand Down
14 changes: 12 additions & 2 deletions controllers/handler/node_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,13 @@ import (
)

// Added for test purposes
type NmstateUpdater func(client client.Client, node *corev1.Node, observedState shared.State, nns *nmstatev1beta1.NodeNetworkState, versions *nmstate.DependencyVersions) error
type NmstateUpdater func(
client client.Client,
node *corev1.Node,
observedState shared.State,
nns *nmstatev1beta1.NodeNetworkState,
versions *nmstate.DependencyVersions,
) error
type NmstatectlShow func() (string, error)

// NodeReconciler reconciles a Node object
Expand Down Expand Up @@ -207,7 +213,11 @@ func (r *NodeReconciler) SetupWithManager(mgr ctrl.Manager) error {
}
err = ctrl.NewControllerManagedBy(mgr).
For(&nmstatev1beta1.NodeNetworkState{}).
Watches(&source.Kind{Type: &nmstatev1beta1.NodeNetworkState{}}, &handler.EnqueueRequestForOwner{OwnerType: &corev1.Node{}}, builder.WithPredicates(onDeleteOrForceUpdateForThisNode)).
Watches(
&source.Kind{Type: &nmstatev1beta1.NodeNetworkState{}},
&handler.EnqueueRequestForOwner{OwnerType: &corev1.Node{}},
builder.WithPredicates(onDeleteOrForceUpdateForThisNode),
).
Complete(r)
if err != nil {
return errors.Wrap(err, "failed to add controller to Node Reconciler listening Node Network State events")
Expand Down
41 changes: 26 additions & 15 deletions controllers/handler/node_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,14 @@ var _ = Describe("Node controller reconcile", func() {
},
}
expectRequeueAfterIsSetWithNetworkStateRefresh = func(result ctrl.Result) {
ExpectWithOffset(1, result.RequeueAfter).To(BeNumerically("~", nmstatenode.NetworkStateRefresh, float64(nmstatenode.NetworkStateRefresh)*nmstatenode.NetworkStateRefreshMaxFactor))
ExpectWithOffset(1, result.RequeueAfter).
To(
BeNumerically(
"~",
nmstatenode.NetworkStateRefresh,
float64(nmstatenode.NetworkStateRefresh)*nmstatenode.NetworkStateRefreshMaxFactor,
),
)
}
)
BeforeEach(func() {
Expand Down Expand Up @@ -216,20 +223,24 @@ routes:
By("Set last state")
reconciler.lastState = filteredOutObservedState
})
It("should create a new nodenetworkstate with node as owner reference, making sure the nodenetworkstate will be removed when the node is deleted", func() {
_, err := reconciler.Reconcile(context.Background(), request)
Expect(err).ToNot(HaveOccurred())

obtainedNNS := nmstatev1beta1.NodeNetworkState{}
nnsKey := types.NamespacedName{Name: existingNodeName}
err = cl.Get(context.TODO(), types.NamespacedName{Name: existingNodeName}, &obtainedNNS)
Expect(err).ToNot(HaveOccurred())
Expect(obtainedNNS.Name).To(Equal(nnsKey.Name))
Expect(obtainedNNS.ObjectMeta.OwnerReferences).To(HaveLen(1))
Expect(obtainedNNS.ObjectMeta.OwnerReferences[0]).To(Equal(
metav1.OwnerReference{Name: existingNodeName, Kind: "Node", APIVersion: "v1", UID: node.UID},
))
})
It(
"should create a new nodenetworkstate with node as owner reference, making sure "+
"the nodenetworkstate will be removed when the node is deleted",
func() {
_, err := reconciler.Reconcile(context.Background(), request)
Expect(err).ToNot(HaveOccurred())

obtainedNNS := nmstatev1beta1.NodeNetworkState{}
nnsKey := types.NamespacedName{Name: existingNodeName}
err = cl.Get(context.TODO(), types.NamespacedName{Name: existingNodeName}, &obtainedNNS)
Expect(err).ToNot(HaveOccurred())
Expect(obtainedNNS.Name).To(Equal(nnsKey.Name))
Expect(obtainedNNS.ObjectMeta.OwnerReferences).To(HaveLen(1))
Expect(obtainedNNS.ObjectMeta.OwnerReferences[0]).To(Equal(
metav1.OwnerReference{Name: existingNodeName, Kind: "Node", APIVersion: "v1", UID: node.UID},
))
},
)
It("should return a Result with RequeueAfter set (trigger re-reconciliation)", func() {
result, err := reconciler.Reconcile(context.Background(), request)
Expect(err).ToNot(HaveOccurred())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,14 @@ var _ = Describe("Node Network Configuration Enactment controller reconcile", fu
},
}
expectRequeueAfterIsSetWithEnactmentRefresh = func(result ctrl.Result) {
ExpectWithOffset(1, result.RequeueAfter).To(BeNumerically("~", nmstateenactment.EnactmentRefresh, float64(nmstateenactment.EnactmentRefresh)*nmstateenactment.EnactmentRefreshMaxFactor))
ExpectWithOffset(1, result.RequeueAfter).
To(
BeNumerically(
"~",
nmstateenactment.EnactmentRefresh,
float64(nmstateenactment.EnactmentRefresh)*nmstateenactment.EnactmentRefreshMaxFactor,
),
)
}
)
BeforeEach(func() {
Expand Down
55 changes: 40 additions & 15 deletions controllers/handler/nodenetworkconfigurationpolicy_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,9 @@ func (r *NodeNetworkConfigurationPolicyReconciler) SetupWithManager(mgr ctrl.Man
return nil
}

func (r *NodeNetworkConfigurationPolicyReconciler) initializeEnactment(policy nmstatev1.NodeNetworkConfigurationPolicy) (*nmstatev1beta1.NodeNetworkConfigurationEnactment, error) {
func (r *NodeNetworkConfigurationPolicyReconciler) initializeEnactment(
policy nmstatev1.NodeNetworkConfigurationPolicy,
) (*nmstatev1beta1.NodeNetworkConfigurationEnactment, error) {
enactmentKey := nmstateapi.EnactmentKey(nodeName, policy.Name)
log := r.Log.WithName("initializeEnactment").WithValues("policy", policy.Name, "enactment", enactmentKey.Name)
// Return if it's already initialize or we cannot retrieve it
Expand Down Expand Up @@ -312,11 +314,20 @@ func (r *NodeNetworkConfigurationPolicyReconciler) fillInEnactmentStatus(nns *nm
policy nmstatev1.NodeNetworkConfigurationPolicy,
enactment nmstatev1beta1.NodeNetworkConfigurationEnactment,
enactmentConditions enactmentconditions.EnactmentConditions) error {
capturedStates, desiredStateMetaInfo, generatedDesiredState, err := nmpolicy.GenerateState(policy.Spec.DesiredState, policy.Spec, nns.Status.CurrentState, enactment.Status.CapturedStates)
capturedStates, desiredStateMetaInfo, generatedDesiredState, err := nmpolicy.GenerateState(
policy.Spec.DesiredState,
policy.Spec,
nns.Status.CurrentState,
enactment.Status.CapturedStates,
)
if err != nil {
err2 := enactmentstatus.Update(r.APIClient, nmstateapi.EnactmentKey(nodeName, policy.Name), func(status *nmstateapi.NodeNetworkConfigurationEnactmentStatus) {
status.PolicyGeneration = policy.Generation
})
err2 := enactmentstatus.Update(
r.APIClient,
nmstateapi.EnactmentKey(nodeName, policy.Name),
func(status *nmstateapi.NodeNetworkConfigurationEnactmentStatus) {
status.PolicyGeneration = policy.Generation
},
)
if err2 != nil {
return err2
}
Expand All @@ -329,15 +340,21 @@ func (r *NodeNetworkConfigurationPolicyReconciler) fillInEnactmentStatus(nns *nm
return err
}

return enactmentstatus.Update(r.APIClient, nmstateapi.EnactmentKey(nodeName, policy.Name), func(status *nmstateapi.NodeNetworkConfigurationEnactmentStatus) {
status.DesiredState = desiredStateWithDefaults
status.DesiredStateMetaInfo = desiredStateMetaInfo
status.CapturedStates = capturedStates
status.PolicyGeneration = policy.Generation
})
return enactmentstatus.Update(
r.APIClient,
nmstateapi.EnactmentKey(nodeName, policy.Name),
func(status *nmstateapi.NodeNetworkConfigurationEnactmentStatus) {
status.DesiredState = desiredStateWithDefaults
status.DesiredStateMetaInfo = desiredStateMetaInfo
status.CapturedStates = capturedStates
status.PolicyGeneration = policy.Generation
},
)
}

func (r *NodeNetworkConfigurationPolicyReconciler) enactmentForPolicy(policy *nmstatev1.NodeNetworkConfigurationPolicy) (*nmstatev1beta1.NodeNetworkConfigurationEnactment, error) {
func (r *NodeNetworkConfigurationPolicyReconciler) enactmentForPolicy(
policy *nmstatev1.NodeNetworkConfigurationPolicy,
) (*nmstatev1beta1.NodeNetworkConfigurationEnactment, error) {
enactmentKey := nmstateapi.EnactmentKey(nodeName, policy.Name)
instance := &nmstatev1beta1.NodeNetworkConfigurationEnactment{}
err := r.APIClient.Get(context.TODO(), enactmentKey, instance)
Expand Down Expand Up @@ -379,7 +396,10 @@ func (r *NodeNetworkConfigurationPolicyReconciler) deleteEnactmentForPolicy(poli
return nil
}

func (r *NodeNetworkConfigurationPolicyReconciler) shouldIncrementUnavailableNodeCount(policy *nmstatev1.NodeNetworkConfigurationPolicy, conditions *nmstateapi.ConditionList) bool {
func (r *NodeNetworkConfigurationPolicyReconciler) shouldIncrementUnavailableNodeCount(
policy *nmstatev1.NodeNetworkConfigurationPolicy,
conditions *nmstateapi.ConditionList,
) bool {
return !enactmentstatus.IsProgressing(conditions) &&
(policy.Status.LastUnavailableNodeCountUpdate == nil ||
time.Since(policy.Status.LastUnavailableNodeCountUpdate.Time) < (nmstate.DesiredStateConfigurationTimeout+probe.ProbesTotalTimeout))
Expand Down Expand Up @@ -419,7 +439,11 @@ func (r *NodeNetworkConfigurationPolicyReconciler) decrementUnavailableNodeCount
}
}

func tryDecrementingUnavailableNodeCount(statusWriterClient client.StatusClient, readerClient client.Reader, policyKey types.NamespacedName) error {
func tryDecrementingUnavailableNodeCount(
statusWriterClient client.StatusClient,
readerClient client.Reader,
policyKey types.NamespacedName,
) error {
instance := &nmstatev1.NodeNetworkConfigurationPolicy{}
err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
err := readerClient.Get(context.TODO(), policyKey, instance)
Expand All @@ -441,7 +465,8 @@ func (r *NodeNetworkConfigurationPolicyReconciler) forceNNSRefresh(name string)
log.Info("forcing NodeNetworkState refresh after NNCP applied")
nns, err := r.readNNS(name)
if err != nil {
log.WithValues("error", err).Info("WARNING: failed retrieving NodeNetworkState to force refresh, it will be refreshed after regular period")
log.WithValues("error", err).
Info("WARNING: failed retrieving NodeNetworkState to force refresh, it will be refreshed after regular period")
return
}
if nns.Labels == nil {
Expand Down
10 changes: 8 additions & 2 deletions controllers/operator/nmstate_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ type NMStateReconciler struct {
Scheme *runtime.Scheme
}

// +kubebuilder:rbac:groups="",resources=services;endpoints;persistentvolumeclaims;events;configmaps;secrets;pods,verbs="*",namespace="{{ .OperatorNamespace }}"
// +kubebuilder:rbac:groups="",resources=services;endpoints;persistentvolumeclaims;events;configmaps;secrets;pods,verbs="*"
//,namespace="{{ .OperatorNamespace }}"
// +kubebuilder:rbac:groups=apps,resources=deployments;daemonsets;replicasets;statefulsets,verbs="*",namespace="{{ .OperatorNamespace }}"
// +kubebuilder:rbac:groups=policy,resources=poddisruptionbudgets,verbs="*",namespace="{{ .OperatorNamespace }}"
// +kubebuilder:rbac:groups=admissionregistration.k8s.io,resources=mutatingwebhookconfigurations,verbs="*"
Expand Down Expand Up @@ -222,7 +223,12 @@ func (r *NMStateReconciler) applyHandler(instance *nmstatev1.NMState) error {
return r.renderAndApply(instance, data, "handler", true)
}

func (r *NMStateReconciler) renderAndApply(instance *nmstatev1.NMState, data render.RenderData, sourceDirectory string, setControllerReference bool) error {
func (r *NMStateReconciler) renderAndApply(
instance *nmstatev1.NMState,
data render.RenderData,
sourceDirectory string,
setControllerReference bool,
) error {
var err error

sourceFullDirectory := filepath.Join(names.ManifestDir, "kubernetes-nmstate", sourceDirectory)
Expand Down
24 changes: 12 additions & 12 deletions deploy/operator/role.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,18 @@ metadata:
creationTimestamp: null
name: nmstate-operator
rules:
- apiGroups:
- ""
resources:
- configmaps
- endpoints
- events
- persistentvolumeclaims
- pods
- secrets
- services
verbs:
- '*'
- apiGroups:
- ""
resources:
Expand Down Expand Up @@ -59,18 +71,6 @@ metadata:
name: nmstate-operator
namespace: '{{ .OperatorNamespace }}'
rules:
- apiGroups:
- ""
resources:
- configmaps
- endpoints
- events
- persistentvolumeclaims
- pods
- secrets
- services
verbs:
- '*'
- apiGroups:
- apps
resources:
Expand Down
9 changes: 8 additions & 1 deletion pkg/enactmentstatus/conditions/counter.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,14 @@ func (c ConditionCount) NotAborted() int {
}

func (c ConditionCount) String() string {
return fmt.Sprintf("{failed: %s, progressing: %s, pending: %s, available: %s, aborted: %s}", c.failed(), c.progressing(), c.pending(), c.available(), c.aborted())
return fmt.Sprintf(
"{failed: %s, progressing: %s, pending: %s, available: %s, aborted: %s}",
c.failed(),
c.progressing(),
c.pending(),
c.available(),
c.aborted(),
)
}

func (c CountByConditionStatus) String() string {
Expand Down
31 changes: 21 additions & 10 deletions pkg/enactmentstatus/message_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,29 @@ import (

var _ = Describe("Error messages formatting", func() {
var (
debugInvalidInput = " 2021-04-15 08:17:35,057 root DEBUG Async action: Create checkpoint started\n 2021-04-15 08:17:35,060 root DEBUG Checkpoint None created for all devices\n"
debugValidInput = "A message containing debug that should not be removed.\n"
tracebackInvalidInput = " Traceback (most recent call last):\n File \"/usr/bin/nmstatectl\", line 11, in <module>\n load_entry_point('nmstate==0.3.6', 'console_scripts', 'nmstatectl')()\n File \"/usr/lib/python3.6/site-packages/nmstatectl/nmstatectl.py\", line 69, in main\n f\"Interface {iface.name} has unknown slave: \"\n libnmstate.error.NmstateValueError: Interface bond1 has unknown slave: eth10\n "
debugInvalidInput = " 2021-04-15 08:17:35,057 root DEBUG Async action: Create checkpoint started\n " +
"2021-04-15 08:17:35,060 root DEBUG Checkpoint None created for all devices\n"
debugValidInput = "A message containing debug that should not be removed.\n"
tracebackInvalidInput = " Traceback (most recent call last):\n File \"/usr/bin/nmstatectl\", line 11, in <module>\n " +
" load_entry_point('nmstate==0.3.6', 'console_scripts', 'nmstatectl')()\n File \"/usr/lib/python3.6/" +
"site-packages/nmstatectl/nmstatectl.py\", line 69, in main\n f\"Interface {iface.name} has unknown slave: \"\n " +
"libnmstate.error.NmstateValueError: Interface bond1 has unknown slave: eth10\n "
tracebackInvalidOutput = " libnmstate.error.NmstateValueError\n Interface bond1 has unknown slave\n eth10\n"
tracebackValidInput = "A message containing File \"/usr/bin/nmstatectl\" that should not be removed.\n"
failedToExecuteInput = " failed to execute nmstatectl set --no-commit --timeout 480: 'exit status 1' '' '2021-02-22 11:10:08,962 root WARNING libnm version 1.26.7 mismatches NetworkManager version 1.29.9\n"
failedToExecuteOutput = "failed to execute nmstatectl set --no-commit --timeout 480: 'exit status 1'\n"
pingInvalidInput = "rolling back desired state configuration: failed runnig probes after network changes: failed runnig probe 'ping' with after network reconfiguration -> currentState: ---\n dns-resolver:\n config:\n search: []\n server: []\n running: {}\n route-rules:\n config: []\n : failed to retrieve default gw at runProbes: timed out waiting for the condition"
pingInvalidOutput = " \n failed to retrieve default gw at runProbes\n timed out waiting for the condition\n"
pingValidInput = "rolling back desired state configuration: failed runnig probes after network changes: failed runnig probe 'ping' with after network reconfiguration.\nThe rest of the message should be kept.\n"
pingValidOutput = "rolling back desired state configuration\n failed runnig probes after network changes\n failed runnig probe 'ping' with after network reconfiguration.\nThe rest of the message should be kept.\n"
desiredStateYaml = "libnmstate.error.NmstateVerificationError:\n desired\n =======\n---\n name: eth1\n type: ethernet\n state: up\n"
failedToExecuteInput = " failed to execute nmstatectl set --no-commit --timeout 480: 'exit status 1' '' '2021-02-22 " +
"11:10:08,962 root WARNING libnm version 1.26.7 mismatches NetworkManager version 1.29.9\n"
failedToExecuteOutput = "failed to execute nmstatectl set --no-commit --timeout 480: 'exit status 1'\n"
pingInvalidInput = "rolling back desired state configuration: failed runnig probes after network changes: failed runnig " +
"probe 'ping' with after network reconfiguration -> currentState: ---\n dns-resolver:\n config:\n " +
"search: []\n server: []\n running: {}\n route-rules:\n config: []\n : failed to retrieve " +
"default gw at runProbes: timed out waiting for the condition"
pingInvalidOutput = " \n failed to retrieve default gw at runProbes\n timed out waiting for the condition\n"
pingValidInput = "rolling back desired state configuration: failed runnig probes after network changes: failed runnig " +
"probe 'ping' with after network reconfiguration.\nThe rest of the message should be kept.\n"
pingValidOutput = "rolling back desired state configuration\n failed runnig probes after network changes\n failed " +
"runnig probe 'ping' with after network reconfiguration.\nThe rest of the message should be kept.\n"
desiredStateYaml = "libnmstate.error.NmstateVerificationError:\n desired\n =======\n---\n name: eth1\n " +
"type: ethernet\n state: up\n"
)

Context("With DEBUG text", func() {
Expand Down
19 changes: 15 additions & 4 deletions pkg/helper/bridges.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,11 @@ func ApplyDefaultVlanFiltering(desiredState nmstate.State) (nmstate.State, error
if hasVlanConfiguration(port) {
continue
}
result, err = sjson.SetBytes(result, fmt.Sprintf("interfaces.%d.bridge.port.%d.vlan", ifaceIndex, portIndex), defaultVlanFiltering)
result, err = sjson.SetBytes(
result,
fmt.Sprintf("interfaces.%d.bridge.port.%d.vlan", ifaceIndex, portIndex),
defaultVlanFiltering,
)
if err != nil {
return desiredState, err
}
Expand All @@ -84,7 +88,10 @@ func EnableVlanFiltering(desiredState nmstate.State) (string, error) {
if err != nil {
return "failed to list bridges with ports", err
}
filteredExistingUpBridgesWithPortsAtDesiredState, err := filterExistingLinuxBridgesWithPorts(upBridgesWithPortsAtCurrentState, desiredState)
filteredExistingUpBridgesWithPortsAtDesiredState, err := filterExistingLinuxBridgesWithPorts(
upBridgesWithPortsAtCurrentState,
desiredState,
)
if err != nil {
return "failed to filter existing bridges with ports from desiredState", err
}
Expand Down Expand Up @@ -120,7 +127,10 @@ func GetUpLinuxBridgesWithPorts(desiredState nmstate.State) (map[string][]string
return bridgesWithPorts, nil
}

func filterExistingLinuxBridgesWithPorts(bridgesAtCurrentState map[string][]string, desiredState nmstate.State) (map[string][]string, error) {
func filterExistingLinuxBridgesWithPorts(
bridgesAtCurrentState map[string][]string,
desiredState nmstate.State,
) (map[string][]string, error) {
filteredBridgesWithPorts := map[string][]string{}
bridgesAtDesiredState, err := GetUpLinuxBridgesWithPorts(desiredState)
if err != nil {
Expand Down Expand Up @@ -168,7 +178,8 @@ func runCommand(command string, args []string) (string, error) {
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("failed to execute %s %s: '%v', '%s', '%s'", command, strings.Join(args, " "), err, stdout.String(), stderr.String())
return "",
fmt.Errorf("failed to execute %s %s: '%v', '%s', '%s'", command, strings.Join(args, " "), err, stdout.String(), stderr.String())
}
return stdout.String(), nil
}
Expand Down
Loading

0 comments on commit 2af503d

Please sign in to comment.