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

list namespaces route implementation

Alexander Belanger пре 5 година
родитељ
комит
76d3e5f880
3 измењених фајлова са 80 додато и 0 уклоњено
  1. 26 0
      internal/forms/k8s.go
  2. 51 0
      server/api/k8s_handler.go
  3. 3 0
      server/router/router.go

+ 26 - 0
internal/forms/k8s.go

@@ -0,0 +1,26 @@
+package forms
+
+import (
+	"github.com/porter-dev/porter/internal/kubernetes"
+	"github.com/porter-dev/porter/internal/repository"
+)
+
+// K8sForm is the generic base type for CRUD operations on k8s objects
+type K8sForm struct {
+	K8sOptions *kubernetes.OutOfClusterConfig `json:"k8s" form:"required"`
+	UserID     uint                           `json:"user_id"`
+}
+
+// PopulateK8sOptions uses the passed user ID to populate the HelmOptions object
+func (kf *K8sForm) PopulateK8sOptions(repo repository.UserRepository) error {
+	user, err := repo.ReadUser(kf.UserID)
+
+	if err != nil {
+		return err
+	}
+
+	kf.K8sOptions.AllowedContexts = user.ContextToSlice()
+	kf.K8sOptions.KubeConfig = user.RawKubeConfig
+
+	return nil
+}

+ 51 - 0
server/api/k8s_handler.go

@@ -0,0 +1,51 @@
+package api
+
+import (
+	"encoding/json"
+	"net/http"
+
+	"github.com/porter-dev/porter/internal/kubernetes"
+
+	"github.com/porter-dev/porter/internal/forms"
+)
+
+// Enumeration of k8s API error codes, represented as int64
+const (
+	ErrK8sDecode ErrorCode = iota + 600
+	ErrK8sValidate
+)
+
+// HandleListNamespaces retrieves a list of namespaces
+func (app *App) HandleListNamespaces(w http.ResponseWriter, r *http.Request) {
+	// get the filter options
+	form := &forms.K8sForm{}
+
+	// decode from JSON to form value
+	if err := json.NewDecoder(r.Body).Decode(form); err != nil {
+		app.handleErrorFormDecoding(err, ErrK8sDecode, w)
+		return
+	}
+
+	form.PopulateK8sOptions(app.repo.User)
+
+	// validate the form
+	if err := app.validator.Struct(form); err != nil {
+		app.handleErrorFormValidation(err, ErrK8sValidate, w)
+		return
+	}
+
+	// create a new agent
+	agent, err := kubernetes.AgentFromOutOfClusterConfig(form.K8sOptions)
+
+	namespaces, err := agent.ListNamespaces()
+
+	if err != nil {
+		app.handleErrorFormValidation(err, ErrK8sValidate, w)
+		return
+	}
+
+	if err := json.NewEncoder(w).Encode(namespaces); err != nil {
+		app.handleErrorFormDecoding(err, ErrK8sDecode, w)
+		return
+	}
+}

+ 3 - 0
server/router/router.go

@@ -31,6 +31,9 @@ func New(a *api.App, store *sessionstore.PGStore, cookieName string) *chi.Mux {
 		// /api/charts routes
 		r.Method("GET", "/charts", auth.DoesUserIDMatch(requestlog.NewHandler(a.HandleListCharts, l), mw.BodyParam))
 		r.Method("GET", "/charts/{name}/{revision}", auth.DoesUserIDMatch(requestlog.NewHandler(a.HandleGetChart, l), mw.BodyParam))
+
+		// /api/k8s routes
+		r.Method("GET", "/k8s/namespaces", auth.DoesUserIDMatch(requestlog.NewHandler(a.HandleListNamespaces, l), mw.BodyParam))
 	})
 
 	return r