Skip to content

Commit

Permalink
update payload to generate snapshot
Browse files Browse the repository at this point in the history
  • Loading branch information
Aijeyomah committed Oct 4, 2024
1 parent 7bba04a commit 50fa5af
Show file tree
Hide file tree
Showing 5 changed files with 71 additions and 57 deletions.
4 changes: 0 additions & 4 deletions .github/workflows/build-and-release-snapshot-plugin.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,6 @@ jobs:
RELEASE_CHANNEL: "stable"
MESHERY_CLOUD_API_COOKIE: ${{ secrets.MESHERY_CLOUD_API_COOKIE }}
MESHERY_API_COOKIE: ${{ secrets.MESHERY_API_COOKIE }}
OWNER: ${{ secrets.OWNER }}
REPO: ${{ secrets.REPO }}
WORKFLOW: ${{ secrets.WORKFLOW }}
BRANCH: ${{ secrets.BRANCH }}
MESHERY_CLOUD_API_BASE_URL: ${{ secrets.MESHERY_CLOUD_API_BASE_URL }}
MESHERY_API_BASE_URL: ${{ secrets.MESHERY_API_BASE_URL }}
SYSTEM_ID: ${{ secrets.SYSTEM_ID }}
Expand Down
9 changes: 2 additions & 7 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ include build/Makefile.core.mk
.PHONY: all
all: dep-check build
## Lint check
# golangci: error dep-check
# golangci-lint run --exclude-use-default
golangci: error dep-check
golangci-lint run --exclude-use-default

## Analyze error codes
error: dep-check
Expand Down Expand Up @@ -58,13 +58,8 @@ BINNAME_WINDOWS ?= kanvas-snapshot-windows-$(ARCH).exe


LDFLAGS := "\
-X 'main.GithubToken=$(GITHUB_TOKEN)' \
-X 'main.MesheryCloudApiCookie=$(MESHERY_CLOUD_API_COOKIES)' \
-X 'main.MesheryApiCookie=$(MESHERY_API_COOKIES)' \
-X 'main.Owner=$(OWNER)' \
-X 'main.Repo=$(REPO)' \
-X 'main.Workflow=$(WORKFLOW)' \
-X 'main.Branch=$(BRANCH)' \
-X 'main.MesheryCloudApiBaseUrl=$(MESHERY_CLOUD_API_BASE_URL)' \
-X 'main.MesheryApiBaseUrl=$(MESHERY_API_BASE_URL)' \
-X 'main.SystemID=$(SYSTEM_ID)'"
Expand Down
9 changes: 2 additions & 7 deletions build/Makefile.core.mk
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
GOVERSION = 1.23
GITHUB_TOKEN=""
MESHERY_API_COOKIE=""
MESHERY_CLOUD_API_COOKIE=""
OWNER="Aijeyomah"
REPO="Ng-depl"
WORKFLOW="meshmap.yml"
BRANCH="new-mesh"
MESHERY_CLOUD_API_BASE_URL="http://localhost:9876"
MESHERY_API_BASE_URL="http://localhost:9081"
SYSTEM_ID="3ae41e77-5626-42d3-aa04-ee871ad3035c"
MESHERY_API_BASE_URL="http://localhost:3000"
SYSTEM_ID="ad8acecd-b742-4958-9af9-538c4183a177"
84 changes: 50 additions & 34 deletions cmd/kanvas-snapshot/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
Expand All @@ -18,19 +19,13 @@ import (
)

var (
GithubToken string
MesheryToken string
MesheryCloudApiCookie string
MesheryApiCookie string
Owner string
Repo string
Workflow string
Branch string
MesheryApiBaseUrl string
MesheryCloudApiBaseUrl string
SystemID string
Log logger.Handler
LogError logger.Handler
)

var (
Expand Down Expand Up @@ -133,10 +128,15 @@ func ExtractNameFromURI(uri string) string {
}

func handleError(err error) {
if err != nil {
LogError.Error(err)
os.Exit(1)
if err == nil {
return
}
if Log != nil {
Log.Error(err)
} else {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
}
os.Exit(1)
}

func CreateMesheryDesign(uri, name, email string) (string, error) {
Expand All @@ -149,58 +149,64 @@ func CreateMesheryDesign(uri, name, email string) (string, error) {

payloadBytes, err := json.Marshal(payload)
if err != nil {
LogError.Error(err)
os.Exit(1)
Log.Info("Failed to marshal payload:", err)
return "", errors.ErrDecodingAPI(err)
}

sourceType := "Helm Chart"
req, err := http.NewRequest("POST", fmt.Sprintf("%s/api/pattern/%s", MesheryApiBaseUrl, sourceType), bytes.NewBuffer(payloadBytes))
encodedChartType := url.PathEscape(sourceType)
fullURL := fmt.Sprintf("%s/api/pattern/%s", MesheryApiBaseUrl, encodedChartType)

// Create the request
req, err := http.NewRequest("POST", fullURL, bytes.NewBuffer(payloadBytes))
if err != nil {
LogError.Error(err)
os.Exit(1)
Log.Info("Failed to create new request:", err)
return "", errors.ErrHTTPPostRequest(err)
}

// Set headers and log them
req.Header.Set("Cookie", MesheryApiCookie)
req.Header.Set("Origin", MesheryApiBaseUrl)
req.Header.Set("Host", MesheryApiBaseUrl)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Content-Type", "text/plain;charset=UTF-8")
req.Header.Set("Accept-Encoding", "gzip, deflate, br, zstd")
req.Header.Set("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8")

client := &http.Client{}

resp, err := client.Do(req)
if err != nil {
return "", err
return "", errors.ErrHTTPPostRequest(err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
io.ReadAll(resp.Body)
return "", err
body, _ := io.ReadAll(resp.Body)
return "", errors.ErrUnexpectedResponseCode(resp.StatusCode, string(body))
}
// Expecting a JSON array in the response

// Decode response
var result []map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
return "", err
body, _ := io.ReadAll(resp.Body)
return "", errors.ErrDecodingAPI(fmt.Errorf("failed to decode json. body: %s, error: %w", body, err))
}

// Extracting the design ID from the result
if len(result) > 0 {
if id, ok := result[0]["id"].(string); ok {
Log.Infof("Successfully created Meshery design. ID: %s", id)
return id, nil
}
}

return "", errors.ErrHTTPPostRequest(err)
return "", errors.ErrCreatingMesheryDesign(fmt.Errorf("failed to extract design ID from response"))
}

func GenerateSnapshot(designID, chartURI, email, assetLocation string) error {

payload := map[string]interface{}{
"Owner": Owner,
"Repo": Repo,
"Workflow": Workflow,
"Branch": Branch,
"github_token": GithubToken,
"Payload": map[string]string{
"application_type": "Helm Chart",
"designID": designID,
Expand Down Expand Up @@ -231,14 +237,24 @@ func GenerateSnapshot(designID, chartURI, email, assetLocation string) error {
req.Header.Set("Referer", fmt.Sprintf("%s/dashboard", MesheryCloudApiBaseUrl))

client := &http.Client{}

resp, err := client.Do(req)
if err != nil {
return err
return errors.ErrHTTPPostRequest(err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
_, err := io.ReadAll(resp.Body)
return err

if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return errors.ErrUnexpectedResponseCode(resp.StatusCode, string(body))
}

// Decode response
var result []map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
body, _ := io.ReadAll(resp.Body)
return errors.ErrDecodingAPI(fmt.Errorf("failed to decode json. body: %s, error: %w", body, err))
}

return nil
Expand All @@ -247,14 +263,14 @@ func GenerateSnapshot(designID, chartURI, email, assetLocation string) error {
func main() {

generateKanvasSnapshotCmd.Flags().StringVarP(&chartURI, "file", "f", "", "URI to Helm chart (required)")
generateKanvasSnapshotCmd.Flags().StringVarP(&designName, "design-name", "l", "", "Optional name for the Meshery design")
generateKanvasSnapshotCmd.Flags().StringVarP(&designName, "design-name", "n", "", "Optional name for the Meshery design")
generateKanvasSnapshotCmd.Flags().StringVarP(&email, "email", "e", "", "Optional email to associate with the Meshery design")

generateKanvasSnapshotCmd.MarkFlagRequired("file")
generateKanvasSnapshotCmd.MarkFlagRequired("email")
_ = generateKanvasSnapshotCmd.MarkFlagRequired("file")
_ = generateKanvasSnapshotCmd.MarkFlagRequired("email")

if err := generateKanvasSnapshotCmd.Execute(); err != nil {
LogError.Error(err)
Log.Error(err)
os.Exit(1)
}

Expand Down
22 changes: 17 additions & 5 deletions internal/errors/error.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
package errors

import (
"fmt"

"github.com/layer5io/meshkit/errors"
)

var (
ErrInvalidChartURICode = "kanvas-snapshot-900"
ErrCreatingMesheryDesignCode = "kanvas-snapshot-901"
ErrGeneratingSnapshotCode = "kanvas-snapshot-902"
ErrHTTPPostRequestCode = "kanvas-snapshot-903"
ErrDecodingAPICode = "kanvas-snapshot-905"
ErrInvalidChartURICode = "kanvas-snapshot-900"
ErrCreatingMesheryDesignCode = "kanvas-snapshot-901"
ErrGeneratingSnapshotCode = "kanvas-snapshot-902"
ErrHTTPPostRequestCode = "kanvas-snapshot-903"
ErrDecodingAPICode = "kanvas-snapshot-905"
ErrUnexpectedResponseCodeCode = "kanvas-snapshot-906"
)

func ErrInvalidChartURI(err error) error {
Expand Down Expand Up @@ -56,3 +59,12 @@ func ErrDecodingAPI(err error) error {
[]string{"Ensure the Meshery API response format is correct."},
)
}

func ErrUnexpectedResponseCode(statusCode int, body string) error {
return errors.New(ErrUnexpectedResponseCodeCode, errors.Alert,
[]string{"Received unexpected response code from Meshery API."},
[]string{fmt.Sprintf("Status Code: %d, Body: %s", statusCode, body)},
[]string{"The API returned an unexpected status code."},
[]string{"Check the request details and ensure the Meshery API is functioning correctly."},
)
}

0 comments on commit 50fa5af

Please sign in to comment.