Przeglądaj źródła

Merge branch 'master' of github.com:porter-dev/porter into belanger/por-160-pod-events-backend

jnfrati 4 lat temu
rodzic
commit
e9647da0bc
43 zmienionych plików z 1839 dodań i 516 usunięć
  1. 2 2
      api/server/authn/handler.go
  2. 8 6
      api/server/authn/session_helpers.go
  3. 5 1
      api/server/authz/git_installation.go
  4. 5 1
      api/server/handlers/handler.go
  5. 63 0
      api/server/handlers/namespace/delete_crd.go
  6. 63 1
      api/server/handlers/release/get.go
  7. 129 0
      api/server/handlers/release/stream_form.go
  8. 13 2
      api/server/handlers/user/create.go
  9. 11 11
      api/server/handlers/user/github_callback.go
  10. 11 11
      api/server/handlers/user/google_callback.go
  11. 8 1
      api/server/handlers/user/login.go
  12. 29 0
      api/server/router/namespace.go
  13. 32 0
      api/server/router/release.go
  14. 16 0
      api/types/crd.go
  15. 13 5
      dashboard/package-lock.json
  16. 1 1
      dashboard/package.json
  17. 94 44
      dashboard/src/components/ExpandableResource.tsx
  18. 14 13
      dashboard/src/components/ProvisionerStatus.tsx
  19. 52 5
      dashboard/src/components/Selector.tsx
  20. 83 3
      dashboard/src/components/porter-form/field-components/ResourceList.tsx
  21. 12 0
      dashboard/src/components/porter-form/types.ts
  22. 12 0
      dashboard/src/main/home/ModalHandler.tsx
  23. 7 5
      dashboard/src/main/home/cluster-dashboard/env-groups/EnvGroupDashboard.tsx
  24. 3 3
      dashboard/src/main/home/dashboard/Dashboard.tsx
  25. 4 5
      dashboard/src/main/home/modals/DeleteNamespaceModal.tsx
  26. 58 0
      dashboard/src/main/home/modals/SkipProvisioningModal.tsx
  27. 32 0
      dashboard/src/main/home/onboarding/Onboarding.tsx
  28. 19 7
      dashboard/src/main/home/onboarding/components/ProviderSelector.tsx
  29. 15 0
      dashboard/src/main/home/onboarding/state/StateHandler.ts
  30. 6 2
      dashboard/src/main/home/onboarding/state/StepHandler.ts
  31. 106 4
      dashboard/src/main/home/onboarding/steps/ConnectRegistry/ConnectRegistry.tsx
  32. 193 0
      dashboard/src/main/home/onboarding/steps/ConnectRegistry/components/Registry.tsx
  33. 1 1
      dashboard/src/main/home/onboarding/steps/ConnectSource.tsx
  34. 6 3
      dashboard/src/main/home/onboarding/steps/ProvisionResources/ProvisionResources.tsx
  35. 1 1
      dashboard/src/main/home/onboarding/steps/ProvisionResources/forms/FormFlow.tsx
  36. 0 365
      dashboard/src/main/home/onboarding/steps/ProvisionResources/forms/SharedStatus.tsx
  37. 641 0
      dashboard/src/main/home/onboarding/steps/ProvisionResources/forms/StatusPage.tsx
  38. 0 1
      dashboard/src/main/home/onboarding/steps/ProvisionResources/forms/_AWSProvisionerForm.tsx
  39. 0 6
      dashboard/src/main/home/onboarding/steps/ProvisionResources/forms/_DOProvisionerForm.tsx
  40. 0 1
      dashboard/src/main/home/onboarding/steps/ProvisionResources/forms/_GCPProvisionerForm.tsx
  41. 12 3
      internal/templater/dynamic/reader.go
  42. 6 2
      internal/templater/dynamic/writer.go
  43. 53 0
      internal/templater/parser/parser.go

+ 2 - 2
api/server/authn/handler.go

@@ -105,9 +105,9 @@ func (authn *AuthN) handleForbiddenForSession(
 	if authn.redirect {
 		// need state parameter to validate when redirected
 		if r.URL.RawQuery == "" {
-			session.Values["redirect"] = r.URL.Path
+			session.Values["redirect_uri"] = r.URL.Path
 		} else {
-			session.Values["redirect"] = r.URL.Path + "?" + r.URL.RawQuery
+			session.Values["redirect_uri"] = r.URL.Path + "?" + r.URL.RawQuery
 		}
 
 		session.Save(r, w)

+ 8 - 6
api/server/authn/session_helpers.go

@@ -12,25 +12,27 @@ func SaveUserAuthenticated(
 	r *http.Request,
 	config *config.Config,
 	user *models.User,
-) error {
+) (string, error) {
 	session, err := config.Store.Get(r, config.ServerConf.CookieName)
 
 	if err != nil {
-		return err
+		return "", err
 	}
 
 	var redirect string
 
-	if valR := session.Values["redirect"]; valR != nil {
-		redirect = session.Values["redirect"].(string)
+	if valR := session.Values["redirect_uri"]; valR != nil {
+		redirect = session.Values["redirect_uri"].(string)
 	}
 
 	session.Values["authenticated"] = true
 	session.Values["user_id"] = user.ID
 	session.Values["email"] = user.Email
-	session.Values["redirect"] = redirect
 
-	return session.Save(r, w)
+	// we unset the redirect uri after login
+	session.Values["redirect_uri"] = ""
+
+	return redirect, session.Save(r, w)
 }
 
 func SaveUserUnauthenticated(

+ 5 - 1
api/server/authz/git_installation.go

@@ -75,8 +75,12 @@ func (p *GitInstallationScopedMiddleware) doesUserHaveGitInstallationAccess(gith
 		return err
 	}
 
+	if p.config.GithubAppConf == nil {
+		return fmt.Errorf("config has invalid GithubAppConf")
+	}
+
 	if _, _, err = oauth.GetAccessToken(oauthInt.SharedOAuthModel,
-		p.config.GithubConf,
+		&p.config.GithubAppConf.Config,
 		oauth.MakeUpdateGithubAppOauthIntegrationFunction(oauthInt, p.config.Repo)); err != nil {
 		return err
 	}

+ 5 - 1
api/server/handlers/handler.go

@@ -90,7 +90,11 @@ func (d *DefaultPorterHandler) PopulateOAuthSession(w http.ResponseWriter, r *ht
 
 	// need state parameter to validate when redirected
 	session.Values["state"] = state
-	session.Values["redirect_uri"] = r.URL.Query().Get("redirect_uri")
+
+	// check if redirect uri is populated, then overwrite
+	if redirect := r.URL.Query().Get("redirect_uri"); redirect != "" {
+		session.Values["redirect_uri"] = redirect
+	}
 
 	if isProject {
 		project, _ := r.Context().Value(types.ProjectScope).(*models.Project)

+ 63 - 0
api/server/handlers/namespace/delete_crd.go

@@ -0,0 +1,63 @@
+package namespace
+
+import (
+	"net/http"
+
+	"github.com/porter-dev/porter/api/server/authz"
+	"github.com/porter-dev/porter/api/server/handlers"
+	"github.com/porter-dev/porter/api/server/shared"
+	"github.com/porter-dev/porter/api/server/shared/apierrors"
+	"github.com/porter-dev/porter/api/server/shared/config"
+	"github.com/porter-dev/porter/api/types"
+	"github.com/porter-dev/porter/internal/models"
+	"github.com/porter-dev/porter/internal/templater/dynamic"
+)
+
+type CRDDeleteHandler struct {
+	handlers.PorterHandlerReadWriter
+	authz.KubernetesAgentGetter
+}
+
+func NewCRDDeleteHandler(
+	config *config.Config,
+	decoderValidator shared.RequestDecoderValidator,
+	writer shared.ResultWriter,
+) *CRDDeleteHandler {
+	return &CRDDeleteHandler{
+		PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
+		KubernetesAgentGetter:   authz.NewOutOfClusterAgentGetter(config),
+	}
+}
+
+func (c *CRDDeleteHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+	cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
+	client, err := c.GetDynamicClient(r, cluster)
+
+	if err != nil {
+		c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
+		return
+	}
+
+	request := &types.DeleteCRDRequest{}
+
+	if ok := c.DecodeAndValidate(w, r, request); !ok {
+		return
+	}
+
+	crdWriter := dynamic.NewDynamicTemplateWriter(client, &dynamic.Object{
+		Group:     request.Group,
+		Version:   request.Version,
+		Resource:  request.Resource,
+		Namespace: request.Namespace,
+		Name:      request.Name,
+	}, map[string]interface{}{})
+
+	err = crdWriter.Delete()
+
+	if err != nil {
+		c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
+		return
+	}
+
+	w.WriteHeader(http.StatusOK)
+}

+ 63 - 1
api/server/handlers/release/get.go

@@ -104,10 +104,72 @@ func (c *ReleaseGetHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
 	form, err := parser.GetFormFromRelease(parserDef, helmRelease)
 
 	if err != nil {
-		// TODO: log non-fatal parsing error
+		c.HandleAPIErrorNoWrite(w, r, apierrors.NewErrInternal(err))
 	} else {
 		res.Form = form
 	}
+	// if form not populated, detect common charts
+	if res.Form == nil {
+		// for now just case by name
+		if res.Release.Chart.Name() == "cert-manager" {
+			formYAML, err := parser.FormYAMLFromBytes(parserDef, []byte(certManagerForm), "")
+
+			if err == nil {
+				res.Form = formYAML
+			}
+		}
+	}
 
 	c.WriteResult(w, r, res)
 }
+
+const certManagerForm string = `tags:
+- hello
+tabs:
+- name: main
+  context:
+    type: cluster
+    config:
+      group: cert-manager.io
+      version: v1
+      resource: certificates
+  label: Certificates
+  sections:
+  - name: section_one
+    contents: 
+    - type: heading
+      label: Certificates
+    - type: resource-list
+      settings:
+        options:
+          resource-button:
+            name: "Renew Certificate"
+            description: "This will delete the existing certificate resource, triggering a new certificate request."
+            actions:
+            - delete:
+                scope: namespace
+                relative_uri: /crd
+                context:
+                  type: cluster
+                  config:
+                    group: cert-manager.io
+                    version: v1
+                    resource: certificates
+      value: |
+        .items[] | { 
+          metadata: .metadata,
+          name: "\(.spec.dnsNames | join(","))", 
+          label: "\(.metadata.namespace)/\(.metadata.name)",
+          status: (
+            ([.status.conditions[].type] | index("Ready")) as $index | (
+              if $index then (
+                if .status.conditions[$index].status == "True" then "Ready" else "Not Ready" end
+              ) else (
+                "Not Ready"
+              ) end
+            )
+          ),
+          timestamp: .status.conditions[0].lastTransitionTime,
+          message: [.status.conditions[].message] | unique | join(","),
+          data: {}
+        }`

+ 129 - 0
api/server/handlers/release/stream_form.go

@@ -0,0 +1,129 @@
+package release
+
+import (
+	"encoding/json"
+	"net/http"
+	"strings"
+
+	"github.com/porter-dev/porter/api/server/authz"
+	"github.com/porter-dev/porter/api/server/handlers"
+	"github.com/porter-dev/porter/api/server/shared"
+	"github.com/porter-dev/porter/api/server/shared/apierrors"
+	"github.com/porter-dev/porter/api/server/shared/config"
+	"github.com/porter-dev/porter/api/server/shared/websocket"
+	"github.com/porter-dev/porter/api/types"
+	"github.com/porter-dev/porter/internal/models"
+	"github.com/porter-dev/porter/internal/templater/parser"
+	"helm.sh/helm/v3/pkg/release"
+)
+
+type StreamFormHandler struct {
+	handlers.PorterHandlerReadWriter
+	authz.KubernetesAgentGetter
+}
+
+func NewStreamFormHandler(
+	config *config.Config,
+	decoderValidator shared.RequestDecoderValidator,
+	writer shared.ResultWriter,
+) *StreamFormHandler {
+	return &StreamFormHandler{
+		PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
+		KubernetesAgentGetter:   authz.NewOutOfClusterAgentGetter(config),
+	}
+}
+
+func getStreamWriter(rw *websocket.WebsocketSafeReadWriter) func(val map[string]interface{}) error {
+	return func(val map[string]interface{}) error {
+		// parse value into json
+		bytes, err := json.Marshal(val)
+
+		if err != nil {
+			return err
+		}
+
+		_, err = rw.Write(bytes)
+		return err
+	}
+}
+
+func (c *StreamFormHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+	helmRelease, _ := r.Context().Value(types.ReleaseScope).(*release.Release)
+	cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
+	safeRW := r.Context().Value(types.RequestCtxWebsocketKey).(*websocket.WebsocketSafeReadWriter)
+
+	request := &types.StreamCRDRequest{}
+
+	if ok := c.DecodeAndValidate(w, r, request); !ok {
+		return
+	}
+
+	// look for the form using the dynamic client
+	dynClient, err := c.GetDynamicClient(r, cluster)
+
+	if err != nil {
+		c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
+		return
+	}
+
+	parserDef := &parser.ClientConfigDefault{
+		DynamicClient: dynClient,
+		HelmChart:     helmRelease.Chart,
+		HelmRelease:   helmRelease,
+	}
+
+	var formData []byte
+
+	for _, file := range helmRelease.Chart.Files {
+		if strings.Contains(file.Name, "form.yaml") {
+			formData = file.Data
+			break
+		}
+	}
+
+	// if form data isn't found, look for common charts
+	if formData == nil {
+		// for now just case by name
+		if helmRelease.Chart.Name() == "cert-manager" {
+			formData = []byte(certManagerForm)
+		}
+	}
+
+	stopper := make(chan struct{})
+	errorchan := make(chan error)
+	defer close(stopper)
+
+	go func() {
+		// listens for websocket closing handshake
+		for {
+			if _, _, err := safeRW.ReadMessage(); err != nil {
+				errorchan <- nil
+				return
+			}
+		}
+	}()
+
+	onData := getStreamWriter(safeRW)
+
+	err = parser.FormStreamer(parserDef, formData, "", &types.FormContext{
+		Type: "cluster",
+		Config: map[string]string{
+			"group":    request.Group,
+			"resource": request.Resource,
+			"version":  request.Version,
+		},
+	}, onData, stopper)
+
+	if err != nil {
+		c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
+		return
+	}
+
+	for {
+		select {
+		case err := <-errorchan:
+			c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
+			return
+		}
+	}
+}

+ 13 - 2
api/server/handlers/user/create.go

@@ -77,14 +77,20 @@ func (u *UserCreateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
 	}
 
 	// save the user as authenticated in the session
-	if err := authn.SaveUserAuthenticated(w, r, u.Config(), user); err != nil {
+	redirect, err := authn.SaveUserAuthenticated(w, r, u.Config(), user)
+
+	if err != nil {
 		u.HandleAPIError(w, r, apierrors.NewErrInternal(err))
 		return
 	}
 
 	// non-fatal send email verification
 	if !user.EmailVerified {
-		startEmailVerification(u.Config(), w, r, user)
+		err = startEmailVerification(u.Config(), w, r, user)
+
+		if err != nil {
+			u.HandleAPIErrorNoWrite(w, r, apierrors.NewErrInternal(err))
+		}
 	}
 
 	u.Config().AnalyticsClient.Identify(analytics.CreateSegmentIdentifyUser(user))
@@ -94,6 +100,11 @@ func (u *UserCreateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
 		Email:               user.Email,
 	}))
 
+	if redirect != "" {
+		http.Redirect(w, r, redirect, http.StatusFound)
+		return
+	}
+
 	u.WriteResult(w, r, user.ToUserType())
 }
 

+ 11 - 11
api/server/handlers/user/github_callback.go

@@ -78,28 +78,28 @@ func (p *UserOAuthGithubCallbackHandler) ServeHTTP(w http.ResponseWriter, r *htt
 	p.Config().AnalyticsClient.Identify(analytics.CreateSegmentIdentifyUser(user))
 
 	// save the user as authenticated in the session
-	if err := authn.SaveUserAuthenticated(w, r, p.Config(), user); err != nil {
+	redirect, err := authn.SaveUserAuthenticated(w, r, p.Config(), user)
+
+	if err != nil {
 		p.HandleAPIError(w, r, apierrors.NewErrInternal(err))
 		return
 	}
 
 	// non-fatal send email verification
 	if !user.EmailVerified {
-		startEmailVerification(p.Config(), w, r, user)
-	}
-
-	if redirectStr, ok := session.Values["redirect_uri"].(string); ok && redirectStr != "" {
-		// attempt to parse the redirect uri, if it fails just redirect to dashboard
-		redirectURI, err := url.Parse(redirectStr)
+		err = startEmailVerification(p.Config(), w, r, user)
 
 		if err != nil {
-			http.Redirect(w, r, "/dashboard", 302)
+			p.HandleAPIErrorNoWrite(w, r, apierrors.NewErrInternal(err))
 		}
+	}
 
-		http.Redirect(w, r, fmt.Sprintf("%s?%s", redirectURI.Path, redirectURI.RawQuery), 302)
-	} else {
-		http.Redirect(w, r, "/dashboard", 302)
+	if redirect != "" {
+		http.Redirect(w, r, redirect, http.StatusFound)
+		return
 	}
+
+	http.Redirect(w, r, "/dashboard", 302)
 }
 
 func upsertUserFromToken(config *config.Config, tok *oauth2.Token) (*models.User, error) {

+ 11 - 11
api/server/handlers/user/google_callback.go

@@ -81,28 +81,28 @@ func (p *UserOAuthGoogleCallbackHandler) ServeHTTP(w http.ResponseWriter, r *htt
 	p.Config().AnalyticsClient.Identify(analytics.CreateSegmentIdentifyUser(user))
 
 	// save the user as authenticated in the session
-	if err := authn.SaveUserAuthenticated(w, r, p.Config(), user); err != nil {
+	redirect, err := authn.SaveUserAuthenticated(w, r, p.Config(), user)
+
+	if err != nil {
 		p.HandleAPIError(w, r, apierrors.NewErrInternal(err))
 		return
 	}
 
 	// non-fatal send email verification
 	if !user.EmailVerified {
-		startEmailVerification(p.Config(), w, r, user)
-	}
-
-	if redirectStr, ok := session.Values["redirect_uri"].(string); ok && redirectStr != "" {
-		// attempt to parse the redirect uri, if it fails just redirect to dashboard
-		redirectURI, err := url.Parse(redirectStr)
+		err = startEmailVerification(p.Config(), w, r, user)
 
 		if err != nil {
-			http.Redirect(w, r, "/dashboard", 302)
+			p.HandleAPIErrorNoWrite(w, r, apierrors.NewErrInternal(err))
 		}
+	}
 
-		http.Redirect(w, r, fmt.Sprintf("%s?%s", redirectURI.Path, redirectURI.RawQuery), 302)
-	} else {
-		http.Redirect(w, r, "/dashboard", 302)
+	if redirect != "" {
+		http.Redirect(w, r, redirect, http.StatusFound)
+		return
 	}
+
+	http.Redirect(w, r, "/dashboard", 302)
 }
 
 func upsertGoogleUserFromToken(config *config.Config, tok *oauth2.Token) (*models.User, error) {

+ 8 - 1
api/server/handlers/user/login.go

@@ -63,11 +63,18 @@ func (u *UserLoginHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
 	}
 
 	// save the user as authenticated in the session
-	if err := authn.SaveUserAuthenticated(w, r, u.Config(), storedUser); err != nil {
+	redirect, err := authn.SaveUserAuthenticated(w, r, u.Config(), storedUser)
+
+	if err != nil {
 		u.HandleAPIError(w, r, apierrors.NewErrInternal(err))
 		return
 	}
 
+	if redirect != "" {
+		http.Redirect(w, r, redirect, http.StatusFound)
+		return
+	}
+
 	u.WriteResult(w, r, storedUser.ToUserType())
 }
 

+ 29 - 0
api/server/router/namespace.go

@@ -234,6 +234,35 @@ func getNamespaceRoutes(
 		Router:   r,
 	})
 
+	// DELETE /api/projects/{project_id}/clusters/{cluster_id}/namespaces/{namespace}/crd -> namespace.NewCRDDeleteHandler
+	deleteCRDEndpoint := factory.NewAPIEndpoint(
+		&types.APIRequestMetadata{
+			Verb:   types.APIVerbDelete,
+			Method: types.HTTPVerbDelete,
+			Path: &types.Path{
+				Parent:       basePath,
+				RelativePath: relPath + "/crd",
+			},
+			Scopes: []types.PermissionScope{
+				types.UserScope,
+				types.ProjectScope,
+				types.ClusterScope,
+			},
+		},
+	)
+
+	deleteCRDHandler := namespace.NewCRDDeleteHandler(
+		config,
+		factory.GetDecoderValidator(),
+		factory.GetResultWriter(),
+	)
+
+	routes = append(routes, &Route{
+		Endpoint: deleteCRDEndpoint,
+		Handler:  deleteCRDHandler,
+		Router:   r,
+	})
+
 	// GET /api/projects/{project_id}/clusters/{cluster_id}/namespaces/{namespace}/releases -> namespace.NewListReleasesHandler
 	listReleasesEndpoint := factory.NewAPIEndpoint(
 		&types.APIRequestMetadata{

+ 32 - 0
api/server/router/release.go

@@ -82,6 +82,38 @@ func getReleaseRoutes(
 		Router:   r,
 	})
 
+	// GET /api/projects/{project_id}/clusters/{cluster_id}/namespaces/{namespace}/releases/{name}/{version}/form_stream -> release.NewStreamFormHandler
+	streamFormEndpoint := factory.NewAPIEndpoint(
+		&types.APIRequestMetadata{
+			Verb:   types.APIVerbGet,
+			Method: types.HTTPVerbGet,
+			Path: &types.Path{
+				Parent:       basePath,
+				RelativePath: relPath + "/form_stream",
+			},
+			Scopes: []types.PermissionScope{
+				types.UserScope,
+				types.ProjectScope,
+				types.ClusterScope,
+				types.NamespaceScope,
+				types.ReleaseScope,
+			},
+			IsWebsocket: true,
+		},
+	)
+
+	streamFormHandler := release.NewStreamFormHandler(
+		config,
+		factory.GetDecoderValidator(),
+		factory.GetResultWriter(),
+	)
+
+	routes = append(routes, &Route{
+		Endpoint: streamFormEndpoint,
+		Handler:  streamFormHandler,
+		Router:   r,
+	})
+
 	// GET /api/projects/{project_id}/clusters/{cluster_id}/namespaces/{namespace}/releases/{name}/{version}/controllers -> release.NewGetControllersHandler
 	getControllersEndpoint := factory.NewAPIEndpoint(
 		&types.APIRequestMetadata{

+ 16 - 0
api/types/crd.go

@@ -0,0 +1,16 @@
+package types
+
+type DeleteCRDRequest struct {
+	Name      string `schema:"name" form:"required"`
+	Namespace string `schema:"namespace" form:"required"`
+	Group     string `schema:"group" form:"required"`
+	Version   string `schema:"version" form:"required"`
+	Resource  string `schema:"resource" form:"required"`
+}
+
+type StreamCRDRequest struct {
+	Namespace string `json:"namespace"`
+	Group     string `json:"group" form:"required"`
+	Version   string `json:"version" form:"required"`
+	Resource  string `json:"resource" form:"required"`
+}

+ 13 - 5
dashboard/package-lock.json

@@ -4267,11 +4267,18 @@
       "dev": true
     },
     "axios": {
-      "version": "0.20.0",
-      "resolved": "https://registry.npmjs.org/axios/-/axios-0.20.0.tgz",
-      "integrity": "sha512-ANA4rr2BDcmmAQLOKft2fufrtuvlqR+cXNNinUmvfeSNCOF98PZL+7M/v1zIdGo7OLjEA9J2gXJL+j4zGsl0bA==",
+      "version": "0.21.2",
+      "resolved": "https://registry.npmjs.org/axios/-/axios-0.21.2.tgz",
+      "integrity": "sha512-87otirqUw3e8CzHTMO+/9kh/FSgXt/eVDvipijwDtEuwbkySWZ9SBm6VEubmJ/kLKEoLQV/POhxXFb66bfekfg==",
       "requires": {
-        "follow-redirects": "^1.10.0"
+        "follow-redirects": "^1.14.0"
+      },
+      "dependencies": {
+        "follow-redirects": {
+          "version": "1.14.5",
+          "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.5.tgz",
+          "integrity": "sha512-wtphSXy7d4/OR+MvIFbCVBDzZ5520qV8XfPklSN5QtxuMUJZ+b0Wnst1e1lCDocfzuCkHqj8k0FpZqO+UIaKNA=="
+        }
       }
     },
     "babel-loader": {
@@ -6714,7 +6721,8 @@
     "follow-redirects": {
       "version": "1.13.1",
       "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.13.1.tgz",
-      "integrity": "sha512-SSG5xmZh1mkPGyKzjZP8zLjltIfpW32Y5QpdNJyjcfGxK3qo3NDDkZOZSFiGn1A6SclQxY9GzEwAHQ3dmYRWpg=="
+      "integrity": "sha512-SSG5xmZh1mkPGyKzjZP8zLjltIfpW32Y5QpdNJyjcfGxK3qo3NDDkZOZSFiGn1A6SclQxY9GzEwAHQ3dmYRWpg==",
+      "dev": true
     },
     "for-in": {
       "version": "1.0.2",

+ 1 - 1
dashboard/package.json

@@ -19,7 +19,7 @@
     "@visx/tooltip": "^1.3.0",
     "ace-builds": "^1.4.12",
     "anser": "^2.0.1",
-    "axios": "^0.20.0",
+    "axios": "^0.21.2",
     "brace": "^0.11.1",
     "clipboard": "^2.0.8",
     "cohere-js": "^1.0.19",

+ 94 - 44
dashboard/src/components/ExpandableResource.tsx

@@ -1,58 +1,104 @@
-import React, { Component } from "react";
+import React, { Component, useContext, useEffect } from "react";
 import styled from "styled-components";
 import { Context } from "shared/Context";
-
 import ResourceTab from "./ResourceTab";
+import SaveButton from "./SaveButton";
+import { baseApi } from "shared/baseApi";
 
-type PropsType = {
+type Props = {
   resource: any;
+  button: any;
   handleClick?: () => void;
   selected?: boolean;
   isLast?: boolean;
   roundAllCorners?: boolean;
 };
 
-type StateType = any;
-
-export default class ExpandableResource extends Component<
-  PropsType,
-  StateType
-> {
-  render() {
-    let { resource } = this.props;
-    return (
-      <ResourceTab
-        label={resource.label}
-        name={resource.name}
-        status={{ label: resource.status }}
-      >
-        <ExpandedWrapper>
-          <StatusSection>
-            <StatusHeader>
-              <Status>
-                <Key>Status:</Key> {resource.status}
-              </Status>
-              <Timestamp>Updated {resource.timestamp}</Timestamp>
-            </StatusHeader>
-            {resource.message}
-          </StatusSection>
-          {Object.keys(this.props.resource.data).map(
-            (key: string, i: number) => {
-              return (
-                <Pair key={i}>
-                  <Key>{key}:</Key>
-                  {this.props.resource.data[key]}
-                </Pair>
-              );
-            }
-          )}
-        </ExpandedWrapper>
-      </ResourceTab>
-    );
-  }
-}
-
-ExpandableResource.contextType = Context;
+const ExpandableResource: React.FC<Props> = (props) => {
+  const { resource, button } = props;
+  const { currentCluster, currentProject } = useContext(Context);
+
+  const onSave = () => {
+    let projID = currentProject.id;
+    let clusterID = currentCluster.id;
+    let config = button.actions[0].delete.context.config;
+
+    // TODO: construct the endpoint scope, right now we're just using release scope
+    let uri = `/api/projects/${projID}/clusters/${clusterID}/namespaces/${resource.metadata.namespace}${button.actions[0].delete.relative_uri}`;
+
+    // compute the endpoint using button and target context
+    baseApi<
+      {
+        name: string;
+        namespace: string;
+        group: string;
+        version: string;
+        resource: string;
+      },
+      {}
+    >("DELETE", uri)(
+      "<token>",
+      {
+        name: resource.metadata.name,
+        namespace: resource.metadata.namespace,
+        group: config.group,
+        version: config.version,
+        resource: config.resource,
+      },
+      {}
+    )
+      .then((res) => {})
+      .catch((err) => console.log(err));
+  };
+
+  const readableDate = (s: string) => {
+    const ts = new Date(s);
+    const date = ts.toLocaleDateString();
+    const time = ts.toLocaleTimeString([], {
+      hour: "numeric",
+      minute: "2-digit",
+    });
+    return `${time} on ${date}`;
+  };
+
+  return (
+    <ResourceTab
+      label={resource.label}
+      name={resource.name}
+      status={{ label: resource.status }}
+    >
+      <ExpandedWrapper>
+        <StatusSection>
+          <StatusHeader>
+            <Status>
+              <Key>Status:</Key> {resource.status}
+            </Status>
+            <Timestamp>Updated {readableDate(resource.timestamp)}</Timestamp>
+          </StatusHeader>
+          {resource.message}
+        </StatusSection>
+        {Object.keys(resource.data).map((key: string, i: number) => {
+          return (
+            <Pair key={i}>
+              <Key>{key}:</Key>
+              {resource.data[key]}
+            </Pair>
+          );
+        })}
+        <StyledSaveButton
+          onClick={onSave}
+          clearPosition={true}
+          text={button.name}
+          helper={button.description}
+          statusPosition={"right"}
+          className="expanded-save-button"
+        />
+      </ExpandedWrapper>
+    </ResourceTab>
+  );
+};
+
+export default ExpandableResource;
 
 const Timestamp = styled.div`
   font-size: 12px;
@@ -97,3 +143,7 @@ const Key = styled.div`
   color: #ffffff;
   margin-right: 8px;
 `;
+
+const StyledSaveButton = styled(SaveButton)`
+  margin-top: 20px;
+`;

+ 14 - 13
dashboard/src/components/ProvisionerStatus.tsx

@@ -4,7 +4,7 @@ import { integrationList } from "shared/common";
 
 import loading from "assets/loading.gif";
 
-import styled from "styled-components";
+import styled, { keyframes } from "styled-components";
 
 type Props = {
   modules: TFModule[];
@@ -15,6 +15,7 @@ export interface TFModule {
   kind: string;
   status: string;
   created_at: string;
+  updated_at: string;
   global_errors?: TFResourceError[];
   got_desired: boolean;
   // optional resources, if not created
@@ -22,7 +23,7 @@ export interface TFModule {
 }
 
 export interface TFResourceError {
-  errored_out: boolean;
+  errored_out?: boolean;
   error_context?: string;
 }
 
@@ -199,6 +200,16 @@ const ExpandedError = styled.div`
   padding-bottom: 17px;
 `;
 
+const movingGradient = keyframes`
+  0% {
+      background-position: left bottom;
+  }
+
+  100% {
+      background-position: right bottom;
+  }
+`;
+
 const LoadingFill = styled.div<{ width: string; status: string }>`
   width: ${(props) => props.width};
   background: ${(props) =>
@@ -209,19 +220,9 @@ const LoadingFill = styled.div<{ width: string; status: string }>`
       : "linear-gradient(to right, #8ce1ff, #616FEE)"};
   height: 100%;
   background-size: 250% 100%;
-  animation: moving-gradient 2s infinite;
+  animation: ${movingGradient} 2s infinite;
   animation-timing-function: ease-in-out;
   animation-direction: alternate;
-
-  @keyframes moving-gradient {
-    0% {
-        background-position: left bottom;
-    }
-
-    100% {
-        background-position: right bottom;
-    }
-  }​
 `;
 
 const StatusIcon = styled.div<{ successful?: boolean }>`

+ 52 - 5
dashboard/src/components/Selector.tsx

@@ -23,6 +23,7 @@ type StateType = {};
 export default class Selector extends Component<PropsType, StateType> {
   state = {
     expanded: false,
+    showTooltip: false,
   };
 
   wrapperRef: any = React.createRef();
@@ -169,6 +170,8 @@ export default class Selector extends Component<PropsType, StateType> {
           expanded={this.state.expanded}
           width={this.props.width}
           height={this.props.height}
+          onMouseEnter={() => this.setState({ showTooltip: true })}
+          onMouseLeave={() => this.setState({ showTooltip: false })}
         >
           <Flex>
             {this.renderIcon()}
@@ -182,6 +185,15 @@ export default class Selector extends Component<PropsType, StateType> {
           </Flex>
           <i className="material-icons">arrow_drop_down</i>
         </MainSelector>
+        {this.state.showTooltip && (
+          <Tooltip>
+            {activeValue
+              ? activeValue === ""
+                ? "All"
+                : this.getLabel(activeValue)
+              : this.props.placeholder}
+          </Tooltip>
+        )}
         {this.renderDropdown()}
       </StyledSelector>
     );
@@ -206,6 +218,7 @@ const ScrollBuffer = styled.div`
 const Flex = styled.div`
   display: flex;
   align-items: center;
+  width: 85%;
 `;
 
 const Icon = styled.div`
@@ -263,16 +276,18 @@ const NewOption = styled.div`
   }
 `;
 
-const Option = styled.div<{
+type OptionProps = {
   selected: boolean;
   lastItem: boolean;
   height: string;
-}>`
+};
+
+const Option = styled.div`
   width: 100%;
   border-top: 1px solid #00000000;
   border-bottom: 1px solid
-    ${(props) => (props.lastItem ? "#ffffff00" : "#ffffff15")};
-  height: ${(props) => props.height || "37px"};
+    ${(props: OptionProps) => (props.lastItem ? "#ffffff00" : "#ffffff15")};
+  height: ${(props: OptionProps) => props.height || "37px"};
   font-size: 13px;
   align-items: center;
   display: flex;
@@ -283,7 +298,7 @@ const Option = styled.div<{
   white-space: nowrap;
   overflow: hidden;
   text-overflow: ellipsis;
-  background: ${(props) => (props.selected ? "#ffffff11" : "")};
+  background: ${(props: OptionProps) => (props.selected ? "#ffffff11" : "")};
 
   :hover {
     background: #ffffff22;
@@ -353,3 +368,35 @@ const MainSelector = styled.div`
     }) => (props.expanded ? "rotate(180deg)" : "")};
   }
 `;
+
+const Tooltip = styled.div`
+  position: absolute;
+  left: 5px;
+  word-wrap: break-word;
+  top: 40px;
+  min-height: 18px;
+  width: fit-content;
+  padding: 5px 7px;
+  background: #272731;
+  z-index: 999;
+  display: flex;
+  flex-direction: column;
+  justify-content: center;
+  flex: 1;
+  color: white;
+  text-transform: none;
+  font-size: 12px;
+  font-family: "Work Sans", sans-serif;
+  outline: 1px solid #ffffff55;
+  opacity: 0;
+  animation: faded-in 0.2s 0.15s;
+  animation-fill-mode: forwards;
+  @keyframes faded-in {
+    from {
+      opacity: 0;
+    }
+    to {
+      opacity: 1;
+    }
+  }
+`;

+ 83 - 3
dashboard/src/components/porter-form/field-components/ResourceList.tsx

@@ -1,18 +1,98 @@
-import React from "react";
+import React, { useEffect, useContext, useState } from "react";
 import { ResourceListField } from "../types";
+import { Context } from "shared/Context";
+import { useWebsockets } from "shared/hooks/useWebsockets";
 import ExpandableResource from "../../ExpandableResource";
+import { PorterFormContext } from "components/porter-form/PorterFormContextProvider";
 import styled from "styled-components";
 
 const ResourceList: React.FC<ResourceListField> = (props) => {
+  const { currentCluster, currentProject } = useContext(Context);
+  const { formState } = useContext(PorterFormContext);
+  const [resourceList, updateResourceList] = useState<any[]>(props.value);
+
+  const {
+    newWebsocket,
+    openWebsocket,
+    closeAllWebsockets,
+    closeWebsocket,
+  } = useWebsockets();
+
+  const sortAndUpdateResources = (list: any[]) => {
+    list.sort((a, b) => {
+      return b.timestamp.localeCompare(a.timestamp);
+    });
+
+    updateResourceList(list);
+  };
+
+  useEffect(() => {
+    let { group, version, resource } = props.context.config;
+    let apiEndpoint = `/api/projects/${currentProject.id}/clusters/${currentCluster.id}/namespaces/${formState.variables.namespace}/releases/${formState.variables.currentChart.name}/0/form_stream?`;
+    apiEndpoint += `resource=${resource}&group=${group}&version=${version}`;
+
+    const wsConfig = {
+      onmessage(evt: MessageEvent) {
+        let { data, kind } = JSON.parse(evt.data);
+
+        // parse for name and label, which uniquely identify a resource
+        for (let [key] of Object.entries(data)) {
+          // check the name and label in the value
+          let { name, label } = data[key][0];
+
+          // attempt to find a corresponding name and label in the current array
+          let foundMatch = false;
+
+          resourceList.forEach((resource, index) => {
+            if (resource.name == name && resource.label == label) {
+              foundMatch = true;
+
+              switch (kind) {
+                case "update":
+                case "create":
+                  // replace this resource in the list
+                  resourceList[index] = data[key][0];
+                  break;
+                case "delete":
+                  // remove this resource from the list
+                  resourceList.splice(index, 1);
+                  break;
+                default:
+              }
+            }
+          });
+
+          if (!foundMatch && kind != "delete") {
+            // add this resource to the list
+            resourceList.push(data[key][0]);
+          }
+        }
+
+        sortAndUpdateResources([...resourceList]);
+      },
+      onerror() {
+        closeWebsocket("stream");
+      },
+    };
+
+    newWebsocket("stream", apiEndpoint, wsConfig);
+    openWebsocket("stream");
+
+    return () => {
+      closeAllWebsockets();
+    };
+  }, []);
+
   return (
     <ResourceListWrapper>
-      {props.value?.map((resource: any, i: number) => {
+      {resourceList?.map((resource: any, i: number) => {
         if (resource.data) {
           return (
             <ExpandableResource
               key={i}
+              button={props?.settings?.options["resource-button"]}
               resource={resource}
-              isLast={i === props.value.length - 1}
+              isLast={i === resourceList.length - 1}
               roundAllCorners={true}
             />
           );

+ 12 - 0
dashboard/src/components/porter-form/types.ts

@@ -39,6 +39,18 @@ export interface ServiceIPListField extends GenericField {
 export interface ResourceListField extends GenericField {
   type: "resource-list";
   value: any[];
+  context?: {
+    config?: {
+      group: string
+      version: string
+      resource: string
+    }
+  },
+  settings?: {
+    options?: {
+      "resource-button": any,
+    }
+  }
 }
 
 export interface VeleroBackupField extends GenericField {

+ 12 - 0
dashboard/src/main/home/ModalHandler.tsx

@@ -15,6 +15,7 @@ import RedirectToOnboardingModal from "./modals/RedirectToOnboardingModal";
 import UsageWarningModal from "./modals/UsageWarningModal";
 import api from "shared/api";
 import { AxiosError } from "axios";
+import SkipOnboardingModal from "./modals/SkipProvisioningModal";
 
 const ModalHandler: React.FC<{
   setRefreshClusters: (x: boolean) => void;
@@ -187,6 +188,17 @@ const ModalHandler: React.FC<{
           <UsageWarningModal />
         </Modal>
       )}
+
+      {modal === "SkipOnboardingModal" && (
+        <Modal
+          onRequestClose={() => setCurrentModal(null, null)}
+          width="600px"
+          height="240px"
+          title="Would you like to skip project setup?"
+        >
+          <SkipOnboardingModal />
+        </Modal>
+      )}
     </>
   );
 };

+ 7 - 5
dashboard/src/main/home/cluster-dashboard/env-groups/EnvGroupDashboard.tsx

@@ -78,10 +78,6 @@ class EnvGroupDashboard extends Component<PropsType, StateType> {
               </Button>
             )}
             <SortFilterWrapper>
-              <SortSelector
-                setSortType={(sortType) => this.setState({ sortType })}
-                sortType={this.state.sortType}
-              />
               <NamespaceSelector
                 setNamespace={(namespace) =>
                   this.setState({ namespace }, () => {
@@ -92,6 +88,10 @@ class EnvGroupDashboard extends Component<PropsType, StateType> {
                 }
                 namespace={this.state.namespace}
               />
+              <SortSelector
+                setSortType={(sortType) => this.setState({ sortType })}
+                sortType={this.state.sortType}
+              />
             </SortFilterWrapper>
           </ControlRow>
 
@@ -145,9 +145,11 @@ EnvGroupDashboard.contextType = Context;
 export default withRouter(withAuth(EnvGroupDashboard));
 
 const SortFilterWrapper = styled.div`
-  width: 468px;
   display: flex;
   justify-content: space-between;
+  > div:not(:first-child) {
+    margin-left: 30px;
+  }
 `;
 
 const ControlRow = styled.div`

+ 3 - 3
dashboard/src/main/home/dashboard/Dashboard.tsx

@@ -16,7 +16,7 @@ import TitleSection from "components/TitleSection";
 
 import { pushFiltered, pushQueryParams } from "shared/routing";
 import { withAuth, WithAuthProps } from "shared/auth/AuthorizationHoc";
-import { SharedStatus } from "../onboarding/steps/ProvisionResources/forms/SharedStatus";
+import { StatusPage } from "../onboarding/steps/ProvisionResources/forms/StatusPage";
 
 type PropsType = RouteComponentProps &
   WithAuthProps & {
@@ -107,10 +107,10 @@ class Dashboard extends Component<PropsType, StateType> {
   renderTabContents = () => {
     if (this.currentTab() === "provisioner") {
       return (
-        <SharedStatus
+        <StatusPage
           filter={[]}
           project_id={this.props.projectId}
-          setInfraStatus={(val: string) => null}
+          setInfraStatus={() => null}
         />
       );
     } else if (this.currentTab() === "create-cluster") {

+ 4 - 5
dashboard/src/main/home/modals/DeleteNamespaceModal.tsx

@@ -1,6 +1,5 @@
 import React, { useContext, useState } from "react";
 import styled from "styled-components";
-import close from "assets/close.png";
 
 import api from "shared/api";
 import { Context } from "shared/Context";
@@ -19,7 +18,7 @@ const DeleteNamespaceModal = () => {
   const [namespaceNameForDelition, setNamespaceNameForDelition] = useState("");
   const [status, setStatus] = useState<string>(null as string);
   const deleteNamespace = () => {
-    if (namespaceNameForDelition !== currentModalData.metadata.name) {
+    if (namespaceNameForDelition !== currentModalData?.metadata?.name) {
       setStatus("Please enter the name of this namespace to confirm deletion");
       return;
     }
@@ -27,7 +26,7 @@ const DeleteNamespaceModal = () => {
     api
       .deleteNamespace(
         "<token>",
-        { name: currentModalData.metadata.name },
+        { name: currentModalData?.metadata?.name },
         {
           id: currentProject.id,
           cluster_id: currentCluster.id,
@@ -50,7 +49,7 @@ const DeleteNamespaceModal = () => {
     <>
       <Subtitle>
         Please insert the name of the namespace to delete it:
-        <DangerText>{" " + currentModalData.metadata.name}</DangerText>
+        <DangerText>{" " + currentModalData?.metadata?.name}</DangerText>
       </Subtitle>
 
       <InputWrapper>
@@ -61,7 +60,7 @@ const DeleteNamespaceModal = () => {
           type="string"
           value={namespaceNameForDelition}
           setValue={(x: string) => setNamespaceNameForDelition(x)}
-          placeholder={currentModalData.metadata.name}
+          placeholder={currentModalData?.metadata?.name}
           width="480px"
         />
       </InputWrapper>

+ 58 - 0
dashboard/src/main/home/modals/SkipProvisioningModal.tsx

@@ -0,0 +1,58 @@
+import InputRow from "components/form-components/InputRow";
+import SaveButton from "components/SaveButton";
+import React, { useContext } from "react";
+import { Context } from "shared/Context";
+import styled from "styled-components";
+
+/**
+ * If user goes to /onboarding and has clusters, the Onboarding component
+ * will open this modal to let user skip onboarding and keep using porter.
+ */
+const SkipOnboardingModal = () => {
+  const { currentModalData, setCurrentModal } = useContext(Context);
+
+  return (
+    <>
+      <Subtitle>
+        Porter has detected an existing Kubernetes cluster that was connected
+        via the CLI. For custom setups, you can skip the project setup flow.
+      </Subtitle>
+      <Subtitle>Do you want to skip project setup?</Subtitle>
+      <ActionsWrapper>
+        <ActionButton
+          text="Yes, skip setup"
+          color="#616FEEcc"
+          onClick={() =>
+            typeof currentModalData?.skipOnboarding === "function" &&
+            currentModalData.skipOnboarding()
+          }
+          status={""}
+          clearPosition
+        />
+      </ActionsWrapper>
+    </>
+  );
+};
+
+export default SkipOnboardingModal;
+
+const ActionButton = styled(SaveButton)``;
+
+const ActionsWrapper = styled.div`
+  position: absolute;
+  bottom: 14px;
+  right: 14px;
+  display: flex;
+  ${ActionButton} {
+    margin-left: 5px;
+  }
+`;
+
+const Subtitle = styled.div`
+  margin-top: 23px;
+  font-family: "Work Sans", sans-serif;
+  font-size: 14px;
+  color: #aaaabb;
+  overflow: hidden;
+  margin-bottom: -10px;
+`;

+ 32 - 0
dashboard/src/main/home/onboarding/Onboarding.tsx

@@ -115,6 +115,38 @@ const Onboarding = () => {
     }
   }, [context.user]);
 
+  const skipOnboarding = () => {
+    OFState.actions.goTo("clean_up");
+  };
+
+  const checkIfUserHasClusters = async () => {
+    const { setCurrentModal, currentProject } = context;
+
+    const project_id = currentProject?.id;
+
+    try {
+      if (typeof project_id !== "number") {
+        return;
+      }
+
+      const clusters = await api
+        .getClusters("<token>", {}, { id: project_id })
+        .then((res) => res?.data);
+
+      const hasClusters = Array.isArray(clusters) && clusters.length;
+
+      if (hasClusters) {
+        setCurrentModal("SkipOnboardingModal", { skipOnboarding });
+      }
+    } catch (error) {
+      console.error(error);
+    }
+  };
+
+  useEffect(() => {
+    checkIfUserHasClusters();
+  }, [context?.currentProject?.id]);
+
   return (
     <StyledOnboarding>{isLoading ? <Loading /> : <Routes />}</StyledOnboarding>
   );

+ 19 - 7
dashboard/src/main/home/onboarding/components/ProviderSelector.tsx

@@ -1,4 +1,4 @@
-import React, { useMemo, useState } from "react";
+import React, { useMemo, useRef, useState } from "react";
 import { integrationList } from "shared/common";
 import styled from "styled-components";
 import { SupportedProviders } from "../types";
@@ -13,6 +13,7 @@ export type ProviderSelectorProps = {
     icon: string;
     label: string;
   }[];
+  defaultOption?: string;
 };
 
 export const registryOptions = [
@@ -68,22 +69,33 @@ export const provisionerOptionsWithExternal = [
 const ProviderSelector: React.FC<ProviderSelectorProps> = ({
   selectProvider,
   options,
+  defaultOption,
 }) => {
-  const [provider, setProvider] = useState(() => {
-    if (options.find((o) => o.value === "skip")) {
-      return "skip";
+  const [provider, setProvider] = useState(null);
+  const [isDirty, setIsDirty] = useState(false);
+
+  const activeProvider = useMemo(() => {
+    if (!isDirty || !provider) {
+      if (typeof defaultOption === "string") {
+        return defaultOption;
+      }
+      if (options.find((o) => o.value === "skip")) {
+        return "skip";
+      }
     }
-    return null;
-  });
+
+    return provider;
+  }, [provider, isDirty, defaultOption]);
 
   return (
     <>
       <Br />
       <Selector
-        activeValue={provider}
+        activeValue={activeProvider}
         options={options}
         placeholder="Select a cloud provider"
         setActiveValue={(provider) => {
+          setIsDirty(true);
           setProvider(provider);
           selectProvider(provider as SupportedProviders);
         }}

+ 15 - 0
dashboard/src/main/home/onboarding/state/StateHandler.ts

@@ -76,6 +76,21 @@ export const StateHandler = proxy({
         skip: true,
       };
     },
+    saveRegistryAndContinue: (data: any) => {
+      const serviceToProvider = {
+        ecr: "aws",
+        gcr: "gcp",
+        dcr: "do",
+      };
+      const connectedRegistry = {
+        skip: false,
+        provider: (serviceToProvider as any)[data?.service],
+        credentials: {
+          id: data?.id,
+        },
+      };
+      StateHandler.connected_registry = connectedRegistry;
+    },
     saveRegistryProvider: (provider: string) => {
       if (provider === StateHandler.connected_registry?.provider) {
         return;

+ 6 - 2
dashboard/src/main/home/onboarding/state/StepHandler.ts

@@ -16,15 +16,17 @@ type Step = {
       skip?: string;
       continue?: string;
       go_back?: string;
+      continue_with_current?: string;
     };
   };
 };
 
-export type Action = "skip" | "continue" | "go_back";
+export type Action = "skip" | "continue" | "go_back" | "continue_with_current";
 type ActionHandler = {
   skip?: string;
   continue: string;
   go_back?: string;
+  continue_with_current?: string;
 };
 
 export type FlowType = {
@@ -53,12 +55,14 @@ const flow: FlowType = {
       on: {
         skip: "provision_resources",
         continue: "connect_registry.credentials",
+        continue_with_current: "provision_resources",
         go_back: "connect_source",
       },
       execute: {
         on: {
           skip: "skipRegistryConnection",
           continue: "saveRegistryProvider",
+          continue_with_current: "saveRegistryAndContinue",
         },
       },
       substeps: {
@@ -112,7 +116,7 @@ const flow: FlowType = {
          * has a proper way of listing the registries and
          * manage them inside the step
          */
-        // go_back: "connect_registry",
+        go_back: "connect_registry",
       },
       execute: {
         on: {

+ 106 - 4
dashboard/src/main/home/onboarding/steps/ConnectRegistry/ConnectRegistry.tsx

@@ -1,7 +1,7 @@
 import Helper from "components/form-components/Helper";
 import SaveButton from "components/SaveButton";
 import TitleSection from "components/TitleSection";
-import React from "react";
+import React, { useEffect, useMemo, useState } from "react";
 import { useParams } from "react-router";
 
 import styled from "styled-components";
@@ -13,16 +13,66 @@ import backArrow from "assets/back_arrow.png";
 import FormFlowWrapper from "./forms/FormFlow";
 import { OFState } from "../../state";
 import { useSnapshot } from "valtio";
+import api from "shared/api";
+import Loading from "components/Loading";
+import { integrationList } from "shared/common";
+import Registry from "./components/Registry";
 
 const ConnectRegistry: React.FC<{}> = ({}) => {
   const snap = useSnapshot(OFState);
   const { step } = useParams<any>();
+  const [connectedRegistries, setConnectedRegistries] = useState(null);
+  const [isLoading, setIsLoading] = useState(true);
 
   const currentProvider = snap.StateHandler.connected_registry?.provider;
 
   const enableGoBack =
     snap.StepHandler.canGoBack && !snap.StepHandler.isSubFlow;
 
+  useEffect(() => {
+    let hookState = { isSubscribed: true };
+
+    getRegistries(hookState);
+
+    return () => {
+      hookState.isSubscribed = false;
+    };
+  }, [snap.StateHandler?.project]);
+
+  const getRegistries = async (
+    props: { isSubscribed: boolean } = { isSubscribed: true }
+  ) => {
+    const projectId = snap.StateHandler?.project?.id;
+
+    if (typeof projectId !== "number") {
+      return;
+    }
+
+    setIsLoading(true);
+    try {
+      const res = await api.getProjectRegistries(
+        "<token>",
+        {},
+        { id: projectId }
+      );
+      const registries = res?.data;
+      if (props.isSubscribed) {
+        if (Array.isArray(registries)) {
+          setConnectedRegistries(registries);
+        }
+      }
+    } catch (error) {
+      console.error(error);
+      if (props.isSubscribed) {
+        setConnectedRegistries(null);
+      }
+    } finally {
+      if (props.isSubscribed) {
+        setIsLoading(false);
+      }
+    }
+  };
+
   const handleGoBack = () => {
     OFState.actions.nextStep("go_back");
   };
@@ -35,6 +85,27 @@ const ConnectRegistry: React.FC<{}> = ({}) => {
     provider !== "skip" && OFState.actions.nextStep("continue", provider);
   };
 
+  const handleContinueWithCurrent = () => {
+    const connectedRegistry = connectedRegistries[0];
+    OFState.actions.nextStep("continue_with_current", connectedRegistry);
+  };
+
+  const selectorOptions = useMemo(() => {
+    const options = [...registryOptions];
+    if (Array.isArray(connectedRegistries) && connectedRegistries.length) {
+      const newOptions = options.filter((o) => o.value !== "skip");
+      return [
+        {
+          value: "use_current",
+          label: "Continue with current",
+          icon: "",
+        },
+        ...newOptions,
+      ];
+    }
+    return options;
+  }, [connectedRegistries]);
+
   return (
     <Div>
       {enableGoBack && (
@@ -62,22 +133,49 @@ const ConnectRegistry: React.FC<{}> = ({}) => {
           : "Link to an existing Docker registry or continue."}
       </Helper>
 
-      {step ? (
+      {!isLoading && step ? (
         <FormFlowWrapper currentStep={step} />
       ) : (
         <>
           <ProviderSelector
+            defaultOption={
+              Array.isArray(connectedRegistries) && connectedRegistries.length
+                ? "use_current"
+                : "skip"
+            }
             selectProvider={(provider) => {
               if (provider !== "external") {
                 handleSelectProvider(provider);
               }
             }}
-            options={registryOptions}
+            options={selectorOptions}
           />
+          {isLoading && <Loading />}
+
+          {!!connectedRegistries?.length && (
+            <IntegrationList>
+              {connectedRegistries.map((registry: any) => (
+                <Registry
+                  key={registry.name}
+                  registry={registry}
+                  onDelete={getRegistries}
+                />
+              ))}
+            </IntegrationList>
+          )}
           <NextStep
             text="Continue"
             disabled={false}
-            onClick={() => handleSkip()}
+            onClick={() => {
+              if (
+                Array.isArray(connectedRegistries) &&
+                connectedRegistries.length
+              ) {
+                handleContinueWithCurrent();
+              } else {
+                handleSkip();
+              }
+            }}
             status={""}
             makeFlush={true}
             clearPosition={true}
@@ -92,6 +190,10 @@ const ConnectRegistry: React.FC<{}> = ({}) => {
 
 export default ConnectRegistry;
 
+const IntegrationList = styled.div`
+  margin-top: 14px;
+`;
+
 const Div = styled.div`
   width: 100%;
 `;

+ 193 - 0
dashboard/src/main/home/onboarding/steps/ConnectRegistry/components/Registry.tsx

@@ -0,0 +1,193 @@
+import Loading from "components/Loading";
+import { OFState } from "main/home/onboarding/state";
+import React, { useContext, useState } from "react";
+import api from "shared/api";
+import { integrationList } from "shared/common";
+import { Context } from "shared/Context";
+import styled from "styled-components";
+import { useSnapshot } from "valtio";
+
+const serviceToProvider: {
+  [key: string]: string;
+} = {
+  docr: "do",
+  ecr: "aws",
+  gcr: "gcp",
+};
+
+const Registry: React.FC<{ registry: any; onDelete: () => void }> = (props) => {
+  const { registry, onDelete } = props;
+  const service = serviceToProvider[registry?.service];
+  const icon = integrationList[service || registry?.service]?.icon;
+  const subtitle = integrationList[registry?.service]?.label;
+  const snap = useSnapshot(OFState);
+  const { setCurrentError } = useContext(Context);
+
+  const [isDeleting, setIsDeleting] = useState(false);
+  const [hasError, setHasError] = useState(false);
+
+  const deleteRegistry = async (id: number) => {
+    const projectId = snap.StateHandler?.project?.id;
+
+    if (typeof projectId !== "number") {
+      return;
+    }
+    setIsDeleting(true);
+    try {
+      await api.deleteRegistryIntegration(
+        "<token>",
+        {},
+        {
+          project_id: projectId,
+          registry_id: id,
+        }
+      );
+      onDelete();
+      setIsDeleting(false);
+    } catch (error) {
+      setIsDeleting(false);
+      setCurrentError(error);
+      setHasError(true);
+      setTimeout(() => setHasError(false), 1000);
+    }
+  };
+
+  return (
+    <React.Fragment key={registry.name}>
+      <Integration>
+        <MainRow disabled={false}>
+          <Flex>
+            <Icon src={icon && icon} />
+            <Description>
+              <Label>{registry?.name}</Label>
+              <IntegrationSubtitle>{subtitle}</IntegrationSubtitle>
+            </Description>
+          </Flex>
+          <MaterialIconTray disabled={false}>
+            {isDeleting && (
+              <I disabled>
+                <Loading height={"28px"} width="28px" />
+              </I>
+            )}
+            {hasError && (
+              <ErrorI className="material-icons">priority_high</ErrorI>
+            )}
+            {!hasError && !isDeleting && (
+              <I
+                className="material-icons"
+                onClick={() => deleteRegistry(registry?.id)}
+              >
+                delete
+              </I>
+            )}
+          </MaterialIconTray>
+        </MainRow>
+      </Integration>
+    </React.Fragment>
+  );
+};
+
+export default Registry;
+
+const Flex = styled.div`
+  display: flex;
+  align-items: center;
+  justify-content: center;
+`;
+
+const Integration = styled.div`
+  margin-left: -2px;
+  display: flex;
+  flex-direction: column;
+  background: #26282f;
+  margin-bottom: 15px;
+  border-radius: 8px;
+  box-shadow: 0 4px 15px 0px #00000055;
+`;
+
+const IntegrationSubtitle = styled.div`
+  color: #aaaabb;
+  font-size: 13px;
+  display: flex;
+  align-items: center;
+  padding-top: 5px;
+`;
+
+const Icon = styled.img`
+  width: 30px;
+  margin-right: 18px;
+`;
+
+const I = styled.i`
+  color: #ffffff44;
+  :hover {
+    cursor: ${(props: { disabled?: boolean }) =>
+      props.disabled ? "not-allowed" : "pointer"};
+  }
+`;
+
+const ErrorI = styled(I)`
+  color: #ed5f85;
+`;
+
+const MainRow = styled.div`
+  height: 70px;
+  width: 100%;
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  padding: 25px;
+  border-radius: 5px;
+  :hover {
+    background: ${(props: { disabled: boolean }) =>
+      props.disabled ? "" : "#ffffff11"};
+    > i {
+      background: ${(props: { disabled: boolean }) =>
+        props.disabled ? "" : "#ffffff11"};
+    }
+  }
+
+  > i {
+    border-radius: 20px;
+    font-size: 18px;
+    padding: 5px;
+    color: #ffffff44;
+    margin-right: -7px;
+    :hover {
+      background: ${(props: { disabled: boolean }) =>
+        props.disabled ? "" : "#ffffff11"};
+    }
+  }
+`;
+
+const MaterialIconTray = styled.div`
+  max-width: 60px;
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  > i {
+    background: #26282f;
+    border-radius: 20px;
+    font-size: 18px;
+    padding: 5px;
+    margin: 0 5px;
+
+    :hover {
+      background: ${(props: { disabled: boolean }) =>
+        props.disabled ? "" : "#ffffff11"};
+    }
+  }
+`;
+
+const Description = styled.div`
+  display: flex;
+  flex-direction: column;
+  margin: 0;
+  padding: 0;
+`;
+
+const Label = styled.div`
+  color: #ffffff;
+  font-size: 14px;
+  font-weight: 500;
+`;

+ 1 - 1
dashboard/src/main/home/onboarding/steps/ConnectSource.tsx

@@ -96,7 +96,7 @@ const ConnectSource: React.FC<{
           </Helper>
         </>
       )}
-      {!isLoading && accountData?.accounts.length && (
+      {!isLoading && accountData?.accounts?.length && (
         <>
           <Helper>Porter currently has access to:</Helper>
           <List>

+ 6 - 3
dashboard/src/main/home/onboarding/steps/ProvisionResources/ProvisionResources.tsx

@@ -12,7 +12,7 @@ import ProviderSelector, {
 import FormFlowWrapper from "./forms/FormFlow";
 import ConnectExternalCluster from "./forms/_ConnectExternalCluster";
 import backArrow from "assets/back_arrow.png";
-import { SharedStatus } from "./forms/SharedStatus";
+import { StatusPage } from "./forms/StatusPage";
 import { useSnapshot } from "valtio";
 import { OFState } from "../../state";
 
@@ -74,7 +74,10 @@ const ProvisionResources: React.FC<Props> = () => {
           <Br height="15px" />
           <SaveButton
             text="Resolve Errors"
-            status="Encountered errors while provisioning."
+            status={
+              infraStatus?.description ||
+              "Encountered errors while provisioning."
+            }
             disabled={false}
             onClick={() => handleGoBack(infraStatus.description)}
             makeFlush={true}
@@ -108,7 +111,7 @@ const ProvisionResources: React.FC<Props> = () => {
       case "status":
         return (
           <>
-            <SharedStatus
+            <StatusPage
               project_id={project?.id}
               filter={getFilterOpts()}
               setInfraStatus={setInfraStatus}

+ 1 - 1
dashboard/src/main/home/onboarding/steps/ProvisionResources/forms/FormFlow.tsx

@@ -125,7 +125,7 @@ const FormFlowWrapper: React.FC<Props> = ({ currentStep }) => {
           {FormTitle[provider] && <img src={FormTitle[provider].icon} />}
           {FormTitle[provider] && FormTitle[provider].label}
         </FormHeader>
-        <GuideButton href={FormTitle[provider].doc} target="_blank">
+        <GuideButton href={FormTitle[provider]?.doc} target="_blank">
           <i className="material-icons-outlined">help</i>
           Guide
         </GuideButton>

+ 0 - 365
dashboard/src/main/home/onboarding/steps/ProvisionResources/forms/SharedStatus.tsx

@@ -1,365 +0,0 @@
-import ProvisionerStatus, {
-  TFModule,
-  TFResource,
-  TFResourceError,
-} from "components/ProvisionerStatus";
-import React, { useEffect, useState } from "react";
-import api from "shared/api";
-import { useWebsockets } from "shared/hooks/useWebsockets";
-
-export const SharedStatus: React.FC<{
-  setInfraStatus: (status: { hasError: boolean; description?: string }) => void;
-  project_id: number;
-  filter: string[];
-}> = ({ setInfraStatus, project_id, filter }) => {
-  const {
-    newWebsocket,
-    openWebsocket,
-    closeWebsocket,
-    closeAllWebsockets,
-  } = useWebsockets();
-
-  const [tfModules, setTFModules] = useState<TFModule[]>([]);
-  const [isLoadingState, setIsLoadingState] = useState(true);
-
-  const updateTFModules = (
-    index: number,
-    addedResources: TFResource[],
-    erroredResources: TFResource[],
-    globalErrors: TFResourceError[],
-    gotDesired?: boolean
-  ) => {
-    if (!tfModules[index]?.resources) {
-      tfModules[index].resources = [];
-    }
-
-    if (!tfModules[index]?.global_errors) {
-      tfModules[index].global_errors = [];
-    }
-
-    if (gotDesired) {
-      tfModules[index].got_desired = true;
-    }
-
-    let resources = tfModules[index].resources;
-
-    // construct map of tf resources addresses to indices
-    let resourceAddrMap = new Map<string, number>();
-
-    tfModules[index].resources.forEach((resource, index) => {
-      resourceAddrMap.set(resource.addr, index);
-    });
-
-    for (let addedResource of addedResources) {
-      // if exists, update state to provisioned
-      if (resourceAddrMap.has(addedResource.addr)) {
-        let currResource = resources[resourceAddrMap.get(addedResource.addr)];
-        addedResource.errored = currResource.errored;
-        resources[resourceAddrMap.get(addedResource.addr)] = addedResource;
-      } else {
-        resources.push(addedResource);
-        resourceAddrMap.set(addedResource.addr, resources.length - 1);
-
-        // if the resource is being added but there's not a desired state, re-query for the
-        // desired state
-        if (!tfModules[index].got_desired) {
-          updateDesiredState(index, tfModules[index]);
-        }
-      }
-    }
-
-    for (let erroredResource of erroredResources) {
-      // if exists, update state to provisioned
-      if (resourceAddrMap.has(erroredResource.addr)) {
-        resources[resourceAddrMap.get(erroredResource.addr)] = erroredResource;
-      } else {
-        resources.push(erroredResource);
-        resourceAddrMap.set(erroredResource.addr, resources.length - 1);
-      }
-    }
-
-    tfModules[index].global_errors = [
-      ...tfModules[index].global_errors,
-      ...globalErrors,
-    ];
-
-    setTFModules([...tfModules]);
-  };
-
-  useEffect(() => {
-    if (isLoadingState) {
-      return;
-    }
-    // recompute tf module state each time, to see if infra is ready
-    if (tfModules.length > 0) {
-      // see if all tf modules are in a "created" state
-      if (
-        tfModules.filter((val) => val.status == "created").length ==
-        tfModules.length
-      ) {
-        setInfraStatus({
-          hasError: false,
-        });
-        return;
-      }
-
-      if (
-        tfModules.filter((val) => val.status == "error").length ==
-        tfModules.length
-      ) {
-        setInfraStatus({
-          hasError: true,
-          description: "Encountered error while provisioning",
-        });
-        return;
-      }
-
-      // otherwise, check that all resources in each module are provisioned. Each module
-      // must have more than one resource
-      let numModulesSuccessful = 0;
-      let numModulesErrored = 0;
-
-      for (let tfModule of tfModules) {
-        if (tfModule.status == "created") {
-          numModulesSuccessful++;
-        } else if (tfModule.status == "error") {
-          numModulesErrored++;
-        } else {
-          let resLength = tfModule.resources?.length;
-          if (resLength > 0) {
-            numModulesSuccessful +=
-              tfModule.resources.filter((resource) => resource.provisioned)
-                .length == resLength
-                ? 1
-                : 0;
-
-            // if there's a global error, or the number of resources that errored_out is
-            // greater than 0, this resource is in an error state
-            numModulesErrored +=
-              tfModule.global_errors?.length > 0 ||
-              tfModule.resources.filter(
-                (resource) => resource.errored?.errored_out
-              ).length > 0
-                ? 1
-                : 0;
-          } else if (tfModule.global_errors?.length > 0) {
-            numModulesErrored += 1;
-          }
-        }
-      }
-
-      if (numModulesSuccessful == tfModules.length) {
-        setInfraStatus({
-          hasError: false,
-        });
-      } else if (numModulesErrored + numModulesSuccessful == tfModules.length) {
-        // otherwise, if all modules are either in an error state or successful,
-        // set the status to error
-        setInfraStatus({
-          hasError: true,
-        });
-      }
-    } else {
-      setInfraStatus(null);
-    }
-  }, [tfModules, isLoadingState]);
-
-  const setupInfraWebsocket = (
-    websocketID: string,
-    module: TFModule,
-    index: number
-  ) => {
-    let apiPath = `/api/projects/${project_id}/infras/${module.id}/logs`;
-
-    const wsConfig = {
-      onopen: () => {
-        console.log(`connected to websocket: ${websocketID}`);
-      },
-      onmessage: (evt: MessageEvent) => {
-        // parse the data
-        let parsedData = JSON.parse(evt.data);
-
-        let addedResources: TFResource[] = [];
-        let erroredResources: TFResource[] = [];
-        let globalErrors: TFResourceError[] = [];
-
-        for (let streamVal of parsedData) {
-          let streamValData = JSON.parse(streamVal?.Values?.data);
-
-          switch (streamValData?.type) {
-            case "apply_complete":
-              addedResources.push({
-                addr: streamValData?.hook?.resource?.addr,
-                provisioned: true,
-                errored: {
-                  errored_out: false,
-                },
-              });
-
-              break;
-            case "diagnostic":
-              if (streamValData["@level"] == "error") {
-                if (streamValData?.hook?.resource?.addr != "") {
-                  erroredResources.push({
-                    addr: streamValData?.hook?.resource?.addr,
-                    provisioned: false,
-                    errored: {
-                      errored_out: true,
-                      error_context: streamValData["@message"],
-                    },
-                  });
-                } else {
-                  globalErrors.push({
-                    errored_out: true,
-                    error_context: streamValData["@message"],
-                  });
-                }
-              }
-            case "change_summary":
-              if (streamValData.changes.add != 0) {
-                updateDesiredState(index, module);
-              }
-            default:
-          }
-        }
-
-        updateTFModules(index, addedResources, erroredResources, globalErrors);
-      },
-
-      onclose: () => {
-        console.log(`closing websocket: ${websocketID}`);
-      },
-
-      onerror: (err: ErrorEvent) => {
-        console.log(err);
-        closeWebsocket(websocketID);
-      },
-    };
-
-    newWebsocket(websocketID, apiPath, wsConfig);
-    openWebsocket(websocketID);
-  };
-
-  const mergeCurrentAndDesired = (
-    index: number,
-    desired: any,
-    currentMap: Map<string, string>
-  ) => {
-    // map desired state to list of resources
-    var addedResources: TFResource[] = desired?.map((val: any) => {
-      return {
-        addr: val?.addr,
-        provisioned: currentMap.has(val?.addr),
-        errored: {
-          errored_out: val?.errored?.errored_out,
-          error_context: val?.errored?.error_context,
-        },
-      };
-    });
-
-    updateTFModules(index, addedResources, [], [], true);
-  };
-
-  const updateDesiredState = (index: number, val: TFModule) => {
-    setIsLoadingState(true);
-    api
-      .getInfraDesired(
-        "<token>",
-        {},
-        { project_id: project_id, infra_id: val?.id }
-      )
-      .then((resDesired) => {
-        api
-          .getInfraCurrent(
-            "<token>",
-            {},
-            { project_id: project_id, infra_id: val?.id }
-          )
-          .then((resCurrent) => {
-            var desired = resDesired.data;
-            var current = resCurrent.data;
-
-            // convert current state to a lookup table
-            var currentMap: Map<string, string> = new Map();
-
-            current?.resources?.forEach((val: any) => {
-              currentMap.set(val?.type + "." + val?.name, "");
-            });
-
-            mergeCurrentAndDesired(index, desired, currentMap);
-          })
-          .catch((err) => {
-            var desired = resDesired.data;
-            var currentMap: Map<string, string> = new Map();
-
-            // merge with empty current map
-            mergeCurrentAndDesired(index, desired, currentMap);
-          })
-          .finally(() => {
-            setIsLoadingState(true);
-          });
-      })
-      .catch((err) => {
-        console.log(err);
-        setIsLoadingState(true);
-      });
-  };
-
-  useEffect(() => {
-    api.getInfra("<token>", {}, { project_id: project_id }).then((res) => {
-      var matchedInfras: Map<string, any> = new Map();
-
-      res.data.forEach((infra: any) => {
-        // if filter list is empty, add infra automatically
-        if (filter.length == 0) {
-          matchedInfras.set(infra.kind + "-" + infra.id, infra);
-        } else if (
-          filter.includes(infra.kind) &&
-          (matchedInfras.get(infra.Kind)?.id || 0 < infra.id)
-        ) {
-          matchedInfras.set(infra.kind, infra);
-        }
-      });
-
-      // query for desired and current state, and convert to tf module
-      matchedInfras.forEach((infra: any) => {
-        var module: TFModule = {
-          id: infra.id,
-          kind: infra.kind,
-          status: infra.status,
-          got_desired: false,
-          created_at: infra.created_at,
-        };
-
-        tfModules.push(module);
-      });
-
-      if (tfModules.every((m) => m.status === "created")) {
-        setInfraStatus({
-          hasError: false,
-        });
-      }
-
-      setTFModules([...tfModules]);
-
-      tfModules.forEach((val, index) => {
-        if (val?.status != "created") {
-          updateDesiredState(index, val);
-          setupInfraWebsocket(val.id + "", val, index);
-        }
-      });
-    });
-
-    return closeAllWebsockets;
-  }, []);
-
-  let sortedModules = tfModules.sort((a, b) =>
-    b.id < a.id ? -1 : b.id > a.id ? 1 : 0
-  );
-
-  return (
-    <>
-      <ProvisionerStatus modules={sortedModules} />
-    </>
-  );
-};

+ 641 - 0
dashboard/src/main/home/onboarding/steps/ProvisionResources/forms/StatusPage.tsx

@@ -0,0 +1,641 @@
+import ProvisionerStatus, {
+  TFModule,
+  TFResource,
+  TFResourceError,
+} from "components/ProvisionerStatus";
+import React, { useEffect, useMemo, useRef, useState } from "react";
+import api from "shared/api";
+import { NewWebsocketOptions, useWebsockets } from "shared/hooks/useWebsockets";
+
+type Props = {
+  setInfraStatus: (status: { hasError: boolean; description?: string }) => void;
+  project_id: number;
+  filter: string[];
+};
+
+type Infra = {
+  id: number;
+  created_at: string;
+  updated_at: string;
+  project_id: number;
+  kind: string;
+  status: string;
+  last_applied: any;
+};
+
+type Desired = {
+  addr: string;
+  errored:
+    | { errored_out: false }
+    | { errored_out: true; error_context: string };
+  implied_provider: string;
+  resource: string;
+  resource_name: string;
+  resource_type: string;
+};
+
+type InfraCurrentResponse = {
+  version: number;
+  terraform_version: string;
+  serial: number;
+  lineage: string;
+  outputs: any;
+  resources: {
+    instances: any[];
+    mode: string;
+    name: string;
+    provider: string;
+    type: string;
+  }[];
+};
+
+export const StatusPage = ({
+  filter: selectedFilters,
+  project_id,
+  setInfraStatus,
+}: Props) => {
+  const {
+    newWebsocket,
+    openWebsocket,
+    closeWebsocket,
+    closeAllWebsockets,
+  } = useWebsockets();
+
+  const {
+    tfModules,
+    initModule,
+    updateDesired,
+    updateModuleResources,
+    updateGlobalErrorsForModule,
+  } = useTFModules();
+
+  const { moduleStatuses } = useModuleChecker(tfModules);
+
+  const filterBySelectedInfras = (currentInfra: Infra) => {
+    if (!Array.isArray(selectedFilters) || !selectedFilters?.length) {
+      return true;
+    }
+
+    if (selectedFilters.includes(currentInfra.kind)) {
+      return true;
+    }
+    return false;
+  };
+
+  const getLatestInfras = (infras: Infra[]) => {
+    // Create a map with the relation infra.kind => infra
+    // This will allow us to keep only one infra per kind.
+    const infraMap = new Map<string, Infra>();
+
+    infras.forEach((infra) => {
+      // Get last infra from that kind, kind being gke, ecr, etc.
+      const latestSavedInfra = infraMap.get(infra.kind);
+
+      // If infra doesn't exists, it means its the first one appearing so we save it
+      if (!latestSavedInfra) {
+        infraMap.set(infra.kind, infra);
+        return;
+      }
+
+      // Check if the latest saved infra was recent than the one we're currently iterating
+      // If the current one iterating is newer, then we update the map!
+      if (
+        new Date(infra.created_at).getTime() >
+        new Date(latestSavedInfra.created_at).getTime()
+      ) {
+        infraMap.set(infra.kind, infra);
+        return;
+      }
+    });
+
+    // Get the array from the values of the array.
+    return Array.from(infraMap.values());
+  };
+
+  const getInfras = async () => {
+    try {
+      const res = await api.getInfra<Infra[]>(
+        "<token>",
+        {},
+        { project_id: project_id }
+      );
+      // Filter infras based on what we care only, usually on the onboarding we'll want only the ones
+      // currently being provisioned
+      const matchedInfras = res.data.filter(filterBySelectedInfras);
+
+      // Get latest infras for each kind of infra on the array.
+      const latestMatchedInfras = getLatestInfras(matchedInfras);
+
+      // Check if all infras are created then enable continue button
+      if (latestMatchedInfras.every((infra) => infra.status === "created")) {
+        setInfraStatus({
+          hasError: false,
+        });
+      }
+
+      // Init tf modules based on matched infras
+      latestMatchedInfras.forEach((infra) => {
+        // Init the module for the hook
+        initModule(infra);
+
+        // Update all the resources needed for the current infra
+        getDesiredState(infra.id);
+      });
+    } catch (error) {}
+  };
+
+  const getDesiredState = async (infra_id: number) => {
+    try {
+      const desired = await api
+        .getInfraDesired("<token>", {}, { project_id, infra_id })
+        .then((res) => res?.data);
+
+      updateDesired(infra_id, desired);
+      // Check if we have some modules already provisioned
+      await getProvisionedModules(infra_id);
+
+      // Connect to websocket that will provide live info of the provisioning for this infra
+      connectToLiveUpdateModule(infra_id);
+    } catch (error) {
+      console.error(error);
+      setTimeout(() => {
+        getDesiredState(infra_id);
+      }, 500);
+    }
+  };
+
+  const getProvisionedModules = async (infra_id: number) => {
+    try {
+      const current = await api
+        .getInfraCurrent<InfraCurrentResponse>(
+          "<token>",
+          {},
+          { project_id, infra_id }
+        )
+        .then((res) => res?.data);
+
+      const provisionedResources: TFResource[] = current?.resources?.map(
+        (resource: any) => {
+          return {
+            addr: `${resource?.type}.${resource?.name}`,
+            provisioned: true,
+            errored: {
+              errored_out: false,
+            },
+          } as TFResource;
+        }
+      );
+
+      updateModuleResources(infra_id, provisionedResources);
+    } catch (error) {
+      console.error(error);
+    }
+  };
+
+  const connectToLiveUpdateModule = (infra_id: number) => {
+    const websocketId = `${infra_id}`;
+    const apiPath = `/api/projects/${project_id}/infras/${infra_id}/logs`;
+
+    const wsConfig: NewWebsocketOptions = {
+      onopen: () => {
+        console.log(`connected to websocket for infra_id: ${websocketId}`);
+      },
+      onmessage: (evt: MessageEvent) => {
+        // parse the data
+        const parsedData = JSON.parse(evt.data);
+
+        const addedResources: TFResource[] = [];
+        const erroredResources: TFResource[] = [];
+        const globalErrors: TFResourceError[] = [];
+
+        for (const streamVal of parsedData) {
+          const streamValData = JSON.parse(streamVal?.Values?.data);
+
+          switch (streamValData?.type) {
+            case "apply_complete":
+              addedResources.push({
+                addr: streamValData?.hook?.resource?.addr,
+                provisioned: true,
+                errored: {
+                  errored_out: false,
+                },
+              });
+
+              break;
+            case "diagnostic":
+              if (streamValData["@level"] == "error") {
+                if (streamValData?.hook?.resource?.addr !== "") {
+                  erroredResources.push({
+                    addr: streamValData?.hook?.resource?.addr,
+                    provisioned: false,
+                    errored: {
+                      errored_out: true,
+                      error_context: streamValData["@message"],
+                    },
+                  });
+                } else {
+                  globalErrors.push({
+                    errored_out: true,
+                    error_context: streamValData["@message"],
+                  });
+                }
+              }
+            default:
+          }
+        }
+
+        updateModuleResources(infra_id, [
+          ...addedResources,
+          ...erroredResources,
+        ]);
+
+        updateGlobalErrorsForModule(infra_id, globalErrors);
+      },
+
+      onclose: () => {
+        console.log(`closing websocket for infra_id: ${websocketId}`);
+      },
+
+      onerror: (err: ErrorEvent) => {
+        console.log(err);
+        closeWebsocket(`${websocketId}`);
+      },
+    };
+
+    newWebsocket(websocketId, apiPath, wsConfig);
+    openWebsocket(websocketId);
+  };
+
+  useEffect(() => {
+    getInfras();
+    return () => {
+      closeAllWebsockets();
+    };
+  }, []);
+
+  useEffect(() => {
+    if (!tfModules?.length) {
+      setInfraStatus(null);
+      return;
+    }
+    const hasModuleWithError = tfModules.find(
+      (module) => module.status === "error"
+    );
+
+    const hasModuleInCreatingState = tfModules.find(
+      (module) => module.status === "creating"
+    );
+
+    const hasModuleWithTimerElapsed = moduleStatuses.find(
+      (module) => module.status === "timed_out"
+    );
+
+    if (hasModuleWithTimerElapsed) {
+      setInfraStatus({
+        hasError: true,
+        description:
+          "We weren't able to provision after 45 minutes, please try again.",
+      });
+      return;
+    }
+
+    if (hasModuleInCreatingState) {
+      setInfraStatus(null);
+      return;
+    }
+
+    if (!hasModuleInCreatingState && !hasModuleWithError) {
+      setInfraStatus({ hasError: false });
+      return;
+    }
+
+    if (!hasModuleInCreatingState && hasModuleWithError) {
+      setInfraStatus({ hasError: true });
+      return;
+    }
+  }, [tfModules, moduleStatuses]);
+
+  const sortedModules = tfModules.sort((a, b) =>
+    b.id < a.id ? -1 : b.id > a.id ? 1 : 0
+  );
+
+  return <ProvisionerStatus modules={sortedModules} />;
+};
+
+type TFModulesState = {
+  [infraId: number]: TFModule;
+};
+
+const useTFModules = () => {
+  // Use a ref to keep track of all the Terraform modules
+  const modules = useRef<TFModulesState>({});
+
+  // Use state to keep the reactive array of terraform modules
+  const [tfModules, setTfModules] = useState<TFModule[]>([]);
+
+  /**
+   * This will map out the ref containing all the terraform modules and return a sorted array.
+   */
+  const updateTFModules = (): void => {
+    if (typeof modules.current !== "object") {
+      setTfModules([]);
+    }
+
+    const sortedModules = Object.values(modules.current).sort((a, b) =>
+      b.id < a.id ? -1 : b.id > a.id ? 1 : 0
+    );
+    setTfModules(sortedModules);
+  };
+
+  /**
+   * Init a TFModule based on a Infra, this infra is usually more basic
+   * and doesn't contain all the resources that it actually needs.
+   * The initialized TFModule will be used to keep track if the infra
+   * changed from creating status to another one.
+   *
+   * @param infra Infra object used to initialize the terraform module used to track provisioning status
+   */
+  const initModule = (infra: Infra) => {
+    const module: TFModule = {
+      id: infra.id,
+      kind: infra.kind,
+      status: infra.status,
+      got_desired: false,
+      created_at: infra.created_at,
+      updated_at: infra.updated_at,
+    };
+    setModule(infra.id, module);
+  };
+
+  /**
+   * Add or replace if existed, this function will set the module into the ref
+   * and call the updateTFModules to update the array used to show the infras
+   *
+   * @param infraId Infra ID to be updated
+   * @param module New updated module
+   */
+  const setModule = (infraId: number, module: TFModule) => {
+    modules.current = {
+      ...modules.current,
+      [infraId]: module,
+    };
+    updateTFModules();
+  };
+
+  const getModule = (infraId: number) => {
+    return { ...modules.current[infraId] };
+  };
+
+  /**
+   * @param infraId Module to be updated
+   * @param desired All the desired resources that are going to be needed to complete provisioning
+   */
+  const updateDesired = (infraId: number, desired: Desired[]) => {
+    const selectedModule = getModule(infraId);
+
+    if (!Array.isArray(selectedModule?.resources)) {
+      selectedModule.resources = [];
+    }
+
+    selectedModule.resources = desired.map((d) => {
+      return {
+        addr: d.addr,
+        errored: d.errored,
+        provisioned: false,
+      };
+    });
+
+    setModule(infraId, selectedModule);
+  };
+
+  /**
+   * @param infraId Module to be updated
+   * @param updatedResources Updated resources array, this may contain one or more objects with some status updates.
+   */
+  const updateModuleResources = (
+    infraId: number,
+    updatedResources: TFResource[]
+  ) => {
+    const selectedModule = getModule(infraId);
+
+    const updatedModuleResources = selectedModule.resources.map((resource) => {
+      const correspondedResource: TFResource = updatedResources.find(
+        (updatedResource) => updatedResource.addr === resource.addr
+      );
+      if (!correspondedResource) {
+        return resource;
+      }
+      let errored = undefined;
+
+      if (correspondedResource?.errored) {
+        errored = {
+          ...(correspondedResource?.errored || {}),
+        };
+      }
+
+      return {
+        ...resource,
+        provisioned: correspondedResource.provisioned,
+        errored,
+      };
+    });
+
+    selectedModule.resources = updatedModuleResources;
+
+    const isModuleCreated =
+      selectedModule.resources.every((resource) => {
+        return resource.provisioned;
+      }) && !selectedModule.global_errors?.length;
+
+    const isModuleOnError =
+      selectedModule.resources.find((resource) => {
+        return resource.errored?.errored_out;
+      }) || selectedModule.global_errors?.length;
+
+    if (isModuleCreated) {
+      selectedModule.status = "created";
+    } else if (isModuleOnError) {
+      selectedModule.status = "error";
+    } else {
+      selectedModule.status = selectedModule.status;
+    }
+
+    setModule(infraId, selectedModule);
+  };
+
+  /**
+   * @param infraId Module to be updated
+   * @param globalErrors Errors that may not belong to a resource but appeared during provisioning
+   */
+  const updateGlobalErrorsForModule = (
+    infraId: number,
+    globalErrors: TFResourceError[]
+  ) => {
+    const module = getModule(infraId);
+
+    module.global_errors = [...(module.global_errors || []), ...globalErrors];
+    if (globalErrors.length) {
+      module.status = "error";
+    }
+    setModule(infraId, module);
+  };
+
+  return {
+    tfModules,
+    initModule,
+    updateDesired,
+    updateModuleResources,
+    updateGlobalErrorsForModule,
+  };
+};
+
+const useModuleChecker = (modules: TFModule[]) => {
+  const [timers, setTimers] = useState<{
+    [timerModuleId: number]: NodeJS.Timeout;
+  }>({});
+
+  const [moduleStatuses, setModuleStatus] = useState<{
+    [timerModuleId: number]: "timed_out" | "creating" | "success";
+  }>({});
+
+  const didModuleTimedOut = (infra: TFModule) => {
+    const last_updated = new Date(infra.updated_at).getTime();
+    const current_date = new Date().getTime();
+
+    let diff = (current_date - last_updated) / 1000 / 60;
+    const minutes_elapsed = Math.abs(Math.round(diff));
+
+    if (minutes_elapsed >= 45) {
+      return true;
+    }
+
+    return false;
+  };
+
+  const hasModuleAnyResourcesProvisionedOrErrored = (module: TFModule) => {
+    if (!Array.isArray(module.resources)) {
+      return false;
+    }
+
+    if (
+      module.resources.every(
+        (resource) => resource.provisioned || resource.errored?.errored_out
+      ) ||
+      module.global_errors.find((resourceError) => resourceError.errored_out)
+    ) {
+      return true;
+    }
+
+    return false;
+  };
+
+  const hasModuleBeenSuccessfullyProvisioned = (module: TFModule) => {
+    if (!Array.isArray(module.resources)) {
+      return false;
+    }
+
+    if (module.resources.every((resource) => resource.provisioned)) {
+      return true;
+    }
+
+    return false;
+  };
+
+  const setupTimeoutToCheckModuleTimeout = (module: TFModule) => {
+    const timer = setTimeout(() => {
+      if (!didModuleTimedOut(module)) {
+        return;
+      }
+
+      if (hasModuleBeenSuccessfullyProvisioned(module)) {
+        setModuleStatus((modulesStatus) => ({
+          ...modulesStatus,
+          [module.id]: "success",
+        }));
+        clearCheckerTimeout(module.id);
+        return;
+      }
+
+      if (!hasModuleAnyResourcesProvisionedOrErrored(module)) {
+        setModuleStatus((modulesStatus) => ({
+          ...modulesStatus,
+          [module.id]: "timed_out",
+        }));
+      } else {
+        setModuleStatus((modulesStatus) => ({
+          ...modulesStatus,
+          [module.id]: "creating",
+        }));
+      }
+      clearCheckerTimeout(module.id);
+    }, 1000);
+    return timer;
+  };
+
+  const clearCheckerTimeout = (moduleId: number) => {
+    const moduleInterval = timers[moduleId];
+    clearTimeout(moduleInterval);
+    setTimers((timers) => ({
+      ...timers,
+      [moduleId]: undefined,
+    }));
+  };
+
+  const clearCheckerTimers = () => {
+    if (typeof timers !== "object") {
+      return;
+    }
+
+    Object.entries(timers).forEach(([moduleId, intervalId]) => {
+      clearTimeout(intervalId);
+      setTimers((timers) => ({
+        ...timers,
+        [moduleId]: undefined,
+      }));
+    });
+  };
+
+  useEffect(() => {
+    modules.forEach((module) => {
+      if (timers[module.id]) {
+        clearTimeout(timers[module.id]);
+      }
+
+      if (
+        moduleStatuses[module.id] &&
+        moduleStatuses[module.id] !== "creating"
+      ) {
+        clearCheckerTimeout(module.id);
+        return;
+      }
+
+      const timerId = setupTimeoutToCheckModuleTimeout(module);
+
+      setTimers((timers) => ({
+        ...timers,
+        [module.id]: timerId,
+      }));
+    });
+
+    return () => {
+      clearCheckerTimers();
+    };
+  }, [modules, moduleStatuses]);
+
+  const moduleStatusesArray = useMemo(() => {
+    if (typeof moduleStatuses !== "object") {
+      return [];
+    }
+
+    return Object.entries(moduleStatuses).map(([moduleId, status]) => {
+      return {
+        id: moduleId,
+        status,
+      };
+    });
+  }, [moduleStatuses]);
+
+  return {
+    moduleStatuses: moduleStatusesArray,
+  };
+};

+ 0 - 1
dashboard/src/main/home/onboarding/steps/ProvisionResources/forms/_AWSProvisionerForm.tsx

@@ -10,7 +10,6 @@ import {
 import React, { useEffect, useState } from "react";
 import api from "shared/api";
 import { useSnapshot } from "valtio";
-import { SharedStatus } from "./SharedStatus";
 import Loading from "components/Loading";
 import Helper from "components/form-components/Helper";
 

+ 0 - 6
dashboard/src/main/home/onboarding/steps/ProvisionResources/forms/_DOProvisionerForm.tsx

@@ -1,10 +1,6 @@
 import Helper from "components/form-components/Helper";
 import InputRow from "components/form-components/InputRow";
 import SelectRow from "components/form-components/SelectRow";
-import ProvisionerStatus, {
-  TFModule,
-  TFResource,
-} from "components/ProvisionerStatus";
 import SaveButton from "components/SaveButton";
 import { OFState } from "main/home/onboarding/state";
 import { DOProvisionerConfig } from "main/home/onboarding/types";
@@ -12,8 +8,6 @@ import React, { useEffect, useState } from "react";
 import api from "shared/api";
 import styled from "styled-components";
 import { useSnapshot } from "valtio";
-import { useWebsockets } from "shared/hooks/useWebsockets";
-import { SharedStatus } from "./SharedStatus";
 import Loading from "components/Loading";
 
 const tierOptions = [

+ 0 - 1
dashboard/src/main/home/onboarding/steps/ProvisionResources/forms/_GCPProvisionerForm.tsx

@@ -13,7 +13,6 @@ import React, { useEffect, useState } from "react";
 import api from "shared/api";
 import styled from "styled-components";
 import { useSnapshot } from "valtio";
-import { SharedStatus } from "./SharedStatus";
 
 const regionOptions = [
   { value: "asia-east1", label: "asia-east1" },

+ 12 - 3
internal/templater/dynamic/reader.go

@@ -118,7 +118,10 @@ func (r *TemplateReader) ReadStream(
 
 			u := obj.(*unstructured.Unstructured)
 
-			data, err := utils.QueryValues(u.Object, r.Queries)
+			queryObj := make(map[string]interface{})
+			queryObj["items"] = []interface{}{u.Object}
+
+			data, err := utils.QueryValues(queryObj, r.Queries)
 
 			if err != nil {
 				return
@@ -133,7 +136,10 @@ func (r *TemplateReader) ReadStream(
 
 			u := newObj.(*unstructured.Unstructured)
 
-			data, err := utils.QueryValues(u.Object, r.Queries)
+			queryObj := make(map[string]interface{})
+			queryObj["items"] = []interface{}{u.Object}
+
+			data, err := utils.QueryValues(queryObj, r.Queries)
 
 			if err != nil {
 				return
@@ -148,7 +154,10 @@ func (r *TemplateReader) ReadStream(
 
 			u := obj.(*unstructured.Unstructured)
 
-			data, err := utils.QueryValues(u.Object, r.Queries)
+			queryObj := make(map[string]interface{})
+			queryObj["items"] = []interface{}{u.Object}
+
+			data, err := utils.QueryValues(queryObj, r.Queries)
 
 			if err != nil {
 				return

+ 6 - 2
internal/templater/dynamic/writer.go

@@ -5,7 +5,6 @@ import (
 
 	"github.com/porter-dev/porter/internal/templater/utils"
 
-	"github.com/porter-dev/porter/internal/templater"
 	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
 	"k8s.io/apimachinery/pkg/runtime/schema"
 
@@ -37,7 +36,7 @@ func NewDynamicTemplateWriter(
 	client dynamic.Interface,
 	obj *Object,
 	base map[string]interface{},
-) templater.TemplateWriter {
+) *TemplateWriter {
 	w := &TemplateWriter{
 		Object: obj,
 		Client: client,
@@ -102,3 +101,8 @@ func (w *TemplateWriter) Update(vals map[string]interface{}) (map[string]interfa
 
 	return update.Object, nil
 }
+
+// Delete deletes a dynamic resource, this must be registered with the API server
+func (w *TemplateWriter) Delete() error {
+	return w.resource.Delete(context.TODO(), w.Object.Name, metav1.DeleteOptions{})
+}

+ 53 - 0
internal/templater/parser/parser.go

@@ -96,6 +96,59 @@ func FormYAMLFromBytes(def *ClientConfigDefault, bytes []byte, stateType string)
 	return form, nil
 }
 
+func FormStreamer(
+	def *ClientConfigDefault,
+	bytes []byte,
+	stateType string,
+	targetContext *types.FormContext,
+	on templater.OnDataStream,
+	stopCh <-chan struct{},
+) error {
+	form, err := unqueriedFormYAMLFromBytes(bytes)
+
+	if err != nil {
+		return err
+	}
+
+	lookup := formToLookupTable(def, form, stateType)
+
+	for lookupContext, lookupVal := range lookup {
+		if lookupVal != nil && areContextsEqual(targetContext, lookupContext) {
+			err := lookupVal.TemplateReader.ReadStream(on, stopCh)
+
+			if err != nil {
+				continue
+			}
+		}
+	}
+
+	return nil
+}
+
+func areContextsEqual(context1, context2 *types.FormContext) bool {
+	if context1.Type != context2.Type {
+		return false
+	}
+
+	subset12 := isSubset(context1.Config, context2.Config)
+	subset21 := isSubset(context2.Config, context1.Config)
+
+	return subset12 && subset21
+}
+
+func isSubset(map1, map2 map[string]string) bool {
+	subset12 := true
+
+	for key1, val1 := range map1 {
+		if val2, exists := map2[key1]; !exists || val2 != val1 {
+			subset12 = false
+			break
+		}
+	}
+
+	return subset12
+}
+
 // unqueriedFormYAMLFromBytes returns a FormYAML without values queries populated
 func unqueriedFormYAMLFromBytes(bytes []byte) (*types.FormYAML, error) {
 	// parse bytes into object