mirror of
https://github.com/portainer/portainer.git
synced 2025-07-24 07:49:41 +02:00
refactor(k8s): namespace core logic (#12142)
Co-authored-by: testA113 <aliharriss1995@gmail.com> Co-authored-by: Anthony Lapenna <anthony.lapenna@portainer.io> Co-authored-by: James Carppe <85850129+jamescarppe@users.noreply.github.com> Co-authored-by: Ali <83188384+testA113@users.noreply.github.com>
This commit is contained in:
parent
da010f3d08
commit
ea228c3d6d
276 changed files with 9241 additions and 3361 deletions
|
@ -7,165 +7,298 @@ import (
|
|||
httperror "github.com/portainer/portainer/pkg/libhttp/error"
|
||||
"github.com/portainer/portainer/pkg/libhttp/request"
|
||||
"github.com/portainer/portainer/pkg/libhttp/response"
|
||||
"github.com/rs/zerolog/log"
|
||||
k8serrors "k8s.io/apimachinery/pkg/api/errors"
|
||||
)
|
||||
|
||||
// @id getKubernetesServices
|
||||
// @summary Get a list of kubernetes services for a given namespace
|
||||
// @description Get a list of kubernetes services for a given namespace
|
||||
// @description **Access policy**: authenticated
|
||||
// @id GetKubernetesServices
|
||||
// @summary Get a list of services
|
||||
// @description Get a list of services that the user has access to.
|
||||
// @description **Access policy**: Authenticated user.
|
||||
// @tags kubernetes
|
||||
// @security ApiKeyAuth
|
||||
// @security jwt
|
||||
// @accept json
|
||||
// @security ApiKeyAuth || jwt
|
||||
// @produce json
|
||||
// @param id path int true "Environment (Endpoint) identifier"
|
||||
// @param namespace path string true "Namespace name"
|
||||
// @param lookupapplications query boolean false "Lookup applications associated with each service"
|
||||
// @param id path int true "Environment identifier"
|
||||
// @param withApplications query boolean false "Lookup applications associated with each service"
|
||||
// @success 200 {array} models.K8sServiceInfo "Success"
|
||||
// @failure 400 "Invalid request"
|
||||
// @failure 500 "Server error"
|
||||
// @router /kubernetes/{id}/namespaces/{namespace}/services [get]
|
||||
func (handler *Handler) getKubernetesServices(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
|
||||
namespace, err := request.RetrieveRouteVariableValue(r, "namespace")
|
||||
// @failure 400 "Invalid request payload, such as missing required fields or fields not meeting validation criteria."
|
||||
// @failure 401 "Unauthorized access - the user is not authenticated or does not have the necessary permissions. Ensure that you have provided a valid API key or JWT token, and that you have the required permissions."
|
||||
// @failure 403 "Permission denied - the user is authenticated but does not have the necessary permissions to access the requested resource or perform the specified operation. Check your user roles and permissions."
|
||||
// @failure 404 "Unable to find an environment with the specified identifier."
|
||||
// @failure 500 "Server error occurred while attempting to retrieve all services."
|
||||
// @router /kubernetes/{id}/services [get]
|
||||
func (handler *Handler) GetAllKubernetesServices(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
|
||||
services, err := handler.getAllKubernetesServices(r)
|
||||
if err != nil {
|
||||
return httperror.BadRequest("Invalid namespace identifier route variable", err)
|
||||
}
|
||||
|
||||
cli, handlerErr := handler.getProxyKubeClient(r)
|
||||
if handlerErr != nil {
|
||||
return handlerErr
|
||||
}
|
||||
|
||||
lookup, err := request.RetrieveBooleanQueryParameter(r, "lookupapplications", true)
|
||||
if err != nil {
|
||||
return httperror.BadRequest("Invalid lookupapplications query parameter", err)
|
||||
}
|
||||
|
||||
services, err := cli.GetServices(namespace, lookup)
|
||||
if err != nil {
|
||||
return httperror.InternalServerError("Unable to retrieve services", err)
|
||||
return err
|
||||
}
|
||||
|
||||
return response.JSON(w, services)
|
||||
}
|
||||
|
||||
// @id createKubernetesService
|
||||
// @summary Create a kubernetes service
|
||||
// @description Create a kubernetes service within a given namespace
|
||||
// @description **Access policy**: authenticated
|
||||
// @id GetAllKubernetesServicesCount
|
||||
// @summary Get services count
|
||||
// @description Get the count of services that the user has access to.
|
||||
// @description **Access policy**: Authenticated user.
|
||||
// @tags kubernetes
|
||||
// @security ApiKeyAuth
|
||||
// @security jwt
|
||||
// @security ApiKeyAuth || jwt
|
||||
// @produce json
|
||||
// @param id path int true "Environment identifier"
|
||||
// @success 200 {integer} integer "Success"
|
||||
// @failure 400 "Invalid request payload, such as missing required fields or fields not meeting validation criteria."
|
||||
// @failure 401 "Unauthorized access - the user is not authenticated or does not have the necessary permissions. Ensure that you have provided a valid API key or JWT token, and that you have the required permissions."
|
||||
// @failure 403 "Permission denied - the user is authenticated but does not have the necessary permissions to access the requested resource or perform the specified operation. Check your user roles and permissions."
|
||||
// @failure 404 "Unable to find an environment with the specified identifier."
|
||||
// @failure 500 "Server error occurred while attempting to retrieve the total count of all services."
|
||||
// @router /kubernetes/{id}/services/count [get]
|
||||
func (handler *Handler) getAllKubernetesServicesCount(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
|
||||
services, err := handler.getAllKubernetesServices(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return response.JSON(w, len(services))
|
||||
}
|
||||
|
||||
func (handler *Handler) getAllKubernetesServices(r *http.Request) ([]models.K8sServiceInfo, *httperror.HandlerError) {
|
||||
withApplications, err := request.RetrieveBooleanQueryParameter(r, "withApplications", true)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Str("context", "GetAllKubernetesServices").Msg("Unable to retrieve withApplications identifier")
|
||||
return nil, httperror.BadRequest("unable to retrieve withApplications query parameter. Error: ", err)
|
||||
}
|
||||
|
||||
cli, httpErr := handler.prepareKubeClient(r)
|
||||
if httpErr != nil {
|
||||
log.Error().Err(httpErr).Str("context", "GetAllKubernetesServices").Msg("Unable to get a Kubernetes client for the user")
|
||||
return nil, httperror.InternalServerError("unable to get a Kubernetes client for the user. Error: ", httpErr)
|
||||
}
|
||||
|
||||
services, err := cli.GetServices("")
|
||||
if err != nil {
|
||||
if k8serrors.IsUnauthorized(err) || k8serrors.IsForbidden(err) {
|
||||
log.Error().Err(err).Str("context", "GetAllKubernetesServices").Msg("Unauthorized access to the Kubernetes API")
|
||||
return nil, httperror.Forbidden("unauthorized access to the Kubernetes API. Error: ", err)
|
||||
}
|
||||
|
||||
log.Error().Err(err).Str("context", "GetAllKubernetesServices").Msg("Unable to retrieve services from the Kubernetes for a cluster level user")
|
||||
return nil, httperror.InternalServerError("unable to retrieve services from the Kubernetes for a cluster level user. Error: ", err)
|
||||
}
|
||||
|
||||
if withApplications && len(services) > 0 {
|
||||
servicesWithApplications, err := cli.CombineServicesWithApplications(services)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Str("context", "GetAllKubernetesServices").Msg("Unable to combine services with applications")
|
||||
return nil, httperror.InternalServerError("unable to combine services with applications. Error: ", err)
|
||||
}
|
||||
|
||||
return servicesWithApplications, nil
|
||||
}
|
||||
|
||||
return services, nil
|
||||
}
|
||||
|
||||
// @id GetKubernetesServicesByNamespace
|
||||
// @summary Get a list of services for a given namespace
|
||||
// @description Get a list of services for a given namespace.
|
||||
// @description **Access policy**: Authenticated user.
|
||||
// @tags kubernetes
|
||||
// @security ApiKeyAuth || jwt
|
||||
// @produce json
|
||||
// @param id path int true "Environment identifier"
|
||||
// @param namespace path string true "Namespace name"
|
||||
// @success 200 {array} models.K8sServiceInfo "Success"
|
||||
// @failure 400 "Invalid request payload, such as missing required fields or fields not meeting validation criteria."
|
||||
// @failure 401 "Unauthorized access - the user is not authenticated or does not have the necessary permissions. Ensure that you have provided a valid API key or JWT token, and that you have the required permissions."
|
||||
// @failure 403 "Permission denied - the user is authenticated but does not have the necessary permissions to access the requested resource or perform the specified operation. Check your user roles and permissions."
|
||||
// @failure 404 "Unable to find an environment with the specified identifier."
|
||||
// @failure 500 "Server error occurred while attempting to retrieve all services for a namespace."
|
||||
// @router /kubernetes/{id}/namespaces/{namespace}/services [get]
|
||||
func (handler *Handler) getKubernetesServicesByNamespace(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
|
||||
namespace, err := request.RetrieveRouteVariableValue(r, "namespace")
|
||||
if err != nil {
|
||||
log.Error().Err(err).Str("context", "GetKubernetesServicesByNamespace").Str("namespace", namespace).Msg("Unable to retrieve namespace identifier route variable")
|
||||
return httperror.BadRequest("unable to retrieve namespace identifier route variable. Error: ", err)
|
||||
}
|
||||
|
||||
cli, httpError := handler.getProxyKubeClient(r)
|
||||
if httpError != nil {
|
||||
return httpError
|
||||
}
|
||||
|
||||
services, err := cli.GetServices(namespace)
|
||||
if err != nil {
|
||||
if k8serrors.IsUnauthorized(err) || k8serrors.IsForbidden(err) {
|
||||
log.Error().Err(err).Str("context", "GetKubernetesServicesByNamespace").Str("namespace", namespace).Msg("Unauthorized access to the Kubernetes API")
|
||||
return httperror.Forbidden("unauthorized access to the Kubernetes API. Error: ", err)
|
||||
}
|
||||
|
||||
log.Error().Err(err).Str("context", "GetKubernetesServicesByNamespace").Str("namespace", namespace).Msg("Unable to retrieve services from the Kubernetes for a namespace level user")
|
||||
return httperror.InternalServerError("unable to retrieve services from the Kubernetes for a namespace level user. Error: ", err)
|
||||
}
|
||||
|
||||
return response.JSON(w, services)
|
||||
}
|
||||
|
||||
// @id CreateKubernetesService
|
||||
// @summary Create a service
|
||||
// @description Create a service within a given namespace
|
||||
// @description **Access policy**: Authenticated user.
|
||||
// @tags kubernetes
|
||||
// @security ApiKeyAuth || jwt
|
||||
// @accept json
|
||||
// @produce json
|
||||
// @param id path int true "Environment (Endpoint) identifier"
|
||||
// @param id path int true "Environment identifier"
|
||||
// @param namespace path string true "Namespace name"
|
||||
// @param body body models.K8sServiceInfo true "Service definition"
|
||||
// @success 200 "Success"
|
||||
// @failure 400 "Invalid request"
|
||||
// @failure 500 "Server error"
|
||||
// @success 204 "Success"
|
||||
// @failure 400 "Invalid request payload, such as missing required fields or fields not meeting validation criteria."
|
||||
// @failure 401 "Unauthorized access - the user is not authenticated or does not have the necessary permissions. Ensure that you have provided a valid API key or JWT token, and that you have the required permissions."
|
||||
// @failure 403 "Permission denied - the user is authenticated but does not have the necessary permissions to access the requested resource or perform the specified operation. Check your user roles and permissions."
|
||||
// @failure 404 "Unable to find an environment with the specified identifier."
|
||||
// @failure 500 "Server error occurred while attempting to create a service."
|
||||
// @router /kubernetes/{id}/namespaces/{namespace}/services [post]
|
||||
func (handler *Handler) createKubernetesService(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
|
||||
namespace, err := request.RetrieveRouteVariableValue(r, "namespace")
|
||||
if err != nil {
|
||||
return httperror.BadRequest("Invalid namespace identifier route variable", err)
|
||||
log.Error().Err(err).Str("context", "CreateKubernetesService").Str("namespace", namespace).Msg("Unable to retrieve namespace identifier route variable")
|
||||
return httperror.BadRequest("unable to retrieve namespace identifier route variable. Error: ", err)
|
||||
}
|
||||
|
||||
var payload models.K8sServiceInfo
|
||||
err = request.DecodeAndValidateJSONPayload(r, &payload)
|
||||
if err != nil {
|
||||
return httperror.BadRequest("Invalid request payload", err)
|
||||
log.Error().Err(err).Str("context", "CreateKubernetesService").Str("namespace", namespace).Msg("Unable to decode and validate the request payload")
|
||||
return httperror.BadRequest("unable to decode and validate the request payload. Error: ", err)
|
||||
}
|
||||
|
||||
cli, handlerErr := handler.getProxyKubeClient(r)
|
||||
if handlerErr != nil {
|
||||
return handlerErr
|
||||
serviceName := payload.Name
|
||||
cli, httpError := handler.getProxyKubeClient(r)
|
||||
if httpError != nil {
|
||||
log.Error().Err(httpError).Str("context", "CreateKubernetesService").Str("namespace", namespace).Str("service", serviceName).Msg("Unable to get a Kubernetes client for the user")
|
||||
return httperror.InternalServerError("unable to get a Kubernetes client for the user. Error: ", httpError)
|
||||
}
|
||||
|
||||
err = cli.CreateService(namespace, payload)
|
||||
if err != nil {
|
||||
return httperror.InternalServerError("Unable to create sercice", err)
|
||||
if k8serrors.IsUnauthorized(err) || k8serrors.IsForbidden(err) {
|
||||
log.Error().Err(err).Str("context", "CreateKubernetesService").Str("namespace", namespace).Str("service", serviceName).Msg("Unauthorized access to the Kubernetes API")
|
||||
return httperror.Forbidden("unauthorized access to the Kubernetes API. Error: ", err)
|
||||
}
|
||||
|
||||
if k8serrors.IsAlreadyExists(err) {
|
||||
log.Error().Err(err).Str("context", "CreateKubernetesService").Str("namespace", namespace).Str("service", serviceName).Msg("A service with the same name already exists in the namespace")
|
||||
return httperror.Conflict("a service with the same name already exists in the namespace. Error: ", err)
|
||||
}
|
||||
|
||||
log.Error().Err(err).Str("context", "CreateKubernetesService").Str("namespace", namespace).Str("service", serviceName).Msg("Unable to create a service")
|
||||
return httperror.InternalServerError("unable to create a service. Error: ", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
return response.Empty(w)
|
||||
}
|
||||
|
||||
// @id deleteKubernetesServices
|
||||
// @summary Delete kubernetes services
|
||||
// @description Delete the provided list of kubernetes services
|
||||
// @description **Access policy**: authenticated
|
||||
// @id DeleteKubernetesServices
|
||||
// @summary Delete services
|
||||
// @description Delete the provided list of services.
|
||||
// @description **Access policy**: Authenticated user.
|
||||
// @tags kubernetes
|
||||
// @security ApiKeyAuth
|
||||
// @security jwt
|
||||
// @security ApiKeyAuth || jwt
|
||||
// @accept json
|
||||
// @produce json
|
||||
// @param id path int true "Environment (Endpoint) identifier"
|
||||
// @param id path int true "Environment identifier"
|
||||
// @param body body models.K8sServiceDeleteRequests true "A map where the key is the namespace and the value is an array of services to delete"
|
||||
// @success 200 "Success"
|
||||
// @failure 400 "Invalid request"
|
||||
// @failure 500 "Server error"
|
||||
// @success 204 "Success"
|
||||
// @failure 400 "Invalid request payload, such as missing required fields or fields not meeting validation criteria."
|
||||
// @failure 401 "Unauthorized access - the user is not authenticated or does not have the necessary permissions. Ensure that you have provided a valid API key or JWT token, and that you have the required permissions."
|
||||
// @failure 403 "Permission denied - the user is authenticated but does not have the necessary permissions to access the requested resource or perform the specified operation. Check your user roles and permissions."
|
||||
// @failure 404 "Unable to find an environment with the specified identifier or unable to find a specific service."
|
||||
// @failure 500 "Server error occurred while attempting to delete services."
|
||||
// @router /kubernetes/{id}/services/delete [post]
|
||||
func (handler *Handler) deleteKubernetesServices(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
|
||||
var payload models.K8sServiceDeleteRequests
|
||||
payload := models.K8sServiceDeleteRequests{}
|
||||
err := request.DecodeAndValidateJSONPayload(r, &payload)
|
||||
if err != nil {
|
||||
return httperror.BadRequest(
|
||||
"Invalid request payload",
|
||||
err,
|
||||
)
|
||||
log.Error().Err(err).Str("context", "DeleteKubernetesServices").Msg("Unable to decode and validate the request payload")
|
||||
return httperror.BadRequest("unable to decode and validate the request payload. Error: ", err)
|
||||
}
|
||||
|
||||
cli, handlerErr := handler.getProxyKubeClient(r)
|
||||
if handlerErr != nil {
|
||||
return handlerErr
|
||||
cli, httpError := handler.getProxyKubeClient(r)
|
||||
if httpError != nil {
|
||||
return httpError
|
||||
}
|
||||
|
||||
err = cli.DeleteServices(payload)
|
||||
if err != nil {
|
||||
return httperror.InternalServerError(
|
||||
"Unable to delete service",
|
||||
err,
|
||||
)
|
||||
if k8serrors.IsUnauthorized(err) || k8serrors.IsForbidden(err) {
|
||||
log.Error().Err(err).Str("context", "DeleteKubernetesServices").Msg("Unauthorized access to the Kubernetes API")
|
||||
return httperror.Forbidden("unauthorized access to the Kubernetes API. Error: ", err)
|
||||
}
|
||||
|
||||
if k8serrors.IsNotFound(err) {
|
||||
log.Error().Err(err).Str("context", "DeleteKubernetesServices").Msg("Unable to find the services to delete")
|
||||
return httperror.NotFound("unable to find the services to delete. Error: ", err)
|
||||
}
|
||||
|
||||
log.Error().Err(err).Str("context", "DeleteKubernetesServices").Msg("Unable to delete services")
|
||||
return httperror.InternalServerError("unable to delete services. Error: ", err)
|
||||
}
|
||||
return nil
|
||||
|
||||
return response.Empty(w)
|
||||
}
|
||||
|
||||
// @id updateKubernetesService
|
||||
// @summary Update a kubernetes service
|
||||
// @description Update a kubernetes service within a given namespace
|
||||
// @description **Access policy**: authenticated
|
||||
// @id UpdateKubernetesService
|
||||
// @summary Update a service
|
||||
// @description Update a service within a given namespace.
|
||||
// @description **Access policy**: Authenticated user.
|
||||
// @tags kubernetes
|
||||
// @security ApiKeyAuth
|
||||
// @security jwt
|
||||
// @security ApiKeyAuth || jwt
|
||||
// @accept json
|
||||
// @produce json
|
||||
// @param id path int true "Environment (Endpoint) identifier"
|
||||
// @param id path int true "Environment identifier"
|
||||
// @param namespace path string true "Namespace name"
|
||||
// @param body body models.K8sServiceInfo true "Service definition"
|
||||
// @success 200 "Success"
|
||||
// @failure 400 "Invalid request"
|
||||
// @failure 500 "Server error"
|
||||
// @success 204 "Success"
|
||||
// @failure 400 "Invalid request payload, such as missing required fields or fields not meeting validation criteria."
|
||||
// @failure 401 "Unauthorized access - the user is not authenticated or does not have the necessary permissions. Ensure that you have provided a valid API key or JWT token, and that you have the required permissions."
|
||||
// @failure 403 "Permission denied - the user is authenticated but does not have the necessary permissions to access the requested resource or perform the specified operation. Check your user roles and permissions."
|
||||
// @failure 404 "Unable to find an environment with the specified identifier or unable to find the service to update."
|
||||
// @failure 500 "Server error occurred while attempting to update a service."
|
||||
// @router /kubernetes/{id}/namespaces/{namespace}/services [put]
|
||||
func (handler *Handler) updateKubernetesService(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
|
||||
namespace, err := request.RetrieveRouteVariableValue(r, "namespace")
|
||||
if err != nil {
|
||||
return httperror.BadRequest("Invalid namespace identifier route variable", err)
|
||||
log.Error().Err(err).Str("context", "UpdateKubernetesService").Str("namespace", namespace).Msg("Unable to retrieve namespace identifier route variable")
|
||||
return httperror.BadRequest("unable to retrieve namespace identifier route variable. Error: ", err)
|
||||
}
|
||||
|
||||
var payload models.K8sServiceInfo
|
||||
err = request.DecodeAndValidateJSONPayload(r, &payload)
|
||||
if err != nil {
|
||||
return httperror.BadRequest("Invalid request payload", err)
|
||||
log.Error().Err(err).Str("context", "UpdateKubernetesService").Str("namespace", namespace).Msg("Unable to decode and validate the request payload")
|
||||
return httperror.BadRequest("unable to decode and validate the request payload. Error: ", err)
|
||||
}
|
||||
|
||||
cli, handlerErr := handler.getProxyKubeClient(r)
|
||||
if handlerErr != nil {
|
||||
return handlerErr
|
||||
serviceName := payload.Name
|
||||
cli, httpError := handler.getProxyKubeClient(r)
|
||||
if httpError != nil {
|
||||
log.Error().Err(httpError).Str("context", "UpdateKubernetesService").Str("namespace", namespace).Str("service", serviceName).Msg("Unable to get a Kubernetes client for the user")
|
||||
return httperror.InternalServerError("unable to get a Kubernetes client for the user. Error: ", httpError)
|
||||
}
|
||||
|
||||
err = cli.UpdateService(namespace, payload)
|
||||
if err != nil {
|
||||
return httperror.InternalServerError("Unable to update service", err)
|
||||
if k8serrors.IsUnauthorized(err) || k8serrors.IsForbidden(err) {
|
||||
log.Error().Err(err).Str("context", "UpdateKubernetesService").Str("namespace", namespace).Str("service", serviceName).Msg("Unauthorized access to the Kubernetes API")
|
||||
return httperror.Forbidden("unauthorized access to the Kubernetes API. Error: ", err)
|
||||
}
|
||||
|
||||
if k8serrors.IsNotFound(err) {
|
||||
log.Error().Err(err).Str("context", "UpdateKubernetesService").Str("namespace", namespace).Str("service", serviceName).Msg("Unable to find the service to update")
|
||||
return httperror.NotFound("unable to find the service to update. Error: ", err)
|
||||
}
|
||||
|
||||
log.Error().Err(err).Str("context", "UpdateKubernetesService").Str("namespace", namespace).Str("service", serviceName).Msg("Unable to update a service")
|
||||
return httperror.InternalServerError("unable to update a service. Error: ", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue