Skip to content

Commit

Permalink
add context object with cancel
Browse files Browse the repository at this point in the history
  • Loading branch information
bdrennz committed Sep 6, 2024
1 parent e7fd50a commit 02a5d76
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 8 deletions.
10 changes: 7 additions & 3 deletions cmd/cloudzero-agent-validator/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"context"
"fmt"
"os"
"os/signal"
Expand All @@ -17,7 +18,7 @@ import (
)

func main() {
ctrlCHandler()
ctx := ctrlCHandler()

app := &cli.App{
Name: build.AppName,
Expand All @@ -36,7 +37,7 @@ func main() {
}

app.Commands = append(app.Commands,
configcmd.NewCommand(),
configcmd.NewCommand(ctx),
diagcmd.NewCommand(),
)

Expand All @@ -46,11 +47,14 @@ func main() {
}
}

func ctrlCHandler() {
func ctrlCHandler() context.Context {
ctx, cancel := context.WithCancel(context.Background())
stopCh := make(chan os.Signal, 1)
signal.Notify(stopCh, os.Interrupt)
go func() {
<-stopCh
cancel()
os.Exit(0)
}()
return ctx
}
5 changes: 3 additions & 2 deletions pkg/cmd/config/command.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package config

import (
"context"
_ "embed"
"html/template"
"os"
Expand All @@ -23,7 +24,7 @@ var (
configAlias = []string{"f"}
)

func NewCommand() *cli.Command {
func NewCommand(ctx context.Context) *cli.Command {
cmd := &cli.Command{
Name: "config",
Usage: "configuration utility commands",
Expand Down Expand Up @@ -94,7 +95,7 @@ func NewCommand() *cli.Command {
return errors.Wrap(err, "creating clientset")
}

return k8s.ListServices(clientset)
return k8s.ListServices(ctx, clientset)
},
},
},
Expand Down
4 changes: 2 additions & 2 deletions pkg/k8s/services.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import (
)

// ListServices lists all Kubernetes services in all namespaces
func ListServices(clientset kubernetes.Interface) error {
func ListServices(ctx context.Context, clientset kubernetes.Interface) error {
// List all services in all namespaces
services, err := clientset.CoreV1().Services("").List(context.TODO(), metav1.ListOptions{})
services, err := clientset.CoreV1().Services("").List(ctx, metav1.ListOptions{})
if err != nil {
return errors.Wrap(err, "listing services")
}
Expand Down
5 changes: 4 additions & 1 deletion pkg/k8s/services_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package k8s_test

import (
"context"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -29,7 +30,9 @@ func TestListServices(t *testing.T) {
},
)

ctx, _ := context.WithCancel(context.Background())

// Test listing services
err := k8s.ListServices(clientset)
err := k8s.ListServices(ctx, clientset)
assert.NoError(t, err)
}

0 comments on commit 02a5d76

Please sign in to comment.