Browse Source

configured endpoint and finished handler

Feroze Mohideen 3 years ago
parent
commit
40bcb7a452

+ 16 - 78
api/server/handlers/stacks/open_stack_pr.go → api/server/handlers/stacks/create_secret_and_open_pr.go

@@ -1,12 +1,10 @@
 package stacks
 
 import (
-	"context"
 	"errors"
 	"fmt"
 	"net/http"
 	"strconv"
-	"strings"
 
 	"github.com/bradleyfalzon/ghinstallation/v2"
 	"github.com/google/go-github/v41/github"
@@ -17,10 +15,8 @@ import (
 	"github.com/porter-dev/porter/api/server/shared/config"
 	"github.com/porter-dev/porter/api/types"
 	"github.com/porter-dev/porter/internal/auth/token"
-	"github.com/porter-dev/porter/internal/encryption"
 	"github.com/porter-dev/porter/internal/integrations/ci/actions"
 	"github.com/porter-dev/porter/internal/models"
-	"github.com/porter-dev/porter/internal/models/integrations"
 )
 
 type OpenStackPRHandler struct {
@@ -38,46 +34,25 @@ func NewOpenStackPRHandler(
 }
 
 func (c *OpenStackPRHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
-	ga, _ := r.Context().Value(types.GitInstallationScope).(*integrations.GithubAppInstallation)
+	gaid := c.Config().GithubAppConf.AppID
 	user, _ := r.Context().Value(types.UserScope).(*models.User)
 	project, _ := r.Context().Value(types.ProjectScope).(*models.Project)
 	cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
 
 	owner, name, ok := commonutils.GetOwnerAndNameParams(c, w, r)
-
 	if !ok {
+		c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("unable to get github owner and name params")))
 		return
 	}
 
 	// create the environment
-	request := &types.CreateEnvironmentRequest{}
+	request := &types.CreateSecretAndOpenGitHubPullRequest{}
 
 	if ok := c.DecodeAndValidate(w, r, request); !ok {
 		return
 	}
 
-	// create a random webhook id
-	webhookUID, err := encryption.GenerateRandomBytes(32)
-	if err != nil {
-		c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error generating webhook UID for new stack: %w", err)))
-		return
-	}
-
-	env := &models.Environment{
-		ProjectID:           project.ID,
-		ClusterID:           cluster.ID,
-		GitInstallationID:   uint(ga.InstallationID),
-		Name:                request.Name,
-		GitRepoOwner:        owner,
-		GitRepoName:         name,
-		GitRepoBranches:     strings.Join(request.GitRepoBranches, ","),
-		Mode:                request.Mode,
-		WebhookID:           string(webhookUID),
-		NewCommentsDisabled: request.DisableNewComments,
-		GitDeployBranches:   strings.Join(request.GitDeployBranches, ","),
-	}
-
-	client, err := getGithubClient(c.Config(), ga.InstallationID)
+	client, err := getGithubClient(c.Config(), gaid)
 	if err != nil {
 		c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
 		return
@@ -86,64 +61,27 @@ func (c *OpenStackPRHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
 	// generate porter jwt token
 	jwt, err := token.GetTokenForAPI(user.ID, project.ID)
 	if err != nil {
-		_, deleteErr := client.Repositories.DeleteHook(context.Background(), owner, name, hook.GetID())
-
-		if deleteErr != nil {
-			c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("%v: %w", errGithubAPI, deleteErr),
-				http.StatusConflict, "error getting token for API while creating environment"))
-			return
-		}
-
-		_, deleteErr = c.Repo().Environment().DeleteEnvironment(env)
-
-		if deleteErr != nil {
-			c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error deleting created preview environment: %w",
-				deleteErr)))
-			return
-		}
-
 		c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error getting token for API: %w", err)))
 		return
 	}
-
 	encoded, err := jwt.EncodeToken(c.Config().TokenConf)
 	if err != nil {
-		_, deleteErr := client.Repositories.DeleteHook(context.Background(), owner, name, hook.GetID())
-
-		if deleteErr != nil {
-			c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(fmt.Errorf("%v: %w", errGithubAPI, deleteErr),
-				http.StatusConflict, "error encoding token while creating environment"))
-			return
-		}
-
-		_, deleteErr = c.Repo().Environment().DeleteEnvironment(env)
-
-		if deleteErr != nil {
-			c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error deleting created preview environment: %w",
-				deleteErr)))
-			return
-		}
-
 		c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error encoding API token: %w", err)))
 		return
 	}
 
-	err = actions.SetupEnv(&actions.EnvOpts{
-		Client:            client,
-		ServerURL:         c.Config().ServerConf.ServerURL,
-		PorterToken:       encoded,
-		GitRepoOwner:      owner,
-		GitRepoName:       name,
-		ProjectID:         project.ID,
-		ClusterID:         cluster.ID,
-		GitInstallationID: uint(ga.InstallationID),
-		EnvironmentName:   request.Name,
-		InstanceName:      c.Config().ServerConf.InstanceName,
-	})
-
-	err = actions.OpenGithubPR(&actions.OpenGithubPROpts{
-		Client: client,
-	})
+	if request.OpenPr {
+		err = actions.OpenGithubPR(&actions.GithubPROpts{
+			Client:       client,
+			GitRepoOwner: owner,
+			GitRepoName:  name,
+			StackName:    request.StackName,
+			ProjectID:    project.ID,
+			ClusterID:    cluster.ID,
+			PorterToken:  encoded,
+			ServerURL:    c.Config().ServerConf.ServerURL,
+		})
+	}
 
 	if err != nil {
 		unwrappedErr := errors.Unwrap(err)

+ 4 - 5
api/server/router/stack.go

@@ -141,7 +141,7 @@ func getStackRoutes(
 	})
 
 	// POST /api/projects/{project_id}/clusters/{cluster_id}/stacks/{stack}/pr -> stacks.NewOpenStackPRHandler
-	openPREndpoint := factory.NewAPIEndpoint(
+	createSecretAndOpenGitHubPullRequestEndpoint := factory.NewAPIEndpoint(
 		&types.APIRequestMetadata{
 			Verb:   types.APIVerbCreate,
 			Method: types.HTTPVerbPost,
@@ -153,20 +153,19 @@ func getStackRoutes(
 				types.UserScope,
 				types.ProjectScope,
 				types.ClusterScope,
-				types.GitInstallationScope,
 			},
 		},
 	)
 
-	openPRHandler := stacks.NewOpenStackPRHandler(
+	createSecretAndOpenGitHubPullRequestHandler := stacks.NewOpenStackPRHandler(
 		config,
 		factory.GetDecoderValidator(),
 		factory.GetResultWriter(),
 	)
 
 	routes = append(routes, &router.Route{
-		Endpoint: openPREndpoint,
-		Handler:  openPRHandler,
+		Endpoint: createSecretAndOpenGitHubPullRequestEndpoint,
+		Handler:  createSecretAndOpenGitHubPullRequestHandler,
 		Router:   r,
 	})
 

+ 5 - 0
api/types/stack.go

@@ -14,3 +14,8 @@ type Dependency struct {
 	Version    string `json:"version" form:"required"`
 	Repository string `json:"repository" form:"required"`
 }
+
+type CreateSecretAndOpenGitHubPullRequest struct {
+	OpenPr    bool `json:"open_pr"`
+	StackName string
+}

+ 40 - 6
internal/integrations/ci/actions/stack.go

@@ -15,9 +15,32 @@ type GithubPROpts struct {
 	ApplyWorkflowYAML         string
 	StackName                 string
 	ProjectID, ClusterID      uint
+	PorterToken               string
+	ServerURL                 string
+}
+
+type GetStackApplyActionYAMLOpts struct {
+	ServerURL            string
+	StackName            string
+	ProjectID, ClusterID uint
+	DefaultBranch        string
+	SecretName           string
 }
 
 func OpenGithubPR(opts *GithubPROpts) error {
+	// create porter secret
+	secretName := fmt.Sprintf("PORTER_STACK_%d_%d", opts.ProjectID, opts.ClusterID)
+	err := createGithubSecret(
+		opts.Client,
+		secretName,
+		opts.PorterToken,
+		opts.GitRepoOwner,
+		opts.GitRepoName,
+	)
+	if err != nil {
+		return err
+	}
+
 	// get the repository to find the default branch
 	repo, _, err := opts.Client.Repositories.Get(
 		context.TODO(),
@@ -30,12 +53,23 @@ func OpenGithubPR(opts *GithubPROpts) error {
 
 	defaultBranch := repo.GetDefaultBranch()
 
+	applyWorkflowYAML, err := getStackApplyActionYAML(&GetStackApplyActionYAMLOpts{
+		ServerURL:     opts.ServerURL,
+		ClusterID:     opts.ClusterID,
+		ProjectID:     opts.ProjectID,
+		StackName:     opts.StackName,
+		DefaultBranch: defaultBranch,
+		SecretName:    secretName,
+	})
+	if err != nil {
+		return err
+	}
+
 	err = createNewBranch(opts.Client,
 		opts.GitRepoOwner,
 		opts.GitRepoName,
 		defaultBranch,
 		"porter-stack")
-
 	if err != nil {
 		return fmt.Errorf(
 			"Unable to create PR to merge workflow files into protected branch: %s.\n"+
@@ -48,7 +82,7 @@ func OpenGithubPR(opts *GithubPROpts) error {
 
 	_, err = commitWorkflowFile(
 		opts.Client,
-		fmt.Sprintf("porter_%s_env.yml", strings.ToLower(opts.EnvironmentName)),
+		fmt.Sprintf("porter_stack_%s.yml", strings.ToLower(opts.StackName)),
 		applyWorkflowYAML, opts.GitRepoOwner,
 		opts.GitRepoName, "porter-preview", false,
 	)
@@ -63,7 +97,7 @@ func OpenGithubPR(opts *GithubPROpts) error {
 		)
 	}
 
-	pr, _, err := opts.Client.PullRequests.Create(
+	_, _, err = opts.Client.PullRequests.Create(
 		context.Background(), opts.GitRepoOwner, opts.GitRepoName, &github.NewPullRequest{
 			Title: github.String("Enable Porter Preview Environment deployments"),
 			Base:  github.String(defaultBranch),
@@ -76,13 +110,13 @@ func OpenGithubPR(opts *GithubPROpts) error {
 	return nil
 }
 
-func GetStackApplyActionYAML(opts *EnvOpts) ([]byte, error) {
+func getStackApplyActionYAML(opts *GetStackApplyActionYAMLOpts) ([]byte, error) {
 	gaSteps := []GithubActionYAMLStep{
 		getCheckoutCodeStep(),
 		getSetTagStep(),
 		getDeployStackStep(
 			opts.ServerURL,
-			getPreviewEnvSecretName(opts.ProjectID, opts.ClusterID, opts.InstanceName),
+			opts.SecretName,
 			opts.StackName,
 			"v0.1.0",
 			opts.ProjectID,
@@ -94,7 +128,7 @@ func GetStackApplyActionYAML(opts *EnvOpts) ([]byte, error) {
 		On: GithubActionYAMLOnPush{
 			Push: GithubActionYAMLOnPushBranches{
 				Branches: []string{
-					opts.Branch,
+					opts.DefaultBranch,
 				},
 			},
 		},