94 lines
2.0 KiB
Go
94 lines
2.0 KiB
Go
package api
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"forge.cadoles.com/Cadoles/emissary/internal/datastore"
|
|
"forge.cadoles.com/Cadoles/emissary/internal/spec"
|
|
"github.com/pkg/errors"
|
|
"gitlab.com/wpetit/goweb/api"
|
|
"gitlab.com/wpetit/goweb/logger"
|
|
)
|
|
|
|
const (
|
|
ErrCodeUnexpectedRevision api.ErrorCode = "unexpected-revision"
|
|
)
|
|
|
|
type updateAgentSpecRequest struct {
|
|
spec.RawSpec
|
|
}
|
|
|
|
func (m *Mount) updateAgentSpec(w http.ResponseWriter, r *http.Request) {
|
|
agentID, ok := getAgentID(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
ctx := r.Context()
|
|
|
|
updateSpecReq := &updateAgentSpecRequest{}
|
|
if ok := api.Bind(w, r, updateSpecReq); !ok {
|
|
return
|
|
}
|
|
|
|
if updateSpecReq.DefinitionVersion == "" {
|
|
updateSpecReq.DefinitionVersion = spec.DefaultVersion
|
|
}
|
|
|
|
validator := spec.NewValidator(m.specDefRepo)
|
|
|
|
if err := validator.Validate(ctx, updateSpecReq); err != nil {
|
|
data := struct {
|
|
Message string `json:"message"`
|
|
}{}
|
|
|
|
var validationErr *spec.ValidationError
|
|
|
|
if errors.As(err, &validationErr) {
|
|
data.Message = validationErr.Error()
|
|
}
|
|
|
|
err = errors.WithStack(err)
|
|
logger.Error(ctx, "could not validate spec", logger.CapturedE(err))
|
|
|
|
api.ErrorResponse(w, http.StatusBadRequest, api.ErrCodeInvalidRequest, data)
|
|
|
|
return
|
|
}
|
|
|
|
spec, err := m.agentRepo.UpdateSpec(
|
|
ctx,
|
|
datastore.AgentID(agentID),
|
|
updateSpecReq.SpecDefinitionName(),
|
|
updateSpecReq.SpecDefinitionVersion(),
|
|
updateSpecReq.SpecRevision(),
|
|
updateSpecReq.SpecData(),
|
|
)
|
|
if err != nil {
|
|
if errors.Is(err, datastore.ErrNotFound) {
|
|
api.ErrorResponse(w, http.StatusNotFound, ErrCodeNotFound, nil)
|
|
|
|
return
|
|
}
|
|
|
|
if errors.Is(err, datastore.ErrUnexpectedRevision) {
|
|
api.ErrorResponse(w, http.StatusConflict, ErrCodeUnexpectedRevision, nil)
|
|
|
|
return
|
|
}
|
|
|
|
err = errors.WithStack(err)
|
|
logger.Error(ctx, "could not update spec", logger.CapturedE(err))
|
|
|
|
api.ErrorResponse(w, http.StatusInternalServerError, ErrCodeUnknownError, nil)
|
|
|
|
return
|
|
}
|
|
|
|
api.DataResponse(w, http.StatusOK, struct {
|
|
Spec *datastore.Spec `json:"spec"`
|
|
}{
|
|
Spec: spec,
|
|
})
|
|
}
|