Преглед изворни кода

Merge pull request #1041 from porter-dev/master

Better user id check -> staging
abelanger5 пре 4 година
родитељ
комит
7e083c339f

+ 35 - 0
.github/workflows/release.yaml

@@ -347,3 +347,38 @@ jobs:
           asset_path: ./release/static/static_${{steps.tag_name.outputs.tag}}.zip
           asset_path: ./release/static/static_${{steps.tag_name.outputs.tag}}.zip
           asset_name: static_${{steps.tag_name.outputs.tag}}.zip
           asset_name: static_${{steps.tag_name.outputs.tag}}.zip
           asset_content_type: application/zip
           asset_content_type: application/zip
+  build-push-docker-cli:
+    name: Build a new porter-cli docker image
+    runs-on: ubuntu-latest
+    needs: release
+    steps:
+      - name: Get tag name
+        id: tag_name
+        run: |
+          tag=${GITHUB_TAG/refs\/tags\//}
+          echo ::set-output name=tag::$tag
+        env:
+          GITHUB_TAG: ${{ github.ref }}
+      - name: Checkout
+        uses: actions/checkout@v2.3.4
+      - name: Configure AWS credentials
+        uses: aws-actions/configure-aws-credentials@v1
+        with:
+          aws-access-key-id: ${{ secrets.ECR_AWS_ACCESS_KEY_ID }}
+          aws-secret-access-key: ${{ secrets.ECR_AWS_SECRET_ACCESS_KEY }}
+          aws-region: us-east-2
+      - name: Login to ECR public
+        id: login-ecr
+        run: |
+          aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/o1j4x7p4
+      - name: Build
+        run: |
+          docker build ./services/porter_cli_container \
+            -t public.ecr.aws/o1j4x7p4/porter-cli:${{steps.tag_name.outputs.tag}} \
+            -t public.ecr.aws/o1j4x7p4/porter-cli:latest \
+            -f ./services/porter_cli_container/Dockerfile \
+            --build-arg VERSION=${{steps.tag_name.outputs.tag}}
+      - name: Push
+        run: |
+          docker push public.ecr.aws/o1j4x7p4/porter-cli:${{steps.tag_name.outputs.tag}}
+          docker push public.ecr.aws/o1j4x7p4/porter-cli:latest

+ 1 - 1
cli/cmd/api/git_repo.go

@@ -10,7 +10,7 @@ import (
 )
 )
 
 
 // ListGitRepoResponse is the list of Git repo integrations for a project
 // ListGitRepoResponse is the list of Git repo integrations for a project
-type ListGitRepoResponse []models.GitRepoExternal
+type ListGitRepoResponse []uint
 
 
 // ListGitRepos returns a list of Git repos for a project
 // ListGitRepos returns a list of Git repos for a project
 func (c *Client) ListGitRepos(
 func (c *Client) ListGitRepos(

+ 0 - 20
cli/cmd/connect.go

@@ -67,18 +67,6 @@ var connectRegistryCmd = &cobra.Command{
 	},
 	},
 }
 }
 
 
-var connectActionsCmd = &cobra.Command{
-	Use:   "actions",
-	Short: "Adds Github Actions to a project",
-	Run: func(cmd *cobra.Command, args []string) {
-		err := checkLoginAndRun(args, runConnectActions)
-
-		if err != nil {
-			os.Exit(1)
-		}
-	},
-}
-
 var connectGCRCmd = &cobra.Command{
 var connectGCRCmd = &cobra.Command{
 	Use:   "gcr",
 	Use:   "gcr",
 	Short: "Adds a GCR instance to a project",
 	Short: "Adds a GCR instance to a project",
@@ -135,7 +123,6 @@ func init() {
 		"the context to connect (defaults to the current context)",
 		"the context to connect (defaults to the current context)",
 	)
 	)
 
 
-	connectCmd.AddCommand(connectActionsCmd)
 	connectCmd.AddCommand(connectECRCmd)
 	connectCmd.AddCommand(connectECRCmd)
 	connectCmd.AddCommand(connectRegistryCmd)
 	connectCmd.AddCommand(connectRegistryCmd)
 	connectCmd.AddCommand(connectDockerhubCmd)
 	connectCmd.AddCommand(connectDockerhubCmd)
@@ -243,10 +230,3 @@ func runConnectHelmRepoBasic(_ *api.AuthCheckResponse, client *api.Client, _ []s
 
 
 	return config.SetHelmRepo(hrID)
 	return config.SetHelmRepo(hrID)
 }
 }
-
-func runConnectActions(_ *api.AuthCheckResponse, client *api.Client, _ []string) error {
-	return connect.Actions(
-		client,
-		config.Project,
-	)
-}

+ 0 - 125
cli/cmd/connect/actions.go

@@ -1,125 +0,0 @@
-package connect
-
-import (
-	"context"
-	"fmt"
-	"strconv"
-	"time"
-
-	"github.com/porter-dev/porter/cli/cmd/api"
-	"github.com/porter-dev/porter/cli/cmd/utils"
-
-	ints "github.com/porter-dev/porter/internal/models/integrations"
-)
-
-// Actions creates a github actions integration
-func Actions(
-	client *api.Client,
-	projectID uint,
-) error {
-	// if project ID is 0, ask the user to set the project ID or create a project
-	if projectID == 0 {
-		return fmt.Errorf("no project set, please run porter project set [id]")
-	}
-
-	// list oauth integrations and make sure Github exists
-	oauthInts, err := client.ListOAuthIntegrations(context.TODO(), projectID)
-
-	if err != nil {
-		return err
-	}
-
-	linkedGH := false
-
-	// iterate through oauth integrations to find do
-	for _, oauthInt := range oauthInts {
-		if oauthInt.Client == ints.OAuthGithub {
-			linkedGH = true
-			break
-		}
-	}
-
-	if !linkedGH {
-		_, err = triggerGithubOAuth(client, projectID)
-
-		if err != nil {
-			return err
-		}
-	}
-
-	gitRepos, err := client.ListGitRepos(context.TODO(), projectID)
-
-	gitRepoID := gitRepos[0].ID
-
-	// prompts (unfortunately a lot)
-	clusterIDStr, _ := utils.PromptPlaintext(fmt.Sprintf(`Please provide the cluster id (can be found with "porter clusters list").
-Cluster ID: `))
-	clusterID, err := strconv.ParseUint(clusterIDStr, 10, 64)
-
-	if err != nil {
-		return err
-	}
-
-	releaseName, _ := utils.PromptPlaintext(fmt.Sprintf(`Release name:`))
-	releaseNamespace, _ := utils.PromptPlaintext(fmt.Sprintf(`Release namespace:`))
-	gitRepo, _ := utils.PromptPlaintext(fmt.Sprintf(`Please enter the Github repo, in the form ${owner}/${repo_name}. For example, porter-dev/porter.
-Github repo:`))
-
-	imageRepo, _ := utils.PromptPlaintext(fmt.Sprintf(`Please enter the image repo url.
-Image repo:`))
-
-	dockerfilePath, _ := utils.PromptPlaintext(fmt.Sprintf(`Please enter the path in the repo to your dockerfile.
-Dockerfile path:`))
-
-	err = client.CreateGithubAction(
-		context.Background(),
-		projectID,
-		uint(clusterID),
-		releaseName,
-		releaseNamespace,
-		&api.CreateGithubActionRequest{
-			GitRepo:        gitRepo,
-			ImageRepoURI:   imageRepo,
-			DockerfilePath: dockerfilePath,
-			GitRepoID:      gitRepoID,
-		},
-	)
-
-	return err
-}
-
-func triggerGithubOAuth(client *api.Client, projectID uint) (ints.OAuthIntegrationExternal, error) {
-	var ghAuth ints.OAuthIntegrationExternal
-
-	oauthURL := fmt.Sprintf("%s/oauth/projects/%d/github", client.BaseURL, projectID)
-
-	fmt.Printf("Please visit %s in your browser to connect to Github (it should open automatically).", oauthURL)
-	utils.OpenBrowser(oauthURL)
-
-	for {
-		oauthInts, err := client.ListOAuthIntegrations(context.TODO(), projectID)
-
-		if err != nil {
-			return ghAuth, err
-		}
-
-		linkedGH := false
-
-		// iterate through oauth integrations to find do
-		for _, oauthInt := range oauthInts {
-			if oauthInt.Client == ints.OAuthGithub {
-				linkedGH = true
-				ghAuth = oauthInt
-				break
-			}
-		}
-
-		if linkedGH {
-			break
-		}
-
-		time.Sleep(2 * time.Second)
-	}
-
-	return ghAuth, nil
-}

+ 2 - 2
cli/cmd/deploy/create.go

@@ -59,7 +59,7 @@ func (c *CreateAgent) CreateFromGithub(
 		githubRepos, err := c.Client.ListGithubRepos(
 		githubRepos, err := c.Client.ListGithubRepos(
 			context.Background(),
 			context.Background(),
 			c.CreateOpts.ProjectID,
 			c.CreateOpts.ProjectID,
-			gitRepo.ID,
+			gitRepo,
 		)
 		)
 
 
 		if err != nil {
 		if err != nil {
@@ -68,7 +68,7 @@ func (c *CreateAgent) CreateFromGithub(
 
 
 		for _, githubRepo := range githubRepos {
 		for _, githubRepo := range githubRepos {
 			if githubRepo.FullName == ghOpts.Repo {
 			if githubRepo.FullName == ghOpts.Repo {
-				gitRepoMatch = gitRepo.ID
+				gitRepoMatch = gitRepo
 				break
 				break
 			}
 			}
 		}
 		}

+ 6 - 2
cli/cmd/errors.go

@@ -2,12 +2,16 @@ package cmd
 
 
 import (
 import (
 	"context"
 	"context"
+	"errors"
 	"strings"
 	"strings"
 
 
 	"github.com/fatih/color"
 	"github.com/fatih/color"
 	"github.com/porter-dev/porter/cli/cmd/api"
 	"github.com/porter-dev/porter/cli/cmd/api"
 )
 )
 
 
+var ErrNotLoggedIn error = errors.New("You are not logged in.")
+var ErrCannotConnect error = errors.New("Unable to connect to the Porter server.")
+
 func checkLoginAndRun(args []string, runner func(user *api.AuthCheckResponse, client *api.Client, args []string) error) error {
 func checkLoginAndRun(args []string, runner func(user *api.AuthCheckResponse, client *api.Client, args []string) error) error {
 	client := GetAPIClient(config)
 	client := GetAPIClient(config)
 
 
@@ -18,12 +22,12 @@ func checkLoginAndRun(args []string, runner func(user *api.AuthCheckResponse, cl
 
 
 		if strings.Contains(err.Error(), "403") {
 		if strings.Contains(err.Error(), "403") {
 			red.Print("You are not logged in. Log in using \"porter auth login\"\n")
 			red.Print("You are not logged in. Log in using \"porter auth login\"\n")
-			return nil
+			return ErrNotLoggedIn
 		} else if strings.Contains(err.Error(), "connection refused") {
 		} else if strings.Contains(err.Error(), "connection refused") {
 			red.Printf("Unable to connect to the Porter server at %s\n", config.Host)
 			red.Printf("Unable to connect to the Porter server at %s\n", config.Host)
 			red.Print("To set a different host, run \"porter config set-host [HOST]\"\n")
 			red.Print("To set a different host, run \"porter config set-host [HOST]\"\n")
 			red.Print("To start a local server, run \"porter server start\"\n")
 			red.Print("To start a local server, run \"porter server start\"\n")
-			return nil
+			return ErrCannotConnect
 		}
 		}
 
 
 		red.Printf("Error: %v\n", err.Error())
 		red.Printf("Error: %v\n", err.Error())

+ 1 - 0
cli/cmd/logs.go

@@ -13,6 +13,7 @@ import (
 // without any subcommands
 // without any subcommands
 var logsCmd = &cobra.Command{
 var logsCmd = &cobra.Command{
 	Use:   "logs [release]",
 	Use:   "logs [release]",
+	Args:  cobra.ExactArgs(1),
 	Short: "Logs the output from a given application.",
 	Short: "Logs the output from a given application.",
 	Run: func(cmd *cobra.Command, args []string) {
 	Run: func(cmd *cobra.Command, args []string) {
 		err := checkLoginAndRun(args, logs)
 		err := checkLoginAndRun(args, logs)

+ 34 - 9
cli/cmd/run.go

@@ -25,6 +25,7 @@ import (
 )
 )
 
 
 var namespace string
 var namespace string
+var verbose bool
 
 
 // runCmd represents the "porter run" base command when called
 // runCmd represents the "porter run" base command when called
 // without any subcommands
 // without any subcommands
@@ -60,6 +61,14 @@ func init() {
 		false,
 		false,
 		"whether to connect to an existing pod",
 		"whether to connect to an existing pod",
 	)
 	)
+
+	runCmd.PersistentFlags().BoolVarP(
+		&verbose,
+		"verbose",
+		"v",
+		false,
+		"whether to print verbose output",
+	)
 }
 }
 
 
 func run(_ *api.AuthCheckResponse, client *api.Client, args []string) error {
 func run(_ *api.AuthCheckResponse, client *api.Client, args []string) error {
@@ -326,20 +335,25 @@ func executeRunEphemeral(config *PorterRunSharedConfig, namespace, name, contain
 
 
 		time.Sleep(2 * time.Second)
 		time.Sleep(2 * time.Second)
 
 
-		// ugly way to catch no TTY errors, such as when running command "echo \"hello\""
-		if i == 4 && err != nil {
-			color.New(color.FgYellow).Println("Could not open a shell to this container. Container logs:\n")
+	}
 
 
-			var writtenBytes int64
+	// ugly way to catch no TTY errors, such as when running command "echo \"hello\""
+	if err != nil {
+		color.New(color.FgYellow).Println("Could not open a shell to this container. Container logs:\n")
 
 
-			writtenBytes, err = pipePodLogsToStdout(config, namespace, podName, container, false)
+		var writtenBytes int64
 
 
-			if writtenBytes == 0 {
-				color.New(color.FgYellow).Println("Could not get logs. Pod events:\n")
+		writtenBytes, err = pipePodLogsToStdout(config, namespace, podName, container, false)
 
 
-				err = pipeEventsToStdout(config, namespace, podName, container, false)
-			}
+		if verbose || writtenBytes == 0 {
+			color.New(color.FgYellow).Println("Could not get logs. Pod events:\n")
+
+			err = pipeEventsToStdout(config, namespace, podName, container, false)
 		}
 		}
+	} else if verbose {
+		color.New(color.FgYellow).Println("Pod events:\n")
+
+		pipeEventsToStdout(config, namespace, podName, container, false)
 	}
 	}
 
 
 	// delete the ephemeral pod
 	// delete the ephemeral pod
@@ -370,6 +384,9 @@ func pipePodLogsToStdout(config *PorterRunSharedConfig, namespace, name, contain
 }
 }
 
 
 func pipeEventsToStdout(config *PorterRunSharedConfig, namespace, name, container string, follow bool) error {
 func pipeEventsToStdout(config *PorterRunSharedConfig, namespace, name, container string, follow bool) error {
+	// update the config in case the operation has taken longer than token expiry time
+	config.setSharedConfig()
+
 	// creates the clientset
 	// creates the clientset
 	resp, err := config.Clientset.CoreV1().Events(namespace).List(
 	resp, err := config.Clientset.CoreV1().Events(namespace).List(
 		context.TODO(),
 		context.TODO(),
@@ -428,6 +445,9 @@ func createPodFromExisting(config *PorterRunSharedConfig, existing *v1.Pod, args
 
 
 	newPod.Status = v1.PodStatus{}
 	newPod.Status = v1.PodStatus{}
 
 
+	// only use "primary" container
+	newPod.Spec.Containers = newPod.Spec.Containers[0:1]
+
 	// set restart policy to never
 	// set restart policy to never
 	newPod.Spec.RestartPolicy = v1.RestartPolicyNever
 	newPod.Spec.RestartPolicy = v1.RestartPolicyNever
 
 
@@ -446,6 +466,11 @@ func createPodFromExisting(config *PorterRunSharedConfig, existing *v1.Pod, args
 	newPod.Spec.Containers[0].StdinOnce = true
 	newPod.Spec.Containers[0].StdinOnce = true
 	newPod.Spec.NodeName = ""
 	newPod.Spec.NodeName = ""
 
 
+	// remove health checks and probes
+	newPod.Spec.Containers[0].LivenessProbe = nil
+	newPod.Spec.Containers[0].ReadinessProbe = nil
+	newPod.Spec.Containers[0].StartupProbe = nil
+
 	// create the pod and return it
 	// create the pod and return it
 	return config.Clientset.CoreV1().Pods(existing.ObjectMeta.Namespace).Create(
 	return config.Clientset.CoreV1().Pods(existing.ObjectMeta.Namespace).Create(
 		context.Background(),
 		context.Background(),

+ 15 - 5
server/api/user_handler.go

@@ -838,20 +838,30 @@ func (app *App) sendUser(w http.ResponseWriter, userID uint, email string, email
 }
 }
 
 
 func (app *App) getUserIDFromRequest(r *http.Request) (uint, error) {
 func (app *App) getUserIDFromRequest(r *http.Request) (uint, error) {
+	// first, check for token
+	tok := app.getTokenFromRequest(r)
+
+	if tok != nil {
+		return tok.IBy, nil
+	}
+
 	session, err := app.Store.Get(r, app.ServerConf.CookieName)
 	session, err := app.Store.Get(r, app.ServerConf.CookieName)
 
 
 	if err != nil {
 	if err != nil {
 		return 0, err
 		return 0, err
 	}
 	}
 
 
-	// first, check for token
-	tok := app.getTokenFromRequest(r)
+	sessID, ok := session.Values["user_id"]
 
 
-	if tok != nil {
-		return tok.IBy, nil
+	if !ok {
+		return 0, fmt.Errorf("could not get user id from session")
 	}
 	}
 
 
-	userID, _ := session.Values["user_id"].(uint)
+	userID, ok := sessID.(uint)
+
+	if !ok {
+		return 0, fmt.Errorf("could not get user id from session")
+	}
 
 
 	return userID, nil
 	return userID, nil
 }
 }

+ 11 - 0
services/porter_cli_container/Dockerfile

@@ -0,0 +1,11 @@
+FROM ubuntu:latest
+
+COPY get-porter-cli.sh /scratch/
+
+RUN apt-get update && apt-get install -y curl unzip
+
+ARG VERSION
+
+RUN /scratch/get-porter-cli.sh
+
+ENTRYPOINT ["porter"]

+ 15 - 0
services/porter_cli_container/get-porter-cli.sh

@@ -0,0 +1,15 @@
+#!/usr/bin/env bash
+
+if [[ -z $VERSION ]]; then
+  name=$(curl -s https://api.github.com/repos/porter-dev/porter/releases/latest | grep "browser_download_url.*/porter_.*_Linux_x86_64\.zip" | cut -d ":" -f 2,3 | tr -d \")
+  name=$(basename "$name")
+  curl -L https://github.com/porter-dev/porter/releases/latest/download/"$name" --output "$name"
+else
+  name=porter-$VERSION.zip
+  curl -L https://github.com/porter-dev/porter/releases/download/"$VERSION"/porter_"$VERSION"_Linux_x86_64.zip --output "$name"
+fi
+
+unzip -a "$name"
+rm "$name"
+chmod +x ./porter
+mv ./porter /usr/local/bin/