Skip to content

Commit

Permalink
Merge pull request meshery#8775 from MUzairS15/k8s/response
Browse files Browse the repository at this point in the history
Format k8s response
  • Loading branch information
MUzairS15 authored Sep 18, 2023
2 parents f94d517 + 1333ee7 commit 0e3f32c
Show file tree
Hide file tree
Showing 15 changed files with 357 additions and 118 deletions.
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,10 @@ proto-build:
error: dep-check
go run github.com/layer5io/meshkit/cmd/errorutil -d . analyze -i ./server/helpers -o ./server/helpers --skip-dirs mesheryctl

## Runs meshkit error utility to update error codes for meshery server only.
server-error-util:
go run github.com/layer5io/meshkit/cmd/errorutil -d . --skip-dirs mesheryctl update -i ./server/helpers/ -o ./server/helpers

## Build Meshery UI; Build and run Meshery Server on your local machine.
ui-server: ui-meshery-build ui-provider-build server

Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ require (
github.com/jinzhu/copier v0.3.5
github.com/layer5io/gowrk2 v0.6.1
github.com/layer5io/meshery-operator v0.6.10
github.com/layer5io/meshkit v0.6.65
github.com/layer5io/meshkit v0.6.66
github.com/layer5io/meshsync v0.6.14
github.com/layer5io/nighthawk-go v1.0.6
github.com/layer5io/service-mesh-performance v0.6.1
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -1571,8 +1571,8 @@ github.com/layer5io/gowrk2 v0.6.1 h1:0eBj7VFYJ+QTMJt7i3PzxDJTEL+X+zWx4OP+lARWIoI
github.com/layer5io/gowrk2 v0.6.1/go.mod h1:ugxQ23+HwQ8dmZYJd1LScw/TLKbdgfN6OOtg6iYMljg=
github.com/layer5io/meshery-operator v0.6.10 h1:4YiznhS4AO/bA+uHBxCYp9Fc9w9LU2sopE3oJBdRU/Y=
github.com/layer5io/meshery-operator v0.6.10/go.mod h1:RX9yjSvJS0KAdWOb/zRfYU/mSOVP1ySuUUlxHhrms1M=
github.com/layer5io/meshkit v0.6.65 h1:JltJ5hq8z/JIJf8V0m6UrsZ/PvIeKevLeIuAvH8q+DU=
github.com/layer5io/meshkit v0.6.65/go.mod h1:ZepHoPUmrDQK6T4ARmyWfKy8HejxFdJsoqC1cq4Slb8=
github.com/layer5io/meshkit v0.6.66 h1:oJKgab+7nlp2EArTwq9r0ZW+/+UIPrY5Efs4eLqIpdg=
github.com/layer5io/meshkit v0.6.66/go.mod h1:/EX5QLmgZpLPqhBHGvNqyHM6ljfc6hYwULCEcnqTCVw=
github.com/layer5io/meshsync v0.6.14 h1:y5Fbq76WGYWjdzYFNOD1YgowP/0m/NxPZ/hA1JGJ3RA=
github.com/layer5io/meshsync v0.6.14/go.mod h1:21VTdYITKXpBSb+kj2CcR3T0KbrcLJwhiewQRKTqvUM=
github.com/layer5io/nighthawk-go v1.0.6 h1:YMCw65FvwpbByX+M7McdNYRNDW9oOw3GQaXJ1RMDdGw=
Expand Down
98 changes: 52 additions & 46 deletions server/handlers/design_engine_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"github.com/ghodss/yaml"
"github.com/gofrs/uuid"
"github.com/layer5io/meshery/server/helpers/utils"
"github.com/layer5io/meshery/server/meshes"
"github.com/layer5io/meshery/server/models"
"github.com/layer5io/meshery/server/models/pattern/core"
Expand Down Expand Up @@ -89,7 +90,7 @@ func (h *Handler) PatternFileHandler(
provider,
patternFile,
prefObj,
user.UserID,
user.ID,
isDel,
r.URL.Query().Get("verify") == "true",
r.URL.Query().Get("dryRun") == "true",
Expand Down Expand Up @@ -345,16 +346,17 @@ func (sap *serviceActionProvider) Mutate(p *core.Pattern) {

// NOTE: Currently tied to kubernetes
// Returns ComponentName->ContextID->Response
func (sap *serviceActionProvider) DryRun(comps []v1alpha1.Component) (resp map[string]map[string]core.DryRunResponse2, err error) {
func (sap *serviceActionProvider) DryRun(comps []v1alpha1.Component) (resp map[string]map[string]core.DryRunResponseWrapper, err error) {
for _, cmp := range comps {
for ctxID, kc := range sap.ctxTokubeconfig {
cl, err := meshkube.New([]byte(kc))
if err != nil {
return resp, err
}

st, ok, err := k8s.DryRunHelper(cl, cmp)
dResp := core.DryRunResponse2{Success: ok, Component: &core.Service{
// status represents kubernetes status object
status, ok, err := k8s.DryRunHelper(cl, cmp)
dResp := core.DryRunResponseWrapper{Success: ok, Component: &core.Service{
Name: cmp.Name,
Type: cmp.Spec.Type,
Namespace: cmp.Namespace,
Expand All @@ -364,10 +366,11 @@ func (sap *serviceActionProvider) DryRun(comps []v1alpha1.Component) (resp map[s
Labels: cmp.Labels,
Annotations: cmp.Annotations,
}}

// Dry run was success
if ok {
dResp.Component.Settings = make(map[string]interface{})
for k, v := range st {
for k, v := range status {
if k == "apiVersion" || k == "kind" || k == "metadata" {
continue
}
Expand All @@ -377,63 +380,66 @@ func (sap *serviceActionProvider) DryRun(comps []v1alpha1.Component) (resp map[s
dResp.Error = &core.DryRunResponse{
Status: err.Error(),
}
} else { //Dry run failure returned with an error wrapped in kubernetes custom error
dResp.Error = &core.DryRunResponse{}
byt, err := json.Marshal(st)
if err != nil {
return nil, err
}
var a v1.StatusApplyConfiguration
err = json.Unmarshal(byt, &a)
} else { //Dry run failure returned with an error wrapped in kubernetes custom error
dResp.Error, err = convertRawDryRunResponse(cmp.Name, status)
if err != nil {
return nil, err
}
if a.Status != nil {
dResp.Error.Status = *a.Status
}
dResp.Error.Causes = make([]core.DryRunFailureCause, 0)
if a.Details != nil {
for _, c := range a.Details.Causes {
msg := ""
field := ""
typ := ""
if c.Message != nil {
msg = *c.Message
}
if c.Field != nil {
field = cmp.Name + "." + getComponentFieldPathFromK8sFieldPath(*c.Field)
}
if c.Type != nil {
typ = string(*c.Type)
}
failureCase := core.DryRunFailureCause{Message: msg, FieldPath: field, Type: typ}
dResp.Error.Causes = append(dResp.Error.Causes, failureCase)
}
}
}
if resp == nil {
resp = make(map[string]map[string]core.DryRunResponse2)
resp = make(map[string]map[string]core.DryRunResponseWrapper)
}
if resp[cmp.Name] == nil {
resp[cmp.Name] = make(map[string]core.DryRunResponse2)
resp[cmp.Name] = make(map[string]core.DryRunResponseWrapper)
}
resp[cmp.Name][ctxID] = dResp
}
}
return
}
func getComponentFieldPathFromK8sFieldPath(path string) (newpath string) {
if strings.HasPrefix(path, "metadata.") {
path = strings.TrimPrefix(path, "metadata.")
paths := strings.Split(path, ".")
if len(paths) != 0 {
if paths[0] == "name" || paths[0] == "namespace" || paths[0] == "labels" || paths[0] == "annotations" {
return paths[0]

func convertRawDryRunResponse(componentName string, status map[string]interface{}) (*core.DryRunResponse, error) {
response := core.DryRunResponse{}

byt, err := json.Marshal(status)
if err != nil {
return nil, err
}

var a v1.StatusApplyConfiguration
err = json.Unmarshal(byt, &a)
if err != nil {
return nil, err
}

if a.Status != nil {
response.Status = *a.Status
}

response.Causes = make([]core.DryRunFailureCause, 0)
if a.Details != nil {
for _, cause := range a.Details.Causes {
msg := ""
field := ""
typ := ""
if cause.Message != nil {
msg = *cause.Message
}
if cause.Field != nil {
field = componentName + "." + utils.GetComponentFieldPathFromK8sFieldPath(*cause.Field)
}
if cause.Type != nil {
typ = string(*cause.Type)
}
failureCase := core.DryRunFailureCause{Message: msg, FieldPath: field, Type: typ}
response.Causes = append(response.Causes, failureCase)
}
return
}
return fmt.Sprintf("%s.%s", "settings", path)

if len(response.Causes) == 0 && a.Message != nil {
response.Status = *a.Message
}
return &response, nil
}

func (sap *serviceActionProvider) Provision(ccp stages.CompConfigPair) (string, error) { // Marshal the component
Expand Down
2 changes: 1 addition & 1 deletion server/handlers/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,7 @@ func ErrDecodePattern(err error) error {
}

func ErrParsePattern(err error) error {
return errors.New(ErrParsePatternCode, errors.Alert, []string{"Error failed to parse pattern file"}, []string{err.Error()}, []string{}, []string{})
return errors.New(ErrParsePatternCode, errors.Alert, []string{"Error failed to parse pattern file from cytoJSON format"}, []string{err.Error()}, []string{}, []string{})
}

func ErrConvertPattern(err error) error {
Expand Down
26 changes: 20 additions & 6 deletions server/handlers/meshery_application_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,10 @@ func (h *Handler) handleApplicationPOST(
}
var parsedBody *MesheryApplicationRequestBody
if err := json.NewDecoder(r.Body).Decode(&parsedBody); err != nil {
http.Error(rw, ErrRetrieveData(err).Error(), http.StatusBadRequest)
http.Error(rw, ErrRequestBody(err).Error(), http.StatusBadRequest)
addMeshkitErr(&res, ErrRetrieveData(err))
event := eventBuilder.WithSeverity(events.Error).WithMetadata(map[string]interface{}{
"error": ErrRetrieveData(err),
"error": ErrRequestBody(err),
}).WithDescription("Unable to parse uploaded application.").Build()

_ = provider.PersistEvent(event)
Expand Down Expand Up @@ -491,7 +491,9 @@ func (h *Handler) handleApplicationPOST(
h.formatApplicationOutput(rw, resp, format, &res, eventBuilder)

eventBuilder.WithSeverity(events.Informational)
_ = provider.PersistEvent(eventBuilder.Build())
event := eventBuilder.Build()
go h.config.EventBroadcaster.Publish(userID, event)
_ = provider.PersistEvent(event)

var mesheryApplicationContent []models.MesheryApplication
err = json.Unmarshal(resp, &mesheryApplicationContent)
Expand Down Expand Up @@ -537,6 +539,10 @@ func (h *Handler) handleApplicationPOST(
}

h.formatApplicationOutput(rw, byt, format, &res, eventBuilder)

event := eventBuilder.Build()
_ = provider.PersistEvent(event)
go h.config.EventBroadcaster.Publish(userID, event)
}

func (h *Handler) handleApplicationUpdate(rw http.ResponseWriter,
Expand Down Expand Up @@ -674,7 +680,9 @@ func (h *Handler) handleApplicationUpdate(rw http.ResponseWriter,

go h.config.ConfigurationChannel.PublishApplications()
h.formatApplicationOutput(rw, resp, format, &res, eventBuilder)
_ = provider.PersistEvent(eventBuilder.Build())
event := eventBuilder.Build()
go h.config.EventBroadcaster.Publish(userID, event)
_ = provider.PersistEvent(event)

return
}
Expand Down Expand Up @@ -718,7 +726,10 @@ func (h *Handler) handleApplicationUpdate(rw http.ResponseWriter,

eventBuilder.WithSeverity(events.Informational)
h.formatApplicationOutput(rw, resp, format, &res, eventBuilder)
_ = provider.PersistEvent(eventBuilder.Build())
event := eventBuilder.Build()
_ = provider.PersistEvent(event)
go h.config.EventBroadcaster.Publish(userID, event)

}

// swagger:route GET /api/application ApplicationsAPI idGetMesheryApplications
Expand Down Expand Up @@ -789,6 +800,9 @@ func (h *Handler) DeleteMesheryApplicationHandler(
eventBuilder := events.NewEvent().FromUser(userID).FromSystem(*h.SystemID).WithCategory("application").WithAction("delete").ActedUpon(uuid.FromStringOrNil(applicationID))
resp, err := provider.DeleteMesheryApplication(r, applicationID)

mesheryApplication := models.MesheryApplication{}
_ = json.Unmarshal(resp, &mesheryApplication)

if err != nil {
errAppDelete := ErrDeleteApplication(err)
h.log.Error(errAppDelete)
Expand All @@ -801,7 +815,7 @@ func (h *Handler) DeleteMesheryApplicationHandler(
return
}

event := eventBuilder.WithSeverity(events.Informational).WithDescription("Application deleted.").Build()
event := eventBuilder.WithSeverity(events.Informational).WithDescription(fmt.Sprintf("Application %s deleted.", mesheryApplication.Name)).Build()
_ = provider.PersistEvent(event)
go h.config.EventBroadcaster.Publish(userID, event)

Expand Down
Loading

0 comments on commit 0e3f32c

Please sign in to comment.