chore(handlers): replace structs by functions for HTTP errors EE-4227 (#7664)

pull/7669/head
andres-portainer 2022-09-14 20:42:39 -03:00 committed by GitHub
parent 7accdf704c
commit 9ef5636718
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
157 changed files with 1123 additions and 1147 deletions

View File

@ -54,24 +54,24 @@ func (handler *Handler) authenticate(rw http.ResponseWriter, r *http.Request) *h
var payload authenticatePayload
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
settings, err := handler.DataStore.Settings().Settings()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve settings from the database", err}
return httperror.InternalServerError("Unable to retrieve settings from the database", err)
}
user, err := handler.DataStore.User().UserByUsername(payload.Username)
if err != nil {
if !handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve a user with the specified username from the database", err}
return httperror.InternalServerError("Unable to retrieve a user with the specified username from the database", err)
}
if settings.AuthenticationMethod == portainer.AuthenticationInternal ||
settings.AuthenticationMethod == portainer.AuthenticationOAuth ||
(settings.AuthenticationMethod == portainer.AuthenticationLDAP && !settings.LDAPSettings.AutoCreateUsers) {
return &httperror.HandlerError{http.StatusUnprocessableEntity, "Invalid credentials", httperrors.ErrUnauthorized}
return &httperror.HandlerError{StatusCode: http.StatusUnprocessableEntity, Message: "Invalid credentials", Err: httperrors.ErrUnauthorized}
}
}
@ -80,14 +80,14 @@ func (handler *Handler) authenticate(rw http.ResponseWriter, r *http.Request) *h
}
if settings.AuthenticationMethod == portainer.AuthenticationOAuth {
return &httperror.HandlerError{http.StatusUnprocessableEntity, "Only initial admin is allowed to login without oauth", httperrors.ErrUnauthorized}
return &httperror.HandlerError{StatusCode: http.StatusUnprocessableEntity, Message: "Only initial admin is allowed to login without oauth", Err: httperrors.ErrUnauthorized}
}
if settings.AuthenticationMethod == portainer.AuthenticationLDAP {
return handler.authenticateLDAP(rw, user, payload.Username, payload.Password, &settings.LDAPSettings)
}
return &httperror.HandlerError{http.StatusUnprocessableEntity, "Login method is not supported", httperrors.ErrUnauthorized}
return &httperror.HandlerError{StatusCode: http.StatusUnprocessableEntity, Message: "Login method is not supported", Err: httperrors.ErrUnauthorized}
}
func isUserInitialAdmin(user *portainer.User) bool {
@ -97,7 +97,7 @@ func isUserInitialAdmin(user *portainer.User) bool {
func (handler *Handler) authenticateInternal(w http.ResponseWriter, user *portainer.User, password string) *httperror.HandlerError {
err := handler.CryptoService.CompareHashAndData(user.Password, password)
if err != nil {
return &httperror.HandlerError{http.StatusUnprocessableEntity, "Invalid credentials", httperrors.ErrUnauthorized}
return &httperror.HandlerError{StatusCode: http.StatusUnprocessableEntity, Message: "Invalid credentials", Err: httperrors.ErrUnauthorized}
}
forceChangePassword := !handler.passwordStrengthChecker.Check(password)
@ -107,11 +107,7 @@ func (handler *Handler) authenticateInternal(w http.ResponseWriter, user *portai
func (handler *Handler) authenticateLDAP(w http.ResponseWriter, user *portainer.User, username, password string, ldapSettings *portainer.LDAPSettings) *httperror.HandlerError {
err := handler.LDAPService.AuthenticateUser(username, password, ldapSettings)
if err != nil {
return &httperror.HandlerError{
StatusCode: http.StatusForbidden,
Message: "Only initial admin is allowed to login without oauth",
Err: err,
}
return httperror.Forbidden("Only initial admin is allowed to login without oauth", err)
}
if user == nil {
@ -123,7 +119,7 @@ func (handler *Handler) authenticateLDAP(w http.ResponseWriter, user *portainer.
err = handler.DataStore.User().Create(user)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist user inside the database", err}
return httperror.InternalServerError("Unable to persist user inside the database", err)
}
}
@ -144,7 +140,7 @@ func (handler *Handler) writeToken(w http.ResponseWriter, user *portainer.User,
func (handler *Handler) persistAndWriteToken(w http.ResponseWriter, tokenData *portainer.TokenData) *httperror.HandlerError {
token, err := handler.JWTService.GenerateToken(tokenData)
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Unable to generate JWT token", Err: err}
return httperror.InternalServerError("Unable to generate JWT token", err)
}
return response.JSON(w, &authenticateResponse{JWT: token})

View File

@ -57,31 +57,31 @@ func (handler *Handler) validateOAuth(w http.ResponseWriter, r *http.Request) *h
var payload oauthPayload
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Invalid request payload", Err: err}
return httperror.BadRequest("Invalid request payload", err)
}
settings, err := handler.DataStore.Settings().Settings()
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Unable to retrieve settings from the database", Err: err}
return httperror.InternalServerError("Unable to retrieve settings from the database", err)
}
if settings.AuthenticationMethod != portainer.AuthenticationOAuth {
return &httperror.HandlerError{StatusCode: http.StatusForbidden, Message: "OAuth authentication is not enabled", Err: errors.New("OAuth authentication is not enabled")}
return httperror.Forbidden("OAuth authentication is not enabled", errors.New("OAuth authentication is not enabled"))
}
username, err := handler.authenticateOAuth(payload.Code, &settings.OAuthSettings)
if err != nil {
log.Printf("[DEBUG] - OAuth authentication error: %s", err)
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Unable to authenticate through OAuth", Err: httperrors.ErrUnauthorized}
return httperror.InternalServerError("Unable to authenticate through OAuth", httperrors.ErrUnauthorized)
}
user, err := handler.DataStore.User().UserByUsername(username)
if err != nil && !handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Unable to retrieve a user with the specified username from the database", Err: err}
return httperror.InternalServerError("Unable to retrieve a user with the specified username from the database", err)
}
if user == nil && !settings.OAuthSettings.OAuthAutoCreateUsers {
return &httperror.HandlerError{StatusCode: http.StatusForbidden, Message: "Account not created beforehand in Portainer and automatic user provisioning not enabled", Err: httperrors.ErrUnauthorized}
return httperror.Forbidden("Account not created beforehand in Portainer and automatic user provisioning not enabled", httperrors.ErrUnauthorized)
}
if user == nil {
@ -92,7 +92,7 @@ func (handler *Handler) validateOAuth(w http.ResponseWriter, r *http.Request) *h
err = handler.DataStore.User().Create(user)
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Unable to persist user inside the database", Err: err}
return httperror.InternalServerError("Unable to persist user inside the database", err)
}
if settings.OAuthSettings.DefaultTeamID != 0 {
@ -104,7 +104,7 @@ func (handler *Handler) validateOAuth(w http.ResponseWriter, r *http.Request) *h
err = handler.DataStore.TeamMembership().Create(membership)
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Unable to persist team membership inside the database", Err: err}
return httperror.InternalServerError("Unable to persist team membership inside the database", err)
}
}

View File

@ -20,7 +20,7 @@ import (
func (handler *Handler) logout(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
tokenData, err := security.RetrieveTokenData(r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve user details from authentication token", err}
return httperror.InternalServerError("Unable to retrieve user details from authentication token", err)
}
handler.KubernetesTokenCacheManager.RemoveUserFromCache(int(tokenData.ID))

View File

@ -39,12 +39,12 @@ func (h *Handler) backup(w http.ResponseWriter, r *http.Request) *httperror.Hand
var payload backupPayload
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Invalid request payload", Err: err}
return httperror.BadRequest("Invalid request payload", err)
}
archivePath, err := operations.CreateBackupArchive(payload.Password, h.gate, h.dataStore, h.filestorePath)
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Failed to create backup", Err: err}
return httperror.InternalServerError("Failed to create backup", err)
}
defer os.RemoveAll(filepath.Dir(archivePath))

View File

@ -31,10 +31,10 @@ type restorePayload struct {
func (h *Handler) restore(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
initialized, err := h.adminMonitor.WasInitialized()
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Failed to check system initialization", Err: err}
return httperror.InternalServerError("Failed to check system initialization", err)
}
if initialized {
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Cannot restore already initialized instance", Err: errors.New("system already initialized")}
return httperror.BadRequest("Cannot restore already initialized instance", errors.New("system already initialized"))
}
h.adminMonitor.Stop()
defer h.adminMonitor.Start()
@ -42,13 +42,13 @@ func (h *Handler) restore(w http.ResponseWriter, r *http.Request) *httperror.Han
var payload restorePayload
err = decodeForm(r, &payload)
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Invalid request payload", Err: err}
return httperror.BadRequest("Invalid request payload", err)
}
var archiveReader io.Reader = bytes.NewReader(payload.FileContent)
err = operations.RestoreArchive(archiveReader, payload.Password, h.filestorePath, h.gate, h.dataStore, h.shutdownTrigger)
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Failed to restore the backup", Err: err}
return httperror.InternalServerError("Failed to restore the backup", err)
}
return nil

View File

@ -44,42 +44,42 @@ import (
func (handler *Handler) customTemplateCreate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
method, err := request.RetrieveQueryParameter(r, "method", false)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid query parameter: method", err}
return httperror.BadRequest("Invalid query parameter: method", err)
}
tokenData, err := security.RetrieveTokenData(r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve user details from authentication token", err}
return httperror.InternalServerError("Unable to retrieve user details from authentication token", err)
}
customTemplate, err := handler.createCustomTemplate(method, r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to create custom template", err}
return httperror.InternalServerError("Unable to create custom template", err)
}
customTemplate.CreatedByUserID = tokenData.ID
customTemplates, err := handler.DataStore.CustomTemplate().CustomTemplates()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve custom templates from the database", err}
return httperror.InternalServerError("Unable to retrieve custom templates from the database", err)
}
for _, existingTemplate := range customTemplates {
if existingTemplate.Title == customTemplate.Title {
return &httperror.HandlerError{http.StatusInternalServerError, "Template name must be unique", errors.New("Template name must be unique")}
return httperror.InternalServerError("Template name must be unique", errors.New("Template name must be unique"))
}
}
err = handler.DataStore.CustomTemplate().Create(customTemplate)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to create custom template", err}
return httperror.InternalServerError("Unable to create custom template", err)
}
resourceControl := authorization.NewPrivateResourceControl(strconv.Itoa(int(customTemplate.ID)), portainer.CustomTemplateResourceControl, tokenData.ID)
err = handler.DataStore.ResourceControl().Create(resourceControl)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist resource control inside the database", err}
return httperror.InternalServerError("Unable to persist resource control inside the database", err)
}
customTemplate.ResourceControl = resourceControl

View File

@ -29,45 +29,45 @@ import (
func (handler *Handler) customTemplateDelete(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
customTemplateID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid Custom template identifier route variable", err}
return httperror.BadRequest("Invalid Custom template identifier route variable", err)
}
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve info from request context", err}
return httperror.InternalServerError("Unable to retrieve info from request context", err)
}
customTemplate, err := handler.DataStore.CustomTemplate().CustomTemplate(portainer.CustomTemplateID(customTemplateID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find a custom template with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find a custom template with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a custom template with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find a custom template with the specified identifier inside the database", err)
}
resourceControl, err := handler.DataStore.ResourceControl().ResourceControlByResourceIDAndType(strconv.Itoa(customTemplateID), portainer.CustomTemplateResourceControl)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve a resource control associated to the custom template", err}
return httperror.InternalServerError("Unable to retrieve a resource control associated to the custom template", err)
}
access := userCanEditTemplate(customTemplate, securityContext)
if !access {
return &httperror.HandlerError{http.StatusForbidden, "Access denied to resource", httperrors.ErrResourceAccessDenied}
return httperror.Forbidden("Access denied to resource", httperrors.ErrResourceAccessDenied)
}
err = handler.DataStore.CustomTemplate().DeleteCustomTemplate(portainer.CustomTemplateID(customTemplateID))
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to remove the custom template from the database", err}
return httperror.InternalServerError("Unable to remove the custom template from the database", err)
}
err = handler.FileService.RemoveDirectory(customTemplate.ProjectPath)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to remove custom template files from disk", err}
return httperror.InternalServerError("Unable to remove custom template files from disk", err)
}
if resourceControl != nil {
err = handler.DataStore.ResourceControl().DeleteResourceControl(resourceControl.ID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to remove the associated resource control from the database", err}
return httperror.InternalServerError("Unable to remove the associated resource control from the database", err)
}
}

View File

@ -30,19 +30,19 @@ type fileResponse struct {
func (handler *Handler) customTemplateFile(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
customTemplateID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid custom template identifier route variable", err}
return httperror.BadRequest("Invalid custom template identifier route variable", err)
}
customTemplate, err := handler.DataStore.CustomTemplate().CustomTemplate(portainer.CustomTemplateID(customTemplateID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find a custom template with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find a custom template with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a custom template with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find a custom template with the specified identifier inside the database", err)
}
fileContent, err := handler.FileService.GetFileContent(customTemplate.ProjectPath, customTemplate.EntryPoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve custom template file from disk", err}
return httperror.InternalServerError("Unable to retrieve custom template file from disk", err)
}
return response.JSON(w, &fileResponse{FileContent: string(fileContent)})

View File

@ -29,29 +29,29 @@ import (
func (handler *Handler) customTemplateInspect(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
customTemplateID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid Custom template identifier route variable", err}
return httperror.BadRequest("Invalid Custom template identifier route variable", err)
}
customTemplate, err := handler.DataStore.CustomTemplate().CustomTemplate(portainer.CustomTemplateID(customTemplateID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find a custom template with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find a custom template with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a custom template with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find a custom template with the specified identifier inside the database", err)
}
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve user info from request context", err}
return httperror.InternalServerError("Unable to retrieve user info from request context", err)
}
resourceControl, err := handler.DataStore.ResourceControl().ResourceControlByResourceIDAndType(strconv.Itoa(customTemplateID), portainer.CustomTemplateResourceControl)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve a resource control associated to the custom template", err}
return httperror.InternalServerError("Unable to retrieve a resource control associated to the custom template", err)
}
access := userCanEditTemplate(customTemplate, securityContext)
if !access {
return &httperror.HandlerError{http.StatusForbidden, "Access denied to resource", httperrors.ErrResourceAccessDenied}
return httperror.Forbidden("Access denied to resource", httperrors.ErrResourceAccessDenied)
}
if resourceControl != nil {

View File

@ -27,30 +27,30 @@ import (
func (handler *Handler) customTemplateList(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
templateTypes, err := parseTemplateTypes(r)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid Custom template type", err}
return httperror.BadRequest("Invalid Custom template type", err)
}
customTemplates, err := handler.DataStore.CustomTemplate().CustomTemplates()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve custom templates from the database", err}
return httperror.InternalServerError("Unable to retrieve custom templates from the database", err)
}
resourceControls, err := handler.DataStore.ResourceControl().ResourceControls()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve resource controls from the database", err}
return httperror.InternalServerError("Unable to retrieve resource controls from the database", err)
}
customTemplates = authorization.DecorateCustomTemplates(customTemplates, resourceControls)
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve info from request context", err}
return httperror.InternalServerError("Unable to retrieve info from request context", err)
}
if !securityContext.IsAdmin {
user, err := handler.DataStore.User().User(securityContext.UserID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve user information from the database", err}
return httperror.InternalServerError("Unable to retrieve user information from the database", err)
}
userTeamIDs := make([]portainer.TeamID, 0)

View File

@ -83,47 +83,47 @@ func (payload *customTemplateUpdatePayload) Validate(r *http.Request) error {
func (handler *Handler) customTemplateUpdate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
customTemplateID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid Custom template identifier route variable", err}
return httperror.BadRequest("Invalid Custom template identifier route variable", err)
}
var payload customTemplateUpdatePayload
err = request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
customTemplates, err := handler.DataStore.CustomTemplate().CustomTemplates()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve custom templates from the database", err}
return httperror.InternalServerError("Unable to retrieve custom templates from the database", err)
}
for _, existingTemplate := range customTemplates {
if existingTemplate.ID != portainer.CustomTemplateID(customTemplateID) && existingTemplate.Title == payload.Title {
return &httperror.HandlerError{http.StatusInternalServerError, "Template name must be unique", errors.New("Template name must be unique")}
return httperror.InternalServerError("Template name must be unique", errors.New("Template name must be unique"))
}
}
customTemplate, err := handler.DataStore.CustomTemplate().CustomTemplate(portainer.CustomTemplateID(customTemplateID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find a custom template with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find a custom template with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a custom template with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find a custom template with the specified identifier inside the database", err)
}
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve info from request context", err}
return httperror.InternalServerError("Unable to retrieve info from request context", err)
}
access := userCanEditTemplate(customTemplate, securityContext)
if !access {
return &httperror.HandlerError{http.StatusForbidden, "Access denied to resource", httperrors.ErrResourceAccessDenied}
return httperror.Forbidden("Access denied to resource", httperrors.ErrResourceAccessDenied)
}
templateFolder := strconv.Itoa(customTemplateID)
_, err = handler.FileService.StoreCustomTemplateFileFromBytes(templateFolder, customTemplate.EntryPoint, []byte(payload.FileContent))
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist updated custom template file on disk", err}
return httperror.InternalServerError("Unable to persist updated custom template file on disk", err)
}
customTemplate.Title = payload.Title
@ -136,7 +136,7 @@ func (handler *Handler) customTemplateUpdate(w http.ResponseWriter, r *http.Requ
err = handler.DataStore.CustomTemplate().UpdateCustomTemplate(customTemplate.ID, customTemplate)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist custom template changes inside the database", err}
return httperror.InternalServerError("Unable to persist custom template changes inside the database", err)
}
return response.JSON(w, customTemplate)

View File

@ -49,17 +49,17 @@ func (handler *Handler) edgeGroupCreate(w http.ResponseWriter, r *http.Request)
var payload edgeGroupCreatePayload
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
edgeGroups, err := handler.DataStore.EdgeGroup().EdgeGroups()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve Edge groups from the database", err}
return httperror.InternalServerError("Unable to retrieve Edge groups from the database", err)
}
for _, edgeGroup := range edgeGroups {
if edgeGroup.Name == payload.Name {
return &httperror.HandlerError{http.StatusBadRequest, "Edge group name must be unique", errors.New("Edge group name must be unique")}
return httperror.BadRequest("Edge group name must be unique", errors.New("Edge group name must be unique"))
}
}
@ -78,7 +78,7 @@ func (handler *Handler) edgeGroupCreate(w http.ResponseWriter, r *http.Request)
for _, endpointID := range payload.Endpoints {
endpoint, err := handler.DataStore.Endpoint().Endpoint(endpointID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environment from the database", err}
return httperror.InternalServerError("Unable to retrieve environment from the database", err)
}
if endpoint.Type == portainer.EdgeAgentOnDockerEnvironment || endpoint.Type == portainer.EdgeAgentOnKubernetesEnvironment {
@ -90,7 +90,7 @@ func (handler *Handler) edgeGroupCreate(w http.ResponseWriter, r *http.Request)
err = handler.DataStore.EdgeGroup().Create(edgeGroup)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist the Edge group inside the database", err}
return httperror.InternalServerError("Unable to persist the Edge group inside the database", err)
}
return response.JSON(w, edgeGroup)

View File

@ -24,32 +24,32 @@ import (
func (handler *Handler) edgeGroupDelete(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
edgeGroupID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid Edge group identifier route variable", err}
return httperror.BadRequest("Invalid Edge group identifier route variable", err)
}
_, err = handler.DataStore.EdgeGroup().EdgeGroup(portainer.EdgeGroupID(edgeGroupID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an Edge group with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an Edge group with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an Edge group with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an Edge group with the specified identifier inside the database", err)
}
edgeStacks, err := handler.DataStore.EdgeStack().EdgeStacks()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve Edge stacks from the database", err}
return httperror.InternalServerError("Unable to retrieve Edge stacks from the database", err)
}
for _, edgeStack := range edgeStacks {
for _, groupID := range edgeStack.EdgeGroups {
if groupID == portainer.EdgeGroupID(edgeGroupID) {
return &httperror.HandlerError{http.StatusForbidden, "Edge group is used by an Edge stack", errors.New("Edge group is used by an Edge stack")}
return httperror.Forbidden("Edge group is used by an Edge stack", errors.New("Edge group is used by an Edge stack"))
}
}
}
err = handler.DataStore.EdgeGroup().DeleteEdgeGroup(portainer.EdgeGroupID(edgeGroupID))
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to remove the Edge group from the database", err}
return httperror.InternalServerError("Unable to remove the Edge group from the database", err)
}
return response.Empty(w)

View File

@ -24,20 +24,20 @@ import (
func (handler *Handler) edgeGroupInspect(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
edgeGroupID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid Edge group identifier route variable", err}
return httperror.BadRequest("Invalid Edge group identifier route variable", err)
}
edgeGroup, err := handler.DataStore.EdgeGroup().EdgeGroup(portainer.EdgeGroupID(edgeGroupID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an Edge group with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an Edge group with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an Edge group with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an Edge group with the specified identifier inside the database", err)
}
if edgeGroup.Dynamic {
endpoints, err := handler.getEndpointsByTags(edgeGroup.TagIDs, edgeGroup.PartialMatch)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environments and environment groups for Edge group", err}
return httperror.InternalServerError("Unable to retrieve environments and environment groups for Edge group", err)
}
edgeGroup.Endpoints = endpoints

View File

@ -30,12 +30,12 @@ type decoratedEdgeGroup struct {
func (handler *Handler) edgeGroupList(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
edgeGroups, err := handler.DataStore.EdgeGroup().EdgeGroups()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve Edge groups from the database", err}
return httperror.InternalServerError("Unable to retrieve Edge groups from the database", err)
}
edgeStacks, err := handler.DataStore.EdgeStack().EdgeStacks()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve Edge stacks from the database", err}
return httperror.InternalServerError("Unable to retrieve Edge stacks from the database", err)
}
usedEdgeGroups := make(map[portainer.EdgeGroupID]bool)
@ -55,7 +55,7 @@ func (handler *Handler) edgeGroupList(w http.ResponseWriter, r *http.Request) *h
if edgeGroup.Dynamic {
endpointIDs, err := handler.getEndpointsByTags(edgeGroup.TagIDs, edgeGroup.PartialMatch)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environments and environment groups for Edge group", err}
return httperror.InternalServerError("Unable to retrieve environments and environment groups for Edge group", err)
}
edgeGroup.Endpoints = endpointIDs
@ -63,7 +63,7 @@ func (handler *Handler) edgeGroupList(w http.ResponseWriter, r *http.Request) *h
endpointTypes, err := getEndpointTypes(handler.DataStore.Endpoint(), edgeGroup.Endpoints)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve endpoint types for Edge group", err}
return httperror.InternalServerError("Unable to retrieve endpoint types for Edge group", err)
}
edgeGroup.EndpointTypes = endpointTypes

View File

@ -50,30 +50,30 @@ func (payload *edgeGroupUpdatePayload) Validate(r *http.Request) error {
func (handler *Handler) edgeGroupUpdate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
edgeGroupID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid Edge group identifier route variable", err}
return httperror.BadRequest("Invalid Edge group identifier route variable", err)
}
var payload edgeGroupUpdatePayload
err = request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
edgeGroup, err := handler.DataStore.EdgeGroup().EdgeGroup(portainer.EdgeGroupID(edgeGroupID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an Edge group with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an Edge group with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an Edge group with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an Edge group with the specified identifier inside the database", err)
}
if payload.Name != "" {
edgeGroups, err := handler.DataStore.EdgeGroup().EdgeGroups()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve Edge groups from the database", err}
return httperror.InternalServerError("Unable to retrieve Edge groups from the database", err)
}
for _, edgeGroup := range edgeGroups {
if edgeGroup.Name == payload.Name && edgeGroup.ID != portainer.EdgeGroupID(edgeGroupID) {
return &httperror.HandlerError{http.StatusBadRequest, "Edge group name must be unique", errors.New("Edge group name must be unique")}
return httperror.BadRequest("Edge group name must be unique", errors.New("Edge group name must be unique"))
}
}
@ -81,12 +81,12 @@ func (handler *Handler) edgeGroupUpdate(w http.ResponseWriter, r *http.Request)
}
endpoints, err := handler.DataStore.Endpoint().Endpoints()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environments from database", err}
return httperror.InternalServerError("Unable to retrieve environments from database", err)
}
endpointGroups, err := handler.DataStore.EndpointGroup().EndpointGroups()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environment groups from database", err}
return httperror.InternalServerError("Unable to retrieve environment groups from database", err)
}
oldRelatedEndpoints := edge.EdgeGroupRelatedEndpoints(edgeGroup, endpoints, endpointGroups)
@ -99,7 +99,7 @@ func (handler *Handler) edgeGroupUpdate(w http.ResponseWriter, r *http.Request)
for _, endpointID := range payload.Endpoints {
endpoint, err := handler.DataStore.Endpoint().Endpoint(endpointID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environment from the database", err}
return httperror.InternalServerError("Unable to retrieve environment from the database", err)
}
if endpoint.Type == portainer.EdgeAgentOnDockerEnvironment || endpoint.Type == portainer.EdgeAgentOnKubernetesEnvironment {
@ -115,7 +115,7 @@ func (handler *Handler) edgeGroupUpdate(w http.ResponseWriter, r *http.Request)
err = handler.DataStore.EdgeGroup().UpdateEdgeGroup(edgeGroup.ID, edgeGroup)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist Edge group changes inside the database", err}
return httperror.InternalServerError("Unable to persist Edge group changes inside the database", err)
}
newRelatedEndpoints := edge.EdgeGroupRelatedEndpoints(edgeGroup, endpoints, endpointGroups)
@ -124,7 +124,7 @@ func (handler *Handler) edgeGroupUpdate(w http.ResponseWriter, r *http.Request)
for _, endpointID := range endpointsToUpdate {
err = handler.updateEndpoint(endpointID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist Environment relation changes inside the database", err}
return httperror.InternalServerError("Unable to persist Environment relation changes inside the database", err)
}
}

View File

@ -31,7 +31,7 @@ import (
func (handler *Handler) edgeJobCreate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
method, err := request.RetrieveQueryParameter(r, "method", false)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid query parameter: method. Valid values are: file or string", err}
return httperror.BadRequest("Invalid query parameter: method. Valid values are: file or string", err)
}
switch method {
@ -40,7 +40,7 @@ func (handler *Handler) edgeJobCreate(w http.ResponseWriter, r *http.Request) *h
case "file":
return handler.createEdgeJobFromFile(w, r)
default:
return &httperror.HandlerError{http.StatusBadRequest, "Invalid query parameter: method. Valid values are: file or string", errors.New(request.ErrInvalidQueryParameter)}
return httperror.BadRequest("Invalid query parameter: method. Valid values are: file or string", errors.New(request.ErrInvalidQueryParameter))
}
}
@ -80,14 +80,14 @@ func (handler *Handler) createEdgeJobFromFileContent(w http.ResponseWriter, r *h
var payload edgeJobCreateFromFileContentPayload
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
edgeJob := handler.createEdgeJobObjectFromFileContentPayload(&payload)
err = handler.addAndPersistEdgeJob(edgeJob, []byte(payload.FileContent))
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to schedule Edge job", err}
return httperror.InternalServerError("Unable to schedule Edge job", err)
}
return response.JSON(w, edgeJob)
@ -138,14 +138,14 @@ func (handler *Handler) createEdgeJobFromFile(w http.ResponseWriter, r *http.Req
payload := &edgeJobCreateFromFilePayload{}
err := payload.Validate(r)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
edgeJob := handler.createEdgeJobObjectFromFilePayload(payload)
err = handler.addAndPersistEdgeJob(edgeJob, payload.File)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to schedule Edge job", err}
return httperror.InternalServerError("Unable to schedule Edge job", err)
}
return response.JSON(w, edgeJob)

View File

@ -25,27 +25,27 @@ import (
func (handler *Handler) edgeJobDelete(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
edgeJobID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid Edge job identifier route variable", err}
return httperror.BadRequest("Invalid Edge job identifier route variable", err)
}
edgeJob, err := handler.DataStore.EdgeJob().EdgeJob(portainer.EdgeJobID(edgeJobID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an Edge job with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an Edge job with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an Edge job with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an Edge job with the specified identifier inside the database", err)
}
edgeJobFolder := handler.FileService.GetEdgeJobFolder(strconv.Itoa(edgeJobID))
err = handler.FileService.RemoveDirectory(edgeJobFolder)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to remove the files associated to the Edge job on the filesystem", err}
return httperror.InternalServerError("Unable to remove the files associated to the Edge job on the filesystem", err)
}
handler.ReverseTunnelService.RemoveEdgeJob(edgeJob.ID)
err = handler.DataStore.EdgeJob().DeleteEdgeJob(edgeJob.ID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to remove the Edge job from the database", err}
return httperror.InternalServerError("Unable to remove the Edge job from the database", err)
}
return response.Empty(w)

View File

@ -29,19 +29,19 @@ type edgeJobFileResponse struct {
func (handler *Handler) edgeJobFile(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
edgeJobID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid Edge job identifier route variable", err}
return httperror.BadRequest("Invalid Edge job identifier route variable", err)
}
edgeJob, err := handler.DataStore.EdgeJob().EdgeJob(portainer.EdgeJobID(edgeJobID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an Edge job with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an Edge job with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an Edge job with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an Edge job with the specified identifier inside the database", err)
}
edgeJobFileContent, err := handler.FileService.GetFileContent(edgeJob.ScriptPath, "")
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve Edge job script file from disk", err}
return httperror.InternalServerError("Unable to retrieve Edge job script file from disk", err)
}
return response.JSON(w, &edgeJobFileResponse{FileContent: string(edgeJobFileContent)})

View File

@ -30,14 +30,14 @@ type edgeJobInspectResponse struct {
func (handler *Handler) edgeJobInspect(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
edgeJobID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid Edge job identifier route variable", err}
return httperror.BadRequest("Invalid Edge job identifier route variable", err)
}
edgeJob, err := handler.DataStore.EdgeJob().EdgeJob(portainer.EdgeJobID(edgeJobID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an Edge job with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an Edge job with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an Edge job with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an Edge job with the specified identifier inside the database", err)
}
endpointIDs := []portainer.EndpointID{}

View File

@ -23,7 +23,7 @@ import (
func (handler *Handler) edgeJobList(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
edgeJobs, err := handler.DataStore.EdgeJob().EdgeJobs()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve Edge jobs from the database", err}
return httperror.InternalServerError("Unable to retrieve Edge jobs from the database", err)
}
return response.JSON(w, edgeJobs)

View File

@ -27,19 +27,19 @@ import (
func (handler *Handler) edgeJobTasksClear(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
edgeJobID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid Edge job identifier route variable", err}
return httperror.BadRequest("Invalid Edge job identifier route variable", err)
}
taskID, err := request.RetrieveNumericRouteVariableValue(r, "taskID")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid Task identifier route variable", err}
return httperror.BadRequest("Invalid Task identifier route variable", err)
}
edgeJob, err := handler.DataStore.EdgeJob().EdgeJob(portainer.EdgeJobID(edgeJobID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an Edge job with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an Edge job with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an Edge job with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an Edge job with the specified identifier inside the database", err)
}
endpointID := portainer.EndpointID(taskID)
@ -51,14 +51,14 @@ func (handler *Handler) edgeJobTasksClear(w http.ResponseWriter, r *http.Request
err = handler.FileService.ClearEdgeJobTaskLogs(strconv.Itoa(edgeJobID), strconv.Itoa(taskID))
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to clear log file from disk", err}
return httperror.InternalServerError("Unable to clear log file from disk", err)
}
handler.ReverseTunnelService.AddEdgeJob(endpointID, edgeJob)
err = handler.DataStore.EdgeJob().UpdateEdgeJob(edgeJob.ID, edgeJob)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist Edge job changes in the database", err}
return httperror.InternalServerError("Unable to persist Edge job changes in the database", err)
}
return response.Empty(w)

View File

@ -26,19 +26,19 @@ import (
func (handler *Handler) edgeJobTasksCollect(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
edgeJobID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid Edge job identifier route variable", err}
return httperror.BadRequest("Invalid Edge job identifier route variable", err)
}
taskID, err := request.RetrieveNumericRouteVariableValue(r, "taskID")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid Task identifier route variable", err}
return httperror.BadRequest("Invalid Task identifier route variable", err)
}
edgeJob, err := handler.DataStore.EdgeJob().EdgeJob(portainer.EdgeJobID(edgeJobID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an Edge job with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an Edge job with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an Edge job with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an Edge job with the specified identifier inside the database", err)
}
endpointID := portainer.EndpointID(taskID)
@ -52,7 +52,7 @@ func (handler *Handler) edgeJobTasksCollect(w http.ResponseWriter, r *http.Reque
err = handler.DataStore.EdgeJob().UpdateEdgeJob(edgeJob.ID, edgeJob)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist Edge job changes in the database", err}
return httperror.InternalServerError("Unable to persist Edge job changes in the database", err)
}
return response.Empty(w)

View File

@ -30,17 +30,17 @@ type fileResponse struct {
func (handler *Handler) edgeJobTaskLogsInspect(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
edgeJobID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid Edge job identifier route variable", err}
return httperror.BadRequest("Invalid Edge job identifier route variable", err)
}
taskID, err := request.RetrieveNumericRouteVariableValue(r, "taskID")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid Task identifier route variable", err}
return httperror.BadRequest("Invalid Task identifier route variable", err)
}
logFileContent, err := handler.FileService.GetEdgeJobTaskLogFileContent(strconv.Itoa(edgeJobID), strconv.Itoa(taskID))
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve log file from disk", err}
return httperror.InternalServerError("Unable to retrieve log file from disk", err)
}
return response.JSON(w, &fileResponse{FileContent: string(logFileContent)})

View File

@ -32,14 +32,14 @@ type taskContainer struct {
func (handler *Handler) edgeJobTasksList(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
edgeJobID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid Edge job identifier route variable", err}
return httperror.BadRequest("Invalid Edge job identifier route variable", err)
}
edgeJob, err := handler.DataStore.EdgeJob().EdgeJob(portainer.EdgeJobID(edgeJobID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an Edge job with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an Edge job with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an Edge job with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an Edge job with the specified identifier inside the database", err)
}
tasks := make([]taskContainer, 0)

View File

@ -45,30 +45,30 @@ func (payload *edgeJobUpdatePayload) Validate(r *http.Request) error {
func (handler *Handler) edgeJobUpdate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
edgeJobID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid Edge job identifier route variable", err}
return httperror.BadRequest("Invalid Edge job identifier route variable", err)
}
var payload edgeJobUpdatePayload
err = request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
edgeJob, err := handler.DataStore.EdgeJob().EdgeJob(portainer.EdgeJobID(edgeJobID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an Edge job with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an Edge job with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an Edge job with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an Edge job with the specified identifier inside the database", err)
}
err = handler.updateEdgeSchedule(edgeJob, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to update Edge job", err}
return httperror.InternalServerError("Unable to update Edge job", err)
}
err = handler.DataStore.EdgeJob().UpdateEdgeJob(edgeJob.ID, edgeJob)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist Edge job changes inside the database", err}
return httperror.InternalServerError("Unable to persist Edge job changes inside the database", err)
}
return response.JSON(w, edgeJob)

View File

@ -36,12 +36,12 @@ import (
func (handler *Handler) edgeStackCreate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
method, err := request.RetrieveQueryParameter(r, "method", false)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid query parameter: method", err}
return httperror.BadRequest("Invalid query parameter: method", err)
}
edgeStack, err := handler.createSwarmStack(method, r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to create Edge stack", err}
return httperror.InternalServerError("Unable to create Edge stack", err)
}
return response.JSON(w, edgeStack)

View File

@ -25,42 +25,42 @@ import (
func (handler *Handler) edgeStackDelete(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
edgeStackID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid edge stack identifier route variable", err}
return httperror.BadRequest("Invalid edge stack identifier route variable", err)
}
edgeStack, err := handler.DataStore.EdgeStack().EdgeStack(portainer.EdgeStackID(edgeStackID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an edge stack with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an edge stack with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an edge stack with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an edge stack with the specified identifier inside the database", err)
}
err = handler.DataStore.EdgeStack().DeleteEdgeStack(portainer.EdgeStackID(edgeStackID))
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to remove the edge stack from the database", err}
return httperror.InternalServerError("Unable to remove the edge stack from the database", err)
}
relationConfig, err := fetchEndpointRelationsConfig(handler.DataStore)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environments relations config from database", err}
return httperror.InternalServerError("Unable to retrieve environments relations config from database", err)
}
relatedEndpointIds, err := edge.EdgeStackRelatedEndpoints(edgeStack.EdgeGroups, relationConfig.endpoints, relationConfig.endpointGroups, relationConfig.edgeGroups)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve edge stack related environments from database", err}
return httperror.InternalServerError("Unable to retrieve edge stack related environments from database", err)
}
for _, endpointID := range relatedEndpointIds {
relation, err := handler.DataStore.EndpointRelation().EndpointRelation(endpointID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find environment relation in database", err}
return httperror.InternalServerError("Unable to find environment relation in database", err)
}
delete(relation.EdgeStacks, edgeStack.ID)
err = handler.DataStore.EndpointRelation().UpdateEndpointRelation(endpointID, relation)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist environment relation in database", err}
return httperror.InternalServerError("Unable to persist environment relation in database", err)
}
}

View File

@ -29,14 +29,14 @@ type stackFileResponse struct {
func (handler *Handler) edgeStackFile(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
stackID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid edge stack identifier route variable", err}
return httperror.BadRequest("Invalid edge stack identifier route variable", err)
}
stack, err := handler.DataStore.EdgeStack().EdgeStack(portainer.EdgeStackID(stackID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an edge stack with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an edge stack with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an edge stack with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an edge stack with the specified identifier inside the database", err)
}
fileName := stack.EntryPoint
@ -46,7 +46,7 @@ func (handler *Handler) edgeStackFile(w http.ResponseWriter, r *http.Request) *h
stackFileContent, err := handler.FileService.GetFileContent(stack.ProjectPath, fileName)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve Compose file from disk", err}
return httperror.InternalServerError("Unable to retrieve Compose file from disk", err)
}
return response.JSON(w, &stackFileResponse{StackFileContent: string(stackFileContent)})

View File

@ -25,14 +25,14 @@ import (
func (handler *Handler) edgeStackInspect(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
edgeStackID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid edge stack identifier route variable", err}
return httperror.BadRequest("Invalid edge stack identifier route variable", err)
}
edgeStack, err := handler.DataStore.EdgeStack().EdgeStack(portainer.EdgeStackID(edgeStackID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an edge stack with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an edge stack with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an edge stack with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an edge stack with the specified identifier inside the database", err)
}
return response.JSON(w, edgeStack)

View File

@ -22,7 +22,7 @@ import (
func (handler *Handler) edgeStackList(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
edgeStacks, err := handler.DataStore.EdgeStack().EdgeStacks()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve edge stacks from the database", err}
return httperror.InternalServerError("Unable to retrieve edge stacks from the database", err)
}
return response.JSON(w, edgeStacks)

View File

@ -11,7 +11,7 @@ import (
)
func (handler *Handler) handlerDBErr(err error, msg string) *httperror.HandlerError {
httpErr := &httperror.HandlerError{http.StatusInternalServerError, msg, err}
httpErr := httperror.InternalServerError(msg, err)
if handler.DataStore.IsErrObjectNotFound(err) {
httpErr.StatusCode = http.StatusNotFound
@ -35,17 +35,17 @@ func (handler *Handler) handlerDBErr(err error, msg string) *httperror.HandlerEr
func (handler *Handler) edgeStackStatusDelete(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
stackID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid stack identifier route variable", err}
return httperror.BadRequest("Invalid stack identifier route variable", err)
}
endpoint, err := middlewares.FetchEndpoint(r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve a valid endpoint from the handler context", err}
return httperror.InternalServerError("Unable to retrieve a valid endpoint from the handler context", err)
}
err = handler.requestBouncer.AuthorizedEdgeEndpointOperation(r, endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusForbidden, "Permission denied to access environment", err}
return httperror.Forbidden("Permission denied to access environment", err)
}
stack, err := handler.DataStore.EdgeStack().EdgeStack(portainer.EdgeStackID(stackID))
@ -57,7 +57,7 @@ func (handler *Handler) edgeStackStatusDelete(w http.ResponseWriter, r *http.Req
err = handler.DataStore.EdgeStack().UpdateEdgeStack(stack.ID, stack)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist the stack changes inside the database", err}
return httperror.InternalServerError("Unable to persist the stack changes inside the database", err)
}
return response.JSON(w, stack)

View File

@ -46,32 +46,32 @@ func (payload *updateStatusPayload) Validate(r *http.Request) error {
func (handler *Handler) edgeStackStatusUpdate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
stackID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid stack identifier route variable", err}
return httperror.BadRequest("Invalid stack identifier route variable", err)
}
stack, err := handler.DataStore.EdgeStack().EdgeStack(portainer.EdgeStackID(stackID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find a stack with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find a stack with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a stack with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find a stack with the specified identifier inside the database", err)
}
var payload updateStatusPayload
err = request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
endpoint, err := handler.DataStore.Endpoint().Endpoint(portainer.EndpointID(*payload.EndpointID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment with the specified identifier inside the database", err)
}
err = handler.requestBouncer.AuthorizedEdgeEndpointOperation(r, endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusForbidden, "Permission denied to access environment", err}
return httperror.Forbidden("Permission denied to access environment", err)
}
stack.Status[*payload.EndpointID] = portainer.EdgeStackStatus{
@ -82,7 +82,7 @@ func (handler *Handler) edgeStackStatusUpdate(w http.ResponseWriter, r *http.Req
err = handler.DataStore.EdgeStack().UpdateEdgeStack(stack.ID, stack)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist the stack changes inside the database", err}
return httperror.InternalServerError("Unable to persist the stack changes inside the database", err)
}
return response.JSON(w, stack)

View File

@ -49,36 +49,36 @@ func (payload *updateEdgeStackPayload) Validate(r *http.Request) error {
func (handler *Handler) edgeStackUpdate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
stackID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid stack identifier route variable", err}
return httperror.BadRequest("Invalid stack identifier route variable", err)
}
stack, err := handler.DataStore.EdgeStack().EdgeStack(portainer.EdgeStackID(stackID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find a stack with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find a stack with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a stack with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find a stack with the specified identifier inside the database", err)
}
var payload updateEdgeStackPayload
err = request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
relationConfig, err := fetchEndpointRelationsConfig(handler.DataStore)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environments relations config from database", err}
return httperror.InternalServerError("Unable to retrieve environments relations config from database", err)
}
relatedEndpointIds, err := edge.EdgeStackRelatedEndpoints(stack.EdgeGroups, relationConfig.endpoints, relationConfig.endpointGroups, relationConfig.edgeGroups)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve edge stack related environments from database", err}
return httperror.InternalServerError("Unable to retrieve edge stack related environments from database", err)
}
if payload.EdgeGroups != nil {
newRelated, err := edge.EdgeStackRelatedEndpoints(payload.EdgeGroups, relationConfig.endpoints, relationConfig.endpointGroups, relationConfig.edgeGroups)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve edge stack related environments from database", err}
return httperror.InternalServerError("Unable to retrieve edge stack related environments from database", err)
}
oldRelatedSet := endpointutils.EndpointSet(relatedEndpointIds)
@ -94,14 +94,14 @@ func (handler *Handler) edgeStackUpdate(w http.ResponseWriter, r *http.Request)
for endpointID := range endpointsToRemove {
relation, err := handler.DataStore.EndpointRelation().EndpointRelation(endpointID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find environment relation in database", err}
return httperror.InternalServerError("Unable to find environment relation in database", err)
}
delete(relation.EdgeStacks, stack.ID)
err = handler.DataStore.EndpointRelation().UpdateEndpointRelation(endpointID, relation)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist environment relation in database", err}
return httperror.InternalServerError("Unable to persist environment relation in database", err)
}
}
@ -115,14 +115,14 @@ func (handler *Handler) edgeStackUpdate(w http.ResponseWriter, r *http.Request)
for endpointID := range endpointsToAdd {
relation, err := handler.DataStore.EndpointRelation().EndpointRelation(endpointID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find environment relation in database", err}
return httperror.InternalServerError("Unable to find environment relation in database", err)
}
relation.EdgeStacks[stack.ID] = true
err = handler.DataStore.EndpointRelation().UpdateEndpointRelation(endpointID, relation)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist environment relation in database", err}
return httperror.InternalServerError("Unable to persist environment relation in database", err)
}
}
@ -134,7 +134,7 @@ func (handler *Handler) edgeStackUpdate(w http.ResponseWriter, r *http.Request)
// deployment type was changed - need to delete the old file
err = handler.FileService.RemoveDirectory(stack.ProjectPath)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to clear old files", err}
return httperror.InternalServerError("Unable to clear old files", err)
}
stack.EntryPoint = ""
@ -150,12 +150,12 @@ func (handler *Handler) edgeStackUpdate(w http.ResponseWriter, r *http.Request)
_, err = handler.FileService.StoreEdgeStackFileFromBytes(stackFolder, stack.EntryPoint, []byte(payload.StackFileContent))
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist updated Compose file on disk", err}
return httperror.InternalServerError("Unable to persist updated Compose file on disk", err)
}
err = handler.convertAndStoreKubeManifestIfNeeded(stack, relatedEndpointIds)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to convert and persist updated Kubernetes manifest file on disk", err}
return httperror.InternalServerError("Unable to convert and persist updated Kubernetes manifest file on disk", err)
}
} else {
@ -165,16 +165,16 @@ func (handler *Handler) edgeStackUpdate(w http.ResponseWriter, r *http.Request)
hasDockerEndpoint, err := hasDockerEndpoint(handler.DataStore.Endpoint(), relatedEndpointIds)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to check for existence of docker environment", err}
return httperror.InternalServerError("Unable to check for existence of docker environment", err)
}
if hasDockerEndpoint {
return &httperror.HandlerError{http.StatusBadRequest, "Edge stack with docker environment cannot be deployed with kubernetes config", err}
return httperror.BadRequest("Edge stack with docker environment cannot be deployed with kubernetes config", err)
}
_, err = handler.FileService.StoreEdgeStackFileFromBytes(stackFolder, stack.ManifestPath, []byte(payload.StackFileContent))
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist updated Compose file on disk", err}
return httperror.InternalServerError("Unable to persist updated Compose file on disk", err)
}
}
@ -185,7 +185,7 @@ func (handler *Handler) edgeStackUpdate(w http.ResponseWriter, r *http.Request)
err = handler.DataStore.EdgeStack().UpdateEdgeStack(stack.ID, stack)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist the stack changes inside the database", err}
return httperror.InternalServerError("Unable to persist the stack changes inside the database", err)
}
return response.JSON(w, stack)

View File

@ -29,7 +29,7 @@ type templateFileFormat struct {
func (handler *Handler) edgeTemplateList(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
settings, err := handler.DataStore.Settings().Settings()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve settings from the database", err}
return httperror.InternalServerError("Unable to retrieve settings from the database", err)
}
url := portainer.DefaultTemplatesURL
@ -40,14 +40,14 @@ func (handler *Handler) edgeTemplateList(w http.ResponseWriter, r *http.Request)
var templateData []byte
templateData, err = client.Get(url, 10)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve external templates", err}
return httperror.InternalServerError("Unable to retrieve external templates", err)
}
var templateFile templateFileFormat
err = json.Unmarshal(templateData, &templateFile)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to parse template file", err}
return httperror.InternalServerError("Unable to parse template file", err)
}
filteredTemplates := make([]portainer.Template, 0)

View File

@ -39,30 +39,30 @@ func (handler *Handler) endpointEdgeJobsLogs(w http.ResponseWriter, r *http.Requ
err = handler.requestBouncer.AuthorizedEdgeEndpointOperation(r, endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusForbidden, "Permission denied to access environment", err}
return httperror.Forbidden("Permission denied to access environment", err)
}
edgeJobID, err := request.RetrieveNumericRouteVariableValue(r, "jobID")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid edge job identifier route variable", err}
return httperror.BadRequest("Invalid edge job identifier route variable", err)
}
var payload logsPayload
err = request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
edgeJob, err := handler.DataStore.EdgeJob().EdgeJob(portainer.EdgeJobID(edgeJobID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an edge job with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an edge job with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an edge job with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an edge job with the specified identifier inside the database", err)
}
err = handler.FileService.StoreEdgeJobTaskLogFileFromBytes(strconv.Itoa(edgeJobID), strconv.Itoa(int(endpoint.ID)), []byte(payload.FileContent))
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to save task log to the filesystem", err}
return httperror.InternalServerError("Unable to save task log to the filesystem", err)
}
meta := edgeJob.Endpoints[endpoint.ID]
@ -75,7 +75,7 @@ func (handler *Handler) endpointEdgeJobsLogs(w http.ResponseWriter, r *http.Requ
handler.ReverseTunnelService.AddEdgeJob(endpoint.ID, edgeJob)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist edge job changes to the database", err}
return httperror.InternalServerError("Unable to persist edge job changes to the database", err)
}
return response.JSON(w, nil)

View File

@ -37,25 +37,25 @@ func (handler *Handler) endpointEdgeStackInspect(w http.ResponseWriter, r *http.
err = handler.requestBouncer.AuthorizedEdgeEndpointOperation(r, endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusForbidden, "Permission denied to access environment", err}
return httperror.Forbidden("Permission denied to access environment", err)
}
edgeStackID, err := request.RetrieveNumericRouteVariableValue(r, "stackId")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid edge stack identifier route variable", err}
return httperror.BadRequest("Invalid edge stack identifier route variable", err)
}
edgeStack, err := handler.DataStore.EdgeStack().EdgeStack(portainer.EdgeStackID(edgeStackID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an edge stack with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an edge stack with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an edge stack with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an edge stack with the specified identifier inside the database", err)
}
fileName := edgeStack.EntryPoint
if endpointutils.IsDockerEndpoint(endpoint) {
if fileName == "" {
return &httperror.HandlerError{http.StatusBadRequest, "Docker is not supported by this stack", errors.New("Docker is not supported by this stack")}
return httperror.BadRequest("Docker is not supported by this stack", errors.New("Docker is not supported by this stack"))
}
}
@ -63,13 +63,13 @@ func (handler *Handler) endpointEdgeStackInspect(w http.ResponseWriter, r *http.
fileName = edgeStack.ManifestPath
if fileName == "" {
return &httperror.HandlerError{http.StatusBadRequest, "Kubernetes is not supported by this stack", errors.New("Kubernetes is not supported by this stack")}
return httperror.BadRequest("Kubernetes is not supported by this stack", errors.New("Kubernetes is not supported by this stack"))
}
}
stackFileContent, err := handler.FileService.GetFileContent(edgeStack.ProjectPath, fileName)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve Compose file from disk", err}
return httperror.InternalServerError("Unable to retrieve Compose file from disk", err)
}
return response.JSON(w, configResponse{

View File

@ -71,7 +71,7 @@ func (handler *Handler) endpointEdgeStatusInspect(w http.ResponseWriter, r *http
err = handler.requestBouncer.AuthorizedEdgeEndpointOperation(r, endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusForbidden, "Permission denied to access environment", err}
return httperror.Forbidden("Permission denied to access environment", err)
}
if endpoint.EdgeID == "" {
@ -92,14 +92,14 @@ func (handler *Handler) endpointEdgeStatusInspect(w http.ResponseWriter, r *http
err = handler.DataStore.Endpoint().UpdateEndpoint(endpoint.ID, endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to Unable to persist environment changes inside the database", err}
return httperror.InternalServerError("Unable to Unable to persist environment changes inside the database", err)
}
checkinInterval := endpoint.EdgeCheckinInterval
if endpoint.EdgeCheckinInterval == 0 {
settings, err := handler.DataStore.Settings().Settings()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve settings from the database", err}
return httperror.InternalServerError("Unable to retrieve settings from the database", err)
}
checkinInterval = settings.EdgeAgentCheckinInterval
}
@ -167,7 +167,7 @@ func (handler *Handler) buildSchedules(endpointID portainer.EndpointID, tunnel p
file, err := handler.FileService.GetFileContent(job.ScriptPath, "")
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve Edge job script file", err}
return nil, httperror.InternalServerError("Unable to retrieve Edge job script file", err)
}
schedule.Script = base64.RawStdEncoding.EncodeToString(file)
@ -179,14 +179,14 @@ func (handler *Handler) buildSchedules(endpointID portainer.EndpointID, tunnel p
func (handler *Handler) buildEdgeStacks(endpointID portainer.EndpointID) ([]stackStatusResponse, *httperror.HandlerError) {
relation, err := handler.DataStore.EndpointRelation().EndpointRelation(endpointID)
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve relation object from the database", err}
return nil, httperror.InternalServerError("Unable to retrieve relation object from the database", err)
}
edgeStacksStatus := []stackStatusResponse{}
for stackID := range relation.EdgeStacks {
stack, err := handler.DataStore.EdgeStack().EdgeStack(stackID)
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve edge stack from the database", err}
return nil, httperror.InternalServerError("Unable to retrieve edge stack from the database", err)
}
stackStatus := stackStatusResponse{

View File

@ -49,7 +49,7 @@ func (handler *Handler) endpointGroupCreate(w http.ResponseWriter, r *http.Reque
var payload endpointGroupCreatePayload
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
endpointGroup := &portainer.EndpointGroup{
@ -62,12 +62,12 @@ func (handler *Handler) endpointGroupCreate(w http.ResponseWriter, r *http.Reque
err = handler.DataStore.EndpointGroup().Create(endpointGroup)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist the environment group inside the database", err}
return httperror.InternalServerError("Unable to persist the environment group inside the database", err)
}
endpoints, err := handler.DataStore.Endpoint().Endpoints()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environments from the database", err}
return httperror.InternalServerError("Unable to retrieve environments from the database", err)
}
for _, id := range payload.AssociatedEndpoints {
@ -77,12 +77,12 @@ func (handler *Handler) endpointGroupCreate(w http.ResponseWriter, r *http.Reque
err := handler.DataStore.Endpoint().UpdateEndpoint(endpoint.ID, &endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to update environment", err}
return httperror.InternalServerError("Unable to update environment", err)
}
err = handler.updateEndpointRelations(&endpoint, endpointGroup)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist environment relations changes inside the database", err}
return httperror.InternalServerError("Unable to persist environment relations changes inside the database", err)
}
break
@ -93,14 +93,14 @@ func (handler *Handler) endpointGroupCreate(w http.ResponseWriter, r *http.Reque
for _, tagID := range endpointGroup.TagIDs {
tag, err := handler.DataStore.Tag().Tag(tagID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve tag from the database", err}
return httperror.InternalServerError("Unable to retrieve tag from the database", err)
}
tag.EndpointGroups[endpointGroup.ID] = true
err = handler.DataStore.Tag().UpdateTag(tagID, tag)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist tag changes inside the database", err}
return httperror.InternalServerError("Unable to persist tag changes inside the database", err)
}
}

View File

@ -26,28 +26,28 @@ import (
func (handler *Handler) endpointGroupDelete(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointGroupID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment group identifier route variable", err}
return httperror.BadRequest("Invalid environment group identifier route variable", err)
}
if endpointGroupID == 1 {
return &httperror.HandlerError{http.StatusForbidden, "Unable to remove the default 'Unassigned' group", errors.New("Cannot remove the default environment group")}
return httperror.Forbidden("Unable to remove the default 'Unassigned' group", errors.New("Cannot remove the default environment group"))
}
endpointGroup, err := handler.DataStore.EndpointGroup().EndpointGroup(portainer.EndpointGroupID(endpointGroupID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment group with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment group with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment group with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment group with the specified identifier inside the database", err)
}
err = handler.DataStore.EndpointGroup().DeleteEndpointGroup(portainer.EndpointGroupID(endpointGroupID))
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to remove the environment group from the database", err}
return httperror.InternalServerError("Unable to remove the environment group from the database", err)
}
endpoints, err := handler.DataStore.Endpoint().Endpoints()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environment from the database", err}
return httperror.InternalServerError("Unable to retrieve environment from the database", err)
}
for _, endpoint := range endpoints {
@ -55,12 +55,12 @@ func (handler *Handler) endpointGroupDelete(w http.ResponseWriter, r *http.Reque
endpoint.GroupID = portainer.EndpointGroupID(1)
err = handler.DataStore.Endpoint().UpdateEndpoint(endpoint.ID, &endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to update environment", err}
return httperror.InternalServerError("Unable to update environment", err)
}
err = handler.updateEndpointRelations(&endpoint, nil)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist environment relations changes inside the database", err}
return httperror.InternalServerError("Unable to persist environment relations changes inside the database", err)
}
}
}
@ -68,14 +68,14 @@ func (handler *Handler) endpointGroupDelete(w http.ResponseWriter, r *http.Reque
for _, tagID := range endpointGroup.TagIDs {
tag, err := handler.DataStore.Tag().Tag(tagID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve tag from the database", err}
return httperror.InternalServerError("Unable to retrieve tag from the database", err)
}
delete(tag.EndpointGroups, endpointGroup.ID)
err = handler.DataStore.Tag().UpdateTag(tagID, tag)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist tag changes inside the database", err}
return httperror.InternalServerError("Unable to persist tag changes inside the database", err)
}
}

View File

@ -26,38 +26,38 @@ import (
func (handler *Handler) endpointGroupAddEndpoint(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointGroupID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment group identifier route variable", err}
return httperror.BadRequest("Invalid environment group identifier route variable", err)
}
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "endpointId")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment identifier route variable", err}
return httperror.BadRequest("Invalid environment identifier route variable", err)
}
endpointGroup, err := handler.DataStore.EndpointGroup().EndpointGroup(portainer.EndpointGroupID(endpointGroupID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment group with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment group with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment group with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment group with the specified identifier inside the database", err)
}
endpoint, err := handler.DataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment with the specified identifier inside the database", err)
}
endpoint.GroupID = endpointGroup.ID
err = handler.DataStore.Endpoint().UpdateEndpoint(endpoint.ID, endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist environment changes inside the database", err}
return httperror.InternalServerError("Unable to persist environment changes inside the database", err)
}
err = handler.updateEndpointRelations(endpoint, endpointGroup)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist environment relations changes inside the database", err}
return httperror.InternalServerError("Unable to persist environment relations changes inside the database", err)
}
return response.Empty(w)

View File

@ -25,38 +25,38 @@ import (
func (handler *Handler) endpointGroupDeleteEndpoint(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointGroupID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment group identifier route variable", err}
return httperror.BadRequest("Invalid environment group identifier route variable", err)
}
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "endpointId")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment identifier route variable", err}
return httperror.BadRequest("Invalid environment identifier route variable", err)
}
_, err = handler.DataStore.EndpointGroup().EndpointGroup(portainer.EndpointGroupID(endpointGroupID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment group with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment group with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment group with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment group with the specified identifier inside the database", err)
}
endpoint, err := handler.DataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment with the specified identifier inside the database", err)
}
endpoint.GroupID = portainer.EndpointGroupID(1)
err = handler.DataStore.Endpoint().UpdateEndpoint(endpoint.ID, endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist environment changes inside the database", err}
return httperror.InternalServerError("Unable to persist environment changes inside the database", err)
}
err = handler.updateEndpointRelations(endpoint, nil)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist environment relations changes inside the database", err}
return httperror.InternalServerError("Unable to persist environment relations changes inside the database", err)
}
return response.Empty(w)

View File

@ -26,14 +26,14 @@ import (
func (handler *Handler) endpointGroupInspect(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointGroupID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment group identifier route variable", err}
return httperror.BadRequest("Invalid environment group identifier route variable", err)
}
endpointGroup, err := handler.DataStore.EndpointGroup().EndpointGroup(portainer.EndpointGroupID(endpointGroupID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment group with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment group with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment group with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment group with the specified identifier inside the database", err)
}
return response.JSON(w, endpointGroup)

View File

@ -24,12 +24,12 @@ import (
func (handler *Handler) endpointGroupList(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointGroups, err := handler.DataStore.EndpointGroup().EndpointGroups()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environment groups from the database", err}
return httperror.InternalServerError("Unable to retrieve environment groups from the database", err)
}
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve info from request context", err}
return httperror.InternalServerError("Unable to retrieve info from request context", err)
}
endpointGroups = security.FilterEndpointGroups(endpointGroups, securityContext)

View File

@ -45,20 +45,20 @@ func (payload *endpointGroupUpdatePayload) Validate(r *http.Request) error {
func (handler *Handler) endpointGroupUpdate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointGroupID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment group identifier route variable", err}
return httperror.BadRequest("Invalid environment group identifier route variable", err)
}
var payload endpointGroupUpdatePayload
err = request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
endpointGroup, err := handler.DataStore.EndpointGroup().EndpointGroup(portainer.EndpointGroupID(endpointGroupID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment group with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment group with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment group with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment group with the specified identifier inside the database", err)
}
if payload.Name != "" {
@ -83,12 +83,12 @@ func (handler *Handler) endpointGroupUpdate(w http.ResponseWriter, r *http.Reque
for tagID := range removeTags {
tag, err := handler.DataStore.Tag().Tag(tagID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a tag inside the database", err}
return httperror.InternalServerError("Unable to find a tag inside the database", err)
}
delete(tag.EndpointGroups, endpointGroup.ID)
err = handler.DataStore.Tag().UpdateTag(tag.ID, tag)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist tag changes inside the database", err}
return httperror.InternalServerError("Unable to persist tag changes inside the database", err)
}
}
@ -96,14 +96,14 @@ func (handler *Handler) endpointGroupUpdate(w http.ResponseWriter, r *http.Reque
for _, tagID := range payload.TagIDs {
tag, err := handler.DataStore.Tag().Tag(tagID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a tag inside the database", err}
return httperror.InternalServerError("Unable to find a tag inside the database", err)
}
tag.EndpointGroups[endpointGroup.ID] = true
err = handler.DataStore.Tag().UpdateTag(tag.ID, tag)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist tag changes inside the database", err}
return httperror.InternalServerError("Unable to persist tag changes inside the database", err)
}
}
}
@ -123,7 +123,7 @@ func (handler *Handler) endpointGroupUpdate(w http.ResponseWriter, r *http.Reque
if updateAuthorizations {
endpoints, err := handler.DataStore.Endpoint().Endpoints()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environments from the database", err}
return httperror.InternalServerError("Unable to retrieve environments from the database", err)
}
for _, endpoint := range endpoints {
@ -131,7 +131,7 @@ func (handler *Handler) endpointGroupUpdate(w http.ResponseWriter, r *http.Reque
if endpoint.Type == portainer.KubernetesLocalEnvironment || endpoint.Type == portainer.AgentOnKubernetesEnvironment || endpoint.Type == portainer.EdgeAgentOnKubernetesEnvironment {
err = handler.AuthorizationService.CleanNAPWithOverridePolicies(&endpoint, endpointGroup)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to update user authorizations", err}
return httperror.InternalServerError("Unable to update user authorizations", err)
}
}
}
@ -140,13 +140,13 @@ func (handler *Handler) endpointGroupUpdate(w http.ResponseWriter, r *http.Reque
err = handler.DataStore.EndpointGroup().UpdateEndpointGroup(endpointGroup.ID, endpointGroup)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist environment group changes inside the database", err}
return httperror.InternalServerError("Unable to persist environment group changes inside the database", err)
}
if tagsChanged {
endpoints, err := handler.DataStore.Endpoint().Endpoints()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environments from the database", err}
return httperror.InternalServerError("Unable to retrieve environments from the database", err)
}
@ -154,7 +154,7 @@ func (handler *Handler) endpointGroupUpdate(w http.ResponseWriter, r *http.Reque
if endpoint.GroupID == endpointGroup.ID {
err = handler.updateEndpointRelations(&endpoint, endpointGroup)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist environment relations changes inside the database", err}
return httperror.InternalServerError("Unable to persist environment relations changes inside the database", err)
}
}
}

View File

@ -13,19 +13,19 @@ import (
func (handler *Handler) proxyRequestsToAzureAPI(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment identifier route variable", err}
return httperror.BadRequest("Invalid environment identifier route variable", err)
}
endpoint, err := handler.DataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment with the specified identifier inside the database", err)
}
err = handler.requestBouncer.AuthorizedEndpointOperation(r, endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusForbidden, "Permission denied to access environment", err}
return httperror.Forbidden("Permission denied to access environment", err)
}
var proxy http.Handler
@ -33,7 +33,7 @@ func (handler *Handler) proxyRequestsToAzureAPI(w http.ResponseWriter, r *http.R
if proxy == nil {
proxy, err = handler.ProxyManager.CreateAndRegisterEndpointProxy(endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to create proxy", err}
return httperror.InternalServerError("Unable to create proxy", err)
}
}

View File

@ -14,29 +14,29 @@ import (
func (handler *Handler) proxyRequestsToDockerAPI(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment identifier route variable", err}
return httperror.BadRequest("Invalid environment identifier route variable", err)
}
endpoint, err := handler.DataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment with the specified identifier inside the database", err)
}
err = handler.requestBouncer.AuthorizedEndpointOperation(r, endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusForbidden, "Permission denied to access environment", err}
return httperror.Forbidden("Permission denied to access environment", err)
}
if endpoint.Type == portainer.EdgeAgentOnDockerEnvironment {
if endpoint.EdgeID == "" {
return &httperror.HandlerError{http.StatusInternalServerError, "No Edge agent registered with the environment", errors.New("No agent available")}
return httperror.InternalServerError("No Edge agent registered with the environment", errors.New("No agent available"))
}
_, err := handler.ReverseTunnelService.GetActiveTunnel(endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to get the active tunnel", err}
return httperror.InternalServerError("Unable to get the active tunnel", err)
}
}
@ -45,7 +45,7 @@ func (handler *Handler) proxyRequestsToDockerAPI(w http.ResponseWriter, r *http.
if proxy == nil {
proxy, err = handler.ProxyManager.CreateAndRegisterEndpointProxy(endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to create proxy", err}
return httperror.InternalServerError("Unable to create proxy", err)
}
}

View File

@ -14,29 +14,29 @@ import (
func (handler *Handler) proxyRequestsToKubernetesAPI(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment identifier route variable", err}
return httperror.BadRequest("Invalid environment identifier route variable", err)
}
endpoint, err := handler.DataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment with the specified identifier inside the database", err)
}
err = handler.requestBouncer.AuthorizedEndpointOperation(r, endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusForbidden, "Permission denied to access environment", err}
return httperror.Forbidden("Permission denied to access environment", err)
}
if endpoint.Type == portainer.EdgeAgentOnKubernetesEnvironment {
if endpoint.EdgeID == "" {
return &httperror.HandlerError{http.StatusInternalServerError, "No Edge agent registered with the environment", errors.New("No agent available")}
return httperror.InternalServerError("No Edge agent registered with the environment", errors.New("No agent available"))
}
_, err := handler.ReverseTunnelService.GetActiveTunnel(endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to get the active tunnel", err}
return httperror.InternalServerError("Unable to get the active tunnel", err)
}
}
@ -45,7 +45,7 @@ func (handler *Handler) proxyRequestsToKubernetesAPI(w http.ResponseWriter, r *h
if proxy == nil {
proxy, err = handler.ProxyManager.CreateAndRegisterEndpointProxy(endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to create proxy", err}
return httperror.InternalServerError("Unable to create proxy", err)
}
}

View File

@ -31,18 +31,18 @@ import (
func (handler *Handler) endpointAssociationDelete(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment identifier route variable", err}
return httperror.BadRequest("Invalid environment identifier route variable", err)
}
endpoint, err := handler.DataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment with the specified identifier inside the database", err)
}
if endpoint.Type != portainer.EdgeAgentOnKubernetesEnvironment && endpoint.Type != portainer.EdgeAgentOnDockerEnvironment {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment type", errors.New("Invalid environment type")}
return httperror.BadRequest("Invalid environment type", errors.New("Invalid environment type"))
}
endpoint.EdgeID = ""
@ -51,12 +51,12 @@ func (handler *Handler) endpointAssociationDelete(w http.ResponseWriter, r *http
endpoint.EdgeKey, err = handler.updateEdgeKey(endpoint.EdgeKey)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Invalid EdgeKey", err}
return httperror.InternalServerError("Invalid EdgeKey", err)
}
err = handler.DataStore.Endpoint().UpdateEndpoint(portainer.EndpointID(endpointID), endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Failed persisting environment in database", err}
return httperror.InternalServerError("Failed persisting environment in database", err)
}
handler.ReverseTunnelService.SetTunnelStatusToIdle(endpoint.ID)

View File

@ -191,7 +191,7 @@ func (handler *Handler) endpointCreate(w http.ResponseWriter, r *http.Request) *
payload := &endpointCreatePayload{}
err := payload.Validate(r)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
isUnique, err := handler.isNameUnique(payload.Name, 0)
@ -210,17 +210,17 @@ func (handler *Handler) endpointCreate(w http.ResponseWriter, r *http.Request) *
endpointGroup, err := handler.DataStore.EndpointGroup().EndpointGroup(endpoint.GroupID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment group inside the database", err}
return httperror.InternalServerError("Unable to find an environment group inside the database", err)
}
edgeGroups, err := handler.DataStore.EdgeGroup().EdgeGroups()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve edge groups from the database", err}
return httperror.InternalServerError("Unable to retrieve edge groups from the database", err)
}
edgeStacks, err := handler.DataStore.EdgeStack().EdgeStacks()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve edge stacks from the database", err}
return httperror.InternalServerError("Unable to retrieve edge stacks from the database", err)
}
relationObject := &portainer.EndpointRelation{
@ -237,7 +237,7 @@ func (handler *Handler) endpointCreate(w http.ResponseWriter, r *http.Request) *
err = handler.DataStore.EndpointRelation().Create(relationObject)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist the relation object inside the database", err}
return httperror.InternalServerError("Unable to persist the relation object inside the database", err)
}
return response.JSON(w, endpoint)
@ -269,7 +269,7 @@ func (handler *Handler) createEndpoint(payload *endpointCreatePayload) (*portain
agentPlatform, version, err := agent.GetAgentVersionAndPlatform(payload.URL, tlsConfig)
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "Unable to get environment type", err}
return nil, httperror.InternalServerError("Unable to get environment type", err)
}
agentVersion = version
@ -297,7 +297,7 @@ func (handler *Handler) createAzureEndpoint(payload *endpointCreatePayload) (*po
httpClient := client.NewHTTPClient()
_, err := httpClient.ExecuteAzureAuthenticationRequest(&credentials)
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "Unable to authenticate against Azure", err}
return nil, httperror.InternalServerError("Unable to authenticate against Azure", err)
}
endpointID := handler.DataStore.Endpoint().GetNextIdentifier()
@ -320,7 +320,7 @@ func (handler *Handler) createAzureEndpoint(payload *endpointCreatePayload) (*po
err = handler.saveEndpointAndUpdateAuthorizations(endpoint)
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "An error occurred while trying to create the environment", err}
return nil, httperror.InternalServerError("An error occurred while trying to create the environment", err)
}
return endpoint, nil
@ -360,13 +360,13 @@ func (handler *Handler) createEdgeAgentEndpoint(payload *endpointCreatePayload)
settings, err := handler.DataStore.Settings().Settings()
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve the settings from the database", err}
return nil, httperror.InternalServerError("Unable to retrieve the settings from the database", err)
}
if settings.EnforceEdgeID {
edgeID, err := uuid.NewV4()
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "Cannot generate the Edge ID", err}
return nil, httperror.InternalServerError("Cannot generate the Edge ID", err)
}
endpoint.EdgeID = edgeID.String()
@ -374,7 +374,7 @@ func (handler *Handler) createEdgeAgentEndpoint(payload *endpointCreatePayload)
err = handler.saveEndpointAndUpdateAuthorizations(endpoint)
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "An error occured while trying to create the environment", err}
return nil, httperror.InternalServerError("An error occured while trying to create the environment", err)
}
return endpoint, nil
@ -498,12 +498,12 @@ func (handler *Handler) snapshotAndPersistEndpoint(endpoint *portainer.Endpoint)
if strings.Contains(err.Error(), "Invalid request signature") || strings.Contains(err.Error(), "unknown") {
err = errors.New("agent already paired with another Portainer instance")
}
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to initiate communications with environment", err}
return httperror.InternalServerError("Unable to initiate communications with environment", err)
}
err = handler.saveEndpointAndUpdateAuthorizations(endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "An error occured while trying to create the environment", err}
return httperror.InternalServerError("An error occured while trying to create the environment", err)
}
return nil
@ -551,7 +551,7 @@ func (handler *Handler) storeTLSFiles(endpoint *portainer.Endpoint, payload *end
if !payload.TLSSkipVerify {
caCertPath, err := handler.FileService.StoreTLSFileFromBytes(folder, portainer.TLSFileCA, payload.TLSCACertFile)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist TLS CA certificate file on disk", err}
return httperror.InternalServerError("Unable to persist TLS CA certificate file on disk", err)
}
endpoint.TLSConfig.TLSCACertPath = caCertPath
}
@ -559,13 +559,13 @@ func (handler *Handler) storeTLSFiles(endpoint *portainer.Endpoint, payload *end
if !payload.TLSSkipClientVerify {
certPath, err := handler.FileService.StoreTLSFileFromBytes(folder, portainer.TLSFileCert, payload.TLSCertFile)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist TLS certificate file on disk", err}
return httperror.InternalServerError("Unable to persist TLS certificate file on disk", err)
}
endpoint.TLSConfig.TLSCertPath = certPath
keyPath, err := handler.FileService.StoreTLSFileFromBytes(folder, portainer.TLSFileKey, payload.TLSKeyFile)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist TLS key file on disk", err}
return httperror.InternalServerError("Unable to persist TLS key file on disk", err)
}
endpoint.TLSConfig.TLSKeyPath = keyPath
}

View File

@ -30,7 +30,7 @@ func (handler *Handler) endpointCreateGlobalKey(w http.ResponseWriter, r *http.R
endpoints, err := handler.DataStore.Endpoint().Endpoints()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve the endpoints from the database", err}
return httperror.InternalServerError("Unable to retrieve the endpoints from the database", err)
}
for _, endpoint := range endpoints {
@ -39,5 +39,5 @@ func (handler *Handler) endpointCreateGlobalKey(w http.ResponseWriter, r *http.R
}
}
return &httperror.HandlerError{http.StatusNotFound, "Unable to find the endpoint in the database", err}
return httperror.NotFound("Unable to find the endpoint in the database", err)
}

View File

@ -27,57 +27,57 @@ import (
func (handler *Handler) endpointDelete(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment identifier route variable", err}
return httperror.BadRequest("Invalid environment identifier route variable", err)
}
if handler.demoService.IsDemoEnvironment(portainer.EndpointID(endpointID)) {
return &httperror.HandlerError{http.StatusForbidden, httperrors.ErrNotAvailableInDemo.Error(), httperrors.ErrNotAvailableInDemo}
return httperror.Forbidden(httperrors.ErrNotAvailableInDemo.Error(), httperrors.ErrNotAvailableInDemo)
}
endpoint, err := handler.DataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment with the specified identifier inside the database", err)
}
if endpoint.TLSConfig.TLS {
folder := strconv.Itoa(endpointID)
err = handler.FileService.DeleteTLSFiles(folder)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to remove TLS files from disk", err}
return httperror.InternalServerError("Unable to remove TLS files from disk", err)
}
}
err = handler.DataStore.Endpoint().DeleteEndpoint(portainer.EndpointID(endpointID))
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to remove environment from the database", err}
return httperror.InternalServerError("Unable to remove environment from the database", err)
}
handler.ProxyManager.DeleteEndpointProxy(endpoint.ID)
err = handler.DataStore.EndpointRelation().DeleteEndpointRelation(endpoint.ID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to remove environment relation from the database", err}
return httperror.InternalServerError("Unable to remove environment relation from the database", err)
}
for _, tagID := range endpoint.TagIDs {
tag, err := handler.DataStore.Tag().Tag(tagID)
if err != nil {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find tag inside the database", err}
return httperror.NotFound("Unable to find tag inside the database", err)
}
delete(tag.Endpoints, endpoint.ID)
err = handler.DataStore.Tag().UpdateTag(tagID, tag)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist tag relation inside the database", err}
return httperror.InternalServerError("Unable to persist tag relation inside the database", err)
}
}
edgeGroups, err := handler.DataStore.EdgeGroup().EdgeGroups()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve edge groups from the database", err}
return httperror.InternalServerError("Unable to retrieve edge groups from the database", err)
}
for idx := range edgeGroups {
@ -87,14 +87,14 @@ func (handler *Handler) endpointDelete(w http.ResponseWriter, r *http.Request) *
edgeGroup.Endpoints = removeElement(edgeGroup.Endpoints, endpointIdx)
err = handler.DataStore.EdgeGroup().UpdateEdgeGroup(edgeGroup.ID, edgeGroup)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to update edge group", err}
return httperror.InternalServerError("Unable to update edge group", err)
}
}
}
edgeStacks, err := handler.DataStore.EdgeStack().EdgeStacks()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve edge stacks from the database", err}
return httperror.InternalServerError("Unable to retrieve edge stacks from the database", err)
}
for idx := range edgeStacks {
@ -103,14 +103,14 @@ func (handler *Handler) endpointDelete(w http.ResponseWriter, r *http.Request) *
delete(edgeStack.Status, endpoint.ID)
err = handler.DataStore.EdgeStack().UpdateEdgeStack(edgeStack.ID, edgeStack)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to update edge stack", err}
return httperror.InternalServerError("Unable to update edge stack", err)
}
}
}
registries, err := handler.DataStore.Registry().Registries()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve registries from the database", err}
return httperror.InternalServerError("Unable to retrieve registries from the database", err)
}
for idx := range registries {
@ -119,7 +119,7 @@ func (handler *Handler) endpointDelete(w http.ResponseWriter, r *http.Request) *
delete(registry.RegistryAccesses, endpoint.ID)
err = handler.DataStore.Registry().UpdateRegistry(registry.ID, registry)
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Unable to update registry accesses", Err: err}
return httperror.InternalServerError("Unable to update registry accesses", err)
}
}
}

View File

@ -42,23 +42,23 @@ type dockerhubStatusResponse struct {
func (handler *Handler) endpointDockerhubStatus(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment identifier route variable", err}
return httperror.BadRequest("Invalid environment identifier route variable", err)
}
endpoint, err := handler.DataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment with the specified identifier inside the database", err)
}
if !endpointutils.IsLocalEndpoint(endpoint) {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment type", errors.New("Invalid environment type")}
return httperror.BadRequest("Invalid environment type", errors.New("Invalid environment type"))
}
registryID, err := request.RetrieveNumericRouteVariableValue(r, "registryId")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid registry identifier route variable", err}
return httperror.BadRequest("Invalid registry identifier route variable", err)
}
var registry *portainer.Registry
@ -68,25 +68,25 @@ func (handler *Handler) endpointDockerhubStatus(w http.ResponseWriter, r *http.R
} else {
registry, err = handler.DataStore.Registry().Registry(portainer.RegistryID(registryID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find a registry with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find a registry with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a registry with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find a registry with the specified identifier inside the database", err)
}
if registry.Type != portainer.DockerHubRegistry {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid registry type", errors.New("Invalid registry type")}
return httperror.BadRequest("Invalid registry type", errors.New("Invalid registry type"))
}
}
httpClient := client.NewHTTPClient()
token, err := getDockerHubToken(httpClient, registry)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve DockerHub token from DockerHub", err}
return httperror.InternalServerError("Unable to retrieve DockerHub token from DockerHub", err)
}
resp, err := getDockerHubLimits(httpClient, token)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve DockerHub rate limits from DockerHub", err}
return httperror.InternalServerError("Unable to retrieve DockerHub rate limits from DockerHub", err)
}
return response.JSON(w, resp)

View File

@ -26,19 +26,19 @@ import (
func (handler *Handler) endpointInspect(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment identifier route variable", err}
return httperror.BadRequest("Invalid environment identifier route variable", err)
}
endpoint, err := handler.DataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment with the specified identifier inside the database", err)
}
err = handler.requestBouncer.AuthorizedEndpointOperation(r, endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusForbidden, "Permission denied to access environment", err}
return httperror.Forbidden("Permission denied to access environment", err)
}
hideFields(endpoint)

View File

@ -28,31 +28,31 @@ import (
func (handler *Handler) endpointRegistriesList(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve info from request context", err}
return httperror.InternalServerError("Unable to retrieve info from request context", err)
}
user, err := handler.DataStore.User().User(securityContext.UserID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve user from the database", err}
return httperror.InternalServerError("Unable to retrieve user from the database", err)
}
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Invalid environment identifier route variable", Err: err}
return httperror.BadRequest("Invalid environment identifier route variable", err)
}
endpoint, err := handler.DataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment with the specified identifier inside the database", err)
}
isAdmin := securityContext.IsAdmin
registries, err := handler.DataStore.Registry().Registries()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve registries from the database", err}
return httperror.InternalServerError("Unable to retrieve registries from the database", err)
}
registries, handleError := handler.filterRegistriesByAccess(r, registries, endpoint, user, securityContext.UserMemberships)
@ -79,16 +79,16 @@ func (handler *Handler) filterKubernetesEndpointRegistries(r *http.Request, regi
namespaceParam, _ := request.RetrieveQueryParameter(r, "namespace", true)
isAdmin, err := security.IsAdmin(r)
if err != nil {
return nil, &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Unable to check user role", Err: err}
return nil, httperror.InternalServerError("Unable to check user role", err)
}
if namespaceParam != "" {
authorized, err := handler.isNamespaceAuthorized(endpoint, namespaceParam, user.ID, memberships, isAdmin)
if err != nil {
return nil, &httperror.HandlerError{StatusCode: http.StatusNotFound, Message: "Unable to check for namespace authorization", Err: err}
return nil, httperror.NotFound("Unable to check for namespace authorization", err)
}
if !authorized {
return nil, &httperror.HandlerError{StatusCode: http.StatusForbidden, Message: "User is not authorized to use namespace", Err: errors.New("user is not authorized to use namespace")}
return nil, httperror.Forbidden("User is not authorized to use namespace", errors.New("user is not authorized to use namespace"))
}
return filterRegistriesByNamespaces(registries, endpoint.ID, []string{namespaceParam}), nil
@ -154,15 +154,15 @@ func registryAccessPoliciesContainsNamespace(registryAccess portainer.RegistryAc
func (handler *Handler) filterKubernetesRegistriesByUserRole(r *http.Request, registries []portainer.Registry, endpoint *portainer.Endpoint, user *portainer.User) ([]portainer.Registry, *httperror.HandlerError) {
err := handler.requestBouncer.AuthorizedEndpointOperation(r, endpoint)
if err == security.ErrAuthorizationRequired {
return nil, &httperror.HandlerError{StatusCode: http.StatusForbidden, Message: "User is not authorized", Err: errors.New("missing namespace query parameter")}
return nil, httperror.Forbidden("User is not authorized", errors.New("missing namespace query parameter"))
}
if err != nil {
return nil, &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Unable to retrieve info from request context", Err: err}
return nil, httperror.InternalServerError("Unable to retrieve info from request context", err)
}
userNamespaces, err := handler.userNamespaces(endpoint, user)
if err != nil {
return nil, &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "unable to retrieve user namespaces", Err: err}
return nil, httperror.InternalServerError("unable to retrieve user namespaces", err)
}
return filterRegistriesByNamespaces(registries, endpoint.ID, userNamespaces), nil

View File

@ -40,46 +40,46 @@ func (payload *registryAccessPayload) Validate(r *http.Request) error {
func (handler *Handler) endpointRegistryAccess(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Invalid environment identifier route variable", Err: err}
return httperror.BadRequest("Invalid environment identifier route variable", err)
}
registryID, err := request.RetrieveNumericRouteVariableValue(r, "registryId")
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Invalid registry identifier route variable", Err: err}
return httperror.BadRequest("Invalid registry identifier route variable", err)
}
endpoint, err := handler.DataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{StatusCode: http.StatusNotFound, Message: "Unable to find an environment with the specified identifier inside the database", Err: err}
return httperror.NotFound("Unable to find an environment with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Unable to find an environment with the specified identifier inside the database", Err: err}
return httperror.InternalServerError("Unable to find an environment with the specified identifier inside the database", err)
}
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve info from request context", err}
return httperror.InternalServerError("Unable to retrieve info from request context", err)
}
err = handler.requestBouncer.AuthorizedEndpointOperation(r, endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusForbidden, "Permission denied to access environment", err}
return httperror.Forbidden("Permission denied to access environment", err)
}
if !securityContext.IsAdmin {
return &httperror.HandlerError{StatusCode: http.StatusForbidden, Message: "User is not authorized", Err: err}
return httperror.Forbidden("User is not authorized", err)
}
registry, err := handler.DataStore.Registry().Registry(portainer.RegistryID(registryID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{StatusCode: http.StatusNotFound, Message: "Unable to find an environment with the specified identifier inside the database", Err: err}
return httperror.NotFound("Unable to find an environment with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Unable to find an environment with the specified identifier inside the database", Err: err}
return httperror.InternalServerError("Unable to find an environment with the specified identifier inside the database", err)
}
var payload registryAccessPayload
err = request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Invalid request payload", Err: err}
return httperror.BadRequest("Invalid request payload", err)
}
if registry.RegistryAccesses == nil {
@ -95,7 +95,7 @@ func (handler *Handler) endpointRegistryAccess(w http.ResponseWriter, r *http.Re
if endpoint.Type == portainer.KubernetesLocalEnvironment || endpoint.Type == portainer.AgentOnKubernetesEnvironment || endpoint.Type == portainer.EdgeAgentOnKubernetesEnvironment {
err := handler.updateKubeAccess(endpoint, registry, registryAccess.Namespaces, payload.Namespaces)
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Unable to update kube access policies", Err: err}
return httperror.InternalServerError("Unable to update kube access policies", err)
}
registryAccess.Namespaces = payload.Namespaces

View File

@ -53,20 +53,20 @@ func (payload *endpointSettingsUpdatePayload) Validate(r *http.Request) error {
func (handler *Handler) endpointSettingsUpdate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment identifier route variable", err}
return httperror.BadRequest("Invalid environment identifier route variable", err)
}
var payload endpointSettingsUpdatePayload
err = request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
endpoint, err := handler.DataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment with the specified identifier inside the database", err)
}
securitySettings := endpoint.SecuritySettings
@ -111,7 +111,7 @@ func (handler *Handler) endpointSettingsUpdate(w http.ResponseWriter, r *http.Re
err = handler.DataStore.Endpoint().UpdateEndpoint(portainer.EndpointID(endpointID), endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Failed persisting environment in database", err}
return httperror.InternalServerError("Failed persisting environment in database", err)
}
return response.JSON(w, endpoint)

View File

@ -27,25 +27,25 @@ import (
func (handler *Handler) endpointSnapshot(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment identifier route variable", err}
return httperror.BadRequest("Invalid environment identifier route variable", err)
}
endpoint, err := handler.DataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment with the specified identifier inside the database", err)
}
if !snapshot.SupportDirectSnapshot(endpoint) {
return &httperror.HandlerError{http.StatusBadRequest, "Snapshots not supported for this environment", errors.New("Snapshots not supported for this environment")}
return httperror.BadRequest("Snapshots not supported for this environment", errors.New("Snapshots not supported for this environment"))
}
snapshotError := handler.SnapshotService.SnapshotEndpoint(endpoint)
latestEndpointReference, err := handler.DataStore.Endpoint().Endpoint(endpoint.ID)
if latestEndpointReference == nil {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment with the specified identifier inside the database", err)
}
latestEndpointReference.Status = portainer.EndpointStatusUp
@ -59,7 +59,7 @@ func (handler *Handler) endpointSnapshot(w http.ResponseWriter, r *http.Request)
err = handler.DataStore.Endpoint().UpdateEndpoint(latestEndpointReference.ID, latestEndpointReference)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist environment changes inside the database", err}
return httperror.InternalServerError("Unable to persist environment changes inside the database", err)
}
return response.Empty(w)

View File

@ -23,7 +23,7 @@ import (
func (handler *Handler) endpointSnapshots(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpoints, err := handler.DataStore.Endpoint().Endpoints()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environments from the database", err}
return httperror.InternalServerError("Unable to retrieve environments from the database", err)
}
for _, endpoint := range endpoints {
@ -51,7 +51,7 @@ func (handler *Handler) endpointSnapshots(w http.ResponseWriter, r *http.Request
err = handler.DataStore.Endpoint().UpdateEndpoint(latestEndpointReference.ID, latestEndpointReference)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist environment changes inside the database", err}
return httperror.InternalServerError("Unable to persist environment changes inside the database", err)
}
}

View File

@ -12,7 +12,7 @@ import (
func (handler *Handler) endpointStatusInspect(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment identifier route variable", err}
return httperror.BadRequest("Invalid environment identifier route variable", err)
}
url := fmt.Sprintf("/api/endpoints/%d/edge/status", endpointID)

View File

@ -73,20 +73,20 @@ func (payload *endpointUpdatePayload) Validate(r *http.Request) error {
func (handler *Handler) endpointUpdate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment identifier route variable", err}
return httperror.BadRequest("Invalid environment identifier route variable", err)
}
var payload endpointUpdatePayload
err = request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
endpoint, err := handler.DataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment with the specified identifier inside the database", err)
}
if payload.Name != nil {
@ -141,13 +141,13 @@ func (handler *Handler) endpointUpdate(w http.ResponseWriter, r *http.Request) *
for tagID := range removeTags {
tag, err := handler.DataStore.Tag().Tag(tagID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a tag inside the database", err}
return httperror.InternalServerError("Unable to find a tag inside the database", err)
}
delete(tag.Endpoints, endpoint.ID)
err = handler.DataStore.Tag().UpdateTag(tag.ID, tag)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist tag changes inside the database", err}
return httperror.InternalServerError("Unable to persist tag changes inside the database", err)
}
}
@ -155,14 +155,14 @@ func (handler *Handler) endpointUpdate(w http.ResponseWriter, r *http.Request) *
for _, tagID := range payload.TagIDs {
tag, err := handler.DataStore.Tag().Tag(tagID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a tag inside the database", err}
return httperror.InternalServerError("Unable to find a tag inside the database", err)
}
tag.Endpoints[endpoint.ID] = true
err = handler.DataStore.Tag().UpdateTag(tag.ID, tag)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist tag changes inside the database", err}
return httperror.InternalServerError("Unable to persist tag changes inside the database", err)
}
}
}
@ -217,7 +217,7 @@ func (handler *Handler) endpointUpdate(w http.ResponseWriter, r *http.Request) *
httpClient := client.NewHTTPClient()
_, authErr := httpClient.ExecuteAzureAuthenticationRequest(&credentials)
if authErr != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to authenticate against Azure", authErr}
return httperror.InternalServerError("Unable to authenticate against Azure", authErr)
}
endpoint.AzureCredentials = credentials
}
@ -261,7 +261,7 @@ func (handler *Handler) endpointUpdate(w http.ResponseWriter, r *http.Request) *
endpoint.TLSConfig.TLSKeyPath = ""
err = handler.FileService.DeleteTLSFiles(folder)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to remove TLS files from disk", err}
return httperror.InternalServerError("Unable to remove TLS files from disk", err)
}
}
@ -275,7 +275,7 @@ func (handler *Handler) endpointUpdate(w http.ResponseWriter, r *http.Request) *
handler.ProxyManager.DeleteEndpointProxy(endpoint.ID)
_, err = handler.ProxyManager.CreateAndRegisterEndpointProxy(endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to register HTTP proxy for the environment", err}
return httperror.InternalServerError("Unable to register HTTP proxy for the environment", err)
}
}
@ -283,35 +283,35 @@ func (handler *Handler) endpointUpdate(w http.ResponseWriter, r *http.Request) *
if endpoint.Type == portainer.KubernetesLocalEnvironment || endpoint.Type == portainer.AgentOnKubernetesEnvironment || endpoint.Type == portainer.EdgeAgentOnKubernetesEnvironment {
err = handler.AuthorizationService.CleanNAPWithOverridePolicies(endpoint, nil)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to update user authorizations", err}
return httperror.InternalServerError("Unable to update user authorizations", err)
}
}
}
err = handler.DataStore.Endpoint().UpdateEndpoint(endpoint.ID, endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist environment changes inside the database", err}
return httperror.InternalServerError("Unable to persist environment changes inside the database", err)
}
if (endpoint.Type == portainer.EdgeAgentOnDockerEnvironment || endpoint.Type == portainer.EdgeAgentOnKubernetesEnvironment) && (groupIDChanged || tagsChanged) {
relation, err := handler.DataStore.EndpointRelation().EndpointRelation(endpoint.ID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find environment relation inside the database", err}
return httperror.InternalServerError("Unable to find environment relation inside the database", err)
}
endpointGroup, err := handler.DataStore.EndpointGroup().EndpointGroup(endpoint.GroupID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find environment group inside the database", err}
return httperror.InternalServerError("Unable to find environment group inside the database", err)
}
edgeGroups, err := handler.DataStore.EdgeGroup().EdgeGroups()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve edge groups from the database", err}
return httperror.InternalServerError("Unable to retrieve edge groups from the database", err)
}
edgeStacks, err := handler.DataStore.EdgeStack().EdgeStacks()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve edge stacks from the database", err}
return httperror.InternalServerError("Unable to retrieve edge stacks from the database", err)
}
currentEdgeStackSet := map[portainer.EdgeStackID]bool{}
@ -325,7 +325,7 @@ func (handler *Handler) endpointUpdate(w http.ResponseWriter, r *http.Request) *
err = handler.DataStore.EndpointRelation().UpdateEndpointRelation(endpoint.ID, relation)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist environment relation changes inside the database", err}
return httperror.InternalServerError("Unable to persist environment relation changes inside the database", err)
}
}

View File

@ -87,22 +87,22 @@ func NewTemplateHandler(bouncer requestBouncer, helmPackageManager libhelm.HelmP
func (handler *Handler) getHelmClusterAccess(r *http.Request) (*options.KubernetesClusterAccess, *httperror.HandlerError) {
endpoint, err := middlewares.FetchEndpoint(r)
if err != nil {
return nil, &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment on request context", err}
return nil, httperror.NotFound("Unable to find an environment on request context", err)
}
tokenData, err := security.RetrieveTokenData(r)
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve user authentication token", err}
return nil, httperror.InternalServerError("Unable to retrieve user authentication token", err)
}
bearerToken, err := handler.jwtService.GenerateToken(tokenData)
if err != nil {
return nil, &httperror.HandlerError{http.StatusUnauthorized, "Unauthorized", err}
return nil, httperror.Unauthorized("Unauthorized", err)
}
sslSettings, err := handler.dataStore.SSLSettings().Settings()
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve settings from the database", err}
return nil, httperror.InternalServerError("Unable to retrieve settings from the database", err)
}
hostURL := "localhost"

View File

@ -28,7 +28,7 @@ import (
func (handler *Handler) helmDelete(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
release, err := request.RetrieveRouteVariableValue(r, "release")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "No release specified", err}
return httperror.BadRequest("No release specified", err)
}
clusterAccess, httperr := handler.getHelmClusterAccess(r)
@ -48,7 +48,7 @@ func (handler *Handler) helmDelete(w http.ResponseWriter, r *http.Request) *http
err = handler.helmPackageManager.Uninstall(uninstallOpts)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Helm returned an error", err}
return httperror.InternalServerError("Helm returned an error", err)
}
return response.Empty(w)

View File

@ -53,20 +53,12 @@ func (handler *Handler) helmInstall(w http.ResponseWriter, r *http.Request) *htt
var payload installChartPayload
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{
StatusCode: http.StatusBadRequest,
Message: "Invalid Helm install payload",
Err: err,
}
return httperror.BadRequest("Invalid Helm install payload", err)
}
release, err := handler.installChart(r, payload)
if err != nil {
return &httperror.HandlerError{
StatusCode: http.StatusInternalServerError,
Message: "Unable to install a chart",
Err: err,
}
return httperror.InternalServerError("Unable to install a chart", err)
}
w.WriteHeader(http.StatusCreated)

View File

@ -58,7 +58,7 @@ func (handler *Handler) helmList(w http.ResponseWriter, r *http.Request) *httper
releases, err := handler.helmPackageManager.List(listOpts)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Helm returned an error", err}
return httperror.InternalServerError("Helm returned an error", err)
}
return response.JSON(w, releases)

View File

@ -28,12 +28,12 @@ import (
func (handler *Handler) helmRepoSearch(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
repo := r.URL.Query().Get("repo")
if repo == "" {
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Bad request", Err: errors.New("missing `repo` query parameter")}
return httperror.BadRequest("Bad request", errors.New("missing `repo` query parameter"))
}
_, err := url.ParseRequestURI(repo)
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Bad request", Err: errors.Wrap(err, fmt.Sprintf("provided URL %q is not valid", repo))}
return httperror.BadRequest("Bad request", errors.Wrap(err, fmt.Sprintf("provided URL %q is not valid", repo)))
}
searchOpts := options.SearchRepoOptions{
@ -42,11 +42,7 @@ func (handler *Handler) helmRepoSearch(w http.ResponseWriter, r *http.Request) *
result, err := handler.helmPackageManager.SearchRepo(searchOpts)
if err != nil {
return &httperror.HandlerError{
StatusCode: http.StatusInternalServerError,
Message: "Search failed",
Err: err,
}
return httperror.InternalServerError("Search failed", err)
}
w.Header().Set("Content-Type", "text/plain")

View File

@ -32,16 +32,16 @@ import (
func (handler *Handler) helmShow(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
repo := r.URL.Query().Get("repo")
if repo == "" {
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Bad request", Err: errors.New("missing `repo` query parameter")}
return httperror.BadRequest("Bad request", errors.New("missing `repo` query parameter"))
}
_, err := url.ParseRequestURI(repo)
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Bad request", Err: errors.Wrap(err, fmt.Sprintf("provided URL %q is not valid", repo))}
return httperror.BadRequest("Bad request", errors.Wrap(err, fmt.Sprintf("provided URL %q is not valid", repo)))
}
chart := r.URL.Query().Get("chart")
if chart == "" {
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Bad request", Err: errors.New("missing `chart` query parameter")}
return httperror.BadRequest("Bad request", errors.New("missing `chart` query parameter"))
}
cmd, err := request.RetrieveRouteVariableValue(r, "command")
@ -57,11 +57,7 @@ func (handler *Handler) helmShow(w http.ResponseWriter, r *http.Request) *httper
}
result, err := handler.helmPackageManager.Show(showOptions)
if err != nil {
return &httperror.HandlerError{
StatusCode: http.StatusInternalServerError,
Message: "Unable to show chart",
Err: err,
}
return httperror.InternalServerError("Unable to show chart", err)
}
w.Header().Set("Content-Type", "text/plain")

View File

@ -47,32 +47,28 @@ func (p *addHelmRepoUrlPayload) Validate(_ *http.Request) error {
func (handler *Handler) userCreateHelmRepo(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
tokenData, err := security.RetrieveTokenData(r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve user authentication token", err}
return httperror.InternalServerError("Unable to retrieve user authentication token", err)
}
userID := portainer.UserID(tokenData.ID)
p := new(addHelmRepoUrlPayload)
err = request.DecodeAndValidateJSONPayload(r, p)
if err != nil {
return &httperror.HandlerError{
StatusCode: http.StatusBadRequest,
Message: "Invalid Helm repository URL",
Err: err,
}
return httperror.BadRequest("Invalid Helm repository URL", err)
}
// lowercase, remove trailing slash
p.URL = strings.TrimSuffix(strings.ToLower(p.URL), "/")
records, err := handler.dataStore.HelmUserRepository().HelmUserRepositoryByUserID(userID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to access the DataStore", err}
return httperror.InternalServerError("Unable to access the DataStore", err)
}
// check if repo already exists - by doing case insensitive comparison
for _, record := range records {
if strings.EqualFold(record.URL, p.URL) {
errMsg := "Helm repo already registered for user"
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: errMsg, Err: errors.New(errMsg)}
return httperror.BadRequest(errMsg, errors.New(errMsg))
}
}
@ -83,7 +79,7 @@ func (handler *Handler) userCreateHelmRepo(w http.ResponseWriter, r *http.Reques
err = handler.dataStore.HelmUserRepository().Create(&record)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to save a user Helm repository URL", err}
return httperror.InternalServerError("Unable to save a user Helm repository URL", err)
}
return response.JSON(w, record)
@ -106,18 +102,18 @@ func (handler *Handler) userCreateHelmRepo(w http.ResponseWriter, r *http.Reques
func (handler *Handler) userGetHelmRepos(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
tokenData, err := security.RetrieveTokenData(r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve user authentication token", err}
return httperror.InternalServerError("Unable to retrieve user authentication token", err)
}
userID := portainer.UserID(tokenData.ID)
settings, err := handler.dataStore.Settings().Settings()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve settings from the database", err}
return httperror.InternalServerError("Unable to retrieve settings from the database", err)
}
userRepos, err := handler.dataStore.HelmUserRepository().HelmUserRepositoryByUserID(userID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to get user Helm repositories", err}
return httperror.InternalServerError("Unable to get user Helm repositories", err)
}
resp := helmUserRepositoryResponse{

View File

@ -64,7 +64,7 @@ func (handler *Handler) fdoConfigureDevice(w http.ResponseWriter, r *http.Reques
guid, err := request.RetrieveRouteVariableValue(r, "guid")
if err != nil {
logrus.WithError(err).Info("fdoConfigureDevice: request.RetrieveRouteVariableValue()")
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "fdoConfigureDevice: guid not found", Err: err}
return httperror.InternalServerError("fdoConfigureDevice: guid not found", err)
}
var payload deviceConfigurePayload
@ -72,26 +72,26 @@ func (handler *Handler) fdoConfigureDevice(w http.ResponseWriter, r *http.Reques
err = request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
logrus.WithError(err).Error("Invalid request payload")
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Invalid request payload", Err: err}
return httperror.BadRequest("Invalid request payload", err)
}
profile, err := handler.DataStore.FDOProfile().FDOProfile(portainer.FDOProfileID(payload.ProfileID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find a FDO Profile with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find a FDO Profile with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a FDO Profile with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find a FDO Profile with the specified identifier inside the database", err)
}
fileContent, err := handler.FileService.GetFileContent(profile.FilePath, "")
if err != nil {
logrus.WithError(err).Info("fdoConfigureDevice: GetFileContent")
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "fdoConfigureDevice: GetFileContent", Err: err}
return httperror.InternalServerError("fdoConfigureDevice: GetFileContent", err)
}
fdoClient, err := handler.newFDOClient()
if err != nil {
logrus.WithError(err).Info("fdoConfigureDevice: newFDOClient()")
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "fdoConfigureDevice: newFDOClient()", Err: err}
return httperror.InternalServerError("fdoConfigureDevice: newFDOClient()", err)
}
// enable fdo_sys
@ -103,7 +103,7 @@ func (handler *Handler) fdoConfigureDevice(w http.ResponseWriter, r *http.Reques
"bytes": []string{"F5"}, // this is "true" in CBOR
}, []byte("")); err != nil {
logrus.WithError(err).Info("fdoConfigureDevice: PutDeviceSVIRaw()")
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "fdoConfigureDevice: PutDeviceSVIRaw()", Err: err}
return httperror.InternalServerError("fdoConfigureDevice: PutDeviceSVIRaw()", err)
}
if err = fdoClient.PutDeviceSVIRaw(url.Values{
@ -114,7 +114,7 @@ func (handler *Handler) fdoConfigureDevice(w http.ResponseWriter, r *http.Reques
"filename": []string{"DEVICE_edgeid.txt"},
}, []byte(payload.EdgeID)); err != nil {
logrus.WithError(err).Info("fdoConfigureDevice: PutDeviceSVIRaw(edgeid)")
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "fdoConfigureDevice: PutDeviceSVIRaw(edgeid)", Err: err}
return httperror.InternalServerError("fdoConfigureDevice: PutDeviceSVIRaw(edgeid)", err)
}
// write down the edgekey
@ -126,7 +126,7 @@ func (handler *Handler) fdoConfigureDevice(w http.ResponseWriter, r *http.Reques
"filename": []string{"DEVICE_edgekey.txt"},
}, []byte(payload.EdgeKey)); err != nil {
logrus.WithError(err).Info("fdoConfigureDevice: PutDeviceSVIRaw(edgekey)")
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "fdoConfigureDevice: PutDeviceSVIRaw(edgekey)", Err: err}
return httperror.InternalServerError("fdoConfigureDevice: PutDeviceSVIRaw(edgekey)", err)
}
// write down the device name
@ -138,7 +138,7 @@ func (handler *Handler) fdoConfigureDevice(w http.ResponseWriter, r *http.Reques
"filename": []string{"DEVICE_name.txt"},
}, []byte(payload.Name)); err != nil {
logrus.WithError(err).Info("fdoConfigureDevice: PutDeviceSVIRaw(name)")
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "fdoConfigureDevice: PutDeviceSVIRaw(name)", Err: err}
return httperror.InternalServerError("fdoConfigureDevice: PutDeviceSVIRaw(name)", err)
}
// write down the device GUID - used as the EDGE_DEVICE_GUID too
@ -150,7 +150,7 @@ func (handler *Handler) fdoConfigureDevice(w http.ResponseWriter, r *http.Reques
"filename": []string{"DEVICE_GUID.txt"},
}, []byte(guid)); err != nil {
logrus.WithError(err).Info("fdoConfigureDevice: PutDeviceSVIRaw()")
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "fdoConfigureDevice: PutDeviceSVIRaw()", Err: err}
return httperror.InternalServerError("fdoConfigureDevice: PutDeviceSVIRaw()", err)
}
if err = fdoClient.PutDeviceSVIRaw(url.Values{
@ -161,13 +161,13 @@ func (handler *Handler) fdoConfigureDevice(w http.ResponseWriter, r *http.Reques
"filename": []string{deploymentScriptName},
}, fileContent); err != nil {
logrus.WithError(err).Info("fdoConfigureDevice: PutDeviceSVIRaw()")
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "fdoConfigureDevice: PutDeviceSVIRaw()", Err: err}
return httperror.InternalServerError("fdoConfigureDevice: PutDeviceSVIRaw()", err)
}
b, err := cbor.Marshal([]string{"/bin/sh", deploymentScriptName})
if err != nil {
logrus.WithError(err).Error("failed to marshal string to CBOR")
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "fdoConfigureDevice: PutDeviceSVIRaw() failed to encode", Err: err}
return httperror.InternalServerError("fdoConfigureDevice: PutDeviceSVIRaw() failed to encode", err)
}
cborBytes := strings.ToUpper(hex.EncodeToString(b))
@ -181,7 +181,7 @@ func (handler *Handler) fdoConfigureDevice(w http.ResponseWriter, r *http.Reques
"bytes": []string{cborBytes},
}, []byte("")); err != nil {
logrus.WithError(err).Info("fdoConfigureDevice: PutDeviceSVIRaw()")
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "fdoConfigureDevice: PutDeviceSVIRaw()", Err: err}
return httperror.InternalServerError("fdoConfigureDevice: PutDeviceSVIRaw()", err)
}
return response.Empty(w)

View File

@ -89,22 +89,22 @@ func (handler *Handler) fdoConfigure(w http.ResponseWriter, r *http.Request) *ht
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
logrus.WithError(err).Error("Invalid request payload")
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Invalid request payload", Err: err}
return httperror.BadRequest("Invalid request payload", err)
}
settings := portainer.FDOConfiguration(payload)
if err = handler.saveSettings(settings); err != nil {
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Error saving FDO settings", Err: err}
return httperror.BadRequest("Error saving FDO settings", err)
}
profiles, err := handler.DataStore.FDOProfile().FDOProfiles()
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Error saving FDO settings", Err: err}
return httperror.InternalServerError("Error saving FDO settings", err)
}
if len(profiles) == 0 {
err = handler.addDefaultProfile()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, err.Error(), err}
return httperror.InternalServerError(err.Error(), err)
}
}

View File

@ -25,14 +25,14 @@ func (handler *Handler) fdoListAll(w http.ResponseWriter, r *http.Request) *http
fdoClient, err := handler.newFDOClient()
if err != nil {
logrus.WithError(err).Info("fdoListAll: newFDOClient()")
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "fdoRegisterDevice: newFDOClient()", Err: err}
return httperror.InternalServerError("fdoRegisterDevice: newFDOClient()", err)
}
// Get all vouchers
guids, err := fdoClient.GetVouchers()
if err != nil {
logrus.WithError(err).Info("fdoListAll: GetVouchers()")
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "fdoListAll: GetVouchers()", Err: err}
return httperror.InternalServerError("fdoListAll: GetVouchers()", err)
}
return response.JSON(w, guids)

View File

@ -45,29 +45,29 @@ func (payload *createProfileFromFileContentPayload) Validate(r *http.Request) er
func (handler *Handler) createProfile(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
method, err := request.RetrieveQueryParameter(r, "method", false)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid query parameter: method", err}
return httperror.BadRequest("Invalid query parameter: method", err)
}
switch method {
case "editor":
return handler.createFDOProfileFromFileContent(w, r)
}
return &httperror.HandlerError{http.StatusBadRequest, "Invalid method. Value must be one of: editor", errors.New("invalid method")}
return httperror.BadRequest("Invalid method. Value must be one of: editor", errors.New("invalid method"))
}
func (handler *Handler) createFDOProfileFromFileContent(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
var payload createProfileFromFileContentPayload
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
isUnique, err := handler.checkUniqueProfileName(payload.Name, -1)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, err.Error(), err}
return httperror.InternalServerError(err.Error(), err)
}
if !isUnique {
return &httperror.HandlerError{http.StatusConflict, fmt.Sprintf("A profile with the name '%s' already exists", payload.Name), errors.New("a profile already exists with this name")}
return &httperror.HandlerError{StatusCode: http.StatusConflict, Message: fmt.Sprintf("A profile with the name '%s' already exists", payload.Name), Err: errors.New("a profile already exists with this name")}
}
profileID := handler.DataStore.FDOProfile().GetNextIdentifier()
@ -78,14 +78,14 @@ func (handler *Handler) createFDOProfileFromFileContent(w http.ResponseWriter, r
filePath, err := handler.FileService.StoreFDOProfileFileFromBytes(strconv.Itoa(int(profile.ID)), []byte(payload.ProfileFileContent))
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist profile file on disk", err}
return httperror.InternalServerError("Unable to persist profile file on disk", err)
}
profile.FilePath = filePath
profile.DateCreated = time.Now().Unix()
err = handler.DataStore.FDOProfile().Create(profile)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist the profile inside the database", err}
return httperror.InternalServerError("Unable to persist the profile inside the database", err)
}
return response.JSON(w, profile)

View File

@ -24,12 +24,12 @@ import (
func (handler *Handler) deleteProfile(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
id, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Bad request", errors.New("missing 'id' query parameter")}
return httperror.BadRequest("Bad request", errors.New("missing 'id' query parameter"))
}
err = handler.DataStore.FDOProfile().Delete(portainer.FDOProfileID(id))
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to delete Profile", err}
return httperror.InternalServerError("Unable to delete Profile", err)
}
return response.Empty(w)

View File

@ -26,24 +26,24 @@ import (
func (handler *Handler) duplicateProfile(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
id, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Bad request", errors.New("missing 'id' query parameter")}
return httperror.BadRequest("Bad request", errors.New("missing 'id' query parameter"))
}
originalProfile, err := handler.DataStore.FDOProfile().FDOProfile(portainer.FDOProfileID(id))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find a FDO Profile with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find a FDO Profile with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a FDO Profile with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find a FDO Profile with the specified identifier inside the database", err)
}
fileContent, err := handler.FileService.GetFileContent(originalProfile.FilePath, "")
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve Profile file content", err}
return httperror.InternalServerError("Unable to retrieve Profile file content", err)
}
profileID := handler.DataStore.FDOProfile().GetNextIdentifier()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to duplicate Profile", err}
return httperror.InternalServerError("Unable to duplicate Profile", err)
}
newProfile := &portainer.FDOProfile{
@ -53,14 +53,14 @@ func (handler *Handler) duplicateProfile(w http.ResponseWriter, r *http.Request)
filePath, err := handler.FileService.StoreFDOProfileFileFromBytes(strconv.Itoa(int(newProfile.ID)), fileContent)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist profile file on disk", err}
return httperror.InternalServerError("Unable to persist profile file on disk", err)
}
newProfile.FilePath = filePath
newProfile.DateCreated = time.Now().Unix()
err = handler.DataStore.FDOProfile().Create(newProfile)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist the profile inside the database", err}
return httperror.InternalServerError("Unable to persist the profile inside the database", err)
}
return response.JSON(w, newProfile)

View File

@ -29,17 +29,17 @@ type fdoProfileResponse struct {
func (handler *Handler) fdoProfileInspect(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
id, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Bad request", errors.New("missing 'id' query parameter")}
return httperror.BadRequest("Bad request", errors.New("missing 'id' query parameter"))
}
profile, err := handler.DataStore.FDOProfile().FDOProfile(portainer.FDOProfileID(id))
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve Profile", err}
return httperror.InternalServerError("Unable to retrieve Profile", err)
}
fileContent, err := handler.FileService.GetFileContent(profile.FilePath, "")
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve Profile file content", err}
return httperror.InternalServerError("Unable to retrieve Profile file content", err)
}
return response.JSON(w, fdoProfileResponse{

View File

@ -24,7 +24,7 @@ func (handler *Handler) fdoProfileList(w http.ResponseWriter, r *http.Request) *
profiles, err := handler.DataStore.FDOProfile().FDOProfiles()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, err.Error(), err}
return httperror.InternalServerError(err.Error(), err)
}
return response.JSON(w, profiles)

View File

@ -27,40 +27,40 @@ import (
func (handler *Handler) updateProfile(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
id, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Bad request", errors.New("missing 'id' query parameter")}
return httperror.BadRequest("Bad request", errors.New("missing 'id' query parameter"))
}
var payload createProfileFromFileContentPayload
err = request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
profile, err := handler.DataStore.FDOProfile().FDOProfile(portainer.FDOProfileID(id))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find a FDO Profile with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find a FDO Profile with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a FDO Profile with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find a FDO Profile with the specified identifier inside the database", err)
}
isUnique, err := handler.checkUniqueProfileName(payload.Name, id)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, err.Error(), err}
return httperror.InternalServerError(err.Error(), err)
}
if !isUnique {
return &httperror.HandlerError{http.StatusConflict, fmt.Sprintf("A profile with the name '%s' already exists", payload.Name), errors.New("a profile already exists with this name")}
return &httperror.HandlerError{StatusCode: http.StatusConflict, Message: fmt.Sprintf("A profile with the name '%s' already exists", payload.Name), Err: errors.New("a profile already exists with this name")}
}
filePath, err := handler.FileService.StoreFDOProfileFileFromBytes(strconv.Itoa(int(profile.ID)), []byte(payload.ProfileFileContent))
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to update profile", err}
return httperror.InternalServerError("Unable to update profile", err)
}
profile.FilePath = filePath
profile.Name = payload.Name
err = handler.DataStore.FDOProfile().Update(profile.ID, profile)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to update profile", err}
return httperror.InternalServerError("Unable to update profile", err)
}
return response.JSON(w, profile)

View File

@ -30,19 +30,19 @@ func (handler *Handler) fdoRegisterDevice(w http.ResponseWriter, r *http.Request
ov, filename, err := request.RetrieveMultiPartFormFile(r, "voucher")
if err != nil {
logrus.WithField("filename", filename).WithError(err).Info("fdoRegisterDevice: readVoucher()")
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "fdoRegisterDevice: read Voucher()", Err: err}
return httperror.InternalServerError("fdoRegisterDevice: read Voucher()", err)
}
fdoClient, err := handler.newFDOClient()
if err != nil {
logrus.WithError(err).Info("fdoRegisterDevice: newFDOClient()")
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "fdoRegisterDevice: newFDOClient()", Err: err}
return httperror.InternalServerError("fdoRegisterDevice: newFDOClient()", err)
}
guid, err := fdoClient.PostVoucher(ov)
if err != nil {
logrus.WithError(err).Info("fdoRegisterDevice: PostVoucher()")
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "fdoRegisterDevice: PostVoucher()", Err: err}
return httperror.InternalServerError("fdoRegisterDevice: PostVoucher()", err)
}
return response.JSON(w, registerDeviceResponse{guid})

View File

@ -29,44 +29,44 @@ import (
func (handler *Handler) openAMTActivate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment identifier route variable", err}
return httperror.BadRequest("Invalid environment identifier route variable", err)
}
endpoint, err := handler.DataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
if err == bolterrors.ErrObjectNotFound {
return &httperror.HandlerError{StatusCode: http.StatusNotFound, Message: "Unable to find an endpoint with the specified identifier inside the database", Err: err}
return httperror.NotFound("Unable to find an endpoint with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Unable to find an endpoint with the specified identifier inside the database", Err: err}
return httperror.InternalServerError("Unable to find an endpoint with the specified identifier inside the database", err)
} else if !endpointutils.IsAgentEndpoint(endpoint) {
errMsg := fmt.Sprintf("%s is not an agent environment", endpoint.Name)
return &httperror.HandlerError{http.StatusBadRequest, errMsg, errors.New(errMsg)}
return httperror.BadRequest(errMsg, errors.New(errMsg))
}
settings, err := handler.DataStore.Settings().Settings()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve settings from the database", err}
return httperror.InternalServerError("Unable to retrieve settings from the database", err)
}
err = handler.activateDevice(endpoint, *settings)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to activate device", err}
return httperror.InternalServerError("Unable to activate device", err)
}
hostInfo, _, err := handler.getEndpointAMTInfo(endpoint)
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Unable to retrieve AMT information", Err: err}
return httperror.InternalServerError("Unable to retrieve AMT information", err)
}
if hostInfo.ControlModeRaw < 1 {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Failed to activate device", Err: errors.New("failed to activate device")}
return httperror.InternalServerError("Failed to activate device", errors.New("failed to activate device"))
}
if hostInfo.UUID == "" {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Unable to retrieve device UUID", Err: errors.New("unable to retrieve device UUID")}
return httperror.InternalServerError("Unable to retrieve device UUID", errors.New("unable to retrieve device UUID"))
}
endpoint.AMTDeviceGUID = hostInfo.UUID
err = handler.DataStore.Endpoint().UpdateEndpoint(endpoint.ID, endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist environment changes inside the database", err}
return httperror.InternalServerError("Unable to persist environment changes inside the database", err)
}
return response.Empty(w)

View File

@ -74,25 +74,25 @@ func (handler *Handler) openAMTConfigure(w http.ResponseWriter, r *http.Request)
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
logrus.WithError(err).Error("Invalid request payload")
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Invalid request payload", Err: err}
return httperror.BadRequest("Invalid request payload", err)
}
if payload.Enabled {
certificateErr := validateCertificate(payload.CertFileContent, payload.CertFilePassword)
if certificateErr != nil {
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Error validating certificate", Err: certificateErr}
return httperror.BadRequest("Error validating certificate", certificateErr)
}
err = handler.enableOpenAMT(payload)
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Error enabling OpenAMT", Err: err}
return httperror.BadRequest("Error enabling OpenAMT", err)
}
return response.Empty(w)
}
err = handler.disableOpenAMT()
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Error disabling OpenAMT", Err: err}
return httperror.BadRequest("Error disabling OpenAMT", err)
}
return response.Empty(w)
}

View File

@ -28,14 +28,14 @@ import (
func (handler *Handler) openAMTDevices(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment identifier route variable", err}
return httperror.BadRequest("Invalid environment identifier route variable", err)
}
endpoint, err := handler.DataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
if err == bolterrors.ErrObjectNotFound {
return &httperror.HandlerError{StatusCode: http.StatusNotFound, Message: "Unable to find an endpoint with the specified identifier inside the database", Err: err}
return httperror.NotFound("Unable to find an endpoint with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Unable to find an endpoint with the specified identifier inside the database", Err: err}
return httperror.InternalServerError("Unable to find an endpoint with the specified identifier inside the database", err)
}
if endpoint.AMTDeviceGUID == "" {
@ -44,12 +44,12 @@ func (handler *Handler) openAMTDevices(w http.ResponseWriter, r *http.Request) *
settings, err := handler.DataStore.Settings().Settings()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve settings from the database", err}
return httperror.InternalServerError("Unable to retrieve settings from the database", err)
}
device, err := handler.OpenAMTService.DeviceInformation(settings.OpenAMTConfiguration, endpoint.AMTDeviceGUID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve device information", err}
return httperror.InternalServerError("Unable to retrieve device information", err)
}
devices := []portainer.OpenAMTDeviceInformation{
@ -87,25 +87,25 @@ func (payload *deviceActionPayload) Validate(r *http.Request) error {
func (handler *Handler) deviceAction(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
deviceID, err := request.RetrieveRouteVariableValue(r, "deviceId")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid device identifier route variable", err}
return httperror.BadRequest("Invalid device identifier route variable", err)
}
var payload deviceActionPayload
err = request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
logrus.WithError(err).Error("Invalid request payload")
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Invalid request payload", Err: err}
return httperror.BadRequest("Invalid request payload", err)
}
settings, err := handler.DataStore.Settings().Settings()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve settings from the database", err}
return httperror.InternalServerError("Unable to retrieve settings from the database", err)
}
err = handler.OpenAMTService.ExecuteDeviceAction(settings.OpenAMTConfiguration, deviceID, payload.Action)
if err != nil {
logrus.WithError(err).Error("Error executing device action")
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Error executing device action", Err: err}
return httperror.BadRequest("Error executing device action", err)
}
return response.Empty(w)
@ -144,30 +144,30 @@ type AuthorizationResponse struct {
func (handler *Handler) deviceFeatures(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
deviceID, err := request.RetrieveRouteVariableValue(r, "deviceId")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid device identifier route variable", err}
return httperror.BadRequest("Invalid device identifier route variable", err)
}
var payload deviceFeaturesPayload
err = request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
logrus.WithError(err).Error("Invalid request payload")
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Invalid request payload", Err: err}
return httperror.BadRequest("Invalid request payload", err)
}
settings, err := handler.DataStore.Settings().Settings()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve settings from the database", err}
return httperror.InternalServerError("Unable to retrieve settings from the database", err)
}
_, err = handler.OpenAMTService.DeviceInformation(settings.OpenAMTConfiguration, deviceID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve device information", err}
return httperror.InternalServerError("Unable to retrieve device information", err)
}
token, err := handler.OpenAMTService.EnableDeviceFeatures(settings.OpenAMTConfiguration, deviceID, payload.Features)
if err != nil {
logrus.WithError(err).Error("Error executing device action")
return &httperror.HandlerError{StatusCode: http.StatusBadRequest, Message: "Error executing device action", Err: err}
return httperror.BadRequest("Error executing device action", err)
}
authorizationResponse := AuthorizationResponse{

View File

@ -57,21 +57,21 @@ const (
func (handler *Handler) openAMTHostInfo(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment identifier route variable", err}
return httperror.BadRequest("Invalid environment identifier route variable", err)
}
logrus.WithField("endpointID", endpointID).Info("OpenAMTHostInfo")
endpoint, err := handler.DataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
if err == bolterrors.ErrObjectNotFound {
return &httperror.HandlerError{StatusCode: http.StatusNotFound, Message: "Unable to find an endpoint with the specified identifier inside the database", Err: err}
return httperror.NotFound("Unable to find an endpoint with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Unable to find an endpoint with the specified identifier inside the database", Err: err}
return httperror.InternalServerError("Unable to find an endpoint with the specified identifier inside the database", err)
}
amtInfo, output, err := handler.getEndpointAMTInfo(endpoint)
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: output, Err: err}
return httperror.InternalServerError(output, err)
}
return response.JSON(w, amtInfo)

View File

@ -36,11 +36,11 @@ import (
func (handler *Handler) getKubernetesConfig(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
tokenData, err := security.RetrieveTokenData(r)
if err != nil {
return &httperror.HandlerError{http.StatusForbidden, "Permission denied to access environment", err}
return httperror.Forbidden("Permission denied to access environment", err)
}
bearerToken, err := handler.jwtService.GenerateTokenForKubeconfig(tokenData)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to generate JWT token", err}
return httperror.InternalServerError("Unable to generate JWT token", err)
}
endpoints, handlerErr := handler.filterUserKubeEndpoints(r)
@ -48,7 +48,7 @@ func (handler *Handler) getKubernetesConfig(w http.ResponseWriter, r *http.Reque
return handlerErr
}
if len(endpoints) == 0 {
return &httperror.HandlerError{http.StatusBadRequest, "empty endpoints list", errors.New("empty endpoints list")}
return httperror.BadRequest("empty endpoints list", errors.New("empty endpoints list"))
}
config, handlerErr := handler.buildConfig(r, tokenData, bearerToken, endpoints)
@ -67,17 +67,17 @@ func (handler *Handler) filterUserKubeEndpoints(r *http.Request) ([]portainer.En
_ = request.RetrieveJSONQueryParameter(r, "excludeIds", &excludeEndpointIDs, true)
if len(endpointIDs) > 0 && len(excludeEndpointIDs) > 0 {
return nil, &httperror.HandlerError{http.StatusBadRequest, "Can't provide both 'ids' and 'excludeIds' parameters", errors.New("invalid parameters")}
return nil, httperror.BadRequest("Can't provide both 'ids' and 'excludeIds' parameters", errors.New("invalid parameters"))
}
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve info from request context", err}
return nil, httperror.InternalServerError("Unable to retrieve info from request context", err)
}
endpointGroups, err := handler.dataStore.EndpointGroup().EndpointGroups()
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environment groups from the database", err}
return nil, httperror.InternalServerError("Unable to retrieve environment groups from the database", err)
}
if len(endpointIDs) > 0 {
@ -85,7 +85,7 @@ func (handler *Handler) filterUserKubeEndpoints(r *http.Request) ([]portainer.En
for _, endpointID := range endpointIDs {
endpoint, err := handler.dataStore.Endpoint().Endpoint(endpointID)
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environment from the database", err}
return nil, httperror.InternalServerError("Unable to retrieve environment from the database", err)
}
if !endpointutils.IsKubernetesEndpoint(endpoint) {
continue
@ -99,7 +99,7 @@ func (handler *Handler) filterUserKubeEndpoints(r *http.Request) ([]portainer.En
var kubeEndpoints []portainer.Endpoint
endpoints, err := handler.dataStore.Endpoint().Endpoints()
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environments from the database", err}
return nil, httperror.InternalServerError("Unable to retrieve environments from the database", err)
}
for _, endpoint := range endpoints {
if !endpointutils.IsKubernetesEndpoint(&endpoint) {
@ -188,7 +188,7 @@ func writeFileContent(w http.ResponseWriter, r *http.Request, endpoints []portai
if r.Header.Get("Accept") == "text/yaml" {
yaml, err := kcli.GenerateYAML(config)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Failed to generate Kubeconfig", err}
return httperror.InternalServerError("Failed to generate Kubeconfig", err)
}
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; %s.yaml", filenameBase))

View File

@ -29,24 +29,24 @@ import (
func (handler *Handler) getKubernetesNodesLimits(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment identifier route variable", err}
return httperror.BadRequest("Invalid environment identifier route variable", err)
}
endpoint, err := handler.dataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
if handler.dataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find an environment with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find an environment with the specified identifier inside the database", err)
}
cli, err := handler.kubernetesClientFactory.GetKubeClient(endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to create Kubernetes client", err}
return httperror.InternalServerError("Unable to create Kubernetes client", err)
}
nodesLimits, err := cli.GetNodesLimits()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve nodes limits", err}
return httperror.InternalServerError("Unable to retrieve nodes limits", err)
}
return response.JSON(w, nodesLimits)

View File

@ -37,28 +37,28 @@ func (payload *namespacesToggleSystemPayload) Validate(r *http.Request) error {
func (handler *Handler) namespacesToggleSystem(rw http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpoint, err := middlewares.FetchEndpoint(r)
if err != nil {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment on request context", err}
return httperror.NotFound("Unable to find an environment on request context", err)
}
namespaceName, err := request.RetrieveRouteVariableValue(r, "namespace")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid namespace identifier route variable", err}
return httperror.BadRequest("Invalid namespace identifier route variable", err)
}
var payload namespacesToggleSystemPayload
err = request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
kubeClient, err := handler.kubernetesClientFactory.GetKubeClient(endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to create kubernetes client", err}
return httperror.InternalServerError("Unable to create kubernetes client", err)
}
err = kubeClient.ToggleSystemState(namespaceName, payload.System)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to toggle system status", err}
return httperror.InternalServerError("Unable to toggle system status", err)
}
return response.Empty(rw)

View File

@ -34,19 +34,19 @@ func (handler *Handler) ldapCheck(w http.ResponseWriter, r *http.Request) *httpe
var payload checkPayload
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
settings := &payload.LDAPSettings
err = handler.prefillSettings(settings)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to fetch default settings", err}
return httperror.InternalServerError("Unable to fetch default settings", err)
}
err = handler.LDAPService.TestConnectivity(settings)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to connect to LDAP server", err}
return httperror.InternalServerError("Unable to connect to LDAP server", err)
}
return response.Empty(w)

View File

@ -10,12 +10,12 @@ import (
func (handler *Handler) proxyRequestsToGitlabAPIWithoutRegistry(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
domain := r.Header.Get("X-Gitlab-Domain")
if domain == "" {
return &httperror.HandlerError{http.StatusBadRequest, "No Gitlab domain provided", nil}
return httperror.BadRequest("No Gitlab domain provided", nil)
}
proxy, err := handler.ProxyManager.CreateGitlabProxy(domain)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to create gitlab proxy", err}
return httperror.InternalServerError("Unable to create gitlab proxy", err)
}
http.StripPrefix("/registries/proxies/gitlab", proxy).ServeHTTP(w, r)

View File

@ -101,28 +101,28 @@ func (payload *registryConfigurePayload) Validate(r *http.Request) error {
func (handler *Handler) registryConfigure(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve info from request context", err}
return httperror.InternalServerError("Unable to retrieve info from request context", err)
}
if !securityContext.IsAdmin {
return &httperror.HandlerError{http.StatusForbidden, "Permission denied to configure registry", httperrors.ErrResourceAccessDenied}
return httperror.Forbidden("Permission denied to configure registry", httperrors.ErrResourceAccessDenied)
}
payload := &registryConfigurePayload{}
err = payload.Validate(r)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
registryID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid registry identifier route variable", err}
return httperror.BadRequest("Invalid registry identifier route variable", err)
}
registry, err := handler.DataStore.Registry().Registry(portainer.RegistryID(registryID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find a registry with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find a registry with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a registry with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find a registry with the specified identifier inside the database", err)
}
registry.ManagementConfiguration = &portainer.RegistryManagementConfiguration{
@ -154,19 +154,19 @@ func (handler *Handler) registryConfigure(w http.ResponseWriter, r *http.Request
certPath, err := handler.FileService.StoreRegistryManagementFileFromBytes(folder, "cert.pem", payload.TLSCertFile)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist TLS certificate file on disk", err}
return httperror.InternalServerError("Unable to persist TLS certificate file on disk", err)
}
registry.ManagementConfiguration.TLSConfig.TLSCertPath = certPath
keyPath, err := handler.FileService.StoreRegistryManagementFileFromBytes(folder, "key.pem", payload.TLSKeyFile)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist TLS key file on disk", err}
return httperror.InternalServerError("Unable to persist TLS key file on disk", err)
}
registry.ManagementConfiguration.TLSConfig.TLSKeyPath = keyPath
cacertPath, err := handler.FileService.StoreRegistryManagementFileFromBytes(folder, "ca.pem", payload.TLSCACertFile)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist TLS CA certificate file on disk", err}
return httperror.InternalServerError("Unable to persist TLS CA certificate file on disk", err)
}
registry.ManagementConfiguration.TLSConfig.TLSCACertPath = cacertPath
}
@ -174,7 +174,7 @@ func (handler *Handler) registryConfigure(w http.ResponseWriter, r *http.Request
err = handler.DataStore.Registry().UpdateRegistry(registry.ID, registry)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist registry changes inside the database", err}
return httperror.InternalServerError("Unable to persist registry changes inside the database", err)
}
return response.Empty(w)

View File

@ -93,16 +93,16 @@ func (payload *registryCreatePayload) Validate(_ *http.Request) error {
func (handler *Handler) registryCreate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve info from request context", err}
return httperror.InternalServerError("Unable to retrieve info from request context", err)
}
if !securityContext.IsAdmin {
return &httperror.HandlerError{http.StatusForbidden, "Permission denied to create registry", httperrors.ErrResourceAccessDenied}
return httperror.Forbidden("Permission denied to create registry", httperrors.ErrResourceAccessDenied)
}
var payload registryCreatePayload
err = request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
registry := &portainer.Registry{
@ -123,20 +123,20 @@ func (handler *Handler) registryCreate(w http.ResponseWriter, r *http.Request) *
registries, err := rs.Registries()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve registries from the database", err}
return httperror.InternalServerError("Unable to retrieve registries from the database", err)
}
for _, r := range registries {
if r.Name == registry.Name {
return &httperror.HandlerError{http.StatusConflict, "Another registry with the same name already exists", errors.New("A registry is already defined with this name")}
return &httperror.HandlerError{StatusCode: http.StatusConflict, Message: "Another registry with the same name already exists", Err: errors.New("A registry is already defined with this name")}
}
if handler.registriesHaveSameURLAndCredentials(&r, registry) {
return &httperror.HandlerError{http.StatusConflict, "Another registry with the same URL and credentials already exists", errors.New("A registry is already defined for this URL and credentials")}
return &httperror.HandlerError{StatusCode: http.StatusConflict, Message: "Another registry with the same URL and credentials already exists", Err: errors.New("A registry is already defined for this URL and credentials")}
}
}
err = rs.Create(registry)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist the registry inside the database", err}
return httperror.InternalServerError("Unable to persist the registry inside the database", err)
}
hideFields(registry, true)

View File

@ -27,27 +27,27 @@ import (
func (handler *Handler) registryDelete(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve info from request context", err}
return httperror.InternalServerError("Unable to retrieve info from request context", err)
}
if !securityContext.IsAdmin {
return &httperror.HandlerError{http.StatusForbidden, "Permission denied to delete registry", httperrors.ErrResourceAccessDenied}
return httperror.Forbidden("Permission denied to delete registry", httperrors.ErrResourceAccessDenied)
}
registryID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid registry identifier route variable", err}
return httperror.BadRequest("Invalid registry identifier route variable", err)
}
_, err = handler.DataStore.Registry().Registry(portainer.RegistryID(registryID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find a registry with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find a registry with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a registry with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find a registry with the specified identifier inside the database", err)
}
err = handler.DataStore.Registry().DeleteRegistry(portainer.RegistryID(registryID))
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to remove the registry from the database", err}
return httperror.InternalServerError("Unable to remove the registry from the database", err)
}
return response.Empty(w)

View File

@ -29,22 +29,22 @@ import (
func (handler *Handler) registryInspect(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
hasAccess, isAdmin, err := handler.userHasRegistryAccess(r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve info from request context", err}
return httperror.InternalServerError("Unable to retrieve info from request context", err)
}
if !hasAccess {
return &httperror.HandlerError{http.StatusForbidden, "Access denied to resource", httperrors.ErrResourceAccessDenied}
return httperror.Forbidden("Access denied to resource", httperrors.ErrResourceAccessDenied)
}
registryID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid registry identifier route variable", err}
return httperror.BadRequest("Invalid registry identifier route variable", err)
}
registry, err := handler.DataStore.Registry().Registry(portainer.RegistryID(registryID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find a registry with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find a registry with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a registry with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find a registry with the specified identifier inside the database", err)
}
hideFields(registry, !isAdmin)

View File

@ -25,15 +25,15 @@ import (
func (handler *Handler) registryList(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve info from request context", err}
return httperror.InternalServerError("Unable to retrieve info from request context", err)
}
if !securityContext.IsAdmin {
return &httperror.HandlerError{http.StatusForbidden, "Permission denied to list registries, use /endpoints/:endpointId/registries route instead", httperrors.ErrResourceAccessDenied}
return httperror.Forbidden("Permission denied to list registries, use /endpoints/:endpointId/registries route instead", httperrors.ErrResourceAccessDenied)
}
registries, err := handler.DataStore.Registry().Registries()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve registries from the database", err}
return httperror.InternalServerError("Unable to retrieve registries from the database", err)
}
return response.JSON(w, registries)

View File

@ -2,9 +2,10 @@ package registries
import (
"errors"
"github.com/portainer/portainer/api/internal/endpointutils"
"net/http"
"github.com/portainer/portainer/api/internal/endpointutils"
httperror "github.com/portainer/libhttp/error"
"github.com/portainer/libhttp/request"
"github.com/portainer/libhttp/response"
@ -58,34 +59,34 @@ func (payload *registryUpdatePayload) Validate(r *http.Request) error {
func (handler *Handler) registryUpdate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve info from request context", err}
return httperror.InternalServerError("Unable to retrieve info from request context", err)
}
if !securityContext.IsAdmin {
return &httperror.HandlerError{http.StatusForbidden, "Permission denied to update registry", httperrors.ErrResourceAccessDenied}
return httperror.Forbidden("Permission denied to update registry", httperrors.ErrResourceAccessDenied)
}
registryID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid registry identifier route variable", err}
return httperror.BadRequest("Invalid registry identifier route variable", err)
}
registry, err := handler.DataStore.Registry().Registry(portainer.RegistryID(registryID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find a registry with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find a registry with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a registry with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find a registry with the specified identifier inside the database", err)
}
registries, err := handler.DataStore.Registry().Registries()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve registries from the database", err}
return httperror.InternalServerError("Unable to retrieve registries from the database", err)
}
var payload registryUpdatePayload
err = request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
if payload.Name != nil {
@ -97,7 +98,7 @@ func (handler *Handler) registryUpdate(w http.ResponseWriter, r *http.Request) *
// see https://portainer.atlassian.net/browse/EE-2706 for more details
for _, r := range registries {
if r.ID != registry.ID && r.Name == registry.Name {
return &httperror.HandlerError{http.StatusConflict, "Another registry with the same name already exists", errors.New("A registry is already defined with this name")}
return &httperror.HandlerError{StatusCode: http.StatusConflict, Message: "Another registry with the same name already exists", Err: errors.New("A registry is already defined with this name")}
}
}
@ -146,7 +147,7 @@ func (handler *Handler) registryUpdate(w http.ResponseWriter, r *http.Request) *
for _, r := range registries {
if r.ID != registry.ID && handler.registriesHaveSameURLAndCredentials(&r, registry) {
return &httperror.HandlerError{http.StatusConflict, "Another registry with the same URL and credentials already exists", errors.New("A registry is already defined for this URL and credentials")}
return &httperror.HandlerError{StatusCode: http.StatusConflict, Message: "Another registry with the same URL and credentials already exists", Err: errors.New("A registry is already defined for this URL and credentials")}
}
}
}
@ -158,13 +159,13 @@ func (handler *Handler) registryUpdate(w http.ResponseWriter, r *http.Request) *
for endpointID, endpointAccess := range registry.RegistryAccesses {
endpoint, err := handler.DataStore.Endpoint().Endpoint(endpointID)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to update access to registry", err}
return httperror.InternalServerError("Unable to update access to registry", err)
}
if endpointutils.IsKubernetesEndpoint(endpoint) {
err = handler.updateEndpointRegistryAccess(endpoint, registry, endpointAccess)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to update access to registry", err}
return httperror.InternalServerError("Unable to update access to registry", err)
}
}
}
@ -176,7 +177,7 @@ func (handler *Handler) registryUpdate(w http.ResponseWriter, r *http.Request) *
err = handler.DataStore.Registry().UpdateRegistry(registry.ID, registry)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist registry changes inside the database", err}
return httperror.InternalServerError("Unable to persist registry changes inside the database", err)
}
return response.JSON(w, registry)

View File

@ -72,15 +72,15 @@ func (handler *Handler) resourceControlCreate(w http.ResponseWriter, r *http.Req
var payload resourceControlCreatePayload
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
rc, err := handler.DataStore.ResourceControl().ResourceControlByResourceIDAndType(payload.ResourceID, payload.Type)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve resource controls from the database", err}
return httperror.InternalServerError("Unable to retrieve resource controls from the database", err)
}
if rc != nil {
return &httperror.HandlerError{http.StatusConflict, "A resource control is already associated to this resource", errResourceControlAlreadyExists}
return &httperror.HandlerError{StatusCode: http.StatusConflict, Message: "A resource control is already associated to this resource", Err: errResourceControlAlreadyExists}
}
var userAccesses = make([]portainer.UserResourceAccess, 0)
@ -113,7 +113,7 @@ func (handler *Handler) resourceControlCreate(w http.ResponseWriter, r *http.Req
err = handler.DataStore.ResourceControl().Create(&resourceControl)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist the resource control inside the database", err}
return httperror.InternalServerError("Unable to persist the resource control inside the database", err)
}
return response.JSON(w, resourceControl)

View File

@ -25,19 +25,19 @@ import (
func (handler *Handler) resourceControlDelete(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
resourceControlID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid resource control identifier route variable", err}
return httperror.BadRequest("Invalid resource control identifier route variable", err)
}
_, err = handler.DataStore.ResourceControl().ResourceControl(portainer.ResourceControlID(resourceControlID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find a resource control with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find a resource control with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a resource control with with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find a resource control with with the specified identifier inside the database", err)
}
err = handler.DataStore.ResourceControl().DeleteResourceControl(portainer.ResourceControlID(resourceControlID))
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to remove the resource control from the database", err}
return httperror.InternalServerError("Unable to remove the resource control from the database", err)
}
return response.Empty(w)

View File

@ -54,29 +54,29 @@ func (payload *resourceControlUpdatePayload) Validate(r *http.Request) error {
func (handler *Handler) resourceControlUpdate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
resourceControlID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid resource control identifier route variable", err}
return httperror.BadRequest("Invalid resource control identifier route variable", err)
}
var payload resourceControlUpdatePayload
err = request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
resourceControl, err := handler.DataStore.ResourceControl().ResourceControl(portainer.ResourceControlID(resourceControlID))
if handler.DataStore.IsErrObjectNotFound(err) {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find a resource control with the specified identifier inside the database", err}
return httperror.NotFound("Unable to find a resource control with the specified identifier inside the database", err)
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a resource control with with the specified identifier inside the database", err}
return httperror.InternalServerError("Unable to find a resource control with with the specified identifier inside the database", err)
}
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve info from request context", err}
return httperror.InternalServerError("Unable to retrieve info from request context", err)
}
if !security.AuthorizedResourceControlAccess(resourceControl, securityContext) {
return &httperror.HandlerError{http.StatusForbidden, "Permission denied to access the resource control", httperrors.ErrResourceAccessDenied}
return httperror.Forbidden("Permission denied to access the resource control", httperrors.ErrResourceAccessDenied)
}
resourceControl.Public = payload.Public
@ -103,12 +103,12 @@ func (handler *Handler) resourceControlUpdate(w http.ResponseWriter, r *http.Req
resourceControl.TeamAccesses = teamAccesses
if !security.AuthorizedResourceControlUpdate(resourceControl, securityContext) {
return &httperror.HandlerError{http.StatusForbidden, "Permission denied to update the resource control", httperrors.ErrResourceAccessDenied}
return httperror.Forbidden("Permission denied to update the resource control", httperrors.ErrResourceAccessDenied)
}
err = handler.DataStore.ResourceControl().UpdateResourceControl(resourceControl.ID, resourceControl)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist resource control changes inside the database", err}
return httperror.InternalServerError("Unable to persist resource control changes inside the database", err)
}
return response.JSON(w, resourceControl)

View File

@ -21,7 +21,7 @@ import (
func (handler *Handler) roleList(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
roles, err := handler.DataStore.Role().Roles()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve authorization sets from the database", err}
return httperror.InternalServerError("Unable to retrieve authorization sets from the database", err)
}
return response.JSON(w, roles)

View File

@ -21,7 +21,7 @@ import (
func (handler *Handler) settingsInspect(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
settings, err := handler.DataStore.Settings().Settings()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve the settings from the database", err}
return httperror.InternalServerError("Unable to retrieve the settings from the database", err)
}
hideFields(settings)

View File

@ -57,7 +57,7 @@ type publicSettingsResponse struct {
func (handler *Handler) settingsPublic(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
settings, err := handler.DataStore.Settings().Settings()
if err != nil {
return &httperror.HandlerError{StatusCode: http.StatusInternalServerError, Message: "Unable to retrieve the settings from the database", Err: err}
return httperror.InternalServerError("Unable to retrieve the settings from the database", err)
}
publicSettings := generatePublicSettings(settings)

View File

@ -106,12 +106,12 @@ func (handler *Handler) settingsUpdate(w http.ResponseWriter, r *http.Request) *
var payload settingsUpdatePayload
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
return httperror.BadRequest("Invalid request payload", err)
}
settings, err := handler.DataStore.Settings().Settings()
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve the settings from the database", err}
return httperror.InternalServerError("Unable to retrieve the settings from the database", err)
}
if handler.demoService.IsDemo() {
@ -139,7 +139,7 @@ func (handler *Handler) settingsUpdate(w http.ResponseWriter, r *http.Request) *
if newHelmRepo != settings.HelmRepositoryURL && newHelmRepo != portainer.DefaultHelmRepositoryURL {
err := libhelm.ValidateHelmRepositoryURL(*payload.HelmRepositoryURL)
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid Helm repository URL. Must correspond to a valid URL format", err}
return httperror.BadRequest("Invalid Helm repository URL. Must correspond to a valid URL format", err)
}
}
@ -205,7 +205,7 @@ func (handler *Handler) settingsUpdate(w http.ResponseWriter, r *http.Request) *
if payload.SnapshotInterval != nil && *payload.SnapshotInterval != settings.SnapshotInterval {
err := handler.updateSnapshotInterval(settings, *payload.SnapshotInterval)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to update snapshot interval", err}
return httperror.InternalServerError("Unable to update snapshot interval", err)
}
}
@ -240,7 +240,7 @@ func (handler *Handler) settingsUpdate(w http.ResponseWriter, r *http.Request) *
err = handler.DataStore.Settings().UpdateSettings(settings)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist settings changes inside the database", err}
return httperror.InternalServerError("Unable to persist settings changes inside the database", err)
}
return response.JSON(w, settings)
@ -265,7 +265,7 @@ func (handler *Handler) updateTLS(settings *portainer.Settings) *httperror.Handl
settings.LDAPSettings.TLSConfig.TLSCACertPath = ""
err := handler.FileService.DeleteTLSFiles(filesystem.LDAPStorePath)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to remove TLS files from disk", err}
return httperror.InternalServerError("Unable to remove TLS files from disk", err)
}
}
return nil

Some files were not shown because too many files have changed in this diff Show More