Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: implement node label management with system and user label separation (#2479)
Lewis Englandfba1093882f3
diff --git a/backend/pkg/utils/cookie/cookie_util.go b/backend/pkg/utils/cookie/cookie_util.goindex e22e1126f..9347eda4d 100644--- a/backend/pkg/utils/cookie/cookie_util.go+++ b/backend/pkg/utils/cookie/cookie_util.go@@ -43,7 +43,7 @@ func BuildTokenCookieString(maxAgeInSeconds int, token string) string {if maxAgeInSeconds < 0 {maxAgeInSeconds = 0}- cookie := &http.Cookie{+ cookie := &http.Cookie{ // #nosec G124Name: InsecureTokenCookieName,Value: token,Path: "/",@@ -56,7 +56,7 @@ func BuildTokenCookieString(maxAgeInSeconds int, token string) string {// BuildClearTokenCookieString builds a Set-Cookie header string to clear the token cookie.func BuildClearTokenCookieString() string {- cookie := &http.Cookie{+ cookie := &http.Cookie{ // #nosec G124Name: InsecureTokenCookieName,Value: "",Path: "/",@@ -72,7 +72,7 @@ func BuildOidcStateCookieString(value string, maxAgeInSeconds int, secure bool)if maxAgeInSeconds < 0 {maxAgeInSeconds = 0}- cookie := &http.Cookie{+ cookie := &http.Cookie{ // #nosec G124Name: OidcStateCookieName,Value: value,Path: "/",@@ -86,7 +86,7 @@ func BuildOidcStateCookieString(value string, maxAgeInSeconds int, secure bool)// BuildClearOidcStateCookieString builds a Set-Cookie header string to clear the OIDC state cookie.func BuildClearOidcStateCookieString(secure bool) string {- cookie := &http.Cookie{+ cookie := &http.Cookie{ // #nosec G124Name: OidcStateCookieName,Value: "",Path: "/",diff --git a/frontend/src/lib/types/swarm.type.ts b/frontend/src/lib/types/swarm.type.tsindex 8ecd4de0e..6f9ac0249 100644--- a/frontend/src/lib/types/swarm.type.ts+++ b/frontend/src/lib/types/swarm.type.ts@@ -252,6 +252,7 @@ export interface SwarmNodeSummary {managerStatus?: string | null;reachability?: string | null;labels?: Record<string, string> | null;+ systemLabels?: Record<string, string> | null;engineVersion?: string | null;platform?: string | null;createdAt: string;diff --git a/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte b/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelteindex 4d53462be..134d65a5c 100644--- a/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte+++ b/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte@@ -2,7 +2,17 @@import ArcaneTable from '$lib/components/arcane-table/arcane-table.svelte';import type { ColumnSpec, MobileFieldVisibility } from '$lib/components/arcane-table';import { UniversalMobileCard } from '$lib/components/arcane-table';- import { UsersIcon, EnvironmentsIcon, EllipsisIcon, InspectIcon, TrashIcon, EdgeConnectionIcon } from '$lib/icons';+ import {+ UsersIcon,+ EnvironmentsIcon,+ EllipsisIcon,+ InspectIcon,+ TrashIcon,+ EdgeConnectionIcon,+ AddIcon,+ CloseIcon,+ TagIcon+ } from '$lib/icons';import { m } from '$lib/paraglide/messages';import { swarmService } from '$lib/services/swarm-service';import type { SwarmNodeAgentDeployment, SwarmNodeSummary } from '$lib/types/swarm.type';@@ -19,6 +29,7 @@import userStore from '$lib/stores/user-store';import { fromStore } from 'svelte/store';import SwarmNodeAgentDialog from './swarm-node-agent-dialog.svelte';+ import SwarmNodeLabelDialog from './swarm-node-label-dialog.svelte';import { getSwarmNodeAgentActionLabel, getSwarmNodeAgentLabel, getSwarmNodeAgentVariant } from './agent-status';let {@@ -37,6 +48,8 @@let agentDeploymentError = $state('');let agentDeployment = $state<SwarmNodeAgentDeployment | null>(null);let isAgentDeploymentLoading = $state(false);+ let isAddLabelDialogOpen = $state(false);+ let nodeToLabel = $state<SwarmNodeSummary | null>(null);function statusVariant(state: string): 'green' | 'red' | 'amber' | 'gray' {if (state === 'ready') return 'green';@@ -116,7 +129,7 @@}async function mutateNode(action: () => Promise<void>, successMessage: string, failureMessage: string) {- handleApiResultWithCallbacks({+ await handleApiResultWithCallbacks({result: await tryCatch(action()),message: failureMessage,setLoadingState: (v) => (isLoading = v),@@ -127,24 +140,24 @@});}- function setAvailability(node: SwarmNodeSummary, availability: 'active' | 'pause' | 'drain') {- mutateNode(+ async function setAvailability(node: SwarmNodeSummary, availability: 'active' | 'pause' | 'drain') {+ await mutateNode(() => swarmService.updateNode(node.id, { availability }),- m.swarm_node_availability_update_success({ name: node.hostname, availability }),+ m.common_update_success({ resource: m.swarm_node() }),m.swarm_node_update_failed({ name: node.hostname }));}- function promoteNode(node: SwarmNodeSummary) {- mutateNode(+ async function promoteNode(node: SwarmNodeSummary) {+ await mutateNode(() => swarmService.promoteNode(node.id),m.swarm_node_promote_success({ name: node.hostname }),m.swarm_node_promote_failed({ name: node.hostname }));}- function demoteNode(node: SwarmNodeSummary) {- mutateNode(+ async function demoteNode(node: SwarmNodeSummary) {+ await mutateNode(() => swarmService.demoteNode(node.id),m.swarm_node_demote_success({ name: node.hostname }),m.swarm_node_demote_failed({ name: node.hostname })@@ -169,12 +182,48 @@});}+ function openAddLabelDialog(node: SwarmNodeSummary) {+ nodeToLabel = node;+ isAddLabelDialogOpen = true;+ }++ async function addLabel(key: string, value: string) {+ if (!nodeToLabel) return;+ const labels = { ...(nodeToLabel.labels ?? {}), [key]: value };+ await mutateNode(+ () => swarmService.updateNode(nodeToLabel!.id, { labels }),+ m.common_update_success({ resource: m.swarm_node() }),+ m.swarm_node_update_failed({ name: nodeToLabel.hostname })+ );+ }++ function removeLabel(node: SwarmNodeSummary, key: string) {+ openConfirmDialog({+ title: m.common_remove_title({ resource: `label "${key}"` }),+ message: m.common_remove_confirm({ resource: `label "${key}"` }),+ confirm: {+ label: m.common_remove(),+ destructive: true,+ action: async () => {+ const labels = { ...(node.labels ?? {}) };+ delete labels[key];+ await mutateNode(+ () => swarmService.updateNode(node.id, { labels }),+ m.common_update_success({ resource: m.swarm_node() }),+ m.swarm_node_update_failed({ name: node.hostname })+ );+ }+ }+ });+ }+const columns = [{ accessorKey: 'id', title: m.common_id(), hidden: true },{ accessorKey: 'hostname', title: m.swarm_hostname(), sortable: true },{ accessorKey: 'role', title: m.common_role(), sortable: true, cell: RoleCell },{ accessorKey: 'status', title: m.common_status(), sortable: true, cell: StatusCell },{ accessorKey: 'availability', title: m.swarm_availability(), sortable: true, cell: AvailabilityCell },+ { accessorKey: 'labels', title: m.common_labels(), cell: LabelsCell },{id: 'agent',title: m.swarm_node_agent_column(),@@ -188,6 +237,7 @@{ id: 'role', label: m.common_role(), defaultVisible: true },{ id: 'status', label: m.common_status(), defaultVisible: true },{ id: 'availability', label: m.swarm_availability(), defaultVisible: true },+ { id: 'labels', label: m.common_labels(), defaultVisible: true },{ id: 'agent', label: m.swarm_node_agent_column(), defaultVisible: true },{ id: 'engineVersion', label: m.swarm_engine_version(), defaultVisible: false }];@@ -214,6 +264,41 @@/>{/snippet}+{#snippet LabelsCell({ item }: { item: SwarmNodeSummary })}+ <div class="flex flex-wrap items-center gap-1.5">+ {#each Object.entries(item.systemLabels ?? {}) as [key, value] (key)}+ <div class="group relative overflow-hidden rounded-[var(--radius)]">+ <StatusBadge text={`${key}${value ? `=${value}` : ''}`} variant="gray" minWidth="none" class="max-w-[200px] truncate" />+ </div>+ {/each}+ {#each Object.entries(item.labels ?? {}) as [key, value] (key)}+ <div class="group relative overflow-hidden rounded-[var(--radius)]">+ <StatusBadge text={`${key}${value ? `=${value}` : ''}`} variant="blue" minWidth="none" class="max-w-[200px] truncate" />+ {#if isAdmin}+ <button+ class="absolute inset-0 flex cursor-pointer items-center justify-end rounded-[var(--radius)] bg-blue-500/10 pr-1 opacity-0 backdrop-blur-[1px] transition-opacity group-hover:opacity-100 dark:bg-blue-400/20"+ onclick={() => removeLabel(item, key)}+ title={m.common_remove()}+ >+ <div class="scale-90 rounded-full bg-red-500 p-0.5 shadow-lg transition-transform group-hover:scale-100">+ <CloseIcon class="size-3 text-white" />+ </div>+ </button>+ {/if}+ </div>+ {/each}+ {#if isAdmin}+ <button+ class="border-border hover:border-primary hover:text-primary inline-flex items-center gap-1 rounded border border-dashed px-2 py-0.5 text-[11px] font-medium transition-colors"+ onclick={() => openAddLabelDialog(item)}+ >+ <AddIcon class="size-3" />+ {m.common_add_button({ resource: 'Label' })}+ </button>+ {/if}+ </div>+{/snippet}+{#snippet NodeMobileCardSnippet({item,mobileFieldVisibility@@ -255,6 +340,14 @@iconVariant: 'gray' as const,show: mobileFieldVisibility.availability ?? true},+ {+ label: m.common_labels(),+ getValue: (item: SwarmNodeSummary) =>+ `${Object.keys(item.labels ?? {}).length + Object.keys(item.systemLabels ?? {}).length} labels`,+ icon: TagIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility.labels ?? true+ },{label: m.swarm_node_agent_column(),getValue: (item: SwarmNodeSummary) => getSwarmNodeAgentLabel(item.agent?.state),@@ -338,3 +431,5 @@onRefresh={refreshAgentDeployment}onRegenerate={regenerateAgentDeployment}/>++<SwarmNodeLabelDialog bind:open={isAddLabelDialogOpen} onAdd={addLabel} />diff --git a/frontend/src/routes/(app)/swarm/nodes/swarm-node-label-dialog.svelte b/frontend/src/routes/(app)/swarm/nodes/swarm-node-label-dialog.sveltenew file mode 100644index 000000000..1888471e5--- /dev/null+++ b/frontend/src/routes/(app)/swarm/nodes/swarm-node-label-dialog.svelte@@ -0,0 +1,84 @@+<script lang="ts">+ import { ArcaneButton } from '$lib/components/arcane-button';+ import * as ResponsiveDialog from '$lib/components/ui/responsive-dialog';+ import { Input } from '$lib/components/ui/input';+ import { Label } from '$lib/components/ui/label';+ import { m } from '$lib/paraglide/messages';+ import { toast } from 'svelte-sonner';+ import { extractApiErrorMessage } from '$lib/utils/api.util';++ type SwarmNodeLabelDialogProps = {+ open: boolean;+ onAdd: (key: string, value: string) => void | Promise<void>;+ };++ let { open = $bindable(false), onAdd }: SwarmNodeLabelDialogProps = $props();++ let key = $state('');+ let value = $state('');+ let isSubmitting = $state(false);++ const isReservedPrefix = $derived(key.trim().startsWith('engine.labels') || key.trim().startsWith('com.docker.swarm'));++ async function handleSubmit(e?: Event) {+ e?.preventDefault();+ if (!key.trim() || isReservedPrefix) return;+ isSubmitting = true;+ try {+ await onAdd(key.trim(), value.trim());+ handleCancel();+ } catch (err) {+ toast.error(m.common_update_failed({ name: m.common_labels() }) + ': ' + extractApiErrorMessage(err));+ } finally {+ isSubmitting = false;+ }+ }++ function handleCancel() {+ open = false;+ key = '';+ value = '';+ }+</script>++<ResponsiveDialog.Root+ bind:open+ title={m.swarm_service_form_add_label()}+ description={m.common_labels_description({ resource: m.swarm_node() })}+>+ <form onsubmit={handleSubmit} class="space-y-4 px-6 py-4">+ <div class="space-y-2">+ <Label for="label-key" class={isReservedPrefix ? 'text-red-500' : ''}>Key</Label>+ <Input+ id="label-key"+ bind:value={key}+ placeholder={m.swarm_service_form_key_placeholder()}+ required+ class={isReservedPrefix ? 'border-red-500 focus-visible:ring-red-500' : ''}+ />+ {#if isReservedPrefix}+ <p class="text-[11px] font-medium text-red-500">+ Prefixes 'engine.labels' and 'com.docker.swarm' are reserved for system use.+ </p>+ {/if}+ </div>+ <div class="space-y-2">+ <Label for="label-value">Value</Label>+ <Input id="label-value" bind:value placeholder={m.swarm_service_form_value_placeholder()} />+ </div>+ <button type="submit" class="hidden"></button>+ </form>++ {#snippet footer()}+ <div class="flex w-full flex-col gap-2 px-6 pb-6 sm:flex-row sm:justify-end">+ <ArcaneButton action="base" tone="outline" customLabel={m.common_cancel()} onclick={handleCancel} disabled={isSubmitting} />+ <ArcaneButton+ action="base"+ customLabel={m.common_add_button({ resource: m.common_labels() })}+ onclick={handleSubmit}+ loading={isSubmitting}+ disabled={!key.trim() || isReservedPrefix || isSubmitting}+ />+ </div>+ {/snippet}+</ResponsiveDialog.Root>diff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex c0462618e..3a1436639 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -25,6 +25,7 @@ export default defineConfig({target: 'es2022'},server: {+ allowedHosts: ['arcane-frontend-dev'],host: process.env['HOST'],proxy: {'/api': {diff --git a/types/swarm/node.go b/types/swarm/node.goindex f9b6f787a..286219cb4 100644--- a/types/swarm/node.go+++ b/types/swarm/node.go@@ -68,11 +68,16 @@ type NodeSummary struct {// Required: falseReachability string `json:"reachability,omitempty"`- // Labels contains node labels.+ // Labels contains user-defined node labels from the node spec.//// Required: falseLabels map[string]string `json:"labels,omitempty"`+ // SystemLabels contains read-only engine labels.+ //+ // Required: false+ SystemLabels map[string]string `json:"systemLabels,omitempty"`+// EngineVersion is the Docker engine version.//// Required: false@@ -162,6 +167,7 @@ func NewNodeSummary(node swarm.Node) NodeSummary {ManagerStatus: managerStatus,Reachability: reachability,Labels: node.Spec.Labels,+ SystemLabels: node.Description.Engine.Labels,EngineVersion: node.Description.Engine.EngineVersion,Platform: platform,CreatedAt: node.CreatedAt,