2018-06-11 13:13:19 +00:00
|
|
|
package endpointgroups
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/asaskevich/govalidator"
|
2018-09-10 10:01:38 +00:00
|
|
|
httperror "github.com/portainer/libhttp/error"
|
|
|
|
"github.com/portainer/libhttp/request"
|
|
|
|
"github.com/portainer/libhttp/response"
|
2019-03-21 01:20:14 +00:00
|
|
|
"github.com/portainer/portainer/api"
|
2018-06-11 13:13:19 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type endpointGroupCreatePayload struct {
|
|
|
|
Name string
|
|
|
|
Description string
|
|
|
|
AssociatedEndpoints []portainer.EndpointID
|
2020-03-29 09:54:14 +00:00
|
|
|
TagIDs []portainer.TagID
|
2018-06-11 13:13:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (payload *endpointGroupCreatePayload) Validate(r *http.Request) error {
|
|
|
|
if govalidator.IsNull(payload.Name) {
|
|
|
|
return portainer.Error("Invalid endpoint group name")
|
|
|
|
}
|
2020-03-29 09:54:14 +00:00
|
|
|
if payload.TagIDs == nil {
|
|
|
|
payload.TagIDs = []portainer.TagID{}
|
2018-06-15 07:18:25 +00:00
|
|
|
}
|
2018-06-11 13:13:19 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// POST request on /api/endpoint_groups
|
|
|
|
func (handler *Handler) endpointGroupCreate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
|
|
|
|
var payload endpointGroupCreatePayload
|
|
|
|
err := request.DecodeAndValidateJSONPayload(r, &payload)
|
|
|
|
if err != nil {
|
|
|
|
return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err}
|
|
|
|
}
|
|
|
|
|
|
|
|
endpointGroup := &portainer.EndpointGroup{
|
2019-05-24 06:04:58 +00:00
|
|
|
Name: payload.Name,
|
|
|
|
Description: payload.Description,
|
|
|
|
UserAccessPolicies: portainer.UserAccessPolicies{},
|
|
|
|
TeamAccessPolicies: portainer.TeamAccessPolicies{},
|
2020-03-29 09:54:14 +00:00
|
|
|
TagIDs: payload.TagIDs,
|
2018-06-11 13:13:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
err = handler.EndpointGroupService.CreateEndpointGroup(endpointGroup)
|
|
|
|
if err != nil {
|
|
|
|
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist the endpoint group inside the database", err}
|
|
|
|
}
|
|
|
|
|
|
|
|
endpoints, err := handler.EndpointService.Endpoints()
|
|
|
|
if err != nil {
|
|
|
|
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve endpoints from the database", err}
|
|
|
|
}
|
|
|
|
|
2019-07-20 23:28:11 +00:00
|
|
|
for _, id := range payload.AssociatedEndpoints {
|
|
|
|
for _, endpoint := range endpoints {
|
|
|
|
if endpoint.ID == id {
|
|
|
|
endpoint.GroupID = endpointGroup.ID
|
|
|
|
|
|
|
|
err := handler.EndpointService.UpdateEndpoint(endpoint.ID, &endpoint)
|
|
|
|
if err != nil {
|
|
|
|
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to update endpoint", err}
|
|
|
|
}
|
|
|
|
|
|
|
|
break
|
2018-06-11 13:13:19 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return response.JSON(w, endpointGroup)
|
|
|
|
}
|