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

add create subdomain handler and add subdomains to proto on cli before applying (#3441)

Co-authored-by: David Townley <davidtownley@Davids-MacBook-Air.local>
d-g-town пре 2 година
родитељ
комит
fffe876f56

+ 24 - 0
api/client/porter_app.go

@@ -272,3 +272,27 @@ func (c *Client) CurrentAppRevision(
 
 	return resp, err
 }
+
+// CreateSubdomain returns a subdomain for a given service that point to the ingress-nginx service in the cluster
+func (c *Client) CreateSubdomain(
+	ctx context.Context,
+	projectID uint, clusterID uint,
+	appName string, serviceName string,
+) (*porter_app.CreateSubdomainResponse, error) {
+	resp := &porter_app.CreateSubdomainResponse{}
+
+	req := &porter_app.CreateSubdomainRequest{
+		ServiceName: serviceName,
+	}
+
+	err := c.postRequest(
+		fmt.Sprintf(
+			"/projects/%d/clusters/%d/apps/%s/subdomain",
+			projectID, clusterID, appName,
+		),
+		req,
+		resp,
+	)
+
+	return resp, err
+}

+ 153 - 0
api/server/handlers/porter_app/create_subdomain.go

@@ -0,0 +1,153 @@
+package porter_app
+
+import (
+	"net/http"
+
+	"github.com/porter-dev/porter/internal/telemetry"
+
+	"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/requestutils"
+	"github.com/porter-dev/porter/api/types"
+	"github.com/porter-dev/porter/internal/kubernetes/domain"
+	"github.com/porter-dev/porter/internal/models"
+)
+
+// CreateSubdomainHandler handles requests to the /apps/{porter_app_name}/subdomain endpoint
+type CreateSubdomainHandler struct {
+	handlers.PorterHandlerReadWriter
+	authz.KubernetesAgentGetter
+}
+
+// NewCreateSubdomainHandler returns a new CreateSubdomainHandler
+func NewCreateSubdomainHandler(
+	config *config.Config,
+	decoderValidator shared.RequestDecoderValidator,
+	writer shared.ResultWriter,
+) *CreateSubdomainHandler {
+	return &CreateSubdomainHandler{
+		PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
+		KubernetesAgentGetter:   authz.NewOutOfClusterAgentGetter(config),
+	}
+}
+
+// CreateSubdomainRequest is the request object for the /apps/{porter_app_name}/subdomain endpoint
+type CreateSubdomainRequest struct {
+	ServiceName string `schema:"service_name"`
+}
+
+// CreateSubdomainResponse is the response object for the /apps/{porter_app_name}/subdomain endpoint
+type CreateSubdomainResponse struct {
+	// Subdomain is the url for the created subdomain
+	Subdomain string `json:"subdomain"`
+}
+
+// ServeHTTP creates a subdomain for the provided service and returns it
+func (c *CreateSubdomainHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+	ctx, span := telemetry.NewSpan(r.Context(), "serve-create-subdomain")
+	defer span.End()
+
+	project, _ := ctx.Value(types.ProjectScope).(*models.Project)
+	cluster, _ := ctx.Value(types.ClusterScope).(*models.Cluster)
+	name, _ := requestutils.GetURLParamString(r, types.URLParamPorterAppName)
+
+	telemetry.WithAttributes(span,
+		telemetry.AttributeKV{Key: "project-id", Value: project.ID},
+		telemetry.AttributeKV{Key: "cluster-id", Value: cluster.ID},
+		telemetry.AttributeKV{Key: "app-name", Value: name},
+	)
+
+	request := &CreateSubdomainRequest{}
+	if ok := c.DecodeAndValidate(w, r, request); !ok {
+		err := telemetry.Error(ctx, span, nil, "error decoding request")
+		c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
+		return
+	}
+
+	if request.ServiceName == "" {
+		err := telemetry.Error(ctx, span, nil, "service name cannot be empty")
+		c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
+		return
+	}
+	telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "service-name", Value: request.ServiceName})
+
+	k8sAgent, err := c.GetAgent(r, cluster, "")
+	if err != nil {
+		err := telemetry.Error(ctx, span, nil, "error getting agent")
+		c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
+		return
+	}
+	if k8sAgent == nil {
+		err := telemetry.Error(ctx, span, nil, "agent is nil")
+		c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
+		return
+	}
+
+	endpoint, found, err := domain.GetNGINXIngressServiceIP(k8sAgent.Clientset)
+	if err != nil {
+		err := telemetry.Error(ctx, span, nil, "error getting nginx ingress service ip")
+		c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
+		return
+	}
+	if !found {
+		err := telemetry.Error(ctx, span, nil, "nginx ingress service ip not found")
+		c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
+		return
+	}
+	if endpoint == "" {
+		err := telemetry.Error(ctx, span, nil, "nginx ingress service ip is empty")
+		c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
+		return
+	}
+	telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "nginx-ingress-ip", Value: endpoint})
+
+	createDomain := domain.CreateDNSRecordConfig{
+		ReleaseName: request.ServiceName,
+		RootDomain:  c.Config().ServerConf.AppRootDomain,
+		Endpoint:    endpoint,
+	}
+
+	record := createDomain.NewDNSRecordForEndpoint()
+	if record == nil {
+		err := telemetry.Error(ctx, span, nil, "dns record is nil")
+		c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
+		return
+	}
+	telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "host-name", Value: record.Hostname})
+
+	record, err = c.Repo().DNSRecord().CreateDNSRecord(record)
+	if err != nil {
+		err := telemetry.Error(ctx, span, nil, "error creating dns record")
+		c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
+		return
+	}
+	if record == nil {
+		err := telemetry.Error(ctx, span, nil, "dns record is nil")
+		c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
+		return
+	}
+
+	_record := domain.DNSRecord(*record)
+
+	if c.Config().PowerDNSClient == nil {
+		err := telemetry.Error(ctx, span, nil, "powerdns client is nil")
+		c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
+		return
+	}
+
+	err = _record.CreateDomain(c.Config().PowerDNSClient)
+	if err != nil {
+		err := telemetry.Error(ctx, span, nil, "error creating domain")
+		c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
+		return
+	}
+
+	resp := &CreateSubdomainResponse{
+		Subdomain: _record.Hostname,
+	}
+
+	c.WriteResult(w, r, resp)
+}

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

@@ -774,5 +774,34 @@ func getPorterAppRoutes(
 		Router:   r,
 	})
 
+	// POST /api/projects/{project_id}/clusters/{cluster_id}/apps/{porter_app_name}/subdomain -> porter_app.NewCreateSubdomainHandler
+	createSubdomainEndpoint := factory.NewAPIEndpoint(
+		&types.APIRequestMetadata{
+			Verb:   types.APIVerbUpdate,
+			Method: types.HTTPVerbPost,
+			Path: &types.Path{
+				Parent:       basePath,
+				RelativePath: fmt.Sprintf("/apps/{%s}/subdomain", types.URLParamPorterAppName),
+			},
+			Scopes: []types.PermissionScope{
+				types.UserScope,
+				types.ProjectScope,
+				types.ClusterScope,
+			},
+		},
+	)
+
+	createSubdomainHandler := porter_app.NewCreateSubdomainHandler(
+		config,
+		factory.GetDecoderValidator(),
+		factory.GetResultWriter(),
+	)
+
+	routes = append(routes, &router.Route{
+		Endpoint: createSubdomainEndpoint,
+		Handler:  createSubdomainHandler,
+		Router:   r,
+	})
+
 	return routes, newPath
 }

+ 58 - 1
cli/cmd/v2/apply.go

@@ -56,7 +56,12 @@ func Apply(ctx context.Context, cliConf config.CLIConfig, client api.Client, por
 	}
 	base64AppProto := validateResp.ValidatedBase64AppProto
 
-	applyResp, err := client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, validateResp.ValidatedBase64AppProto, targetResp.DeploymentTargetID, "")
+	base64AppProtoWithSubdomains, err := addPorterSubdomainsIfNecessary(ctx, client, cliConf.Project, cliConf.Cluster, base64AppProto)
+	if err != nil {
+		return fmt.Errorf("error creating subdomains: %w", err)
+	}
+
+	applyResp, err := client.ApplyPorterApp(ctx, cliConf.Project, cliConf.Cluster, base64AppProtoWithSubdomains, targetResp.DeploymentTargetID, "")
 	if err != nil {
 		return fmt.Errorf("error calling apply endpoint: %w", err)
 	}
@@ -112,6 +117,58 @@ func Apply(ctx context.Context, cliConf config.CLIConfig, client api.Client, por
 	return nil
 }
 
+func addPorterSubdomainsIfNecessary(ctx context.Context, client api.Client, project uint, cluster uint, base64AppProto string) (string, error) {
+	var editedB64AppProto string
+
+	decoded, err := base64.StdEncoding.DecodeString(base64AppProto)
+	if err != nil {
+		return editedB64AppProto, fmt.Errorf("unable to decode base64 app for revision: %w", err)
+	}
+
+	app := &porterv1.PorterApp{}
+	err = helpers.UnmarshalContractObject(decoded, app)
+	if err != nil {
+		return editedB64AppProto, fmt.Errorf("unable to unmarshal app for revision: %w", err)
+	}
+
+	for serviceName, service := range app.Services {
+		if service.Type == porterv1.ServiceType_SERVICE_TYPE_WEB {
+			if service.GetWebConfig() == nil {
+				return editedB64AppProto, fmt.Errorf("web service %s does not contain web config", serviceName)
+			}
+
+			webConfig := service.GetWebConfig()
+
+			if !webConfig.Private && len(webConfig.Domains) == 0 {
+				color.New(color.FgYellow).Printf("Service %s is public but does not contain any domains, creating Porter domain\n", serviceName) // nolint:errcheck,gosec
+				domain, err := client.CreateSubdomain(ctx, project, cluster, app.Name, serviceName)
+				if err != nil {
+					return editedB64AppProto, fmt.Errorf("error creating subdomain: %w", err)
+				}
+
+				if domain.Subdomain == "" {
+					return editedB64AppProto, errors.New("response subdomain is empty")
+				}
+
+				webConfig.Domains = []*porterv1.Domain{
+					{Name: domain.Subdomain},
+				}
+
+				service.Config = &porterv1.Service_WebConfig{WebConfig: webConfig}
+			}
+		}
+	}
+
+	marshalled, err := helpers.MarshalContractObject(ctx, app)
+	if err != nil {
+		return editedB64AppProto, fmt.Errorf("unable to marshal app back to json: %w", err)
+	}
+
+	editedB64AppProto = base64.StdEncoding.EncodeToString(marshalled)
+
+	return editedB64AppProto, nil
+}
+
 func buildSettingsFromBase64AppProto(base64AppProto string) (buildInput, error) {
 	var buildSettings buildInput