diff --git a/api/http/handler/kubernetes/deprecated_routes.go b/api/http/handler/kubernetes/deprecated_routes.go new file mode 100644 index 000000000..cc44d10e5 --- /dev/null +++ b/api/http/handler/kubernetes/deprecated_routes.go @@ -0,0 +1,51 @@ +package kubernetes + +import ( + "bytes" + "io" + "net/http" + + models "github.com/portainer/portainer/api/http/models/kubernetes" + httperror "github.com/portainer/portainer/pkg/libhttp/error" + "github.com/portainer/portainer/pkg/libhttp/request" +) + +// @id UpdateKubernetesNamespaceDeprecated +// @summary Update a namespace +// @description Update a namespace within the given environment. +// @description **Access policy**: Authenticated user. +// @tags kubernetes +// @security ApiKeyAuth || jwt +// @accept json +// @produce json +// @param id path int true "Environment identifier" +// @param namespace path string true "Namespace" +// @param body body models.K8sNamespaceDetails true "Namespace details" +// @success 200 {object} portainer.K8sNamespaceInfo "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 namespace." +// @failure 500 "Server error occurred while attempting to update the namespace." +// @router /kubernetes/{id}/namespaces [put] +func deprecatedNamespaceParser(w http.ResponseWriter, r *http.Request) (string, *httperror.HandlerError) { + environmentId, err := request.RetrieveRouteVariableValue(r, "id") + if err != nil { + return "", httperror.BadRequest("Invalid query parameter: id", err) + } + + // Restore the original body for further use + bodyBytes, err := io.ReadAll(r.Body) + r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) + + payload := models.K8sNamespaceDetails{} + err = request.DecodeAndValidateJSONPayload(r, &payload) + if err != nil { + return "", httperror.BadRequest("Invalid request. Unable to parse namespace payload", err) + } + namespaceName := payload.Name + + r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) + + return "/kubernetes/" + environmentId + "/namespaces/" + namespaceName, nil +} diff --git a/api/http/handler/kubernetes/handler.go b/api/http/handler/kubernetes/handler.go index 16db63329..2ea77e589 100644 --- a/api/http/handler/kubernetes/handler.go +++ b/api/http/handler/kubernetes/handler.go @@ -81,11 +81,11 @@ func NewHandler(bouncer security.BouncerService, authorizationService *authoriza endpointRouter.Handle("/services/delete", httperror.LoggerHandler(h.deleteKubernetesServices)).Methods(http.MethodPost) endpointRouter.Handle("/rbac_enabled", httperror.LoggerHandler(h.getKubernetesRBACStatus)).Methods(http.MethodGet) endpointRouter.Handle("/namespaces", httperror.LoggerHandler(h.createKubernetesNamespace)).Methods(http.MethodPost) - endpointRouter.Handle("/namespaces", httperror.LoggerHandler(h.updateKubernetesNamespace)).Methods(http.MethodPut) endpointRouter.Handle("/namespaces", httperror.LoggerHandler(h.deleteKubernetesNamespace)).Methods(http.MethodDelete) endpointRouter.Handle("/namespaces", httperror.LoggerHandler(h.getKubernetesNamespaces)).Methods(http.MethodGet) endpointRouter.Handle("/namespaces/count", httperror.LoggerHandler(h.getKubernetesNamespacesCount)).Methods(http.MethodGet) endpointRouter.Handle("/namespaces/{namespace}", httperror.LoggerHandler(h.getKubernetesNamespace)).Methods(http.MethodGet) + endpointRouter.Handle("/namespaces/{namespace}", httperror.LoggerHandler(h.updateKubernetesNamespace)).Methods(http.MethodPut) endpointRouter.Handle("/volumes", httperror.LoggerHandler(h.GetAllKubernetesVolumes)).Methods(http.MethodGet) endpointRouter.Handle("/volumes/count", httperror.LoggerHandler(h.getAllKubernetesVolumesCount)).Methods(http.MethodGet) endpointRouter.Handle("/service_accounts", httperror.LoggerHandler(h.getAllKubernetesServiceAccounts)).Methods(http.MethodGet) @@ -115,8 +115,12 @@ func NewHandler(bouncer security.BouncerService, authorizationService *authoriza namespaceRouter.Handle("/services", httperror.LoggerHandler(h.createKubernetesService)).Methods(http.MethodPost) namespaceRouter.Handle("/services", httperror.LoggerHandler(h.updateKubernetesService)).Methods(http.MethodPut) namespaceRouter.Handle("/services", httperror.LoggerHandler(h.getKubernetesServicesByNamespace)).Methods(http.MethodGet) + namespaceRouter.Handle("/volumes", httperror.LoggerHandler(h.GetKubernetesVolumesInNamespace)).Methods(http.MethodGet) namespaceRouter.Handle("/volumes/{volume}", httperror.LoggerHandler(h.getKubernetesVolume)).Methods(http.MethodGet) + // Deprecated + endpointRouter.Handle("/namespaces", middlewares.Deprecated(endpointRouter, deprecatedNamespaceParser)).Methods(http.MethodPut) + return h } diff --git a/api/http/handler/kubernetes/volumes.go b/api/http/handler/kubernetes/volumes.go index 6702f6b7a..70163f7bd 100644 --- a/api/http/handler/kubernetes/volumes.go +++ b/api/http/handler/kubernetes/volumes.go @@ -27,7 +27,7 @@ import ( // @failure 500 "Server error occurred while attempting to retrieve kubernetes volumes." // @router /kubernetes/{id}/volumes [get] func (handler *Handler) GetAllKubernetesVolumes(w http.ResponseWriter, r *http.Request) *httperror.HandlerError { - volumes, err := handler.getKubernetesVolumes(r) + volumes, err := handler.getKubernetesVolumes(r, "") if err != nil { return err } @@ -49,7 +49,7 @@ func (handler *Handler) GetAllKubernetesVolumes(w http.ResponseWriter, r *http.R // @failure 500 "Server error occurred while attempting to retrieve kubernetes volumes count." // @router /kubernetes/{id}/volumes/count [get] func (handler *Handler) getAllKubernetesVolumesCount(w http.ResponseWriter, r *http.Request) *httperror.HandlerError { - volumes, err := handler.getKubernetesVolumes(r) + volumes, err := handler.getKubernetesVolumes(r, "") if err != nil { return err } @@ -57,6 +57,36 @@ func (handler *Handler) getAllKubernetesVolumesCount(w http.ResponseWriter, r *h return response.JSON(w, len(volumes)) } +// @id GetKubernetesVolumesInNamespace +// @summary Get Kubernetes volumes within a namespace in the given Portainer environment +// @description Get a list of kubernetes volumes within the specified namespace in the given environment (Endpoint). The Endpoint ID must be a valid Portainer environment identifier. +// @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 identifier" +// @param withApplications query boolean false "When set to True, include the applications that are using the volumes. It is set to false by default" +// @success 200 {object} map[string]kubernetes.K8sVolumeInfo "Success" +// @failure 400 "Invalid request payload, such as missing required fields or fields not meeting validation criteria." +// @failure 403 "Unauthorized access or operation not allowed." +// @failure 500 "Server error occurred while attempting to retrieve kubernetes volumes in the namespace." +// @router /kubernetes/{id}/namespaces/{namespace}/volumes [get] +func (handler *Handler) GetKubernetesVolumesInNamespace(w http.ResponseWriter, r *http.Request) *httperror.HandlerError { + namespace, err := request.RetrieveRouteVariableValue(r, "namespace") + if err != nil { + log.Error().Err(err).Str("context", "GetKubernetesVolumesInNamespace").Msg("Unable to retrieve namespace identifier") + return httperror.BadRequest("Invalid namespace identifier", err) + } + + volumes, httpErr := handler.getKubernetesVolumes(r, namespace) + if httpErr != nil { + return httpErr + } + + return response.JSON(w, volumes) +} + // @id GetKubernetesVolume // @summary Get a Kubernetes volume within the given Portainer environment // @description Get a Kubernetes volume within the given environment (Endpoint). The Endpoint ID must be a valid Portainer environment identifier. @@ -109,7 +139,7 @@ func (handler *Handler) getKubernetesVolume(w http.ResponseWriter, r *http.Reque return response.JSON(w, volume) } -func (handler *Handler) getKubernetesVolumes(r *http.Request) ([]models.K8sVolumeInfo, *httperror.HandlerError) { +func (handler *Handler) getKubernetesVolumes(r *http.Request, namespace string) ([]models.K8sVolumeInfo, *httperror.HandlerError) { withApplications, err := request.RetrieveBooleanQueryParameter(r, "withApplications", true) if err != nil { log.Error().Err(err).Str("context", "GetKubernetesVolumes").Bool("withApplications", withApplications).Msg("Unable to parse query parameter") @@ -122,7 +152,7 @@ func (handler *Handler) getKubernetesVolumes(r *http.Request) ([]models.K8sVolum return nil, httperror.InternalServerError("Failed to prepare Kubernetes client", httpErr) } - volumes, err := cli.GetVolumes("") + volumes, err := cli.GetVolumes(namespace) if err != nil { if k8serrors.IsUnauthorized(err) { log.Error().Err(err).Str("context", "GetKubernetesVolumes").Msg("Unauthorized access") diff --git a/api/kubernetes/cli/namespace.go b/api/kubernetes/cli/namespace.go index 24c6cab60..0ebb6189a 100644 --- a/api/kubernetes/cli/namespace.go +++ b/api/kubernetes/cli/namespace.go @@ -47,7 +47,9 @@ func (kcl *KubeClient) GetNamespaces() (map[string]portainer.K8sNamespaceInfo, e // fetchNamespacesForNonAdmin gets the namespaces in the current k8s environment(endpoint) for the non-admin user. func (kcl *KubeClient) fetchNamespacesForNonAdmin() (map[string]portainer.K8sNamespaceInfo, error) { - log.Debug().Msgf("Fetching namespaces for non-admin user: %v", kcl.NonAdminNamespaces) + log.Debug(). + Str("context", "fetchNamespacesForNonAdmin"). + Msg("Fetching namespaces for non-admin user") if len(kcl.NonAdminNamespaces) == 0 { return nil, nil @@ -75,6 +77,11 @@ func (kcl *KubeClient) fetchNamespacesForNonAdmin() (map[string]portainer.K8sNam func (kcl *KubeClient) fetchNamespaces() (map[string]portainer.K8sNamespaceInfo, error) { namespaces, err := kcl.cli.CoreV1().Namespaces().List(context.TODO(), metav1.ListOptions{}) if err != nil { + log.Error(). + Str("context", "fetchNamespaces"). + Err(err). + Msg("Failed to list namespaces") + return nil, fmt.Errorf("an error occurred during the fetchNamespacesForAdmin operation, unable to list namespaces for the admin user: %w", err) } @@ -92,6 +99,7 @@ func parseNamespace(namespace *corev1.Namespace) portainer.K8sNamespaceInfo { Id: string(namespace.UID), Name: namespace.Name, Status: namespace.Status, + Annotations: namespace.Annotations, CreationDate: namespace.CreationTimestamp.Format(time.RFC3339), NamespaceOwner: namespace.Labels[namespaceOwnerLabel], IsSystem: isSystemNamespace(namespace), @@ -103,13 +111,18 @@ func parseNamespace(namespace *corev1.Namespace) portainer.K8sNamespaceInfo { func (kcl *KubeClient) GetNamespace(name string) (portainer.K8sNamespaceInfo, error) { namespace, err := kcl.cli.CoreV1().Namespaces().Get(context.TODO(), name, metav1.GetOptions{}) if err != nil { + log.Error(). + Str("context", "GetNamespace"). + Str("namespace", name). + Err(err). + Msg("Failed to get namespace") return portainer.K8sNamespaceInfo{}, err } return parseNamespace(namespace), nil } -// CreateNamespace creates a new ingress in a given namespace in a k8s endpoint. +// CreateNamespace creates a new namespace in a k8s endpoint. func (kcl *KubeClient) CreateNamespace(info models.K8sNamespaceDetails) (*corev1.Namespace, error) { portainerLabels := map[string]string{ namespaceNameLabel: stackutils.SanitizeLabel(info.Name), @@ -125,52 +138,127 @@ func (kcl *KubeClient) CreateNamespace(info models.K8sNamespaceDetails) (*corev1 if err != nil { log.Error(). Err(err). + Str("context", "CreateNamespace"). Str("Namespace", info.Name). Msg("Failed to create the namespace") return nil, err } - if info.ResourceQuota != nil && info.ResourceQuota.Enabled { - log.Info().Msgf("Creating resource quota for namespace %s", info.Name) - log.Debug().Msgf("Creating resource quota with details: %+v", info.ResourceQuota) - - resourceQuota := &corev1.ResourceQuota{ - ObjectMeta: metav1.ObjectMeta{ - Name: "portainer-rq-" + info.Name, - Namespace: info.Name, - Labels: portainerLabels, - }, - Spec: corev1.ResourceQuotaSpec{ - Hard: corev1.ResourceList{}, - }, - } - - if info.ResourceQuota.Enabled { - memory := resource.MustParse(info.ResourceQuota.Memory) - cpu := resource.MustParse(info.ResourceQuota.CPU) - if memory.Value() > 0 { - memQuota := memory - resourceQuota.Spec.Hard[corev1.ResourceLimitsMemory] = memQuota - resourceQuota.Spec.Hard[corev1.ResourceRequestsMemory] = memQuota - } - - if cpu.Value() > 0 { - cpuQuota := cpu - resourceQuota.Spec.Hard[corev1.ResourceLimitsCPU] = cpuQuota - resourceQuota.Spec.Hard[corev1.ResourceRequestsCPU] = cpuQuota - } - } - - _, err := kcl.cli.CoreV1().ResourceQuotas(info.Name).Create(context.Background(), resourceQuota, metav1.CreateOptions{}) - if err != nil { - log.Error().Msgf("Failed to create resource quota for namespace %s: %s", info.Name, err) - return nil, err - } + if err := kcl.createOrUpdateNamespaceResourceQuota(info, portainerLabels); err != nil { + log.Error(). + Err(err). + Str("context", "CreateNamespace"). + Str("name", info.Name). + Msg("failed to create or update resource quota for namespace") + return nil, err } return namespace, nil } +// UpdateIngress updates an ingress in a given namespace in a k8s endpoint. +func (kcl *KubeClient) UpdateNamespace(info models.K8sNamespaceDetails) (*corev1.Namespace, error) { + portainerLabels := map[string]string{ + namespaceNameLabel: stackutils.SanitizeLabel(info.Name), + namespaceOwnerLabel: stackutils.SanitizeLabel(info.Owner), + } + + namespace := corev1.Namespace{ + ObjectMeta: metav1.ObjectMeta{ + Name: info.Name, + Annotations: info.Annotations, + }, + } + + updatedNamespace, err := kcl.cli.CoreV1().Namespaces().Update(context.Background(), &namespace, metav1.UpdateOptions{}) + if err != nil { + log.Error(). + Str("context", "UpdateNamespace"). + Str("namespace", info.Name). + Err(err). + Msg("Failed to update namespace") + return nil, err + } + + if err := kcl.createOrUpdateNamespaceResourceQuota(info, portainerLabels); err != nil { + log.Error(). + Err(err). + Str("context", "UpdateNamespace"). + Str("name", info.Name). + Msg("failed to create or update resource quota for namespace") + return nil, err + } + + return updatedNamespace, nil +} + +func (kcl *KubeClient) createOrUpdateNamespaceResourceQuota(info models.K8sNamespaceDetails, portainerLabels map[string]string) error { + if !info.ResourceQuota.Enabled { + if err := kcl.deleteNamespaceResourceQuota(info.Name); err != nil { + log.Debug().Err(err).Str("context", "createOrUpdateNamespaceResourceQuota").Str("name", info.Name).Msg("failed to delete resource quota for namespace") + } + return nil + } + + resourceQuota := &corev1.ResourceQuota{ + ObjectMeta: metav1.ObjectMeta{ + Name: "portainer-rq-" + info.Name, + Namespace: info.Name, + Labels: portainerLabels, + }, + Spec: corev1.ResourceQuotaSpec{ + Hard: corev1.ResourceList{}, + }, + } + + if info.ResourceQuota.Enabled { + memory := resource.MustParse(info.ResourceQuota.Memory) + cpu := resource.MustParse(info.ResourceQuota.CPU) + + if memory.Value() > 0 { + memQuota := memory + resourceQuota.Spec.Hard[corev1.ResourceLimitsMemory] = memQuota + resourceQuota.Spec.Hard[corev1.ResourceRequestsMemory] = memQuota + } + + if cpu.Value() > 0 { + cpuQuota := cpu + resourceQuota.Spec.Hard[corev1.ResourceLimitsCPU] = cpuQuota + resourceQuota.Spec.Hard[corev1.ResourceRequestsCPU] = cpuQuota + } + } + + _, err := kcl.cli.CoreV1().ResourceQuotas(info.Name).Update(context.Background(), resourceQuota, metav1.UpdateOptions{}) + if err != nil { + if k8serrors.IsNotFound(err) { + log.Warn(). + Str("context", "createOrUpdateNamespaceResourceQuota"). + Str("name", info.Name). + Msg("resource quota not found, creating") + _, err = kcl.cli.CoreV1().ResourceQuotas(info.Name).Create(context.Background(), resourceQuota, metav1.CreateOptions{}) + } + } + + return err +} + +func (kcl *KubeClient) deleteNamespaceResourceQuota(namespaceName string) error { + err := kcl.cli.CoreV1().ResourceQuotas(namespaceName).Delete(context.Background(), "portainer-rq-"+namespaceName, metav1.DeleteOptions{}) + if err != nil && !k8serrors.IsNotFound(err) { + log.Error(). + Str("context", "deleteNamespaceResourceQuota"). + Str("name", namespaceName). + Err(err). + Msg("failed to delete resource quota for namespace") + return err + } + log.Warn(). + Str("context", "deleteNamespaceResourceQuota"). + Str("name", namespaceName). + Msg("resource quota to delete not found") + return nil +} + func isSystemNamespace(namespace *corev1.Namespace) bool { systemLabelValue, hasSystemLabel := namespace.Labels[systemNamespaceLabel] if hasSystemLabel { @@ -180,7 +268,6 @@ func isSystemNamespace(namespace *corev1.Namespace) bool { systemNamespaces := defaultSystemNamespaces() _, isSystem := systemNamespaces[namespace.Name] - return isSystem } @@ -201,10 +288,13 @@ func (kcl *KubeClient) ToggleSystemState(namespaceName string, isSystem bool) er return nil } - nsService := kcl.cli.CoreV1().Namespaces() - - namespace, err := nsService.Get(context.TODO(), namespaceName, metav1.GetOptions{}) + namespace, err := kcl.cli.CoreV1().Namespaces().Get(context.TODO(), namespaceName, metav1.GetOptions{}) if err != nil { + log.Error(). + Str("context", "ToggleSystemState"). + Str("namespace", namespaceName). + Err(err). + Msg("failed to get namespace") return errors.Wrap(err, "failed fetching namespace object") } @@ -218,8 +308,12 @@ func (kcl *KubeClient) ToggleSystemState(namespaceName string, isSystem bool) er namespace.Labels[systemNamespaceLabel] = strconv.FormatBool(isSystem) - _, err = nsService.Update(context.TODO(), namespace, metav1.UpdateOptions{}) - if err != nil { + if _, err := kcl.cli.CoreV1().Namespaces().Update(context.TODO(), namespace, metav1.UpdateOptions{}); err != nil { + log.Error(). + Str("context", "ToggleSystemState"). + Str("namespace", namespaceName). + Err(err). + Msg("failed updating namespace object") return errors.Wrap(err, "failed updating namespace object") } @@ -228,29 +322,26 @@ func (kcl *KubeClient) ToggleSystemState(namespaceName string, isSystem bool) er } return nil - -} - -// UpdateIngress updates an ingress in a given namespace in a k8s endpoint. -func (kcl *KubeClient) UpdateNamespace(info models.K8sNamespaceDetails) (*corev1.Namespace, error) { - namespace := corev1.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: info.Name, - Annotations: info.Annotations, - }, - } - - return kcl.cli.CoreV1().Namespaces().Update(context.Background(), &namespace, metav1.UpdateOptions{}) } func (kcl *KubeClient) DeleteNamespace(namespaceName string) (*corev1.Namespace, error) { namespace, err := kcl.cli.CoreV1().Namespaces().Get(context.Background(), namespaceName, metav1.GetOptions{}) if err != nil { + log.Error(). + Str("context", "DeleteNamespace"). + Str("namespace", namespaceName). + Err(err). + Msg("failed fetching namespace object") return nil, err } err = kcl.cli.CoreV1().Namespaces().Delete(context.Background(), namespaceName, metav1.DeleteOptions{}) if err != nil { + log.Error(). + Str("context", "DeleteNamespace"). + Str("namespace", namespaceName). + Err(err). + Msg("failed deleting namespace object") return nil, err } @@ -261,6 +352,10 @@ func (kcl *KubeClient) DeleteNamespace(namespaceName string) (*corev1.Namespace, func (kcl *KubeClient) CombineNamespacesWithResourceQuotas(namespaces map[string]portainer.K8sNamespaceInfo, w http.ResponseWriter) *httperror.HandlerError { resourceQuotas, err := kcl.GetResourceQuotas("") if err != nil && !k8serrors.IsNotFound(err) { + log.Error(). + Str("context", "CombineNamespacesWithResourceQuotas"). + Err(err). + Msg("unable to retrieve resource quotas from the Kubernetes for an admin user") return httperror.InternalServerError("an error occurred during the CombineNamespacesWithResourceQuotas operation, unable to retrieve resource quotas from the Kubernetes for an admin user. Error: ", err) } @@ -275,6 +370,11 @@ func (kcl *KubeClient) CombineNamespacesWithResourceQuotas(namespaces map[string func (kcl *KubeClient) CombineNamespaceWithResourceQuota(namespace portainer.K8sNamespaceInfo, w http.ResponseWriter) *httperror.HandlerError { resourceQuota, err := kcl.GetPortainerResourceQuota(namespace.Name) if err != nil && !k8serrors.IsNotFound(err) { + log.Error(). + Str("context", "CombineNamespaceWithResourceQuota"). + Str("namespace", namespace.Name). + Err(err). + Msg("unable to retrieve the resource quota associated with the namespace") return httperror.InternalServerError(fmt.Sprintf("an error occurred during the CombineNamespaceWithResourceQuota operation, unable to retrieve the resource quota associated with the namespace: %s for a non-admin user. Error: ", namespace.Name), err) } diff --git a/api/portainer.go b/api/portainer.go index 99530febe..dbb581efe 100644 --- a/api/portainer.go +++ b/api/portainer.go @@ -611,6 +611,7 @@ type ( Id string `json:"Id"` Name string `json:"Name"` Status corev1.NamespaceStatus `json:"Status"` + Annotations map[string]string `json:"Annotations"` CreationDate string `json:"CreationDate"` NamespaceOwner string `json:"NamespaceOwner"` IsSystem bool `json:"IsSystem"` diff --git a/app/kubernetes/__module.js b/app/kubernetes/__module.js index 19567a36b..07e1cf389 100644 --- a/app/kubernetes/__module.js +++ b/app/kubernetes/__module.js @@ -478,10 +478,10 @@ angular.module('portainer.kubernetes', ['portainer.app', registriesModule, custo const resourcePool = { name: 'kubernetes.resourcePools.resourcePool', - url: '/:id', + url: '/:id?tab', views: { 'content@': { - component: 'kubernetesResourcePoolView', + component: 'namespaceView', }, }, data: { diff --git a/app/kubernetes/react/components/clusterManagement.ts b/app/kubernetes/react/components/clusterManagement.ts index 61219beff..d96979111 100644 --- a/app/kubernetes/react/components/clusterManagement.ts +++ b/app/kubernetes/react/components/clusterManagement.ts @@ -17,6 +17,6 @@ export const clusterManagementModule = angular 'resourceEventsDatatable', r2a( withUIRouter(withReactQuery(withCurrentUser(ResourceEventsDatatable))), - ['resourceId', 'storageKey', 'namespace'] + ['resourceId', 'storageKey', 'namespace', 'noWidget'] ) ).name; diff --git a/app/kubernetes/react/components/index.ts b/app/kubernetes/react/components/index.ts index e42874d86..9775b9453 100644 --- a/app/kubernetes/react/components/index.ts +++ b/app/kubernetes/react/components/index.ts @@ -4,7 +4,6 @@ import { r2a } from '@/react-tools/react2angular'; import { IngressClassDatatableAngular } from '@/react/kubernetes/cluster/ingressClass/IngressClassDatatable/IngressClassDatatableAngular'; import { NamespacesSelector } from '@/react/kubernetes/cluster/RegistryAccessView/NamespacesSelector'; import { NamespaceAccessUsersSelector } from '@/react/kubernetes/namespaces/AccessView/NamespaceAccessUsersSelector'; -import { RegistriesSelector } from '@/react/kubernetes/namespaces/components/RegistriesFormSection/RegistriesSelector'; import { KubeServicesForm } from '@/react/kubernetes/applications/CreateView/application-services/KubeServicesForm'; import { kubeServicesValidation } from '@/react/kubernetes/applications/CreateView/application-services/kubeServicesValidation'; import { withReactQuery } from '@/react-tools/withReactQuery'; @@ -106,15 +105,6 @@ export const ngModule = angular 'name', ]) ) - .component( - 'createNamespaceRegistriesSelector', - r2a(withUIRouter(withReactQuery(withCurrentUser(RegistriesSelector))), [ - 'inputId', - 'onChange', - 'options', - 'value', - ]) - ) .component( 'kubeNodesDatatable', r2a(withUIRouter(withReactQuery(withCurrentUser(NodesDatatable))), []) diff --git a/app/kubernetes/react/components/namespaces.ts b/app/kubernetes/react/components/namespaces.ts index 4e5c09447..c00b7b9b1 100644 --- a/app/kubernetes/react/components/namespaces.ts +++ b/app/kubernetes/react/components/namespaces.ts @@ -3,26 +3,11 @@ import angular from 'angular'; import { r2a } from '@/react-tools/react2angular'; import { withUIRouter } from '@/react-tools/withUIRouter'; import { withCurrentUser } from '@/react-tools/withCurrentUser'; -import { withReactQuery } from '@/react-tools/withReactQuery'; import { NamespacesDatatable } from '@/react/kubernetes/namespaces/ListView/NamespacesDatatable'; -import { NamespaceAppsDatatable } from '@/react/kubernetes/namespaces/ItemView/NamespaceAppsDatatable'; -import { AccessDatatable } from '@/react/kubernetes/namespaces/AccessView/AccessDatatable/AccessDatatable'; export const namespacesModule = angular .module('portainer.kubernetes.react.components.namespaces', []) .component( 'kubernetesNamespacesDatatable', r2a(withUIRouter(withCurrentUser(NamespacesDatatable)), []) - ) - .component( - 'kubernetesNamespaceApplicationsDatatable', - r2a(withUIRouter(withCurrentUser(NamespaceAppsDatatable)), [ - 'dataset', - 'isLoading', - 'onRefresh', - ]) - ) - .component( - 'namespaceAccessDatatable', - r2a(withUIRouter(withReactQuery(AccessDatatable)), []) ).name; diff --git a/app/kubernetes/react/views/index.ts b/app/kubernetes/react/views/index.ts index 55b4ac927..a9f7bae59 100644 --- a/app/kubernetes/react/views/index.ts +++ b/app/kubernetes/react/views/index.ts @@ -19,6 +19,7 @@ import { ServiceAccountsView } from '@/react/kubernetes/more-resources/ServiceAc import { ClusterRolesView } from '@/react/kubernetes/more-resources/ClusterRolesView'; import { RolesView } from '@/react/kubernetes/more-resources/RolesView'; import { VolumesView } from '@/react/kubernetes/volumes/ListView/VolumesView'; +import { NamespaceView } from '@/react/kubernetes/namespaces/ItemView/NamespaceView'; import { AccessView } from '@/react/kubernetes/namespaces/AccessView/AccessView'; export const viewsModule = angular @@ -27,6 +28,10 @@ export const viewsModule = angular 'kubernetesCreateNamespaceView', r2a(withUIRouter(withReactQuery(withCurrentUser(CreateNamespaceView))), []) ) + .component( + 'namespaceView', + r2a(withUIRouter(withReactQuery(withCurrentUser(NamespaceView))), []) + ) .component( 'kubernetesNamespacesView', r2a(withUIRouter(withReactQuery(withCurrentUser(NamespacesView))), []) diff --git a/app/kubernetes/views/applications/create/createApplicationController.js b/app/kubernetes/views/applications/create/createApplicationController.js index ac8aea483..0343127a4 100644 --- a/app/kubernetes/views/applications/create/createApplicationController.js +++ b/app/kubernetes/views/applications/create/createApplicationController.js @@ -3,7 +3,7 @@ import _ from 'lodash-es'; import filesizeParser from 'filesize-parser'; import * as JsonPatch from 'fast-json-patch'; import { RegistryTypes } from '@/portainer/models/registryTypes'; -import { getServices } from '@/react/kubernetes/networks/services/service'; +import { getServices } from '@/react/kubernetes/services/useNamespaceServices'; import { KubernetesConfigurationKinds } from 'Kubernetes/models/configuration/models'; import { getGlobalDeploymentOptions } from '@/react/portainer/settings/settings.service'; @@ -25,11 +25,11 @@ import KubernetesNamespaceHelper from 'Kubernetes/helpers/namespaceHelper'; import { KubernetesNodeHelper } from 'Kubernetes/node/helper'; import { updateIngress, getIngresses } from '@/react/kubernetes/ingresses/service'; import { confirmUpdateAppIngress } from '@/react/kubernetes/applications/CreateView/UpdateIngressPrompt'; +import { KUBE_STACK_NAME_VALIDATION_REGEX } from '@/react/kubernetes/DeployView/StackName/constants'; +import { isVolumeUsed } from '@/react/kubernetes/volumes/utils'; import { confirm, confirmUpdate, confirmWebEditorDiscard } from '@@/modals/confirm'; import { buildConfirmButton } from '@@/modals/utils'; import { ModalType } from '@@/modals'; -import { KUBE_STACK_NAME_VALIDATION_REGEX } from '@/react/kubernetes/DeployView/StackName/constants'; -import { isVolumeUsed } from '@/react/kubernetes/volumes/utils'; class KubernetesCreateApplicationController { /* #region CONSTRUCTOR */ diff --git a/app/kubernetes/views/resource-pools/components/storage-class-switch/index.js b/app/kubernetes/views/resource-pools/components/storage-class-switch/index.js deleted file mode 100644 index 502d1614f..000000000 --- a/app/kubernetes/views/resource-pools/components/storage-class-switch/index.js +++ /dev/null @@ -1,14 +0,0 @@ -import angular from 'angular'; -import controller from './storage-class-switch.controller.js'; - -export const storageClassSwitch = { - templateUrl: './storage-class-switch.html', - controller, - bindings: { - value: '<', - onChange: '<', - name: '<', - }, -}; - -angular.module('portainer.kubernetes').component('storageClassSwitch', storageClassSwitch); diff --git a/app/kubernetes/views/resource-pools/components/storage-class-switch/storage-class-switch.controller.js b/app/kubernetes/views/resource-pools/components/storage-class-switch/storage-class-switch.controller.js deleted file mode 100644 index 155db49a7..000000000 --- a/app/kubernetes/views/resource-pools/components/storage-class-switch/storage-class-switch.controller.js +++ /dev/null @@ -1,16 +0,0 @@ -import { FeatureId } from '@/react/portainer/feature-flags/enums'; - -class StorageClassSwitchController { - /* @ngInject */ - constructor() { - this.featureId = FeatureId.K8S_RESOURCE_POOL_STORAGE_QUOTA; - - this.handleChange = this.handleChange.bind(this); - } - - handleChange(value) { - this.onChange(this.name, value); - } -} - -export default StorageClassSwitchController; diff --git a/app/kubernetes/views/resource-pools/components/storage-class-switch/storage-class-switch.html b/app/kubernetes/views/resource-pools/components/storage-class-switch/storage-class-switch.html deleted file mode 100644 index 6f65e39ef..000000000 --- a/app/kubernetes/views/resource-pools/components/storage-class-switch/storage-class-switch.html +++ /dev/null @@ -1,13 +0,0 @@ -
-
- -
-
diff --git a/app/kubernetes/views/resource-pools/create/createResourcePool.html b/app/kubernetes/views/resource-pools/create/createResourcePool.html deleted file mode 100644 index 7c78743ca..000000000 --- a/app/kubernetes/views/resource-pools/create/createResourcePool.html +++ /dev/null @@ -1,278 +0,0 @@ - - - - -
-
-
- - -
- -
- -
- - -
-
-
-

This field is required.

-

This field must consist of lower case alphanumeric characters or '-', and contain at most 63 - characters, and must start and end with an alphanumeric character.

-
-

Prefix "kube-" is reserved for Kubernetes system namespaces.

-

- A namespace with the same name already exists. -

-
-
-
-
-
- -
- -
- - - -
Quota
- - -
-
-

- - A namespace segments the underlying physical Kubernetes cluster into smaller virtual clusters. You should assign a capped limit of resources to this namespace or - disable for the safe operation of your platform. -

-
-
- -
-
- -
-
Resource limits
-
-
- -

At least a single limit must be set for the quota to be valid. -

-

-
-
- - -
- -
- -
-
- -
-
-
- - -
-
-
-

Value must be between {{ $ctrl.defaults.MemoryLimit }} and - {{ $ctrl.state.sliderMaxMemory }} -

-
-
-
-
-
- - -
- -
- -
-
- -
-
- - - -
Load balancers
- -
- - - You can set a quota on the amount of external load balancers that can be created inside this namespace. Set this quota to 0 to effectively disable the use of load - balancers in this namespace. - -
-
-
- -
-
- - -
- -
Networking
- - -
- - -
Registries
-
-
-

- - Define which registries can be used by users who have access to this namespace. -

-
-
- -
- -
- - No registries available. Head over to the registry view to define a container registry. - - - No registries available. Contact your administrator to create a container registry. - - - -
-
- - - -
Storage
- -
- - - Quotas can be set on each storage option to prevent users from exceeding a specific threshold when deploying applications. You can set a quota to 0 to effectively - prevent the usage of a specific storage option inside this namespace. - -
-
- - standard -
- - - - - - - - - -
Actions
- -
-
- -
-
- - -
-
-
-
-
-
diff --git a/app/kubernetes/views/resource-pools/create/createResourcePoolController.js b/app/kubernetes/views/resource-pools/create/createResourcePoolController.js deleted file mode 100644 index e319e0b13..000000000 --- a/app/kubernetes/views/resource-pools/create/createResourcePoolController.js +++ /dev/null @@ -1,236 +0,0 @@ -import _ from 'lodash-es'; -import filesizeParser from 'filesize-parser'; -import { KubernetesResourceQuotaDefaults } from 'Kubernetes/models/resource-quota/models'; -import KubernetesResourceReservationHelper from 'Kubernetes/helpers/resourceReservationHelper'; -import { KubernetesResourcePoolFormValues, KubernetesResourcePoolIngressClassHostFormValue } from 'Kubernetes/models/resource-pool/formValues'; -import { KubernetesIngressConverter } from 'Kubernetes/ingress/converter'; -import { KubernetesFormValidationReferences } from 'Kubernetes/models/application/formValues'; -import { KubernetesIngressClassTypes } from 'Kubernetes/ingress/constants'; -import { FeatureId } from '@/react/portainer/feature-flags/enums'; -import { getIngressControllerClassMap, updateIngressControllerClassMap } from '@/react/kubernetes/cluster/ingressClass/useIngressControllerClassMap'; - -class KubernetesCreateResourcePoolController { - /* #region CONSTRUCTOR */ - /* @ngInject */ - constructor($async, $state, $scope, Notifications, KubernetesNodeService, KubernetesResourcePoolService, KubernetesIngressService, Authentication, EndpointService) { - Object.assign(this, { - $async, - $state, - $scope, - Notifications, - KubernetesNodeService, - KubernetesResourcePoolService, - KubernetesIngressService, - Authentication, - EndpointService, - }); - - this.IngressClassTypes = KubernetesIngressClassTypes; - this.EndpointService = EndpointService; - this.LBQuotaFeatureId = FeatureId.K8S_RESOURCE_POOL_LB_QUOTA; - - this.onToggleStorageQuota = this.onToggleStorageQuota.bind(this); - this.onToggleLoadBalancerQuota = this.onToggleLoadBalancerQuota.bind(this); - this.onToggleResourceQuota = this.onToggleResourceQuota.bind(this); - this.onChangeIngressControllerAvailability = this.onChangeIngressControllerAvailability.bind(this); - this.onRegistriesChange = this.onRegistriesChange.bind(this); - this.handleMemoryLimitChange = this.handleMemoryLimitChange.bind(this); - this.handleCpuLimitChange = this.handleCpuLimitChange.bind(this); - } - /* #endregion */ - - onRegistriesChange(registries) { - return this.$scope.$evalAsync(() => { - this.formValues.Registries = registries; - }); - } - - onToggleStorageQuota(storageClassName, enabled) { - this.$scope.$evalAsync(() => { - this.formValues.StorageClasses = this.formValues.StorageClasses.map((sClass) => (sClass.Name !== storageClassName ? sClass : { ...sClass, Selected: enabled })); - }); - } - - onToggleLoadBalancerQuota(enabled) { - this.$scope.$evalAsync(() => { - this.formValues.UseLoadBalancersQuota = enabled; - }); - } - - onToggleResourceQuota(enabled) { - this.$scope.$evalAsync(() => { - this.formValues.HasQuota = enabled; - }); - } - - /* #region INGRESS MANAGEMENT */ - onChangeIngressControllerAvailability(controllerClassMap) { - this.ingressControllers = controllerClassMap; - } - /* #endregion */ - - isCreateButtonDisabled() { - return ( - this.state.actionInProgress || - (this.formValues.HasQuota && !this.isQuotaValid()) || - this.state.isAlreadyExist || - this.state.hasPrefixKube || - this.state.duplicates.ingressHosts.hasRefs - ); - } - - onChangeName() { - this.state.isAlreadyExist = _.find(this.resourcePools, (resourcePool) => resourcePool.Namespace.Name === this.formValues.Name) !== undefined; - this.state.hasPrefixKube = /^kube-/.test(this.formValues.Name); - } - - isQuotaValid() { - if ( - this.state.sliderMaxCpu < this.formValues.CpuLimit || - this.state.sliderMaxMemory < this.formValues.MemoryLimit || - (this.formValues.CpuLimit === 0 && this.formValues.MemoryLimit === 0) - ) { - return false; - } - return true; - } - - checkDefaults() { - if (this.formValues.CpuLimit < this.defaults.CpuLimit) { - this.formValues.CpuLimit = this.defaults.CpuLimit; - } - if (this.formValues.MemoryLimit < KubernetesResourceReservationHelper.megaBytesValue(this.defaults.MemoryLimit)) { - this.formValues.MemoryLimit = KubernetesResourceReservationHelper.megaBytesValue(this.defaults.MemoryLimit); - } - } - - handleMemoryLimitChange(memoryLimit) { - return this.$async(async () => { - this.formValues.MemoryLimit = memoryLimit; - }); - } - - handleCpuLimitChange(cpuLimit) { - return this.$async(async () => { - this.formValues.CpuLimit = cpuLimit; - }); - } - - /* #region CREATE NAMESPACE */ - createResourcePool() { - return this.$async(async () => { - this.state.actionInProgress = true; - try { - this.checkDefaults(); - this.formValues.Owner = this.Authentication.getUserDetails().username; - await this.KubernetesResourcePoolService.create(this.formValues); - await updateIngressControllerClassMap(this.endpoint.Id, this.ingressControllers || [], this.formValues.Name); - this.Notifications.success('Namespace successfully created', this.formValues.Name); - this.$state.go('kubernetes.resourcePools'); - } catch (err) { - this.Notifications.error('Failure', err, 'Unable to create namespace'); - } finally { - this.state.actionInProgress = false; - } - }); - } - /* #endregion */ - - /* #region GET INGRESSES */ - getIngresses() { - return this.$async(async () => { - try { - this.allIngresses = await this.KubernetesIngressService.get(); - } catch (err) { - this.Notifications.error('Failure', err, 'Unable to retrieve ingresses.'); - } - }); - } - /* #endregion */ - - /* #region GET NAMESPACES */ - getResourcePools() { - return this.$async(async () => { - try { - this.resourcePools = await this.KubernetesResourcePoolService.get('', { getQuota: true }); - } catch (err) { - this.Notifications.error('Failure', err, 'Unable to retrieve namespaces'); - } - }); - } - /* #endregion */ - - /* #region GET REGISTRIES */ - getRegistries() { - return this.$async(async () => { - try { - this.registries = await this.EndpointService.registries(this.endpoint.Id); - } catch (err) { - this.Notifications.error('Failure', err, 'Unable to retrieve registries'); - } - }); - } - /* #endregion */ - - /* #region ON INIT */ - $onInit() { - return this.$async(async () => { - try { - const endpoint = await this.EndpointService.endpoint(this.endpoint.Id); - this.defaults = KubernetesResourceQuotaDefaults; - this.formValues = new KubernetesResourcePoolFormValues(this.defaults); - this.formValues.EndpointId = this.endpoint.Id; - this.formValues.HasQuota = false; - - this.state = { - actionInProgress: false, - sliderMaxMemory: 0, - sliderMaxCpu: 0, - viewReady: false, - isAlreadyExist: false, - hasPrefixKube: false, - canUseIngress: false, - duplicates: { - ingressHosts: new KubernetesFormValidationReferences(), - }, - isAdmin: this.Authentication.isAdmin(), - ingressAvailabilityPerNamespace: endpoint.Kubernetes.Configuration.IngressAvailabilityPerNamespace, - }; - - const nodes = await this.KubernetesNodeService.get(); - - this.ingressControllers = []; - if (this.state.ingressAvailabilityPerNamespace) { - this.ingressControllers = await getIngressControllerClassMap({ environmentId: this.endpoint.Id, allowedOnly: true }); - this.initialIngressControllers = structuredClone(this.ingressControllers); - } - - _.forEach(nodes, (item) => { - this.state.sliderMaxMemory += filesizeParser(item.Memory); - this.state.sliderMaxCpu += item.CPU; - }); - this.state.sliderMaxMemory = KubernetesResourceReservationHelper.megaBytesValue(this.state.sliderMaxMemory); - await this.getResourcePools(); - if (this.state.canUseIngress) { - await this.getIngresses(); - const ingressClasses = endpoint.Kubernetes.Configuration.IngressClasses; - this.formValues.IngressClasses = KubernetesIngressConverter.ingressClassesToFormValues(ingressClasses); - } - _.forEach(this.formValues.IngressClasses, (ic) => { - if (ic.Hosts.length === 0) { - ic.Hosts.push(new KubernetesResourcePoolIngressClassHostFormValue()); - } - }); - - await this.getRegistries(); - } catch (err) { - this.Notifications.error('Failure', err, 'Unable to load view data'); - } finally { - this.state.viewReady = true; - } - }); - } - /* #endregion */ -} - -export default KubernetesCreateResourcePoolController; diff --git a/app/kubernetes/views/resource-pools/edit/resourcePool.html b/app/kubernetes/views/resource-pools/edit/resourcePool.html deleted file mode 100644 index 5a94051eb..000000000 --- a/app/kubernetes/views/resource-pools/edit/resourcePool.html +++ /dev/null @@ -1,302 +0,0 @@ - - - - -
-
-
- - - - - Namespace -
- - - - - - - -
Name - {{ ctrl.pool.Namespace.Name }} - system -
- -
- -
- - -
Resource quota
- -
-
-
-
- -
-
- -
-
-
-
-
- - -
- -
-
Resource limits
-
-
- -

At least a single limit must be set for the quota to be valid. -

-

-
-
- -
- -
- -
-
- -
-
-
-
-
-
-

- Value must be between {{ ctrl.ResourceQuotaDefaults.MemoryLimit }} and - {{ ctrl.state.sliderMaxMemory }}. -

-
-
-
- - -
- -
- -
-
- -
-
- -
Load balancers
- -
-
-

- - You can set a quota on the amount of external load balancers that can be created inside this namespace. Set this quota to 0 to effectively disable the use of - load balancers in this namespace. -

-
-
-
-
- -
-
- -
- -
Networking
- - - -
- -
-
Registries
- -
- -
{{ ctrl.selectedRegistries ? ctrl.selectedRegistries : 'None' }}
-
- -
-
-
-

- - Define which registries can be used by users who have access to this namespace. -

-
-
-
- -
- - -
-
-
-
- - - -
Storage
- -
- -

- - Quotas can be set on each storage option to prevent users from exceeding a specific threshold when deploying applications. You can set a quota to 0 to - effectively prevent the usage of a specific storage option inside this namespace. -

-
-
- -
-
standard
-
-
- - - - - - - - - - -
Actions
-
-
- - -
-
- -
-
- - - Events -
- - {{ ctrl.state.eventWarningCount }} warning(s) -
-
- -
- - YAML -
- -
-
-
-
-
-
-
- -
- - -
-
diff --git a/app/kubernetes/views/resource-pools/edit/resourcePool.js b/app/kubernetes/views/resource-pools/edit/resourcePool.js deleted file mode 100644 index d612e9f6a..000000000 --- a/app/kubernetes/views/resource-pools/edit/resourcePool.js +++ /dev/null @@ -1,8 +0,0 @@ -angular.module('portainer.kubernetes').component('kubernetesResourcePoolView', { - templateUrl: './resourcePool.html', - controller: 'KubernetesResourcePoolController', - controllerAs: 'ctrl', - bindings: { - endpoint: '<', - }, -}); diff --git a/app/kubernetes/views/resource-pools/edit/resourcePoolController.js b/app/kubernetes/views/resource-pools/edit/resourcePoolController.js deleted file mode 100644 index 8946d2dda..000000000 --- a/app/kubernetes/views/resource-pools/edit/resourcePoolController.js +++ /dev/null @@ -1,405 +0,0 @@ -import angular from 'angular'; -import _ from 'lodash-es'; -import filesizeParser from 'filesize-parser'; -import { KubernetesResourceQuotaDefaults } from 'Kubernetes/models/resource-quota/models'; -import KubernetesResourceReservationHelper from 'Kubernetes/helpers/resourceReservationHelper'; -import { KubernetesResourceReservation } from 'Kubernetes/models/resource-reservation/models'; -import KubernetesEventHelper from 'Kubernetes/helpers/eventHelper'; - -import { KubernetesResourcePoolFormValues } from 'Kubernetes/models/resource-pool/formValues'; -import { KubernetesFormValidationReferences } from 'Kubernetes/models/application/formValues'; -import { KubernetesIngressClassTypes } from 'Kubernetes/ingress/constants'; -import KubernetesResourceQuotaConverter from 'Kubernetes/converters/resourceQuota'; -import KubernetesNamespaceHelper from 'Kubernetes/helpers/namespaceHelper'; -import { FeatureId } from '@/react/portainer/feature-flags/enums'; -import { updateIngressControllerClassMap, getIngressControllerClassMap } from '@/react/kubernetes/cluster/ingressClass/useIngressControllerClassMap'; -import { confirmUpdate } from '@@/modals/confirm'; -import { confirmUpdateNamespace } from '@/react/kubernetes/namespaces/ItemView/ConfirmUpdateNamespace'; -import { getMetricsForAllPods } from '@/react/kubernetes/metrics/metrics.ts'; - -class KubernetesResourcePoolController { - /* #region CONSTRUCTOR */ - /* @ngInject */ - constructor( - $async, - $state, - $scope, - Authentication, - Notifications, - LocalStorage, - EndpointService, - KubernetesResourceQuotaService, - KubernetesResourcePoolService, - KubernetesEventService, - KubernetesPodService, - KubernetesApplicationService, - KubernetesIngressService, - KubernetesVolumeService, - KubernetesNamespaceService, - KubernetesNodeService - ) { - Object.assign(this, { - $async, - $state, - $scope, - Authentication, - Notifications, - LocalStorage, - EndpointService, - KubernetesResourceQuotaService, - KubernetesResourcePoolService, - KubernetesEventService, - KubernetesPodService, - KubernetesApplicationService, - KubernetesIngressService, - KubernetesVolumeService, - KubernetesNamespaceService, - KubernetesNodeService, - }); - - this.IngressClassTypes = KubernetesIngressClassTypes; - this.ResourceQuotaDefaults = KubernetesResourceQuotaDefaults; - this.EndpointService = EndpointService; - - this.LBQuotaFeatureId = FeatureId.K8S_RESOURCE_POOL_LB_QUOTA; - this.StorageQuotaFeatureId = FeatureId.K8S_RESOURCE_POOL_STORAGE_QUOTA; - this.StorageQuotaFeatureId = FeatureId.K8S_RESOURCE_POOL_STORAGE_QUOTA; - - this.updateResourcePoolAsync = this.updateResourcePoolAsync.bind(this); - this.getEvents = this.getEvents.bind(this); - this.onToggleLoadBalancersQuota = this.onToggleLoadBalancersQuota.bind(this); - this.onToggleStorageQuota = this.onToggleStorageQuota.bind(this); - this.onChangeIngressControllerAvailability = this.onChangeIngressControllerAvailability.bind(this); - this.onRegistriesChange = this.onRegistriesChange.bind(this); - this.handleMemoryLimitChange = this.handleMemoryLimitChange.bind(this); - this.handleCpuLimitChange = this.handleCpuLimitChange.bind(this); - } - /* #endregion */ - - onRegistriesChange(registries) { - return this.$scope.$evalAsync(() => { - this.formValues.Registries = registries; - }); - } - - onToggleLoadBalancersQuota(checked) { - return this.$scope.$evalAsync(() => { - this.formValues.UseLoadBalancersQuota = checked; - }); - } - - onToggleStorageQuota(storageClassName, enabled) { - this.$scope.$evalAsync(() => { - this.formValues.StorageClasses = this.formValues.StorageClasses.map((sClass) => (sClass.Name !== storageClassName ? sClass : { ...sClass, Selected: enabled })); - }); - } - - onChangeIngressControllerAvailability(controllerClassMap) { - this.ingressControllers = controllerClassMap; - } - - selectTab(index) { - this.LocalStorage.storeActiveTab('resourcePool', index); - } - - isUpdateButtonDisabled() { - return this.state.actionInProgress || (this.formValues.HasQuota && !this.isQuotaValid()) || this.state.duplicates.ingressHosts.hasRefs; - } - - isQuotaValid() { - if ( - this.state.sliderMaxCpu < this.formValues.CpuLimit || - this.state.sliderMaxMemory < this.formValues.MemoryLimit || - (this.formValues.CpuLimit === 0 && this.formValues.MemoryLimit === 0) - ) { - return false; - } - return true; - } - - checkDefaults() { - if (this.formValues.CpuLimit < KubernetesResourceQuotaDefaults.CpuLimit) { - this.formValues.CpuLimit = KubernetesResourceQuotaDefaults.CpuLimit; - } - if (this.formValues.MemoryLimit < KubernetesResourceReservationHelper.megaBytesValue(KubernetesResourceQuotaDefaults.MemoryLimit)) { - this.formValues.MemoryLimit = KubernetesResourceReservationHelper.megaBytesValue(KubernetesResourceQuotaDefaults.MemoryLimit); - } - } - - handleMemoryLimitChange(memoryLimit) { - return this.$async(async () => { - this.formValues.MemoryLimit = memoryLimit; - }); - } - - handleCpuLimitChange(cpuLimit) { - return this.$async(async () => { - this.formValues.CpuLimit = cpuLimit; - }); - } - - showEditor() { - this.state.showEditorTab = true; - this.selectTab(2); - } - - hasResourceQuotaBeenReduced() { - if (this.formValues.HasQuota && this.oldQuota) { - const cpuLimit = this.formValues.CpuLimit; - const memoryLimit = KubernetesResourceReservationHelper.bytesValue(this.formValues.MemoryLimit); - if (cpuLimit < this.oldQuota.CpuLimit || memoryLimit < this.oldQuota.MemoryLimit) { - return true; - } - } - return false; - } - - /* #region UPDATE NAMESPACE */ - async updateResourcePoolAsync(oldFormValues, newFormValues) { - this.state.actionInProgress = true; - try { - this.checkDefaults(); - await this.KubernetesResourcePoolService.patch(oldFormValues, newFormValues); - await updateIngressControllerClassMap(this.endpoint.Id, this.ingressControllers || [], this.formValues.Name); - this.Notifications.success('Namespace successfully updated', this.pool.Namespace.Name); - this.$state.reload(this.$state.current); - } catch (err) { - this.Notifications.error('Failure', err, 'Unable to create namespace'); - } finally { - this.state.actionInProgress = false; - } - } - - updateResourcePool() { - const ingressesToDelete = _.filter(this.formValues.IngressClasses, { WasSelected: true, Selected: false }); - const registriesToDelete = _.filter(this.registries, { WasChecked: true, Checked: false }); - const warnings = { - quota: this.hasResourceQuotaBeenReduced(), - ingress: ingressesToDelete.length !== 0, - registries: registriesToDelete.length !== 0, - }; - - if (warnings.quota || warnings.registries) { - confirmUpdateNamespace(warnings.quota, warnings.ingress, warnings.registries).then((confirmed) => { - if (confirmed) { - return this.$async(this.updateResourcePoolAsync, this.savedFormValues, this.formValues); - } - }); - } else { - return this.$async(this.updateResourcePoolAsync, this.savedFormValues, this.formValues); - } - } - - async confirmMarkUnmarkAsSystem() { - const message = this.isSystem - ? 'Unmarking this namespace as system will allow non administrator users to manage it and the resources in contains depending on the access control settings. Are you sure?' - : 'Marking this namespace as a system namespace will prevent non administrator users from managing it and the resources it contains. Are you sure?'; - - return new Promise((resolve) => { - confirmUpdate(message, resolve); - }); - } - - markUnmarkAsSystem() { - return this.$async(async () => { - try { - const namespaceName = this.$state.params.id; - this.state.actionInProgress = true; - - const confirmed = await this.confirmMarkUnmarkAsSystem(); - if (!confirmed) { - return; - } - await this.KubernetesResourcePoolService.toggleSystem(this.endpoint.Id, namespaceName, !this.isSystem); - - this.Notifications.success('Namespace successfully updated', namespaceName); - this.$state.reload(this.$state.current); - } catch (err) { - this.Notifications.error('Failure', err, 'Unable to create namespace'); - } finally { - this.state.actionInProgress = false; - } - }); - } - /* #endregion */ - - hasEventWarnings() { - return this.state.eventWarningCount; - } - - /* #region GET EVENTS */ - getEvents() { - return this.$async(async () => { - try { - this.state.eventsLoading = true; - this.events = await this.KubernetesEventService.get(this.pool.Namespace.Name); - this.state.eventWarningCount = KubernetesEventHelper.warningCount(this.events); - } catch (err) { - this.Notifications.error('Failure', err, 'Unable to retrieve namespace related events'); - } finally { - this.state.eventsLoading = false; - } - }); - } - /* #endregion */ - - /* #region GET APPLICATIONS */ - getApplications() { - return this.$async(async () => { - try { - this.state.applicationsLoading = true; - this.applications = await this.KubernetesApplicationService.get(this.pool.Namespace.Name); - this.applications = _.map(this.applications, (app) => { - const resourceReservation = KubernetesResourceReservationHelper.computeResourceReservation(app.Pods); - app.CPU = resourceReservation.CPU; - app.Memory = resourceReservation.Memory; - return app; - }); - - if (this.state.useServerMetrics) { - await this.getResourceUsage(this.pool.Namespace.Name); - } - } catch (err) { - this.Notifications.error('Failure', err, 'Unable to retrieve applications.'); - } finally { - this.state.applicationsLoading = false; - } - }); - } - /* #endregion */ - - /* #region GET REGISTRIES */ - getRegistries() { - return this.$async(async () => { - try { - const namespace = this.$state.params.id; - - if (this.isAdmin) { - this.registries = await this.EndpointService.registries(this.endpoint.Id); - this.registries.forEach((reg) => { - if (reg.RegistryAccesses && reg.RegistryAccesses[this.endpoint.Id] && reg.RegistryAccesses[this.endpoint.Id].Namespaces.includes(namespace)) { - reg.Checked = true; - reg.WasChecked = true; - this.formValues.Registries.push(reg); - } - }); - this.selectedRegistries = this.formValues.Registries.map((r) => r.Name).join(', '); - return; - } - - const registries = await this.EndpointService.registries(this.endpoint.Id, namespace); - this.selectedRegistries = registries.map((r) => r.Name).join(', '); - } catch (err) { - this.Notifications.error('Failure', err, 'Unable to retrieve registries'); - } - }); - } - /* #endregion */ - - async getResourceUsage(namespace) { - try { - const namespaceMetrics = await getMetricsForAllPods(this.$state.params.endpointId, namespace); - // extract resource usage of all containers within each pod of the namespace - const containerResourceUsageList = namespaceMetrics.items.flatMap((i) => i.containers.map((c) => c.usage)); - const namespaceResourceUsage = containerResourceUsageList.reduce((total, u) => { - total.CPU += KubernetesResourceReservationHelper.parseCPU(u.cpu); - total.Memory += KubernetesResourceReservationHelper.megaBytesValue(u.memory); - return total; - }, new KubernetesResourceReservation()); - this.state.resourceUsage = namespaceResourceUsage; - } catch (err) { - this.Notifications.error('Failure', err, 'Unable to retrieve namespace resource usage'); - } - } - - /* #region ON INIT */ - $onInit() { - return this.$async(async () => { - try { - this.endpoint = await this.EndpointService.endpoint(this.endpoint.Id); - this.isAdmin = this.Authentication.isAdmin(); - - this.state = { - actionInProgress: false, - sliderMaxMemory: 0, - sliderMaxCpu: 0, - cpuUsage: 0, - memoryUsage: 0, - resourceReservation: { CPU: 0, Memory: 0 }, - activeTab: 0, - currentName: this.$state.$current.name, - showEditorTab: false, - eventsLoading: true, - applicationsLoading: true, - ingressesLoading: true, - viewReady: false, - eventWarningCount: 0, - useServerMetrics: this.endpoint.Kubernetes.Configuration.UseServerMetrics, - duplicates: { - ingressHosts: new KubernetesFormValidationReferences(), - }, - ingressAvailabilityPerNamespace: this.endpoint.Kubernetes.Configuration.IngressAvailabilityPerNamespace, - }; - - this.state.activeTab = this.LocalStorage.getActiveTab('resourcePool'); - - const name = this.$state.params.id; - - const [nodes, pool] = await Promise.all([this.KubernetesNodeService.get(), this.KubernetesResourcePoolService.get(name)]); - - this.ingressControllers = []; - if (this.state.ingressAvailabilityPerNamespace) { - this.ingressControllers = await getIngressControllerClassMap({ environmentId: this.endpoint.Id, namespace: name }); - this.initialIngressControllers = structuredClone(this.ingressControllers); - } - - this.pool = pool; - this.formValues = new KubernetesResourcePoolFormValues(KubernetesResourceQuotaDefaults); - this.formValues.Name = this.pool.Namespace.Name; - this.formValues.EndpointId = this.endpoint.Id; - this.formValues.IsSystem = this.pool.Namespace.IsSystem; - - _.forEach(nodes, (item) => { - this.state.sliderMaxMemory += filesizeParser(item.Memory); - this.state.sliderMaxCpu += item.CPU; - }); - this.state.sliderMaxMemory = KubernetesResourceReservationHelper.megaBytesValue(this.state.sliderMaxMemory); - - const quota = this.pool.Quota; - if (quota) { - this.oldQuota = angular.copy(quota); - this.formValues = KubernetesResourceQuotaConverter.quotaToResourcePoolFormValues(quota); - this.formValues.EndpointId = this.endpoint.Id; - - this.state.resourceReservation.CPU = quota.CpuLimitUsed; - this.state.resourceReservation.Memory = KubernetesResourceReservationHelper.megaBytesValue(quota.MemoryLimitUsed); - } - this.isSystem = KubernetesNamespaceHelper.isSystemNamespace(this.pool.Namespace.Name); - this.isDefaultNamespace = KubernetesNamespaceHelper.isDefaultNamespace(this.pool.Namespace.Name); - this.isEditable = !this.isSystem && !this.isDefaultNamespace; - - await this.getEvents(); - await this.getApplications(); - - await this.getRegistries(); - - this.savedFormValues = angular.copy(this.formValues); - } catch (err) { - this.Notifications.error('Failure', err, 'Unable to load view data'); - } finally { - this.state.viewReady = true; - } - }); - } - - /* #endregion */ - - $onDestroy() { - if (this.state.currentName !== this.$state.$current.name) { - this.LocalStorage.storeActiveTab('resourcePool', 0); - } - } -} - -export default KubernetesResourcePoolController; -angular.module('portainer.kubernetes').controller('KubernetesResourcePoolController', KubernetesResourcePoolController); diff --git a/app/kubernetes/views/resource-pools/resourcePools.html b/app/kubernetes/views/resource-pools/resourcePools.html deleted file mode 100644 index e995a16e9..000000000 --- a/app/kubernetes/views/resource-pools/resourcePools.html +++ /dev/null @@ -1,7 +0,0 @@ - - - - -
- -
diff --git a/app/kubernetes/views/resource-pools/resourcePools.js b/app/kubernetes/views/resource-pools/resourcePools.js deleted file mode 100644 index bf999a576..000000000 --- a/app/kubernetes/views/resource-pools/resourcePools.js +++ /dev/null @@ -1,8 +0,0 @@ -angular.module('portainer.kubernetes').component('kubernetesResourcePoolsView', { - templateUrl: './resourcePools.html', - controller: 'KubernetesResourcePoolsController', - controllerAs: 'ctrl', - bindings: { - endpoint: '<', - }, -}); diff --git a/app/kubernetes/views/resource-pools/resourcePoolsController.js b/app/kubernetes/views/resource-pools/resourcePoolsController.js deleted file mode 100644 index 4b39f4077..000000000 --- a/app/kubernetes/views/resource-pools/resourcePoolsController.js +++ /dev/null @@ -1,109 +0,0 @@ -import angular from 'angular'; -import { confirm } from '@@/modals/confirm'; -import { ModalType } from '@@/modals'; -import { buildConfirmButton } from '@@/modals/utils'; -import { dispatchCacheRefreshEvent } from '@/portainer/services/http-request.helper'; - -class KubernetesResourcePoolsController { - /* @ngInject */ - constructor($async, $state, Notifications, KubernetesResourcePoolService, KubernetesNamespaceService) { - this.$async = $async; - this.$state = $state; - this.Notifications = Notifications; - this.KubernetesResourcePoolService = KubernetesResourcePoolService; - this.KubernetesNamespaceService = KubernetesNamespaceService; - - this.onInit = this.onInit.bind(this); - this.getResourcePools = this.getResourcePools.bind(this); - this.getResourcePoolsAsync = this.getResourcePoolsAsync.bind(this); - this.removeAction = this.removeAction.bind(this); - this.removeActionAsync = this.removeActionAsync.bind(this); - this.onReload = this.onReload.bind(this); - } - - async onReload() { - this.$state.reload(this.$state.current); - } - - async removeActionAsync(selectedItems) { - let actionCount = selectedItems.length; - for (const pool of selectedItems) { - try { - const isTerminating = pool.Namespace.Status === 'Terminating'; - if (isTerminating) { - const ns = await this.KubernetesNamespaceService.getJSONAsync(pool.Namespace.Name); - ns.$promise.then(async (namespace) => { - const n = JSON.parse(namespace.data); - if (n.spec && n.spec.finalizers) { - delete n.spec.finalizers; - } - await this.KubernetesNamespaceService.updateFinalizeAsync(n); - }); - } else { - await this.KubernetesResourcePoolService.delete(pool); - } - this.Notifications.success('Namespace successfully removed', pool.Namespace.Name); - const index = this.resourcePools.indexOf(pool); - this.resourcePools.splice(index, 1); - } catch (err) { - this.Notifications.error('Failure', err, 'Unable to remove namespace'); - } finally { - --actionCount; - if (actionCount === 0) { - this.$state.reload(this.$state.current); - } - } - } - } - - removeAction(selectedItems) { - const isTerminatingNS = selectedItems.some((pool) => pool.Namespace.Status === 'Terminating'); - const message = isTerminatingNS - ? 'At least one namespace is in a terminating state. For terminating state namespaces, you may continue and force removal, but doing so without having properly cleaned up may lead to unstable and unpredictable behavior. Are you sure you wish to proceed?' - : 'Do you want to remove the selected namespace(s)? All the resources associated to the selected namespace(s) will be removed too. Are you sure you wish to proceed?'; - confirm({ - title: isTerminatingNS ? 'Force namespace removal' : 'Are you sure?', - message, - confirmButton: buildConfirmButton('Remove', 'danger'), - - modalType: ModalType.Destructive, - }).then((confirmed) => { - if (confirmed) { - return this.$async(this.removeActionAsync, selectedItems); - } - }); - } - - async getResourcePoolsAsync() { - try { - this.resourcePools = await this.KubernetesResourcePoolService.get('', { getQuota: true }); - // make sure table refreshes with fresh data when namespaces are in a terminating state - if (this.resourcePools.some((namespace) => namespace.Namespace.Status === 'Terminating')) { - dispatchCacheRefreshEvent(); - } - } catch (err) { - this.Notifications.error('Failure', err, 'Unable to retreive namespaces'); - } - } - - getResourcePools() { - return this.$async(this.getResourcePoolsAsync); - } - - async onInit() { - this.state = { - viewReady: false, - }; - - await this.getResourcePools(); - - this.state.viewReady = true; - } - - $onInit() { - return this.$async(this.onInit); - } -} - -export default KubernetesResourcePoolsController; -angular.module('portainer.kubernetes').controller('KubernetesResourcePoolsController', KubernetesResourcePoolsController); diff --git a/app/react-tools/test-mocks.ts b/app/react-tools/test-mocks.ts index 829b397f8..556d7e4c2 100644 --- a/app/react-tools/test-mocks.ts +++ b/app/react-tools/test-mocks.ts @@ -78,6 +78,11 @@ export function createMockEnvironment(): Environment { URL: 'url', Snapshots: [], Kubernetes: { + Flags: { + IsServerMetricsDetected: true, + IsServerIngressClassDetected: true, + IsServerStorageDetected: true, + }, Snapshots: [], Configuration: { IngressClasses: [], @@ -85,6 +90,9 @@ export function createMockEnvironment(): Environment { AllowNoneIngressClass: false, }, }, + UserAccessPolicies: {}, + TeamAccessPolicies: {}, + ComposeSyntaxMaxVersion: '0', EdgeKey: '', EnableGPUManagement: false, Id: 3, diff --git a/app/react/components/ProgressBar/ProgressBar.tsx b/app/react/components/ProgressBar/ProgressBar.tsx new file mode 100644 index 000000000..899e03368 --- /dev/null +++ b/app/react/components/ProgressBar/ProgressBar.tsx @@ -0,0 +1,66 @@ +import clsx from 'clsx'; + +type Step = { value: number; color?: string; className?: string }; +type StepWithPercent = Step & { percent: number }; +interface Props { + steps: Array; + total: number; + className?: string; +} + +export function ProgressBar({ steps, total, className }: Props) { + const { steps: reducedSteps } = steps.reduce<{ + steps: Array; + total: number; + totalPercent: number; + }>( + (acc, cur) => { + const value = + acc.total + cur.value > total ? total - acc.total : cur.value; + // If the remaining acc.total + the current value adds up to the total, then make sure the percentage will fill the remaining bar space + const percent = + acc.total + value === total + ? 100 - acc.totalPercent + : Math.floor((value / total) * 100); + return { + steps: [ + ...acc.steps, + { + ...cur, + value, + percent, + }, + ], + total: acc.total + value, + totalPercent: acc.totalPercent + percent, + }; + }, + { steps: [], total: 0, totalPercent: 0 } + ); + + const sum = steps.reduce((sum, s) => sum + s.value, 0); + + return ( +
100 ? 'text-blue-8' : 'text-error-7', + className + )} + aria-valuemin={0} + aria-valuemax={100} + role="progressbar" + > + {reducedSteps.map((step, index) => ( +
+ ))} +
+ ); +} diff --git a/app/react/components/ProgressBar/index.ts b/app/react/components/ProgressBar/index.ts new file mode 100644 index 000000000..d702dcfb8 --- /dev/null +++ b/app/react/components/ProgressBar/index.ts @@ -0,0 +1 @@ +export { ProgressBar } from './ProgressBar'; diff --git a/app/react/kubernetes/annotations/AnnotationsForm.tsx b/app/react/kubernetes/annotations/AnnotationsForm.tsx index 14a099e2a..3b6ed4c9f 100644 --- a/app/react/kubernetes/annotations/AnnotationsForm.tsx +++ b/app/react/kubernetes/annotations/AnnotationsForm.tsx @@ -11,7 +11,7 @@ interface Props { annotations: Annotation[]; handleAnnotationChange: ( index: number, - key: 'Key' | 'Value', + key: 'key' | 'value', val: string ) => void; removeAnnotation: (index: number) => void; @@ -33,7 +33,7 @@ export function AnnotationsForm({ return ( <> {annotations.map((annotation, i) => ( -
+
Key @@ -42,16 +42,16 @@ export function AnnotationsForm({ type="text" className="form-control form-control-sm" placeholder={placeholder[0]} - defaultValue={annotation.Key} + defaultValue={annotation.key} onChange={(e: ChangeEvent) => - handleAnnotationChange(i, 'Key', e.target.value) + handleAnnotationChange(i, 'key', e.target.value) } data-cy={`annotation-key-${i}`} />
- {annotationErrors?.[i]?.Key && ( + {annotationErrors?.[i]?.key && ( - {annotationErrors[i]?.Key} + {annotationErrors[i]?.key} )}
@@ -63,16 +63,16 @@ export function AnnotationsForm({ type="text" className="form-control form-control-sm" placeholder={placeholder[1]} - defaultValue={annotation.Value} + defaultValue={annotation.value} onChange={(e: ChangeEvent) => - handleAnnotationChange(i, 'Value', e.target.value) + handleAnnotationChange(i, 'value', e.target.value) } data-cy={`annotation-value-${i}`} />
- {annotationErrors?.[i]?.Value && ( + {annotationErrors?.[i]?.value && ( - {annotationErrors[i]?.Value} + {annotationErrors[i]?.value} )}
diff --git a/app/react/kubernetes/annotations/types.ts b/app/react/kubernetes/annotations/types.ts index d364c8aed..04ca9fc9d 100644 --- a/app/react/kubernetes/annotations/types.ts +++ b/app/react/kubernetes/annotations/types.ts @@ -1,9 +1,9 @@ import { FormikErrors } from 'formik'; export interface Annotation { - Key: string; - Value: string; - ID: string; + key: string; + value: string; + id: string; } export type AnnotationsPayload = Record; diff --git a/app/react/kubernetes/annotations/validation.ts b/app/react/kubernetes/annotations/validation.ts index 3f5ced0a0..1d660225f 100644 --- a/app/react/kubernetes/annotations/validation.ts +++ b/app/react/kubernetes/annotations/validation.ts @@ -11,12 +11,12 @@ export const annotationsSchema: SchemaOf = array( ).test( 'unique', 'Duplicate keys are not allowed.', - buildUniquenessTest(() => 'Duplicate keys are not allowed.', 'Key') + buildUniquenessTest(() => 'Duplicate keys are not allowed.', 'key') ); function getAnnotationValidation(): SchemaOf { return object({ - Key: string() + key: string() .required('Key is required.') .test('is-valid', (value, { createError }) => { if (!value) { @@ -62,7 +62,7 @@ function getAnnotationValidation(): SchemaOf { } return true; }), - Value: string().required('Value is required.'), - ID: string().required('ID is required.'), + value: string().required('Value is required.'), + id: string().required('ID is required.'), }); } diff --git a/app/react/kubernetes/cluster/ingressClass/useIngressControllerClassMap.ts b/app/react/kubernetes/cluster/ingressClass/useIngressControllerClassMap.ts index 4e2f93295..5049a368b 100644 --- a/app/react/kubernetes/cluster/ingressClass/useIngressControllerClassMap.ts +++ b/app/react/kubernetes/cluster/ingressClass/useIngressControllerClassMap.ts @@ -70,6 +70,9 @@ export async function updateIngressControllerClassMap( ingressControllerClassMap: IngressControllerClassMap[], namespace?: string ) { + if (ingressControllerClassMap.length === 0) { + return []; + } try { const { data: controllerMaps } = await axios.put< IngressControllerClassMap[] diff --git a/app/react/kubernetes/components/EventsDatatable/ResourceEventsDatatable.tsx b/app/react/kubernetes/components/EventsDatatable/ResourceEventsDatatable.tsx index d94d4a3b5..f763043c9 100644 --- a/app/react/kubernetes/components/EventsDatatable/ResourceEventsDatatable.tsx +++ b/app/react/kubernetes/components/EventsDatatable/ResourceEventsDatatable.tsx @@ -10,6 +10,7 @@ type Props = { resourceId?: string; /** if undefined, events are fetched for the cluster */ namespace?: string; + noWidget?: boolean; }; /** ResourceEventsDatatable returns the EventsDatatable for all events that relate to a specific resource id */ @@ -17,6 +18,7 @@ export function ResourceEventsDatatable({ storageKey, resourceId, namespace, + noWidget = true, }: Props) { const tableState = useKubeStore(storageKey, { id: 'Date', @@ -47,7 +49,7 @@ export function ResourceEventsDatatable({ tableState={tableState} isLoading={resourceEventsQuery.isLoading} data-cy="k8sNodeDetail-eventsTable" - noWidget + noWidget={noWidget} /> ); } diff --git a/app/react/kubernetes/ingresses/CreateIngressView/CreateIngressView.tsx b/app/react/kubernetes/ingresses/CreateIngressView/CreateIngressView.tsx index 04b544dbe..b5de9afe1 100644 --- a/app/react/kubernetes/ingresses/CreateIngressView/CreateIngressView.tsx +++ b/app/react/kubernetes/ingresses/CreateIngressView/CreateIngressView.tsx @@ -5,7 +5,6 @@ import { debounce } from 'lodash'; import { useEnvironmentId } from '@/react/hooks/useEnvironmentId'; import { useK8sSecrets } from '@/react/kubernetes/configs/queries/useK8sSecrets'; -import { useNamespaceServices } from '@/react/kubernetes/networks/services/queries'; import { notifyError, notifySuccess } from '@/portainer/services/notifications'; import { useAuthorizations } from '@/react/hooks/useUser'; import { Annotation } from '@/react/kubernetes/annotations/types'; @@ -24,6 +23,7 @@ import { useUpdateIngress, useIngressControllers, } from '../queries'; +import { useNamespaceServices } from '../../services/useNamespaceServices'; import { Rule, @@ -410,13 +410,13 @@ export function CreateIngressView() { const duplicatedAnnotations: string[] = []; const re = /^([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]$/; rule.Annotations?.forEach((a, i) => { - if (!a.Key) { + if (!a.key) { errors[`annotations.key[${i}]`] = 'Key is required.'; - } else if (duplicatedAnnotations.includes(a.Key)) { + } else if (duplicatedAnnotations.includes(a.key)) { errors[`annotations.key[${i}]`] = 'Key is a duplicate of an existing one.'; } else { - const key = a.Key.split('/'); + const key = a.key.split('/'); if (key.length > 2) { errors[`annotations.key[${i}]`] = 'Two segments are allowed, separated by a slash (/): a prefix (optional) and a name.'; @@ -441,10 +441,10 @@ export function CreateIngressView() { } } } - if (!a.Value) { + if (!a.value) { errors[`annotations.value[${i}]`] = 'Value is required.'; } - duplicatedAnnotations.push(a.Key); + duplicatedAnnotations.push(a.key); }); const duplicatedHosts: string[] = []; @@ -677,7 +677,7 @@ export function CreateIngressView() { function handleAnnotationChange( index: number, - key: 'Key' | 'Value', + key: 'key' | 'value', val: string ) { setIngressRule((prevRules) => { @@ -685,8 +685,8 @@ export function CreateIngressView() { rules.Annotations = rules.Annotations || []; rules.Annotations[index] = rules.Annotations[index] || { - Key: '', - Value: '', + key: '', + value: '', }; rules.Annotations[index][key] = val; @@ -760,22 +760,22 @@ export function CreateIngressView() { const rule = { ...ingressRule }; const annotation: Annotation = { - Key: '', - Value: '', - ID: uuidv4(), + key: '', + value: '', + id: uuidv4(), }; switch (type) { case 'rewrite': - annotation.Key = 'nginx.ingress.kubernetes.io/rewrite-target'; - annotation.Value = '/$1'; + annotation.key = 'nginx.ingress.kubernetes.io/rewrite-target'; + annotation.value = '/$1'; break; case 'regex': - annotation.Key = 'nginx.ingress.kubernetes.io/use-regex'; - annotation.Value = 'true'; + annotation.key = 'nginx.ingress.kubernetes.io/use-regex'; + annotation.value = 'true'; break; case 'ingressClass': - annotation.Key = 'kubernetes.io/ingress.class'; - annotation.Value = ''; + annotation.key = 'kubernetes.io/ingress.class'; + annotation.value = ''; break; default: break; diff --git a/app/react/kubernetes/ingresses/CreateIngressView/IngressForm.tsx b/app/react/kubernetes/ingresses/CreateIngressView/IngressForm.tsx index 6f5aa3da6..230d08a42 100644 --- a/app/react/kubernetes/ingresses/CreateIngressView/IngressForm.tsx +++ b/app/react/kubernetes/ingresses/CreateIngressView/IngressForm.tsx @@ -73,7 +73,7 @@ interface Props { ) => void; handleAnnotationChange: ( index: number, - key: 'Key' | 'Value', + key: 'key' | 'value', val: string ) => void; handlePathChange: ( diff --git a/app/react/kubernetes/ingresses/CreateIngressView/utils.ts b/app/react/kubernetes/ingresses/CreateIngressView/utils.ts index 29f99774f..120a1e7c4 100644 --- a/app/react/kubernetes/ingresses/CreateIngressView/utils.ts +++ b/app/react/kubernetes/ingresses/CreateIngressView/utils.ts @@ -83,9 +83,9 @@ export function getAnnotationsForEdit( Object.keys(annotations).forEach((k) => { if (ignoreAnnotationsForEdit.indexOf(k) === -1) { result.push({ - Key: k, - Value: annotations[k], - ID: uuidv4(), + key: k, + value: annotations[k], + id: uuidv4(), }); } }); diff --git a/app/react/kubernetes/metrics/metrics.ts b/app/react/kubernetes/metrics/metrics.ts index 2025dc21e..512bacd33 100644 --- a/app/react/kubernetes/metrics/metrics.ts +++ b/app/react/kubernetes/metrics/metrics.ts @@ -32,20 +32,6 @@ export async function getMetricsForNode( } } -export async function getMetricsForAllPods( - environmentId: EnvironmentId, - namespace: string -) { - try { - const { data: pods } = await axios.get( - `kubernetes/${environmentId}/metrics/pods/namespace/${namespace}` - ); - return pods; - } catch (e) { - throw parseAxiosError(e, 'Unable to retrieve metrics for all pods'); - } -} - export async function getMetricsForPod( environmentId: EnvironmentId, namespace: string, diff --git a/app/react/kubernetes/metrics/queries/query-keys.ts b/app/react/kubernetes/metrics/queries/query-keys.ts new file mode 100644 index 000000000..f4acc1c55 --- /dev/null +++ b/app/react/kubernetes/metrics/queries/query-keys.ts @@ -0,0 +1,9 @@ +import { EnvironmentId } from '@/react/portainer/environments/types'; +import { queryKeys as namespaceQueryKeys } from '@/react/kubernetes/namespaces/queries/queryKeys'; + +export const queryKeys = { + namespaceMetrics: (environmentId: EnvironmentId, namespaceName: string) => [ + ...namespaceQueryKeys.namespace(environmentId, namespaceName), + 'metrics', + ], +}; diff --git a/app/react/kubernetes/metrics/queries/useMetricsForNamespace.ts b/app/react/kubernetes/metrics/queries/useMetricsForNamespace.ts new file mode 100644 index 000000000..146b25f97 --- /dev/null +++ b/app/react/kubernetes/metrics/queries/useMetricsForNamespace.ts @@ -0,0 +1,34 @@ +import { useQuery, UseQueryOptions } from '@tanstack/react-query'; + +import axios, { parseAxiosError } from '@/portainer/services/axios'; +import { EnvironmentId } from '@/react/portainer/environments/types'; + +import { PodMetrics } from '../types'; + +import { queryKeys } from './query-keys'; + +export function useMetricsForNamespace( + environmentId: EnvironmentId, + namespaceName: string, + queryOptions?: UseQueryOptions +) { + return useQuery({ + queryKey: queryKeys.namespaceMetrics(environmentId, namespaceName), + queryFn: () => getMetricsForNamespace(environmentId, namespaceName), + ...queryOptions, + }); +} + +export async function getMetricsForNamespace( + environmentId: EnvironmentId, + namespaceName: string +) { + try { + const { data: pods } = await axios.get( + `kubernetes/${environmentId}/metrics/pods/namespace/${namespaceName}` + ); + return pods; + } catch (e) { + throw parseAxiosError(e, 'Unable to retrieve metrics for all pods'); + } +} diff --git a/app/react/kubernetes/metrics/types.ts b/app/react/kubernetes/metrics/types.ts index 78223dda0..fa7118b8c 100644 --- a/app/react/kubernetes/metrics/types.ts +++ b/app/react/kubernetes/metrics/types.ts @@ -1,3 +1,20 @@ +export type PodMetrics = { + items: PodMetric[]; +}; + +export type PodMetric = { + containers: ContainerMetric[]; +}; + +type ContainerMetric = { + usage: ResourceUsage; +}; + +type ResourceUsage = { + cpu: string; + memory: string; +}; + export type NodeMetrics = { items: NodeMetric[]; }; diff --git a/app/react/kubernetes/namespaces/CreateView/CreateNamespaceForm.tsx b/app/react/kubernetes/namespaces/CreateView/CreateNamespaceForm.tsx index 134e3b6be..d09f5a761 100644 --- a/app/react/kubernetes/namespaces/CreateView/CreateNamespaceForm.tsx +++ b/app/react/kubernetes/namespaces/CreateView/CreateNamespaceForm.tsx @@ -10,18 +10,17 @@ import { useCurrentUser } from '@/react/hooks/useUser'; import { Widget, WidgetBody } from '@@/Widget'; import { useIngressControllerClassMapQuery } from '../../cluster/ingressClass/useIngressControllerClassMap'; -import { NamespaceInnerForm } from '../components/NamespaceInnerForm'; +import { NamespaceInnerForm } from '../components/NamespaceForm/NamespaceInnerForm'; import { useNamespacesQuery } from '../queries/useNamespacesQuery'; - +import { useClusterResourceLimitsQuery } from '../queries/useResourceLimitsQuery'; +import { useCreateNamespaceMutation } from '../queries/useCreateNamespaceMutation'; +import { getNamespaceValidationSchema } from '../components/NamespaceForm/NamespaceForm.validation'; +import { transformFormValuesToNamespacePayload } from '../components/NamespaceForm/utils'; import { - CreateNamespaceFormValues, - CreateNamespacePayload, + NamespaceFormValues, + NamespacePayload, UpdateRegistryPayload, -} from './types'; -import { useClusterResourceLimitsQuery } from './queries/useResourceLimitsQuery'; -import { getNamespaceValidationSchema } from './CreateNamespaceForm.validation'; -import { transformFormValuesToNamespacePayload } from './utils'; -import { useCreateNamespaceMutation } from './queries/useCreateNamespaceMutation'; +} from '../types'; export function CreateNamespaceForm() { const router = useRouter(); @@ -49,8 +48,8 @@ export function CreateNamespaceForm() { } const memoryLimit = resourceLimitsQuery.data?.Memory ?? 0; - - const initialValues: CreateNamespaceFormValues = { + const cpuLimit = resourceLimitsQuery.data?.CPU ?? 0; + const initialValues: NamespaceFormValues = { name: '', ingressClasses: ingressClasses ?? [], resourceQuota: { @@ -71,6 +70,7 @@ export function CreateNamespaceForm() { validateOnMount validationSchema={getNamespaceValidationSchema( memoryLimit, + cpuLimit, namespaceNames )} > @@ -80,8 +80,8 @@ export function CreateNamespaceForm() { ); - function handleSubmit(values: CreateNamespaceFormValues, userName: string) { - const createNamespacePayload: CreateNamespacePayload = + function handleSubmit(values: NamespaceFormValues, userName: string) { + const createNamespacePayload: NamespacePayload = transformFormValuesToNamespacePayload(values, userName); const updateRegistriesPayload: UpdateRegistryPayload[] = values.registries.flatMap((registryFormValues) => { @@ -93,7 +93,7 @@ export function CreateNamespaceForm() { return []; } const envNamespacesWithAccess = - selectedRegistry.RegistryAccesses[`${environmentId}`]?.Namespaces || + selectedRegistry.RegistryAccesses?.[`${environmentId}`]?.Namespaces || []; return { Id: selectedRegistry.Id, diff --git a/app/react/kubernetes/namespaces/CreateView/types.ts b/app/react/kubernetes/namespaces/CreateView/types.ts index 9aa04b20c..7b4102833 100644 --- a/app/react/kubernetes/namespaces/CreateView/types.ts +++ b/app/react/kubernetes/namespaces/CreateView/types.ts @@ -4,7 +4,7 @@ import { IngressControllerClassMap } from '../../cluster/ingressClass/types'; import { ResourceQuotaFormValues, ResourceQuotaPayload, -} from '../components/ResourceQuotaFormSection/types'; +} from '../components/NamespaceForm/ResourceQuotaFormSection/types'; export type CreateNamespaceFormValues = { name: string; diff --git a/app/react/kubernetes/namespaces/ItemView/ConfirmUpdateNamespace.tsx b/app/react/kubernetes/namespaces/ItemView/ConfirmUpdateNamespace.tsx index b80fc2454..00fa8107e 100644 --- a/app/react/kubernetes/namespaces/ItemView/ConfirmUpdateNamespace.tsx +++ b/app/react/kubernetes/namespaces/ItemView/ConfirmUpdateNamespace.tsx @@ -2,14 +2,16 @@ import { ModalType } from '@@/modals'; import { confirm } from '@@/modals/confirm'; import { buildConfirmButton } from '@@/modals/utils'; -export function confirmUpdateNamespace( - quotaWarning: boolean, - ingressWarning: boolean, - registriesWarning: boolean -) { +type Warnings = { + quota: boolean; + ingress: boolean; + registries: boolean; +}; + +export function confirmUpdateNamespace(warnings: Warnings) { const message = ( <> - {quotaWarning && ( + {warnings.quota && (

Reducing the quota assigned to an "in-use" namespace may have unintended consequences, including preventing running @@ -17,13 +19,13 @@ export function confirmUpdateNamespace( them from running at all.

)} - {ingressWarning && ( + {warnings.ingress && (

Deactivating ingresses may cause applications to be unaccessible. All ingress configurations from affected applications will be removed.

)} - {registriesWarning && ( + {warnings.registries && (

Some registries you removed might be used by one or more applications inside this environment. Removing the registries access could lead to diff --git a/app/react/kubernetes/namespaces/ItemView/NamespaceAppsDatatable.tsx b/app/react/kubernetes/namespaces/ItemView/NamespaceAppsDatatable.tsx index e0805c1de..1ab17c5d7 100644 --- a/app/react/kubernetes/namespaces/ItemView/NamespaceAppsDatatable.tsx +++ b/app/react/kubernetes/namespaces/ItemView/NamespaceAppsDatatable.tsx @@ -1,7 +1,8 @@ import { Code } from 'lucide-react'; +import { useEnvironmentId } from '@/react/hooks/useEnvironmentId'; + import { Datatable, TableSettingsMenu } from '@@/datatables'; -import { useRepeater } from '@@/datatables/useRepeater'; import { TableSettingsMenuAutoRefresh } from '@@/datatables/TableSettingsMenuAutoRefresh'; import { useTableStateWithStorage } from '@@/datatables/useTableState'; import { @@ -10,20 +11,14 @@ import { RefreshableTableSettings, } from '@@/datatables/types'; -import { NamespaceApp } from './types'; +import { useApplications } from '../../applications/queries/useApplications'; + import { useColumns } from './columns'; interface TableSettings extends BasicTableSettings, RefreshableTableSettings {} -export function NamespaceAppsDatatable({ - dataset, - onRefresh, - isLoading, -}: { - dataset: Array; - onRefresh: () => void; - isLoading: boolean; -}) { +export function NamespaceAppsDatatable({ namespace }: { namespace: string }) { + const environmentId = useEnvironmentId(); const tableState = useTableStateWithStorage( 'kube-namespace-apps', 'Name', @@ -31,18 +26,25 @@ export function NamespaceAppsDatatable({ ...refreshableSettings(set), }) ); - useRepeater(tableState.autoRefreshRate, onRefresh); + + const applicationsQuery = useApplications(environmentId, { + refetchInterval: tableState.autoRefreshRate * 1000, + namespace, + withDependencies: true, + }); + const applications = applicationsQuery.data ?? []; + const columns = useColumns(); return ( ( , + selectedTabParam: 'namespace', + }, + { + name: ( +

+ Events + {eventWarningCount >= 1 && ( + + + {eventWarningCount} + + )} +
+ ), + icon: History, + widget: ( + + ), + selectedTabParam: 'events', + }, + { + name: 'YAML', + icon: Code, + widget: , + selectedTabParam: 'YAML', + }, + ]; + const currentTabIndex = findSelectedTabIndex(stateAndParams, tabs); + + return ( + <> + + <> + + {tabs[currentTabIndex].widget} + + + + ); +} diff --git a/app/react/kubernetes/namespaces/ItemView/UpdateNamespaceForm.tsx b/app/react/kubernetes/namespaces/ItemView/UpdateNamespaceForm.tsx new file mode 100644 index 000000000..632fba952 --- /dev/null +++ b/app/react/kubernetes/namespaces/ItemView/UpdateNamespaceForm.tsx @@ -0,0 +1,256 @@ +import { Formik } from 'formik'; +import { useCurrentStateAndParams, useRouter } from '@uirouter/react'; + +import { useEnvironmentId } from '@/react/hooks/useEnvironmentId'; +import { notifySuccess } from '@/portainer/services/notifications'; +import { useCurrentEnvironment } from '@/react/hooks/useCurrentEnvironment'; +import { useEnvironmentRegistries } from '@/react/portainer/environments/queries/useEnvironmentRegistries'; +import { useCurrentUser } from '@/react/hooks/useUser'; +import { Registry } from '@/react/portainer/registries/types/registry'; + +import { Loading, Widget, WidgetBody } from '@@/Widget'; +import { Alert } from '@@/Alert'; + +import { NamespaceInnerForm } from '../components/NamespaceForm/NamespaceInnerForm'; +import { useNamespacesQuery } from '../queries/useNamespacesQuery'; +import { useClusterResourceLimitsQuery } from '../queries/useResourceLimitsQuery'; +import { NamespaceFormValues, NamespacePayload } from '../types'; +import { getNamespaceValidationSchema } from '../components/NamespaceForm/NamespaceForm.validation'; +import { transformFormValuesToNamespacePayload } from '../components/NamespaceForm/utils'; +import { useNamespaceQuery } from '../queries/useNamespaceQuery'; +import { useIngressControllerClassMapQuery } from '../../cluster/ingressClass/useIngressControllerClassMap'; +import { ResourceQuotaFormValues } from '../components/NamespaceForm/ResourceQuotaFormSection/types'; +import { IngressControllerClassMap } from '../../cluster/ingressClass/types'; +import { useUpdateNamespaceMutation } from '../queries/useUpdateNamespaceMutation'; + +import { useNamespaceFormValues } from './useNamespaceFormValues'; +import { confirmUpdateNamespace } from './ConfirmUpdateNamespace'; +import { createUpdateRegistriesPayload } from './createUpdateRegistriesPayload'; + +export function UpdateNamespaceForm() { + const { + params: { id: namespaceName }, + } = useCurrentStateAndParams(); + const router = useRouter(); + + // for initial values + const { user } = useCurrentUser(); + const environmentId = useEnvironmentId(); + const environmentQuery = useCurrentEnvironment(); + const namespacesQuery = useNamespacesQuery(environmentId); + const resourceLimitsQuery = useClusterResourceLimitsQuery(environmentId); + const namespaceQuery = useNamespaceQuery(environmentId, namespaceName, { + params: { withResourceQuota: 'true' }, + }); + const registriesQuery = useEnvironmentRegistries(environmentId, { + hideDefault: true, + }); + const ingressClassesQuery = useIngressControllerClassMapQuery({ + environmentId, + namespace: namespaceName, + allowedOnly: true, + }); + const storageClasses = + environmentQuery.data?.Kubernetes.Configuration.StorageClasses; + const { data: namespaces } = namespacesQuery; + const { data: resourceLimits } = resourceLimitsQuery; + const { data: namespace } = namespaceQuery; + const { data: registries } = registriesQuery; + const { data: ingressClasses } = ingressClassesQuery; + + const updateNamespaceMutation = useUpdateNamespaceMutation(environmentId); + + const namespaceNames = Object.keys(namespaces || {}); + const memoryLimit = resourceLimits?.Memory ?? 0; + const cpuLimit = resourceLimits?.CPU ?? 0; + const initialValues = useNamespaceFormValues({ + namespaceName, + environmentId, + storageClasses, + namespace, + registries, + ingressClasses, + }); + const isQueryLoading = + environmentQuery.isLoading || + resourceLimitsQuery.isLoading || + namespacesQuery.isLoading || + namespaceQuery.isLoading || + registriesQuery.isLoading || + ingressClassesQuery.isLoading; + + const isQueryError = + environmentQuery.isError || + resourceLimitsQuery.isError || + namespacesQuery.isError || + namespaceQuery.isError || + registriesQuery.isError || + ingressClassesQuery.isError; + + if (isQueryLoading) { + return ; + } + + if (isQueryError) { + return ( + + Error loading namespace + + ); + } + + if (!initialValues) { + return ( + + No data found for namespace + + ); + } + + return ( +
+
+ + + handleSubmit(values, user.Username)} + validateOnMount + validationSchema={getNamespaceValidationSchema( + memoryLimit, + cpuLimit, + namespaceNames + )} + > + {(formikProps) => ( + + )} + + + +
+
+ ); + + async function handleSubmit(values: NamespaceFormValues, userName: string) { + const createNamespacePayload: NamespacePayload = + transformFormValuesToNamespacePayload(values, userName); + const updateRegistriesPayload = createUpdateRegistriesPayload({ + registries, + namespaceName, + newRegistriesValues: values.registries, + initialRegistriesValues: initialValues?.registries || [], + environmentId, + }); + + // give update warnings if needed + const isNamespaceAccessRemoved = hasNamespaceAccessBeenRemoved( + values.registries, + initialValues?.registries || [], + environmentId, + values.name + ); + const isIngressClassesRemoved = hasIngressClassesBeenRemoved( + values.ingressClasses, + initialValues?.ingressClasses || [] + ); + const warnings = { + quota: hasResourceQuotaBeenReduced( + values.resourceQuota, + initialValues?.resourceQuota + ), + ingress: isIngressClassesRemoved, + registries: isNamespaceAccessRemoved, + }; + if (Object.values(warnings).some(Boolean)) { + const confirmed = await confirmUpdateNamespace(warnings); + if (!confirmed) { + return; + } + } + + // update the namespace + updateNamespaceMutation.mutate( + { + createNamespacePayload, + updateRegistriesPayload, + namespaceIngressControllerPayload: values.ingressClasses, + }, + { + onSuccess: () => { + notifySuccess( + 'Success', + `Namespace '${values.name}' updated successfully` + ); + router.stateService.reload(); + }, + } + ); + } +} + +function hasResourceQuotaBeenReduced( + newResourceQuota: ResourceQuotaFormValues, + initialResourceQuota?: ResourceQuotaFormValues +) { + if (!initialResourceQuota) { + return false; + } + // if the new value is an empty string or '0', it's counted as 'unlimited' + const unlimitedValue = String(Number.MAX_SAFE_INTEGER); + return ( + (Number(initialResourceQuota.cpu) || unlimitedValue) > + (Number(newResourceQuota.cpu) || unlimitedValue) || + (Number(initialResourceQuota.memory) || unlimitedValue) > + (Number(newResourceQuota.memory) || unlimitedValue) + ); +} + +function hasNamespaceAccessBeenRemoved( + newRegistries: Registry[], + initialRegistries: Registry[], + environmentId: number, + namespaceName: string +) { + return initialRegistries.some((oldRegistry) => { + // Check if the namespace was in the old registry's accesses + const isNamespaceInOldAccesses = + oldRegistry.RegistryAccesses?.[`${environmentId}`]?.Namespaces.includes( + namespaceName + ); + + if (!isNamespaceInOldAccesses) { + return false; + } + + // Find the corresponding new registry + const newRegistry = newRegistries.find((r) => r.Id === oldRegistry.Id); + if (!newRegistry) { + return true; + } + + // If the registry no longer exists or the namespace is not in its accesses, access has been removed + const isNamespaceInNewAccesses = + newRegistry.RegistryAccesses?.[`${environmentId}`]?.Namespaces.includes( + namespaceName + ); + + return !isNamespaceInNewAccesses; + }); +} + +function hasIngressClassesBeenRemoved( + newIngressClasses: IngressControllerClassMap[], + initialIngressClasses: IngressControllerClassMap[] +) { + // go through all old classes and check if their availability has changed + return initialIngressClasses.some((oldClass) => { + const newClass = newIngressClasses.find((c) => c.Name === oldClass.Name); + return newClass?.Availability !== oldClass.Availability; + }); +} diff --git a/app/react/kubernetes/namespaces/ItemView/columns.tsx b/app/react/kubernetes/namespaces/ItemView/columns.tsx index f29c084bf..18a7e30f1 100644 --- a/app/react/kubernetes/namespaces/ItemView/columns.tsx +++ b/app/react/kubernetes/namespaces/ItemView/columns.tsx @@ -2,18 +2,17 @@ import { createColumnHelper } from '@tanstack/react-table'; import _ from 'lodash'; import { useMemo } from 'react'; -import { humanize, truncate } from '@/portainer/filters/filters'; import { usePublicSettings } from '@/react/portainer/settings/queries'; +import { humanize } from '@/portainer/filters/filters'; import { Link } from '@@/Link'; import { ExternalBadge } from '@@/Badge/ExternalBadge'; import { isExternalApplication } from '../../applications/utils'; import { cpuHumanValue } from '../../applications/utils/cpuHumanValue'; +import { Application } from '../../applications/ListView/ApplicationsDatatable/types'; -import { NamespaceApp } from './types'; - -const columnHelper = createColumnHelper(); +const columnHelper = createColumnHelper(); export function useColumns() { const hideStacksQuery = usePublicSettings({ @@ -27,7 +26,7 @@ export function useColumns() { columnHelper.accessor('Name', { header: 'Name', cell: ({ row: { original: item } }) => ( - <> +
)} - +
), }), !hideStacksQuery.data && @@ -50,23 +49,34 @@ export function useColumns() { }), columnHelper.accessor('Image', { header: 'Image', - cell: ({ row: { original: item } }) => ( - <> - {truncate(item.Image, 64)} - {item.Containers?.length > 1 && ( - <>+ {item.Containers.length - 1} - )} - + cell: ({ getValue }) => ( +
{getValue()}
), }), - columnHelper.accessor('CPU', { - header: 'CPU', - cell: ({ getValue }) => cpuHumanValue(getValue()), - }), - columnHelper.accessor('Memory', { - header: 'Memory', - cell: ({ getValue }) => humanize(getValue()), - }), + columnHelper.accessor( + (row) => + row.Resource?.CpuRequest + ? cpuHumanValue(row.Resource?.CpuRequest) + : '-', + { + header: 'CPU', + cell: ({ getValue }) => getValue(), + } + ), + columnHelper.accessor( + (row) => + row.Resource?.MemoryRequest ? row.Resource?.MemoryRequest : '-', + { + header: 'Memory', + cell: ({ getValue }) => { + const value = getValue(); + if (value === '-') { + return value; + } + return humanize(value); + }, + } + ), ]), [hideStacksQuery.data] ); diff --git a/app/react/kubernetes/namespaces/ItemView/createUpdateRegistriesPayload.test.ts b/app/react/kubernetes/namespaces/ItemView/createUpdateRegistriesPayload.test.ts new file mode 100644 index 000000000..f4c574840 --- /dev/null +++ b/app/react/kubernetes/namespaces/ItemView/createUpdateRegistriesPayload.test.ts @@ -0,0 +1,518 @@ +import { createUpdateRegistriesPayload } from './createUpdateRegistriesPayload'; + +const tests: { + testName: string; + params: Parameters[0]; + expected: ReturnType; +}[] = [ + { + testName: 'Add new registry', + params: { + registries: [ + { + Id: 1, + Type: 6, + Name: 'dockerhub', + URL: 'docker.io', + BaseURL: '', + Authentication: true, + Username: 'portainer', + Gitlab: { + ProjectId: 0, + InstanceURL: '', + ProjectPath: '', + }, + Quay: { + OrganisationName: '', + }, + Ecr: { + Region: '', + }, + RegistryAccesses: { + '7': { + UserAccessPolicies: null, + TeamAccessPolicies: null, + Namespaces: [], + }, + }, + Github: { + UseOrganisation: false, + OrganisationName: '', + }, + }, + { + Id: 2, + Type: 3, + Name: 'portainertest', + URL: 'test123.com', + BaseURL: '', + Authentication: false, + Username: '', + Gitlab: { + ProjectId: 0, + InstanceURL: '', + ProjectPath: '', + }, + Quay: { + OrganisationName: '', + }, + Ecr: { + Region: '', + }, + RegistryAccesses: { + '7': { + UserAccessPolicies: null, + TeamAccessPolicies: null, + Namespaces: ['newns'], + }, + }, + Github: { + UseOrganisation: false, + OrganisationName: '', + }, + }, + ], + namespaceName: 'newns', + newRegistriesValues: [ + { + Id: 2, + Type: 3, + Name: 'portainertest', + URL: 'test123.com', + BaseURL: '', + Authentication: false, + Username: '', + Gitlab: { + ProjectId: 0, + InstanceURL: '', + ProjectPath: '', + }, + Quay: { + OrganisationName: '', + }, + Ecr: { + Region: '', + }, + RegistryAccesses: { + '7': { + UserAccessPolicies: null, + TeamAccessPolicies: null, + Namespaces: ['newns'], + }, + }, + Github: { + UseOrganisation: false, + OrganisationName: '', + }, + }, + { + Id: 1, + Type: 6, + Name: 'dockerhub', + URL: 'docker.io', + BaseURL: '', + Authentication: true, + Username: 'portainer', + Gitlab: { + ProjectId: 0, + InstanceURL: '', + ProjectPath: '', + }, + Quay: { + OrganisationName: '', + }, + Ecr: { + Region: '', + }, + RegistryAccesses: { + '7': { + UserAccessPolicies: null, + TeamAccessPolicies: null, + Namespaces: [], + }, + }, + Github: { + UseOrganisation: false, + OrganisationName: '', + }, + }, + ], + initialRegistriesValues: [ + { + Id: 2, + Type: 3, + Name: 'portainertest', + URL: 'test123.com', + BaseURL: '', + Authentication: false, + Username: '', + Gitlab: { + ProjectId: 0, + InstanceURL: '', + ProjectPath: '', + }, + Quay: { + OrganisationName: '', + }, + Ecr: { + Region: '', + }, + RegistryAccesses: { + '7': { + UserAccessPolicies: null, + TeamAccessPolicies: null, + Namespaces: ['newns'], + }, + }, + Github: { + UseOrganisation: false, + OrganisationName: '', + }, + }, + ], + environmentId: 7, + }, + expected: [ + { + Id: 2, + Namespaces: ['newns'], + }, + { + Id: 1, + Namespaces: ['newns'], + }, + ], + }, + { + testName: 'Remove a registry', + params: { + registries: [ + { + Id: 1, + Type: 6, + Name: 'dockerhub', + URL: 'docker.io', + BaseURL: '', + Authentication: true, + Username: 'portainer', + Gitlab: { + ProjectId: 0, + InstanceURL: '', + ProjectPath: '', + }, + Quay: { + OrganisationName: '', + }, + Ecr: { + Region: '', + }, + RegistryAccesses: { + '7': { + UserAccessPolicies: null, + TeamAccessPolicies: null, + Namespaces: ['newns'], + }, + }, + Github: { + UseOrganisation: false, + OrganisationName: '', + }, + }, + { + Id: 2, + Type: 3, + Name: 'portainertest', + URL: 'test123.com', + BaseURL: '', + Authentication: false, + Username: '', + Gitlab: { + ProjectId: 0, + InstanceURL: '', + ProjectPath: '', + }, + Quay: { + OrganisationName: '', + }, + Ecr: { + Region: '', + }, + RegistryAccesses: { + '7': { + UserAccessPolicies: null, + TeamAccessPolicies: null, + Namespaces: ['newns'], + }, + }, + Github: { + UseOrganisation: false, + OrganisationName: '', + }, + }, + ], + namespaceName: 'newns', + newRegistriesValues: [ + { + Id: 2, + Type: 3, + Name: 'portainertest', + URL: 'test123.com', + BaseURL: '', + Authentication: false, + Username: '', + Gitlab: { + ProjectId: 0, + InstanceURL: '', + ProjectPath: '', + }, + Quay: { + OrganisationName: '', + }, + Ecr: { + Region: '', + }, + RegistryAccesses: { + '7': { + UserAccessPolicies: null, + TeamAccessPolicies: null, + Namespaces: ['newns'], + }, + }, + Github: { + UseOrganisation: false, + OrganisationName: '', + }, + }, + ], + initialRegistriesValues: [ + { + Id: 1, + Type: 6, + Name: 'dockerhub', + URL: 'docker.io', + BaseURL: '', + Authentication: true, + Username: 'portainer', + Gitlab: { + ProjectId: 0, + InstanceURL: '', + ProjectPath: '', + }, + Quay: { + OrganisationName: '', + }, + Ecr: { + Region: '', + }, + RegistryAccesses: { + '7': { + UserAccessPolicies: null, + TeamAccessPolicies: null, + Namespaces: ['newns'], + }, + }, + Github: { + UseOrganisation: false, + OrganisationName: '', + }, + }, + { + Id: 2, + Type: 3, + Name: 'portainertest', + URL: 'test123.com', + BaseURL: '', + Authentication: false, + Username: '', + Gitlab: { + ProjectId: 0, + InstanceURL: '', + ProjectPath: '', + }, + Quay: { + OrganisationName: '', + }, + Ecr: { + Region: '', + }, + RegistryAccesses: { + '7': { + UserAccessPolicies: null, + TeamAccessPolicies: null, + Namespaces: ['newns'], + }, + }, + Github: { + UseOrganisation: false, + OrganisationName: '', + }, + }, + ], + environmentId: 7, + }, + expected: [ + { + Id: 1, + Namespaces: [], + }, + { + Id: 2, + Namespaces: ['newns'], + }, + ], + }, + { + testName: 'Remove all registries', + params: { + registries: [ + { + Id: 1, + Type: 6, + Name: 'dockerhub', + URL: 'docker.io', + BaseURL: '', + Authentication: true, + Username: 'portainer', + Gitlab: { + ProjectId: 0, + InstanceURL: '', + ProjectPath: '', + }, + Quay: { + OrganisationName: '', + }, + Ecr: { + Region: '', + }, + RegistryAccesses: { + '7': { + UserAccessPolicies: null, + TeamAccessPolicies: null, + Namespaces: ['newns'], + }, + }, + Github: { + UseOrganisation: false, + OrganisationName: '', + }, + }, + { + Id: 2, + Type: 3, + Name: 'portainertest', + URL: 'test123.com', + BaseURL: '', + Authentication: false, + Username: '', + Gitlab: { + ProjectId: 0, + InstanceURL: '', + ProjectPath: '', + }, + Quay: { + OrganisationName: '', + }, + Ecr: { + Region: '', + }, + RegistryAccesses: { + '7': { + UserAccessPolicies: null, + TeamAccessPolicies: null, + Namespaces: ['newns'], + }, + }, + Github: { + UseOrganisation: false, + OrganisationName: '', + }, + }, + ], + namespaceName: 'newns', + newRegistriesValues: [], + initialRegistriesValues: [ + { + Id: 1, + Type: 6, + Name: 'dockerhub', + URL: 'docker.io', + BaseURL: '', + Authentication: true, + Username: 'portainer', + Gitlab: { + ProjectId: 0, + InstanceURL: '', + ProjectPath: '', + }, + Quay: { + OrganisationName: '', + }, + Ecr: { + Region: '', + }, + RegistryAccesses: { + '7': { + UserAccessPolicies: null, + TeamAccessPolicies: null, + Namespaces: ['newns'], + }, + }, + Github: { + UseOrganisation: false, + OrganisationName: '', + }, + }, + { + Id: 2, + Type: 3, + Name: 'portainertest', + URL: 'test123.com', + BaseURL: '', + Authentication: false, + Username: '', + Gitlab: { + ProjectId: 0, + InstanceURL: '', + ProjectPath: '', + }, + Quay: { + OrganisationName: '', + }, + Ecr: { + Region: '', + }, + RegistryAccesses: { + '7': { + UserAccessPolicies: null, + TeamAccessPolicies: null, + Namespaces: ['newns'], + }, + }, + Github: { + UseOrganisation: false, + OrganisationName: '', + }, + }, + ], + environmentId: 7, + }, + expected: [ + { + Id: 1, + Namespaces: [], + }, + { + Id: 2, + Namespaces: [], + }, + ], + }, +]; + +describe('createUpdateRegistriesPayload', () => { + tests.forEach(({ testName, params, expected }) => { + it(`Should return the correct payload: ${testName}`, () => { + expect(createUpdateRegistriesPayload(params)).toEqual(expected); + }); + }); +}); diff --git a/app/react/kubernetes/namespaces/ItemView/createUpdateRegistriesPayload.ts b/app/react/kubernetes/namespaces/ItemView/createUpdateRegistriesPayload.ts new file mode 100644 index 000000000..523af1ba8 --- /dev/null +++ b/app/react/kubernetes/namespaces/ItemView/createUpdateRegistriesPayload.ts @@ -0,0 +1,50 @@ +import { uniqBy } from 'lodash'; + +import { Registry } from '@/react/portainer/registries/types/registry'; + +import { UpdateRegistryPayload } from '../types'; + +export function createUpdateRegistriesPayload({ + registries, + namespaceName, + newRegistriesValues, + initialRegistriesValues, + environmentId, +}: { + registries: Registry[] | undefined; + namespaceName: string; + newRegistriesValues: Registry[]; + initialRegistriesValues: Registry[]; + environmentId: number; +}): UpdateRegistryPayload[] { + if (!registries) { + return []; + } + + // Get all unique registries from both initial and new values + const uniqueRegistries = uniqBy( + [...initialRegistriesValues, ...newRegistriesValues], + 'Id' + ); + + const payload = uniqueRegistries.map((registry) => { + const currentNamespaces = + registry.RegistryAccesses?.[`${environmentId}`]?.Namespaces || []; + + const existsInNewValues = newRegistriesValues.some( + (r) => r.Id === registry.Id + ); + + // If registry is in new values, add namespace; if not, remove it + const updatedNamespaces = existsInNewValues + ? [...new Set([...currentNamespaces, namespaceName])] + : currentNamespaces.filter((ns) => ns !== namespaceName); + + return { + Id: registry.Id, + Namespaces: updatedNamespaces, + }; + }); + + return payload; +} diff --git a/app/react/kubernetes/namespaces/ItemView/useNamespaceFormValues.test.ts b/app/react/kubernetes/namespaces/ItemView/useNamespaceFormValues.test.ts new file mode 100644 index 000000000..623a4993c --- /dev/null +++ b/app/react/kubernetes/namespaces/ItemView/useNamespaceFormValues.test.ts @@ -0,0 +1,247 @@ +import { computeInitialValues } from './useNamespaceFormValues'; + +type NamespaceTestData = { + testName: string; + namespaceData: Parameters[0]; + expectedFormValues: ReturnType; +}; + +// various namespace data from simple to complex +const tests: NamespaceTestData[] = [ + { + testName: + 'No resource quotas, registries, storage requests or ingress controllers', + namespaceData: { + namespaceName: 'test', + environmentId: 4, + storageClasses: [ + { + Name: 'local-path', + AccessModes: ['RWO'], + Provisioner: 'rancher.io/local-path', + AllowVolumeExpansion: false, + }, + ], + namespace: { + Id: '6110390e-f7cb-4f23-b219-197e4a1d0291', + Name: 'test', + Status: { + phase: 'Active', + }, + Annotations: null, + CreationDate: '2024-10-17T17:50:08+13:00', + NamespaceOwner: 'admin', + IsSystem: false, + IsDefault: false, + }, + registries: [ + { + Id: 1, + Type: 6, + Name: 'dockerhub', + URL: 'docker.io', + BaseURL: '', + Authentication: true, + Username: 'aliharriss', + Gitlab: { + ProjectId: 0, + InstanceURL: '', + ProjectPath: '', + }, + Ecr: { + Region: '', + }, + Quay: { + OrganisationName: '', + }, + RegistryAccesses: { + '4': { + UserAccessPolicies: null, + TeamAccessPolicies: null, + Namespaces: ['newns'], + }, + }, + Github: { + UseOrganisation: false, + OrganisationName: '', + }, + }, + ], + ingressClasses: [ + { + Name: 'none', + ClassName: 'none', + Type: 'custom', + Availability: true, + New: false, + Used: false, + }, + ], + }, + expectedFormValues: { + name: 'test', + ingressClasses: [ + { + Name: 'none', + ClassName: 'none', + Type: 'custom', + Availability: true, + New: false, + Used: false, + }, + ], + resourceQuota: { + enabled: false, + memory: '0', + cpu: '0', + }, + registries: [], + }, + }, + { + testName: + 'With annotations, registry, storage request, resource quota and disabled ingress controller', + namespaceData: { + namespaceName: 'newns', + environmentId: 4, + storageClasses: [ + { + Name: 'local-path', + AccessModes: ['RWO'], + Provisioner: 'rancher.io/local-path', + AllowVolumeExpansion: false, + }, + ], + namespace: { + Id: 'd5c3cb69-bf9b-4625-b754-d7ba6ce2c688', + Name: 'newns', + Status: { + phase: 'Active', + }, + Annotations: { + asdf: 'asdf', + }, + CreationDate: '2024-10-01T10:20:46+13:00', + NamespaceOwner: 'admin', + IsSystem: false, + IsDefault: false, + ResourceQuota: { + metadata: {}, + spec: { + hard: { + 'limits.cpu': '800m', + 'limits.memory': '768M', + 'local-path.storageclass.storage.k8s.io/requests.storage': '1G', + 'requests.cpu': '800m', + 'requests.memory': '768M', + 'services.loadbalancers': '1', + }, + }, + }, + }, + registries: [ + { + Id: 1, + Type: 6, + Name: 'dockerhub', + URL: 'docker.io', + BaseURL: '', + Authentication: true, + Username: 'aliharriss', + Gitlab: { + ProjectId: 0, + InstanceURL: '', + ProjectPath: '', + }, + Quay: { + OrganisationName: '', + }, + Ecr: { + Region: '', + }, + RegistryAccesses: { + '4': { + UserAccessPolicies: null, + TeamAccessPolicies: null, + Namespaces: ['newns'], + }, + }, + Github: { + UseOrganisation: false, + OrganisationName: '', + }, + }, + ], + ingressClasses: [ + { + Name: 'none', + ClassName: 'none', + Type: 'custom', + Availability: true, + New: false, + Used: false, + }, + ], + }, + expectedFormValues: { + name: 'newns', + ingressClasses: [ + { + Name: 'none', + ClassName: 'none', + Type: 'custom', + Availability: true, + New: false, + Used: false, + }, + ], + resourceQuota: { + enabled: true, + memory: '768', + cpu: '0.8', + }, + registries: [ + { + Id: 1, + Type: 6, + Name: 'dockerhub', + URL: 'docker.io', + BaseURL: '', + Authentication: true, + Username: 'aliharriss', + Gitlab: { + ProjectId: 0, + InstanceURL: '', + ProjectPath: '', + }, + Quay: { + OrganisationName: '', + }, + Ecr: { + Region: '', + }, + RegistryAccesses: { + '4': { + UserAccessPolicies: null, + TeamAccessPolicies: null, + Namespaces: ['newns'], + }, + }, + Github: { + UseOrganisation: false, + OrganisationName: '', + }, + }, + ], + }, + }, +]; + +describe('useNamespaceFormValues', () => { + tests.forEach((test) => { + it(`should return the correct form values: ${test.testName}`, () => { + const formValues = computeInitialValues(test.namespaceData); + expect(formValues).toEqual(test.expectedFormValues); + }); + }); +}); diff --git a/app/react/kubernetes/namespaces/ItemView/useNamespaceFormValues.ts b/app/react/kubernetes/namespaces/ItemView/useNamespaceFormValues.ts new file mode 100644 index 000000000..b3f0202d7 --- /dev/null +++ b/app/react/kubernetes/namespaces/ItemView/useNamespaceFormValues.ts @@ -0,0 +1,78 @@ +import { useMemo } from 'react'; + +import { StorageClass } from '@/react/portainer/environments/types'; +import { Registry } from '@/react/portainer/registries/types/registry'; + +import { NamespaceFormValues, PortainerNamespace } from '../types'; +import { megaBytesValue, parseCPU } from '../resourceQuotaUtils'; +import { IngressControllerClassMap } from '../../cluster/ingressClass/types'; + +interface ComputeInitialValuesParams { + namespaceName: string; + environmentId: number; + storageClasses?: StorageClass[]; + namespace?: PortainerNamespace; + registries?: Registry[]; + ingressClasses?: IngressControllerClassMap[]; +} + +export function computeInitialValues({ + namespaceName, + environmentId, + namespace, + registries, + ingressClasses, +}: ComputeInitialValuesParams): NamespaceFormValues | null { + if (!namespace) { + return null; + } + const memory = namespace.ResourceQuota?.spec?.hard?.['requests.memory'] ?? ''; + const cpu = namespace.ResourceQuota?.spec?.hard?.['requests.cpu'] ?? ''; + + const registriesUsed = registries?.filter( + (registry) => + registry.RegistryAccesses?.[`${environmentId}`]?.Namespaces.includes( + namespaceName + ) + ); + + return { + name: namespaceName, + ingressClasses: ingressClasses ?? [], + resourceQuota: { + enabled: !!memory || !!cpu, + memory: `${megaBytesValue(memory)}`, + cpu: `${parseCPU(cpu)}`, + }, + registries: registriesUsed ?? [], + }; +} + +export function useNamespaceFormValues({ + namespaceName, + environmentId, + storageClasses, + namespace, + registries, + ingressClasses, +}: ComputeInitialValuesParams): NamespaceFormValues | null { + return useMemo( + () => + computeInitialValues({ + namespaceName, + environmentId, + storageClasses, + namespace, + registries, + ingressClasses, + }), + [ + storageClasses, + namespace, + registries, + namespaceName, + ingressClasses, + environmentId, + ] + ); +} diff --git a/app/react/kubernetes/namespaces/ListView/NamespacesDatatable.tsx b/app/react/kubernetes/namespaces/ListView/NamespacesDatatable.tsx index 17092a653..7307f830e 100644 --- a/app/react/kubernetes/namespaces/ListView/NamespacesDatatable.tsx +++ b/app/react/kubernetes/namespaces/ListView/NamespacesDatatable.tsx @@ -91,7 +91,7 @@ export function NamespacesDatatable() { function TableActions({ selectedItems, - namespaces: namespacesQueryData, + namespaces, }: { selectedItems: PortainerNamespace[]; namespaces?: PortainerNamespace[]; @@ -168,18 +168,21 @@ function TableActions({ // Plain invalidation / refetching is confusing because namespaces hang in a terminating state // instead, optimistically update the cache manually to hide the deleting (terminating) namespaces + const remainingNamespaces = deletedNamespaces.reduce( + (acc, ns) => { + const index = acc.findIndex((n) => n.Name === ns); + if (index !== -1) { + acc.splice(index, 1); + } + return acc; + }, + [...(namespaces ?? [])] + ); queryClient.setQueryData( queryKeys.list(environmentId, { withResourceQuota: true, }), - () => - deletedNamespaces.reduce( - (acc, ns) => { - delete acc[ns as keyof typeof acc]; - return acc; - }, - { ...namespacesQueryData } - ) + () => remainingNamespaces ); }, } diff --git a/app/react/kubernetes/namespaces/components/LoadBalancerFormSection/LoadBalancerFormSection.tsx b/app/react/kubernetes/namespaces/components/NamespaceForm/LoadBalancerFormSection/LoadBalancerFormSection.tsx similarity index 100% rename from app/react/kubernetes/namespaces/components/LoadBalancerFormSection/LoadBalancerFormSection.tsx rename to app/react/kubernetes/namespaces/components/NamespaceForm/LoadBalancerFormSection/LoadBalancerFormSection.tsx diff --git a/app/react/kubernetes/namespaces/components/LoadBalancerFormSection/index.ts b/app/react/kubernetes/namespaces/components/NamespaceForm/LoadBalancerFormSection/index.ts similarity index 100% rename from app/react/kubernetes/namespaces/components/LoadBalancerFormSection/index.ts rename to app/react/kubernetes/namespaces/components/NamespaceForm/LoadBalancerFormSection/index.ts diff --git a/app/react/kubernetes/namespaces/CreateView/CreateNamespaceForm.validation.tsx b/app/react/kubernetes/namespaces/components/NamespaceForm/NamespaceForm.validation.tsx similarity index 67% rename from app/react/kubernetes/namespaces/CreateView/CreateNamespaceForm.validation.tsx rename to app/react/kubernetes/namespaces/components/NamespaceForm/NamespaceForm.validation.tsx index 1eb8572f6..9c6f5acfb 100644 --- a/app/react/kubernetes/namespaces/CreateView/CreateNamespaceForm.validation.tsx +++ b/app/react/kubernetes/namespaces/components/NamespaceForm/NamespaceForm.validation.tsx @@ -1,14 +1,15 @@ import { string, object, array, SchemaOf } from 'yup'; -import { registriesValidationSchema } from '../components/RegistriesFormSection/registriesValidationSchema'; -import { getResourceQuotaValidationSchema } from '../components/ResourceQuotaFormSection/getResourceQuotaValidationSchema'; +import { NamespaceFormValues } from '../../types'; -import { CreateNamespaceFormValues } from './types'; +import { registriesValidationSchema } from './RegistriesFormSection/registriesValidationSchema'; +import { getResourceQuotaValidationSchema } from './ResourceQuotaFormSection/getResourceQuotaValidationSchema'; export function getNamespaceValidationSchema( memoryLimit: number, + cpuLimit: number, namespaceNames: string[] -): SchemaOf { +): SchemaOf { return object({ name: string() .matches( @@ -19,7 +20,7 @@ export function getNamespaceValidationSchema( // must not have the same name as an existing namespace .notOneOf(namespaceNames, 'Name must be unique.') .required('Name is required.'), - resourceQuota: getResourceQuotaValidationSchema(memoryLimit), + resourceQuota: getResourceQuotaValidationSchema(memoryLimit, cpuLimit), // ingress classes table is constrained already, and doesn't need validation ingressClasses: array(), registries: registriesValidationSchema, diff --git a/app/react/kubernetes/namespaces/components/NamespaceForm/NamespaceInnerForm.tsx b/app/react/kubernetes/namespaces/components/NamespaceForm/NamespaceInnerForm.tsx new file mode 100644 index 000000000..99ea225d8 --- /dev/null +++ b/app/react/kubernetes/namespaces/components/NamespaceForm/NamespaceInnerForm.tsx @@ -0,0 +1,164 @@ +import { Field, Form, FormikProps } from 'formik'; +import { MultiValue } from 'react-select'; + +import { useEnvironmentId } from '@/react/hooks/useEnvironmentId'; +import { useCurrentEnvironment } from '@/react/hooks/useCurrentEnvironment'; +import { Registry } from '@/react/portainer/registries/types/registry'; +import { Authorized, useAuthorizations } from '@/react/hooks/useUser'; + +import { FormControl } from '@@/form-components/FormControl'; +import { FormSection } from '@@/form-components/FormSection'; +import { Input } from '@@/form-components/Input'; +import { FormActions } from '@@/form-components/FormActions'; +import { SystemBadge } from '@@/Badge/SystemBadge'; + +import { IngressClassDatatable } from '../../../cluster/ingressClass/IngressClassDatatable'; +import { useIngressControllerClassMapQuery } from '../../../cluster/ingressClass/useIngressControllerClassMap'; +import { CreateNamespaceFormValues } from '../../CreateView/types'; +import { AnnotationsBeTeaser } from '../../../annotations/AnnotationsBeTeaser'; +import { isDefaultNamespace } from '../../isDefaultNamespace'; +import { useIsSystemNamespace } from '../../queries/useIsSystemNamespace'; + +import { NamespaceSummary } from './NamespaceSummary'; +import { StorageQuotaFormSection } from './StorageQuotaFormSection/StorageQuotaFormSection'; +import { RegistriesFormSection } from './RegistriesFormSection'; +import { ResourceQuotaFormValues } from './ResourceQuotaFormSection/types'; +import { ResourceQuotaFormSection } from './ResourceQuotaFormSection'; +import { LoadBalancerFormSection } from './LoadBalancerFormSection'; +import { ToggleSystemNamespaceButton } from './ToggleSystemNamespaceButton'; + +const namespaceWriteAuth = 'K8sResourcePoolDetailsW'; + +export function NamespaceInnerForm({ + errors, + isValid, + dirty, + setFieldValue, + values, + isSubmitting, + initialValues, + isEdit, +}: FormikProps & { isEdit?: boolean }) { + const { authorized: hasNamespaceWriteAuth } = useAuthorizations( + namespaceWriteAuth, + undefined, + true + ); + const isSystemNamespace = useIsSystemNamespace(values.name, isEdit === true); + const isEditingDisabled = + !hasNamespaceWriteAuth || + isDefaultNamespace(values.name) || + isSystemNamespace; + const environmentId = useEnvironmentId(); + const environmentQuery = useCurrentEnvironment(); + const ingressClassesQuery = useIngressControllerClassMapQuery({ + environmentId, + namespace: values.name, + allowedOnly: true, + }); + + if (environmentQuery.isLoading) { + return null; + } + + const useLoadBalancer = + environmentQuery.data?.Kubernetes.Configuration.UseLoadBalancer; + const enableResourceOverCommit = + environmentQuery.data?.Kubernetes.Configuration.EnableResourceOverCommit; + const enableIngressControllersPerNamespace = + environmentQuery.data?.Kubernetes.Configuration + .IngressAvailabilityPerNamespace; + const storageClasses = + environmentQuery.data?.Kubernetes.Configuration.StorageClasses ?? []; + + return ( +
+ + {isEdit ? ( +
+ {values.name} + {isSystemNamespace && } +
+ ) : ( + + )} +
+ + {(values.resourceQuota.enabled || !isEditingDisabled) && ( + + setFieldValue('resourceQuota', resourceQuota) + } + errors={errors.resourceQuota} + namespaceName={values.name} + isEditingDisabled={isEditingDisabled} + /> + )} + {useLoadBalancer && } + {enableIngressControllersPerNamespace && ( + + + setFieldValue('ingressClasses', classes)} + values={values.ingressClasses} + description="Enable the ingress controllers that users can select when publishing applications in this namespace." + noIngressControllerLabel="No ingress controllers available in the cluster. Go to the cluster setup view to configure and allow the use of ingress controllers in the cluster." + view="namespace" + isLoading={ingressClassesQuery.isLoading} + initialValues={initialValues.ingressClasses} + /> + + + )} + ) => + setFieldValue('registries', registries) + } + errors={errors.registries} + isEditingDisabled={isEditingDisabled} + /> + {storageClasses.length > 0 && ( + + )} + + + + {isEdit && ( + + )} + + + + ); +} diff --git a/app/react/kubernetes/namespaces/components/NamespaceForm/NamespaceSummary.tsx b/app/react/kubernetes/namespaces/components/NamespaceForm/NamespaceSummary.tsx new file mode 100644 index 000000000..3c1a36aea --- /dev/null +++ b/app/react/kubernetes/namespaces/components/NamespaceForm/NamespaceSummary.tsx @@ -0,0 +1,74 @@ +import { isEqual } from 'lodash'; + +import { FormSection } from '@@/form-components/FormSection'; +import { TextTip } from '@@/Tip/TextTip'; + +import { NamespaceFormValues } from '../../types'; + +interface Props { + initialValues: NamespaceFormValues; + values: NamespaceFormValues; + isValid: boolean; +} + +export function NamespaceSummary({ initialValues, values, isValid }: Props) { + // only compare the values from k8s related resources + const { registries: newRegistryValues, ...newK8sValues } = values; + const { registries: oldRegistryValues, ...oldK8sValues } = initialValues; + const hasChanges = !isEqual(newK8sValues, oldK8sValues); + if (!hasChanges || !isValid) { + return null; + } + + const isCreatingNamespace = !oldK8sValues.name && newK8sValues.name; + + const enabledQuotaInitialValues = initialValues.resourceQuota.enabled; + const enabledQuotaNewValues = values.resourceQuota.enabled; + + const isCreatingResourceQuota = + !enabledQuotaInitialValues && enabledQuotaNewValues; + const isUpdatingResourceQuota = + enabledQuotaInitialValues && enabledQuotaNewValues; + const isDeletingResourceQuota = + enabledQuotaInitialValues && !enabledQuotaNewValues; + + return ( + +
+
+ + Portainer will execute the following Kubernetes actions. + +
+
+
+
    + {isCreatingNamespace && ( +
  • + Create a Namespace named{' '} + {values.name} +
  • + )} + {isCreatingResourceQuota && ( +
  • + Create a ResourceQuota named{' '} + portainer-rq-{values.name} +
  • + )} + {isUpdatingResourceQuota && ( +
  • + Update a ResourceQuota named{' '} + portainer-rq-{values.name} +
  • + )} + {isDeletingResourceQuota && ( +
  • + Delete a ResourceQuota named{' '} + portainer-rq-{values.name} +
  • + )} +
+
+
+ ); +} diff --git a/app/react/kubernetes/namespaces/components/RegistriesFormSection/RegistriesFormSection.tsx b/app/react/kubernetes/namespaces/components/NamespaceForm/RegistriesFormSection/RegistriesFormSection.tsx similarity index 75% rename from app/react/kubernetes/namespaces/components/RegistriesFormSection/RegistriesFormSection.tsx rename to app/react/kubernetes/namespaces/components/NamespaceForm/RegistriesFormSection/RegistriesFormSection.tsx index 597a4b86d..e491fb101 100644 --- a/app/react/kubernetes/namespaces/components/RegistriesFormSection/RegistriesFormSection.tsx +++ b/app/react/kubernetes/namespaces/components/NamespaceForm/RegistriesFormSection/RegistriesFormSection.tsx @@ -16,22 +16,30 @@ type Props = { values: MultiValue; onChange: (value: MultiValue) => void; errors?: string | string[] | FormikErrors[]; + isEditingDisabled: boolean; }; -export function RegistriesFormSection({ values, onChange, errors }: Props) { +export function RegistriesFormSection({ + values, + onChange, + errors, + isEditingDisabled, +}: Props) { const environmentId = useEnvironmentId(); const registriesQuery = useEnvironmentRegistries(environmentId, { hideDefault: true, }); return ( - - Define which registries can be used by users who have access to this - namespace. - + {!isEditingDisabled && ( + + Define which registries can be used by users who have access to this + namespace. + + )} {registriesQuery.isLoading && ( @@ -43,6 +51,7 @@ export function RegistriesFormSection({ values, onChange, errors }: Props) { onChange={(registries) => onChange(registries)} options={registriesQuery.data} inputId="registries" + isEditingDisabled={isEditingDisabled} /> )} diff --git a/app/react/kubernetes/namespaces/components/NamespaceForm/RegistriesFormSection/RegistriesSelector.tsx b/app/react/kubernetes/namespaces/components/NamespaceForm/RegistriesFormSection/RegistriesSelector.tsx new file mode 100644 index 000000000..4cf9d5f8f --- /dev/null +++ b/app/react/kubernetes/namespaces/components/NamespaceForm/RegistriesFormSection/RegistriesSelector.tsx @@ -0,0 +1,74 @@ +import { MultiValue } from 'react-select'; + +import { Registry } from '@/react/portainer/registries/types/registry'; +import { useCurrentUser } from '@/react/hooks/useUser'; + +import { Select } from '@@/form-components/ReactSelect'; +import { Link } from '@@/Link'; + +interface Props { + value: MultiValue; + onChange(value: MultiValue): void; + options?: Registry[]; + inputId?: string; + isEditingDisabled?: boolean; +} + +export function RegistriesSelector({ + value, + onChange, + options = [], + inputId, + isEditingDisabled, +}: Props) { + const { isPureAdmin } = useCurrentUser(); + + if (options.length === 0) { + return ( +

+ {isPureAdmin ? ( + + No registries available. Head over to the{' '} + + registry view + {' '} + to define a container registry. + + ) : ( + + No registries available. Contact your administrator to create a + container registry. + + )} +

+ ); + } + + if (isEditingDisabled) { + return ( +

+ {value.length === 0 ? 'None' : value.map((v) => v.Name).join(', ')} +

+ ); + } + + return ( + option.Name} - getOptionValue={(option) => String(option.Id)} - options={options} - value={value} - closeMenuOnSelect={false} - onChange={onChange} - inputId={inputId} - data-cy="namespaceCreate-registrySelect" - placeholder="Select one or more registries" - /> - - ); -} diff --git a/app/react/kubernetes/namespaces/components/ResourceQuotaFormSection/ResourceQuotaFormSection.tsx b/app/react/kubernetes/namespaces/components/ResourceQuotaFormSection/ResourceQuotaFormSection.tsx deleted file mode 100644 index a7f3be7d0..000000000 --- a/app/react/kubernetes/namespaces/components/ResourceQuotaFormSection/ResourceQuotaFormSection.tsx +++ /dev/null @@ -1,125 +0,0 @@ -import { FormikErrors } from 'formik'; - -import { useEnvironmentId } from '@/react/hooks/useEnvironmentId'; - -import { FormControl } from '@@/form-components/FormControl'; -import { FormError } from '@@/form-components/FormError'; -import { FormSection } from '@@/form-components/FormSection'; -import { FormSectionTitle } from '@@/form-components/FormSectionTitle'; -import { Slider } from '@@/form-components/Slider'; -import { SwitchField } from '@@/form-components/SwitchField'; -import { TextTip } from '@@/Tip/TextTip'; -import { SliderWithInput } from '@@/form-components/Slider/SliderWithInput'; - -import { useClusterResourceLimitsQuery } from '../../CreateView/queries/useResourceLimitsQuery'; - -import { ResourceQuotaFormValues } from './types'; - -interface Props { - values: ResourceQuotaFormValues; - onChange: (value: ResourceQuotaFormValues) => void; - enableResourceOverCommit?: boolean; - errors?: FormikErrors; -} - -export function ResourceQuotaFormSection({ - values, - onChange, - errors, - enableResourceOverCommit, -}: Props) { - const environmentId = useEnvironmentId(); - const resourceLimitsQuery = useClusterResourceLimitsQuery(environmentId); - const cpuLimit = resourceLimitsQuery.data?.CPU ?? 0; - const memoryLimit = resourceLimitsQuery.data?.Memory ?? 0; - - return ( - - - A resource quota sets boundaries on the compute resources a namespace - can use. It's good practice to set a quota for a namespace to - manage resources effectively. Alternatively, you can disable assigning a - quota for unrestricted access (not recommended). - - - onChange({ ...values, enabled })} - /> - - {(values.enabled || !enableResourceOverCommit) && ( -
-
- Resource Limits -
- - {(!cpuLimit || !memoryLimit) && ( - - Not enough resources available in the cluster to apply a resource - reservation. - - )} - - {/* keep the FormError component present, but invisible to avoid layout shift */} - {cpuLimit && memoryLimit ? ( - - {/* 'error' keeps the formerror the exact same height while hidden so there is no layout shift */} - {typeof errors === 'string' ? errors : 'error'} - - ) : null} - - -
- {memoryLimit >= 0 && ( - - onChange({ ...values, memory: `${value}` }) - } - max={memoryLimit} - step={128} - dataCy="k8sNamespaceCreate-memoryLimit" - visibleTooltip - inputId="memory-limit" - /> - )} - {errors?.memory && ( - {errors.memory} - )} -
-
- - -
- { - if (Array.isArray(cpu)) { - return; - } - onChange({ ...values, cpu: cpu.toString() }); - }} - dataCy="k8sNamespaceCreate-cpuLimitSlider" - visibleTooltip - /> -
-
-
- )} -
- ); -} diff --git a/app/react/kubernetes/namespaces/components/ResourceQuotaFormSection/getResourceQuotaValidationSchema.ts b/app/react/kubernetes/namespaces/components/ResourceQuotaFormSection/getResourceQuotaValidationSchema.ts deleted file mode 100644 index d7565aa53..000000000 --- a/app/react/kubernetes/namespaces/components/ResourceQuotaFormSection/getResourceQuotaValidationSchema.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { boolean, string, object, SchemaOf, TestContext } from 'yup'; - -import { ResourceQuotaFormValues } from './types'; - -export function getResourceQuotaValidationSchema( - memoryLimit: number -): SchemaOf { - return object({ - enabled: boolean().required('Resource quota enabled status is required.'), - memory: string().test( - 'memory-validation', - `Value must be between 0 and ${memoryLimit}.`, - memoryValidation - ), - cpu: string().test( - 'cpu-validation', - 'CPU limit value is required.', - cpuValidation - ), - }).test( - 'resource-quota-validation', - 'At least a single limit must be set.', - oneLimitSet - ); - - function oneLimitSet({ - enabled, - memory, - cpu, - }: Partial) { - return !enabled || (Number(memory) ?? 0) > 0 || (Number(cpu) ?? 0) > 0; - } - - function memoryValidation(this: TestContext, memoryValue?: string) { - const memory = Number(memoryValue) ?? 0; - const { enabled } = this.parent; - return !enabled || (memory >= 0 && memory <= memoryLimit); - } - - function cpuValidation(this: TestContext, cpuValue?: string) { - const cpu = Number(cpuValue) ?? 0; - const { enabled } = this.parent; - return !enabled || cpu >= 0; - } -} diff --git a/app/react/kubernetes/namespaces/components/ResourceUsageItem.tsx b/app/react/kubernetes/namespaces/components/ResourceUsageItem.tsx new file mode 100644 index 000000000..647464ba9 --- /dev/null +++ b/app/react/kubernetes/namespaces/components/ResourceUsageItem.tsx @@ -0,0 +1,32 @@ +import { ProgressBar } from '@@/ProgressBar'; +import { FormControl } from '@@/form-components/FormControl'; + +interface ResourceUsageItemProps { + value: number; + total: number; + annotation?: React.ReactNode; + label: string; +} + +export function ResourceUsageItem({ + value, + total, + annotation, + label, +}: ResourceUsageItemProps) { + return ( + +
+ +
{annotation}
+
+
+ ); +} diff --git a/app/react/kubernetes/namespaces/components/StorageQuotaFormSection/StorageQuotaItem.tsx b/app/react/kubernetes/namespaces/components/StorageQuotaFormSection/StorageQuotaItem.tsx deleted file mode 100644 index 4de76917d..000000000 --- a/app/react/kubernetes/namespaces/components/StorageQuotaFormSection/StorageQuotaItem.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import { Database } from 'lucide-react'; - -import { FeatureId } from '@/react/portainer/feature-flags/enums'; - -import { Icon } from '@@/Icon'; -import { FormSectionTitle } from '@@/form-components/FormSectionTitle'; -import { SwitchField } from '@@/form-components/SwitchField'; - -export function StorageQuotaItem() { - return ( -
- -
- - standard -
-
-
-
-
- {}} - featureId={FeatureId.K8S_RESOURCE_POOL_STORAGE_QUOTA} - /> -
-
-
- ); -} diff --git a/app/react/kubernetes/namespaces/queries/queryKeys.ts b/app/react/kubernetes/namespaces/queries/queryKeys.ts index 67f2a4566..ecfe4ea58 100644 --- a/app/react/kubernetes/namespaces/queries/queryKeys.ts +++ b/app/react/kubernetes/namespaces/queries/queryKeys.ts @@ -1,7 +1,12 @@ import { compact } from 'lodash'; +import { EnvironmentId } from '@/react/portainer/environments/types'; + export const queryKeys = { - list: (environmentId: number, options?: { withResourceQuota?: boolean }) => + list: ( + environmentId: EnvironmentId, + options?: { withResourceQuota?: boolean } + ) => compact([ 'environments', environmentId, @@ -9,7 +14,7 @@ export const queryKeys = { 'namespaces', options?.withResourceQuota, ]), - namespace: (environmentId: number, namespace: string) => + namespace: (environmentId: EnvironmentId, namespace: string) => [ 'environments', environmentId, @@ -17,4 +22,13 @@ export const queryKeys = { 'namespaces', namespace, ] as const, + namespaceYAML: (environmentId: EnvironmentId, namespace: string) => + [ + 'environments', + environmentId, + 'kubernetes', + 'namespaces', + namespace, + 'yaml', + ] as const, }; diff --git a/app/react/kubernetes/namespaces/CreateView/queries/useCreateNamespaceMutation.ts b/app/react/kubernetes/namespaces/queries/useCreateNamespaceMutation.ts similarity index 75% rename from app/react/kubernetes/namespaces/CreateView/queries/useCreateNamespaceMutation.ts rename to app/react/kubernetes/namespaces/queries/useCreateNamespaceMutation.ts index 717d0979a..638d2977c 100644 --- a/app/react/kubernetes/namespaces/CreateView/queries/useCreateNamespaceMutation.ts +++ b/app/react/kubernetes/namespaces/queries/useCreateNamespaceMutation.ts @@ -1,23 +1,25 @@ -import { useMutation } from '@tanstack/react-query'; +import { useMutation, useQueryClient } from '@tanstack/react-query'; import axios, { parseAxiosError } from '@/portainer/services/axios'; -import { withError } from '@/react-tools/react-query'; +import { withGlobalError, withInvalidate } from '@/react-tools/react-query'; import { updateEnvironmentRegistryAccess } from '@/react/portainer/environments/environment.service/registries'; import { EnvironmentId } from '@/react/portainer/environments/types'; -import { IngressControllerClassMap } from '../../../cluster/ingressClass/types'; -import { updateIngressControllerClassMap } from '../../../cluster/ingressClass/useIngressControllerClassMap'; -import { Namespaces } from '../../types'; -import { CreateNamespacePayload, UpdateRegistryPayload } from '../types'; +import { IngressControllerClassMap } from '../../cluster/ingressClass/types'; +import { updateIngressControllerClassMap } from '../../cluster/ingressClass/useIngressControllerClassMap'; +import { Namespaces, NamespacePayload, UpdateRegistryPayload } from '../types'; + +import { queryKeys } from './queryKeys'; export function useCreateNamespaceMutation(environmentId: EnvironmentId) { + const queryClient = useQueryClient(); return useMutation( async ({ createNamespacePayload, updateRegistriesPayload, namespaceIngressControllerPayload, }: { - createNamespacePayload: CreateNamespacePayload; + createNamespacePayload: NamespacePayload; updateRegistriesPayload: UpdateRegistryPayload[]; namespaceIngressControllerPayload: IngressControllerClassMap[]; }) => { @@ -51,7 +53,8 @@ export function useCreateNamespaceMutation(environmentId: EnvironmentId) { ]); }, { - ...withError('Unable to create namespace'), + ...withGlobalError('Unable to create namespace'), + ...withInvalidate(queryClient, [queryKeys.list(environmentId)]), } ); } @@ -59,7 +62,7 @@ export function useCreateNamespaceMutation(environmentId: EnvironmentId) { // createNamespace is used to create a namespace using the Portainer backend async function createNamespace( environmentId: EnvironmentId, - payload: CreateNamespacePayload + payload: NamespacePayload ) { try { const { data: ns } = await axios.post( diff --git a/app/react/kubernetes/namespaces/queries/useIsSystemNamespace.ts b/app/react/kubernetes/namespaces/queries/useIsSystemNamespace.ts index f9e806524..2b59ac9cb 100644 --- a/app/react/kubernetes/namespaces/queries/useIsSystemNamespace.ts +++ b/app/react/kubernetes/namespaces/queries/useIsSystemNamespace.ts @@ -4,10 +4,11 @@ import { PortainerNamespace } from '../types'; import { useNamespaceQuery } from './useNamespaceQuery'; -export function useIsSystemNamespace(namespace: string) { +export function useIsSystemNamespace(namespace: string, enabled = true) { const envId = useEnvironmentId(); const query = useNamespaceQuery(envId, namespace, { select: (namespace) => namespace.IsSystem, + enabled, }); return !!query.data; diff --git a/app/react/kubernetes/namespaces/queries/useNamespaceQuery.ts b/app/react/kubernetes/namespaces/queries/useNamespaceQuery.ts index b14c3d625..194016774 100644 --- a/app/react/kubernetes/namespaces/queries/useNamespaceQuery.ts +++ b/app/react/kubernetes/namespaces/queries/useNamespaceQuery.ts @@ -8,19 +8,26 @@ import { PortainerNamespace } from '../types'; import { queryKeys } from './queryKeys'; +type QueryParams = 'withResourceQuota'; + export function useNamespaceQuery( environmentId: EnvironmentId, namespace: string, { select, + enabled, + params, }: { select?(namespace: PortainerNamespace): T; + params?: Record; + enabled?: boolean; } = {} ) { return useQuery( queryKeys.namespace(environmentId, namespace), - () => getNamespace(environmentId, namespace), + () => getNamespace(environmentId, namespace, params), { + enabled: !!environmentId && !!namespace && enabled, onError: (err) => { notifyError('Failure', err as Error, 'Unable to get namespace.'); }, @@ -32,11 +39,15 @@ export function useNamespaceQuery( // getNamespace is used to retrieve a namespace using the Portainer backend export async function getNamespace( environmentId: EnvironmentId, - namespace: string + namespace: string, + params?: Record ) { try { const { data: ns } = await axios.get( - `kubernetes/${environmentId}/namespaces/${namespace}` + `kubernetes/${environmentId}/namespaces/${namespace}`, + { + params, + } ); return ns; } catch (e) { diff --git a/app/react/kubernetes/namespaces/queries/useNamespaceYAML.ts b/app/react/kubernetes/namespaces/queries/useNamespaceYAML.ts new file mode 100644 index 000000000..436b200be --- /dev/null +++ b/app/react/kubernetes/namespaces/queries/useNamespaceYAML.ts @@ -0,0 +1,71 @@ +import { useQuery } from '@tanstack/react-query'; + +import axios from '@/portainer/services/axios'; +import { EnvironmentId } from '@/react/portainer/environments/types'; +import { isFulfilled } from '@/portainer/helpers/promise-utils'; + +import { parseKubernetesAxiosError } from '../../axiosError'; +import { generateResourceQuotaName } from '../resourceQuotaUtils'; + +import { queryKeys } from './queryKeys'; + +/** + * Gets the YAML for a namespace and its resource quota directly from the K8s proxy API. + */ +export function useNamespaceYAML( + environmentId: EnvironmentId, + namespaceName: string +) { + return useQuery({ + queryKey: queryKeys.namespaceYAML(environmentId, namespaceName), + queryFn: () => composeNamespaceYAML(environmentId, namespaceName), + }); +} + +async function composeNamespaceYAML( + environmentId: EnvironmentId, + namespace: string +) { + const settledPromises = await Promise.allSettled([ + getNamespaceYAML(environmentId, namespace), + getResourceQuotaYAML(environmentId, namespace), + ]); + const resolvedPromises = settledPromises.filter(isFulfilled); + return resolvedPromises.map((p) => p.value).join('\n---\n'); +} + +async function getNamespaceYAML( + environmentId: EnvironmentId, + namespace: string +) { + try { + const { data: yaml } = await axios.get( + `/endpoints/${environmentId}/kubernetes/api/v1/namespaces/${namespace}`, + { + headers: { + Accept: 'application/yaml', + }, + } + ); + return yaml; + } catch (error) { + throw parseKubernetesAxiosError(error, 'Unable to retrieve namespace YAML'); + } +} + +async function getResourceQuotaYAML( + environmentId: EnvironmentId, + namespace: string +) { + const resourceQuotaName = generateResourceQuotaName(namespace); + try { + const { data: yaml } = await axios.get( + `/endpoints/${environmentId}/kubernetes/api/v1/namespaces/${namespace}/resourcequotas/${resourceQuotaName}`, + { headers: { Accept: 'application/yaml' } } + ); + return yaml; + } catch (e) { + // silently ignore if resource quota does not exist + return null; + } +} diff --git a/app/react/kubernetes/namespaces/CreateView/queries/useResourceLimitsQuery.ts b/app/react/kubernetes/namespaces/queries/useResourceLimitsQuery.ts similarity index 100% rename from app/react/kubernetes/namespaces/CreateView/queries/useResourceLimitsQuery.ts rename to app/react/kubernetes/namespaces/queries/useResourceLimitsQuery.ts diff --git a/app/react/kubernetes/namespaces/queries/useToggleSystemNamespace.ts b/app/react/kubernetes/namespaces/queries/useToggleSystemNamespace.ts new file mode 100644 index 000000000..eab570ef4 --- /dev/null +++ b/app/react/kubernetes/namespaces/queries/useToggleSystemNamespace.ts @@ -0,0 +1,34 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query'; + +import axios from '@/portainer/services/axios'; +import { EnvironmentId } from '@/react/portainer/environments/types'; +import { withGlobalError, withInvalidate } from '@/react-tools/react-query'; + +import { queryKeys } from './queryKeys'; + +export function useToggleSystemNamespaceMutation( + environmentId: EnvironmentId, + namespaceName: string +) { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (isSystem: boolean) => + toggleSystemNamespace(environmentId, namespaceName, isSystem), + ...withInvalidate(queryClient, [ + queryKeys.namespace(environmentId, namespaceName), + ]), + ...withGlobalError('Failed to update namespace'), + }); +} + +async function toggleSystemNamespace( + environmentId: EnvironmentId, + namespaceName: string, + system: boolean +) { + const response = await axios.put( + `/kubernetes/${environmentId}/namespaces/${namespaceName}/system`, + { system } + ); + return response.data; +} diff --git a/app/react/kubernetes/namespaces/queries/useUpdateNamespaceMutation.ts b/app/react/kubernetes/namespaces/queries/useUpdateNamespaceMutation.ts new file mode 100644 index 000000000..c281a4b60 --- /dev/null +++ b/app/react/kubernetes/namespaces/queries/useUpdateNamespaceMutation.ts @@ -0,0 +1,83 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query'; + +import axios, { parseAxiosError } from '@/portainer/services/axios'; +import { withGlobalError, withInvalidate } from '@/react-tools/react-query'; +import { updateEnvironmentRegistryAccess } from '@/react/portainer/environments/environment.service/registries'; +import { EnvironmentId } from '@/react/portainer/environments/types'; +import { notifyError } from '@/portainer/services/notifications'; + +import { IngressControllerClassMap } from '../../cluster/ingressClass/types'; +import { updateIngressControllerClassMap } from '../../cluster/ingressClass/useIngressControllerClassMap'; +import { Namespaces, NamespacePayload, UpdateRegistryPayload } from '../types'; + +import { queryKeys } from './queryKeys'; + +export function useUpdateNamespaceMutation(environmentId: EnvironmentId) { + const queryClient = useQueryClient(); + return useMutation( + async ({ + createNamespacePayload, + updateRegistriesPayload, + namespaceIngressControllerPayload, + }: { + createNamespacePayload: NamespacePayload; + updateRegistriesPayload: UpdateRegistryPayload[]; + namespaceIngressControllerPayload: IngressControllerClassMap[]; + }) => { + const { Name: namespaceName } = createNamespacePayload; + const updatedNamespace = await updateNamespace( + environmentId, + namespaceName, + createNamespacePayload + ); + + // collect promises + const updateRegistriesPromises = updateRegistriesPayload.map( + ({ Id, Namespaces }) => + updateEnvironmentRegistryAccess(environmentId, Id, { + Namespaces, + }) + ); + const updateIngressControllerPromise = updateIngressControllerClassMap( + environmentId, + namespaceIngressControllerPayload, + createNamespacePayload.Name + ); + const results = await Promise.allSettled([ + updateIngressControllerPromise, + ...updateRegistriesPromises, + ]); + // Check for any failures in the additional updates + const failures = results.filter((result) => result.status === 'rejected'); + failures.forEach((failure) => { + notifyError( + 'Unable to update namespace', + undefined, + failure.reason as string + ); + }); + return updatedNamespace; + }, + { + ...withGlobalError('Unable to update namespace'), + ...withInvalidate(queryClient, [queryKeys.list(environmentId)]), + } + ); +} + +// updateNamespace is used to update a namespace using the Portainer backend +async function updateNamespace( + environmentId: EnvironmentId, + namespace: string, + payload: NamespacePayload +) { + try { + const { data: ns } = await axios.put( + `kubernetes/${environmentId}/namespaces/${namespace}`, + payload + ); + return ns; + } catch (e) { + throw parseAxiosError(e as Error, 'Unable to create namespace'); + } +} diff --git a/app/react/kubernetes/namespaces/resourceQuotaUtils.test.ts b/app/react/kubernetes/namespaces/resourceQuotaUtils.test.ts new file mode 100644 index 000000000..4376e996a --- /dev/null +++ b/app/react/kubernetes/namespaces/resourceQuotaUtils.test.ts @@ -0,0 +1,17 @@ +import { parseCPU } from './resourceQuotaUtils'; + +// test parseCPU with '', '2', '100m', '100u' +describe('parseCPU', () => { + it('should return 0 for empty string', () => { + expect(parseCPU('')).toBe(0); + }); + it('should return 2 for 2', () => { + expect(parseCPU('2')).toBe(2); + }); + it('should return 0.1 for 100m', () => { + expect(parseCPU('100m')).toBe(0.1); + }); + it('should return 0.0001 for 100u', () => { + expect(parseCPU('100u')).toBe(0.0001); + }); +}); diff --git a/app/react/kubernetes/namespaces/resourceQuotaUtils.ts b/app/react/kubernetes/namespaces/resourceQuotaUtils.ts new file mode 100644 index 000000000..b19879cf5 --- /dev/null +++ b/app/react/kubernetes/namespaces/resourceQuotaUtils.ts @@ -0,0 +1,64 @@ +import { endsWith } from 'lodash'; +import filesizeParser from 'filesize-parser'; + +export const KubernetesPortainerResourceQuotaPrefix = 'portainer-rq-'; + +export function generateResourceQuotaName(name: string) { + return `${KubernetesPortainerResourceQuotaPrefix}${name}`; +} + +/** + * parseCPU converts a CPU string to a number in cores. + * It supports m (milli), u (micro), n (nano), p (pico) suffixes. + * + * If given an empty string, it returns 0. + */ +export function parseCPU(cpu: string) { + let res = parseInt(cpu, 10); + if (Number.isNaN(res)) { + return 0; + } + + if (endsWith(cpu, 'm')) { + // milli + res /= 1000; + } else if (endsWith(cpu, 'u')) { + // micro + res /= 1000000; + } else if (endsWith(cpu, 'n')) { + // nano + res /= 1000000000; + } else if (endsWith(cpu, 'p')) { + // pico + res /= 1000000000000; + } + return res; +} + +export function terabytesValue(value: string | number) { + return gigabytesValue(value) / 1000; +} + +export function gigabytesValue(value: string | number) { + return megaBytesValue(value) / 1000; +} + +export function megaBytesValue(value: string | number) { + return Math.floor(safeFilesizeParser(value, 10) / 1000 / 1000); +} + +export function bytesValue(mem: string | number) { + return safeFilesizeParser(mem, 10) * 1000 * 1000; +} + +/** + * The default base is 2, you can use base 10 if you want + * https://github.com/patrickkettner/filesize-parser#readme + */ +function safeFilesizeParser(value: string | number, base: 2 | 10 = 2) { + if (!value || Number.isNaN(value)) { + return 0; + } + + return filesizeParser(value, { base }); +} diff --git a/app/react/kubernetes/namespaces/types.ts b/app/react/kubernetes/namespaces/types.ts index 922e74a15..ba4abb744 100644 --- a/app/react/kubernetes/namespaces/types.ts +++ b/app/react/kubernetes/namespaces/types.ts @@ -1,10 +1,17 @@ import { NamespaceStatus, ResourceQuota } from 'kubernetes-types/core/v1'; +import { Registry } from '@/react/portainer/registries/types/registry'; + +import { IngressControllerClassMap } from '../cluster/ingressClass/types'; + +import { ResourceQuotaFormValues } from './components/NamespaceForm/ResourceQuotaFormSection/types'; + export interface PortainerNamespace { Id: string; Name: string; Status: NamespaceStatus; - CreationDate: number; + Annotations: Record | null; + CreationDate: string; NamespaceOwner: string; IsSystem: boolean; IsDefault: boolean; @@ -14,3 +21,21 @@ export interface PortainerNamespace { // type returned via the internal portainer namespaces api, with simplified fields // it is a record currently (legacy reasons), but it should be an array export type Namespaces = Record; + +export type NamespaceFormValues = { + name: string; + resourceQuota: ResourceQuotaFormValues; + ingressClasses: IngressControllerClassMap[]; + registries: Registry[]; +}; + +export type NamespacePayload = { + Name: string; + Owner: string; + ResourceQuota: ResourceQuotaFormValues; +}; + +export type UpdateRegistryPayload = { + Id: number; + Namespaces: string[]; +}; diff --git a/app/react/kubernetes/networks/services/queries.ts b/app/react/kubernetes/networks/services/queries.ts deleted file mode 100644 index 00b798e9a..000000000 --- a/app/react/kubernetes/networks/services/queries.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { useQuery } from '@tanstack/react-query'; - -import { EnvironmentId } from '@/react/portainer/environments/types'; -import { error as notifyError } from '@/portainer/services/notifications'; - -import { getServices } from './service'; -import { Service } from './types'; - -export function useNamespaceServices( - environmentId: EnvironmentId, - namespace: string -) { - return useQuery( - [ - 'environments', - environmentId, - 'kubernetes', - 'namespaces', - namespace, - 'services', - ], - () => - namespace ? getServices(environmentId, namespace) : ([] as Service[]), - { - onError: (err) => { - notifyError('Failure', err as Error, 'Unable to get services'); - }, - } - ); -} diff --git a/app/react/kubernetes/networks/services/service.ts b/app/react/kubernetes/networks/services/service.ts deleted file mode 100644 index 5ea7c27e9..000000000 --- a/app/react/kubernetes/networks/services/service.ts +++ /dev/null @@ -1,23 +0,0 @@ -import axios, { parseAxiosError } from '@/portainer/services/axios'; -import { EnvironmentId } from '@/react/portainer/environments/types'; - -import { Service } from './types'; - -export async function getServices( - environmentId: EnvironmentId, - namespace: string -) { - try { - const { data: services } = await axios.get( - buildUrl(environmentId, namespace) - ); - return services; - } catch (e) { - throw parseAxiosError(e as Error, 'Unable to retrieve services'); - } -} - -function buildUrl(environmentId: EnvironmentId, namespace: string) { - const url = `kubernetes/${environmentId}/namespaces/${namespace}/services`; - return url; -} diff --git a/app/react/kubernetes/networks/services/types.ts b/app/react/kubernetes/networks/services/types.ts deleted file mode 100644 index 1ed154eba..000000000 --- a/app/react/kubernetes/networks/services/types.ts +++ /dev/null @@ -1,33 +0,0 @@ -export interface Port { - Name: string; - Protocol: string; - Port: number; - TargetPort: number; - NodePort?: number; -} - -export interface IngressIP { - IP: string; -} - -export interface LoadBalancer { - Ingress: IngressIP[]; -} - -export interface Status { - LoadBalancer: LoadBalancer; -} - -export interface Service { - Annotations?: Document; - CreationTimestamp?: string; - Labels?: Document; - Name: string; - Namespace: string; - UID: string; - AllocateLoadBalancerNodePorts?: boolean; - Ports?: Port[]; - Selector?: Document; - Type: string; - Status?: Status; -} diff --git a/app/react/kubernetes/queries/useEvents.ts b/app/react/kubernetes/queries/useEvents.ts index 870a468ca..87d38eb94 100644 --- a/app/react/kubernetes/queries/useEvents.ts +++ b/app/react/kubernetes/queries/useEvents.ts @@ -3,7 +3,7 @@ import { useQuery } from '@tanstack/react-query'; import { EnvironmentId } from '@/react/portainer/environments/types'; import axios from '@/portainer/services/axios'; -import { withError } from '@/react-tools/react-query'; +import { withGlobalError } from '@/react-tools/react-query'; import { parseKubernetesAxiosError } from '../axiosError'; @@ -71,7 +71,7 @@ export function useEvents( queryKeys.base(environmentId, { params, namespace }), () => getEvents(environmentId, { params, namespace }), { - ...withError('Unable to retrieve events'), + ...withGlobalError('Unable to retrieve events'), refetchInterval() { return queryOptions?.autoRefreshRate ?? false; }, @@ -79,6 +79,17 @@ export function useEvents( ); } +export function useEventWarningsCount( + environmentId: EnvironmentId, + namespace?: string +) { + const resourceEventsQuery = useEvents(environmentId, { + namespace, + }); + const events = resourceEventsQuery.data || []; + return events.filter((e) => e.type === 'Warning').length; +} + function buildUrl(environmentId: EnvironmentId, namespace?: string) { return namespace ? `/endpoints/${environmentId}/kubernetes/api/v1/namespaces/${namespace}/events` diff --git a/app/react/kubernetes/services/ServicesView/ServicesDatatable/ServicesDatatable.tsx b/app/react/kubernetes/services/ServicesView/ServicesDatatable/ServicesDatatable.tsx index 86e717128..4786eaf2f 100644 --- a/app/react/kubernetes/services/ServicesView/ServicesDatatable/ServicesDatatable.tsx +++ b/app/react/kubernetes/services/ServicesView/ServicesDatatable/ServicesDatatable.tsx @@ -26,6 +26,7 @@ import { Service } from '../../types'; import { columns } from './columns'; import { createStore } from './datatable-store'; +import { ServiceRowData } from './types'; const storageKey = 'k8sServicesDatatable'; const settingsStore = createStore(storageKey); @@ -104,7 +105,7 @@ export function ServicesDatatable() { function useServicesRowData( services: Service[], namespaces?: Namespaces -): Service[] { +): ServiceRowData[] { return useMemo( () => services.map((service) => ({ @@ -119,9 +120,12 @@ function useServicesRowData( // needed to apply custom styling to the row cells and not globally. // required in the AC's for this ticket. -function servicesRenderRow(row: Row, highlightedItemId?: string) { +function servicesRenderRow( + row: Row, + highlightedItemId?: string +) { return ( - + cells={row.getVisibleCells()} className={clsx('[&>td]:!py-4 [&>td]:!align-top', { active: highlightedItemId === row.id, @@ -136,7 +140,7 @@ interface SelectedService { } type TableActionsProps = { - selectedItems: Service[]; + selectedItems: ServiceRowData[]; }; function TableActions({ selectedItems }: TableActionsProps) { diff --git a/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/application.tsx b/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/application.tsx index ba643739e..05b01d9cd 100644 --- a/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/application.tsx +++ b/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/application.tsx @@ -4,7 +4,7 @@ import { useEnvironmentId } from '@/react/hooks/useEnvironmentId'; import { Link } from '@@/Link'; -import { Service } from '../../../types'; +import { ServiceRowData } from '../types'; import { columnHelper } from './helper'; @@ -17,7 +17,7 @@ export const application = columnHelper.accessor( } ); -function Cell({ row, getValue }: CellContext) { +function Cell({ row, getValue }: CellContext) { const appName = getValue(); const environmentId = useEnvironmentId(); diff --git a/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/externalIP.tsx b/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/externalIP.tsx index a392d5fff..6a9a10be6 100644 --- a/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/externalIP.tsx +++ b/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/externalIP.tsx @@ -1,6 +1,6 @@ import { CellContext } from '@tanstack/react-table'; -import { Service } from '../../../types'; +import { ServiceRowData } from '../types'; import { ExternalIPLink } from './ExternalIPLink'; import { columnHelper } from './helper'; @@ -46,7 +46,7 @@ export const externalIP = columnHelper.accessor( } ); -function Cell({ row }: CellContext) { +function Cell({ row }: CellContext) { if (row.original.Type === 'ExternalName') { if (row.original.ExternalName) { const linkTo = `http://${row.original.ExternalName}`; @@ -106,7 +106,7 @@ function Cell({ row }: CellContext) { // calculate the scheme based on the ports of the service // favour https over http. -function getSchemeAndPort(svc: Service): [string, number] { +function getSchemeAndPort(svc: ServiceRowData): [string, number] { let scheme = ''; let servicePort = 0; diff --git a/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/helper.ts b/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/helper.ts index 1debacd16..b6b4547cf 100644 --- a/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/helper.ts +++ b/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/helper.ts @@ -1,5 +1,5 @@ import { createColumnHelper } from '@tanstack/react-table'; -import { Service } from '../../../types'; +import { ServiceRowData } from '../types'; -export const columnHelper = createColumnHelper(); +export const columnHelper = createColumnHelper(); diff --git a/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/namespace.tsx b/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/namespace.tsx index 9c37c96c7..050e24b00 100644 --- a/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/namespace.tsx +++ b/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/namespace.tsx @@ -4,7 +4,7 @@ import { filterHOC } from '@/react/components/datatables/Filter'; import { Link } from '@@/Link'; -import { Service } from '../../../types'; +import { ServiceRowData } from '../types'; import { columnHelper } from './helper'; @@ -31,6 +31,9 @@ export const namespace = columnHelper.accessor('Namespace', { filter: filterHOC('Filter by namespace'), }, enableColumnFilter: true, - filterFn: (row: Row, columnId: string, filterValue: string[]) => - filterValue.length === 0 || filterValue.includes(row.original.Namespace), + filterFn: ( + row: Row, + columnId: string, + filterValue: string[] + ) => filterValue.length === 0 || filterValue.includes(row.original.Namespace), }); diff --git a/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/type.tsx b/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/type.tsx index f443865e1..2dde20598 100644 --- a/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/type.tsx +++ b/app/react/kubernetes/services/ServicesView/ServicesDatatable/columns/type.tsx @@ -2,7 +2,7 @@ import { Row } from '@tanstack/react-table'; import { filterHOC } from '@@/datatables/Filter'; -import { Service } from '../../../types'; +import { ServiceRowData } from '../types'; import { columnHelper } from './helper'; @@ -13,6 +13,9 @@ export const type = columnHelper.accessor('Type', { filter: filterHOC('Filter by type'), }, enableColumnFilter: true, - filterFn: (row: Row, columnId: string, filterValue: string[]) => - filterValue.length === 0 || filterValue.includes(row.original.Type), + filterFn: ( + row: Row, + columnId: string, + filterValue: string[] + ) => filterValue.length === 0 || filterValue.includes(row.original.Type), }); diff --git a/app/react/kubernetes/services/ServicesView/ServicesDatatable/types.ts b/app/react/kubernetes/services/ServicesView/ServicesDatatable/types.ts new file mode 100644 index 000000000..00bc0393c --- /dev/null +++ b/app/react/kubernetes/services/ServicesView/ServicesDatatable/types.ts @@ -0,0 +1,5 @@ +import { Service } from '../../types'; + +export type ServiceRowData = Service & { + IsSystem: boolean; +}; diff --git a/app/react/kubernetes/services/types.ts b/app/react/kubernetes/services/types.ts index c03bc3e69..805397c54 100644 --- a/app/react/kubernetes/services/types.ts +++ b/app/react/kubernetes/services/types.ts @@ -26,18 +26,17 @@ export type ServiceType = export type Service = { Name: string; UID: string; + Type: ServiceType; Namespace: string; Annotations?: Record; + CreationDate: string; Labels?: Record; - Type: ServiceType; + AllocateLoadBalancerNodePorts?: boolean; Ports?: Array; Selector?: Record; - ClusterIPs?: Array; IngressStatus?: Array; + Applications?: Application[]; + ClusterIPs?: Array; ExternalName?: string; ExternalIPs?: Array; - CreationDate: string; - Applications?: Application[]; - - IsSystem: boolean; }; diff --git a/app/react/kubernetes/services/useNamespaceServices.ts b/app/react/kubernetes/services/useNamespaceServices.ts new file mode 100644 index 000000000..5da0dcdd1 --- /dev/null +++ b/app/react/kubernetes/services/useNamespaceServices.ts @@ -0,0 +1,43 @@ +import { useQuery, UseQueryOptions } from '@tanstack/react-query'; + +import { EnvironmentId } from '@/react/portainer/environments/types'; +import { error as notifyError } from '@/portainer/services/notifications'; +import axios, { parseAxiosError } from '@/portainer/services/axios'; + +import { Service } from './types'; + +export function useNamespaceServices( + environmentId: EnvironmentId, + namespace: string, + queryOptions?: UseQueryOptions +) { + return useQuery({ + queryKey: [ + 'environments', + environmentId, + 'kubernetes', + 'namespaces', + namespace, + 'services', + ], + queryFn: () => getServices(environmentId, namespace), + onError: (err) => { + notifyError('Failure', err as Error, 'Unable to get services'); + }, + ...queryOptions, + }); +} + +export async function getServices( + environmentId: EnvironmentId, + namespace: string +) { + try { + const { data: services } = await axios.get( + `kubernetes/${environmentId}/namespaces/${namespace}/services` + ); + return services; + } catch (e) { + throw parseAxiosError(e as Error, 'Unable to retrieve services'); + } +} diff --git a/app/react/kubernetes/utils.ts b/app/react/kubernetes/utils.ts index 97805cf79..644debad0 100644 --- a/app/react/kubernetes/utils.ts +++ b/app/react/kubernetes/utils.ts @@ -13,7 +13,7 @@ export function parseCpu(cpu: string) { export function prepareAnnotations(annotations?: Annotation[]) { const result = annotations?.reduce( (acc, a) => { - acc[a.Key] = a.Value; + acc[a.key] = a.value; return acc; }, {} as Record diff --git a/app/react/kubernetes/volumes/ListView/types.ts b/app/react/kubernetes/volumes/ListView/types.ts index dd8b3efcf..64cde553b 100644 --- a/app/react/kubernetes/volumes/ListView/types.ts +++ b/app/react/kubernetes/volumes/ListView/types.ts @@ -10,7 +10,7 @@ export interface VolumeViewModel { storageClass: { Name: string; }; - Storage?: unknown; + Storage?: string | number; CreationDate?: string; ApplicationOwner?: string; IsExternal?: boolean; diff --git a/app/react/kubernetes/volumes/queries/useNamespaceVolumes.ts b/app/react/kubernetes/volumes/queries/useNamespaceVolumes.ts new file mode 100644 index 000000000..cdf6b6ee0 --- /dev/null +++ b/app/react/kubernetes/volumes/queries/useNamespaceVolumes.ts @@ -0,0 +1,51 @@ +import { useQuery } from '@tanstack/react-query'; + +import { EnvironmentId } from '@/react/portainer/environments/types'; +import { withGlobalError } from '@/react-tools/react-query'; +import axios, { parseAxiosError } from '@/portainer/services/axios'; + +import { K8sVolumeInfo } from '../types'; + +import { queryKeys } from './query-keys'; +import { convertToVolumeViewModels } from './useVolumesQuery'; + +// useQuery to get a list of all volumes in a cluster +export function useNamespaceVolumes( + environmentId: EnvironmentId, + namespace: string, + queryOptions?: { + refetchInterval?: number; + withApplications?: boolean; + } +) { + return useQuery( + queryKeys.volumes(environmentId), + () => + getNamespaceVolumes(environmentId, namespace, { + withApplications: queryOptions?.withApplications ?? false, + }), + { + enabled: !!namespace, + refetchInterval: queryOptions?.refetchInterval, + select: convertToVolumeViewModels, + ...withGlobalError('Unable to retrieve volumes'), + } + ); +} + +// get all volumes in a cluster +async function getNamespaceVolumes( + environmentId: EnvironmentId, + namespace: string, + params?: { withApplications: boolean } +) { + try { + const { data } = await axios.get( + `/kubernetes/${environmentId}/namespaces/${namespace}/volumes`, + { params } + ); + return data; + } catch (e) { + throw parseAxiosError(e, 'Unable to retrieve volumes'); + } +} diff --git a/app/react/kubernetes/volumes/queries/useVolumesQuery.ts b/app/react/kubernetes/volumes/queries/useVolumesQuery.ts index b70e2dc67..94b30345b 100644 --- a/app/react/kubernetes/volumes/queries/useVolumesQuery.ts +++ b/app/react/kubernetes/volumes/queries/useVolumesQuery.ts @@ -49,7 +49,7 @@ export function useAllStoragesQuery( ); } -// get all volumes from a namespace +// get all volumes in a cluster export async function getAllVolumes( environmentId: EnvironmentId, params?: { withApplications: boolean } @@ -65,7 +65,7 @@ export async function getAllVolumes( } } -function convertToVolumeViewModels( +export function convertToVolumeViewModels( volumes: K8sVolumeInfo[] ): VolumeViewModel[] { return volumes.map((volume) => { diff --git a/app/react/portainer/environments/environment.service/registries.ts b/app/react/portainer/environments/environment.service/registries.ts index 024fc1877..b176ec955 100644 --- a/app/react/portainer/environments/environment.service/registries.ts +++ b/app/react/portainer/environments/environment.service/registries.ts @@ -32,7 +32,7 @@ export async function updateEnvironmentRegistryAccess( try { await axios.put(buildRegistryUrl(environmentId, registryId), access); } catch (e) { - throw parseAxiosError(e as Error); + throw parseAxiosError(e); } } @@ -46,7 +46,7 @@ export async function getEnvironmentRegistries( }); return data; } catch (e) { - throw parseAxiosError(e as Error); + throw parseAxiosError(e); } } @@ -60,7 +60,7 @@ export async function getEnvironmentRegistry( ); return data; } catch (e) { - throw parseAxiosError(e as Error); + throw parseAxiosError(e); } } diff --git a/app/react/portainer/environments/types.ts b/app/react/portainer/environments/types.ts index 14dfd7624..e9dc5aa25 100644 --- a/app/react/portainer/environments/types.ts +++ b/app/react/portainer/environments/types.ts @@ -56,6 +56,8 @@ export interface KubernetesSnapshot { export type IngressClass = { Name: string; Type: string; + Blocked?: boolean; + BlockedNamespaces?: string[] | null; }; export interface StorageClass { @@ -82,6 +84,11 @@ export interface KubernetesConfiguration { export interface KubernetesSettings { Snapshots?: KubernetesSnapshot[] | null; Configuration: KubernetesConfiguration; + Flags: { + IsServerMetricsDetected: boolean; + IsServerIngressClassDetected: boolean; + IsServerStorageDetected: boolean; + }; } export type EnvironmentEdge = { @@ -153,11 +160,21 @@ export type Environment = { Snapshots: DockerSnapshot[]; Kubernetes: KubernetesSettings; PublicURL?: string; - UserTrusted: boolean; + UserTrusted?: boolean; AMTDeviceGUID?: string; Edge: EnvironmentEdge; SecuritySettings: EnvironmentSecuritySettings; Gpus?: { name: string; value: string }[]; + TLSConfig?: { + TLS: boolean; + TLSSkipVerify: boolean; + }; + AzureCredentials?: { + ApplicationID: string; + TenantID: string; + AuthenticationKey: string; + }; + ComposeSyntaxMaxVersion: string; EnableImageNotification: boolean; LocalTimeZone?: string; diff --git a/app/react/portainer/registries/types/registry.ts b/app/react/portainer/registries/types/registry.ts index 37b0a175a..34c6d2e09 100644 --- a/app/react/portainer/registries/types/registry.ts +++ b/app/react/portainer/registries/types/registry.ts @@ -21,8 +21,8 @@ export enum RegistryTypes { } export interface RegistryAccess { - UserAccessPolicies: UserAccessPolicies; - TeamAccessPolicies: TeamAccessPolicies; + UserAccessPolicies: UserAccessPolicies | null; + TeamAccessPolicies: TeamAccessPolicies | null; Namespaces: string[]; } @@ -37,7 +37,7 @@ export interface Gitlab { } export interface Quay { - UseOrganisation: boolean; + UseOrganisation?: boolean; OrganisationName: string; } @@ -71,7 +71,7 @@ export interface Registry { Authentication: boolean; Username: string; Password?: string; - RegistryAccesses: RegistryAccesses; + RegistryAccesses: RegistryAccesses | null; Gitlab: Gitlab; Quay: Quay; Github: Github;