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

Implement watch mechanism for all resources #2

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
36 changes: 36 additions & 0 deletions cyclops-ctrl/internal/cluster/k8sclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -1077,3 +1077,39 @@ func isRole(group, version, kind string) bool {
func isNetworkPolicy(group, version, kind string) bool {
return group == "networking.k8s.io" && version == "v1" && kind == "NetworkPolicy"
}

func WatchResource(clientset *kubernetes.Clientset, group, version, kind, name, namespace string) (<-chan watch.Event, error) {
// Create a channel to publish events
eventChannel := make(chan watch.Event)

// Define a context
ctx, cancel := context.WithCancel(context.Background())

// Create a dynamic client for the specified resource
dynamicClient, err := dynamic.NewForConfig(clientset.RESTConfig())
if err != nil {
return nil, err
}

resource := schema.GroupVersionResource{Group: group, Version: version, Resource: kind}

// Start the watch
watch, err := dynamicClient.Resource(resource).Namespace(namespace).Watch(ctx, metav1.ListOptions{
FieldSelector: "metadata.name=" + name,
})
if err != nil {
cancel()
return nil, err
}

// Goroutine to handle watch events
go func() {
defer close(eventChannel)
defer cancel()
for event := range watch.ResultChan() {
eventChannel <- event
}
}()

return eventChannel, nil
}