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

chore: refactor context handling in cmd/ #9860

Merged
merged 1 commit into from
Jul 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ func NewCommand() *cobra.Command {
Long: "ArgoCD application controller is a Kubernetes controller that continuously monitors running applications and compares the current, live state against the desired target state (as specified in the repo). This command runs Application Controller in the foreground. It can be configured by following options.",
DisableAutoGenTag: true,
RunE: func(c *cobra.Command, args []string) error {
ctx, cancel := context.WithCancel(c.Context())
defer cancel()

vers := common.GetVersion()
namespace, _, err := clientConfig.Namespace()
errors.CheckError(err)
Expand Down Expand Up @@ -119,9 +122,6 @@ func NewCommand() *cobra.Command {

repoClientset := apiclient.NewRepoServerClientset(repoServerAddress, repoServerTimeoutSeconds, tlsConfig)

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

cache, err := cacheSrc()
errors.CheckError(err)
cache.Cache.SetClient(cacheutil.NewTwoLevelClient(cache.Cache.GetClient(), 10*time.Minute))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package command

import (
"context"
"fmt"
"net/http"
"os"
Expand Down Expand Up @@ -60,6 +59,8 @@ func NewCommand() *cobra.Command {
Use: "controller",
Short: "Starts Argo CD ApplicationSet controller",
RunE: func(c *cobra.Command, args []string) error {
ctx := c.Context()

vers := common.GetVersion()
namespace, _, err := clientConfig.Namespace()
errors.CheckError(err)
Expand Down Expand Up @@ -123,7 +124,7 @@ func NewCommand() *cobra.Command {
if err != nil {
return err
}
argoSettingsMgr := argosettings.NewSettingsManager(context.Background(), k8sClient, namespace)
argoSettingsMgr := argosettings.NewSettingsManager(ctx, k8sClient, namespace)
appSetConfig := appclientset.NewForConfigOrDie(mgr.GetConfig())
argoCDDB := db.NewDB(namespace, argoSettingsMgr, k8sClient)
// start a webhook server that listens to incoming webhook payloads
Expand All @@ -139,10 +140,10 @@ func NewCommand() *cobra.Command {
go func() { errors.CheckError(askPassServer.Run(askpass.SocketPath)) }()
terminalGenerators := map[string]generators.Generator{
"List": generators.NewListGenerator(),
"Clusters": generators.NewClusterGenerator(mgr.GetClient(), context.Background(), k8sClient, namespace),
"Clusters": generators.NewClusterGenerator(mgr.GetClient(), ctx, k8sClient, namespace),
"Git": generators.NewGitGenerator(services.NewArgoCDService(argoCDDB, askPassServer, argocdRepoServer)),
"SCMProvider": generators.NewSCMProviderGenerator(mgr.GetClient()),
"ClusterDecisionResource": generators.NewDuckTypeGenerator(context.Background(), dynamicClient, k8sClient, namespace),
"ClusterDecisionResource": generators.NewDuckTypeGenerator(ctx, dynamicClient, k8sClient, namespace),
"PullRequest": generators.NewPullRequestGenerator(mgr.GetClient()),
}

Expand Down
5 changes: 3 additions & 2 deletions cmd/argocd-cmp-server/commands/argocd_cmp_server.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package commands

import (
"context"
"time"

"github.com/argoproj/pkg/stats"
Expand Down Expand Up @@ -34,6 +33,8 @@ func NewCommand() *cobra.Command {
Long: "ArgoCD ConfigManagementPlugin Server is an internal service which runs as sidecar container in reposerver deployment. It can be configured by following options.",
DisableAutoGenTag: true,
RunE: func(c *cobra.Command, args []string) error {
ctx := c.Context()

vers := common.GetVersion()
vers.LogStartupInfo("ArgoCD ConfigManagementPlugin Server", nil)

Expand All @@ -46,7 +47,7 @@ func NewCommand() *cobra.Command {
if otlpAddress != "" {
var closer func()
var err error
closer, err = traceutil.InitTracer(context.Background(), "argocd-cmp-server", otlpAddress)
closer, err = traceutil.InitTracer(ctx, "argocd-cmp-server", otlpAddress)
if err != nil {
log.Fatalf("failed to initialize tracing: %v", err)
}
Expand Down
9 changes: 6 additions & 3 deletions cmd/argocd-dex/commands/argocd_dex.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package commands

import (
"context"
"fmt"
"io/ioutil"
"os"
Expand Down Expand Up @@ -51,6 +50,8 @@ func NewRunDexCommand() *cobra.Command {
Use: "rundex",
Short: "Runs dex generating a config using settings from the Argo CD configmap and secret",
RunE: func(c *cobra.Command, args []string) error {
ctx := c.Context()

vers := common.GetVersion()
namespace, _, err := clientConfig.Namespace()
errors.CheckError(err)
Expand All @@ -70,7 +71,7 @@ func NewRunDexCommand() *cobra.Command {
config.UserAgent = fmt.Sprintf("argocd-dex/%s (%s)", vers.Version, vers.Platform)
kubeClientset := kubernetes.NewForConfigOrDie(config)

settingsMgr := settings.NewSettingsManager(context.Background(), kubeClientset, namespace)
settingsMgr := settings.NewSettingsManager(ctx, kubeClientset, namespace)
prevSettings, err := settingsMgr.GetSettings()
errors.CheckError(err)
updateCh := make(chan *settings.ArgoCDSettings, 1)
Expand Down Expand Up @@ -131,14 +132,16 @@ func NewGenDexConfigCommand() *cobra.Command {
Use: "gendexcfg",
Short: "Generates a dex config from Argo CD settings",
RunE: func(c *cobra.Command, args []string) error {
ctx := c.Context()

cli.SetLogFormat(cmdutil.LogFormat)
cli.SetLogLevel(cmdutil.LogLevel)
config, err := clientConfig.ClientConfig()
errors.CheckError(err)
namespace, _, err := clientConfig.Namespace()
errors.CheckError(err)
kubeClientset := kubernetes.NewForConfigOrDie(config)
settingsMgr := settings.NewSettingsManager(context.Background(), kubeClientset, namespace)
settingsMgr := settings.NewSettingsManager(ctx, kubeClientset, namespace)
settings, err := settingsMgr.GetSettings()
errors.CheckError(err)
dexCfgBytes, err := dex.GenerateDexConfigYAML(settings)
Expand Down
7 changes: 4 additions & 3 deletions cmd/argocd-git-ask-pass/commands/argocd_git_ask_pass.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package commands

import (
"context"
"fmt"
"os"
"strings"
Expand Down Expand Up @@ -29,19 +28,21 @@ func NewCommand() *cobra.Command {
Short: "Argo CD git credential helper",
DisableAutoGenTag: true,
Run: func(c *cobra.Command, args []string) {
ctx := c.Context()

if len(os.Args) != 2 {
errors.CheckError(fmt.Errorf("expected 1 argument, got %d", len(os.Args)-1))
}
nonce := os.Getenv(git.ASKPASS_NONCE_ENV)
if nonce == "" {
errors.CheckError(fmt.Errorf("%s is not set", git.ASKPASS_NONCE_ENV))
}
conn, err := grpc_util.BlockingDial(context.Background(), "unix", askpass.SocketPath, nil, grpc.WithTransportCredentials(insecure.NewCredentials()))
conn, err := grpc_util.BlockingDial(ctx, "unix", askpass.SocketPath, nil, grpc.WithTransportCredentials(insecure.NewCredentials()))
errors.CheckError(err)
defer io.Close(conn)
client := askpass.NewAskPassServiceClient(conn)

creds, err := client.GetCredentials(context.Background(), &askpass.CredentialsRequest{Nonce: nonce})
creds, err := client.GetCredentials(ctx, &askpass.CredentialsRequest{Nonce: nonce})
errors.CheckError(err)
switch {
case strings.HasPrefix(os.Args[1], "Username"):
Expand Down
8 changes: 5 additions & 3 deletions cmd/argocd-k8s-auth/commands/aws.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ func newAWSCommand() *cobra.Command {
var command = &cobra.Command{
Use: "aws",
Run: func(c *cobra.Command, args []string) {
presignedURLString, err := getSignedRequestWithRetry(time.Minute, 5*time.Second, clusterName, roleARN, getSignedRequest)
ctx := c.Context()

presignedURLString, err := getSignedRequestWithRetry(ctx, time.Minute, 5*time.Second, clusterName, roleARN, getSignedRequest)
errors.CheckError(err)
token := v1Prefix + base64.RawURLEncoding.EncodeToString([]byte(presignedURLString))
// Set token expiration to 1 minute before the presigned URL expires for some cushion
Expand All @@ -56,8 +58,8 @@ func newAWSCommand() *cobra.Command {

type getSignedRequestFunc func(clusterName, roleARN string) (string, error)

func getSignedRequestWithRetry(timeout, interval time.Duration, clusterName, roleARN string, fn getSignedRequestFunc) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
func getSignedRequestWithRetry(ctx context.Context, timeout, interval time.Duration, clusterName, roleARN string, fn getSignedRequestFunc) (string, error) {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
for {
signed, err := fn(clusterName, roleARN)
Expand Down
9 changes: 6 additions & 3 deletions cmd/argocd-k8s-auth/commands/aws_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package commands

import (
"context"
"fmt"
"testing"
"time"
Expand All @@ -9,6 +10,8 @@ import (
)

func TestGetSignedRequestWithRetry(t *testing.T) {
ctx := context.Background()

t.Run("will return signed request on first attempt", func(t *testing.T) {
// given
t.Parallel()
Expand All @@ -19,7 +22,7 @@ func TestGetSignedRequestWithRetry(t *testing.T) {
}

// when
signed, err := getSignedRequestWithRetry(time.Second, time.Millisecond, "cluster-name", "", mock.getSignedRequestMock)
signed, err := getSignedRequestWithRetry(ctx, time.Second, time.Millisecond, "cluster-name", "", mock.getSignedRequestMock)

// then
assert.NoError(t, err)
Expand All @@ -38,7 +41,7 @@ func TestGetSignedRequestWithRetry(t *testing.T) {
}

// when
signed, err := getSignedRequestWithRetry(time.Second, time.Millisecond, "cluster-name", "", mock.getSignedRequestMock)
signed, err := getSignedRequestWithRetry(ctx, time.Second, time.Millisecond, "cluster-name", "", mock.getSignedRequestMock)

// then
assert.NoError(t, err)
Expand All @@ -54,7 +57,7 @@ func TestGetSignedRequestWithRetry(t *testing.T) {
}

// when
signed, err := getSignedRequestWithRetry(time.Second, time.Millisecond, "cluster-name", "", mock.getSignedRequestMock)
signed, err := getSignedRequestWithRetry(ctx, time.Second, time.Millisecond, "cluster-name", "", mock.getSignedRequestMock)

// then
assert.Error(t, err)
Expand Down
5 changes: 3 additions & 2 deletions cmd/argocd-k8s-auth/commands/gcp.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package commands

import (
"context"
"fmt"
"os"

Expand All @@ -27,9 +26,11 @@ func newGCPCommand() *cobra.Command {
var command = &cobra.Command{
Use: "gcp",
Run: func(c *cobra.Command, args []string) {
ctx := c.Context()

// Preferred way to retrieve GCP credentials
// https://github.com/golang/oauth2/blob/9780585627b5122c8cc9c6a378ac9861507e7551/google/doc.go#L54-L68
cred, err := google.FindDefaultCredentials(context.Background(), defaultGCPScopes...)
cred, err := google.FindDefaultCredentials(ctx, defaultGCPScopes...)
errors.CheckError(err)
token, err := cred.TokenSource.Token()
errors.CheckError(err)
Expand Down
9 changes: 5 additions & 4 deletions cmd/argocd-notification/commands/controller.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package commands

import (
"context"
"fmt"
"net/http"
"os"
Expand Down Expand Up @@ -58,6 +57,8 @@ func NewCommand() *cobra.Command {
Use: "controller",
Short: "Starts Argo CD Notifications controller",
RunE: func(c *cobra.Command, args []string) error {
ctx := c.Context()

vers := common.GetVersion()
namespace, _, err := clientConfig.Namespace()
errors.CheckError(err)
Expand Down Expand Up @@ -120,13 +121,13 @@ func NewCommand() *cobra.Command {
log.Infof("loading configuration %d", metricsPort)

ctrl := notificationscontroller.NewController(k8sClient, dynamicClient, argocdService, namespace, appLabelSelector, registry, secretName, configMapName)
err = ctrl.Init(context.Background())
err = ctrl.Init(ctx)
if err != nil {
return err
}

go ctrl.Run(context.Background(), processorsCount)
<-context.Background().Done()
go ctrl.Run(ctx, processorsCount)
<-ctx.Done()
return nil
},
}
Expand Down
5 changes: 3 additions & 2 deletions cmd/argocd-repo-server/commands/argocd_repo_server.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package commands

import (
"context"
"fmt"
"math"
"net"
Expand Down Expand Up @@ -89,6 +88,8 @@ func NewCommand() *cobra.Command {
Long: "ArgoCD Repository Server is an internal service which maintains a local cache of the Git repository holding the application manifests, and is responsible for generating and returning the Kubernetes manifests. This command runs Repository Server in the foreground. It can be configured by following options.",
DisableAutoGenTag: true,
RunE: func(c *cobra.Command, args []string) error {
ctx := c.Context()

vers := common.GetVersion()
vers.LogStartupInfo(
"ArgoCD Repository Server",
Expand Down Expand Up @@ -129,7 +130,7 @@ func NewCommand() *cobra.Command {
if otlpAddress != "" {
var closer func()
var err error
closer, err = traceutil.InitTracer(context.Background(), "argocd-repo-server", otlpAddress)
closer, err = traceutil.InitTracer(ctx, "argocd-repo-server", otlpAddress)
if err != nil {
log.Fatalf("failed to initialize tracing: %v", err)
}
Expand Down
7 changes: 4 additions & 3 deletions cmd/argocd-server/commands/argocd_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ func NewCommand() *cobra.Command {
Long: "The API server is a gRPC/REST server which exposes the API consumed by the Web UI, CLI, and CI/CD systems. This command runs API server in the foreground. It can be configured by following options.",
DisableAutoGenTag: true,
Run: func(c *cobra.Command, args []string) {
ctx := c.Context()

vers := common.GetVersion()
namespace, _, err := clientConfig.Namespace()
errors.CheckError(err)
Expand Down Expand Up @@ -159,13 +161,12 @@ func NewCommand() *cobra.Command {
stats.RegisterStackDumper()
stats.StartStatsTicker(10 * time.Minute)
stats.RegisterHeapDumper("memprofile")
argocd := server.NewServer(context.Background(), argoCDOpts)
argocd.Init(context.Background())
argocd := server.NewServer(ctx, argoCDOpts)
argocd.Init(ctx)
lns, err := argocd.Listen()
errors.CheckError(err)
for {
var closer func()
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
if otlpAddress != "" {
closer, err = traceutil.InitTracer(ctx, "argocd-server", otlpAddress)
Expand Down