Skip to content

Commit

Permalink
Fix-migration-gs-ns (#724)
Browse files Browse the repository at this point in the history
## What
removed hard-coded namespace from git-source template

## Why
it shouldn't be there. the namespace will be supplied by the in-cluster
app that actually syncs those applications to the cluster.

## Notes
<!-- Add any additional notes here -->
  • Loading branch information
ATGardner authored Nov 29, 2023
1 parent c614f06 commit fcd73ea
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 27 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
VERSION=v0.1.53
VERSION=v0.1.54

OUT_DIR=dist
YEAR?=$(shell date +"%Y")
Expand Down
39 changes: 28 additions & 11 deletions cmd/commands/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,12 @@ import (

type (
MigrateOptions struct {
runtimeName string
cloneOpts *apgit.CloneOptions
helm helm.Helm
kubeContext string
kubeFactory apkube.Factory
runtimeName string
helmReleaseName string
cloneOpts *apgit.CloneOptions
helm helm.Helm
kubeContext string
kubeFactory apkube.Factory
}
)

Expand All @@ -61,7 +62,7 @@ func NewMigrateCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "migrate",
Short: "migrate a cli-runtime to the new helm-runtime",
Example: util.Doc("<BIN> helm migrate [RUNTIME_NAME]"),
Example: util.Doc("<BIN> helm migrate [RUNTIME_NAME] --helm-release-name [HELM_RELEASE_NAME]"),
Args: cobra.MaximumNArgs(1),
PreRunE: func(cmd *cobra.Command, args []string) error {
var err error
Expand Down Expand Up @@ -94,13 +95,15 @@ func NewMigrateCommand() *cobra.Command {
},
}

cmd.Flags().StringVarP(&opts.helmReleaseName, "helm-release-name", "r", "", "The expected helm release name, after the migration")
opts.cloneOpts = apu.AddRepoFlags(cmd, &apu.CloneFlagsOptions{
CreateIfNotExist: false,
CloneForWrite: true,
Optional: false,
})
opts.helm, _ = helm.AddFlags(cmd.Flags())
opts.kubeFactory = apkube.AddFlags(cmd.Flags())
util.Die(cobra.MarkFlagRequired(cmd.Flags(), "helm-release-name"))

return cmd
}
Expand Down Expand Up @@ -179,7 +182,7 @@ func runHelmMigrate(ctx context.Context, opts *MigrateOptions) error {
log.G(ctx).Infof("Pushed changes to shared-config-repo %q, sha: %s", *runtime.Repo, sha)
log.G(ctx).Infof("Done migrating resources from %q to %q", *runtime.Repo, *user.ActiveAccount.SharedConfigRepo)

err = removeFromCluster(ctx, *runtime.Metadata.Namespace, opts.kubeContext, srcCloneOpts, opts.kubeFactory)
err = removeFromCluster(ctx, opts.helmReleaseName, *runtime.Metadata.Namespace, opts.kubeContext, srcCloneOpts, opts.kubeFactory)
if err != nil {
return fmt.Errorf("failed removing runtime from cluster: %w", err)
}
Expand Down Expand Up @@ -506,7 +509,7 @@ func addSuffix(str, suffix string, length int) string {
return str[:length-len(suffix)] + suffix
}

func removeFromCluster(ctx context.Context, runtimeNamespace, kubeContext string, cloneOptions *apgit.CloneOptions, kubeFactory apkube.Factory) error {
func removeFromCluster(ctx context.Context, releaseName, runtimeNamespace, kubeContext string, cloneOptions *apgit.CloneOptions, kubeFactory apkube.Factory) error {
err := switchManagedByLabel(ctx, kubeFactory, runtimeNamespace)
if err != nil {
return fmt.Errorf("failed preserving codefresh token secret: %w", err)
Expand All @@ -525,7 +528,7 @@ func removeFromCluster(ctx context.Context, runtimeNamespace, kubeContext string
return fmt.Errorf("failed uninstalling runtime: %w", err)
}

err = patchCrds(ctx, kubeFactory)
err = patchCrds(ctx, kubeFactory, releaseName, runtimeNamespace)
if err != nil {
return fmt.Errorf("failed updating argoproj CRDs: %w", err)
}
Expand Down Expand Up @@ -563,7 +566,7 @@ func switchManagedByLabel(ctx context.Context, kubeFactory apkube.Factory, names
return nil
}

func patchCrds(ctx context.Context, kubeFactory apkube.Factory) error {
func patchCrds(ctx context.Context, kubeFactory apkube.Factory, releaseName, releaseNamespace string) error {
gvr := schema.GroupVersionResource(apiextv1.SchemeGroupVersion.WithResource("customresourcedefinitions"))
crdInterface := kube.GetDynamicClientOrDie(kubeFactory).Resource(gvr)
crds, err := crdInterface.List(ctx, metav1.ListOptions{})
Expand All @@ -580,7 +583,7 @@ func patchCrds(ctx context.Context, kubeFactory apkube.Factory) error {
ctx,
crd.GetName(),
types.StrategicMergePatchType,
[]byte(getLabelPatch("Helm")),
[]byte(getCrdPatch(releaseName, releaseNamespace)),
metav1.PatchOptions{},
)
if err != nil {
Expand All @@ -601,6 +604,20 @@ func getLabelPatch(value string) string {
return fmt.Sprintf(`{ "metadata": { "labels": { "%s": "%s" } } }`, apstore.Default.LabelKeyAppManagedBy, value)
}

func getCrdPatch(releaseName, releaseNamespace string) string {
return fmt.Sprintf(`{
"metadata": {
"annotations": {
"%s": "%s",
"%s": "%s"
},
"labels": {
"%s": "Helm"
}
}
}`, store.Get().AnnotationKeyReleaseName, releaseName, store.Get().AnnotationKeyReleaseNamespace, releaseNamespace, apstore.Default.LabelKeyAppManagedBy)
}

func filterStatus(manifest []byte) []byte {
lines := strings.Split(string(manifest), "\n")
var res []string
Expand Down
23 changes: 12 additions & 11 deletions docs/commands/cli-v2_migrate.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,23 @@ cli-v2 migrate [flags]
### Examples

```
cli-v2 helm migrate [RUNTIME_NAME]
cli-v2 helm migrate [RUNTIME_NAME] --helm-release-name [HELM_RELEASE_NAME]
```

### Options

```
--context string The name of the kubeconfig context to use
--devel use development versions, too. Equivalent to version '>0.0.0-0'. If --version is set, this is ignored
--git-server-crt string Git Server certificate file
-t, --git-token string Your git provider api token [GIT_TOKEN]
-u, --git-user string Your git provider user name [GIT_USER] (not required in GitHub)
-h, --help help for migrate
--kubeconfig string Path to the kubeconfig file to use for CLI requests.
-n, --namespace string If present, the namespace scope for this CLI request
--request-timeout string The length of time to wait before giving up on a single server request. Non-zero values should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests. (default "0")
--version string specify a version constraint for the chart version to use. This constraint can be a specific tag (e.g. 1.1.1) or it may reference a valid range (e.g. ^2.0.0). If this is not specified, the latest version is used
--context string The name of the kubeconfig context to use
--devel use development versions, too. Equivalent to version '>0.0.0-0'. If --version is set, this is ignored
--git-server-crt string Git Server certificate file
-t, --git-token string Your git provider api token [GIT_TOKEN]
-u, --git-user string Your git provider user name [GIT_USER] (not required in GitHub)
-r, --helm-release-name string The expected helm release name, after the migration
-h, --help help for migrate
--kubeconfig string Path to the kubeconfig file to use for CLI requests.
-n, --namespace string If present, the namespace scope for this CLI request
--request-timeout string The length of time to wait before giving up on a single server request. Non-zero values should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests. (default "0")
--version string specify a version constraint for the chart version to use. This constraint can be a specific tag (e.g. 1.1.1) or it may reference a valid range (e.g. ^2.0.0). If this is not specified, the latest version is used
```

### Options inherited from parent commands
Expand Down
10 changes: 7 additions & 3 deletions pkg/store/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ type Version struct {
type Store struct {
AddClusterJobName string
AnalysisRunResourceName string
AnnotationKeyReleaseName string
AnnotationKeyReleaseNamespace string
AnnotationKeySyncWave string
AppProxyIngressName string
AppProxyIngressPath string
Expand Down Expand Up @@ -112,8 +114,8 @@ type Store struct {
GitTokensLink string
GsCreateFlow string
InClusterName string
InClusterServerURL string
InClusterPath string
InClusterServerURL string
IngressHost string
InsecureIngressHost bool
InternalRouterIngressFilePath string
Expand All @@ -125,10 +127,10 @@ type Store struct {
IsDownloadRuntimeLogs bool
KubeVersionConstrint *semver.Constraints
LabelFieldCFType string
LabelKeyCFInternal string
LabelKeyCFType string
LabelGitIntegrationTypeKey string
LabelGitIntegrationTypeValue string
LabelKeyCFInternal string
LabelKeyCFType string
LabelSelectorGitIntegrationSecret string
LabelSelectorSealedSecret string
LastRuntimeVersionInCLI *semver.Version
Expand Down Expand Up @@ -179,6 +181,8 @@ func (s *Store) IsCustomDefURL(orgRepo string) bool {
func init() {
s.AddClusterJobName = "csdp-add-cluster-job-"
s.AnalysisRunResourceName = "analysisruns"
s.AnnotationKeyReleaseName = "meta.helm.sh/release-name"
s.AnnotationKeyReleaseNamespace = "meta.helm.sh/release-namespace"
s.AnnotationKeySyncWave = "argocd.argoproj.io/sync-wave"
s.AppProxyIngressName = "-cap-app-proxy"
s.AppProxyIngressPath = "/app-proxy"
Expand Down
1 change: 0 additions & 1 deletion pkg/templates/git-source.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ metadata:
codefresh.io/entity: '{{ index .Labels "codefresh_io_entity" }}'
codefresh.io/internal: '{{ index .Labels "codefresh_io_internal" }}'
name: '{{ .RuntimeName }}-{{ .UserGivenName }}'
namespace: runtime
spec:
destination:
namespace: '{{ .DestNamespace }}'
Expand Down

0 comments on commit fcd73ea

Please sign in to comment.