Skip to content

Commit

Permalink
Merge pull request #71 from theBeginner86/thebeginner86/chore/4
Browse files Browse the repository at this point in the history
[chore] Fix request headers
  • Loading branch information
theBeginner86 authored Dec 21, 2024
2 parents 5151915 + fe1365f commit ab09e14
Show file tree
Hide file tree
Showing 6 changed files with 107 additions and 73 deletions.
1 change: 1 addition & 0 deletions .github/.goreleaser.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ builds:
- -X main.providerToken={{.Env.PROVIDER_TOKEN}}
- -X main.mesheryCloudAPIBaseURL=https://cloud.layer5.io
- -X main.mesheryAPIBaseURL=https://playground.meshery.io
- -X main.workflowAccessToken=${{ .Env.GH_ACCESS_TOKEN }}
goos:
- linux
- darwin
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/build-and-release-snapshot-plugin.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,6 @@ jobs:
version: 2 # Use latest GoReleaser action version
args: release --clean --skip validate -f .github/.goreleaser.yml # Corrected filename to root
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RELEASE_CHANNEL: "stable"
PROVIDER_TOKEN: ${{ secrets.PROVIDER_TOKEN }}
GH_ACCESS_TOKEN: ${{ secrets.GH_ACCESS_TOKEN }}
1 change: 1 addition & 0 deletions .github/workflows/golangci-lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ jobs:
env:
RELEASE_CHANNEL: "edge"
PROVIDER_TOKEN: ${{ secrets.PROVIDER_TOKEN }}
GH_ACCESS_TOKEN: ${{ secrets.GH_ACCESS_TOKEN }}
with:
version: 2
args: release --snapshot --skip publish --clean -f .github/.goreleaser.yml
65 changes: 65 additions & 0 deletions .github/workflows/kanvas.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
name: Kanvas Screenshot Service
on: # rebuild any PRs and main branch changes
pull_request_target:
types: [opened, synchronize, reopened]
workflow_dispatch:
inputs:
contentID:
description: ID of the design to render.
required: true
type: string
assetLocation:
required: true
type: string
description: Remote location where the generated asset (screenshot) for the design will be stored.
workflow_call:
inputs:
contentID:
description: ID of the design to render.
required: true
type: string
assetLocation:
required: true
type: string
description: Remote location where the generated asset (screenshot) for the design will be stored.
outputs:
resource_url:
description: "The URL of the generated resource."
value: ${{ jobs.KanvasScreenshot.outputs.resource_url }}
permissions:
actions: read
contents: write
security-events: write
statuses: write
pull-requests: write
id-token: write

jobs:
KanvasScreenshot:
runs-on: ubuntu-latest
outputs:
resource_url: ${{ steps.test_result.outputs.resource_url }}
steps:
- name: Set PR number # To comment the final status on the Pull-request opened in any repository
run: |
export pull_number=$(jq --raw-output .pull_request.number "$GITHUB_EVENT_PATH")
echo "PULL_NO=$pull_number" >> $GITHUB_ENV
- uses: actions/checkout@v3
- uses: actions/checkout@v3 #this step would go away
with:
path: action
repository: layer5labs/kanvas-snapshot
- run: |
echo ${{ inputs.contentID }}
echo ${{ inputs.assetLocation }}
shell: bash
- id: test_result
uses: layer5labs/Kanvas-Snapshot@v0.2.13
with:
githubToken: ${{ secrets.GITHUB_TOKEN }} # github's personal access token example: "ghp_...."
mesheryToken: ${{ secrets.MESHERY_TOKEN }} # Meshery Cloud Authentication token, signin to meshery-cloud to get one, example: ey.....
prNumber: ${{ env.PULL_NO }} # auto-filled from the above step
application_type: "Design" # your application type, could be any of three: "Kubernetes Manifest", "Docker Compose", "Helm Chart"
skipComment: true
designID: ${{ inputs.contentID }} # relative file-path from the root directory in the github-runner env, you might require to checkout the repository as described in step 2
assetLocation: ${{ inputs.assetLocation }}
108 changes: 37 additions & 71 deletions cmd/kanvas-snapshot/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"path/filepath"
"regexp"
"strings"
"time"

"github.com/layer5io/meshkit/logger"
"github.com/meshery/helm-kanvas-snapshot/internal/errors"
Expand All @@ -23,6 +22,7 @@ var (
ProviderToken string
MesheryAPIBaseURL string
MesheryCloudAPIBaseURL string
WorkflowAccessToken string
Log logger.Handler
)

Expand Down Expand Up @@ -69,13 +69,13 @@ var generateKanvasSnapshotCmd = &cobra.Command{
assetLocation := fmt.Sprintf("https://raw.githubusercontent.com/layer5labs/meshery-extensions-packages/master/action-assets/%s.png", designID)

// Generate Snapshot
err = GenerateSnapshot(designID, chartURI, email, assetLocation)
err = GenerateSnapshot(designID, assetLocation, WorkflowAccessToken)
if err != nil {
handleError(errors.ErrGeneratingSnapshot(err))
}

if email == "" {
loader(2*time.Minute + 40*time.Second) // Loader running for 2 minutes and 40 seconds
// loader(2*time.Minute + 40*time.Second) // Loader running for 2 minutes and 40 seconds
Log.Infof("\nSnapshot generated. Snapshot URL: %s\n", assetLocation)
} else {
Log.Info("You will be notified via email when your snapshot is ready.")
Expand All @@ -91,36 +91,36 @@ type MesheryDesignPayload struct {
Email string `json:"email"`
}

func loader(duration time.Duration) {
total := int(duration.Seconds()) // Total time in seconds
progress := 0
// func loader(duration time.Duration) {
// total := int(duration.Seconds()) // Total time in seconds
// progress := 0

for progress <= total {
printProgressBar(progress, total)
time.Sleep(1 * time.Second) // Sleep for 1 second to update progress
progress++
}
fmt.Println() // Print a new line at the end for better output formatting
}
// for progress <= total {
// printProgressBar(progress, total)
// time.Sleep(1 * time.Second) // Sleep for 1 second to update progress
// progress++
// }
// fmt.Println() // Print a new line at the end for better output formatting
// }

func printProgressBar(progress, total int) {
barWidth := 25
// func printProgressBar(progress, total int) {
// barWidth := 25

percentage := float64(progress) / float64(total)
barProgress := int(percentage * float64(barWidth))
// percentage := float64(progress) / float64(total)
// barProgress := int(percentage * float64(barWidth))

bar := "[" + fmt.Sprintf("%s%s", repeat("=", barProgress), repeat("-", barWidth-barProgress)) + "]"
fmt.Printf("\rProgress %s %.2f%% Complete", bar, percentage*100)
}
// bar := "[" + fmt.Sprintf("%s%s", repeat("=", barProgress), repeat("-", barWidth-barProgress)) + "]"
// fmt.Printf("\rProgress %s %.2f%% Complete", bar, percentage*100)
// }

// Helper function to repeat a character n times
func repeat(char string, times int) string {
result := ""
for i := 0; i < times; i++ {
result += char
}
return result
}
// func repeat(char string, times int) string {
// result := ""
// for i := 0; i < times; i++ {
// result += char
// }
// return result
// }

// ExtractNameFromURI extracts the name from the URI
func ExtractNameFromURI(uri string) string {
Expand Down Expand Up @@ -166,7 +166,7 @@ func CreateMesheryDesign(uri, name, email string) (string, error) {
}

// Set headers and log them
req.Header.Set("Cookie", ProviderToken)
req.Header.Set("Cookie", fmt.Sprintf("token=%s;meshery-provider=Meshery", ProviderToken))
req.Header.Set("Origin", MesheryAPIBaseURL)
req.Header.Set("Host", MesheryAPIBaseURL)
req.Header.Set("Content-Type", "text/plain;charset=UTF-8")
Expand Down Expand Up @@ -205,74 +205,40 @@ func CreateMesheryDesign(uri, name, email string) (string, error) {
return "", errors.ErrCreatingMesheryDesign(fmt.Errorf("failed to extract design ID from response"))
}

func GenerateSnapshot(designID, _, email, assetLocation string) error {
payload := map[string]interface{}{
"Payload": map[string]string{
"application_type": "Helm Chart",
"designID": designID,
"email": email,
"assetLocation": assetLocation,
},
}

// Marshal the payload into JSON
payloadBytes, err := json.Marshal(payload)
if err != nil {
return err
}

// Create the POST request
req, err := http.NewRequest(
"POST",
fmt.Sprintf("%s/api/integrations/trigger/workflow", MesheryCloudAPIBaseURL),
bytes.NewBuffer(payloadBytes),
)
func GenerateSnapshot(contentID, assetLocation string, ghAccessToken string) error {
payload := fmt.Sprintf(`{"ref":"master","inputs":{"contentID":"%s","assetLocation":"%s"}}`, contentID, assetLocation)
req, err := http.NewRequest("POST", "https://api.github.com/repos/meshery/helm-kanvas-snapshot/actions/workflows/kanvas.yml/dispatches", bytes.NewBuffer([]byte(payload)))
if err != nil {
return err
}

req.Header.Set("Cookie", ProviderToken)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Referer", fmt.Sprintf("%s/dashboard", MesheryCloudAPIBaseURL))
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("Authorization", "Bearer "+ghAccessToken)
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")

client := &http.Client{}

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

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
}

func isValidEmail(email string) bool {
return emailRegex.MatchString(email)
}

func Main(providerToken, mesheryCloudAPIBaseURL, mesheryAPIBaseURL string) {
func Main(providerToken, mesheryCloudAPIBaseURL, mesheryAPIBaseURL, workflowAccessToken string) {
ProviderToken = providerToken
MesheryCloudAPIBaseURL = mesheryCloudAPIBaseURL
MesheryAPIBaseURL = mesheryAPIBaseURL
WorkflowAccessToken = workflowAccessToken
generateKanvasSnapshotCmd.Flags().StringVarP(&chartURI, "file", "f", "", "URI to Helm chart (required)")
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")

if err := generateKanvasSnapshotCmd.Execute(); err != nil {
Log.Error(err)
Expand Down
3 changes: 2 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ var (
providerToken string
mesheryCloudAPIBaseURL string
mesheryAPIBaseURL string
workflowAccessToken string
)

func main() {
cmd.Main(providerToken, mesheryCloudAPIBaseURL, mesheryAPIBaseURL)
cmd.Main(providerToken, mesheryCloudAPIBaseURL, mesheryAPIBaseURL, workflowAccessToken)
}

0 comments on commit ab09e14

Please sign in to comment.