Skip to content

Commit

Permalink
feat: add uninstall command to the controller
Browse files Browse the repository at this point in the history
  • Loading branch information
Skarlso committed May 7, 2024
1 parent e05a5a0 commit 552d792
Show file tree
Hide file tree
Showing 15 changed files with 650 additions and 172 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//
// SPDX-License-Identifier: Apache-2.0

package install
package common

import (
"bufio"
Expand All @@ -20,7 +20,7 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
)

func readObjects(manifestPath string) ([]*unstructured.Unstructured, error) {
func ReadObjects(manifestPath string) ([]*unstructured.Unstructured, error) {
fi, err := os.Lstat(manifestPath)
if err != nil {
return nil, err
Expand Down
107 changes: 107 additions & 0 deletions cmds/ocm/commands/controllercmds/common/fetcher.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// SPDX-FileCopyrightText: 2022 SAP SE or an SAP affiliate company and Open Component Model contributors.
//
// SPDX-License-Identifier: Apache-2.0

package common

import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
)

func getLatestVersion(ctx context.Context, url string) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url+"/latest", nil)
if err != nil {
return "", err
}

res, err := http.DefaultClient.Do(req)
if err != nil {
return "", fmt.Errorf("GitHub API call failed: %w", err)
}

if res.Body != nil {
defer res.Body.Close()
}

type meta struct {
Tag string `json:"tag_name"`
}
var m meta
if err := json.NewDecoder(res.Body).Decode(&m); err != nil {
return "", fmt.Errorf("decoding GitHub API response failed: %w", err)
}

return m.Tag, err
}

// existingVersion calls the GitHub API to confirm the given version does exist.
func existingVersion(ctx context.Context, url, version string) (bool, error) {
if !strings.HasPrefix(version, "v") {
version = "v" + version
}

ghURL := fmt.Sprintf(url+"/tags/%s", version)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ghURL, nil)
if err != nil {
return false, fmt.Errorf("GitHub API call failed: %w", err)
}

res, err := http.DefaultClient.Do(req)
if err != nil {
return false, err
}

if res.Body != nil {
defer res.Body.Close()
}

switch res.StatusCode {
case http.StatusOK:
return true, nil
case http.StatusNotFound:
return false, nil
default:
return false, fmt.Errorf("GitHub API returned an unexpected status code (%d)", res.StatusCode)
}
}

func fetch(ctx context.Context, url, version, dir, filename string) error {
ghURL := fmt.Sprintf("%s/latest/download/%s", url, filename)
if strings.HasPrefix(version, "v") {
ghURL = fmt.Sprintf("%s/download/%s/%s", url, version, filename)
}

req, err := http.NewRequest(http.MethodGet, ghURL, nil)
if err != nil {
return fmt.Errorf("failed to create HTTP request for %s, error: %w", ghURL, err)
}

resp, err := http.DefaultClient.Do(req.WithContext(ctx))
if err != nil {
return fmt.Errorf("failed to download manifests.tar.gz from %s, error: %w", ghURL, err)
}
defer resp.Body.Close()

// check response
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to download %s from %s, status: %s", filename, ghURL, resp.Status)
}

wf, err := os.OpenFile(filepath.Join(dir, filename), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o777)
if err != nil {
return fmt.Errorf("failed to open temp file: %w", err)
}

if _, err := io.Copy(wf, resp.Body); err != nil {
return fmt.Errorf("failed to write to temp file: %w", err)
}

return nil
}
115 changes: 115 additions & 0 deletions cmds/ocm/commands/controllercmds/common/manifests.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// SPDX-FileCopyrightText: 2022 SAP SE or an SAP affiliate company and Open Component Model contributors.
//
// SPDX-License-Identifier: Apache-2.0

package common

import (
"context"
"fmt"
"os"
"path/filepath"

"github.com/fluxcd/pkg/ssa"
"github.com/open-component-model/ocm/pkg/contexts/clictx"
"github.com/open-component-model/ocm/pkg/out"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)

func Install(ctx context.Context, octx clictx.Context, sm *ssa.ResourceManager, releaseURL, baseURL, manifest, filename, version string, dryRun bool) error {
objects, err := fetchObjects(ctx, octx, releaseURL, baseURL, manifest, filename, version, dryRun)
if err != nil {
return fmt.Errorf("✗ failed to construct objects to apply: %w", err)
}

// dry run was set to true, no objects are returned
if len(objects) == 0 {
return nil
}

if _, err := sm.ApplyAllStaged(context.Background(), objects, ssa.DefaultApplyOptions()); err != nil {
return fmt.Errorf("✗ failed to apply manifests: %w", err)
}

out.Outf(octx, "► waiting for ocm deployment to be ready\n")
if err = sm.Wait(objects, ssa.DefaultWaitOptions()); err != nil {
return fmt.Errorf("✗ failed to wait for objects to be ready: %w", err)
}

return nil
}

func Uninstall(ctx context.Context, octx clictx.Context, sm *ssa.ResourceManager, releaseURL, baseURL, manifest, filename, version string, dryRun bool) error {
objects, err := fetchObjects(ctx, octx, releaseURL, baseURL, manifest, filename, version, dryRun)
if err != nil {
return fmt.Errorf("✗ failed to construct objects to apply: %w", err)
}

// dry run was set to true, no objects are returned
if len(objects) == 0 {
return nil
}

if _, err := sm.DeleteAll(context.Background(), objects, ssa.DefaultDeleteOptions()); err != nil {
return fmt.Errorf("✗ failed to delete manifests: %w", err)
}

out.Outf(octx, "► waiting for ocm deployment to be deleted\n")
if err = sm.WaitForTermination(objects, ssa.DefaultWaitOptions()); err != nil {
return fmt.Errorf("✗ failed to wait for objects to be deleted: %w", err)
}

return nil
}

func fetchObjects(ctx context.Context, octx clictx.Context, releaseURL, baseURL, manifest, filename, version string, dryRun bool) ([]*unstructured.Unstructured, error) {
if version == "latest" {
latest, err := getLatestVersion(ctx, releaseURL)
if err != nil {
return nil, fmt.Errorf("✗ failed to retrieve latest version for %s: %w", manifest, err)
}
out.Outf(octx, "► got latest version %q\n", latest)
version = latest
} else {
exists, err := existingVersion(ctx, releaseURL, version)
if err != nil {
return nil, fmt.Errorf("✗ failed to check if version exists: %w", err)
}
if !exists {
return nil, fmt.Errorf("✗ version %q does not exist", version)
}
}

temp, err := os.MkdirTemp("", manifest+"-download")
if err != nil {
return nil, fmt.Errorf("✗ failed to create temp folder: %w", err)
}
defer os.RemoveAll(temp)

if err := fetch(ctx, baseURL, version, temp, filename); err != nil {
return nil, fmt.Errorf("✗ failed to download install.yaml file: %w", err)
}

path := filepath.Join(temp, filename)
if _, err := os.Stat(path); os.IsNotExist(err) {
return nil, fmt.Errorf("✗ failed to find %s file at location: %w", filename, err)
}
out.Outf(octx, "✔ successfully fetched install file\n")
if dryRun {
content, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("✗ failed to read %s file at location: %w", filename, err)
}

out.Outf(octx, string(content))
return nil, nil
}
out.Outf(octx, "► applying to cluster...\n")

objects, err := ReadObjects(path)
if err != nil {
return nil, fmt.Errorf("✗ failed to construct objects to apply: %w", err)
}

return objects, nil
}
Loading

0 comments on commit 552d792

Please sign in to comment.