Repository: kubernetes-sigs/kwok (go)
Issue: panic caused by nil point
### How to use it?

- [X] kwok
- [ ] kwokctl --runtime=docker (default runtime)
- [ ] kwokctl --runtime=binary
- [ ] kwokctl --runtime=nerdctl
- [ ] kwokctl --runtime=kind

### What happened?

There is a panic when I execute kwok with `--manage-nodes-with-label-selector=node-role.kubernetes.io/worker`:


```
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x1595ba6]

goroutine 82 [running]:
sigs.k8s.io/kwok/pkg/kwok/controllers.(*NodeController).needLockNode(0xc000514600, 0xc0002cc000)
	/opt/tiger/compile_path/src/code.byted.org/godel/kwok/pkg/kwok/controllers/node_controller.go:164 +0x26
sigs.k8s.io/kwok/pkg/kwok/controllers.(*NodeController).WatchNodes.func1()
	/opt/tiger/compile_path/src/code.byted.org/godel/kwok/pkg/kwok/controllers/node_controller.go:215 +0x1a6
created by sigs.k8s.io/kwok/pkg/kwok/controllers.(*NodeController).WatchNodes
	/opt/tiger/compile_path/src/code.byted.org/godel/kwok/pkg/kwok/controllers/node_controller.go:190 +0x2ec
```

### What did you expect to happen?

Expect to execute kwok with `--manage-nodes-with-label-selector=node-role.kubernetes.io/worker` successfully.

### How can we reproduce it (as minimally and precisely as possible)?

Execute kwok wtih `--manage-nodes-with-label-selector=node-role.kubernetes.io/worker`:

### Anything else we need to know?

_No response_

### Kwok version

<details>

```console
$ kwok --version
kwok version ad2f53b

```
</details>


### OS version

<details>

```console
$ cat /etc/os-release
  PRETTY_NAME="Debian GNU/Linux 9 (stretch)"
  NAME="Debian GNU/Linux"
  VERSION_ID="9"
  VERSION="9 (stretch)"
  VERSION_CODENAME=stretch
  ID=debian
  HOME_URL="https://www.debian.org/"
  SUPPORT_URL="https://www.debian.org/support"
  BUG_REPORT_URL="https://bugs.debian.org/

$ uname -a
  Linux kind-simulator-control-plane 5.4.143.bsk.8-amd64 #5.4.143.bsk.8 SMP Debian 5.4.143.bsk.8 Wed Jul 20 08:43:36 UTC  x86_64 GNU/Linux

```
</details>

Pull request description: initialize nodeSelectorFunc when --manage-nodes-with-label-selector is set
<!--  Thanks for sending a pull request!  Here are some tips for you:

1. If this is your first time, please read our contributor guidelines: https://git.k8s.io/community/contributors/guide/first-contribution.md#your-first-contribution and developer guide https://git.k8s.io/community/contributors/devel/development.md#development-guide
2. Please label this pull request according to what type of issue you are addressing, especially if this is a release targeted pull request. For reference on required PR/issue labels, read here:
https://git.k8s.io/community/contributors/devel/sig-release/release.md#issuepr-kind-label
3. Ensure you have added or ran the appropriate tests for your PR: https://git.k8s.io/community/contributors/devel/sig-testing/testing.md
4. If you want *faster* PR reviews, read how: https://git.k8s.io/community/contributors/guide/pull-requests.md#best-practices-for-faster-reviews
5. If the PR is unfinished, see how to mark it: https://git.k8s.io/community/contributors/guide/pull-requests.md#marking-unfinished-pull-requests
-->

#### What type of PR is this?
/kind bug
<!--
Add one of the following kinds:
/kind bug
/kind cleanup
/kind documentation
/kind feature

Optionally add one or more of the following kinds if applicable:
/kind api-change
/kind deprecation
/kind failing-test
/kind flake
/kind regression
-->

#### What this PR does / why we need it:
The reason why #346 happened is that kwok doesn't initialize `nodeSelectorFunc` when `--manage-nodes-with-label-selector` is set, this PR will initialize `nodeSelectorFunc` to fix it.

#### Which issue(s) this PR fixes:
<!--
*Automatically closes linked issue when PR is merged.
Usage: `Fixes #<issue number>`, or `Fixes (paste link of issue)`.
_If PR is about `failing-tests or flakes`, please post the related issues/tests in a comment and do not use `Fixes`_*
-->
Fixes #346 

#### Special notes for your reviewer:

Kwok doesn't initializes `nodeSelectorFunc` when `--manage-nodes-with-label-selector` is set, so [node_controller.go#L170](https://github.com/kubernetes-sigs/kwok/blob/main/pkg/kwok/controllers/node_controller.go#L170) causes nil point panic.

#### Does this PR introduce a user-facing change?
<!--
If no, just write "NONE" in the release-note block below.
If yes, a release note is required:
Enter your extended release note in the block below. If the PR requires additional action from users switching to the new release, include the string "action required".

For more information on release notes see: https://git.k8s.io/community/contributors/guide/release-notes.md
-->
```release-note

```

#### Additional documentation e.g., KEPs (Kubernetes Enhancement Proposals), usage docs, etc.:

<!--
This section can be blank if this pull request does not require a release note.

When adding links which point to resources within git repositories, like
KEPs or supporting documentation, please reference a specific commit and avoid
linking directly to the master branch. This ensures that links reference a
specific point in time, rather than a document that may change over time.

See here for guidance on getting permanent links to files: https://help.github.com/en/articles/getting-permanent-links-to-files

Please use the following format for linking documentation:
- [KEP]: <link>
- [Usage]: <link>
- [Other doc]: <link>
-->
```docs

```


Patch:
diff --git a/pkg/kwok/controllers/controller.go b/pkg/kwok/controllers/controller.go
index 530ceb5c..0a2a0047 100644
--- a/pkg/kwok/controllers/controller.go
+++ b/pkg/kwok/controllers/controller.go
@@ -104,7 +104,10 @@ func NewController(conf Config) (*Controller, error) {
 			return selector.Matches(labels.Set(node.Annotations))
 		}
 	case conf.ManageNodesWithLabelSelector != "":
-		// client-go supports label filtering, so ignore this.
+		// client-go supports label filtering, so return true is ok.
+		nodeSelectorFunc = func(node *corev1.Node) bool {
+			return true
+		}
 	default:
 		return nil, fmt.Errorf("no nodes are managed")
 	}


Test patch:
diff --git a/pkg/kwok/controllers/controller_test.go b/pkg/kwok/controllers/controller_test.go
new file mode 100644
index 00000000..9400bdf9
--- /dev/null
+++ b/pkg/kwok/controllers/controller_test.go
@@ -0,0 +1,168 @@
+/*
+Copyright 2023 The Kubernetes Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package controllers
+
+import (
+	"context"
+	"fmt"
+	"os"
+	"testing"
+	"time"
+
+	corev1 "k8s.io/api/core/v1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/runtime"
+	"k8s.io/apimachinery/pkg/util/wait"
+	"k8s.io/client-go/kubernetes/fake"
+
+	"sigs.k8s.io/kwok/pkg/log"
+	"sigs.k8s.io/kwok/stages"
+)
+
+func TestController(t *testing.T) {
+	nodes := []runtime.Object{
+		&corev1.Node{
+			ObjectMeta: metav1.ObjectMeta{
+				Name: "node-0",
+				Labels: map[string]string{
+					"manage-by-kwok": "true",
+				},
+			},
+			Status: corev1.NodeStatus{
+				Phase: corev1.NodePending,
+			},
+		},
+		&corev1.Node{
+			ObjectMeta: metav1.ObjectMeta{
+				Name: "node-1",
+				Annotations: map[string]string{
+					"manage-by-kwok": "true",
+				},
+			},
+			Status: corev1.NodeStatus{
+				Phase: corev1.NodePending,
+			},
+		},
+		&corev1.Node{
+			ObjectMeta: metav1.ObjectMeta{
+				Name: "node-2",
+			},
+			Status: corev1.NodeStatus{
+				Phase: corev1.NodePending,
+			},
+		},
+	}
+
+	nodeStages, _ := NewStagesFromYaml([]byte(stages.DefaultNodeStages))
+	podStages, _ := NewStagesFromYaml([]byte(stages.DefaultPodStages))
+
+	tests := []struct {
+		name          string
+		conf          Config
+		wantNodePhase map[string]corev1.NodePhase
+		wantErr       bool
+	}{
+		{
+			name: "node controller test: manage all nodes",
+			conf: Config{
+				ClientSet:      fake.NewSimpleClientset(nodes...),
+				ManageAllNodes: true,
+				NodeStages:     nodeStages,
+				PodStages:      podStages,
+				CIDR:           "10.0.0.1/24",
+			},
+			wantNodePhase: map[string]corev1.NodePhase{
+				"node-0": corev1.NodeRunning,
+				"node-1": corev1.NodeRunning,
+				"node-2": corev1.NodeRunning,
+			},
+			wantErr: false,
+		},
+		{
+			name: "node controller test: manage nodes with label selector `manage-by-kwok=true`",
+			conf: Config{
+				ClientSet:                    fake.NewSimpleClientset(nodes...),
+				ManageNodesWithLabelSelector: "manage-by-kwok",
+				NodeStages:                   nodeStages,
+				PodStages:                    podStages,
+				CIDR:                         "10.0.0.1/24",
+			},
+			wantNodePhase: map[string]corev1.NodePhase{
+				"node-0": corev1.NodeRunning,
+				"node-1": corev1.NodePending,
+				"node-2": corev1.NodePending,
+			},
+			wantErr: false,
+		},
+		{
+			name: "node controller test: manage nodes with annotation selector `manage-by-kwok=true`",
+			conf: Config{
+				ClientSet:                         fake.NewSimpleClientset(nodes...),
+				ManageNodesWithAnnotationSelector: "manage-by-kwok=true",
+				NodeStages:                        nodeStages,
+				PodStages:                         podStages,
+				CIDR:                              "10.0.0.1/24",
+			},
+			wantNodePhase: map[string]corev1.NodePhase{
+				"node-0": corev1.NodePending,
+				"node-1": corev1.NodeRunning,
+				"node-2": corev1.NodePending,
+			},
+			wantErr: false,
+		},
+	}
+
+	ctx := context.Background()
+	ctx = log.NewContext(ctx, log.NewLogger(os.Stderr, log.DebugLevel))
+	ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
+	t.Cleanup(func() {
+		cancel()
+		time.Sleep(time.Second)
+	})
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			ctr, err := NewController(tt.conf)
+			if (err != nil) != tt.wantErr {
+				t.Fatalf("NewController() error = %v, wantErr %v", err, tt.wantErr)
+			}
+
+			if err := ctr.Start(ctx); err != nil {
+				t.Fatalf("failed to start nodes controller: %v", err)
+			}
+
+			// wait for nodes to be right phase indicated by `tt.wantNodePhase`
+			err = wait.PollUntilWithContext(ctx, time.Second, func(ctx context.Context) (done bool, err error) {
+				list, err := ctr.clientSet.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
+				if err != nil {
+					return false, fmt.Errorf("failed to list nodes, err: %w", err)
+				}
+
+				for _, node := range list.Items {
+					wantNodePhase := tt.wantNodePhase[node.Name]
+					if node.Status.Phase != wantNodePhase {
+						return false, fmt.Errorf("node %s phase is %s, want %s", node.Name, node.Status.Phase, wantNodePhase)
+					}
+				}
+				return true, nil
+			})
+			if err != nil {
+				t.Fatal(err)
+			}
+		})
+	}
+}