Skip to content

SeaweedFS is a distributed storage system for object storage (S3), file systems, Iceberg table buckets, and Lance vector buckets, designed to handle billions of files with O(1) disk access and effortless horizontal scaling.

Batch volume balance: run multiple moves per job (#8561)

Chris Lu5f85bf5e8acd
diff --git a/test/plugin_workers/fake_volume_server.go b/test/plugin_workers/fake_volume_server.go
index 9229537598..5ad35edff6 100644
--- a/test/plugin_workers/fake_volume_server.go
+++ b/test/plugin_workers/fake_volume_server.go
@@ -27,19 +27,21 @@ type VolumeServer struct {
address string
baseDir string
- mu sync.Mutex
- receivedFiles map[string]uint64
- mountRequests []*volume_server_pb.VolumeEcShardsMountRequest
- deleteRequests []*volume_server_pb.VolumeDeleteRequest
- markReadonlyCalls int
- vacuumGarbageRatio float64
- vacuumCheckCalls int
- vacuumCompactCalls int
- vacuumCommitCalls int
- vacuumCleanupCalls int
- volumeCopyCalls int
- volumeMountCalls int
- tailReceiverCalls int
+ mu sync.Mutex
+ receivedFiles map[string]uint64
+ mountRequests []*volume_server_pb.VolumeEcShardsMountRequest
+ deleteRequests []*volume_server_pb.VolumeDeleteRequest
+ markReadonlyCalls int
+ markWritableCalls int
+ readFileStatusCalls int
+ vacuumGarbageRatio float64
+ vacuumCheckCalls int
+ vacuumCompactCalls int
+ vacuumCommitCalls int
+ vacuumCleanupCalls int
+ volumeCopyCalls int
+ volumeMountCalls int
+ tailReceiverCalls int
}
// NewVolumeServer starts a test volume server using the provided base directory.
@@ -151,6 +153,20 @@ func (v *VolumeServer) MarkReadonlyCount() int {
return v.markReadonlyCalls
}
+// MarkWritableCount returns the number of writable calls.
+func (v *VolumeServer) MarkWritableCount() int {
+ v.mu.Lock()
+ defer v.mu.Unlock()
+ return v.markWritableCalls
+}
+
+// ReadFileStatusCount returns the number of ReadVolumeFileStatus calls.
+func (v *VolumeServer) ReadFileStatusCount() int {
+ v.mu.Lock()
+ defer v.mu.Unlock()
+ return v.readFileStatusCalls
+}
+
// Shutdown stops the volume server.
func (v *VolumeServer) Shutdown() {
if v.server != nil {
@@ -280,6 +296,25 @@ func (v *VolumeServer) VolumeMarkReadonly(ctx context.Context, req *volume_serve
return &volume_server_pb.VolumeMarkReadonlyResponse{}, nil
}
+func (v *VolumeServer) VolumeMarkWritable(ctx context.Context, req *volume_server_pb.VolumeMarkWritableRequest) (*volume_server_pb.VolumeMarkWritableResponse, error) {
+ v.mu.Lock()
+ v.markWritableCalls++
+ v.mu.Unlock()
+ return &volume_server_pb.VolumeMarkWritableResponse{}, nil
+}
+
+func (v *VolumeServer) ReadVolumeFileStatus(ctx context.Context, req *volume_server_pb.ReadVolumeFileStatusRequest) (*volume_server_pb.ReadVolumeFileStatusResponse, error) {
+ v.mu.Lock()
+ v.readFileStatusCalls++
+ v.mu.Unlock()
+ return &volume_server_pb.ReadVolumeFileStatusResponse{
+ VolumeId: req.VolumeId,
+ DatFileSize: 1024,
+ IdxFileSize: 16,
+ FileCount: 1,
+ }, nil
+}
+
func (v *VolumeServer) VacuumVolumeCheck(ctx context.Context, req *volume_server_pb.VacuumVolumeCheckRequest) (*volume_server_pb.VacuumVolumeCheckResponse, error) {
v.mu.Lock()
v.vacuumCheckCalls++
diff --git a/test/plugin_workers/volume_balance/detection_test.go b/test/plugin_workers/volume_balance/detection_test.go
index 0aa7e3a37e..dd3b3dd9f8 100644
--- a/test/plugin_workers/volume_balance/detection_test.go
+++ b/test/plugin_workers/volume_balance/detection_test.go
@@ -37,19 +37,25 @@ func TestVolumeBalanceDetectionIntegration(t *testing.T) {
MasterGrpcAddresses: []string{master.Address()},
}, 10)
require.NoError(t, err)
- // With 10 volumes on one server and 1 on the other (avg=5.5),
- // multiple balance moves should be detected until imbalance is within threshold.
- require.Greater(t, len(proposals), 1, "expected multiple balance proposals")
-
- for _, proposal := range proposals {
- require.Equal(t, "volume_balance", proposal.JobType)
- paramsValue := proposal.Parameters["task_params_pb"]
- require.NotNil(t, paramsValue)
-
- params := &worker_pb.TaskParams{}
- require.NoError(t, proto.Unmarshal(paramsValue.GetBytesValue(), params))
- require.NotEmpty(t, params.Sources)
- require.NotEmpty(t, params.Targets)
+ // With default batch_size=20 and 10 overloaded volumes vs 1 underloaded,
+ // all moves are grouped into a single batch proposal.
+ require.Len(t, proposals, 1, "expected exactly one batch proposal")
+
+ proposal := proposals[0]
+ require.Equal(t, "volume_balance", proposal.JobType)
+ paramsValue := proposal.Parameters["task_params_pb"]
+ require.NotNil(t, paramsValue)
+
+ params := &worker_pb.TaskParams{}
+ require.NoError(t, proto.Unmarshal(paramsValue.GetBytesValue(), params))
+
+ bp := params.GetBalanceParams()
+ require.NotNil(t, bp, "expected BalanceParams in batch proposal")
+ require.Greater(t, len(bp.Moves), 1, "batch proposal should contain multiple moves")
+ for _, move := range bp.Moves {
+ require.NotZero(t, move.VolumeId)
+ require.NotEmpty(t, move.SourceNode)
+ require.NotEmpty(t, move.TargetNode)
}
}
diff --git a/test/plugin_workers/volume_balance/execution_test.go b/test/plugin_workers/volume_balance/execution_test.go
index 0d2091fc69..e7c13154b2 100644
--- a/test/plugin_workers/volume_balance/execution_test.go
+++ b/test/plugin_workers/volume_balance/execution_test.go
@@ -8,10 +8,12 @@ import (
pluginworkers "github.com/seaweedfs/seaweedfs/test/plugin_workers"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
+ "github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
pluginworker "github.com/seaweedfs/seaweedfs/weed/plugin/worker"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
+ "google.golang.org/protobuf/proto"
)
func TestVolumeBalanceExecutionIntegration(t *testing.T) {
@@ -60,8 +62,85 @@ func TestVolumeBalanceExecutionIntegration(t *testing.T) {
require.GreaterOrEqual(t, source.MarkReadonlyCount(), 1)
require.GreaterOrEqual(t, len(source.DeleteRequests()), 1)
- copyCalls, mountCalls, tailCalls := target.BalanceStats()
+ copyCalls, _, tailCalls := target.BalanceStats()
require.GreaterOrEqual(t, copyCalls, 1)
- require.GreaterOrEqual(t, mountCalls, 1)
require.GreaterOrEqual(t, tailCalls, 1)
}
+
+func TestVolumeBalanceBatchExecutionIntegration(t *testing.T) {
+ dialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
+ handler := pluginworker.NewVolumeBalanceHandler(dialOption)
+ harness := pluginworkers.NewHarness(t, pluginworkers.HarnessConfig{
+ WorkerOptions: pluginworker.WorkerOptions{
+ GrpcDialOption: dialOption,
+ },
+ Handlers: []pluginworker.JobHandler{handler},
+ })
+ harness.WaitForJobType("volume_balance")
+
+ // Create one source and one target fake volume server.
+ source := pluginworkers.NewVolumeServer(t, "")
+ target := pluginworkers.NewVolumeServer(t, "")
+
+ // Build a batch job with 3 volume moves from source → target.
+ volumeIDs := []uint32{401, 402, 403}
+ moves := make([]*worker_pb.BalanceMoveSpec, len(volumeIDs))
+ for i, vid := range volumeIDs {
+ moves[i] = &worker_pb.BalanceMoveSpec{
+ VolumeId: vid,
+ SourceNode: source.Address(),
+ TargetNode: target.Address(),
+ Collection: "batch-test",
+ }
+ }
+
+ params := &worker_pb.TaskParams{
+ TaskId: "batch-balance-test",
+ TaskParams: &worker_pb.TaskParams_BalanceParams{
+ BalanceParams: &worker_pb.BalanceTaskParams{
+ MaxConcurrentMoves: 2,
+ Moves: moves,
+ },
+ },
+ }
+ paramBytes, err := proto.Marshal(params)
+ require.NoError(t, err)
+
+ job := &plugin_pb.JobSpec{
+ JobId: "batch-balance-test",
+ JobType: "volume_balance",
+ Parameters: map[string]*plugin_pb.ConfigValue{
+ "task_params_pb": {
+ Kind: &plugin_pb.ConfigValue_BytesValue{BytesValue: paramBytes},
+ },
+ },
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ result, err := harness.Plugin().ExecuteJob(ctx, job, nil, 1)
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.True(t, result.Success, "batch balance job should succeed; result: %+v", result)
+
+ // Each of the 3 moves should have marked the source readonly and deleted.
+ require.Equal(t, len(volumeIDs), source.MarkReadonlyCount(),
+ "each move should mark source volume readonly")
+ require.Equal(t, len(volumeIDs), len(source.DeleteRequests()),
+ "each move should delete the source volume")
+
+ // Verify delete requests reference the expected volume IDs.
+ deletedVols := make(map[uint32]bool)
+ for _, req := range source.DeleteRequests() {
+ deletedVols[req.VolumeId] = true
+ }
+ for _, vid := range volumeIDs {
+ require.True(t, deletedVols[vid], "volume %d should have been deleted from source", vid)
+ }
+
+ // Target should have received copy and tail calls for all 3 volumes.
+ copyCalls, _, tailCalls := target.BalanceStats()
+ require.Equal(t, len(volumeIDs), copyCalls, "target should receive one copy per volume")
+ require.Equal(t, len(volumeIDs), tailCalls, "target should receive one tail per volume")
+}
diff --git a/weed/admin/view/app/plugin.templ b/weed/admin/view/app/plugin.templ
index 2b9e8fe273..2ccd6705cb 100644
--- a/weed/admin/view/app/plugin.templ
+++ b/weed/admin/view/app/plugin.templ
@@ -1026,6 +1026,9 @@ templ Plugin(page string) {
}
var jobType = String(plan.job_type || '').trim().toLowerCase();
+ if (jobType === 'volume_balance') {
+ return renderBalanceExecutionPlan(plan);
+ }
if (jobType !== 'erasure_coding') {
var fallbackText = toPrettyJson(plan);
if (!fallbackText) {
@@ -1107,6 +1110,44 @@ templ Plugin(page string) {
return html;
}
+ function renderBalanceExecutionPlan(plan) {
+ var html = '<div class="mb-3"><h6>Execution Plan</h6>';
+ var moves = Array.isArray(plan.moves) ? plan.moves : [];
+
+ if (moves.length === 0) {
+ // Single-move balance job
+ var src = textOrDash(plan.source_node || plan.source_server);
+ var dst = textOrDash(plan.target_node || plan.target_server);
+ var vid = textOrDash(plan.volume_id);
+ var col = textOrDash(plan.collection);
+ html += `<div class="row g-2 mb-2">
+ <div class="col-md-3"><small><strong>Volume:</strong> ${escapeHtml(vid)}</small></div>
+ <div class="col-md-3"><small><strong>Collection:</strong> ${escapeHtml(col)}</small></div>
+ <div class="col-md-3"><small><strong>Source:</strong> <code>${escapeHtml(src)}</code></small></div>
+ <div class="col-md-3"><small><strong>Target:</strong> <code>${escapeHtml(dst)}</code></small></div>
+ </div>`;
+ } else {
+ // Batch balance job
+ html += '<div class="mb-2"><span class="badge bg-info">' + escapeHtml(String(moves.length)) + ' moves</span></div>';
+ html += '<div class="table-responsive"><table class="table table-sm table-striped mb-0">' +
+ '<thead><tr><th>#</th><th>Volume</th><th>Source</th><th>Target</th><th>Collection</th></tr></thead><tbody>';
+ for (var i = 0; i < moves.length; i++) {
+ var move = moves[i] || {};
+ html += `<tr>
+ <td>${escapeHtml(String(i + 1))}</td>
+ <td>${escapeHtml(textOrDash(move.volume_id))}</td>
+ <td><code>${escapeHtml(textOrDash(move.source_node))}</code></td>
+ <td><code>${escapeHtml(textOrDash(move.target_node))}</code></td>
+ <td>${escapeHtml(textOrDash(move.collection))}</td>
+ </tr>`;
+ }
+ html += '</tbody></table></div>';
+ }
+
+ html += '</div>';
+ return html;
+ }
+
function isActiveJobState(candidateState) {
var jobState = candidateState;
if (candidateState && typeof candidateState === 'object' && candidateState.state !== undefined) {
@@ -1676,9 +1717,15 @@ templ Plugin(page string) {
barClass = 'bg-warning';
}
+ var jobTypeCell = escapeHtml(textOrDash(executionJob.job_type));
+ var execLabels = executionJob.labels || {};
+ if (execLabels.batch === 'true' && execLabels.batch_size) {
+ jobTypeCell += ' <span class="badge bg-info">' + escapeHtml(execLabels.batch_size) + ' moves</span>';
+ }
+
rows += '<tr>' +
'<td>' + renderJobLink(executionJob.job_id) + '</td>' +
- '<td>' + escapeHtml(textOrDash(executionJob.job_type)) + '</td>' +
+ '<td>' + jobTypeCell + '</td>' +
'<td><span class="badge bg-light text-dark">' + escapeHtml(textOrDash(executionJob.state)) + '</span></td>' +
'<td class="plugin-job-progress"><div class="progress" style="height: 14px;"><div class="progress-bar ' + barClass + '" role="progressbar" style="width:' + progress + '%">' + Math.round(progress) + '%</div></div></td>' +
'<td><small>' + escapeHtml(textOrDash(executionJob.worker_id)) + '</small></td>' +
diff --git a/weed/admin/view/app/plugin_templ.go b/weed/admin/view/app/plugin_templ.go
index cd9ae58d2f..c43d040789 100644
--- a/weed/admin/view/app/plugin_templ.go
+++ b/weed/admin/view/app/plugin_templ.go
@@ -46,7 +46,7 @@ func Plugin(page string) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "\"><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"d-flex justify-content-between align-items-center flex-wrap gap-2\"><div><h2 class=\"mb-0\"><i class=\"fas fa-plug me-2\"></i>Workers</h2><p class=\"text-muted mb-0\">Cluster-wide worker status, per-job configuration, detection, queue, and execution workflows.</p></div><div class=\"btn-group\"><button type=\"button\" class=\"btn btn-outline-secondary\" id=\"plugin-refresh-all-btn\"><i class=\"fas fa-sync-alt me-1\"></i>Refresh</button></div></div></div></div><div class=\"row mb-3\"><div class=\"col-12\"><ul class=\"nav nav-tabs\" id=\"plugin-top-tabs\"><li class=\"nav-item\"><button type=\"button\" class=\"nav-link active\" data-plugin-top-tab=\"overview\"><i class=\"fas fa-chart-line me-1\"></i>Overview</button></li></ul></div></div><div class=\"row mb-3 d-none\" id=\"plugin-subtab-row\"><div class=\"col-12\"><ul class=\"nav nav-pills gap-2\" id=\"plugin-subtabs\"><li class=\"nav-item\"><button type=\"button\" class=\"nav-link active\" data-plugin-subtab=\"configuration\"><i class=\"fas fa-sliders-h me-1\"></i>Configuration</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"detection\"><i class=\"fas fa-search me-1\"></i>Job Detection</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"queue\"><i class=\"fas fa-list me-1\"></i>Job Queue</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"execution\"><i class=\"fas fa-tasks me-1\"></i>Job Execution</button></li></ul></div></div><div class=\"plugin-section plugin-section-overview\"><div class=\"row mb-4\"><div class=\"col-md-3 mb-3\"><div class=\"card border-info h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Workers</div><h4 class=\"mb-0\" id=\"plugin-status-workers\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-warning h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Active Jobs</div><h4 class=\"mb-0\" id=\"plugin-status-active-jobs\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-success h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Activities (recent)</div><h4 class=\"mb-0\" id=\"plugin-status-activities\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-secondary h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Next Run</div><h4 class=\"mb-0 plugin-scheduler-next-run\">-</h4><div class=\"text-muted small plugin-scheduler-next-run-meta\"></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"fas fa-chart-bar me-2\"></i>Per Job Type Summary</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Active Jobs</th><th>Recent Activities</th></tr></thead> <tbody id=\"plugin-jobtype-summary-body\"><tr><td colspan=\"3\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"fas fa-clock me-2\"></i>Scheduler State</h5><small class=\"text-muted\">Sequential scheduler with per-job runtime limits</small></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Enabled</th><th>Detector</th><th>In Flight</th><th>Max Runtime</th><th>Exec Global</th><th>Exec/Worker</th><th>Executor Workers</th><th>Effective Exec</th><th>Last Run</th></tr></thead> <tbody id=\"plugin-scheduler-table-body\"><tr><td colspan=\"10\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"fas fa-users me-2\"></i>Workers</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\" style=\"max-height: 560px; overflow-y: auto;\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light sticky-top\"><tr><th>Worker</th><th>Address</th><th>Capabilities</th><th>Load</th></tr></thead> <tbody id=\"plugin-workers-table-body\"><tr><td colspan=\"4\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div></div><div class=\"plugin-section plugin-section-configuration\"><div class=\"row mb-4\"><div class=\"col-lg-8 mb-3\"><div class=\"card shadow-sm h-100\"><div class=\"card-header d-flex justify-content-between align-items-center\"><h5 class=\"mb-0\"><i class=\"fas fa-sliders-h me-2\"></i>Job Type Configuration</h5><small class=\"text-muted\" id=\"plugin-config-updated-at\">Not loaded</small></div><div class=\"card-body\"><div class=\"mb-3\"><div class=\"small text-muted\">Selected Job Type</div><div class=\"fw-semibold\" id=\"plugin-selected-job-type\">-</div></div><div class=\"mb-3\"><div class=\"d-flex justify-content-between align-items-center mb-2\"><h6 class=\"mb-0\">Descriptor</h6><button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" id=\"plugin-refresh-schema-btn\"><i class=\"fas fa-cloud-download-alt me-1\"></i>Refresh Schema</button></div><div class=\"alert alert-light border\" id=\"plugin-descriptor-summary\">Select a job type to load schema and config.</div></div><div class=\"mb-3\"><h6>Admin Config Form</h6><div id=\"plugin-admin-config-form\" class=\"plugin-form-root\"><div class=\"text-muted\">No admin form loaded.</div></div></div><div class=\"mb-3\"><h6>Worker Config Form</h6><div id=\"plugin-worker-config-form\" class=\"plugin-form-root\"><div class=\"text-muted\">No worker form loaded.</div></div></div><div class=\"d-flex flex-wrap gap-2\"><button type=\"button\" class=\"btn btn-primary\" id=\"plugin-save-config-btn\"><i class=\"fas fa-save me-1\"></i>Save Config</button> <button type=\"button\" class=\"btn btn-outline-primary\" id=\"plugin-trigger-detection-btn\"><i class=\"fas fa-search me-1\"></i>Run Detection</button> <button type=\"button\" class=\"btn btn-outline-success\" id=\"plugin-run-workflow-btn\"><i class=\"fas fa-play me-1\"></i>Run Detect + Execute</button></div></div></div></div><div class=\"col-lg-4 mb-3\"><div class=\"card shadow-sm h-100\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"fas fa-cogs me-2\"></i>Job Scheduling Settings</h5></div><div class=\"card-body\"><div class=\"row g-2\" id=\"plugin-admin-settings-form\"><div class=\"col-12\"><label class=\"form-label\" for=\"plugin-admin-enabled\">Enabled</label><div class=\"form-check form-switch mt-1\"><input class=\"form-check-input\" type=\"checkbox\" id=\"plugin-admin-enabled\"></div></div><div class=\"col-12\"><label class=\"form-label\" for=\"plugin-admin-detection-interval\">Detection Interval (s)</label> <input type=\"number\" class=\"form-control\" id=\"plugin-admin-detection-interval\" min=\"0\"><div class=\"form-text\">How often to check for new work.</div></div><div class=\"col-12\"><label class=\"form-label\" for=\"plugin-admin-detection-timeout\">Detection Timeout (s)</label> <input type=\"number\" class=\"form-control\" id=\"plugin-admin-detection-timeout\" min=\"0\"></div><div class=\"col-12\"><label class=\"form-label\" for=\"plugin-admin-max-runtime\">Job Type Max Runtime (s)</label> <input type=\"number\" class=\"form-control\" id=\"plugin-admin-max-runtime\" min=\"0\"></div><div class=\"col-12\"><label class=\"form-label\" for=\"plugin-admin-max-results\">Max Jobs / Detection</label> <input type=\"number\" class=\"form-control\" id=\"plugin-admin-max-results\" min=\"0\"></div><div class=\"col-12\"><label class=\"form-label\" for=\"plugin-admin-global-exec\">Global Execution Concurrency</label> <input type=\"number\" class=\"form-control\" id=\"plugin-admin-global-exec\" min=\"0\"></div><div class=\"col-12\"><label class=\"form-label\" for=\"plugin-admin-per-worker-exec\">Per Worker Concurrency</label> <input type=\"number\" class=\"form-control\" id=\"plugin-admin-per-worker-exec\" min=\"0\"></div><div class=\"col-12\"><label class=\"form-label\" for=\"plugin-admin-retry-limit\">Retry Limit</label> <input type=\"number\" class=\"form-control\" id=\"plugin-admin-retry-limit\" min=\"0\"></div><div class=\"col-12\"><label class=\"form-label\" for=\"plugin-admin-retry-backoff\">Retry Backoff (s)</label> <input type=\"number\" class=\"form-control\" id=\"plugin-admin-retry-backoff\" min=\"0\"></div></div></div></div><div class=\"card shadow-sm mt-3\"><div class=\"card-header d-flex justify-content-between align-items-center\"><h5 class=\"mb-0\"><i class=\"fas fa-hourglass-half me-2\"></i>Next Run</h5><small class=\"text-muted\">Scheduler</small></div><div class=\"card-body\"><div class=\"h5 mb-1 plugin-scheduler-next-run\">-</div><div class=\"text-muted small plugin-scheduler-next-run-meta\">Not scheduled</div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-lg-6 mb-3\"><div class=\"card shadow-sm h-100\"><div class=\"card-header d-flex justify-content-between align-items-center\"><h5 class=\"mb-0\"><i class=\"fas fa-clipboard-check me-2\"></i>Run History</h5><small class=\"text-muted\">Keep last 10 success + last 10 errors</small></div><div class=\"card-body\"><div class=\"row\"><div class=\"col-12 mb-3\"><h6 class=\"text-success\">Successful Runs</h6><div class=\"table-responsive\"><table class=\"table table-sm table-striped\"><thead><tr><th>Time</th><th>Job ID</th><th>Worker</th><th>Duration</th></tr></thead> <tbody id=\"plugin-runs-success-body\"><tr><td colspan=\"4\" class=\"text-muted\">No data</td></tr></tbody></table></div></div><div class=\"col-12\"><h6 class=\"text-danger\">Error Runs</h6><div class=\"table-responsive\"><table class=\"table table-sm table-striped\"><thead><tr><th>Time</th><th>Job ID</th><th>Worker</th><th>Error</th></tr></thead> <tbody id=\"plugin-runs-error-body\"><tr><td colspan=\"4\" class=\"text-muted\">No data</td></tr></tbody></table></div></div></div></div></div></div><div class=\"col-lg-6 mb-3\"><div class=\"card shadow-sm h-100\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"fas fa-lightbulb me-2\"></i>Detection Results</h5></div><div class=\"card-body\" id=\"plugin-detection-results\"><div class=\"text-muted\">Run detection to see proposals.</div></div></div></div></div></div><div class=\"plugin-section plugin-section-queue\"><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"fas fa-list me-2\"></i>Job Queue</h5><div class=\"d-flex gap-2 align-items-center flex-wrap\"><small class=\"text-muted\">States: pending/assigned/running</small></div></div><div class=\"card-body p-0\"><div class=\"table-responsive\" style=\"max-height: 560px; overflow-y: auto;\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light sticky-top\"><tr><th>Job ID</th><th>Type</th><th>State</th><th>Progress</th><th>Worker</th><th>Updated</th><th>Message</th></tr></thead> <tbody id=\"plugin-queue-jobs-table-body\"><tr><td colspan=\"7\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div></div><div class=\"plugin-section plugin-section-detection\"><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"fas fa-search me-2\"></i>Detection Jobs</h5><div class=\"small text-muted\">Detection activities for selected job type</div></div><div class=\"card-body p-0\"><div class=\"table-responsive\" style=\"max-height: 420px; overflow-y: auto;\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light sticky-top\"><tr><th>Time</th><th>Job Type</th><th>Request ID</th><th>Worker</th><th>Stage</th><th>Source</th><th>Message</th></tr></thead> <tbody id=\"plugin-detection-table-body\"><tr><td colspan=\"7\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div></div><div class=\"plugin-section plugin-section-execution\"><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"fas fa-tasks me-2\"></i>Execution Jobs</h5><div class=\"d-flex gap-2 align-items-center flex-wrap\"><select class=\"form-select form-select-sm\" id=\"plugin-monitor-job-state-filter\" style=\"min-width: 180px;\"><option value=\"\">All States</option> <option value=\"assigned\">Assigned</option> <option value=\"running\">Running</option> <option value=\"succeeded\">Succeeded</option> <option value=\"failed\">Failed</option> <option value=\"canceled\">Canceled</option></select></div></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job ID</th><th>Type</th><th>State</th><th>Progress</th><th>Worker</th><th>Updated</th><th>Message</th></tr></thead> <tbody id=\"plugin-execution-jobs-table-body\"><tr><td colspan=\"7\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"fas fa-stream me-2\"></i>Execution Activities</h5><small class=\"text-muted\">Non-detection events only</small></div><div class=\"card-body p-0\"><div class=\"table-responsive\" style=\"max-height: 420px; overflow-y: auto;\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light sticky-top\"><tr><th>Time</th><th>Job Type</th><th>Job ID</th><th>Source</th><th>Stage</th><th>Message</th></tr></thead> <tbody id=\"plugin-execution-activities-table-body\"><tr><td colspan=\"6\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div></div></div><div class=\"modal fade\" id=\"plugin-job-detail-modal\" tabindex=\"-1\" aria-labelledby=\"plugin-job-detail-modal-label\" aria-hidden=\"true\"><div class=\"modal-dialog modal-xl modal-dialog-scrollable\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"plugin-job-detail-modal-label\"><i class=\"fas fa-file-alt me-2\"></i>Job Detail</h5><div class=\"ms-auto me-2\"><button type=\"button\" class=\"btn btn-outline-danger btn-sm\" id=\"plugin-expire-job-btn\" disabled><i class=\"fas fa-stop-circle me-1\"></i>Expire Job</button></div><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\" id=\"plugin-job-detail-content\"><div class=\"text-muted\">Select a job to view details.</div></div></div></div></div><style>\n .plugin-section {\n display: none;\n }\n\n .plugin-section.plugin-section-active {\n display: block;\n }\n\n .plugin-form-root .card {\n border: 1px solid #dee2e6;\n }\n .plugin-form-root textarea {\n min-height: 12rem;\n }\n\n .plugin-field-hidden {\n display: none;\n }\n\n .plugin-capability-badge {\n font-size: 0.72rem;\n margin-right: 0.25rem;\n }\n\n .plugin-job-progress {\n min-width: 120px;\n }\n\n .plugin-detection-item {\n border: 1px solid #dee2e6;\n border-radius: 6px;\n padding: 0.5rem 0.75rem;\n margin-bottom: 0.5rem;\n background: #fbfcfd;\n }\n\n .plugin-job-link {\n text-decoration: none;\n }\n\n .plugin-job-detail-json {\n max-height: 220px;\n overflow: auto;\n background: #f8f9fa;\n border: 1px solid #dee2e6;\n border-radius: 6px;\n padding: 0.5rem;\n margin-bottom: 0;\n font-size: 0.82rem;\n }\n </style><script>\n (function() {\n var page = document.getElementById('plugin-page');\n if (!page) {\n return;\n }\n\n var state = {\n selectedJobType: '',\n jobTypes: [],\n lastDetectionByJobType: {},\n initialPage: String(page.getAttribute('data-plugin-page') || 'overview').trim().toLowerCase(),\n activeTopTab: 'overview',\n activeSubTab: 'configuration',\n initialNavigationApplied: false,\n monitorExecutionJobState: '',\n workers: [],\n jobs: [],\n activities: [],\n schedulerStates: [],\n schedulerStatus: null,\n allJobs: [],\n allActivities: [],\n loadedJobType: '',\n descriptor: null,\n config: null,\n refreshTimer: null,\n };\n\n function getCSRFToken() {\n var meta = document.querySelector('meta[name=\"csrf-token\"]');\n if (!meta) {\n return '';\n }\n return meta.getAttribute('content') || '';\n }\n\n function notify(message, level) {\n if (typeof window.showAlert === 'function') {\n window.showAlert(message, level || 'info');\n return;\n }\n if (level === 'error') {\n console.error(message);\n }\n alert(message);\n }\n\n async function readResponseJSON(response) {\n var bodyText = await response.text();\n if (!bodyText) {\n return {};\n }\n try {\n return JSON.parse(bodyText);\n } catch (e) {\n return { error: bodyText };\n }\n }\n\n async function pluginRequest(method, url, payload) {\n var headers = {};\n var requestOptions = {\n method: method,\n headers: headers,\n };\n\n if (payload !== undefined && payload !== null) {\n headers['Content-Type'] = 'application/json';\n requestOptions.body = JSON.stringify(payload);\n }\n\n if (method !== 'GET') {\n var csrf = getCSRFToken();\n if (csrf) {\n headers['X-CSRF-Token'] = csrf;\n }\n }\n\n var response = await fetch(url, requestOptions);\n var data = await readResponseJSON(response);\n if (!response.ok) {\n var message = (data && (data.error || data.message)) ? (data.error || data.message) : ('Request failed: ' + response.status);\n var requestError = new Error(message);\n requestError.responseData = data;\n requestError.responseStatus = response.status;\n throw requestError;\n }\n return data;\n }\n\n function textOrDash(value) {\n if (value === null || value === undefined || value === '') {\n return '-';\n }\n return String(value);\n }\n\n function escapeHtml(value) {\n if (value === null || value === undefined) {\n return '';\n }\n return String(value)\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#039;');\n }\n\n function encodePath(value) {\n return encodeURIComponent(value || '');\n }\n\n function normalizeEnum(value) {\n if (value === undefined || value === null) {\n return '';\n }\n return String(value).toUpperCase();\n }\n\n function parseTime(value) {\n if (!value) {\n return '';\n }\n var date = new Date(value);\n if (Number.isNaN(date.getTime())) {\n return '';\n }\n return date.toLocaleString();\n }\n\n function normalizeSubTab(value) {\n var normalized = String(value || '').toLowerCase();\n if (normalized === 'configuration' || normalized === 'detection' || normalized === 'queue' || normalized === 'execution') {\n return normalized;\n }\n return 'configuration';\n }\n\n // Parse a job type item (string or object) into a safe object shape\n function parseJobTypeItem(item) {\n var jobType = '';\n var displayName = '';\n \n if (typeof item === 'string') {\n jobType = String(item || '').trim();\n displayName = jobType;\n } else if (item && typeof item === 'object') {\n jobType = String(item.job_type || item.jobType || '').trim();\n displayName = String(item.display_name || item.displayName || jobType || '').trim();\n if (!displayName) {\n displayName = jobType;\n }\n }\n \n return { jobType: jobType, displayName: displayName };\n }\n\n function topTabKeyForJobType(jobType) {\n var normalized = String(jobType || '').trim();\n if (!normalized) {\n return '';\n }\n return 'job:' + normalized;\n }\n\n function parseJobTypeFromTopTab(tabKey) {\n var normalized = String(tabKey || '').trim();\n if (normalized.indexOf('job:') !== 0) {\n return '';\n }\n return normalized.slice(4);\n }\n\n function hasJobType(jobType) {\n var normalized = String(jobType || '').trim();\n if (!normalized) {\n return false;\n }\n var jobTypes = Array.isArray(state.jobTypes) ? state.jobTypes : [];\n for (var i = 0; i < jobTypes.length; i++) {\n var item = parseJobTypeItem(jobTypes[i]);\n if (item.jobType === normalized) {\n return true;\n }\n }\n return false;\n }\n\n function applyInitialNavigation() {\n if (state.initialNavigationApplied) {\n return;\n }\n state.initialNavigationApplied = true;\n state.activeSubTab = normalizeSubTab(state.initialPage);\n\n if (state.initialPage === 'overview') {\n state.activeTopTab = 'overview';\n return;\n }\n if (!Array.isArray(state.jobTypes) || state.jobTypes.length === 0) {\n state.activeTopTab = 'overview';\n return;\n }\n var firstItem = parseJobTypeItem(state.jobTypes[0]);\n state.selectedJobType = firstItem.jobType;\n state.activeTopTab = topTabKeyForJobType(state.selectedJobType);\n }\n\n function ensureActiveNavigation() {\n state.activeSubTab = normalizeSubTab(state.activeSubTab);\n\n if (state.selectedJobType && !hasJobType(state.selectedJobType)) {\n state.selectedJobType = '';\n state.descriptor = null;\n state.config = null;\n }\n\n var topTabJobType = parseJobTypeFromTopTab(state.activeTopTab);\n if (topTabJobType && !hasJobType(topTabJobType)) {\n state.activeTopTab = 'overview';\n topTabJobType = '';\n }\n\n if (state.activeTopTab === 'overview') {\n if (!state.selectedJobType && Array.isArray(state.jobTypes) && state.jobTypes.length > 0) {\n var item = parseJobTypeItem(state.jobTypes[0]);\n state.selectedJobType = item.jobType;\n }\n return;\n }\n\n if (!topTabJobType && state.selectedJobType) {\n topTabJobType = state.selectedJobType;\n }\n if (!topTabJobType && Array.isArray(state.jobTypes) && state.jobTypes.length > 0) {\n var item = parseJobTypeItem(state.jobTypes[0]);\n topTabJobType = item.jobType;\n }\n if (!topTabJobType) {\n state.activeTopTab = 'overview';\n return;\n }\n\n state.selectedJobType = topTabJobType;\n state.activeTopTab = topTabKeyForJobType(topTabJobType);\n }\n\n function renderTopTabs() {\n var root = document.getElementById('plugin-top-tabs');\n if (!root) {\n return;\n }\n\n var html = '' +\n '<li class=\"nav-item\">' +\n '<button type=\"button\" class=\"nav-link\" data-plugin-top-tab=\"overview\">' +\n '<i class=\"fas fa-chart-line me-1\"></i>Overview' +\n '</button>' +\n '</li>';\n\n var jobTypes = Array.isArray(state.jobTypes) ? state.jobTypes : [];\n for (var i = 0; i < jobTypes.length; i++) {\n var item = parseJobTypeItem(jobTypes[i]);\n var jobType = item.jobType;\n var displayName = item.displayName;\n \n if (!jobType) {\n continue;\n }\n html += '' +\n '<li class=\"nav-item\">' +\n '<button type=\"button\" class=\"nav-link\" data-plugin-top-tab=\"' + escapeHtml(topTabKeyForJobType(jobType)) + '\">' +\n escapeHtml(displayName) +\n '</button>' +\n '</li>';\n }\n root.innerHTML = html;\n }\n\n function renderNavigationState() {\n var selectedJobTypeLabel = document.getElementById('plugin-selected-job-type');\n if (selectedJobTypeLabel) {\n selectedJobTypeLabel.textContent = state.selectedJobType || '-';\n }\n\n var isOverview = state.activeTopTab === 'overview';\n var subtabRow = document.getElementById('plugin-subtab-row');\n if (subtabRow) {\n subtabRow.classList.toggle('d-none', isOverview);\n }\n\n var topTabs = document.querySelectorAll('#plugin-top-tabs [data-plugin-top-tab]');\n for (var i = 0; i < topTabs.length; i++) {\n var topTab = topTabs[i];\n var topKey = String(topTab.getAttribute('data-plugin-top-tab') || '');\n topTab.classList.toggle('active', topKey === state.activeTopTab);\n }\n\n var subTabs = document.querySelectorAll('#plugin-subtabs [data-plugin-subtab]');\n for (var j = 0; j < subTabs.length; j++) {\n var subTab = subTabs[j];\n var subKey = String(subTab.getAttribute('data-plugin-subtab') || '');\n subTab.classList.toggle('active', !isOverview && subKey === state.activeSubTab);\n }\n\n function toggleSection(sectionName, visible) {\n var section = document.querySelector('.plugin-section-' + sectionName);\n if (!section) {\n return;\n }\n section.classList.toggle('plugin-section-active', !!visible);\n }\n\n toggleSection('overview', isOverview);\n toggleSection('configuration', !isOverview && state.activeSubTab === 'configuration');\n toggleSection('detection', !isOverview && state.activeSubTab === 'detection');\n toggleSection('queue', !isOverview && state.activeSubTab === 'queue');\n toggleSection('execution', !isOverview && state.activeSubTab === 'execution');\n }\n\n function renderJobLink(jobID) {\n var normalized = String(jobID || '').trim();\n if (!normalized) {\n return '<small>-</small>';\n }\n return '<button type=\"button\" class=\"btn btn-link btn-sm p-0 align-baseline plugin-job-link\" data-job-id=\"' + escapeHtml(normalized) + '\">' + escapeHtml(normalized) + '</button>';\n }\n\n function toPrettyJson(value) {\n if (value === null || value === undefined || value === '') {\n return '';\n }\n if (typeof value === 'string') {\n return value;\n }\n try {\n return JSON.stringify(value, null, 2);\n } catch (e) {\n return String(value);\n }\n }\n\n function clonePlainObject(value) {\n if (!value || typeof value !== 'object') {\n return null;\n }\n try {\n return JSON.parse(JSON.stringify(value));\n } catch (e) {\n return null;\n }\n }\n\n function extractExecutionPlan(job) {\n if (!job || !job.parameters) {\n return null;\n }\n var plan = job.parameters.execution_plan;\n if (!plan) {\n return null;\n }\n if (typeof plan === 'string') {\n try {\n plan = JSON.parse(plan);\n } catch (e) {\n return null;\n }\n }\n if (typeof plan !== 'object' || Array.isArray(plan)) {\n return null;\n }\n return plan;\n }\n\n function removeExecutionPlanForDisplay(parameters) {\n var copy = clonePlainObject(parameters);\n if (!copy) {\n return parameters;\n }\n if (copy.execution_plan !== undefined) {\n delete copy.execution_plan;\n }\n if (Object.keys(copy).length === 0) {\n return null;\n }\n return copy;\n }\n\n function parseIntOrDefault(value, fallback) {\n var parsed = parseInt(value, 10);\n if (Number.isNaN(parsed)) {\n return fallback;\n }\n return parsed;\n }\n\n function normalizeShardIDs(value) {\n if (!Array.isArray(value)) {\n return [];\n }\n var out = [];\n for (var i = 0; i < value.length; i++) {\n var parsed = parseIntOrDefault(value[i], -1);\n if (parsed >= 0) {\n out.push(parsed);\n }\n }\n out.sort(function(a, b) { return a - b; });\n return out;\n }\n\n function classifyShardLabel(shardID, dataShardCount) {\n if (shardID < dataShardCount) {\n return {\n kind: 'data',\n label: String(shardID),\n className: 'bg-primary',\n title: 'Data shard ' + shardID,\n };\n }\n var parityIndex = shardID - dataShardCount;\n return {\n kind: 'parity',\n label: String(shardID),\n className: 'bg-warning text-dark',\n title: 'Parity shard ' + shardID + ' (index ' + parityIndex + ')',\n };\n }\n\n function renderShardBadges(shardIDs, dataShardCount) {\n if (!Array.isArray(shardIDs) || shardIDs.length === 0) {\n return '<span class=\"text-muted\">-</span>';\n }\n var html = '';\n for (var i = 0; i < shardIDs.length; i++) {\n var shard = classifyShardLabel(shardIDs[i], dataShardCount);\n html += '<span class=\"badge me-1 ' + shard.className + '\" title=\"' + escapeHtml(shard.title) + '\">' + escapeHtml(shard.label) + '</span>';\n }\n return html;\n }\n\n function renderExecutionPlan(plan) {\n if (!plan || typeof plan !== 'object') {\n return '';\n }\n\n var jobType = String(plan.job_type || '').trim().toLowerCase();\n if (jobType !== 'erasure_coding') {\n var fallbackText = toPrettyJson(plan);\n if (!fallbackText) {\n return '';\n }\n return '<div class=\"mb-3\"><h6>Execution Plan</h6><pre class=\"plugin-job-detail-json\">' + escapeHtml(fallbackText) + '</pre></div>';\n }\n\n var dataShards = parseIntOrDefault(plan.data_shards, 10);\n var parityShards = parseIntOrDefault(plan.parity_shards, 4);\n var totalShards = parseIntOrDefault(plan.total_shards, dataShards + parityShards);\n var sources = Array.isArray(plan.sources) ? plan.sources : [];\n var targets = Array.isArray(plan.targets) ? plan.targets : [];\n var assignments = Array.isArray(plan.shard_assignments) ? plan.shard_assignments : [];\n\n var html = '';\n html += '<div class=\"mb-3\"><h6>Execution Plan</h6>';\n html += '<div class=\"row g-2 mb-2\">' +\n '<div class=\"col-md-3\"><small><strong>Volume:</strong> ' + escapeHtml(textOrDash(plan.volume_id)) + '</small></div>' +\n '<div class=\"col-md-3\"><small><strong>Collection:</strong> ' + escapeHtml(textOrDash(plan.collection)) + '</small></div>' +\n '<div class=\"col-md-3\"><small><strong>Shards:</strong> ' + escapeHtml(String(dataShards)) + '+' + escapeHtml(String(parityShards)) + '</small></div>' +\n '<div class=\"col-md-3\"><small><strong>Total:</strong> ' + escapeHtml(String(totalShards)) + '</small></div>' +\n '</div>';\n\n html += '<div class=\"small text-muted mb-2\">' +\n '<span class=\"badge bg-primary me-1\">Data</span>' +\n '<span class=\"badge bg-warning text-dark me-2\">Parity</span>' +\n 'Source and target placement per shard.' +\n '</div>';\n\n function renderEndpointsTable(title, endpoints) {\n if (!endpoints.length) {\n return '<div class=\"mb-2\"><strong>' + escapeHtml(title) + ':</strong> <span class=\"text-muted\">none</span></div>';\n }\n var table = '<div class=\"table-responsive mb-2\"><table class=\"table table-sm table-striped mb-0\">' +\n '<thead><tr><th>#</th><th>Node</th><th>DC</th><th>Rack</th><th>Volume</th><th>Shards</th></tr></thead><tbody>';\n for (var i = 0; i < endpoints.length; i++) {\n var endpoint = endpoints[i] || {};\n var endpointShards = normalizeShardIDs(endpoint.shard_ids);\n table += '<tr>' +\n '<td>' + escapeHtml(String(i + 1)) + '</td>' +\n '<td><code>' + escapeHtml(textOrDash(endpoint.node)) + '</code></td>' +\n '<td>' + escapeHtml(textOrDash(endpoint.data_center)) + '</td>' +\n '<td>' + escapeHtml(textOrDash(endpoint.rack)) + '</td>' +\n '<td>' + escapeHtml(textOrDash(endpoint.volume_id)) + '</td>' +\n '<td>' + renderShardBadges(endpointShards, dataShards) + '</td>' +\n '</tr>';\n }\n table += '</tbody></table></div>';\n return '<div class=\"mb-2\"><strong>' + escapeHtml(title) + '</strong></div>' + table;\n }\n\n html += renderEndpointsTable('Sources', sources);\n html += renderEndpointsTable('Targets', targets);\n\n if (assignments.length) {\n html += '<div class=\"mb-2\"><strong>Shard Assignments</strong></div>';\n html += '<div class=\"table-responsive\"><table class=\"table table-sm table-striped mb-0\">' +\n '<thead><tr><th>Shard</th><th>Kind</th><th>Target</th><th>DC</th><th>Rack</th></tr></thead><tbody>';\n for (var j = 0; j < assignments.length; j++) {\n var assignment = assignments[j] || {};\n var shardID = parseIntOrDefault(assignment.shard_id, -1);\n if (shardID < 0) {\n continue;\n }\n var shard = classifyShardLabel(shardID, dataShards);\n html += '<tr>' +\n '<td><span class=\"badge ' + shard.className + '\">' + escapeHtml(shard.label) + '</span></td>' +\n '<td>' + escapeHtml(textOrDash(assignment.kind || shard.kind)) + '</td>' +\n '<td><code>' + escapeHtml(textOrDash(assignment.target_node)) + '</code></td>' +\n '<td>' + escapeHtml(textOrDash(assignment.target_data_center)) + '</td>' +\n '<td>' + escapeHtml(textOrDash(assignment.target_rack)) + '</td>' +\n '</tr>';\n }\n html += '</tbody></table></div>';\n }\n\n html += '</div>';\n return html;\n }\n\n function isActiveJobState(candidateState) {\n var jobState = candidateState;\n if (candidateState && typeof candidateState === 'object' && candidateState.state !== undefined) {\n jobState = candidateState.state;\n }\n var st = String(jobState || '').toLowerCase();\n return st === 'job_state_pending' || st === 'job_state_assigned' || st === 'job_state_running' ||\n st === 'pending' || st === 'assigned' || st === 'running' || st === 'in_progress';\n }\n\n function setExpireButtonState(job) {\n var expireBtn = document.getElementById('plugin-expire-job-btn');\n if (!expireBtn) {\n return;\n }\n var jobID = job && job.job_id ? String(job.job_id) : '';\n var active = isActiveJobState(job);\n expireBtn.setAttribute('data-job-id', jobID);\n expireBtn.disabled = !jobID || !active;\n if (!jobID) {\n expireBtn.title = 'Select a job to expire.';\n } else if (!active) {\n expireBtn.title = 'Job is not active.';\n } else {\n expireBtn.title = 'Expire job to unblock scheduling.';\n }\n }\n\n async function expireJob(jobID) {\n var normalizedJobID = String(jobID || '').trim();\n if (!normalizedJobID) {\n return;\n }\n\n var reason = window.prompt('Expire job ' + normalizedJobID + '? Optional reason:', 'job expired by admin request');\n if (reason === null) {\n return;\n }\n\n var expireBtn = document.getElementById('plugin-expire-job-btn');\n if (expireBtn) {\n expireBtn.disabled = true;\n }\n\n try {\n var response = await pluginRequest('POST', '/api/plugin/jobs/' + encodePath(normalizedJobID) + '/expire', {\n reason: reason,\n });\n if (response && response.expired === false) {\n notify(response.message || 'Job is not active.', 'info');\n } else {\n notify('Job expired: ' + normalizedJobID, 'success');\n }\n await refreshJobsAndActivities();\n await openJobDetail(normalizedJobID);\n } catch (e) {\n notify('Failed to expire job: ' + e.message, 'error');\n }\n }\n\n async function openJobDetail(jobID) {\n var normalizedJobID = String(jobID || '').trim();\n if (!normalizedJobID) {\n return;\n }\n\n var modalElement = document.getElementById('plugin-job-detail-modal');\n var contentRoot = document.getElementById('plugin-job-detail-content');\n if (!modalElement || !contentRoot) {\n return;\n }\n\n var modal;\n if (window.bootstrap && window.bootstrap.Modal) {\n modal = window.bootstrap.Modal.getOrCreateInstance(modalElement);\n }\n if (modal) {\n modal.show();\n }\n\n setExpireButtonState(null);\n contentRoot.innerHTML = '<div class=\"text-muted\">Loading job detail...</div>';\n try {\n var detail = await pluginRequest('GET', '/api/plugin/jobs/' + encodePath(normalizedJobID) + '/detail?activity_limit=500&related_limit=20');\n var job = (detail && detail.job) ? detail.job : {};\n setExpireButtonState(job);\n var runRecord = detail && detail.run_record ? detail.run_record : null;\n var activities = (detail && Array.isArray(detail.activities)) ? detail.activities : [];\n var relatedJobs = (detail && Array.isArray(detail.related_jobs)) ? detail.related_jobs : [];\n var html = '';\n\n html += '<div class=\"row g-3 mb-3\">' +\n '<div class=\"col-lg-8\">' +\n '<div><strong>Job ID:</strong> ' + escapeHtml(textOrDash(job.job_id || normalizedJobID)) + '</div>' +\n '<div><strong>Type:</strong> ' + escapeHtml(textOrDash(job.job_type)) + '</div>' +\n '<div><strong>State:</strong> ' + escapeHtml(textOrDash(job.state)) + '</div>' +\n '<div><strong>Worker:</strong> ' + escapeHtml(textOrDash(job.worker_id)) + '</div>' +\n '<div><strong>Updated:</strong> ' + escapeHtml(parseTime(job.updated_at) || '-') + '</div>' +\n '</div>' +\n '<div class=\"col-lg-4\">' +\n '<div><strong>Attempt:</strong> ' + escapeHtml(textOrDash(job.attempt)) + '</div>' +\n '<div><strong>Progress:</strong> ' + escapeHtml(String(Math.round(Number(job.progress || 0)))) + '%</div>' +\n '<div><strong>Created:</strong> ' + escapeHtml(parseTime(job.created_at) || '-') + '</div>' +\n '<div><strong>Completed:</strong> ' + escapeHtml(parseTime(job.completed_at) || '-') + '</div>' +\n '</div>' +\n '</div>';\n\n if (job.summary) {\n html += '<div class=\"mb-2\"><strong>Summary:</strong> ' + escapeHtml(String(job.summary)) + '</div>';\n }\n if (job.detail) {\n html += '<div class=\"mb-2\"><strong>Detail:</strong> ' + escapeHtml(String(job.detail)) + '</div>';\n }\n if (job.message) {\n html += '<div class=\"mb-2\"><strong>Message:</strong> ' + escapeHtml(String(job.message)) + '</div>';\n }\n if (job.error_message) {\n html += '<div class=\"mb-2 text-danger\"><strong>Error:</strong> ' + escapeHtml(String(job.error_message)) + '</div>';\n }\n if (job.result_summary) {\n html += '<div class=\"mb-2\"><strong>Result:</strong> ' + escapeHtml(String(job.result_summary)) + '</div>';\n }\n\n var executionPlan = extractExecutionPlan(job);\n if (executionPlan) {\n html += renderExecutionPlan(executionPlan);\n }\n\n var parametersText = toPrettyJson(removeExecutionPlanForDisplay(job.parameters));\n if (parametersText) {\n html += '<div class=\"mb-3\"><h6>Parameters</h6><pre class=\"plugin-job-detail-json\">' + escapeHtml(parametersText) + '</pre></div>';\n }\n var labelsText = toPrettyJson(job.labels);\n if (labelsText) {\n html += '<div class=\"mb-3\"><h6>Labels</h6><pre class=\"plugin-job-detail-json\">' + escapeHtml(labelsText) + '</pre></div>';\n }\n var outputsText = toPrettyJson(job.result_output_values);\n if (outputsText) {\n html += '<div class=\"mb-3\"><h6>Result Output Values</h6><pre class=\"plugin-job-detail-json\">' + escapeHtml(outputsText) + '</pre></div>';\n }\n\n if (runRecord) {\n html += '<div class=\"mb-3\"><h6>Run Record</h6>' +\n '<div><strong>Outcome:</strong> ' + escapeHtml(textOrDash(runRecord.outcome)) + '</div>' +\n '<div><strong>Duration:</strong> ' + escapeHtml(formatDurationMs(runRecord.duration_ms)) + '</div>' +\n '<div><strong>Completed:</strong> ' + escapeHtml(parseTime(runRecord.completed_at) || '-') + '</div>' +\n '<div><strong>Message:</strong> ' + escapeHtml(textOrDash(runRecord.message)) + '</div>' +\n '</div>';\n }\n\n html += '<h6 class=\"mt-3\">Activity Timeline</h6>';\n if (!activities.length) {\n html += '<div class=\"text-muted mb-3\">No activity records.</div>';\n } else {\n html += '<div class=\"table-responsive mb-3\"><table class=\"table table-sm table-striped\">' +\n '<thead><tr><th>Time</th><th>Stage</th><th>Source</th><th>Worker</th><th>Message</th></tr></thead><tbody>';\n for (var i = 0; i < activities.length; i++) {\n var activity = activities[i] || {};\n html += '<tr>' +\n '<td><small>' + escapeHtml(parseTime(activity.occurred_at) || '-') + '</small></td>' +\n '<td>' + escapeHtml(textOrDash(activity.stage)) + '</td>' +\n '<td>' + escapeHtml(textOrDash(activity.source)) + '</td>' +\n '<td>' + escapeHtml(textOrDash(activity.worker_id)) + '</td>' +\n '<td><small>' + escapeHtml(textOrDash(activity.message)) + '</small></td>' +\n '</tr>';\n }\n html += '</tbody></table></div>';\n }\n\n if (relatedJobs.length) {\n html += '<h6>Related Jobs</h6><div class=\"table-responsive\"><table class=\"table table-sm table-hover\">' +\n '<thead><tr><th>Job ID</th><th>State</th><th>Worker</th><th>Updated</th></tr></thead><tbody>';\n for (var j = 0; j < relatedJobs.length; j++) {\n var related = relatedJobs[j] || {};\n html += '<tr>' +\n '<td><small>' + escapeHtml(textOrDash(related.job_id)) + '</small></td>' +\n '<td>' + escapeHtml(textOrDash(related.state)) + '</td>' +\n '<td>' + escapeHtml(textOrDash(related.worker_id)) + '</td>' +\n '<td><small>' + escapeHtml(parseTime(related.updated_at) || '-') + '</small></td>' +\n '</tr>';\n }\n html += '</tbody></table></div>';\n }\n\n contentRoot.innerHTML = html;\n } catch (e) {\n setExpireButtonState(null);\n contentRoot.innerHTML = '<div class=\"alert alert-danger mb-0\">Failed to load job detail: ' + escapeHtml(e.message) + '</div>';\n }\n }\n\n function formatDurationMs(value) {\n var ms = Number(value || 0);\n if (!Number.isFinite(ms) || ms <= 0) {\n return '-';\n }\n if (ms < 1000) {\n return ms + 'ms';\n }\n var sec = Math.floor(ms / 1000);\n var remainMs = ms % 1000;\n if (sec < 60) {\n return sec + '.' + String(Math.floor(remainMs / 100)) + 's';\n }\n var min = Math.floor(sec / 60);\n var remainSec = sec % 60;\n return min + 'm ' + remainSec + 's';\n }\n\n function getWorkerField(worker, name) {\n if (!worker) {\n return null;\n }\n if (worker[name] !== undefined) {\n return worker[name];\n }\n var camel = name.charAt(0).toUpperCase() + name.slice(1);\n if (worker[camel] !== undefined) {\n return worker[camel];\n }\n return null;\n }\n\n function renderStatus() {\n var allJobs = Array.isArray(state.allJobs) ? state.allJobs : [];\n var allActivities = Array.isArray(state.allActivities) ? state.allActivities : [];\n\n var activeCount = allJobs.filter(function(job) {\n return isActiveJobState(job);\n }).length;\n\n document.getElementById('plugin-status-workers').textContent = String(state.workers.length);\n document.getElementById('plugin-status-active-jobs').textContent = String(activeCount);\n document.getElementById('plugin-status-activities').textContent = String(allActivities.length);\n }\n\n function renderJobTypeSummary() {\n var tbody = document.getElementById('plugin-jobtype-summary-body');\n if (!tbody) {\n return;\n }\n\n var activeByType = {};\n var activityByType = {};\n\n var allJobs = Array.isArray(state.allJobs) ? state.allJobs : [];\n var allActivities = Array.isArray(state.allActivities) ? state.allActivities : [];\n\n for (var i = 0; i < allJobs.length; i++) {\n var job = allJobs[i] || {};\n var jobType = String(job.job_type || '').trim();\n if (!jobType) {\n continue;\n }\n var isActive = isActiveJobState(job);\n if (!isActive) {\n continue;\n }\n if (!activeByType[jobType]) {\n activeByType[jobType] = 0;\n }\n activeByType[jobType]++;\n }\n\n for (var j = 0; j < allActivities.length; j++) {\n var activity = allActivities[j] || {};\n var activityJobType = String(activity.job_type || '').trim();\n if (!activityJobType) {\n continue;\n }\n if (!activityByType[activityJobType]) {\n activityByType[activityJobType] = 0;\n }\n activityByType[activityJobType]++;\n }\n\n var known = Array.isArray(state.jobTypes) ? state.jobTypes.slice() : [];\n var seen = {};\n var jobTypes = [];\n\n for (var k = 0; k < known.length; k++) {\n var item = parseJobTypeItem(known[k]);\n var knownType = item && item.jobType ? String(item.jobType).trim() : '';\n if (!knownType || seen[knownType]) {\n continue;\n }\n seen[knownType] = true;\n jobTypes.push(knownType);\n }\n\n Object.keys(activeByType).forEach(function(jobType) {\n if (!seen[jobType]) {\n seen[jobType] = true;\n jobTypes.push(jobType);\n }\n });\n Object.keys(activityByType).forEach(function(jobType) {\n if (!seen[jobType]) {\n seen[jobType] = true;\n jobTypes.push(jobType);\n }\n });\n\n jobTypes.sort();\n\n if (jobTypes.length === 0) {\n tbody.innerHTML = '<tr><td colspan=\\\"3\\\" class=\\\"text-muted text-center py-3\\\">No job types discovered</td></tr>';\n return;\n }\n\n var rows = '';\n for (var m = 0; m < jobTypes.length; m++) {\n var rowType = jobTypes[m];\n rows += '<tr>' +\n '<td>' + escapeHtml(rowType) + '</td>' +\n '<td><span class=\\\"badge bg-warning text-dark\\\">' + escapeHtml(String(activeByType[rowType] || 0)) + '</span></td>' +\n '<td><span class=\\\"badge bg-info\\\">' + escapeHtml(String(activityByType[rowType] || 0)) + '</span></td>' +\n '</tr>';\n }\n tbody.innerHTML = rows;\n }\n\n function computeEffectiveExecutionCapacity(globalExec, perWorkerExec, executorWorkers) {\n var capacities = [];\n if (globalExec > 0) {\n capacities.push(globalExec);\n }\n var workerCapacity = perWorkerExec > 0 && executorWorkers > 0 ? (perWorkerExec * executorWorkers) : 0;\n if (workerCapacity > 0) {\n capacities.push(workerCapacity);\n }\n if (!capacities.length) {\n return 0;\n }\n var effective = capacities[0];\n for (var i = 1; i < capacities.length; i++) {\n if (capacities[i] < effective) {\n effective = capacities[i];\n }\n }\n return effective;\n }\n\n function renderSchedulerStates() {\n var tbody = document.getElementById('plugin-scheduler-table-body');\n if (!tbody) {\n return;\n }\n\n var states = Array.isArray(state.schedulerStates) ? state.schedulerStates : [];\n if (!states.length) {\n tbody.innerHTML = '<tr><td colspan=\"10\" class=\"text-muted text-center py-3\">No scheduler state available</td></tr>';\n return;\n }\n\n var rows = '';\n for (var i = 0; i < states.length; i++) {\n var item = states[i] || {};\n var enabled = !!item.enabled;\n var inFlight = !!item.detection_in_flight;\n var detector = item.detector_available ? textOrDash(item.detector_worker_id) : 'No detector';\n var maxRuntimeSeconds = Number(item.job_type_max_runtime_seconds || 0);\n var maxRuntimeText = maxRuntimeSeconds > 0 ? (String(maxRuntimeSeconds) + 's') : '-';\n var globalExec = Number(item.global_execution_concurrency || 0);\n var perWorkerExec = Number(item.per_worker_execution_concurrency || 0);\n var executorWorkers = Number(item.executor_worker_count || 0);\n var effectiveExec = computeEffectiveExecutionCapacity(globalExec, perWorkerExec, executorWorkers);\n var globalExecText = enabled ? String(globalExec) : '-';\n var perWorkerExecText = enabled ? String(perWorkerExec) : '-';\n var executorWorkersText = enabled ? String(executorWorkers) : '-';\n var effectiveExecText = enabled ? String(effectiveExec) : '-';\n var lastRunStatus = textOrDash(item.last_run_status);\n var lastRunTime = parseTime(item.last_run_completed_at);\n var lastRunText = '-';\n if (lastRunStatus !== '-' || lastRunTime) {\n var statusLabel = lastRunStatus !== '-' ? lastRunStatus : 'run';\n lastRunText = lastRunTime ? (statusLabel + ' @ ' + lastRunTime) : statusLabel;\n }\n\n var enabledBadge = enabled ? '<span class=\"badge bg-success\">Enabled</span>' : '<span class=\"badge bg-secondary\">Disabled</span>';\n var inFlightBadge = inFlight ? '<span class=\"badge bg-warning text-dark\">Yes</span>' : '<span class=\"badge bg-light text-dark\">No</span>';\n var policyErrorHtml = '';\n if (item.policy_error) {\n policyErrorHtml = '<div><small class=\"text-danger\">' + escapeHtml(String(item.policy_error)) + '</small></div>';\n }\n\n rows += '<tr>' +\n '<td>' + escapeHtml(textOrDash(item.job_type)) + policyErrorHtml + '</td>' +\n '<td>' + enabledBadge + '</td>' +\n '<td><small>' + escapeHtml(detector) + '</small></td>' +\n '<td>' + inFlightBadge + '</td>' +\n '<td><small>' + escapeHtml(maxRuntimeText) + '</small></td>' +\n '<td><small>' + escapeHtml(globalExecText) + '</small></td>' +\n '<td><small>' + escapeHtml(perWorkerExecText) + '</small></td>' +\n '<td><small>' + escapeHtml(executorWorkersText) + '</small></td>' +\n '<td><small>' + escapeHtml(effectiveExecText) + '</small></td>' +\n '<td><small>' + escapeHtml(lastRunText) + '</small></td>' +\n '</tr>';\n }\n\n tbody.innerHTML = rows;\n }\n\n function renderSchedulerStatus() {\n var valueNodes = document.querySelectorAll('.plugin-scheduler-next-run');\n if (!valueNodes.length) {\n return;\n }\n var metaNodes = document.querySelectorAll('.plugin-scheduler-next-run-meta');\n var status = state.schedulerStatus || {};\n var nextRun = parseTime(status.next_detection_at);\n var display = nextRun || '-';\n valueNodes.forEach(function(node) {\n node.textContent = display;\n });\n var metaText = nextRun ? 'Local time' : 'Not scheduled';\n if (metaNodes.length) {\n metaNodes.forEach(function(node) {\n node.textContent = metaText;\n });\n }\n }\n\n function renderWorkers() {\n var tbody = document.getElementById('plugin-workers-table-body');\n if (!state.workers.length) {\n tbody.innerHTML = '<tr><td colspan=\"4\" class=\"text-muted text-center py-3\">No connected workers</td></tr>';\n return;\n }\n\n var rows = '';\n for (var i = 0; i < state.workers.length; i++) {\n var worker = state.workers[i];\n var workerID = textOrDash(getWorkerField(worker, 'workerID'));\n var address = textOrDash(getWorkerField(worker, 'address'));\n var caps = getWorkerField(worker, 'capabilities') || {};\n var capBadges = [];\n\n Object.keys(caps).sort().forEach(function(jobType) {\n var cap = caps[jobType] || {};\n var labels = [];\n if (cap.can_detect) {\n labels.push('D');\n }\n if (cap.can_execute) {\n labels.push('E');\n }\n var text = jobType;\n if (labels.length) {\n text += ' (' + labels.join('/') + ')';\n }\n capBadges.push('<span class=\"badge bg-secondary plugin-capability-badge\">' + escapeHtml(text) + '</span>');\n });\n\n if (!capBadges.length) {\n capBadges.push('<span class=\"text-muted\">-</span>');\n }\n\n var heartbeat = getWorkerField(worker, 'heartbeat') || {};\n var detUsed = Number(heartbeat.detection_slots_used || heartbeat.DetectionSlotsUsed || 0);\n var detTotal = Number(heartbeat.detection_slots_total || heartbeat.DetectionSlotsTotal || 0);\n var execUsed = Number(heartbeat.execution_slots_used || heartbeat.ExecutionSlotsUsed || 0);\n var execTotal = Number(heartbeat.execution_slots_total || heartbeat.ExecutionSlotsTotal || 0);\n var runningWork = heartbeat.running_work || heartbeat.RunningWork || [];\n var queuedByType = heartbeat.queued_jobs_by_type || heartbeat.QueuedJobsByType || {};\n var queuedTotal = 0;\n Object.keys(queuedByType || {}).forEach(function(jobType) {\n var queuedCount = Number(queuedByType[jobType] || 0);\n if (Number.isFinite(queuedCount) && queuedCount > 0) {\n queuedTotal += queuedCount;\n }\n });\n var loadLines = [];\n loadLines.push('Detect: ' + String(detUsed) + '/' + String(detTotal));\n loadLines.push('Execute: ' + String(execUsed) + '/' + String(execTotal));\n loadLines.push('Running: ' + String(Array.isArray(runningWork) ? runningWork.length : 0));\n loadLines.push('Queued: ' + String(queuedTotal));\n\n rows += '<tr>' +\n '<td><div class=\"fw-semibold\">' + escapeHtml(workerID) + '</div></td>' +\n '<td><small>' + escapeHtml(address) + '</small></td>' +\n '<td>' + capBadges.join('') + '</td>' +\n '<td><small>' + escapeHtml(loadLines.join(' | ')) + '</small></td>' +\n '</tr>';\n }\n\n tbody.innerHTML = rows;\n }\n\n function normalizeJobStateForFilter(value) {\n var normalized = String(value || '').toLowerCase();\n if (normalized.indexOf('job_state_') === 0) {\n normalized = normalized.slice('job_state_'.length);\n }\n return normalized;\n }\n\n function matchesExecutionStateFilter(jobState, selectedFilter) {\n var target = normalizeJobStateForFilter(selectedFilter);\n if (!target) {\n return true;\n }\n var actual = normalizeJobStateForFilter(jobState);\n if (actual === target) {\n return true;\n }\n if (target === 'running' && actual === 'in_progress') {\n return true;\n }\n return false;\n }\n\n function isDetectionActivitySource(source) {\n var normalized = String(source || '').toLowerCase();\n if (!normalized) {\n return false;\n }\n if (normalized === 'worker_detection') {\n return true;\n }\n return normalized.indexOf('detector') >= 0;\n }\n\n function renderExecutionJobs() {\n var tbody = document.getElementById('plugin-execution-jobs-table-body');\n if (!tbody) {\n return;\n }\n\n var filteredJobs = [];\n var allJobs = Array.isArray(state.allJobs) ? state.allJobs : [];\n for (var i = 0; i < allJobs.length; i++) {\n var job = allJobs[i] || {};\n var jobType = String(job.job_type || '').trim();\n if (state.selectedJobType && jobType !== state.selectedJobType) {\n continue;\n }\n if (!matchesExecutionStateFilter(job.state, state.monitorExecutionJobState)) {\n continue;\n }\n filteredJobs.push(job);\n }\n\n if (!filteredJobs.length) {\n tbody.innerHTML = '<tr><td colspan=\"7\" class=\"text-muted text-center py-3\">No execution jobs tracked yet</td></tr>';\n return;\n }\n\n var rows = '';\n for (var j = 0; j < filteredJobs.length; j++) {\n var executionJob = filteredJobs[j] || {};\n var progress = Number(executionJob.progress || 0);\n if (!Number.isFinite(progress) || progress < 0) {\n progress = 0;\n }\n if (progress > 100) {\n progress = 100;\n }\n\n var barClass = 'bg-info';\n var stateText = String(executionJob.state || 'unknown').toLowerCase();\n if (stateText.indexOf('failed') >= 0) {\n barClass = 'bg-danger';\n } else if (stateText.indexOf('succeed') >= 0 || stateText.indexOf('complete') >= 0) {\n barClass = 'bg-success';\n } else if (stateText.indexOf('run') >= 0 || stateText.indexOf('progress') >= 0) {\n barClass = 'bg-warning';\n }\n\n rows += '<tr>' +\n '<td>' + renderJobLink(executionJob.job_id) + '</td>' +\n '<td>' + escapeHtml(textOrDash(executionJob.job_type)) + '</td>' +\n '<td><span class=\"badge bg-light text-dark\">' + escapeHtml(textOrDash(executionJob.state)) + '</span></td>' +\n '<td class=\"plugin-job-progress\"><div class=\"progress\" style=\"height: 14px;\"><div class=\"progress-bar ' + barClass + '\" role=\"progressbar\" style=\"width:' + progress + '%\">' + Math.round(progress) + '%</div></div></td>' +\n '<td><small>' + escapeHtml(textOrDash(executionJob.worker_id)) + '</small></td>' +\n '<td><small>' + escapeHtml(parseTime(executionJob.updated_at) || '-') + '</small></td>' +\n '<td><small>' + escapeHtml(textOrDash(executionJob.message)) + '</small></td>' +\n '</tr>';\n }\n\n tbody.innerHTML = rows;\n }\n\n function renderQueueJobs() {\n var tbody = document.getElementById('plugin-queue-jobs-table-body');\n if (!tbody) {\n return;\n }\n\n var filteredJobs = [];\n var allJobs = Array.isArray(state.allJobs) ? state.allJobs : [];\n for (var i = 0; i < allJobs.length; i++) {\n var queueJob = allJobs[i] || {};\n var queueJobType = String(queueJob.job_type || '').trim();\n if (state.selectedJobType && queueJobType !== state.selectedJobType) {\n continue;\n }\n var normalizedState = normalizeJobStateForFilter(queueJob.state);\n if (normalizedState !== 'pending' && normalizedState !== 'assigned' && normalizedState !== 'running' && normalizedState !== 'in_progress') {\n continue;\n }\n filteredJobs.push(queueJob);\n }\n\n if (!filteredJobs.length) {\n tbody.innerHTML = '<tr><td colspan=\"7\" class=\"text-muted text-center py-3\">No queued/active jobs</td></tr>';\n return;\n }\n\n var rows = '';\n for (var j = 0; j < filteredJobs.length; j++) {\n var queueItem = filteredJobs[j] || {};\n var progress = Number(queueItem.progress || 0);\n if (!Number.isFinite(progress) || progress < 0) {\n progress = 0;\n }\n if (progress > 100) {\n progress = 100;\n }\n\n var barClass = 'bg-warning';\n var queueStateText = String(queueItem.state || 'unknown').toLowerCase();\n if (queueStateText.indexOf('run') >= 0 || queueStateText.indexOf('progress') >= 0) {\n barClass = 'bg-info';\n }\n\n rows += '<tr>' +\n '<td>' + renderJobLink(queueItem.job_id) + '</td>' +\n '<td>' + escapeHtml(textOrDash(queueItem.job_type)) + '</td>' +\n '<td><span class=\"badge bg-light text-dark\">' + escapeHtml(textOrDash(queueItem.state)) + '</span></td>' +\n '<td class=\"plugin-job-progress\"><div class=\"progress\" style=\"height: 14px;\"><div class=\"progress-bar ' + barClass + '\" role=\"progressbar\" style=\"width:' + progress + '%\">' + Math.round(progress) + '%</div></div></td>' +\n '<td><small>' + escapeHtml(textOrDash(queueItem.worker_id)) + '</small></td>' +\n '<td><small>' + escapeHtml(parseTime(queueItem.updated_at) || '-') + '</small></td>' +\n '<td><small>' + escapeHtml(textOrDash(queueItem.message)) + '</small></td>' +\n '</tr>';\n }\n\n tbody.innerHTML = rows;\n }\n\n function renderDetectionJobs() {\n var tbody = document.getElementById('plugin-detection-table-body');\n if (!tbody) {\n return;\n }\n\n var filteredActivities = [];\n var allActivities = Array.isArray(state.allActivities) ? state.allActivities : [];\n for (var i = 0; i < allActivities.length; i++) {\n var activity = allActivities[i] || {};\n var jobType = String(activity.job_type || '').trim();\n if (state.selectedJobType && jobType !== state.selectedJobType) {\n continue;\n }\n if (!isDetectionActivitySource(activity.source)) {\n continue;\n }\n filteredActivities.push(activity);\n }\n\n if (!filteredActivities.length) {\n tbody.innerHTML = '<tr><td colspan=\"7\" class=\"text-muted text-center py-3\">No detection jobs tracked yet</td></tr>';\n return;\n }\n\n var rows = '';\n for (var j = 0; j < filteredActivities.length; j++) {\n var detectionActivity = filteredActivities[j] || {};\n rows += '<tr>' +\n '<td><small>' + escapeHtml(parseTime(detectionActivity.occurred_at) || '-') + '</small></td>' +\n '<td>' + escapeHtml(textOrDash(detectionActivity.job_type)) + '</td>' +\n '<td><small>' + escapeHtml(textOrDash(detectionActivity.request_id)) + '</small></td>' +\n '<td><small>' + escapeHtml(textOrDash(detectionActivity.worker_id)) + '</small></td>' +\n '<td>' + escapeHtml(textOrDash(detectionActivity.stage)) + '</td>' +\n '<td><span class=\"badge bg-light text-dark\">' + escapeHtml(textOrDash(detectionActivity.source)) + '</span></td>' +\n '<td><small>' + escapeHtml(textOrDash(detectionActivity.message)) + '</small></td>' +\n '</tr>';\n }\n\n tbody.innerHTML = rows;\n }\n\n function renderExecutionActivities() {\n var tbody = document.getElementById('plugin-execution-activities-table-body');\n if (!tbody) {\n return;\n }\n\n var filteredActivities = [];\n var allActivities = Array.isArray(state.allActivities) ? state.allActivities : [];\n for (var i = 0; i < allActivities.length; i++) {\n var activity = allActivities[i] || {};\n if (isDetectionActivitySource(activity.source)) {\n continue;\n }\n var jobType = String(activity.job_type || '').trim();\n if (state.selectedJobType && jobType !== state.selectedJobType) {\n continue;\n }\n filteredActivities.push(activity);\n }\n\n if (!filteredActivities.length) {\n tbody.innerHTML = '<tr><td colspan=\"6\" class=\"text-muted text-center py-3\">No execution activities yet</td></tr>';\n return;\n }\n\n var rows = '';\n for (var j = 0; j < filteredActivities.length; j++) {\n var executionActivity = filteredActivities[j] || {};\n rows += '<tr>' +\n '<td><small>' + escapeHtml(parseTime(executionActivity.occurred_at) || '-') + '</small></td>' +\n '<td>' + escapeHtml(textOrDash(executionActivity.job_type)) + '</td>' +\n '<td>' + renderJobLink(executionActivity.job_id) + '</td>' +\n '<td><span class=\"badge bg-light text-dark\">' + escapeHtml(textOrDash(executionActivity.source)) + '</span></td>' +\n '<td>' + escapeHtml(textOrDash(executionActivity.stage)) + '</td>' +\n '<td><small>' + escapeHtml(textOrDash(executionActivity.message)) + '</small></td>' +\n '</tr>';\n }\n\n tbody.innerHTML = rows;\n }\n\n function getSelectValueArray(selectEl) {\n if (!selectEl) {\n return [];\n }\n var values = [];\n for (var i = 0; i < selectEl.options.length; i++) {\n if (selectEl.options[i].selected) {\n values.push(selectEl.options[i].value);\n }\n }\n return values;\n }\n\n function configValueToNative(configValue) {\n if (!configValue || typeof configValue !== 'object') {\n return null;\n }\n if (Object.prototype.hasOwnProperty.call(configValue, 'bool_value')) {\n return !!configValue.bool_value;\n }\n if (Object.prototype.hasOwnProperty.call(configValue, 'int64_value')) {\n return configValue.int64_value;\n }\n if (Object.prototype.hasOwnProperty.call(configValue, 'double_value')) {\n return configValue.double_value;\n }\n if (Object.prototype.hasOwnProperty.call(configValue, 'string_value')) {\n return configValue.string_value;\n }\n if (Object.prototype.hasOwnProperty.call(configValue, 'bytes_value')) {\n return configValue.bytes_value;\n }\n if (Object.prototype.hasOwnProperty.call(configValue, 'duration_value')) {\n return configValue.duration_value;\n }\n if (configValue.string_list && Array.isArray(configValue.string_list.values)) {\n return configValue.string_list.values.slice();\n }\n if (configValue.int64_list && Array.isArray(configValue.int64_list.values)) {\n return configValue.int64_list.values.slice();\n }\n if (configValue.double_list && Array.isArray(configValue.double_list.values)) {\n return configValue.double_list.values.slice();\n }\n if (configValue.bool_list && Array.isArray(configValue.bool_list.values)) {\n return configValue.bool_list.values.slice();\n }\n if (configValue.list_value && Array.isArray(configValue.list_value.values)) {\n return configValue.list_value.values.map(function(v) {\n return configValueToNative(v);\n });\n }\n if (configValue.map_value && configValue.map_value.fields) {\n var out = {};\n Object.keys(configValue.map_value.fields).forEach(function(k) {\n out[k] = configValueToNative(configValue.map_value.fields[k]);\n });\n return out;\n }\n return null;\n }\n\n function inferConfigValue(value) {\n if (value === null || value === undefined) {\n return { string_value: '' };\n }\n if (typeof value === 'boolean') {\n return { bool_value: value };\n }\n if (typeof value === 'number') {\n if (Number.isInteger(value)) {\n return { int64_value: String(value) };\n }\n return { double_value: value };\n }\n if (typeof value === 'string') {\n return { string_value: value };\n }\n if (Array.isArray(value)) {\n var listValues = value.map(function(item) {\n return inferConfigValue(item);\n });\n return { list_value: { values: listValues } };\n }\n if (typeof value === 'object') {\n var fields = {};\n Object.keys(value).forEach(function(key) {\n fields[key] = inferConfigValue(value[key]);\n });\n return { map_value: { fields: fields } };\n }\n return { string_value: String(value) };\n }\n\n function nativeToConfigValue(value, fieldType, widget, field) {\n var normalizedFieldType = normalizeEnum(fieldType);\n var normalizedWidget = normalizeEnum(widget);\n\n if (normalizedFieldType === 'CONFIG_FIELD_TYPE_BOOL') {\n return { bool_value: !!value };\n }\n\n if (normalizedFieldType === 'CONFIG_FIELD_TYPE_INT64') {\n if (value === '' || value === null || value === undefined) {\n return null;\n }\n var intValue = parseInt(value, 10);\n if (Number.isNaN(intValue)) {\n throw new Error('Invalid int64 value for field ' + field.name);\n }\n return { int64_value: String(intValue) };\n }\n\n if (normalizedFieldType === 'CONFIG_FIELD_TYPE_DOUBLE') {\n if (value === '' || value === null || value === undefined) {\n return null;\n }\n var doubleValue = parseFloat(value);\n if (Number.isNaN(doubleValue)) {\n throw new Error('Invalid number for field ' + field.name);\n }\n return { double_value: doubleValue };\n }\n\n if (normalizedFieldType === 'CONFIG_FIELD_TYPE_DURATION') {\n if (value === '' || value === null || value === undefined) {\n return null;\n }\n var text = String(value).trim();\n if (!text) {\n return null;\n }\n if (/^\\d+$/.test(text)) {\n text += 's';\n }\n return { duration_value: text };\n }\n\n if (normalizedFieldType === 'CONFIG_FIELD_TYPE_LIST') {\n if (value === '' || value === null || value === undefined) {\n return null;\n }\n\n if (normalizedWidget === 'CONFIG_WIDGET_MULTI_SELECT' && Array.isArray(value)) {\n return { string_list: { values: value } };\n }\n\n if (typeof value === 'string') {\n try {\n var parsed = JSON.parse(value);\n if (!Array.isArray(parsed)) {\n throw new Error('Expected JSON array');\n }\n return inferConfigValue(parsed);\n } catch (e) {\n throw new Error('Invalid JSON list for field ' + field.name + ': ' + e.message);\n }\n }\n return inferConfigValue(value);\n }\n\n if (normalizedFieldType === 'CONFIG_FIELD_TYPE_OBJECT') {\n if (value === '' || value === null || value === undefined) {\n return null;\n }\n if (typeof value === 'string') {\n try {\n var parsedObject = JSON.parse(value);\n if (!parsedObject || typeof parsedObject !== 'object' || Array.isArray(parsedObject)) {\n throw new Error('Expected JSON object');\n }\n return inferConfigValue(parsedObject);\n } catch (e) {\n throw new Error('Invalid JSON object for field ' + field.name + ': ' + e.message);\n }\n }\n return inferConfigValue(value);\n }\n\n if (normalizedFieldType === 'CONFIG_FIELD_TYPE_ENUM') {\n if (normalizedWidget === 'CONFIG_WIDGET_MULTI_SELECT') {\n if (!value || !value.length) {\n return null;\n }\n return { string_list: { values: value } };\n }\n if (value === '' || value === null || value === undefined) {\n return null;\n }\n return { string_value: String(value) };\n }\n\n if (value === '' || value === null || value === undefined) {\n return null;\n }\n\n return { string_value: String(value) };\n }\n\n function toInputID(scope, fieldName) {\n return 'plugin-' + scope + '-field-' + String(fieldName || '').replace(/[^a-zA-Z0-9_-]/g, '_');\n }\n\n function resolveFieldConfigValue(scope, field) {\n if (!field || !field.name) {\n return null;\n }\n var fromConfig = null;\n if (state.config) {\n if (scope === 'admin' && state.config.admin_config_values) {\n fromConfig = state.config.admin_config_values[field.name];\n }\n if (scope === 'worker' && state.config.worker_config_values) {\n fromConfig = state.config.worker_config_values[field.name];\n }\n }\n if (fromConfig) {\n return fromConfig;\n }\n\n var formDefaults = null;\n if (scope === 'admin' && state.descriptor && state.descriptor.admin_config_form && state.descriptor.admin_config_form.default_values) {\n formDefaults = state.descriptor.admin_config_form.default_values[field.name];\n }\n if (scope === 'worker' && state.descriptor && state.descriptor.worker_config_form && state.descriptor.worker_config_form.default_values) {\n formDefaults = state.descriptor.worker_config_form.default_values[field.name];\n }\n if (formDefaults) {\n return formDefaults;\n }\n\n if (scope === 'worker' && state.descriptor && state.descriptor.worker_default_values) {\n return state.descriptor.worker_default_values[field.name] || null;\n }\n\n return null;\n }\n\n function renderFieldInput(scope, field, value) {\n var inputID = toInputID(scope, field.name);\n var normalizedType = normalizeEnum(field.field_type);\n var normalizedWidget = normalizeEnum(field.widget);\n var input;\n\n if (normalizedType === 'CONFIG_FIELD_TYPE_BOOL' || normalizedWidget === 'CONFIG_WIDGET_TOGGLE') {\n input = document.createElement('input');\n input.type = 'checkbox';\n input.className = 'form-check-input';\n input.id = inputID;\n input.checked = !!value;\n } else if ((normalizedType === 'CONFIG_FIELD_TYPE_ENUM' && normalizedWidget === 'CONFIG_WIDGET_MULTI_SELECT') || normalizedWidget === 'CONFIG_WIDGET_MULTI_SELECT') {\n input = document.createElement('select');\n input.className = 'form-select';\n input.id = inputID;\n input.multiple = true;\n var selected = Array.isArray(value) ? value : [];\n var options = Array.isArray(field.options) ? field.options : [];\n for (var i = 0; i < options.length; i++) {\n var option = document.createElement('option');\n option.value = options[i].value || '';\n option.textContent = options[i].label || options[i].value || '';\n if (selected.indexOf(option.value) >= 0) {\n option.selected = true;\n }\n input.appendChild(option);\n }\n } else if (normalizedType === 'CONFIG_FIELD_TYPE_ENUM' || normalizedWidget === 'CONFIG_WIDGET_SELECT') {\n input = document.createElement('select');\n input.className = 'form-select';\n input.id = inputID;\n var blankOption = document.createElement('option');\n blankOption.value = '';\n blankOption.textContent = '-- select --';\n input.appendChild(blankOption);\n var enumOptions = Array.isArray(field.options) ? field.options : [];\n for (var j = 0; j < enumOptions.length; j++) {\n var enumOption = document.createElement('option');\n enumOption.value = enumOptions[j].value || '';\n enumOption.textContent = enumOptions[j].label || enumOptions[j].value || '';\n if (String(value) === enumOption.value) {\n enumOption.selected = true;\n }\n input.appendChild(enumOption);\n }\n } else if (normalizedType === 'CONFIG_FIELD_TYPE_INT64' || normalizedType === 'CONFIG_FIELD_TYPE_DOUBLE' || normalizedWidget === 'CONFIG_WIDGET_NUMBER') {\n input = document.createElement('input');\n input.type = 'number';\n if (normalizedType === 'CONFIG_FIELD_TYPE_DOUBLE') {\n input.step = 'any';\n }\n input.className = 'form-control';\n input.id = inputID;\n if (value !== null && value !== undefined && value !== '') {\n input.value = String(value);\n }\n } else if (normalizedType === 'CONFIG_FIELD_TYPE_LIST' || normalizedType === 'CONFIG_FIELD_TYPE_OBJECT' || normalizedWidget === 'CONFIG_WIDGET_TEXTAREA') {\n input = document.createElement('textarea');\n input.className = 'form-control';\n input.id = inputID;\n input.rows = 4;\n if (normalizedType === 'CONFIG_FIELD_TYPE_LIST' || normalizedType === 'CONFIG_FIELD_TYPE_OBJECT') {\n input.placeholder = normalizedType === 'CONFIG_FIELD_TYPE_LIST' ? '[...]' : '{...}';\n }\n if (value !== null && value !== undefined && value !== '') {\n if (typeof value === 'object') {\n input.value = JSON.stringify(value, null, 2);\n } else {\n input.value = String(value);\n }\n }\n } else {\n input = document.createElement('input');\n input.className = 'form-control';\n input.id = inputID;\n if (normalizedWidget === 'CONFIG_WIDGET_PASSWORD' || field.sensitive) {\n input.type = 'password';\n } else {\n input.type = 'text';\n }\n if (value !== null && value !== undefined && value !== '') {\n input.value = String(value);\n }\n }\n\n if (field.placeholder && input.tagName === 'INPUT') {\n input.placeholder = field.placeholder;\n }\n if (field.placeholder && input.tagName === 'TEXTAREA') {\n input.placeholder = field.placeholder;\n }\n\n if (field.required) {\n input.required = true;\n }\n if (field.read_only) {\n input.disabled = true;\n }\n\n return input;\n }\n\n function renderConfigForm(scope, rootID, form) {\n var root = document.getElementById(rootID);\n if (!root) {\n return;\n }\n\n root.innerHTML = '';\n if (!form || !Array.isArray(form.sections) || form.sections.length === 0) {\n root.innerHTML = '<div class=\"text-muted\">No fields provided by descriptor.</div>';\n return;\n }\n\n for (var s = 0; s < form.sections.length; s++) {\n var section = form.sections[s] || {};\n var sectionCard = document.createElement('div');\n sectionCard.className = 'card mb-3';\n\n var sectionHeader = document.createElement('div');\n sectionHeader.className = 'card-header py-2';\n sectionHeader.innerHTML = '<strong>' + escapeHtml(textOrDash(section.title || section.section_id)) + '</strong>';\n sectionCard.appendChild(sectionHeader);\n\n var sectionBody = document.createElement('div');\n sectionBody.className = 'card-body';\n\n if (section.description) {\n var sectionDescription = document.createElement('p');\n sectionDescription.className = 'text-muted small';\n sectionDescription.textContent = section.description;\n sectionBody.appendChild(sectionDescription);\n }\n\n var fields = Array.isArray(section.fields) ? section.fields : [];\n if (!fields.length) {\n var noFields = document.createElement('div');\n noFields.className = 'text-muted';\n noFields.textContent = 'No fields in this section.';\n sectionBody.appendChild(noFields);\n }\n\n for (var f = 0; f < fields.length; f++) {\n var field = fields[f] || {};\n if (!field.name) {\n continue;\n }\n\n var configValue = resolveFieldConfigValue(scope, field);\n var nativeValue = configValueToNative(configValue);\n\n var wrapper = document.createElement('div');\n wrapper.className = 'mb-3 plugin-field';\n wrapper.dataset.scope = scope;\n wrapper.dataset.fieldName = field.name;\n wrapper.dataset.fieldType = normalizeEnum(field.field_type);\n wrapper.dataset.widget = normalizeEnum(field.widget);\n wrapper.dataset.visibleWhenField = field.visible_when_field || '';\n wrapper.dataset.visibleWhenEquals = JSON.stringify(field.visible_when_equals || null);\n\n var label = document.createElement('label');\n label.className = 'form-label';\n label.setAttribute('for', toInputID(scope, field.name));\n label.innerHTML = escapeHtml(field.label || field.name) + (field.required ? ' <span class=\"text-danger\">*</span>' : '');\n wrapper.appendChild(label);\n\n var input = renderFieldInput(scope, field, nativeValue);\n wrapper.appendChild(input);\n\n if (field.description || field.help_text) {\n var help = document.createElement('div');\n help.className = 'form-text';\n help.textContent = field.help_text || field.description || '';\n wrapper.appendChild(help);\n }\n\n sectionBody.appendChild(wrapper);\n }\n\n sectionCard.appendChild(sectionBody);\n root.appendChild(sectionCard);\n }\n\n root.addEventListener('change', function() {\n applyVisibility(scope);\n });\n root.addEventListener('input', function() {\n applyVisibility(scope);\n });\n\n applyVisibility(scope);\n }\n\n function readRawFieldValue(scope, fieldName) {\n var input = document.getElementById(toInputID(scope, fieldName));\n if (!input) {\n return null;\n }\n if (input.tagName === 'SELECT' && input.multiple) {\n return getSelectValueArray(input);\n }\n if (input.type === 'checkbox') {\n return !!input.checked;\n }\n return input.value;\n }\n\n function compareVisibleValue(currentValue, expectedValueObject) {\n if (!expectedValueObject) {\n return true;\n }\n var expectedNative = configValueToNative(expectedValueObject);\n if (Array.isArray(expectedNative)) {\n if (!Array.isArray(currentValue)) {\n return false;\n }\n if (expectedNative.length !== currentValue.length) {\n return false;\n }\n for (var i = 0; i < expectedNative.length; i++) {\n if (String(expectedNative[i]) !== String(currentValue[i])) {\n return false;\n }\n }\n return true;\n }\n return String(currentValue) === String(expectedNative);\n }\n\n function applyVisibility(scope) {\n var fields = document.querySelectorAll('.plugin-field[data-scope=\"' + scope + '\"]');\n for (var i = 0; i < fields.length; i++) {\n var wrapper = fields[i];\n var dependsOn = wrapper.dataset.visibleWhenField;\n if (!dependsOn) {\n wrapper.classList.remove('plugin-field-hidden');\n continue;\n }\n\n var expectedRaw = null;\n try {\n expectedRaw = JSON.parse(wrapper.dataset.visibleWhenEquals || 'null');\n } catch (e) {\n expectedRaw = null;\n }\n var current = readRawFieldValue(scope, dependsOn);\n var visible = compareVisibleValue(current, expectedRaw);\n if (visible) {\n wrapper.classList.remove('plugin-field-hidden');\n } else {\n wrapper.classList.add('plugin-field-hidden');\n }\n }\n }\n\n function collectConfigValues(scope, form) {\n var out = {};\n if (!form || !Array.isArray(form.sections)) {\n return out;\n }\n\n for (var s = 0; s < form.sections.length; s++) {\n var section = form.sections[s] || {};\n var fields = Array.isArray(section.fields) ? section.fields : [];\n for (var f = 0; f < fields.length; f++) {\n var field = fields[f] || {};\n if (!field.name) {\n continue;\n }\n\n var wrapper = document.querySelector('.plugin-field[data-scope=\"' + scope + '\"][data-field-name=\"' + field.name + '\"]');\n if (wrapper && wrapper.classList.contains('plugin-field-hidden')) {\n continue;\n }\n\n var input = document.getElementById(toInputID(scope, field.name));\n if (!input) {\n continue;\n }\n\n var rawValue;\n if (input.tagName === 'SELECT' && input.multiple) {\n rawValue = getSelectValueArray(input);\n } else if (input.type === 'checkbox') {\n rawValue = !!input.checked;\n } else {\n rawValue = input.value;\n }\n\n if (field.required) {\n var missing = false;\n if (input.type === 'checkbox') {\n missing = false;\n } else if (Array.isArray(rawValue)) {\n missing = rawValue.length === 0;\n } else {\n missing = String(rawValue || '').trim() === '';\n }\n if (missing) {\n throw new Error('Missing required field: ' + (field.label || field.name));\n }\n }\n\n var converted = nativeToConfigValue(rawValue, field.field_type, field.widget, field);\n if (converted !== null) {\n out[field.name] = converted;\n }\n }\n }\n\n return out;\n }\n\n function renderDescriptorSummary() {\n var summary = document.getElementById('plugin-descriptor-summary');\n if (!state.descriptor) {\n summary.innerHTML = 'No descriptor loaded.';\n return;\n }\n\n var descriptor = state.descriptor;\n var html = '';\n html += '<div><strong>' + escapeHtml(textOrDash(descriptor.display_name || descriptor.job_type)) + '</strong></div>';\n html += '<div><small>Job Type: ' + escapeHtml(textOrDash(descriptor.job_type)) + '</small></div>';\n html += '<div><small>Descriptor Version: ' + escapeHtml(textOrDash(descriptor.descriptor_version)) + '</small></div>';\n if (descriptor.description) {\n html += '<div class=\"mt-1\">' + escapeHtml(descriptor.description) + '</div>';\n }\n summary.innerHTML = html;\n }\n\n function fillAdminSettings() {\n var runtimeConfig = (state.config && state.config.admin_runtime) ? state.config.admin_runtime : {};\n var defaults = (state.descriptor && state.descriptor.admin_runtime_defaults) ? state.descriptor.admin_runtime_defaults : {};\n\n function pickNumber(key) {\n if (runtimeConfig && runtimeConfig[key] !== undefined && runtimeConfig[key] !== null) {\n return runtimeConfig[key];\n }\n if (defaults && defaults[key] !== undefined && defaults[key] !== null) {\n return defaults[key];\n }\n return 0;\n }\n\n function pickBool(key) {\n if (runtimeConfig && runtimeConfig[key] !== undefined && runtimeConfig[key] !== null) {\n return !!runtimeConfig[key];\n }\n if (defaults && defaults[key] !== undefined && defaults[key] !== null) {\n return !!defaults[key];\n }\n return true;\n }\n\n document.getElementById('plugin-admin-enabled').checked = pickBool('enabled');\n document.getElementById('plugin-admin-detection-interval').value = String(pickNumber('detection_interval_seconds'));\n document.getElementById('plugin-admin-detection-timeout').value = String(pickNumber('detection_timeout_seconds'));\n document.getElementById('plugin-admin-max-runtime').value = String(pickNumber('job_type_max_runtime_seconds'));\n document.getElementById('plugin-admin-max-results').value = String(pickNumber('max_jobs_per_detection'));\n document.getElementById('plugin-admin-global-exec').value = String(pickNumber('global_execution_concurrency'));\n document.getElementById('plugin-admin-per-worker-exec').value = String(pickNumber('per_worker_execution_concurrency'));\n document.getElementById('plugin-admin-retry-limit').value = String(pickNumber('retry_limit'));\n document.getElementById('plugin-admin-retry-backoff').value = String(pickNumber('retry_backoff_seconds'));\n }\n\n function collectAdminSettings() {\n function getInt(id) {\n var raw = String(document.getElementById(id).value || '').trim();\n if (!raw) {\n return 0;\n }\n var parsed = parseInt(raw, 10);\n if (Number.isNaN(parsed) || parsed < 0) {\n throw new Error('Invalid number for ' + id);\n }\n return parsed;\n }\n\n return {\n enabled: !!document.getElementById('plugin-admin-enabled').checked,\n detection_interval_seconds: getInt('plugin-admin-detection-interval'),\n detection_timeout_seconds: getInt('plugin-admin-detection-timeout'),\n job_type_max_runtime_seconds: getInt('plugin-admin-max-runtime'),\n max_jobs_per_detection: getInt('plugin-admin-max-results'),\n global_execution_concurrency: getInt('plugin-admin-global-exec'),\n per_worker_execution_concurrency: getInt('plugin-admin-per-worker-exec'),\n retry_limit: getInt('plugin-admin-retry-limit'),\n retry_backoff_seconds: getInt('plugin-admin-retry-backoff'),\n };\n }\n\n function renderRunHistory(history) {\n var successBody = document.getElementById('plugin-runs-success-body');\n var errorBody = document.getElementById('plugin-runs-error-body');\n\n var successRuns = (history && Array.isArray(history.successful_runs)) ? history.successful_runs : [];\n var errorRuns = (history && Array.isArray(history.error_runs)) ? history.error_runs : [];\n\n if (!successRuns.length) {\n successBody.innerHTML = '<tr><td colspan=\"4\" class=\"text-muted\">No successful runs</td></tr>';\n } else {\n var successRows = '';\n for (var i = 0; i < successRuns.length; i++) {\n var run = successRuns[i] || {};\n successRows += '<tr>' +\n '<td><small>' + escapeHtml(parseTime(run.completed_at) || '-') + '</small></td>' +\n '<td>' + renderJobLink(run.job_id) + '</td>' +\n '<td><small>' + escapeHtml(textOrDash(run.worker_id)) + '</small></td>' +\n '<td><small>' + escapeHtml(formatDurationMs(run.duration_ms)) + '</small></td>' +\n '</tr>';\n }\n successBody.innerHTML = successRows;\n }\n\n if (!errorRuns.length) {\n errorBody.innerHTML = '<tr><td colspan=\"4\" class=\"text-muted\">No error runs</td></tr>';\n } else {\n var errorRows = '';\n for (var j = 0; j < errorRuns.length; j++) {\n var errorRun = errorRuns[j] || {};\n errorRows += '<tr>' +\n '<td><small>' + escapeHtml(parseTime(errorRun.completed_at) || '-') + '</small></td>' +\n '<td>' + renderJobLink(errorRun.job_id) + '</td>' +\n '<td><small>' + escapeHtml(textOrDash(errorRun.worker_id)) + '</small></td>' +\n '<td><small class=\"text-danger\">' + escapeHtml(textOrDash(errorRun.message)) + '</small></td>' +\n '</tr>';\n }\n errorBody.innerHTML = errorRows;\n }\n }\n\n function renderDetectionResult(data) {\n var root = document.getElementById('plugin-detection-results');\n if (!root) {\n return;\n }\n\n function normalizeProposals(payload) {\n if (!payload || typeof payload !== 'object') {\n return [];\n }\n if (Array.isArray(payload.proposals)) {\n return payload.proposals;\n }\n if (payload.proposals && typeof payload.proposals === 'object') {\n return Object.keys(payload.proposals).map(function(key) {\n return payload.proposals[key];\n }).filter(function(item) {\n return !!item;\n });\n }\n return [];\n }\n\n function proposalID(proposal) {\n return proposal.proposal_id || proposal.proposalId || proposal.id || '';\n }\n\n function proposalSummary(proposal) {\n return proposal.summary || proposal.title || proposalID(proposal) || 'Proposal';\n }\n\n function proposalDetail(proposal) {\n return proposal.detail || proposal.reason || proposal.message || '-';\n }\n\n function normalizeActivities(payload) {\n if (!payload || typeof payload !== 'object') {\n return [];\n }\n if (Array.isArray(payload.activities)) {\n return payload.activities;\n }\n return [];\n }\n\n function encodeDetails(details) {\n if (!details || typeof details !== 'object') {\n return '';\n }\n var text = '';\n try {\n text = JSON.stringify(details);\n } catch (e) {\n text = '';\n }\n if (!text) {\n return '';\n }\n if (text.length > 360) {\n text = text.slice(0, 360) + '...';\n }\n return text;\n }\n\n if (!data) {\n root.innerHTML = '<div class=\"text-muted\">No results.</div>';\n return;\n }\n\n var proposals = normalizeProposals(data);\n var activities = normalizeActivities(data);\n var responseCount = Number(data.count || 0);\n if (!Number.isFinite(responseCount) || responseCount < 0) {\n responseCount = proposals.length;\n }\n var requestID = data.request_id || data.requestId || '';\n var detectorWorkerID = data.detector_worker_id || data.detectorWorkerId || '';\n var totalProposals = Number(data.total_proposals || 0);\n if (!Number.isFinite(totalProposals) || totalProposals < 0) {\n totalProposals = responseCount;\n }\n\n var html = '';\n html += '<div class=\"mb-2\"><strong>Detection Run</strong></div>';\n if (requestID) {\n html += '<div><small>request_id: ' + escapeHtml(String(requestID)) + '</small></div>';\n }\n if (detectorWorkerID) {\n html += '<div><small>detector: ' + escapeHtml(String(detectorWorkerID)) + '</small></div>';\n }\n html += '<div><small>proposals: ' + escapeHtml(String(responseCount)) + ' / total: ' + escapeHtml(String(totalProposals)) + '</small></div>';\n if (data.error) {\n html += '<div class=\"mt-1 text-danger\"><small>' + escapeHtml(String(data.error)) + '</small></div>';\n }\n\n if (!proposals.length) {\n html += '<div class=\"mt-2 text-muted\">No proposals returned.</div>';\n } else {\n html += '<div class=\"mt-2 mb-1\"><strong>' + escapeHtml(String(proposals.length)) + '</strong> proposal(s)</div>';\n for (var i = 0; i < proposals.length; i++) {\n var proposal = proposals[i] || {};\n var pID = proposalID(proposal);\n var pSummary = proposalSummary(proposal);\n var pDetail = proposalDetail(proposal);\n var pPriority = proposal.priority;\n if (pPriority === null || pPriority === undefined || pPriority === '') {\n pPriority = '-';\n }\n html += '<div class=\"plugin-detection-item\">' +\n '<div class=\"fw-semibold\">' + escapeHtml(textOrDash(pSummary)) + '</div>' +\n '<div><small>proposal_id: ' + escapeHtml(textOrDash(pID)) + '</small></div>' +\n '<div><small>priority: ' + escapeHtml(textOrDash(pPriority)) + '</small></div>' +\n '<div><small>detail: ' + escapeHtml(textOrDash(pDetail)) + '</small></div>' +\n '</div>';\n }\n }\n\n if (activities.length) {\n html += '<hr class=\"my-2\"/>';\n html += '<div class=\"mb-2\"><strong>Detection Process</strong></div>';\n for (var j = 0; j < activities.length; j++) {\n var activity = activities[j] || {};\n var activityStage = activity.stage || '-';\n var activitySource = activity.source || '-';\n var activityMessage = activity.message || '-';\n var activityTime = parseTime(activity.occurred_at) || '-';\n var detailsText = encodeDetails(activity.details);\n html += '<div class=\"plugin-detection-item\">' +\n '<div class=\"fw-semibold\">' + escapeHtml(textOrDash(activityStage)) + '</div>' +\n '<div><small>source: ' + escapeHtml(textOrDash(activitySource)) + ' | at: ' + escapeHtml(activityTime) + '</small></div>' +\n '<div><small>' + escapeHtml(textOrDash(activityMessage)) + '</small></div>';\n if (detailsText) {\n html += '<div><small class=\"text-muted\">details: ' + escapeHtml(detailsText) + '</small></div>';\n }\n html += '</div>';\n }\n }\n\n root.innerHTML = html;\n }\n\n function getSelectedJobType() {\n return String(state.selectedJobType || '').trim();\n }\n\n function resetJobTypePanels() {\n state.loadedJobType = '';\n state.descriptor = null;\n state.config = null;\n document.getElementById('plugin-descriptor-summary').textContent = 'No descriptor loaded.';\n document.getElementById('plugin-admin-config-form').innerHTML = '<div class=\"text-muted\">No admin form loaded.</div>';\n document.getElementById('plugin-worker-config-form').innerHTML = '<div class=\"text-muted\">No worker form loaded.</div>';\n document.getElementById('plugin-config-updated-at').textContent = 'Not loaded';\n renderRunHistory(null);\n renderDetectionResult(null);\n }\n\n async function loadDescriptorAndConfig(jobType, forceRefresh) {\n if (!jobType) {\n return;\n }\n\n state.selectedJobType = jobType;\n renderNavigationState();\n\n var summary = document.getElementById('plugin-descriptor-summary');\n summary.textContent = 'Loading descriptor and config...';\n\n try {\n if (forceRefresh) {\n var refreshURL = '/api/plugin/job-types/' + encodePath(jobType) + '/schema?force_refresh=true';\n state.descriptor = await pluginRequest('POST', refreshURL, null);\n } else {\n try {\n state.descriptor = await pluginRequest('GET', '/api/plugin/job-types/' + encodePath(jobType) + '/descriptor');\n } catch (descriptorLoadError) {\n state.descriptor = await pluginRequest('POST', '/api/plugin/job-types/' + encodePath(jobType) + '/schema', null);\n }\n }\n } catch (schemaError) {\n state.loadedJobType = '';\n state.descriptor = null;\n summary.innerHTML = '<span class=\"text-danger\">Failed to load descriptor: ' + escapeHtml(schemaError.message) + '</span>';\n document.getElementById('plugin-admin-config-form').innerHTML = '<div class=\"text-muted\">No admin form loaded.</div>';\n document.getElementById('plugin-worker-config-form').innerHTML = '<div class=\"text-muted\">No worker form loaded.</div>';\n throw schemaError;\n }\n\n try {\n state.config = await pluginRequest('GET', '/api/plugin/job-types/' + encodePath(jobType) + '/config');\n } catch (configError) {\n state.config = null;\n notify('Failed to load config: ' + configError.message, 'error');\n }\n\n renderDescriptorSummary();\n fillAdminSettings();\n\n if (state.descriptor) {\n renderConfigForm('admin', 'plugin-admin-config-form', state.descriptor.admin_config_form || {});\n renderConfigForm('worker', 'plugin-worker-config-form', state.descriptor.worker_config_form || {});\n }\n\n if (state.config && state.config.updated_at) {\n document.getElementById('plugin-config-updated-at').textContent = 'Updated: ' + (parseTime(state.config.updated_at) || state.config.updated_at);\n } else {\n document.getElementById('plugin-config-updated-at').textContent = 'Not saved yet';\n }\n state.loadedJobType = jobType;\n\n await loadRunHistory(jobType);\n\n if (state.lastDetectionByJobType && state.lastDetectionByJobType[jobType]) {\n renderDetectionResult(state.lastDetectionByJobType[jobType]);\n } else {\n renderDetectionResult(null);\n }\n }\n\n async function loadRunHistory(jobType) {\n if (!jobType) {\n renderRunHistory(null);\n return;\n }\n try {\n var history = await pluginRequest('GET', '/api/plugin/job-types/' + encodePath(jobType) + '/runs');\n renderRunHistory(history);\n } catch (e) {\n renderRunHistory(null);\n notify('Failed to load run history: ' + e.message, 'error');\n }\n }\n\n async function saveConfig() {\n var jobType = state.selectedJobType || getSelectedJobType();\n if (!jobType) {\n notify('Select a job type first.', 'error');\n return;\n }\n if (!state.descriptor) {\n notify('Load descriptor before saving config.', 'error');\n return;\n }\n\n var payload;\n try {\n payload = {\n job_type: jobType,\n descriptor_version: state.descriptor.descriptor_version || 0,\n admin_runtime: collectAdminSettings(),\n admin_config_values: collectConfigValues('admin', state.descriptor.admin_config_form || {}),\n worker_config_values: collectConfigValues('worker', state.descriptor.worker_config_form || {}),\n };\n } catch (err) {\n notify(err.message, 'error');\n return;\n }\n\n try {\n state.config = await pluginRequest('PUT', '/api/plugin/job-types/' + encodePath(jobType) + '/config', payload);\n document.getElementById('plugin-config-updated-at').textContent = 'Updated: ' + (parseTime(state.config.updated_at) || state.config.updated_at || 'just now');\n notify('Config saved for ' + jobType, 'success');\n } catch (e) {\n notify('Failed to save config: ' + e.message, 'error');\n }\n }\n\n function getMaxResults() {\n var raw = String(document.getElementById('plugin-admin-max-results').value || '').trim();\n if (!raw) {\n return 0;\n }\n var parsed = parseInt(raw, 10);\n if (Number.isNaN(parsed) || parsed < 0) {\n return 0;\n }\n return parsed;\n }\n\n async function runDetection() {\n var jobType = state.selectedJobType || getSelectedJobType();\n if (!jobType) {\n notify('Select a job type first.', 'error');\n return;\n }\n\n try {\n var data = await pluginRequest('POST', '/api/plugin/job-types/' + encodePath(jobType) + '/detect', {\n max_results: getMaxResults(),\n });\n state.lastDetectionByJobType[jobType] = data;\n renderDetectionResult(data);\n } catch (e) {\n if (e && e.responseData) {\n state.lastDetectionByJobType[jobType] = e.responseData;\n renderDetectionResult(e.responseData);\n }\n notify('Detection failed: ' + e.message, 'error');\n return;\n }\n\n try {\n await refreshJobsAndActivities();\n } catch (refreshErr) {\n notify('Detection succeeded, but monitoring refresh failed: ' + refreshErr.message, 'error');\n }\n }\n\n async function runWorkflow() {\n var jobType = state.selectedJobType || getSelectedJobType();\n if (!jobType) {\n notify('Select a job type first.', 'error');\n return;\n }\n\n try {\n var data = await pluginRequest('POST', '/api/plugin/job-types/' + encodePath(jobType) + '/run', {\n max_results: getMaxResults(),\n });\n var resultRoot = document.getElementById('plugin-detection-results');\n resultRoot.innerHTML = '<div class=\"mb-2\"><strong>Workflow completed</strong></div>' +\n '<div>Detected: <strong>' + escapeHtml(String(data.detected_count || 0)) + '</strong></div>' +\n '<div>Ready to Execute: <strong>' + escapeHtml(String(data.ready_to_execute_count || 0)) + '</strong></div>' +\n '<div>Skipped (Already Active): <strong>' + escapeHtml(String(data.skipped_active_count || 0)) + '</strong></div>' +\n '<div>Executed: <strong>' + escapeHtml(String(data.executed_count || 0)) + '</strong></div>' +\n '<div class=\"text-success\">Success: ' + escapeHtml(String(data.success_count || 0)) + '</div>' +\n '<div class=\"text-danger\">Errors: ' + escapeHtml(String(data.error_count || 0)) + '</div>';\n await loadRunHistory(jobType);\n await refreshJobsAndActivities();\n } catch (e) {\n notify('Workflow run failed: ' + e.message, 'error');\n }\n }\n\n async function refreshJobsAndActivities() {\n var executionStateFilter = document.getElementById('plugin-monitor-job-state-filter');\n\n state.monitorExecutionJobState = executionStateFilter ? String(executionStateFilter.value || '').trim() : '';\n\n var allJobsPromise = pluginRequest('GET', '/api/plugin/jobs?limit=500');\n var allActivitiesPromise = pluginRequest('GET', '/api/plugin/activities?limit=500');\n var schedulerPromise = pluginRequest('GET', '/api/plugin/scheduler-states');\n var schedulerStatusPromise = pluginRequest('GET', '/api/plugin/scheduler-status');\n\n var allJobs = await allJobsPromise;\n var allActivities = await allActivitiesPromise;\n var schedulerStates = await schedulerPromise;\n var schedulerStatus = null;\n try {\n schedulerStatus = await schedulerStatusPromise;\n } catch (e) {\n schedulerStatus = null;\n }\n\n state.jobs = Array.isArray(allJobs) ? allJobs : [];\n state.activities = Array.isArray(allActivities) ? allActivities : [];\n state.allJobs = state.jobs;\n state.allActivities = state.activities;\n state.schedulerStates = Array.isArray(schedulerStates) ? schedulerStates : [];\n state.schedulerStatus = schedulerStatus && schedulerStatus.scheduler ? schedulerStatus.scheduler : null;\n renderQueueJobs();\n renderDetectionJobs();\n renderExecutionJobs();\n renderExecutionActivities();\n renderSchedulerStates();\n renderSchedulerStatus();\n renderStatus();\n renderJobTypeSummary();\n }\n\n async function refreshAll() {\n try {\n var previousSelectedJobType = state.selectedJobType;\n\n var workers = await pluginRequest('GET', '/api/plugin/workers');\n state.workers = Array.isArray(workers) ? workers : [];\n renderWorkers();\n\n var jobTypes = await pluginRequest('GET', '/api/plugin/job-types');\n state.jobTypes = Array.isArray(jobTypes) ? jobTypes : [];\n applyInitialNavigation();\n ensureActiveNavigation();\n renderTopTabs();\n renderNavigationState();\n\n if (!state.selectedJobType) {\n resetJobTypePanels();\n } else if (state.loadedJobType !== state.selectedJobType || previousSelectedJobType !== state.selectedJobType) {\n try {\n await loadDescriptorAndConfig(state.selectedJobType, false);\n } catch (loadError) {\n // Already rendered in UI.\n }\n }\n\n await refreshJobsAndActivities();\n } catch (e) {\n notify('Refresh failed: ' + e.message, 'error');\n }\n }\n\n function bindActions() {\n var monitorStateFilter = document.getElementById('plugin-monitor-job-state-filter');\n if (monitorStateFilter) {\n monitorStateFilter.addEventListener('change', function() {\n state.monitorExecutionJobState = String(monitorStateFilter.value || '').trim();\n renderExecutionJobs();\n });\n }\n\n var expireBtn = document.getElementById('plugin-expire-job-btn');\n if (expireBtn) {\n expireBtn.addEventListener('click', function() {\n var jobID = String(expireBtn.getAttribute('data-job-id') || '').trim();\n if (!jobID) {\n return;\n }\n expireJob(jobID);\n });\n }\n\n document.getElementById('plugin-refresh-all-btn').addEventListener('click', function() {\n refreshAll();\n });\n\n document.getElementById('plugin-refresh-schema-btn').addEventListener('click', async function() {\n var jobType = getSelectedJobType();\n if (!jobType) {\n notify('Select a job type first.', 'error');\n return;\n }\n try {\n await loadDescriptorAndConfig(jobType, true);\n notify('Schema refreshed for ' + jobType, 'success');\n } catch (e) {\n notify('Schema refresh failed: ' + e.message, 'error');\n }\n });\n\n document.getElementById('plugin-save-config-btn').addEventListener('click', function() {\n saveConfig();\n });\n\n document.getElementById('plugin-trigger-detection-btn').addEventListener('click', function() {\n runDetection();\n });\n\n document.getElementById('plugin-run-workflow-btn').addEventListener('click', function() {\n runWorkflow();\n });\n\n page.addEventListener('click', async function(event) {\n var target = event.target;\n if (!target) {\n return;\n }\n\n var topTab = target.closest('[data-plugin-top-tab]');\n if (topTab) {\n event.preventDefault();\n var topTabKey = String(topTab.getAttribute('data-plugin-top-tab') || '').trim();\n if (!topTabKey) {\n return;\n }\n if (topTabKey === 'overview') {\n state.activeTopTab = 'overview';\n renderNavigationState();\n return;\n }\n\n var jobType = parseJobTypeFromTopTab(topTabKey);\n if (!jobType) {\n return;\n }\n state.activeTopTab = topTabKey;\n state.selectedJobType = jobType;\n ensureActiveNavigation();\n renderNavigationState();\n if (state.loadedJobType !== jobType) {\n try {\n await loadDescriptorAndConfig(jobType, false);\n } catch (e) {\n // Already rendered in UI.\n }\n } else {\n if (state.lastDetectionByJobType && state.lastDetectionByJobType[jobType]) {\n renderDetectionResult(state.lastDetectionByJobType[jobType]);\n } else {\n renderDetectionResult(null);\n }\n await loadRunHistory(jobType);\n }\n renderQueueJobs();\n renderDetectionJobs();\n renderExecutionJobs();\n renderExecutionActivities();\n return;\n }\n\n var subTab = target.closest('[data-plugin-subtab]');\n if (subTab) {\n event.preventDefault();\n var subTabKey = normalizeSubTab(subTab.getAttribute('data-plugin-subtab'));\n state.activeSubTab = subTabKey;\n renderNavigationState();\n return;\n }\n\n var trigger = target.closest('.plugin-job-link');\n if (!trigger) {\n return;\n }\n event.preventDefault();\n var jobID = trigger.getAttribute('data-job-id');\n if (!jobID) {\n return;\n }\n openJobDetail(jobID);\n });\n }\n\n async function init() {\n bindActions();\n renderTopTabs();\n ensureActiveNavigation();\n renderNavigationState();\n await refreshAll();\n\n state.refreshTimer = setInterval(function() {\n refreshAll();\n }, 3000);\n }\n\n window.addEventListener('beforeunload', function() {\n if (state.refreshTimer) {\n clearInterval(state.refreshTimer);\n state.refreshTimer = null;\n }\n });\n\n init();\n })();\n </script>")
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "\"><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"d-flex justify-content-between align-items-center flex-wrap gap-2\"><div><h2 class=\"mb-0\"><i class=\"fas fa-plug me-2\"></i>Workers</h2><p class=\"text-muted mb-0\">Cluster-wide worker status, per-job configuration, detection, queue, and execution workflows.</p></div><div class=\"btn-group\"><button type=\"button\" class=\"btn btn-outline-secondary\" id=\"plugin-refresh-all-btn\"><i class=\"fas fa-sync-alt me-1\"></i>Refresh</button></div></div></div></div><div class=\"row mb-3\"><div class=\"col-12\"><ul class=\"nav nav-tabs\" id=\"plugin-top-tabs\"><li class=\"nav-item\"><button type=\"button\" class=\"nav-link active\" data-plugin-top-tab=\"overview\"><i class=\"fas fa-chart-line me-1\"></i>Overview</button></li></ul></div></div><div class=\"row mb-3 d-none\" id=\"plugin-subtab-row\"><div class=\"col-12\"><ul class=\"nav nav-pills gap-2\" id=\"plugin-subtabs\"><li class=\"nav-item\"><button type=\"button\" class=\"nav-link active\" data-plugin-subtab=\"configuration\"><i class=\"fas fa-sliders-h me-1\"></i>Configuration</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"detection\"><i class=\"fas fa-search me-1\"></i>Job Detection</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"queue\"><i class=\"fas fa-list me-1\"></i>Job Queue</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"execution\"><i class=\"fas fa-tasks me-1\"></i>Job Execution</button></li></ul></div></div><div class=\"plugin-section plugin-section-overview\"><div class=\"row mb-4\"><div class=\"col-md-3 mb-3\"><div class=\"card border-info h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Workers</div><h4 class=\"mb-0\" id=\"plugin-status-workers\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-warning h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Active Jobs</div><h4 class=\"mb-0\" id=\"plugin-status-active-jobs\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-success h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Activities (recent)</div><h4 class=\"mb-0\" id=\"plugin-status-activities\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-secondary h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Next Run</div><h4 class=\"mb-0 plugin-scheduler-next-run\">-</h4><div class=\"text-muted small plugin-scheduler-next-run-meta\"></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"fas fa-chart-bar me-2\"></i>Per Job Type Summary</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Active Jobs</th><th>Recent Activities</th></tr></thead> <tbody id=\"plugin-jobtype-summary-body\"><tr><td colspan=\"3\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"fas fa-clock me-2\"></i>Scheduler State</h5><small class=\"text-muted\">Sequential scheduler with per-job runtime limits</small></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Enabled</th><th>Detector</th><th>In Flight</th><th>Max Runtime</th><th>Exec Global</th><th>Exec/Worker</th><th>Executor Workers</th><th>Effective Exec</th><th>Last Run</th></tr></thead> <tbody id=\"plugin-scheduler-table-body\"><tr><td colspan=\"10\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"fas fa-users me-2\"></i>Workers</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\" style=\"max-height: 560px; overflow-y: auto;\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light sticky-top\"><tr><th>Worker</th><th>Address</th><th>Capabilities</th><th>Load</th></tr></thead> <tbody id=\"plugin-workers-table-body\"><tr><td colspan=\"4\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div></div><div class=\"plugin-section plugin-section-configuration\"><div class=\"row mb-4\"><div class=\"col-lg-8 mb-3\"><div class=\"card shadow-sm h-100\"><div class=\"card-header d-flex justify-content-between align-items-center\"><h5 class=\"mb-0\"><i class=\"fas fa-sliders-h me-2\"></i>Job Type Configuration</h5><small class=\"text-muted\" id=\"plugin-config-updated-at\">Not loaded</small></div><div class=\"card-body\"><div class=\"mb-3\"><div class=\"small text-muted\">Selected Job Type</div><div class=\"fw-semibold\" id=\"plugin-selected-job-type\">-</div></div><div class=\"mb-3\"><div class=\"d-flex justify-content-between align-items-center mb-2\"><h6 class=\"mb-0\">Descriptor</h6><button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" id=\"plugin-refresh-schema-btn\"><i class=\"fas fa-cloud-download-alt me-1\"></i>Refresh Schema</button></div><div class=\"alert alert-light border\" id=\"plugin-descriptor-summary\">Select a job type to load schema and config.</div></div><div class=\"mb-3\"><h6>Admin Config Form</h6><div id=\"plugin-admin-config-form\" class=\"plugin-form-root\"><div class=\"text-muted\">No admin form loaded.</div></div></div><div class=\"mb-3\"><h6>Worker Config Form</h6><div id=\"plugin-worker-config-form\" class=\"plugin-form-root\"><div class=\"text-muted\">No worker form loaded.</div></div></div><div class=\"d-flex flex-wrap gap-2\"><button type=\"button\" class=\"btn btn-primary\" id=\"plugin-save-config-btn\"><i class=\"fas fa-save me-1\"></i>Save Config</button> <button type=\"button\" class=\"btn btn-outline-primary\" id=\"plugin-trigger-detection-btn\"><i class=\"fas fa-search me-1\"></i>Run Detection</button> <button type=\"button\" class=\"btn btn-outline-success\" id=\"plugin-run-workflow-btn\"><i class=\"fas fa-play me-1\"></i>Run Detect + Execute</button></div></div></div></div><div class=\"col-lg-4 mb-3\"><div class=\"card shadow-sm h-100\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"fas fa-cogs me-2\"></i>Job Scheduling Settings</h5></div><div class=\"card-body\"><div class=\"row g-2\" id=\"plugin-admin-settings-form\"><div class=\"col-12\"><label class=\"form-label\" for=\"plugin-admin-enabled\">Enabled</label><div class=\"form-check form-switch mt-1\"><input class=\"form-check-input\" type=\"checkbox\" id=\"plugin-admin-enabled\"></div></div><div class=\"col-12\"><label class=\"form-label\" for=\"plugin-admin-detection-interval\">Detection Interval (s)</label> <input type=\"number\" class=\"form-control\" id=\"plugin-admin-detection-interval\" min=\"0\"><div class=\"form-text\">How often to check for new work.</div></div><div class=\"col-12\"><label class=\"form-label\" for=\"plugin-admin-detection-timeout\">Detection Timeout (s)</label> <input type=\"number\" class=\"form-control\" id=\"plugin-admin-detection-timeout\" min=\"0\"></div><div class=\"col-12\"><label class=\"form-label\" for=\"plugin-admin-max-runtime\">Job Type Max Runtime (s)</label> <input type=\"number\" class=\"form-control\" id=\"plugin-admin-max-runtime\" min=\"0\"></div><div class=\"col-12\"><label class=\"form-label\" for=\"plugin-admin-max-results\">Max Jobs / Detection</label> <input type=\"number\" class=\"form-control\" id=\"plugin-admin-max-results\" min=\"0\"></div><div class=\"col-12\"><label class=\"form-label\" for=\"plugin-admin-global-exec\">Global Execution Concurrency</label> <input type=\"number\" class=\"form-control\" id=\"plugin-admin-global-exec\" min=\"0\"></div><div class=\"col-12\"><label class=\"form-label\" for=\"plugin-admin-per-worker-exec\">Per Worker Concurrency</label> <input type=\"number\" class=\"form-control\" id=\"plugin-admin-per-worker-exec\" min=\"0\"></div><div class=\"col-12\"><label class=\"form-label\" for=\"plugin-admin-retry-limit\">Retry Limit</label> <input type=\"number\" class=\"form-control\" id=\"plugin-admin-retry-limit\" min=\"0\"></div><div class=\"col-12\"><label class=\"form-label\" for=\"plugin-admin-retry-backoff\">Retry Backoff (s)</label> <input type=\"number\" class=\"form-control\" id=\"plugin-admin-retry-backoff\" min=\"0\"></div></div></div></div><div class=\"card shadow-sm mt-3\"><div class=\"card-header d-flex justify-content-between align-items-center\"><h5 class=\"mb-0\"><i class=\"fas fa-hourglass-half me-2\"></i>Next Run</h5><small class=\"text-muted\">Scheduler</small></div><div class=\"card-body\"><div class=\"h5 mb-1 plugin-scheduler-next-run\">-</div><div class=\"text-muted small plugin-scheduler-next-run-meta\">Not scheduled</div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-lg-6 mb-3\"><div class=\"card shadow-sm h-100\"><div class=\"card-header d-flex justify-content-between align-items-center\"><h5 class=\"mb-0\"><i class=\"fas fa-clipboard-check me-2\"></i>Run History</h5><small class=\"text-muted\">Keep last 10 success + last 10 errors</small></div><div class=\"card-body\"><div class=\"row\"><div class=\"col-12 mb-3\"><h6 class=\"text-success\">Successful Runs</h6><div class=\"table-responsive\"><table class=\"table table-sm table-striped\"><thead><tr><th>Time</th><th>Job ID</th><th>Worker</th><th>Duration</th></tr></thead> <tbody id=\"plugin-runs-success-body\"><tr><td colspan=\"4\" class=\"text-muted\">No data</td></tr></tbody></table></div></div><div class=\"col-12\"><h6 class=\"text-danger\">Error Runs</h6><div class=\"table-responsive\"><table class=\"table table-sm table-striped\"><thead><tr><th>Time</th><th>Job ID</th><th>Worker</th><th>Error</th></tr></thead> <tbody id=\"plugin-runs-error-body\"><tr><td colspan=\"4\" class=\"text-muted\">No data</td></tr></tbody></table></div></div></div></div></div></div><div class=\"col-lg-6 mb-3\"><div class=\"card shadow-sm h-100\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"fas fa-lightbulb me-2\"></i>Detection Results</h5></div><div class=\"card-body\" id=\"plugin-detection-results\"><div class=\"text-muted\">Run detection to see proposals.</div></div></div></div></div></div><div class=\"plugin-section plugin-section-queue\"><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"fas fa-list me-2\"></i>Job Queue</h5><div class=\"d-flex gap-2 align-items-center flex-wrap\"><small class=\"text-muted\">States: pending/assigned/running</small></div></div><div class=\"card-body p-0\"><div class=\"table-responsive\" style=\"max-height: 560px; overflow-y: auto;\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light sticky-top\"><tr><th>Job ID</th><th>Type</th><th>State</th><th>Progress</th><th>Worker</th><th>Updated</th><th>Message</th></tr></thead> <tbody id=\"plugin-queue-jobs-table-body\"><tr><td colspan=\"7\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div></div><div class=\"plugin-section plugin-section-detection\"><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"fas fa-search me-2\"></i>Detection Jobs</h5><div class=\"small text-muted\">Detection activities for selected job type</div></div><div class=\"card-body p-0\"><div class=\"table-responsive\" style=\"max-height: 420px; overflow-y: auto;\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light sticky-top\"><tr><th>Time</th><th>Job Type</th><th>Request ID</th><th>Worker</th><th>Stage</th><th>Source</th><th>Message</th></tr></thead> <tbody id=\"plugin-detection-table-body\"><tr><td colspan=\"7\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div></div><div class=\"plugin-section plugin-section-execution\"><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"fas fa-tasks me-2\"></i>Execution Jobs</h5><div class=\"d-flex gap-2 align-items-center flex-wrap\"><select class=\"form-select form-select-sm\" id=\"plugin-monitor-job-state-filter\" style=\"min-width: 180px;\"><option value=\"\">All States</option> <option value=\"assigned\">Assigned</option> <option value=\"running\">Running</option> <option value=\"succeeded\">Succeeded</option> <option value=\"failed\">Failed</option> <option value=\"canceled\">Canceled</option></select></div></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job ID</th><th>Type</th><th>State</th><th>Progress</th><th>Worker</th><th>Updated</th><th>Message</th></tr></thead> <tbody id=\"plugin-execution-jobs-table-body\"><tr><td colspan=\"7\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"fas fa-stream me-2\"></i>Execution Activities</h5><small class=\"text-muted\">Non-detection events only</small></div><div class=\"card-body p-0\"><div class=\"table-responsive\" style=\"max-height: 420px; overflow-y: auto;\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light sticky-top\"><tr><th>Time</th><th>Job Type</th><th>Job ID</th><th>Source</th><th>Stage</th><th>Message</th></tr></thead> <tbody id=\"plugin-execution-activities-table-body\"><tr><td colspan=\"6\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div></div></div><div class=\"modal fade\" id=\"plugin-job-detail-modal\" tabindex=\"-1\" aria-labelledby=\"plugin-job-detail-modal-label\" aria-hidden=\"true\"><div class=\"modal-dialog modal-xl modal-dialog-scrollable\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"plugin-job-detail-modal-label\"><i class=\"fas fa-file-alt me-2\"></i>Job Detail</h5><div class=\"ms-auto me-2\"><button type=\"button\" class=\"btn btn-outline-danger btn-sm\" id=\"plugin-expire-job-btn\" disabled><i class=\"fas fa-stop-circle me-1\"></i>Expire Job</button></div><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\" id=\"plugin-job-detail-content\"><div class=\"text-muted\">Select a job to view details.</div></div></div></div></div><style>\n .plugin-section {\n display: none;\n }\n\n .plugin-section.plugin-section-active {\n display: block;\n }\n\n .plugin-form-root .card {\n border: 1px solid #dee2e6;\n }\n .plugin-form-root textarea {\n min-height: 12rem;\n }\n\n .plugin-field-hidden {\n display: none;\n }\n\n .plugin-capability-badge {\n font-size: 0.72rem;\n margin-right: 0.25rem;\n }\n\n .plugin-job-progress {\n min-width: 120px;\n }\n\n .plugin-detection-item {\n border: 1px solid #dee2e6;\n border-radius: 6px;\n padding: 0.5rem 0.75rem;\n margin-bottom: 0.5rem;\n background: #fbfcfd;\n }\n\n .plugin-job-link {\n text-decoration: none;\n }\n\n .plugin-job-detail-json {\n max-height: 220px;\n overflow: auto;\n background: #f8f9fa;\n border: 1px solid #dee2e6;\n border-radius: 6px;\n padding: 0.5rem;\n margin-bottom: 0;\n font-size: 0.82rem;\n }\n </style><script>\n (function() {\n var page = document.getElementById('plugin-page');\n if (!page) {\n return;\n }\n\n var state = {\n selectedJobType: '',\n jobTypes: [],\n lastDetectionByJobType: {},\n initialPage: String(page.getAttribute('data-plugin-page') || 'overview').trim().toLowerCase(),\n activeTopTab: 'overview',\n activeSubTab: 'configuration',\n initialNavigationApplied: false,\n monitorExecutionJobState: '',\n workers: [],\n jobs: [],\n activities: [],\n schedulerStates: [],\n schedulerStatus: null,\n allJobs: [],\n allActivities: [],\n loadedJobType: '',\n descriptor: null,\n config: null,\n refreshTimer: null,\n };\n\n function getCSRFToken() {\n var meta = document.querySelector('meta[name=\"csrf-token\"]');\n if (!meta) {\n return '';\n }\n return meta.getAttribute('content') || '';\n }\n\n function notify(message, level) {\n if (typeof window.showAlert === 'function') {\n window.showAlert(message, level || 'info');\n return;\n }\n if (level === 'error') {\n console.error(message);\n }\n alert(message);\n }\n\n async function readResponseJSON(response) {\n var bodyText = await response.text();\n if (!bodyText) {\n return {};\n }\n try {\n return JSON.parse(bodyText);\n } catch (e) {\n return { error: bodyText };\n }\n }\n\n async function pluginRequest(method, url, payload) {\n var headers = {};\n var requestOptions = {\n method: method,\n headers: headers,\n };\n\n if (payload !== undefined && payload !== null) {\n headers['Content-Type'] = 'application/json';\n requestOptions.body = JSON.stringify(payload);\n }\n\n if (method !== 'GET') {\n var csrf = getCSRFToken();\n if (csrf) {\n headers['X-CSRF-Token'] = csrf;\n }\n }\n\n var response = await fetch(url, requestOptions);\n var data = await readResponseJSON(response);\n if (!response.ok) {\n var message = (data && (data.error || data.message)) ? (data.error || data.message) : ('Request failed: ' + response.status);\n var requestError = new Error(message);\n requestError.responseData = data;\n requestError.responseStatus = response.status;\n throw requestError;\n }\n return data;\n }\n\n function textOrDash(value) {\n if (value === null || value === undefined || value === '') {\n return '-';\n }\n return String(value);\n }\n\n function escapeHtml(value) {\n if (value === null || value === undefined) {\n return '';\n }\n return String(value)\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#039;');\n }\n\n function encodePath(value) {\n return encodeURIComponent(value || '');\n }\n\n function normalizeEnum(value) {\n if (value === undefined || value === null) {\n return '';\n }\n return String(value).toUpperCase();\n }\n\n function parseTime(value) {\n if (!value) {\n return '';\n }\n var date = new Date(value);\n if (Number.isNaN(date.getTime())) {\n return '';\n }\n return date.toLocaleString();\n }\n\n function normalizeSubTab(value) {\n var normalized = String(value || '').toLowerCase();\n if (normalized === 'configuration' || normalized === 'detection' || normalized === 'queue' || normalized === 'execution') {\n return normalized;\n }\n return 'configuration';\n }\n\n // Parse a job type item (string or object) into a safe object shape\n function parseJobTypeItem(item) {\n var jobType = '';\n var displayName = '';\n \n if (typeof item === 'string') {\n jobType = String(item || '').trim();\n displayName = jobType;\n } else if (item && typeof item === 'object') {\n jobType = String(item.job_type || item.jobType || '').trim();\n displayName = String(item.display_name || item.displayName || jobType || '').trim();\n if (!displayName) {\n displayName = jobType;\n }\n }\n \n return { jobType: jobType, displayName: displayName };\n }\n\n function topTabKeyForJobType(jobType) {\n var normalized = String(jobType || '').trim();\n if (!normalized) {\n return '';\n }\n return 'job:' + normalized;\n }\n\n function parseJobTypeFromTopTab(tabKey) {\n var normalized = String(tabKey || '').trim();\n if (normalized.indexOf('job:') !== 0) {\n return '';\n }\n return normalized.slice(4);\n }\n\n function hasJobType(jobType) {\n var normalized = String(jobType || '').trim();\n if (!normalized) {\n return false;\n }\n var jobTypes = Array.isArray(state.jobTypes) ? state.jobTypes : [];\n for (var i = 0; i < jobTypes.length; i++) {\n var item = parseJobTypeItem(jobTypes[i]);\n if (item.jobType === normalized) {\n return true;\n }\n }\n return false;\n }\n\n function applyInitialNavigation() {\n if (state.initialNavigationApplied) {\n return;\n }\n state.initialNavigationApplied = true;\n state.activeSubTab = normalizeSubTab(state.initialPage);\n\n if (state.initialPage === 'overview') {\n state.activeTopTab = 'overview';\n return;\n }\n if (!Array.isArray(state.jobTypes) || state.jobTypes.length === 0) {\n state.activeTopTab = 'overview';\n return;\n }\n var firstItem = parseJobTypeItem(state.jobTypes[0]);\n state.selectedJobType = firstItem.jobType;\n state.activeTopTab = topTabKeyForJobType(state.selectedJobType);\n }\n\n function ensureActiveNavigation() {\n state.activeSubTab = normalizeSubTab(state.activeSubTab);\n\n if (state.selectedJobType && !hasJobType(state.selectedJobType)) {\n state.selectedJobType = '';\n state.descriptor = null;\n state.config = null;\n }\n\n var topTabJobType = parseJobTypeFromTopTab(state.activeTopTab);\n if (topTabJobType && !hasJobType(topTabJobType)) {\n state.activeTopTab = 'overview';\n topTabJobType = '';\n }\n\n if (state.activeTopTab === 'overview') {\n if (!state.selectedJobType && Array.isArray(state.jobTypes) && state.jobTypes.length > 0) {\n var item = parseJobTypeItem(state.jobTypes[0]);\n state.selectedJobType = item.jobType;\n }\n return;\n }\n\n if (!topTabJobType && state.selectedJobType) {\n topTabJobType = state.selectedJobType;\n }\n if (!topTabJobType && Array.isArray(state.jobTypes) && state.jobTypes.length > 0) {\n var item = parseJobTypeItem(state.jobTypes[0]);\n topTabJobType = item.jobType;\n }\n if (!topTabJobType) {\n state.activeTopTab = 'overview';\n return;\n }\n\n state.selectedJobType = topTabJobType;\n state.activeTopTab = topTabKeyForJobType(topTabJobType);\n }\n\n function renderTopTabs() {\n var root = document.getElementById('plugin-top-tabs');\n if (!root) {\n return;\n }\n\n var html = '' +\n '<li class=\"nav-item\">' +\n '<button type=\"button\" class=\"nav-link\" data-plugin-top-tab=\"overview\">' +\n '<i class=\"fas fa-chart-line me-1\"></i>Overview' +\n '</button>' +\n '</li>';\n\n var jobTypes = Array.isArray(state.jobTypes) ? state.jobTypes : [];\n for (var i = 0; i < jobTypes.length; i++) {\n var item = parseJobTypeItem(jobTypes[i]);\n var jobType = item.jobType;\n var displayName = item.displayName;\n \n if (!jobType) {\n continue;\n }\n html += '' +\n '<li class=\"nav-item\">' +\n '<button type=\"button\" class=\"nav-link\" data-plugin-top-tab=\"' + escapeHtml(topTabKeyForJobType(jobType)) + '\">' +\n escapeHtml(displayName) +\n '</button>' +\n '</li>';\n }\n root.innerHTML = html;\n }\n\n function renderNavigationState() {\n var selectedJobTypeLabel = document.getElementById('plugin-selected-job-type');\n if (selectedJobTypeLabel) {\n selectedJobTypeLabel.textContent = state.selectedJobType || '-';\n }\n\n var isOverview = state.activeTopTab === 'overview';\n var subtabRow = document.getElementById('plugin-subtab-row');\n if (subtabRow) {\n subtabRow.classList.toggle('d-none', isOverview);\n }\n\n var topTabs = document.querySelectorAll('#plugin-top-tabs [data-plugin-top-tab]');\n for (var i = 0; i < topTabs.length; i++) {\n var topTab = topTabs[i];\n var topKey = String(topTab.getAttribute('data-plugin-top-tab') || '');\n topTab.classList.toggle('active', topKey === state.activeTopTab);\n }\n\n var subTabs = document.querySelectorAll('#plugin-subtabs [data-plugin-subtab]');\n for (var j = 0; j < subTabs.length; j++) {\n var subTab = subTabs[j];\n var subKey = String(subTab.getAttribute('data-plugin-subtab') || '');\n subTab.classList.toggle('active', !isOverview && subKey === state.activeSubTab);\n }\n\n function toggleSection(sectionName, visible) {\n var section = document.querySelector('.plugin-section-' + sectionName);\n if (!section) {\n return;\n }\n section.classList.toggle('plugin-section-active', !!visible);\n }\n\n toggleSection('overview', isOverview);\n toggleSection('configuration', !isOverview && state.activeSubTab === 'configuration');\n toggleSection('detection', !isOverview && state.activeSubTab === 'detection');\n toggleSection('queue', !isOverview && state.activeSubTab === 'queue');\n toggleSection('execution', !isOverview && state.activeSubTab === 'execution');\n }\n\n function renderJobLink(jobID) {\n var normalized = String(jobID || '').trim();\n if (!normalized) {\n return '<small>-</small>';\n }\n return '<button type=\"button\" class=\"btn btn-link btn-sm p-0 align-baseline plugin-job-link\" data-job-id=\"' + escapeHtml(normalized) + '\">' + escapeHtml(normalized) + '</button>';\n }\n\n function toPrettyJson(value) {\n if (value === null || value === undefined || value === '') {\n return '';\n }\n if (typeof value === 'string') {\n return value;\n }\n try {\n return JSON.stringify(value, null, 2);\n } catch (e) {\n return String(value);\n }\n }\n\n function clonePlainObject(value) {\n if (!value || typeof value !== 'object') {\n return null;\n }\n try {\n return JSON.parse(JSON.stringify(value));\n } catch (e) {\n return null;\n }\n }\n\n function extractExecutionPlan(job) {\n if (!job || !job.parameters) {\n return null;\n }\n var plan = job.parameters.execution_plan;\n if (!plan) {\n return null;\n }\n if (typeof plan === 'string') {\n try {\n plan = JSON.parse(plan);\n } catch (e) {\n return null;\n }\n }\n if (typeof plan !== 'object' || Array.isArray(plan)) {\n return null;\n }\n return plan;\n }\n\n function removeExecutionPlanForDisplay(parameters) {\n var copy = clonePlainObject(parameters);\n if (!copy) {\n return parameters;\n }\n if (copy.execution_plan !== undefined) {\n delete copy.execution_plan;\n }\n if (Object.keys(copy).length === 0) {\n return null;\n }\n return copy;\n }\n\n function parseIntOrDefault(value, fallback) {\n var parsed = parseInt(value, 10);\n if (Number.isNaN(parsed)) {\n return fallback;\n }\n return parsed;\n }\n\n function normalizeShardIDs(value) {\n if (!Array.isArray(value)) {\n return [];\n }\n var out = [];\n for (var i = 0; i < value.length; i++) {\n var parsed = parseIntOrDefault(value[i], -1);\n if (parsed >= 0) {\n out.push(parsed);\n }\n }\n out.sort(function(a, b) { return a - b; });\n return out;\n }\n\n function classifyShardLabel(shardID, dataShardCount) {\n if (shardID < dataShardCount) {\n return {\n kind: 'data',\n label: String(shardID),\n className: 'bg-primary',\n title: 'Data shard ' + shardID,\n };\n }\n var parityIndex = shardID - dataShardCount;\n return {\n kind: 'parity',\n label: String(shardID),\n className: 'bg-warning text-dark',\n title: 'Parity shard ' + shardID + ' (index ' + parityIndex + ')',\n };\n }\n\n function renderShardBadges(shardIDs, dataShardCount) {\n if (!Array.isArray(shardIDs) || shardIDs.length === 0) {\n return '<span class=\"text-muted\">-</span>';\n }\n var html = '';\n for (var i = 0; i < shardIDs.length; i++) {\n var shard = classifyShardLabel(shardIDs[i], dataShardCount);\n html += '<span class=\"badge me-1 ' + shard.className + '\" title=\"' + escapeHtml(shard.title) + '\">' + escapeHtml(shard.label) + '</span>';\n }\n return html;\n }\n\n function renderExecutionPlan(plan) {\n if (!plan || typeof plan !== 'object') {\n return '';\n }\n\n var jobType = String(plan.job_type || '').trim().toLowerCase();\n if (jobType === 'volume_balance') {\n return renderBalanceExecutionPlan(plan);\n }\n if (jobType !== 'erasure_coding') {\n var fallbackText = toPrettyJson(plan);\n if (!fallbackText) {\n return '';\n }\n return '<div class=\"mb-3\"><h6>Execution Plan</h6><pre class=\"plugin-job-detail-json\">' + escapeHtml(fallbackText) + '</pre></div>';\n }\n\n var dataShards = parseIntOrDefault(plan.data_shards, 10);\n var parityShards = parseIntOrDefault(plan.parity_shards, 4);\n var totalShards = parseIntOrDefault(plan.total_shards, dataShards + parityShards);\n var sources = Array.isArray(plan.sources) ? plan.sources : [];\n var targets = Array.isArray(plan.targets) ? plan.targets : [];\n var assignments = Array.isArray(plan.shard_assignments) ? plan.shard_assignments : [];\n\n var html = '';\n html += '<div class=\"mb-3\"><h6>Execution Plan</h6>';\n html += '<div class=\"row g-2 mb-2\">' +\n '<div class=\"col-md-3\"><small><strong>Volume:</strong> ' + escapeHtml(textOrDash(plan.volume_id)) + '</small></div>' +\n '<div class=\"col-md-3\"><small><strong>Collection:</strong> ' + escapeHtml(textOrDash(plan.collection)) + '</small></div>' +\n '<div class=\"col-md-3\"><small><strong>Shards:</strong> ' + escapeHtml(String(dataShards)) + '+' + escapeHtml(String(parityShards)) + '</small></div>' +\n '<div class=\"col-md-3\"><small><strong>Total:</strong> ' + escapeHtml(String(totalShards)) + '</small></div>' +\n '</div>';\n\n html += '<div class=\"small text-muted mb-2\">' +\n '<span class=\"badge bg-primary me-1\">Data</span>' +\n '<span class=\"badge bg-warning text-dark me-2\">Parity</span>' +\n 'Source and target placement per shard.' +\n '</div>';\n\n function renderEndpointsTable(title, endpoints) {\n if (!endpoints.length) {\n return '<div class=\"mb-2\"><strong>' + escapeHtml(title) + ':</strong> <span class=\"text-muted\">none</span></div>';\n }\n var table = '<div class=\"table-responsive mb-2\"><table class=\"table table-sm table-striped mb-0\">' +\n '<thead><tr><th>#</th><th>Node</th><th>DC</th><th>Rack</th><th>Volume</th><th>Shards</th></tr></thead><tbody>';\n for (var i = 0; i < endpoints.length; i++) {\n var endpoint = endpoints[i] || {};\n var endpointShards = normalizeShardIDs(endpoint.shard_ids);\n table += '<tr>' +\n '<td>' + escapeHtml(String(i + 1)) + '</td>' +\n '<td><code>' + escapeHtml(textOrDash(endpoint.node)) + '</code></td>' +\n '<td>' + escapeHtml(textOrDash(endpoint.data_center)) + '</td>' +\n '<td>' + escapeHtml(textOrDash(endpoint.rack)) + '</td>' +\n '<td>' + escapeHtml(textOrDash(endpoint.volume_id)) + '</td>' +\n '<td>' + renderShardBadges(endpointShards, dataShards) + '</td>' +\n '</tr>';\n }\n table += '</tbody></table></div>';\n return '<div class=\"mb-2\"><strong>' + escapeHtml(title) + '</strong></div>' + table;\n }\n\n html += renderEndpointsTable('Sources', sources);\n html += renderEndpointsTable('Targets', targets);\n\n if (assignments.length) {\n html += '<div class=\"mb-2\"><strong>Shard Assignments</strong></div>';\n html += '<div class=\"table-responsive\"><table class=\"table table-sm table-striped mb-0\">' +\n '<thead><tr><th>Shard</th><th>Kind</th><th>Target</th><th>DC</th><th>Rack</th></tr></thead><tbody>';\n for (var j = 0; j < assignments.length; j++) {\n var assignment = assignments[j] || {};\n var shardID = parseIntOrDefault(assignment.shard_id, -1);\n if (shardID < 0) {\n continue;\n }\n var shard = classifyShardLabel(shardID, dataShards);\n html += '<tr>' +\n '<td><span class=\"badge ' + shard.className + '\">' + escapeHtml(shard.label) + '</span></td>' +\n '<td>' + escapeHtml(textOrDash(assignment.kind || shard.kind)) + '</td>' +\n '<td><code>' + escapeHtml(textOrDash(assignment.target_node)) + '</code></td>' +\n '<td>' + escapeHtml(textOrDash(assignment.target_data_center)) + '</td>' +\n '<td>' + escapeHtml(textOrDash(assignment.target_rack)) + '</td>' +\n '</tr>';\n }\n html += '</tbody></table></div>';\n }\n\n html += '</div>';\n return html;\n }\n\n function renderBalanceExecutionPlan(plan) {\n var html = '<div class=\"mb-3\"><h6>Execution Plan</h6>';\n var moves = Array.isArray(plan.moves) ? plan.moves : [];\n\n if (moves.length === 0) {\n // Single-move balance job\n var src = textOrDash(plan.source_node || plan.source_server);\n var dst = textOrDash(plan.target_node || plan.target_server);\n var vid = textOrDash(plan.volume_id);\n var col = textOrDash(plan.collection);\n html += `<div class=\"row g-2 mb-2\">\n <div class=\"col-md-3\"><small><strong>Volume:</strong> ${escapeHtml(vid)}</small></div>\n <div class=\"col-md-3\"><small><strong>Collection:</strong> ${escapeHtml(col)}</small></div>\n <div class=\"col-md-3\"><small><strong>Source:</strong> <code>${escapeHtml(src)}</code></small></div>\n <div class=\"col-md-3\"><small><strong>Target:</strong> <code>${escapeHtml(dst)}</code></small></div>\n </div>`;\n } else {\n // Batch balance job\n html += '<div class=\"mb-2\"><span class=\"badge bg-info\">' + escapeHtml(String(moves.length)) + ' moves</span></div>';\n html += '<div class=\"table-responsive\"><table class=\"table table-sm table-striped mb-0\">' +\n '<thead><tr><th>#</th><th>Volume</th><th>Source</th><th>Target</th><th>Collection</th></tr></thead><tbody>';\n for (var i = 0; i < moves.length; i++) {\n var move = moves[i] || {};\n html += `<tr>\n <td>${escapeHtml(String(i + 1))}</td>\n <td>${escapeHtml(textOrDash(move.volume_id))}</td>\n <td><code>${escapeHtml(textOrDash(move.source_node))}</code></td>\n <td><code>${escapeHtml(textOrDash(move.target_node))}</code></td>\n <td>${escapeHtml(textOrDash(move.collection))}</td>\n </tr>`;\n }\n html += '</tbody></table></div>';\n }\n\n html += '</div>';\n return html;\n }\n\n function isActiveJobState(candidateState) {\n var jobState = candidateState;\n if (candidateState && typeof candidateState === 'object' && candidateState.state !== undefined) {\n jobState = candidateState.state;\n }\n var st = String(jobState || '').toLowerCase();\n return st === 'job_state_pending' || st === 'job_state_assigned' || st === 'job_state_running' ||\n st === 'pending' || st === 'assigned' || st === 'running' || st === 'in_progress';\n }\n\n function setExpireButtonState(job) {\n var expireBtn = document.getElementById('plugin-expire-job-btn');\n if (!expireBtn) {\n return;\n }\n var jobID = job && job.job_id ? String(job.job_id) : '';\n var active = isActiveJobState(job);\n expireBtn.setAttribute('data-job-id', jobID);\n expireBtn.disabled = !jobID || !active;\n if (!jobID) {\n expireBtn.title = 'Select a job to expire.';\n } else if (!active) {\n expireBtn.title = 'Job is not active.';\n } else {\n expireBtn.title = 'Expire job to unblock scheduling.';\n }\n }\n\n async function expireJob(jobID) {\n var normalizedJobID = String(jobID || '').trim();\n if (!normalizedJobID) {\n return;\n }\n\n var reason = window.prompt('Expire job ' + normalizedJobID + '? Optional reason:', 'job expired by admin request');\n if (reason === null) {\n return;\n }\n\n var expireBtn = document.getElementById('plugin-expire-job-btn');\n if (expireBtn) {\n expireBtn.disabled = true;\n }\n\n try {\n var response = await pluginRequest('POST', '/api/plugin/jobs/' + encodePath(normalizedJobID) + '/expire', {\n reason: reason,\n });\n if (response && response.expired === false) {\n notify(response.message || 'Job is not active.', 'info');\n } else {\n notify('Job expired: ' + normalizedJobID, 'success');\n }\n await refreshJobsAndActivities();\n await openJobDetail(normalizedJobID);\n } catch (e) {\n notify('Failed to expire job: ' + e.message, 'error');\n }\n }\n\n async function openJobDetail(jobID) {\n var normalizedJobID = String(jobID || '').trim();\n if (!normalizedJobID) {\n return;\n }\n\n var modalElement = document.getElementById('plugin-job-detail-modal');\n var contentRoot = document.getElementById('plugin-job-detail-content');\n if (!modalElement || !contentRoot) {\n return;\n }\n\n var modal;\n if (window.bootstrap && window.bootstrap.Modal) {\n modal = window.bootstrap.Modal.getOrCreateInstance(modalElement);\n }\n if (modal) {\n modal.show();\n }\n\n setExpireButtonState(null);\n contentRoot.innerHTML = '<div class=\"text-muted\">Loading job detail...</div>';\n try {\n var detail = await pluginRequest('GET', '/api/plugin/jobs/' + encodePath(normalizedJobID) + '/detail?activity_limit=500&related_limit=20');\n var job = (detail && detail.job) ? detail.job : {};\n setExpireButtonState(job);\n var runRecord = detail && detail.run_record ? detail.run_record : null;\n var activities = (detail && Array.isArray(detail.activities)) ? detail.activities : [];\n var relatedJobs = (detail && Array.isArray(detail.related_jobs)) ? detail.related_jobs : [];\n var html = '';\n\n html += '<div class=\"row g-3 mb-3\">' +\n '<div class=\"col-lg-8\">' +\n '<div><strong>Job ID:</strong> ' + escapeHtml(textOrDash(job.job_id || normalizedJobID)) + '</div>' +\n '<div><strong>Type:</strong> ' + escapeHtml(textOrDash(job.job_type)) + '</div>' +\n '<div><strong>State:</strong> ' + escapeHtml(textOrDash(job.state)) + '</div>' +\n '<div><strong>Worker:</strong> ' + escapeHtml(textOrDash(job.worker_id)) + '</div>' +\n '<div><strong>Updated:</strong> ' + escapeHtml(parseTime(job.updated_at) || '-') + '</div>' +\n '</div>' +\n '<div class=\"col-lg-4\">' +\n '<div><strong>Attempt:</strong> ' + escapeHtml(textOrDash(job.attempt)) + '</div>' +\n '<div><strong>Progress:</strong> ' + escapeHtml(String(Math.round(Number(job.progress || 0)))) + '%</div>' +\n '<div><strong>Created:</strong> ' + escapeHtml(parseTime(job.created_at) || '-') + '</div>' +\n '<div><strong>Completed:</strong> ' + escapeHtml(parseTime(job.completed_at) || '-') + '</div>' +\n '</div>' +\n '</div>';\n\n if (job.summary) {\n html += '<div class=\"mb-2\"><strong>Summary:</strong> ' + escapeHtml(String(job.summary)) + '</div>';\n }\n if (job.detail) {\n html += '<div class=\"mb-2\"><strong>Detail:</strong> ' + escapeHtml(String(job.detail)) + '</div>';\n }\n if (job.message) {\n html += '<div class=\"mb-2\"><strong>Message:</strong> ' + escapeHtml(String(job.message)) + '</div>';\n }\n if (job.error_message) {\n html += '<div class=\"mb-2 text-danger\"><strong>Error:</strong> ' + escapeHtml(String(job.error_message)) + '</div>';\n }\n if (job.result_summary) {\n html += '<div class=\"mb-2\"><strong>Result:</strong> ' + escapeHtml(String(job.result_summary)) + '</div>';\n }\n\n var executionPlan = extractExecutionPlan(job);\n if (executionPlan) {\n html += renderExecutionPlan(executionPlan);\n }\n\n var parametersText = toPrettyJson(removeExecutionPlanForDisplay(job.parameters));\n if (parametersText) {\n html += '<div class=\"mb-3\"><h6>Parameters</h6><pre class=\"plugin-job-detail-json\">' + escapeHtml(parametersText) + '</pre></div>';\n }\n var labelsText = toPrettyJson(job.labels);\n if (labelsText) {\n html += '<div class=\"mb-3\"><h6>Labels</h6><pre class=\"plugin-job-detail-json\">' + escapeHtml(labelsText) + '</pre></div>';\n }\n var outputsText = toPrettyJson(job.result_output_values);\n if (outputsText) {\n html += '<div class=\"mb-3\"><h6>Result Output Values</h6><pre class=\"plugin-job-detail-json\">' + escapeHtml(outputsText) + '</pre></div>';\n }\n\n if (runRecord) {\n html += '<div class=\"mb-3\"><h6>Run Record</h6>' +\n '<div><strong>Outcome:</strong> ' + escapeHtml(textOrDash(runRecord.outcome)) + '</div>' +\n '<div><strong>Duration:</strong> ' + escapeHtml(formatDurationMs(runRecord.duration_ms)) + '</div>' +\n '<div><strong>Completed:</strong> ' + escapeHtml(parseTime(runRecord.completed_at) || '-') + '</div>' +\n '<div><strong>Message:</strong> ' + escapeHtml(textOrDash(runRecord.message)) + '</div>' +\n '</div>';\n }\n\n html += '<h6 class=\"mt-3\">Activity Timeline</h6>';\n if (!activities.length) {\n html += '<div class=\"text-muted mb-3\">No activity records.</div>';\n } else {\n html += '<div class=\"table-responsive mb-3\"><table class=\"table table-sm table-striped\">' +\n '<thead><tr><th>Time</th><th>Stage</th><th>Source</th><th>Worker</th><th>Message</th></tr></thead><tbody>';\n for (var i = 0; i < activities.length; i++) {\n var activity = activities[i] || {};\n html += '<tr>' +\n '<td><small>' + escapeHtml(parseTime(activity.occurred_at) || '-') + '</small></td>' +\n '<td>' + escapeHtml(textOrDash(activity.stage)) + '</td>' +\n '<td>' + escapeHtml(textOrDash(activity.source)) + '</td>' +\n '<td>' + escapeHtml(textOrDash(activity.worker_id)) + '</td>' +\n '<td><small>' + escapeHtml(textOrDash(activity.message)) + '</small></td>' +\n '</tr>';\n }\n html += '</tbody></table></div>';\n }\n\n if (relatedJobs.length) {\n html += '<h6>Related Jobs</h6><div class=\"table-responsive\"><table class=\"table table-sm table-hover\">' +\n '<thead><tr><th>Job ID</th><th>State</th><th>Worker</th><th>Updated</th></tr></thead><tbody>';\n for (var j = 0; j < relatedJobs.length; j++) {\n var related = relatedJobs[j] || {};\n html += '<tr>' +\n '<td><small>' + escapeHtml(textOrDash(related.job_id)) + '</small></td>' +\n '<td>' + escapeHtml(textOrDash(related.state)) + '</td>' +\n '<td>' + escapeHtml(textOrDash(related.worker_id)) + '</td>' +\n '<td><small>' + escapeHtml(parseTime(related.updated_at) || '-') + '</small></td>' +\n '</tr>';\n }\n html += '</tbody></table></div>';\n }\n\n contentRoot.innerHTML = html;\n } catch (e) {\n setExpireButtonState(null);\n contentRoot.innerHTML = '<div class=\"alert alert-danger mb-0\">Failed to load job detail: ' + escapeHtml(e.message) + '</div>';\n }\n }\n\n function formatDurationMs(value) {\n var ms = Number(value || 0);\n if (!Number.isFinite(ms) || ms <= 0) {\n return '-';\n }\n if (ms < 1000) {\n return ms + 'ms';\n }\n var sec = Math.floor(ms / 1000);\n var remainMs = ms % 1000;\n if (sec < 60) {\n return sec + '.' + String(Math.floor(remainMs / 100)) + 's';\n }\n var min = Math.floor(sec / 60);\n var remainSec = sec % 60;\n return min + 'm ' + remainSec + 's';\n }\n\n function getWorkerField(worker, name) {\n if (!worker) {\n return null;\n }\n if (worker[name] !== undefined) {\n return worker[name];\n }\n var camel = name.charAt(0).toUpperCase() + name.slice(1);\n if (worker[camel] !== undefined) {\n return worker[camel];\n }\n return null;\n }\n\n function renderStatus() {\n var allJobs = Array.isArray(state.allJobs) ? state.allJobs : [];\n var allActivities = Array.isArray(state.allActivities) ? state.allActivities : [];\n\n var activeCount = allJobs.filter(function(job) {\n return isActiveJobState(job);\n }).length;\n\n document.getElementById('plugin-status-workers').textContent = String(state.workers.length);\n document.getElementById('plugin-status-active-jobs').textContent = String(activeCount);\n document.getElementById('plugin-status-activities').textContent = String(allActivities.length);\n }\n\n function renderJobTypeSummary() {\n var tbody = document.getElementById('plugin-jobtype-summary-body');\n if (!tbody) {\n return;\n }\n\n var activeByType = {};\n var activityByType = {};\n\n var allJobs = Array.isArray(state.allJobs) ? state.allJobs : [];\n var allActivities = Array.isArray(state.allActivities) ? state.allActivities : [];\n\n for (var i = 0; i < allJobs.length; i++) {\n var job = allJobs[i] || {};\n var jobType = String(job.job_type || '').trim();\n if (!jobType) {\n continue;\n }\n var isActive = isActiveJobState(job);\n if (!isActive) {\n continue;\n }\n if (!activeByType[jobType]) {\n activeByType[jobType] = 0;\n }\n activeByType[jobType]++;\n }\n\n for (var j = 0; j < allActivities.length; j++) {\n var activity = allActivities[j] || {};\n var activityJobType = String(activity.job_type || '').trim();\n if (!activityJobType) {\n continue;\n }\n if (!activityByType[activityJobType]) {\n activityByType[activityJobType] = 0;\n }\n activityByType[activityJobType]++;\n }\n\n var known = Array.isArray(state.jobTypes) ? state.jobTypes.slice() : [];\n var seen = {};\n var jobTypes = [];\n\n for (var k = 0; k < known.length; k++) {\n var item = parseJobTypeItem(known[k]);\n var knownType = item && item.jobType ? String(item.jobType).trim() : '';\n if (!knownType || seen[knownType]) {\n continue;\n }\n seen[knownType] = true;\n jobTypes.push(knownType);\n }\n\n Object.keys(activeByType).forEach(function(jobType) {\n if (!seen[jobType]) {\n seen[jobType] = true;\n jobTypes.push(jobType);\n }\n });\n Object.keys(activityByType).forEach(function(jobType) {\n if (!seen[jobType]) {\n seen[jobType] = true;\n jobTypes.push(jobType);\n }\n });\n\n jobTypes.sort();\n\n if (jobTypes.length === 0) {\n tbody.innerHTML = '<tr><td colspan=\\\"3\\\" class=\\\"text-muted text-center py-3\\\">No job types discovered</td></tr>';\n return;\n }\n\n var rows = '';\n for (var m = 0; m < jobTypes.length; m++) {\n var rowType = jobTypes[m];\n rows += '<tr>' +\n '<td>' + escapeHtml(rowType) + '</td>' +\n '<td><span class=\\\"badge bg-warning text-dark\\\">' + escapeHtml(String(activeByType[rowType] || 0)) + '</span></td>' +\n '<td><span class=\\\"badge bg-info\\\">' + escapeHtml(String(activityByType[rowType] || 0)) + '</span></td>' +\n '</tr>';\n }\n tbody.innerHTML = rows;\n }\n\n function computeEffectiveExecutionCapacity(globalExec, perWorkerExec, executorWorkers) {\n var capacities = [];\n if (globalExec > 0) {\n capacities.push(globalExec);\n }\n var workerCapacity = perWorkerExec > 0 && executorWorkers > 0 ? (perWorkerExec * executorWorkers) : 0;\n if (workerCapacity > 0) {\n capacities.push(workerCapacity);\n }\n if (!capacities.length) {\n return 0;\n }\n var effective = capacities[0];\n for (var i = 1; i < capacities.length; i++) {\n if (capacities[i] < effective) {\n effective = capacities[i];\n }\n }\n return effective;\n }\n\n function renderSchedulerStates() {\n var tbody = document.getElementById('plugin-scheduler-table-body');\n if (!tbody) {\n return;\n }\n\n var states = Array.isArray(state.schedulerStates) ? state.schedulerStates : [];\n if (!states.length) {\n tbody.innerHTML = '<tr><td colspan=\"10\" class=\"text-muted text-center py-3\">No scheduler state available</td></tr>';\n return;\n }\n\n var rows = '';\n for (var i = 0; i < states.length; i++) {\n var item = states[i] || {};\n var enabled = !!item.enabled;\n var inFlight = !!item.detection_in_flight;\n var detector = item.detector_available ? textOrDash(item.detector_worker_id) : 'No detector';\n var maxRuntimeSeconds = Number(item.job_type_max_runtime_seconds || 0);\n var maxRuntimeText = maxRuntimeSeconds > 0 ? (String(maxRuntimeSeconds) + 's') : '-';\n var globalExec = Number(item.global_execution_concurrency || 0);\n var perWorkerExec = Number(item.per_worker_execution_concurrency || 0);\n var executorWorkers = Number(item.executor_worker_count || 0);\n var effectiveExec = computeEffectiveExecutionCapacity(globalExec, perWorkerExec, executorWorkers);\n var globalExecText = enabled ? String(globalExec) : '-';\n var perWorkerExecText = enabled ? String(perWorkerExec) : '-';\n var executorWorkersText = enabled ? String(executorWorkers) : '-';\n var effectiveExecText = enabled ? String(effectiveExec) : '-';\n var lastRunStatus = textOrDash(item.last_run_status);\n var lastRunTime = parseTime(item.last_run_completed_at);\n var lastRunText = '-';\n if (lastRunStatus !== '-' || lastRunTime) {\n var statusLabel = lastRunStatus !== '-' ? lastRunStatus : 'run';\n lastRunText = lastRunTime ? (statusLabel + ' @ ' + lastRunTime) : statusLabel;\n }\n\n var enabledBadge = enabled ? '<span class=\"badge bg-success\">Enabled</span>' : '<span class=\"badge bg-secondary\">Disabled</span>';\n var inFlightBadge = inFlight ? '<span class=\"badge bg-warning text-dark\">Yes</span>' : '<span class=\"badge bg-light text-dark\">No</span>';\n var policyErrorHtml = '';\n if (item.policy_error) {\n policyErrorHtml = '<div><small class=\"text-danger\">' + escapeHtml(String(item.policy_error)) + '</small></div>';\n }\n\n rows += '<tr>' +\n '<td>' + escapeHtml(textOrDash(item.job_type)) + policyErrorHtml + '</td>' +\n '<td>' + enabledBadge + '</td>' +\n '<td><small>' + escapeHtml(detector) + '</small></td>' +\n '<td>' + inFlightBadge + '</td>' +\n '<td><small>' + escapeHtml(maxRuntimeText) + '</small></td>' +\n '<td><small>' + escapeHtml(globalExecText) + '</small></td>' +\n '<td><small>' + escapeHtml(perWorkerExecText) + '</small></td>' +\n '<td><small>' + escapeHtml(executorWorkersText) + '</small></td>' +\n '<td><small>' + escapeHtml(effectiveExecText) + '</small></td>' +\n '<td><small>' + escapeHtml(lastRunText) + '</small></td>' +\n '</tr>';\n }\n\n tbody.innerHTML = rows;\n }\n\n function renderSchedulerStatus() {\n var valueNodes = document.querySelectorAll('.plugin-scheduler-next-run');\n if (!valueNodes.length) {\n return;\n }\n var metaNodes = document.querySelectorAll('.plugin-scheduler-next-run-meta');\n var status = state.schedulerStatus || {};\n var nextRun = parseTime(status.next_detection_at);\n var display = nextRun || '-';\n valueNodes.forEach(function(node) {\n node.textContent = display;\n });\n var metaText = nextRun ? 'Local time' : 'Not scheduled';\n if (metaNodes.length) {\n metaNodes.forEach(function(node) {\n node.textContent = metaText;\n });\n }\n }\n\n function renderWorkers() {\n var tbody = document.getElementById('plugin-workers-table-body');\n if (!state.workers.length) {\n tbody.innerHTML = '<tr><td colspan=\"4\" class=\"text-muted text-center py-3\">No connected workers</td></tr>';\n return;\n }\n\n var rows = '';\n for (var i = 0; i < state.workers.length; i++) {\n var worker = state.workers[i];\n var workerID = textOrDash(getWorkerField(worker, 'workerID'));\n var address = textOrDash(getWorkerField(worker, 'address'));\n var caps = getWorkerField(worker, 'capabilities') || {};\n var capBadges = [];\n\n Object.keys(caps).sort().forEach(function(jobType) {\n var cap = caps[jobType] || {};\n var labels = [];\n if (cap.can_detect) {\n labels.push('D');\n }\n if (cap.can_execute) {\n labels.push('E');\n }\n var text = jobType;\n if (labels.length) {\n text += ' (' + labels.join('/') + ')';\n }\n capBadges.push('<span class=\"badge bg-secondary plugin-capability-badge\">' + escapeHtml(text) + '</span>');\n });\n\n if (!capBadges.length) {\n capBadges.push('<span class=\"text-muted\">-</span>');\n }\n\n var heartbeat = getWorkerField(worker, 'heartbeat') || {};\n var detUsed = Number(heartbeat.detection_slots_used || heartbeat.DetectionSlotsUsed || 0);\n var detTotal = Number(heartbeat.detection_slots_total || heartbeat.DetectionSlotsTotal || 0);\n var execUsed = Number(heartbeat.execution_slots_used || heartbeat.ExecutionSlotsUsed || 0);\n var execTotal = Number(heartbeat.execution_slots_total || heartbeat.ExecutionSlotsTotal || 0);\n var runningWork = heartbeat.running_work || heartbeat.RunningWork || [];\n var queuedByType = heartbeat.queued_jobs_by_type || heartbeat.QueuedJobsByType || {};\n var queuedTotal = 0;\n Object.keys(queuedByType || {}).forEach(function(jobType) {\n var queuedCount = Number(queuedByType[jobType] || 0);\n if (Number.isFinite(queuedCount) && queuedCount > 0) {\n queuedTotal += queuedCount;\n }\n });\n var loadLines = [];\n loadLines.push('Detect: ' + String(detUsed) + '/' + String(detTotal));\n loadLines.push('Execute: ' + String(execUsed) + '/' + String(execTotal));\n loadLines.push('Running: ' + String(Array.isArray(runningWork) ? runningWork.length : 0));\n loadLines.push('Queued: ' + String(queuedTotal));\n\n rows += '<tr>' +\n '<td><div class=\"fw-semibold\">' + escapeHtml(workerID) + '</div></td>' +\n '<td><small>' + escapeHtml(address) + '</small></td>' +\n '<td>' + capBadges.join('') + '</td>' +\n '<td><small>' + escapeHtml(loadLines.join(' | ')) + '</small></td>' +\n '</tr>';\n }\n\n tbody.innerHTML = rows;\n }\n\n function normalizeJobStateForFilter(value) {\n var normalized = String(value || '').toLowerCase();\n if (normalized.indexOf('job_state_') === 0) {\n normalized = normalized.slice('job_state_'.length);\n }\n return normalized;\n }\n\n function matchesExecutionStateFilter(jobState, selectedFilter) {\n var target = normalizeJobStateForFilter(selectedFilter);\n if (!target) {\n return true;\n }\n var actual = normalizeJobStateForFilter(jobState);\n if (actual === target) {\n return true;\n }\n if (target === 'running' && actual === 'in_progress') {\n return true;\n }\n return false;\n }\n\n function isDetectionActivitySource(source) {\n var normalized = String(source || '').toLowerCase();\n if (!normalized) {\n return false;\n }\n if (normalized === 'worker_detection') {\n return true;\n }\n return normalized.indexOf('detector') >= 0;\n }\n\n function renderExecutionJobs() {\n var tbody = document.getElementById('plugin-execution-jobs-table-body');\n if (!tbody) {\n return;\n }\n\n var filteredJobs = [];\n var allJobs = Array.isArray(state.allJobs) ? state.allJobs : [];\n for (var i = 0; i < allJobs.length; i++) {\n var job = allJobs[i] || {};\n var jobType = String(job.job_type || '').trim();\n if (state.selectedJobType && jobType !== state.selectedJobType) {\n continue;\n }\n if (!matchesExecutionStateFilter(job.state, state.monitorExecutionJobState)) {\n continue;\n }\n filteredJobs.push(job);\n }\n\n if (!filteredJobs.length) {\n tbody.innerHTML = '<tr><td colspan=\"7\" class=\"text-muted text-center py-3\">No execution jobs tracked yet</td></tr>';\n return;\n }\n\n var rows = '';\n for (var j = 0; j < filteredJobs.length; j++) {\n var executionJob = filteredJobs[j] || {};\n var progress = Number(executionJob.progress || 0);\n if (!Number.isFinite(progress) || progress < 0) {\n progress = 0;\n }\n if (progress > 100) {\n progress = 100;\n }\n\n var barClass = 'bg-info';\n var stateText = String(executionJob.state || 'unknown').toLowerCase();\n if (stateText.indexOf('failed') >= 0) {\n barClass = 'bg-danger';\n } else if (stateText.indexOf('succeed') >= 0 || stateText.indexOf('complete') >= 0) {\n barClass = 'bg-success';\n } else if (stateText.indexOf('run') >= 0 || stateText.indexOf('progress') >= 0) {\n barClass = 'bg-warning';\n }\n\n var jobTypeCell = escapeHtml(textOrDash(executionJob.job_type));\n var execLabels = executionJob.labels || {};\n if (execLabels.batch === 'true' && execLabels.batch_size) {\n jobTypeCell += ' <span class=\"badge bg-info\">' + escapeHtml(execLabels.batch_size) + ' moves</span>';\n }\n\n rows += '<tr>' +\n '<td>' + renderJobLink(executionJob.job_id) + '</td>' +\n '<td>' + jobTypeCell + '</td>' +\n '<td><span class=\"badge bg-light text-dark\">' + escapeHtml(textOrDash(executionJob.state)) + '</span></td>' +\n '<td class=\"plugin-job-progress\"><div class=\"progress\" style=\"height: 14px;\"><div class=\"progress-bar ' + barClass + '\" role=\"progressbar\" style=\"width:' + progress + '%\">' + Math.round(progress) + '%</div></div></td>' +\n '<td><small>' + escapeHtml(textOrDash(executionJob.worker_id)) + '</small></td>' +\n '<td><small>' + escapeHtml(parseTime(executionJob.updated_at) || '-') + '</small></td>' +\n '<td><small>' + escapeHtml(textOrDash(executionJob.message)) + '</small></td>' +\n '</tr>';\n }\n\n tbody.innerHTML = rows;\n }\n\n function renderQueueJobs() {\n var tbody = document.getElementById('plugin-queue-jobs-table-body');\n if (!tbody) {\n return;\n }\n\n var filteredJobs = [];\n var allJobs = Array.isArray(state.allJobs) ? state.allJobs : [];\n for (var i = 0; i < allJobs.length; i++) {\n var queueJob = allJobs[i] || {};\n var queueJobType = String(queueJob.job_type || '').trim();\n if (state.selectedJobType && queueJobType !== state.selectedJobType) {\n continue;\n }\n var normalizedState = normalizeJobStateForFilter(queueJob.state);\n if (normalizedState !== 'pending' && normalizedState !== 'assigned' && normalizedState !== 'running' && normalizedState !== 'in_progress') {\n continue;\n }\n filteredJobs.push(queueJob);\n }\n\n if (!filteredJobs.length) {\n tbody.innerHTML = '<tr><td colspan=\"7\" class=\"text-muted text-center py-3\">No queued/active jobs</td></tr>';\n return;\n }\n\n var rows = '';\n for (var j = 0; j < filteredJobs.length; j++) {\n var queueItem = filteredJobs[j] || {};\n var progress = Number(queueItem.progress || 0);\n if (!Number.isFinite(progress) || progress < 0) {\n progress = 0;\n }\n if (progress > 100) {\n progress = 100;\n }\n\n var barClass = 'bg-warning';\n var queueStateText = String(queueItem.state || 'unknown').toLowerCase();\n if (queueStateText.indexOf('run') >= 0 || queueStateText.indexOf('progress') >= 0) {\n barClass = 'bg-info';\n }\n\n rows += '<tr>' +\n '<td>' + renderJobLink(queueItem.job_id) + '</td>' +\n '<td>' + escapeHtml(textOrDash(queueItem.job_type)) + '</td>' +\n '<td><span class=\"badge bg-light text-dark\">' + escapeHtml(textOrDash(queueItem.state)) + '</span></td>' +\n '<td class=\"plugin-job-progress\"><div class=\"progress\" style=\"height: 14px;\"><div class=\"progress-bar ' + barClass + '\" role=\"progressbar\" style=\"width:' + progress + '%\">' + Math.round(progress) + '%</div></div></td>' +\n '<td><small>' + escapeHtml(textOrDash(queueItem.worker_id)) + '</small></td>' +\n '<td><small>' + escapeHtml(parseTime(queueItem.updated_at) || '-') + '</small></td>' +\n '<td><small>' + escapeHtml(textOrDash(queueItem.message)) + '</small></td>' +\n '</tr>';\n }\n\n tbody.innerHTML = rows;\n }\n\n function renderDetectionJobs() {\n var tbody = document.getElementById('plugin-detection-table-body');\n if (!tbody) {\n return;\n }\n\n var filteredActivities = [];\n var allActivities = Array.isArray(state.allActivities) ? state.allActivities : [];\n for (var i = 0; i < allActivities.length; i++) {\n var activity = allActivities[i] || {};\n var jobType = String(activity.job_type || '').trim();\n if (state.selectedJobType && jobType !== state.selectedJobType) {\n continue;\n }\n if (!isDetectionActivitySource(activity.source)) {\n continue;\n }\n filteredActivities.push(activity);\n }\n\n if (!filteredActivities.length) {\n tbody.innerHTML = '<tr><td colspan=\"7\" class=\"text-muted text-center py-3\">No detection jobs tracked yet</td></tr>';\n return;\n }\n\n var rows = '';\n for (var j = 0; j < filteredActivities.length; j++) {\n var detectionActivity = filteredActivities[j] || {};\n rows += '<tr>' +\n '<td><small>' + escapeHtml(parseTime(detectionActivity.occurred_at) || '-') + '</small></td>' +\n '<td>' + escapeHtml(textOrDash(detectionActivity.job_type)) + '</td>' +\n '<td><small>' + escapeHtml(textOrDash(detectionActivity.request_id)) + '</small></td>' +\n '<td><small>' + escapeHtml(textOrDash(detectionActivity.worker_id)) + '</small></td>' +\n '<td>' + escapeHtml(textOrDash(detectionActivity.stage)) + '</td>' +\n '<td><span class=\"badge bg-light text-dark\">' + escapeHtml(textOrDash(detectionActivity.source)) + '</span></td>' +\n '<td><small>' + escapeHtml(textOrDash(detectionActivity.message)) + '</small></td>' +\n '</tr>';\n }\n\n tbody.innerHTML = rows;\n }\n\n function renderExecutionActivities() {\n var tbody = document.getElementById('plugin-execution-activities-table-body');\n if (!tbody) {\n return;\n }\n\n var filteredActivities = [];\n var allActivities = Array.isArray(state.allActivities) ? state.allActivities : [];\n for (var i = 0; i < allActivities.length; i++) {\n var activity = allActivities[i] || {};\n if (isDetectionActivitySource(activity.source)) {\n continue;\n }\n var jobType = String(activity.job_type || '').trim();\n if (state.selectedJobType && jobType !== state.selectedJobType) {\n continue;\n }\n filteredActivities.push(activity);\n }\n\n if (!filteredActivities.length) {\n tbody.innerHTML = '<tr><td colspan=\"6\" class=\"text-muted text-center py-3\">No execution activities yet</td></tr>';\n return;\n }\n\n var rows = '';\n for (var j = 0; j < filteredActivities.length; j++) {\n var executionActivity = filteredActivities[j] || {};\n rows += '<tr>' +\n '<td><small>' + escapeHtml(parseTime(executionActivity.occurred_at) || '-') + '</small></td>' +\n '<td>' + escapeHtml(textOrDash(executionActivity.job_type)) + '</td>' +\n '<td>' + renderJobLink(executionActivity.job_id) + '</td>' +\n '<td><span class=\"badge bg-light text-dark\">' + escapeHtml(textOrDash(executionActivity.source)) + '</span></td>' +\n '<td>' + escapeHtml(textOrDash(executionActivity.stage)) + '</td>' +\n '<td><small>' + escapeHtml(textOrDash(executionActivity.message)) + '</small></td>' +\n '</tr>';\n }\n\n tbody.innerHTML = rows;\n }\n\n function getSelectValueArray(selectEl) {\n if (!selectEl) {\n return [];\n }\n var values = [];\n for (var i = 0; i < selectEl.options.length; i++) {\n if (selectEl.options[i].selected) {\n values.push(selectEl.options[i].value);\n }\n }\n return values;\n }\n\n function configValueToNative(configValue) {\n if (!configValue || typeof configValue !== 'object') {\n return null;\n }\n if (Object.prototype.hasOwnProperty.call(configValue, 'bool_value')) {\n return !!configValue.bool_value;\n }\n if (Object.prototype.hasOwnProperty.call(configValue, 'int64_value')) {\n return configValue.int64_value;\n }\n if (Object.prototype.hasOwnProperty.call(configValue, 'double_value')) {\n return configValue.double_value;\n }\n if (Object.prototype.hasOwnProperty.call(configValue, 'string_value')) {\n return configValue.string_value;\n }\n if (Object.prototype.hasOwnProperty.call(configValue, 'bytes_value')) {\n return configValue.bytes_value;\n }\n if (Object.prototype.hasOwnProperty.call(configValue, 'duration_value')) {\n return configValue.duration_value;\n }\n if (configValue.string_list && Array.isArray(configValue.string_list.values)) {\n return configValue.string_list.values.slice();\n }\n if (configValue.int64_list && Array.isArray(configValue.int64_list.values)) {\n return configValue.int64_list.values.slice();\n }\n if (configValue.double_list && Array.isArray(configValue.double_list.values)) {\n return configValue.double_list.values.slice();\n }\n if (configValue.bool_list && Array.isArray(configValue.bool_list.values)) {\n return configValue.bool_list.values.slice();\n }\n if (configValue.list_value && Array.isArray(configValue.list_value.values)) {\n return configValue.list_value.values.map(function(v) {\n return configValueToNative(v);\n });\n }\n if (configValue.map_value && configValue.map_value.fields) {\n var out = {};\n Object.keys(configValue.map_value.fields).forEach(function(k) {\n out[k] = configValueToNative(configValue.map_value.fields[k]);\n });\n return out;\n }\n return null;\n }\n\n function inferConfigValue(value) {\n if (value === null || value === undefined) {\n return { string_value: '' };\n }\n if (typeof value === 'boolean') {\n return { bool_value: value };\n }\n if (typeof value === 'number') {\n if (Number.isInteger(value)) {\n return { int64_value: String(value) };\n }\n return { double_value: value };\n }\n if (typeof value === 'string') {\n return { string_value: value };\n }\n if (Array.isArray(value)) {\n var listValues = value.map(function(item) {\n return inferConfigValue(item);\n });\n return { list_value: { values: listValues } };\n }\n if (typeof value === 'object') {\n var fields = {};\n Object.keys(value).forEach(function(key) {\n fields[key] = inferConfigValue(value[key]);\n });\n return { map_value: { fields: fields } };\n }\n return { string_value: String(value) };\n }\n\n function nativeToConfigValue(value, fieldType, widget, field) {\n var normalizedFieldType = normalizeEnum(fieldType);\n var normalizedWidget = normalizeEnum(widget);\n\n if (normalizedFieldType === 'CONFIG_FIELD_TYPE_BOOL') {\n return { bool_value: !!value };\n }\n\n if (normalizedFieldType === 'CONFIG_FIELD_TYPE_INT64') {\n if (value === '' || value === null || value === undefined) {\n return null;\n }\n var intValue = parseInt(value, 10);\n if (Number.isNaN(intValue)) {\n throw new Error('Invalid int64 value for field ' + field.name);\n }\n return { int64_value: String(intValue) };\n }\n\n if (normalizedFieldType === 'CONFIG_FIELD_TYPE_DOUBLE') {\n if (value === '' || value === null || value === undefined) {\n return null;\n }\n var doubleValue = parseFloat(value);\n if (Number.isNaN(doubleValue)) {\n throw new Error('Invalid number for field ' + field.name);\n }\n return { double_value: doubleValue };\n }\n\n if (normalizedFieldType === 'CONFIG_FIELD_TYPE_DURATION') {\n if (value === '' || value === null || value === undefined) {\n return null;\n }\n var text = String(value).trim();\n if (!text) {\n return null;\n }\n if (/^\\d+$/.test(text)) {\n text += 's';\n }\n return { duration_value: text };\n }\n\n if (normalizedFieldType === 'CONFIG_FIELD_TYPE_LIST') {\n if (value === '' || value === null || value === undefined) {\n return null;\n }\n\n if (normalizedWidget === 'CONFIG_WIDGET_MULTI_SELECT' && Array.isArray(value)) {\n return { string_list: { values: value } };\n }\n\n if (typeof value === 'string') {\n try {\n var parsed = JSON.parse(value);\n if (!Array.isArray(parsed)) {\n throw new Error('Expected JSON array');\n }\n return inferConfigValue(parsed);\n } catch (e) {\n throw new Error('Invalid JSON list for field ' + field.name + ': ' + e.message);\n }\n }\n return inferConfigValue(value);\n }\n\n if (normalizedFieldType === 'CONFIG_FIELD_TYPE_OBJECT') {\n if (value === '' || value === null || value === undefined) {\n return null;\n }\n if (typeof value === 'string') {\n try {\n var parsedObject = JSON.parse(value);\n if (!parsedObject || typeof parsedObject !== 'object' || Array.isArray(parsedObject)) {\n throw new Error('Expected JSON object');\n }\n return inferConfigValue(parsedObject);\n } catch (e) {\n throw new Error('Invalid JSON object for field ' + field.name + ': ' + e.message);\n }\n }\n return inferConfigValue(value);\n }\n\n if (normalizedFieldType === 'CONFIG_FIELD_TYPE_ENUM') {\n if (normalizedWidget === 'CONFIG_WIDGET_MULTI_SELECT') {\n if (!value || !value.length) {\n return null;\n }\n return { string_list: { values: value } };\n }\n if (value === '' || value === null || value === undefined) {\n return null;\n }\n return { string_value: String(value) };\n }\n\n if (value === '' || value === null || value === undefined) {\n return null;\n }\n\n return { string_value: String(value) };\n }\n\n function toInputID(scope, fieldName) {\n return 'plugin-' + scope + '-field-' + String(fieldName || '').replace(/[^a-zA-Z0-9_-]/g, '_');\n }\n\n function resolveFieldConfigValue(scope, field) {\n if (!field || !field.name) {\n return null;\n }\n var fromConfig = null;\n if (state.config) {\n if (scope === 'admin' && state.config.admin_config_values) {\n fromConfig = state.config.admin_config_values[field.name];\n }\n if (scope === 'worker' && state.config.worker_config_values) {\n fromConfig = state.config.worker_config_values[field.name];\n }\n }\n if (fromConfig) {\n return fromConfig;\n }\n\n var formDefaults = null;\n if (scope === 'admin' && state.descriptor && state.descriptor.admin_config_form && state.descriptor.admin_config_form.default_values) {\n formDefaults = state.descriptor.admin_config_form.default_values[field.name];\n }\n if (scope === 'worker' && state.descriptor && state.descriptor.worker_config_form && state.descriptor.worker_config_form.default_values) {\n formDefaults = state.descriptor.worker_config_form.default_values[field.name];\n }\n if (formDefaults) {\n return formDefaults;\n }\n\n if (scope === 'worker' && state.descriptor && state.descriptor.worker_default_values) {\n return state.descriptor.worker_default_values[field.name] || null;\n }\n\n return null;\n }\n\n function renderFieldInput(scope, field, value) {\n var inputID = toInputID(scope, field.name);\n var normalizedType = normalizeEnum(field.field_type);\n var normalizedWidget = normalizeEnum(field.widget);\n var input;\n\n if (normalizedType === 'CONFIG_FIELD_TYPE_BOOL' || normalizedWidget === 'CONFIG_WIDGET_TOGGLE') {\n input = document.createElement('input');\n input.type = 'checkbox';\n input.className = 'form-check-input';\n input.id = inputID;\n input.checked = !!value;\n } else if ((normalizedType === 'CONFIG_FIELD_TYPE_ENUM' && normalizedWidget === 'CONFIG_WIDGET_MULTI_SELECT') || normalizedWidget === 'CONFIG_WIDGET_MULTI_SELECT') {\n input = document.createElement('select');\n input.className = 'form-select';\n input.id = inputID;\n input.multiple = true;\n var selected = Array.isArray(value) ? value : [];\n var options = Array.isArray(field.options) ? field.options : [];\n for (var i = 0; i < options.length; i++) {\n var option = document.createElement('option');\n option.value = options[i].value || '';\n option.textContent = options[i].label || options[i].value || '';\n if (selected.indexOf(option.value) >= 0) {\n option.selected = true;\n }\n input.appendChild(option);\n }\n } else if (normalizedType === 'CONFIG_FIELD_TYPE_ENUM' || normalizedWidget === 'CONFIG_WIDGET_SELECT') {\n input = document.createElement('select');\n input.className = 'form-select';\n input.id = inputID;\n var blankOption = document.createElement('option');\n blankOption.value = '';\n blankOption.textContent = '-- select --';\n input.appendChild(blankOption);\n var enumOptions = Array.isArray(field.options) ? field.options : [];\n for (var j = 0; j < enumOptions.length; j++) {\n var enumOption = document.createElement('option');\n enumOption.value = enumOptions[j].value || '';\n enumOption.textContent = enumOptions[j].label || enumOptions[j].value || '';\n if (String(value) === enumOption.value) {\n enumOption.selected = true;\n }\n input.appendChild(enumOption);\n }\n } else if (normalizedType === 'CONFIG_FIELD_TYPE_INT64' || normalizedType === 'CONFIG_FIELD_TYPE_DOUBLE' || normalizedWidget === 'CONFIG_WIDGET_NUMBER') {\n input = document.createElement('input');\n input.type = 'number';\n if (normalizedType === 'CONFIG_FIELD_TYPE_DOUBLE') {\n input.step = 'any';\n }\n input.className = 'form-control';\n input.id = inputID;\n if (value !== null && value !== undefined && value !== '') {\n input.value = String(value);\n }\n } else if (normalizedType === 'CONFIG_FIELD_TYPE_LIST' || normalizedType === 'CONFIG_FIELD_TYPE_OBJECT' || normalizedWidget === 'CONFIG_WIDGET_TEXTAREA') {\n input = document.createElement('textarea');\n input.className = 'form-control';\n input.id = inputID;\n input.rows = 4;\n if (normalizedType === 'CONFIG_FIELD_TYPE_LIST' || normalizedType === 'CONFIG_FIELD_TYPE_OBJECT') {\n input.placeholder = normalizedType === 'CONFIG_FIELD_TYPE_LIST' ? '[...]' : '{...}';\n }\n if (value !== null && value !== undefined && value !== '') {\n if (typeof value === 'object') {\n input.value = JSON.stringify(value, null, 2);\n } else {\n input.value = String(value);\n }\n }\n } else {\n input = document.createElement('input');\n input.className = 'form-control';\n input.id = inputID;\n if (normalizedWidget === 'CONFIG_WIDGET_PASSWORD' || field.sensitive) {\n input.type = 'password';\n } else {\n input.type = 'text';\n }\n if (value !== null && value !== undefined && value !== '') {\n input.value = String(value);\n }\n }\n\n if (field.placeholder && input.tagName === 'INPUT') {\n input.placeholder = field.placeholder;\n }\n if (field.placeholder && input.tagName === 'TEXTAREA') {\n input.placeholder = field.placeholder;\n }\n\n if (field.required) {\n input.required = true;\n }\n if (field.read_only) {\n input.disabled = true;\n }\n\n return input;\n }\n\n function renderConfigForm(scope, rootID, form) {\n var root = document.getElementById(rootID);\n if (!root) {\n return;\n }\n\n root.innerHTML = '';\n if (!form || !Array.isArray(form.sections) || form.sections.length === 0) {\n root.innerHTML = '<div class=\"text-muted\">No fields provided by descriptor.</div>';\n return;\n }\n\n for (var s = 0; s < form.sections.length; s++) {\n var section = form.sections[s] || {};\n var sectionCard = document.createElement('div');\n sectionCard.className = 'card mb-3';\n\n var sectionHeader = document.createElement('div');\n sectionHeader.className = 'card-header py-2';\n sectionHeader.innerHTML = '<strong>' + escapeHtml(textOrDash(section.title || section.section_id)) + '</strong>';\n sectionCard.appendChild(sectionHeader);\n\n var sectionBody = document.createElement('div');\n sectionBody.className = 'card-body';\n\n if (section.description) {\n var sectionDescription = document.createElement('p');\n sectionDescription.className = 'text-muted small';\n sectionDescription.textContent = section.description;\n sectionBody.appendChild(sectionDescription);\n }\n\n var fields = Array.isArray(section.fields) ? section.fields : [];\n if (!fields.length) {\n var noFields = document.createElement('div');\n noFields.className = 'text-muted';\n noFields.textContent = 'No fields in this section.';\n sectionBody.appendChild(noFields);\n }\n\n for (var f = 0; f < fields.length; f++) {\n var field = fields[f] || {};\n if (!field.name) {\n continue;\n }\n\n var configValue = resolveFieldConfigValue(scope, field);\n var nativeValue = configValueToNative(configValue);\n\n var wrapper = document.createElement('div');\n wrapper.className = 'mb-3 plugin-field';\n wrapper.dataset.scope = scope;\n wrapper.dataset.fieldName = field.name;\n wrapper.dataset.fieldType = normalizeEnum(field.field_type);\n wrapper.dataset.widget = normalizeEnum(field.widget);\n wrapper.dataset.visibleWhenField = field.visible_when_field || '';\n wrapper.dataset.visibleWhenEquals = JSON.stringify(field.visible_when_equals || null);\n\n var label = document.createElement('label');\n label.className = 'form-label';\n label.setAttribute('for', toInputID(scope, field.name));\n label.innerHTML = escapeHtml(field.label || field.name) + (field.required ? ' <span class=\"text-danger\">*</span>' : '');\n wrapper.appendChild(label);\n\n var input = renderFieldInput(scope, field, nativeValue);\n wrapper.appendChild(input);\n\n if (field.description || field.help_text) {\n var help = document.createElement('div');\n help.className = 'form-text';\n help.textContent = field.help_text || field.description || '';\n wrapper.appendChild(help);\n }\n\n sectionBody.appendChild(wrapper);\n }\n\n sectionCard.appendChild(sectionBody);\n root.appendChild(sectionCard);\n }\n\n root.addEventListener('change', function() {\n applyVisibility(scope);\n });\n root.addEventListener('input', function() {\n applyVisibility(scope);\n });\n\n applyVisibility(scope);\n }\n\n function readRawFieldValue(scope, fieldName) {\n var input = document.getElementById(toInputID(scope, fieldName));\n if (!input) {\n return null;\n }\n if (input.tagName === 'SELECT' && input.multiple) {\n return getSelectValueArray(input);\n }\n if (input.type === 'checkbox') {\n return !!input.checked;\n }\n return input.value;\n }\n\n function compareVisibleValue(currentValue, expectedValueObject) {\n if (!expectedValueObject) {\n return true;\n }\n var expectedNative = configValueToNative(expectedValueObject);\n if (Array.isArray(expectedNative)) {\n if (!Array.isArray(currentValue)) {\n return false;\n }\n if (expectedNative.length !== currentValue.length) {\n return false;\n }\n for (var i = 0; i < expectedNative.length; i++) {\n if (String(expectedNative[i]) !== String(currentValue[i])) {\n return false;\n }\n }\n return true;\n }\n return String(currentValue) === String(expectedNative);\n }\n\n function applyVisibility(scope) {\n var fields = document.querySelectorAll('.plugin-field[data-scope=\"' + scope + '\"]');\n for (var i = 0; i < fields.length; i++) {\n var wrapper = fields[i];\n var dependsOn = wrapper.dataset.visibleWhenField;\n if (!dependsOn) {\n wrapper.classList.remove('plugin-field-hidden');\n continue;\n }\n\n var expectedRaw = null;\n try {\n expectedRaw = JSON.parse(wrapper.dataset.visibleWhenEquals || 'null');\n } catch (e) {\n expectedRaw = null;\n }\n var current = readRawFieldValue(scope, dependsOn);\n var visible = compareVisibleValue(current, expectedRaw);\n if (visible) {\n wrapper.classList.remove('plugin-field-hidden');\n } else {\n wrapper.classList.add('plugin-field-hidden');\n }\n }\n }\n\n function collectConfigValues(scope, form) {\n var out = {};\n if (!form || !Array.isArray(form.sections)) {\n return out;\n }\n\n for (var s = 0; s < form.sections.length; s++) {\n var section = form.sections[s] || {};\n var fields = Array.isArray(section.fields) ? section.fields : [];\n for (var f = 0; f < fields.length; f++) {\n var field = fields[f] || {};\n if (!field.name) {\n continue;\n }\n\n var wrapper = document.querySelector('.plugin-field[data-scope=\"' + scope + '\"][data-field-name=\"' + field.name + '\"]');\n if (wrapper && wrapper.classList.contains('plugin-field-hidden')) {\n continue;\n }\n\n var input = document.getElementById(toInputID(scope, field.name));\n if (!input) {\n continue;\n }\n\n var rawValue;\n if (input.tagName === 'SELECT' && input.multiple) {\n rawValue = getSelectValueArray(input);\n } else if (input.type === 'checkbox') {\n rawValue = !!input.checked;\n } else {\n rawValue = input.value;\n }\n\n if (field.required) {\n var missing = false;\n if (input.type === 'checkbox') {\n missing = false;\n } else if (Array.isArray(rawValue)) {\n missing = rawValue.length === 0;\n } else {\n missing = String(rawValue || '').trim() === '';\n }\n if (missing) {\n throw new Error('Missing required field: ' + (field.label || field.name));\n }\n }\n\n var converted = nativeToConfigValue(rawValue, field.field_type, field.widget, field);\n if (converted !== null) {\n out[field.name] = converted;\n }\n }\n }\n\n return out;\n }\n\n function renderDescriptorSummary() {\n var summary = document.getElementById('plugin-descriptor-summary');\n if (!state.descriptor) {\n summary.innerHTML = 'No descriptor loaded.';\n return;\n }\n\n var descriptor = state.descriptor;\n var html = '';\n html += '<div><strong>' + escapeHtml(textOrDash(descriptor.display_name || descriptor.job_type)) + '</strong></div>';\n html += '<div><small>Job Type: ' + escapeHtml(textOrDash(descriptor.job_type)) + '</small></div>';\n html += '<div><small>Descriptor Version: ' + escapeHtml(textOrDash(descriptor.descriptor_version)) + '</small></div>';\n if (descriptor.description) {\n html += '<div class=\"mt-1\">' + escapeHtml(descriptor.description) + '</div>';\n }\n summary.innerHTML = html;\n }\n\n function fillAdminSettings() {\n var runtimeConfig = (state.config && state.config.admin_runtime) ? state.config.admin_runtime : {};\n var defaults = (state.descriptor && state.descriptor.admin_runtime_defaults) ? state.descriptor.admin_runtime_defaults : {};\n\n function pickNumber(key) {\n if (runtimeConfig && runtimeConfig[key] !== undefined && runtimeConfig[key] !== null) {\n return runtimeConfig[key];\n }\n if (defaults && defaults[key] !== undefined && defaults[key] !== null) {\n return defaults[key];\n }\n return 0;\n }\n\n function pickBool(key) {\n if (runtimeConfig && runtimeConfig[key] !== undefined && runtimeConfig[key] !== null) {\n return !!runtimeConfig[key];\n }\n if (defaults && defaults[key] !== undefined && defaults[key] !== null) {\n return !!defaults[key];\n }\n return true;\n }\n\n document.getElementById('plugin-admin-enabled').checked = pickBool('enabled');\n document.getElementById('plugin-admin-detection-interval').value = String(pickNumber('detection_interval_seconds'));\n document.getElementById('plugin-admin-detection-timeout').value = String(pickNumber('detection_timeout_seconds'));\n document.getElementById('plugin-admin-max-runtime').value = String(pickNumber('job_type_max_runtime_seconds'));\n document.getElementById('plugin-admin-max-results').value = String(pickNumber('max_jobs_per_detection'));\n document.getElementById('plugin-admin-global-exec').value = String(pickNumber('global_execution_concurrency'));\n document.getElementById('plugin-admin-per-worker-exec').value = String(pickNumber('per_worker_execution_concurrency'));\n document.getElementById('plugin-admin-retry-limit').value = String(pickNumber('retry_limit'));\n document.getElementById('plugin-admin-retry-backoff').value = String(pickNumber('retry_backoff_seconds'));\n }\n\n function collectAdminSettings() {\n function getInt(id) {\n var raw = String(document.getElementById(id).value || '').trim();\n if (!raw) {\n return 0;\n }\n var parsed = parseInt(raw, 10);\n if (Number.isNaN(parsed) || parsed < 0) {\n throw new Error('Invalid number for ' + id);\n }\n return parsed;\n }\n\n return {\n enabled: !!document.getElementById('plugin-admin-enabled').checked,\n detection_interval_seconds: getInt('plugin-admin-detection-interval'),\n detection_timeout_seconds: getInt('plugin-admin-detection-timeout'),\n job_type_max_runtime_seconds: getInt('plugin-admin-max-runtime'),\n max_jobs_per_detection: getInt('plugin-admin-max-results'),\n global_execution_concurrency: getInt('plugin-admin-global-exec'),\n per_worker_execution_concurrency: getInt('plugin-admin-per-worker-exec'),\n retry_limit: getInt('plugin-admin-retry-limit'),\n retry_backoff_seconds: getInt('plugin-admin-retry-backoff'),\n };\n }\n\n function renderRunHistory(history) {\n var successBody = document.getElementById('plugin-runs-success-body');\n var errorBody = document.getElementById('plugin-runs-error-body');\n\n var successRuns = (history && Array.isArray(history.successful_runs)) ? history.successful_runs : [];\n var errorRuns = (history && Array.isArray(history.error_runs)) ? history.error_runs : [];\n\n if (!successRuns.length) {\n successBody.innerHTML = '<tr><td colspan=\"4\" class=\"text-muted\">No successful runs</td></tr>';\n } else {\n var successRows = '';\n for (var i = 0; i < successRuns.length; i++) {\n var run = successRuns[i] || {};\n successRows += '<tr>' +\n '<td><small>' + escapeHtml(parseTime(run.completed_at) || '-') + '</small></td>' +\n '<td>' + renderJobLink(run.job_id) + '</td>' +\n '<td><small>' + escapeHtml(textOrDash(run.worker_id)) + '</small></td>' +\n '<td><small>' + escapeHtml(formatDurationMs(run.duration_ms)) + '</small></td>' +\n '</tr>';\n }\n successBody.innerHTML = successRows;\n }\n\n if (!errorRuns.length) {\n errorBody.innerHTML = '<tr><td colspan=\"4\" class=\"text-muted\">No error runs</td></tr>';\n } else {\n var errorRows = '';\n for (var j = 0; j < errorRuns.length; j++) {\n var errorRun = errorRuns[j] || {};\n errorRows += '<tr>' +\n '<td><small>' + escapeHtml(parseTime(errorRun.completed_at) || '-') + '</small></td>' +\n '<td>' + renderJobLink(errorRun.job_id) + '</td>' +\n '<td><small>' + escapeHtml(textOrDash(errorRun.worker_id)) + '</small></td>' +\n '<td><small class=\"text-danger\">' + escapeHtml(textOrDash(errorRun.message)) + '</small></td>' +\n '</tr>';\n }\n errorBody.innerHTML = errorRows;\n }\n }\n\n function renderDetectionResult(data) {\n var root = document.getElementById('plugin-detection-results');\n if (!root) {\n return;\n }\n\n function normalizeProposals(payload) {\n if (!payload || typeof payload !== 'object') {\n return [];\n }\n if (Array.isArray(payload.proposals)) {\n return payload.proposals;\n }\n if (payload.proposals && typeof payload.proposals === 'object') {\n return Object.keys(payload.proposals).map(function(key) {\n return payload.proposals[key];\n }).filter(function(item) {\n return !!item;\n });\n }\n return [];\n }\n\n function proposalID(proposal) {\n return proposal.proposal_id || proposal.proposalId || proposal.id || '';\n }\n\n function proposalSummary(proposal) {\n return proposal.summary || proposal.title || proposalID(proposal) || 'Proposal';\n }\n\n function proposalDetail(proposal) {\n return proposal.detail || proposal.reason || proposal.message || '-';\n }\n\n function normalizeActivities(payload) {\n if (!payload || typeof payload !== 'object') {\n return [];\n }\n if (Array.isArray(payload.activities)) {\n return payload.activities;\n }\n return [];\n }\n\n function encodeDetails(details) {\n if (!details || typeof details !== 'object') {\n return '';\n }\n var text = '';\n try {\n text = JSON.stringify(details);\n } catch (e) {\n text = '';\n }\n if (!text) {\n return '';\n }\n if (text.length > 360) {\n text = text.slice(0, 360) + '...';\n }\n return text;\n }\n\n if (!data) {\n root.innerHTML = '<div class=\"text-muted\">No results.</div>';\n return;\n }\n\n var proposals = normalizeProposals(data);\n var activities = normalizeActivities(data);\n var responseCount = Number(data.count || 0);\n if (!Number.isFinite(responseCount) || responseCount < 0) {\n responseCount = proposals.length;\n }\n var requestID = data.request_id || data.requestId || '';\n var detectorWorkerID = data.detector_worker_id || data.detectorWorkerId || '';\n var totalProposals = Number(data.total_proposals || 0);\n if (!Number.isFinite(totalProposals) || totalProposals < 0) {\n totalProposals = responseCount;\n }\n\n var html = '';\n html += '<div class=\"mb-2\"><strong>Detection Run</strong></div>';\n if (requestID) {\n html += '<div><small>request_id: ' + escapeHtml(String(requestID)) + '</small></div>';\n }\n if (detectorWorkerID) {\n html += '<div><small>detector: ' + escapeHtml(String(detectorWorkerID)) + '</small></div>';\n }\n html += '<div><small>proposals: ' + escapeHtml(String(responseCount)) + ' / total: ' + escapeHtml(String(totalProposals)) + '</small></div>';\n if (data.error) {\n html += '<div class=\"mt-1 text-danger\"><small>' + escapeHtml(String(data.error)) + '</small></div>';\n }\n\n if (!proposals.length) {\n html += '<div class=\"mt-2 text-muted\">No proposals returned.</div>';\n } else {\n html += '<div class=\"mt-2 mb-1\"><strong>' + escapeHtml(String(proposals.length)) + '</strong> proposal(s)</div>';\n for (var i = 0; i < proposals.length; i++) {\n var proposal = proposals[i] || {};\n var pID = proposalID(proposal);\n var pSummary = proposalSummary(proposal);\n var pDetail = proposalDetail(proposal);\n var pPriority = proposal.priority;\n if (pPriority === null || pPriority === undefined || pPriority === '') {\n pPriority = '-';\n }\n html += '<div class=\"plugin-detection-item\">' +\n '<div class=\"fw-semibold\">' + escapeHtml(textOrDash(pSummary)) + '</div>' +\n '<div><small>proposal_id: ' + escapeHtml(textOrDash(pID)) + '</small></div>' +\n '<div><small>priority: ' + escapeHtml(textOrDash(pPriority)) + '</small></div>' +\n '<div><small>detail: ' + escapeHtml(textOrDash(pDetail)) + '</small></div>' +\n '</div>';\n }\n }\n\n if (activities.length) {\n html += '<hr class=\"my-2\"/>';\n html += '<div class=\"mb-2\"><strong>Detection Process</strong></div>';\n for (var j = 0; j < activities.length; j++) {\n var activity = activities[j] || {};\n var activityStage = activity.stage || '-';\n var activitySource = activity.source || '-';\n var activityMessage = activity.message || '-';\n var activityTime = parseTime(activity.occurred_at) || '-';\n var detailsText = encodeDetails(activity.details);\n html += '<div class=\"plugin-detection-item\">' +\n '<div class=\"fw-semibold\">' + escapeHtml(textOrDash(activityStage)) + '</div>' +\n '<div><small>source: ' + escapeHtml(textOrDash(activitySource)) + ' | at: ' + escapeHtml(activityTime) + '</small></div>' +\n '<div><small>' + escapeHtml(textOrDash(activityMessage)) + '</small></div>';\n if (detailsText) {\n html += '<div><small class=\"text-muted\">details: ' + escapeHtml(detailsText) + '</small></div>';\n }\n html += '</div>';\n }\n }\n\n root.innerHTML = html;\n }\n\n function getSelectedJobType() {\n return String(state.selectedJobType || '').trim();\n }\n\n function resetJobTypePanels() {\n state.loadedJobType = '';\n state.descriptor = null;\n state.config = null;\n document.getElementById('plugin-descriptor-summary').textContent = 'No descriptor loaded.';\n document.getElementById('plugin-admin-config-form').innerHTML = '<div class=\"text-muted\">No admin form loaded.</div>';\n document.getElementById('plugin-worker-config-form').innerHTML = '<div class=\"text-muted\">No worker form loaded.</div>';\n document.getElementById('plugin-config-updated-at').textContent = 'Not loaded';\n renderRunHistory(null);\n renderDetectionResult(null);\n }\n\n async function loadDescriptorAndConfig(jobType, forceRefresh) {\n if (!jobType) {\n return;\n }\n\n state.selectedJobType = jobType;\n renderNavigationState();\n\n var summary = document.getElementById('plugin-descriptor-summary');\n summary.textContent = 'Loading descriptor and config...';\n\n try {\n if (forceRefresh) {\n var refreshURL = '/api/plugin/job-types/' + encodePath(jobType) + '/schema?force_refresh=true';\n state.descriptor = await pluginRequest('POST', refreshURL, null);\n } else {\n try {\n state.descriptor = await pluginRequest('GET', '/api/plugin/job-types/' + encodePath(jobType) + '/descriptor');\n } catch (descriptorLoadError) {\n state.descriptor = await pluginRequest('POST', '/api/plugin/job-types/' + encodePath(jobType) + '/schema', null);\n }\n }\n } catch (schemaError) {\n state.loadedJobType = '';\n state.descriptor = null;\n summary.innerHTML = '<span class=\"text-danger\">Failed to load descriptor: ' + escapeHtml(schemaError.message) + '</span>';\n document.getElementById('plugin-admin-config-form').innerHTML = '<div class=\"text-muted\">No admin form loaded.</div>';\n document.getElementById('plugin-worker-config-form').innerHTML = '<div class=\"text-muted\">No worker form loaded.</div>';\n throw schemaError;\n }\n\n try {\n state.config = await pluginRequest('GET', '/api/plugin/job-types/' + encodePath(jobType) + '/config');\n } catch (configError) {\n state.config = null;\n notify('Failed to load config: ' + configError.message, 'error');\n }\n\n renderDescriptorSummary();\n fillAdminSettings();\n\n if (state.descriptor) {\n renderConfigForm('admin', 'plugin-admin-config-form', state.descriptor.admin_config_form || {});\n renderConfigForm('worker', 'plugin-worker-config-form', state.descriptor.worker_config_form || {});\n }\n\n if (state.config && state.config.updated_at) {\n document.getElementById('plugin-config-updated-at').textContent = 'Updated: ' + (parseTime(state.config.updated_at) || state.config.updated_at);\n } else {\n document.getElementById('plugin-config-updated-at').textContent = 'Not saved yet';\n }\n state.loadedJobType = jobType;\n\n await loadRunHistory(jobType);\n\n if (state.lastDetectionByJobType && state.lastDetectionByJobType[jobType]) {\n renderDetectionResult(state.lastDetectionByJobType[jobType]);\n } else {\n renderDetectionResult(null);\n }\n }\n\n async function loadRunHistory(jobType) {\n if (!jobType) {\n renderRunHistory(null);\n return;\n }\n try {\n var history = await pluginRequest('GET', '/api/plugin/job-types/' + encodePath(jobType) + '/runs');\n renderRunHistory(history);\n } catch (e) {\n renderRunHistory(null);\n notify('Failed to load run history: ' + e.message, 'error');\n }\n }\n\n async function saveConfig() {\n var jobType = state.selectedJobType || getSelectedJobType();\n if (!jobType) {\n notify('Select a job type first.', 'error');\n return;\n }\n if (!state.descriptor) {\n notify('Load descriptor before saving config.', 'error');\n return;\n }\n\n var payload;\n try {\n payload = {\n job_type: jobType,\n descriptor_version: state.descriptor.descriptor_version || 0,\n admin_runtime: collectAdminSettings(),\n admin_config_values: collectConfigValues('admin', state.descriptor.admin_config_form || {}),\n worker_config_values: collectConfigValues('worker', state.descriptor.worker_config_form || {}),\n };\n } catch (err) {\n notify(err.message, 'error');\n return;\n }\n\n try {\n state.config = await pluginRequest('PUT', '/api/plugin/job-types/' + encodePath(jobType) + '/config', payload);\n document.getElementById('plugin-config-updated-at').textContent = 'Updated: ' + (parseTime(state.config.updated_at) || state.config.updated_at || 'just now');\n notify('Config saved for ' + jobType, 'success');\n } catch (e) {\n notify('Failed to save config: ' + e.message, 'error');\n }\n }\n\n function getMaxResults() {\n var raw = String(document.getElementById('plugin-admin-max-results').value || '').trim();\n if (!raw) {\n return 0;\n }\n var parsed = parseInt(raw, 10);\n if (Number.isNaN(parsed) || parsed < 0) {\n return 0;\n }\n return parsed;\n }\n\n async function runDetection() {\n var jobType = state.selectedJobType || getSelectedJobType();\n if (!jobType) {\n notify('Select a job type first.', 'error');\n return;\n }\n\n try {\n var data = await pluginRequest('POST', '/api/plugin/job-types/' + encodePath(jobType) + '/detect', {\n max_results: getMaxResults(),\n });\n state.lastDetectionByJobType[jobType] = data;\n renderDetectionResult(data);\n } catch (e) {\n if (e && e.responseData) {\n state.lastDetectionByJobType[jobType] = e.responseData;\n renderDetectionResult(e.responseData);\n }\n notify('Detection failed: ' + e.message, 'error');\n return;\n }\n\n try {\n await refreshJobsAndActivities();\n } catch (refreshErr) {\n notify('Detection succeeded, but monitoring refresh failed: ' + refreshErr.message, 'error');\n }\n }\n\n async function runWorkflow() {\n var jobType = state.selectedJobType || getSelectedJobType();\n if (!jobType) {\n notify('Select a job type first.', 'error');\n return;\n }\n\n try {\n var data = await pluginRequest('POST', '/api/plugin/job-types/' + encodePath(jobType) + '/run', {\n max_results: getMaxResults(),\n });\n var resultRoot = document.getElementById('plugin-detection-results');\n resultRoot.innerHTML = '<div class=\"mb-2\"><strong>Workflow completed</strong></div>' +\n '<div>Detected: <strong>' + escapeHtml(String(data.detected_count || 0)) + '</strong></div>' +\n '<div>Ready to Execute: <strong>' + escapeHtml(String(data.ready_to_execute_count || 0)) + '</strong></div>' +\n '<div>Skipped (Already Active): <strong>' + escapeHtml(String(data.skipped_active_count || 0)) + '</strong></div>' +\n '<div>Executed: <strong>' + escapeHtml(String(data.executed_count || 0)) + '</strong></div>' +\n '<div class=\"text-success\">Success: ' + escapeHtml(String(data.success_count || 0)) + '</div>' +\n '<div class=\"text-danger\">Errors: ' + escapeHtml(String(data.error_count || 0)) + '</div>';\n await loadRunHistory(jobType);\n await refreshJobsAndActivities();\n } catch (e) {\n notify('Workflow run failed: ' + e.message, 'error');\n }\n }\n\n async function refreshJobsAndActivities() {\n var executionStateFilter = document.getElementById('plugin-monitor-job-state-filter');\n\n state.monitorExecutionJobState = executionStateFilter ? String(executionStateFilter.value || '').trim() : '';\n\n var allJobsPromise = pluginRequest('GET', '/api/plugin/jobs?limit=500');\n var allActivitiesPromise = pluginRequest('GET', '/api/plugin/activities?limit=500');\n var schedulerPromise = pluginRequest('GET', '/api/plugin/scheduler-states');\n var schedulerStatusPromise = pluginRequest('GET', '/api/plugin/scheduler-status');\n\n var allJobs = await allJobsPromise;\n var allActivities = await allActivitiesPromise;\n var schedulerStates = await schedulerPromise;\n var schedulerStatus = null;\n try {\n schedulerStatus = await schedulerStatusPromise;\n } catch (e) {\n schedulerStatus = null;\n }\n\n state.jobs = Array.isArray(allJobs) ? allJobs : [];\n state.activities = Array.isArray(allActivities) ? allActivities : [];\n state.allJobs = state.jobs;\n state.allActivities = state.activities;\n state.schedulerStates = Array.isArray(schedulerStates) ? schedulerStates : [];\n state.schedulerStatus = schedulerStatus && schedulerStatus.scheduler ? schedulerStatus.scheduler : null;\n renderQueueJobs();\n renderDetectionJobs();\n renderExecutionJobs();\n renderExecutionActivities();\n renderSchedulerStates();\n renderSchedulerStatus();\n renderStatus();\n renderJobTypeSummary();\n }\n\n async function refreshAll() {\n try {\n var previousSelectedJobType = state.selectedJobType;\n\n var workers = await pluginRequest('GET', '/api/plugin/workers');\n state.workers = Array.isArray(workers) ? workers : [];\n renderWorkers();\n\n var jobTypes = await pluginRequest('GET', '/api/plugin/job-types');\n state.jobTypes = Array.isArray(jobTypes) ? jobTypes : [];\n applyInitialNavigation();\n ensureActiveNavigation();\n renderTopTabs();\n renderNavigationState();\n\n if (!state.selectedJobType) {\n resetJobTypePanels();\n } else if (state.loadedJobType !== state.selectedJobType || previousSelectedJobType !== state.selectedJobType) {\n try {\n await loadDescriptorAndConfig(state.selectedJobType, false);\n } catch (loadError) {\n // Already rendered in UI.\n }\n }\n\n await refreshJobsAndActivities();\n } catch (e) {\n notify('Refresh failed: ' + e.message, 'error');\n }\n }\n\n function bindActions() {\n var monitorStateFilter = document.getElementById('plugin-monitor-job-state-filter');\n if (monitorStateFilter) {\n monitorStateFilter.addEventListener('change', function() {\n state.monitorExecutionJobState = String(monitorStateFilter.value || '').trim();\n renderExecutionJobs();\n });\n }\n\n var expireBtn = document.getElementById('plugin-expire-job-btn');\n if (expireBtn) {\n expireBtn.addEventListener('click', function() {\n var jobID = String(expireBtn.getAttribute('data-job-id') || '').trim();\n if (!jobID) {\n return;\n }\n expireJob(jobID);\n });\n }\n\n document.getElementById('plugin-refresh-all-btn').addEventListener('click', function() {\n refreshAll();\n });\n\n document.getElementById('plugin-refresh-schema-btn').addEventListener('click', async function() {\n var jobType = getSelectedJobType();\n if (!jobType) {\n notify('Select a job type first.', 'error');\n return;\n }\n try {\n await loadDescriptorAndConfig(jobType, true);\n notify('Schema refreshed for ' + jobType, 'success');\n } catch (e) {\n notify('Schema refresh failed: ' + e.message, 'error');\n }\n });\n\n document.getElementById('plugin-save-config-btn').addEventListener('click', function() {\n saveConfig();\n });\n\n document.getElementById('plugin-trigger-detection-btn').addEventListener('click', function() {\n runDetection();\n });\n\n document.getElementById('plugin-run-workflow-btn').addEventListener('click', function() {\n runWorkflow();\n });\n\n page.addEventListener('click', async function(event) {\n var target = event.target;\n if (!target) {\n return;\n }\n\n var topTab = target.closest('[data-plugin-top-tab]');\n if (topTab) {\n event.preventDefault();\n var topTabKey = String(topTab.getAttribute('data-plugin-top-tab') || '').trim();\n if (!topTabKey) {\n return;\n }\n if (topTabKey === 'overview') {\n state.activeTopTab = 'overview';\n renderNavigationState();\n return;\n }\n\n var jobType = parseJobTypeFromTopTab(topTabKey);\n if (!jobType) {\n return;\n }\n state.activeTopTab = topTabKey;\n state.selectedJobType = jobType;\n ensureActiveNavigation();\n renderNavigationState();\n if (state.loadedJobType !== jobType) {\n try {\n await loadDescriptorAndConfig(jobType, false);\n } catch (e) {\n // Already rendered in UI.\n }\n } else {\n if (state.lastDetectionByJobType && state.lastDetectionByJobType[jobType]) {\n renderDetectionResult(state.lastDetectionByJobType[jobType]);\n } else {\n renderDetectionResult(null);\n }\n await loadRunHistory(jobType);\n }\n renderQueueJobs();\n renderDetectionJobs();\n renderExecutionJobs();\n renderExecutionActivities();\n return;\n }\n\n var subTab = target.closest('[data-plugin-subtab]');\n if (subTab) {\n event.preventDefault();\n var subTabKey = normalizeSubTab(subTab.getAttribute('data-plugin-subtab'));\n state.activeSubTab = subTabKey;\n renderNavigationState();\n return;\n }\n\n var trigger = target.closest('.plugin-job-link');\n if (!trigger) {\n return;\n }\n event.preventDefault();\n var jobID = trigger.getAttribute('data-job-id');\n if (!jobID) {\n return;\n }\n openJobDetail(jobID);\n });\n }\n\n async function init() {\n bindActions();\n renderTopTabs();\n ensureActiveNavigation();\n renderNavigationState();\n await refreshAll();\n\n state.refreshTimer = setInterval(function() {\n refreshAll();\n }, 3000);\n }\n\n window.addEventListener('beforeunload', function() {\n if (state.refreshTimer) {\n clearInterval(state.refreshTimer);\n state.refreshTimer = null;\n }\n });\n\n init();\n })();\n </script>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
diff --git a/weed/pb/worker.proto b/weed/pb/worker.proto
index bfb7751511..9f96844736 100644
--- a/weed/pb/worker.proto
+++ b/weed/pb/worker.proto
@@ -157,10 +157,21 @@ message TaskTarget {
+// BalanceMoveSpec describes a single volume move within a batch balance job
+message BalanceMoveSpec {
+ uint32 volume_id = 1; // Volume to move
+ string source_node = 2; // Source server address (host:port)
+ string target_node = 3; // Destination server address (host:port)
+ string collection = 4; // Collection name
+ uint64 volume_size = 5; // Volume size in bytes (informational)
+}
+
// BalanceTaskParams for volume balancing operations
message BalanceTaskParams {
bool force_move = 1; // Force move even with conflicts
int32 timeout_seconds = 2; // Operation timeout
+ int32 max_concurrent_moves = 3; // Max concurrent moves in a batch job (0 = default 5)
+ repeated BalanceMoveSpec moves = 4; // Batch: multiple volume moves in one job
}
// ReplicationTaskParams for adding replicas
diff --git a/weed/pb/worker_pb/worker.pb.go b/weed/pb/worker_pb/worker.pb.go
index 1502f78678..7677b0837e 100644
--- a/weed/pb/worker_pb/worker.pb.go
+++ b/weed/pb/worker_pb/worker.pb.go
@@ -1331,18 +1331,97 @@ func (x *TaskTarget) GetEstimatedSize() uint64 {
return 0
}
+// BalanceMoveSpec describes a single volume move within a batch balance job
+type BalanceMoveSpec struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ VolumeId uint32 `protobuf:"varint,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"` // Volume to move
+ SourceNode string `protobuf:"bytes,2,opt,name=source_node,json=sourceNode,proto3" json:"source_node,omitempty"` // Source server address (host:port)
+ TargetNode string `protobuf:"bytes,3,opt,name=target_node,json=targetNode,proto3" json:"target_node,omitempty"` // Destination server address (host:port)
+ Collection string `protobuf:"bytes,4,opt,name=collection,proto3" json:"collection,omitempty"` // Collection name
+ VolumeSize uint64 `protobuf:"varint,5,opt,name=volume_size,json=volumeSize,proto3" json:"volume_size,omitempty"` // Volume size in bytes (informational)
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *BalanceMoveSpec) Reset() {
+ *x = BalanceMoveSpec{}
+ mi := &file_worker_proto_msgTypes[13]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *BalanceMoveSpec) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*BalanceMoveSpec) ProtoMessage() {}
+
+func (x *BalanceMoveSpec) ProtoReflect() protoreflect.Message {
+ mi := &file_worker_proto_msgTypes[13]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use BalanceMoveSpec.ProtoReflect.Descriptor instead.
+func (*BalanceMoveSpec) Descriptor() ([]byte, []int) {
+ return file_worker_proto_rawDescGZIP(), []int{13}
+}
+
+func (x *BalanceMoveSpec) GetVolumeId() uint32 {
+ if x != nil {
+ return x.VolumeId
+ }
+ return 0
+}
+
+func (x *BalanceMoveSpec) GetSourceNode() string {
+ if x != nil {
+ return x.SourceNode
+ }
+ return ""
+}
+
+func (x *BalanceMoveSpec) GetTargetNode() string {
+ if x != nil {
+ return x.TargetNode
+ }
+ return ""
+}
+
+func (x *BalanceMoveSpec) GetCollection() string {
+ if x != nil {
+ return x.Collection
+ }
+ return ""
+}
+
+func (x *BalanceMoveSpec) GetVolumeSize() uint64 {
+ if x != nil {
+ return x.VolumeSize
+ }
+ return 0
+}
+
// BalanceTaskParams for volume balancing operations
type BalanceTaskParams struct {
- state protoimpl.MessageState `protogen:"open.v1"`
- ForceMove bool `protobuf:"varint,1,opt,name=force_move,json=forceMove,proto3" json:"force_move,omitempty"` // Force move even with conflicts
- TimeoutSeconds int32 `protobuf:"varint,2,opt,name=timeout_seconds,json=timeoutSeconds,proto3" json:"timeout_seconds,omitempty"` // Operation timeout
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ state protoimpl.MessageState `protogen:"open.v1"`
+ ForceMove bool `protobuf:"varint,1,opt,name=force_move,json=forceMove,proto3" json:"force_move,omitempty"` // Force move even with conflicts
+ TimeoutSeconds int32 `protobuf:"varint,2,opt,name=timeout_seconds,json=timeoutSeconds,proto3" json:"timeout_seconds,omitempty"` // Operation timeout
+ MaxConcurrentMoves int32 `protobuf:"varint,3,opt,name=max_concurrent_moves,json=maxConcurrentMoves,proto3" json:"max_concurrent_moves,omitempty"` // Max concurrent moves in a batch job (0 = default 5)
+ Moves []*BalanceMoveSpec `protobuf:"bytes,4,rep,name=moves,proto3" json:"moves,omitempty"` // Batch: multiple volume moves in one job
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *BalanceTaskParams) Reset() {
*x = BalanceTaskParams{}
- mi := &file_worker_proto_msgTypes[13]
+ mi := &file_worker_proto_msgTypes[14]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1354,7 +1433,7 @@ func (x *BalanceTaskParams) String() string {
func (*BalanceTaskParams) ProtoMessage() {}
func (x *BalanceTaskParams) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[13]
+ mi := &file_worker_proto_msgTypes[14]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1367,7 +1446,7 @@ func (x *BalanceTaskParams) ProtoReflect() protoreflect.Message {
// Deprecated: Use BalanceTaskParams.ProtoReflect.Descriptor instead.
func (*BalanceTaskParams) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{13}
+ return file_worker_proto_rawDescGZIP(), []int{14}
}
func (x *BalanceTaskParams) GetForceMove() bool {
@@ -1384,6 +1463,20 @@ func (x *BalanceTaskParams) GetTimeoutSeconds() int32 {
return 0
}
+func (x *BalanceTaskParams) GetMaxConcurrentMoves() int32 {
+ if x != nil {
+ return x.MaxConcurrentMoves
+ }
+ return 0
+}
+
+func (x *BalanceTaskParams) GetMoves() []*BalanceMoveSpec {
+ if x != nil {
+ return x.Moves
+ }
+ return nil
+}
+
// ReplicationTaskParams for adding replicas
type ReplicationTaskParams struct {
state protoimpl.MessageState `protogen:"open.v1"`
@@ -1395,7 +1488,7 @@ type ReplicationTaskParams struct {
func (x *ReplicationTaskParams) Reset() {
*x = ReplicationTaskParams{}
- mi := &file_worker_proto_msgTypes[14]
+ mi := &file_worker_proto_msgTypes[15]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1407,7 +1500,7 @@ func (x *ReplicationTaskParams) String() string {
func (*ReplicationTaskParams) ProtoMessage() {}
func (x *ReplicationTaskParams) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[14]
+ mi := &file_worker_proto_msgTypes[15]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1420,7 +1513,7 @@ func (x *ReplicationTaskParams) ProtoReflect() protoreflect.Message {
// Deprecated: Use ReplicationTaskParams.ProtoReflect.Descriptor instead.
func (*ReplicationTaskParams) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{14}
+ return file_worker_proto_rawDescGZIP(), []int{15}
}
func (x *ReplicationTaskParams) GetReplicaCount() int32 {
@@ -1452,7 +1545,7 @@ type TaskUpdate struct {
func (x *TaskUpdate) Reset() {
*x = TaskUpdate{}
- mi := &file_worker_proto_msgTypes[15]
+ mi := &file_worker_proto_msgTypes[16]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1464,7 +1557,7 @@ func (x *TaskUpdate) String() string {
func (*TaskUpdate) ProtoMessage() {}
func (x *TaskUpdate) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[15]
+ mi := &file_worker_proto_msgTypes[16]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1477,7 +1570,7 @@ func (x *TaskUpdate) ProtoReflect() protoreflect.Message {
// Deprecated: Use TaskUpdate.ProtoReflect.Descriptor instead.
func (*TaskUpdate) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{15}
+ return file_worker_proto_rawDescGZIP(), []int{16}
}
func (x *TaskUpdate) GetTaskId() string {
@@ -1537,7 +1630,7 @@ type TaskComplete struct {
func (x *TaskComplete) Reset() {
*x = TaskComplete{}
- mi := &file_worker_proto_msgTypes[16]
+ mi := &file_worker_proto_msgTypes[17]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1549,7 +1642,7 @@ func (x *TaskComplete) String() string {
func (*TaskComplete) ProtoMessage() {}
func (x *TaskComplete) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[16]
+ mi := &file_worker_proto_msgTypes[17]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1562,7 +1655,7 @@ func (x *TaskComplete) ProtoReflect() protoreflect.Message {
// Deprecated: Use TaskComplete.ProtoReflect.Descriptor instead.
func (*TaskComplete) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{16}
+ return file_worker_proto_rawDescGZIP(), []int{17}
}
func (x *TaskComplete) GetTaskId() string {
@@ -1619,7 +1712,7 @@ type TaskCancellation struct {
func (x *TaskCancellation) Reset() {
*x = TaskCancellation{}
- mi := &file_worker_proto_msgTypes[17]
+ mi := &file_worker_proto_msgTypes[18]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1631,7 +1724,7 @@ func (x *TaskCancellation) String() string {
func (*TaskCancellation) ProtoMessage() {}
func (x *TaskCancellation) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[17]
+ mi := &file_worker_proto_msgTypes[18]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1644,7 +1737,7 @@ func (x *TaskCancellation) ProtoReflect() protoreflect.Message {
// Deprecated: Use TaskCancellation.ProtoReflect.Descriptor instead.
func (*TaskCancellation) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{17}
+ return file_worker_proto_rawDescGZIP(), []int{18}
}
func (x *TaskCancellation) GetTaskId() string {
@@ -1680,7 +1773,7 @@ type WorkerShutdown struct {
func (x *WorkerShutdown) Reset() {
*x = WorkerShutdown{}
- mi := &file_worker_proto_msgTypes[18]
+ mi := &file_worker_proto_msgTypes[19]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1692,7 +1785,7 @@ func (x *WorkerShutdown) String() string {
func (*WorkerShutdown) ProtoMessage() {}
func (x *WorkerShutdown) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[18]
+ mi := &file_worker_proto_msgTypes[19]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1705,7 +1798,7 @@ func (x *WorkerShutdown) ProtoReflect() protoreflect.Message {
// Deprecated: Use WorkerShutdown.ProtoReflect.Descriptor instead.
func (*WorkerShutdown) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{18}
+ return file_worker_proto_rawDescGZIP(), []int{19}
}
func (x *WorkerShutdown) GetWorkerId() string {
@@ -1740,7 +1833,7 @@ type AdminShutdown struct {
func (x *AdminShutdown) Reset() {
*x = AdminShutdown{}
- mi := &file_worker_proto_msgTypes[19]
+ mi := &file_worker_proto_msgTypes[20]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1752,7 +1845,7 @@ func (x *AdminShutdown) String() string {
func (*AdminShutdown) ProtoMessage() {}
func (x *AdminShutdown) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[19]
+ mi := &file_worker_proto_msgTypes[20]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1765,7 +1858,7 @@ func (x *AdminShutdown) ProtoReflect() protoreflect.Message {
// Deprecated: Use AdminShutdown.ProtoReflect.Descriptor instead.
func (*AdminShutdown) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{19}
+ return file_worker_proto_rawDescGZIP(), []int{20}
}
func (x *AdminShutdown) GetReason() string {
@@ -1798,7 +1891,7 @@ type TaskLogRequest struct {
func (x *TaskLogRequest) Reset() {
*x = TaskLogRequest{}
- mi := &file_worker_proto_msgTypes[20]
+ mi := &file_worker_proto_msgTypes[21]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1810,7 +1903,7 @@ func (x *TaskLogRequest) String() string {
func (*TaskLogRequest) ProtoMessage() {}
func (x *TaskLogRequest) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[20]
+ mi := &file_worker_proto_msgTypes[21]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1823,7 +1916,7 @@ func (x *TaskLogRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use TaskLogRequest.ProtoReflect.Descriptor instead.
func (*TaskLogRequest) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{20}
+ return file_worker_proto_rawDescGZIP(), []int{21}
}
func (x *TaskLogRequest) GetTaskId() string {
@@ -1890,7 +1983,7 @@ type TaskLogResponse struct {
func (x *TaskLogResponse) Reset() {
*x = TaskLogResponse{}
- mi := &file_worker_proto_msgTypes[21]
+ mi := &file_worker_proto_msgTypes[22]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1902,7 +1995,7 @@ func (x *TaskLogResponse) String() string {
func (*TaskLogResponse) ProtoMessage() {}
func (x *TaskLogResponse) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[21]
+ mi := &file_worker_proto_msgTypes[22]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1915,7 +2008,7 @@ func (x *TaskLogResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use TaskLogResponse.ProtoReflect.Descriptor instead.
func (*TaskLogResponse) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{21}
+ return file_worker_proto_rawDescGZIP(), []int{22}
}
func (x *TaskLogResponse) GetTaskId() string {
@@ -1983,7 +2076,7 @@ type TaskLogMetadata struct {
func (x *TaskLogMetadata) Reset() {
*x = TaskLogMetadata{}
- mi := &file_worker_proto_msgTypes[22]
+ mi := &file_worker_proto_msgTypes[23]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1995,7 +2088,7 @@ func (x *TaskLogMetadata) String() string {
func (*TaskLogMetadata) ProtoMessage() {}
func (x *TaskLogMetadata) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[22]
+ mi := &file_worker_proto_msgTypes[23]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2008,7 +2101,7 @@ func (x *TaskLogMetadata) ProtoReflect() protoreflect.Message {
// Deprecated: Use TaskLogMetadata.ProtoReflect.Descriptor instead.
func (*TaskLogMetadata) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{22}
+ return file_worker_proto_rawDescGZIP(), []int{23}
}
func (x *TaskLogMetadata) GetTaskId() string {
@@ -2124,7 +2217,7 @@ type TaskLogEntry struct {
func (x *TaskLogEntry) Reset() {
*x = TaskLogEntry{}
- mi := &file_worker_proto_msgTypes[23]
+ mi := &file_worker_proto_msgTypes[24]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2136,7 +2229,7 @@ func (x *TaskLogEntry) String() string {
func (*TaskLogEntry) ProtoMessage() {}
func (x *TaskLogEntry) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[23]
+ mi := &file_worker_proto_msgTypes[24]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2149,7 +2242,7 @@ func (x *TaskLogEntry) ProtoReflect() protoreflect.Message {
// Deprecated: Use TaskLogEntry.ProtoReflect.Descriptor instead.
func (*TaskLogEntry) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{23}
+ return file_worker_proto_rawDescGZIP(), []int{24}
}
func (x *TaskLogEntry) GetTimestamp() int64 {
@@ -2212,7 +2305,7 @@ type MaintenanceConfig struct {
func (x *MaintenanceConfig) Reset() {
*x = MaintenanceConfig{}
- mi := &file_worker_proto_msgTypes[24]
+ mi := &file_worker_proto_msgTypes[25]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2224,7 +2317,7 @@ func (x *MaintenanceConfig) String() string {
func (*MaintenanceConfig) ProtoMessage() {}
func (x *MaintenanceConfig) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[24]
+ mi := &file_worker_proto_msgTypes[25]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2237,7 +2330,7 @@ func (x *MaintenanceConfig) ProtoReflect() protoreflect.Message {
// Deprecated: Use MaintenanceConfig.ProtoReflect.Descriptor instead.
func (*MaintenanceConfig) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{24}
+ return file_worker_proto_rawDescGZIP(), []int{25}
}
func (x *MaintenanceConfig) GetEnabled() bool {
@@ -2316,7 +2409,7 @@ type MaintenancePolicy struct {
func (x *MaintenancePolicy) Reset() {
*x = MaintenancePolicy{}
- mi := &file_worker_proto_msgTypes[25]
+ mi := &file_worker_proto_msgTypes[26]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2328,7 +2421,7 @@ func (x *MaintenancePolicy) String() string {
func (*MaintenancePolicy) ProtoMessage() {}
func (x *MaintenancePolicy) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[25]
+ mi := &file_worker_proto_msgTypes[26]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2341,7 +2434,7 @@ func (x *MaintenancePolicy) ProtoReflect() protoreflect.Message {
// Deprecated: Use MaintenancePolicy.ProtoReflect.Descriptor instead.
func (*MaintenancePolicy) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{25}
+ return file_worker_proto_rawDescGZIP(), []int{26}
}
func (x *MaintenancePolicy) GetTaskPolicies() map[string]*TaskPolicy {
@@ -2394,7 +2487,7 @@ type TaskPolicy struct {
func (x *TaskPolicy) Reset() {
*x = TaskPolicy{}
- mi := &file_worker_proto_msgTypes[26]
+ mi := &file_worker_proto_msgTypes[27]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2406,7 +2499,7 @@ func (x *TaskPolicy) String() string {
func (*TaskPolicy) ProtoMessage() {}
func (x *TaskPolicy) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[26]
+ mi := &file_worker_proto_msgTypes[27]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2419,7 +2512,7 @@ func (x *TaskPolicy) ProtoReflect() protoreflect.Message {
// Deprecated: Use TaskPolicy.ProtoReflect.Descriptor instead.
func (*TaskPolicy) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{26}
+ return file_worker_proto_rawDescGZIP(), []int{27}
}
func (x *TaskPolicy) GetEnabled() bool {
@@ -2533,7 +2626,7 @@ type VacuumTaskConfig struct {
func (x *VacuumTaskConfig) Reset() {
*x = VacuumTaskConfig{}
- mi := &file_worker_proto_msgTypes[27]
+ mi := &file_worker_proto_msgTypes[28]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2545,7 +2638,7 @@ func (x *VacuumTaskConfig) String() string {
func (*VacuumTaskConfig) ProtoMessage() {}
func (x *VacuumTaskConfig) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[27]
+ mi := &file_worker_proto_msgTypes[28]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2558,7 +2651,7 @@ func (x *VacuumTaskConfig) ProtoReflect() protoreflect.Message {
// Deprecated: Use VacuumTaskConfig.ProtoReflect.Descriptor instead.
func (*VacuumTaskConfig) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{27}
+ return file_worker_proto_rawDescGZIP(), []int{28}
}
func (x *VacuumTaskConfig) GetGarbageThreshold() float64 {
@@ -2596,7 +2689,7 @@ type ErasureCodingTaskConfig struct {
func (x *ErasureCodingTaskConfig) Reset() {
*x = ErasureCodingTaskConfig{}
- mi := &file_worker_proto_msgTypes[28]
+ mi := &file_worker_proto_msgTypes[29]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2608,7 +2701,7 @@ func (x *ErasureCodingTaskConfig) String() string {
func (*ErasureCodingTaskConfig) ProtoMessage() {}
func (x *ErasureCodingTaskConfig) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[28]
+ mi := &file_worker_proto_msgTypes[29]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2621,7 +2714,7 @@ func (x *ErasureCodingTaskConfig) ProtoReflect() protoreflect.Message {
// Deprecated: Use ErasureCodingTaskConfig.ProtoReflect.Descriptor instead.
func (*ErasureCodingTaskConfig) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{28}
+ return file_worker_proto_rawDescGZIP(), []int{29}
}
func (x *ErasureCodingTaskConfig) GetFullnessRatio() float64 {
@@ -2670,7 +2763,7 @@ type BalanceTaskConfig struct {
func (x *BalanceTaskConfig) Reset() {
*x = BalanceTaskConfig{}
- mi := &file_worker_proto_msgTypes[29]
+ mi := &file_worker_proto_msgTypes[30]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2682,7 +2775,7 @@ func (x *BalanceTaskConfig) String() string {
func (*BalanceTaskConfig) ProtoMessage() {}
func (x *BalanceTaskConfig) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[29]
+ mi := &file_worker_proto_msgTypes[30]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2695,7 +2788,7 @@ func (x *BalanceTaskConfig) ProtoReflect() protoreflect.Message {
// Deprecated: Use BalanceTaskConfig.ProtoReflect.Descriptor instead.
func (*BalanceTaskConfig) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{29}
+ return file_worker_proto_rawDescGZIP(), []int{30}
}
func (x *BalanceTaskConfig) GetImbalanceThreshold() float64 {
@@ -2722,7 +2815,7 @@ type ReplicationTaskConfig struct {
func (x *ReplicationTaskConfig) Reset() {
*x = ReplicationTaskConfig{}
- mi := &file_worker_proto_msgTypes[30]
+ mi := &file_worker_proto_msgTypes[31]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2734,7 +2827,7 @@ func (x *ReplicationTaskConfig) String() string {
func (*ReplicationTaskConfig) ProtoMessage() {}
func (x *ReplicationTaskConfig) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[30]
+ mi := &file_worker_proto_msgTypes[31]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2747,7 +2840,7 @@ func (x *ReplicationTaskConfig) ProtoReflect() protoreflect.Message {
// Deprecated: Use ReplicationTaskConfig.ProtoReflect.Descriptor instead.
func (*ReplicationTaskConfig) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{30}
+ return file_worker_proto_rawDescGZIP(), []int{31}
}
func (x *ReplicationTaskConfig) GetTargetReplicaCount() int32 {
@@ -2791,7 +2884,7 @@ type MaintenanceTaskData struct {
func (x *MaintenanceTaskData) Reset() {
*x = MaintenanceTaskData{}
- mi := &file_worker_proto_msgTypes[31]
+ mi := &file_worker_proto_msgTypes[32]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -2803,7 +2896,7 @@ func (x *MaintenanceTaskData) String() string {
func (*MaintenanceTaskData) ProtoMessage() {}
func (x *MaintenanceTaskData) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[31]
+ mi := &file_worker_proto_msgTypes[32]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -2816,7 +2909,7 @@ func (x *MaintenanceTaskData) ProtoReflect() protoreflect.Message {
// Deprecated: Use MaintenanceTaskData.ProtoReflect.Descriptor instead.
func (*MaintenanceTaskData) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{31}
+ return file_worker_proto_rawDescGZIP(), []int{32}
}
func (x *MaintenanceTaskData) GetId() string {
@@ -3001,7 +3094,7 @@ type TaskAssignmentRecord struct {
func (x *TaskAssignmentRecord) Reset() {
*x = TaskAssignmentRecord{}
- mi := &file_worker_proto_msgTypes[32]
+ mi := &file_worker_proto_msgTypes[33]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -3013,7 +3106,7 @@ func (x *TaskAssignmentRecord) String() string {
func (*TaskAssignmentRecord) ProtoMessage() {}
func (x *TaskAssignmentRecord) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[32]
+ mi := &file_worker_proto_msgTypes[33]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -3026,7 +3119,7 @@ func (x *TaskAssignmentRecord) ProtoReflect() protoreflect.Message {
// Deprecated: Use TaskAssignmentRecord.ProtoReflect.Descriptor instead.
func (*TaskAssignmentRecord) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{32}
+ return file_worker_proto_rawDescGZIP(), []int{33}
}
func (x *TaskAssignmentRecord) GetWorkerId() string {
@@ -3078,7 +3171,7 @@ type TaskCreationMetrics struct {
func (x *TaskCreationMetrics) Reset() {
*x = TaskCreationMetrics{}
- mi := &file_worker_proto_msgTypes[33]
+ mi := &file_worker_proto_msgTypes[34]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -3090,7 +3183,7 @@ func (x *TaskCreationMetrics) String() string {
func (*TaskCreationMetrics) ProtoMessage() {}
func (x *TaskCreationMetrics) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[33]
+ mi := &file_worker_proto_msgTypes[34]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -3103,7 +3196,7 @@ func (x *TaskCreationMetrics) ProtoReflect() protoreflect.Message {
// Deprecated: Use TaskCreationMetrics.ProtoReflect.Descriptor instead.
func (*TaskCreationMetrics) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{33}
+ return file_worker_proto_rawDescGZIP(), []int{34}
}
func (x *TaskCreationMetrics) GetTriggerMetric() string {
@@ -3160,7 +3253,7 @@ type VolumeHealthMetrics struct {
func (x *VolumeHealthMetrics) Reset() {
*x = VolumeHealthMetrics{}
- mi := &file_worker_proto_msgTypes[34]
+ mi := &file_worker_proto_msgTypes[35]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -3172,7 +3265,7 @@ func (x *VolumeHealthMetrics) String() string {
func (*VolumeHealthMetrics) ProtoMessage() {}
func (x *VolumeHealthMetrics) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[34]
+ mi := &file_worker_proto_msgTypes[35]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -3185,7 +3278,7 @@ func (x *VolumeHealthMetrics) ProtoReflect() protoreflect.Message {
// Deprecated: Use VolumeHealthMetrics.ProtoReflect.Descriptor instead.
func (*VolumeHealthMetrics) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{34}
+ return file_worker_proto_rawDescGZIP(), []int{35}
}
func (x *VolumeHealthMetrics) GetTotalSize() uint64 {
@@ -3270,7 +3363,7 @@ type TaskStateFile struct {
func (x *TaskStateFile) Reset() {
*x = TaskStateFile{}
- mi := &file_worker_proto_msgTypes[35]
+ mi := &file_worker_proto_msgTypes[36]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -3282,7 +3375,7 @@ func (x *TaskStateFile) String() string {
func (*TaskStateFile) ProtoMessage() {}
func (x *TaskStateFile) ProtoReflect() protoreflect.Message {
- mi := &file_worker_proto_msgTypes[35]
+ mi := &file_worker_proto_msgTypes[36]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -3295,7 +3388,7 @@ func (x *TaskStateFile) ProtoReflect() protoreflect.Message {
// Deprecated: Use TaskStateFile.ProtoReflect.Descriptor instead.
func (*TaskStateFile) Descriptor() ([]byte, []int) {
- return file_worker_proto_rawDescGZIP(), []int{35}
+ return file_worker_proto_rawDescGZIP(), []int{36}
}
func (x *TaskStateFile) GetTask() *MaintenanceTaskData {
@@ -3441,11 +3534,24 @@ const file_worker_proto_rawDesc = "" +
"dataCenter\x12\x1b\n" +
"\tvolume_id\x18\x05 \x01(\rR\bvolumeId\x12\x1b\n" +
"\tshard_ids\x18\x06 \x03(\rR\bshardIds\x12%\n" +
- "\x0eestimated_size\x18\a \x01(\x04R\restimatedSize\"[\n" +
+ "\x0eestimated_size\x18\a \x01(\x04R\restimatedSize\"\xb1\x01\n" +
+ "\x0fBalanceMoveSpec\x12\x1b\n" +
+ "\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x1f\n" +
+ "\vsource_node\x18\x02 \x01(\tR\n" +
+ "sourceNode\x12\x1f\n" +
+ "\vtarget_node\x18\x03 \x01(\tR\n" +
+ "targetNode\x12\x1e\n" +
+ "\n" +
+ "collection\x18\x04 \x01(\tR\n" +
+ "collection\x12\x1f\n" +
+ "\vvolume_size\x18\x05 \x01(\x04R\n" +
+ "volumeSize\"\xbf\x01\n" +
"\x11BalanceTaskParams\x12\x1d\n" +
"\n" +
"force_move\x18\x01 \x01(\bR\tforceMove\x12'\n" +
- "\x0ftimeout_seconds\x18\x02 \x01(\x05R\x0etimeoutSeconds\"k\n" +
+ "\x0ftimeout_seconds\x18\x02 \x01(\x05R\x0etimeoutSeconds\x120\n" +
+ "\x14max_concurrent_moves\x18\x03 \x01(\x05R\x12maxConcurrentMoves\x120\n" +
+ "\x05moves\x18\x04 \x03(\v2\x1a.worker_pb.BalanceMoveSpecR\x05moves\"k\n" +
"\x15ReplicationTaskParams\x12#\n" +
"\rreplica_count\x18\x01 \x01(\x05R\freplicaCount\x12-\n" +
"\x12verify_consistency\x18\x02 \x01(\bR\x11verifyConsistency\"\x8e\x02\n" +
@@ -3667,7 +3773,7 @@ func file_worker_proto_rawDescGZIP() []byte {
return file_worker_proto_rawDescData
}
-var file_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 45)
+var file_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 46)
var file_worker_proto_goTypes = []any{
(*WorkerMessage)(nil), // 0: worker_pb.WorkerMessage
(*AdminMessage)(nil), // 1: worker_pb.AdminMessage
@@ -3682,89 +3788,91 @@ var file_worker_proto_goTypes = []any{
(*ErasureCodingTaskParams)(nil), // 10: worker_pb.ErasureCodingTaskParams
(*TaskSource)(nil), // 11: worker_pb.TaskSource
(*TaskTarget)(nil), // 12: worker_pb.TaskTarget
- (*BalanceTaskParams)(nil), // 13: worker_pb.BalanceTaskParams
- (*ReplicationTaskParams)(nil), // 14: worker_pb.ReplicationTaskParams
- (*TaskUpdate)(nil), // 15: worker_pb.TaskUpdate
- (*TaskComplete)(nil), // 16: worker_pb.TaskComplete
- (*TaskCancellation)(nil), // 17: worker_pb.TaskCancellation
- (*WorkerShutdown)(nil), // 18: worker_pb.WorkerShutdown
- (*AdminShutdown)(nil), // 19: worker_pb.AdminShutdown
- (*TaskLogRequest)(nil), // 20: worker_pb.TaskLogRequest
- (*TaskLogResponse)(nil), // 21: worker_pb.TaskLogResponse
- (*TaskLogMetadata)(nil), // 22: worker_pb.TaskLogMetadata
- (*TaskLogEntry)(nil), // 23: worker_pb.TaskLogEntry
- (*MaintenanceConfig)(nil), // 24: worker_pb.MaintenanceConfig
- (*MaintenancePolicy)(nil), // 25: worker_pb.MaintenancePolicy
- (*TaskPolicy)(nil), // 26: worker_pb.TaskPolicy
- (*VacuumTaskConfig)(nil), // 27: worker_pb.VacuumTaskConfig
- (*ErasureCodingTaskConfig)(nil), // 28: worker_pb.ErasureCodingTaskConfig
- (*BalanceTaskConfig)(nil), // 29: worker_pb.BalanceTaskConfig
- (*ReplicationTaskConfig)(nil), // 30: worker_pb.ReplicationTaskConfig
- (*MaintenanceTaskData)(nil), // 31: worker_pb.MaintenanceTaskData
- (*TaskAssignmentRecord)(nil), // 32: worker_pb.TaskAssignmentRecord
- (*TaskCreationMetrics)(nil), // 33: worker_pb.TaskCreationMetrics
- (*VolumeHealthMetrics)(nil), // 34: worker_pb.VolumeHealthMetrics
- (*TaskStateFile)(nil), // 35: worker_pb.TaskStateFile
- nil, // 36: worker_pb.WorkerRegistration.MetadataEntry
- nil, // 37: worker_pb.TaskAssignment.MetadataEntry
- nil, // 38: worker_pb.TaskUpdate.MetadataEntry
- nil, // 39: worker_pb.TaskComplete.ResultMetadataEntry
- nil, // 40: worker_pb.TaskLogMetadata.CustomDataEntry
- nil, // 41: worker_pb.TaskLogEntry.FieldsEntry
- nil, // 42: worker_pb.MaintenancePolicy.TaskPoliciesEntry
- nil, // 43: worker_pb.MaintenanceTaskData.TagsEntry
- nil, // 44: worker_pb.TaskCreationMetrics.AdditionalDataEntry
+ (*BalanceMoveSpec)(nil), // 13: worker_pb.BalanceMoveSpec
+ (*BalanceTaskParams)(nil), // 14: worker_pb.BalanceTaskParams
+ (*ReplicationTaskParams)(nil), // 15: worker_pb.ReplicationTaskParams
+ (*TaskUpdate)(nil), // 16: worker_pb.TaskUpdate
+ (*TaskComplete)(nil), // 17: worker_pb.TaskComplete
+ (*TaskCancellation)(nil), // 18: worker_pb.TaskCancellation
+ (*WorkerShutdown)(nil), // 19: worker_pb.WorkerShutdown
+ (*AdminShutdown)(nil), // 20: worker_pb.AdminShutdown
+ (*TaskLogRequest)(nil), // 21: worker_pb.TaskLogRequest
+ (*TaskLogResponse)(nil), // 22: worker_pb.TaskLogResponse
+ (*TaskLogMetadata)(nil), // 23: worker_pb.TaskLogMetadata
+ (*TaskLogEntry)(nil), // 24: worker_pb.TaskLogEntry
+ (*MaintenanceConfig)(nil), // 25: worker_pb.MaintenanceConfig
+ (*MaintenancePolicy)(nil), // 26: worker_pb.MaintenancePolicy
+ (*TaskPolicy)(nil), // 27: worker_pb.TaskPolicy
+ (*VacuumTaskConfig)(nil), // 28: worker_pb.VacuumTaskConfig
+ (*ErasureCodingTaskConfig)(nil), // 29: worker_pb.ErasureCodingTaskConfig
+ (*BalanceTaskConfig)(nil), // 30: worker_pb.BalanceTaskConfig
+ (*ReplicationTaskConfig)(nil), // 31: worker_pb.ReplicationTaskConfig
+ (*MaintenanceTaskData)(nil), // 32: worker_pb.MaintenanceTaskData
+ (*TaskAssignmentRecord)(nil), // 33: worker_pb.TaskAssignmentRecord
+ (*TaskCreationMetrics)(nil), // 34: worker_pb.TaskCreationMetrics
+ (*VolumeHealthMetrics)(nil), // 35: worker_pb.VolumeHealthMetrics
+ (*TaskStateFile)(nil), // 36: worker_pb.TaskStateFile
+ nil, // 37: worker_pb.WorkerRegistration.MetadataEntry
+ nil, // 38: worker_pb.TaskAssignment.MetadataEntry
+ nil, // 39: worker_pb.TaskUpdate.MetadataEntry
+ nil, // 40: worker_pb.TaskComplete.ResultMetadataEntry
+ nil, // 41: worker_pb.TaskLogMetadata.CustomDataEntry
+ nil, // 42: worker_pb.TaskLogEntry.FieldsEntry
+ nil, // 43: worker_pb.MaintenancePolicy.TaskPoliciesEntry
+ nil, // 44: worker_pb.MaintenanceTaskData.TagsEntry
+ nil, // 45: worker_pb.TaskCreationMetrics.AdditionalDataEntry
}
var file_worker_proto_depIdxs = []int32{
2, // 0: worker_pb.WorkerMessage.registration:type_name -> worker_pb.WorkerRegistration
4, // 1: worker_pb.WorkerMessage.heartbeat:type_name -> worker_pb.WorkerHeartbeat
6, // 2: worker_pb.WorkerMessage.task_request:type_name -> worker_pb.TaskRequest
- 15, // 3: worker_pb.WorkerMessage.task_update:type_name -> worker_pb.TaskUpdate
- 16, // 4: worker_pb.WorkerMessage.task_complete:type_name -> worker_pb.TaskComplete
- 18, // 5: worker_pb.WorkerMessage.shutdown:type_name -> worker_pb.WorkerShutdown
- 21, // 6: worker_pb.WorkerMessage.task_log_response:type_name -> worker_pb.TaskLogResponse
+ 16, // 3: worker_pb.WorkerMessage.task_update:type_name -> worker_pb.TaskUpdate
+ 17, // 4: worker_pb.WorkerMessage.task_complete:type_name -> worker_pb.TaskComplete
+ 19, // 5: worker_pb.WorkerMessage.shutdown:type_name -> worker_pb.WorkerShutdown
+ 22, // 6: worker_pb.WorkerMessage.task_log_response:type_name -> worker_pb.TaskLogResponse
3, // 7: worker_pb.AdminMessage.registration_response:type_name -> worker_pb.RegistrationResponse
5, // 8: worker_pb.AdminMessage.heartbeat_response:type_name -> worker_pb.HeartbeatResponse
7, // 9: worker_pb.AdminMessage.task_assignment:type_name -> worker_pb.TaskAssignment
- 17, // 10: worker_pb.AdminMessage.task_cancellation:type_name -> worker_pb.TaskCancellation
- 19, // 11: worker_pb.AdminMessage.admin_shutdown:type_name -> worker_pb.AdminShutdown
- 20, // 12: worker_pb.AdminMessage.task_log_request:type_name -> worker_pb.TaskLogRequest
- 36, // 13: worker_pb.WorkerRegistration.metadata:type_name -> worker_pb.WorkerRegistration.MetadataEntry
+ 18, // 10: worker_pb.AdminMessage.task_cancellation:type_name -> worker_pb.TaskCancellation
+ 20, // 11: worker_pb.AdminMessage.admin_shutdown:type_name -> worker_pb.AdminShutdown
+ 21, // 12: worker_pb.AdminMessage.task_log_request:type_name -> worker_pb.TaskLogRequest
+ 37, // 13: worker_pb.WorkerRegistration.metadata:type_name -> worker_pb.WorkerRegistration.MetadataEntry
8, // 14: worker_pb.TaskAssignment.params:type_name -> worker_pb.TaskParams
- 37, // 15: worker_pb.TaskAssignment.metadata:type_name -> worker_pb.TaskAssignment.MetadataEntry
+ 38, // 15: worker_pb.TaskAssignment.metadata:type_name -> worker_pb.TaskAssignment.MetadataEntry
11, // 16: worker_pb.TaskParams.sources:type_name -> worker_pb.TaskSource
12, // 17: worker_pb.TaskParams.targets:type_name -> worker_pb.TaskTarget
9, // 18: worker_pb.TaskParams.vacuum_params:type_name -> worker_pb.VacuumTaskParams
10, // 19: worker_pb.TaskParams.erasure_coding_params:type_name -> worker_pb.ErasureCodingTaskParams
- 13, // 20: worker_pb.TaskParams.balance_params:type_name -> worker_pb.BalanceTaskParams
- 14, // 21: worker_pb.TaskParams.replication_params:type_name -> worker_pb.ReplicationTaskParams
- 38, // 22: worker_pb.TaskUpdate.metadata:type_name -> worker_pb.TaskUpdate.MetadataEntry
- 39, // 23: worker_pb.TaskComplete.result_metadata:type_name -> worker_pb.TaskComplete.ResultMetadataEntry
- 22, // 24: worker_pb.TaskLogResponse.metadata:type_name -> worker_pb.TaskLogMetadata
- 23, // 25: worker_pb.TaskLogResponse.log_entries:type_name -> worker_pb.TaskLogEntry
- 40, // 26: worker_pb.TaskLogMetadata.custom_data:type_name -> worker_pb.TaskLogMetadata.CustomDataEntry
- 41, // 27: worker_pb.TaskLogEntry.fields:type_name -> worker_pb.TaskLogEntry.FieldsEntry
- 25, // 28: worker_pb.MaintenanceConfig.policy:type_name -> worker_pb.MaintenancePolicy
- 42, // 29: worker_pb.MaintenancePolicy.task_policies:type_name -> worker_pb.MaintenancePolicy.TaskPoliciesEntry
- 27, // 30: worker_pb.TaskPolicy.vacuum_config:type_name -> worker_pb.VacuumTaskConfig
- 28, // 31: worker_pb.TaskPolicy.erasure_coding_config:type_name -> worker_pb.ErasureCodingTaskConfig
- 29, // 32: worker_pb.TaskPolicy.balance_config:type_name -> worker_pb.BalanceTaskConfig
- 30, // 33: worker_pb.TaskPolicy.replication_config:type_name -> worker_pb.ReplicationTaskConfig
- 8, // 34: worker_pb.MaintenanceTaskData.typed_params:type_name -> worker_pb.TaskParams
- 32, // 35: worker_pb.MaintenanceTaskData.assignment_history:type_name -> worker_pb.TaskAssignmentRecord
- 43, // 36: worker_pb.MaintenanceTaskData.tags:type_name -> worker_pb.MaintenanceTaskData.TagsEntry
- 33, // 37: worker_pb.MaintenanceTaskData.creation_metrics:type_name -> worker_pb.TaskCreationMetrics
- 34, // 38: worker_pb.TaskCreationMetrics.volume_metrics:type_name -> worker_pb.VolumeHealthMetrics
- 44, // 39: worker_pb.TaskCreationMetrics.additional_data:type_name -> worker_pb.TaskCreationMetrics.AdditionalDataEntry
- 31, // 40: worker_pb.TaskStateFile.task:type_name -> worker_pb.MaintenanceTaskData
- 26, // 41: worker_pb.MaintenancePolicy.TaskPoliciesEntry.value:type_name -> worker_pb.TaskPolicy
- 0, // 42: worker_pb.WorkerService.WorkerStream:input_type -> worker_pb.WorkerMessage
- 1, // 43: worker_pb.WorkerService.WorkerStream:output_type -> worker_pb.AdminMessage
- 43, // [43:44] is the sub-list for method output_type
- 42, // [42:43] is the sub-list for method input_type
- 42, // [42:42] is the sub-list for extension type_name
- 42, // [42:42] is the sub-list for extension extendee
- 0, // [0:42] is the sub-list for field type_name
+ 14, // 20: worker_pb.TaskParams.balance_params:type_name -> worker_pb.BalanceTaskParams
+ 15, // 21: worker_pb.TaskParams.replication_params:type_name -> worker_pb.ReplicationTaskParams
+ 13, // 22: worker_pb.BalanceTaskParams.moves:type_name -> worker_pb.BalanceMoveSpec
+ 39, // 23: worker_pb.TaskUpdate.metadata:type_name -> worker_pb.TaskUpdate.MetadataEntry
+ 40, // 24: worker_pb.TaskComplete.result_metadata:type_name -> worker_pb.TaskComplete.ResultMetadataEntry
+ 23, // 25: worker_pb.TaskLogResponse.metadata:type_name -> worker_pb.TaskLogMetadata
+ 24, // 26: worker_pb.TaskLogResponse.log_entries:type_name -> worker_pb.TaskLogEntry
+ 41, // 27: worker_pb.TaskLogMetadata.custom_data:type_name -> worker_pb.TaskLogMetadata.CustomDataEntry
+ 42, // 28: worker_pb.TaskLogEntry.fields:type_name -> worker_pb.TaskLogEntry.FieldsEntry
+ 26, // 29: worker_pb.MaintenanceConfig.policy:type_name -> worker_pb.MaintenancePolicy
+ 43, // 30: worker_pb.MaintenancePolicy.task_policies:type_name -> worker_pb.MaintenancePolicy.TaskPoliciesEntry
+ 28, // 31: worker_pb.TaskPolicy.vacuum_config:type_name -> worker_pb.VacuumTaskConfig
+ 29, // 32: worker_pb.TaskPolicy.erasure_coding_config:type_name -> worker_pb.ErasureCodingTaskConfig
+ 30, // 33: worker_pb.TaskPolicy.balance_config:type_name -> worker_pb.BalanceTaskConfig
+ 31, // 34: worker_pb.TaskPolicy.replication_config:type_name -> worker_pb.ReplicationTaskConfig
+ 8, // 35: worker_pb.MaintenanceTaskData.typed_params:type_name -> worker_pb.TaskParams
+ 33, // 36: worker_pb.MaintenanceTaskData.assignment_history:type_name -> worker_pb.TaskAssignmentRecord
+ 44, // 37: worker_pb.MaintenanceTaskData.tags:type_name -> worker_pb.MaintenanceTaskData.TagsEntry
+ 34, // 38: worker_pb.MaintenanceTaskData.creation_metrics:type_name -> worker_pb.TaskCreationMetrics
+ 35, // 39: worker_pb.TaskCreationMetrics.volume_metrics:type_name -> worker_pb.VolumeHealthMetrics
+ 45, // 40: worker_pb.TaskCreationMetrics.additional_data:type_name -> worker_pb.TaskCreationMetrics.AdditionalDataEntry
+ 32, // 41: worker_pb.TaskStateFile.task:type_name -> worker_pb.MaintenanceTaskData
+ 27, // 42: worker_pb.MaintenancePolicy.TaskPoliciesEntry.value:type_name -> worker_pb.TaskPolicy
+ 0, // 43: worker_pb.WorkerService.WorkerStream:input_type -> worker_pb.WorkerMessage
+ 1, // 44: worker_pb.WorkerService.WorkerStream:output_type -> worker_pb.AdminMessage
+ 44, // [44:45] is the sub-list for method output_type
+ 43, // [43:44] is the sub-list for method input_type
+ 43, // [43:43] is the sub-list for extension type_name
+ 43, // [43:43] is the sub-list for extension extendee
+ 0, // [0:43] is the sub-list for field type_name
}
func init() { file_worker_proto_init() }
@@ -3795,7 +3903,7 @@ func file_worker_proto_init() {
(*TaskParams_BalanceParams)(nil),
(*TaskParams_ReplicationParams)(nil),
}
- file_worker_proto_msgTypes[26].OneofWrappers = []any{
+ file_worker_proto_msgTypes[27].OneofWrappers = []any{
(*TaskPolicy_VacuumConfig)(nil),
(*TaskPolicy_ErasureCodingConfig)(nil),
(*TaskPolicy_BalanceConfig)(nil),
@@ -3807,7 +3915,7 @@ func file_worker_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_worker_proto_rawDesc), len(file_worker_proto_rawDesc)),
NumEnums: 0,
- NumMessages: 45,
+ NumMessages: 46,
NumExtensions: 0,
NumServices: 1,
},
diff --git a/weed/plugin/worker/admin_script_handler.go b/weed/plugin/worker/admin_script_handler.go
index 5338a11626..8aee33a3ce 100644
--- a/weed/plugin/worker/admin_script_handler.go
+++ b/weed/plugin/worker/admin_script_handler.go
@@ -284,6 +284,7 @@ func (h *AdminScriptHandler) Execute(ctx context.Context, request *plugin_pb.Exe
_, _ = fmt.Fprintf(output, "$ %s\n", commandLine)
found := false
+ sendBroken := false
for _, command := range shell.Commands {
if command.Name() != cmd.Name {
continue
@@ -292,7 +293,7 @@ func (h *AdminScriptHandler) Execute(ctx context.Context, request *plugin_pb.Exe
if err := command.Do(cmd.Args, commandEnv, output); err != nil {
msg := fmt.Sprintf("%s: %v", cmd.Name, err)
errorMessages = append(errorMessages, msg)
- _ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
+ if sendErr := sender.SendProgress(&plugin_pb.JobProgressUpdate{
State: plugin_pb.JobState_JOB_STATE_RUNNING,
ProgressPercent: percentProgress(executed+1, len(execCommands)),
Stage: "error",
@@ -300,15 +301,20 @@ func (h *AdminScriptHandler) Execute(ctx context.Context, request *plugin_pb.Exe
Activities: []*plugin_pb.ActivityEvent{
BuildExecutorActivity("error", msg),
},
- })
+ }); sendErr != nil {
+ sendBroken = true
+ }
}
break
}
+ if sendBroken {
+ break
+ }
if !found {
msg := fmt.Sprintf("unknown admin command: %s", cmd.Name)
errorMessages = append(errorMessages, msg)
- _ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
+ if sendErr := sender.SendProgress(&plugin_pb.JobProgressUpdate{
State: plugin_pb.JobState_JOB_STATE_RUNNING,
ProgressPercent: percentProgress(executed+1, len(execCommands)),
Stage: "error",
@@ -316,12 +322,14 @@ func (h *AdminScriptHandler) Execute(ctx context.Context, request *plugin_pb.Exe
Activities: []*plugin_pb.ActivityEvent{
BuildExecutorActivity("error", msg),
},
- })
+ }); sendErr != nil {
+ break
+ }
}
executed++
progress := percentProgress(executed, len(execCommands))
- _ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
+ if sendErr := sender.SendProgress(&plugin_pb.JobProgressUpdate{
State: plugin_pb.JobState_JOB_STATE_RUNNING,
ProgressPercent: progress,
Stage: "running",
@@ -329,7 +337,9 @@ func (h *AdminScriptHandler) Execute(ctx context.Context, request *plugin_pb.Exe
Activities: []*plugin_pb.ActivityEvent{
BuildExecutorActivity("running", commandLine),
},
- })
+ }); sendErr != nil {
+ break
+ }
}
scriptHash := hashAdminScript(script)
diff --git a/weed/plugin/worker/erasure_coding_handler.go b/weed/plugin/worker/erasure_coding_handler.go
index 881181ae6d..d5f32c3f41 100644
--- a/weed/plugin/worker/erasure_coding_handler.go
+++ b/weed/plugin/worker/erasure_coding_handler.go
@@ -518,12 +518,14 @@ func (h *ErasureCodingHandler) Execute(
params.Collection,
h.grpcDialOption,
)
+ execCtx, execCancel := context.WithCancel(ctx)
+ defer execCancel()
task.SetProgressCallback(func(progress float64, stage string) {
message := fmt.Sprintf("erasure coding progress %.0f%%", progress)
if strings.TrimSpace(stage) != "" {
message = stage
}
- _ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
+ if err := sender.SendProgress(&plugin_pb.JobProgressUpdate{
JobId: request.Job.JobId,
JobType: request.Job.JobType,
State: plugin_pb.JobState_JOB_STATE_RUNNING,
@@ -533,7 +535,9 @@ func (h *ErasureCodingHandler) Execute(
Activities: []*plugin_pb.ActivityEvent{
BuildExecutorActivity(stage, message),
},
- })
+ }); err != nil {
+ execCancel()
+ }
})
if err := sender.SendProgress(&plugin_pb.JobProgressUpdate{
@@ -550,7 +554,7 @@ func (h *ErasureCodingHandler) Execute(
return err
}
- if err := task.Execute(ctx, params); err != nil {
+ if err := task.Execute(execCtx, params); err != nil {
_ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
JobId: request.Job.JobId,
JobType: request.Job.JobType,
diff --git a/weed/plugin/worker/vacuum_handler.go b/weed/plugin/worker/vacuum_handler.go
index c520e7efca..d1a93d2996 100644
--- a/weed/plugin/worker/vacuum_handler.go
+++ b/weed/plugin/worker/vacuum_handler.go
@@ -427,12 +427,14 @@ func (h *VacuumHandler) Execute(ctx context.Context, request *plugin_pb.ExecuteJ
params.Collection,
h.grpcDialOption,
)
+ execCtx, execCancel := context.WithCancel(ctx)
+ defer execCancel()
task.SetProgressCallback(func(progress float64, stage string) {
message := fmt.Sprintf("vacuum progress %.0f%%", progress)
if strings.TrimSpace(stage) != "" {
message = stage
}
- _ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
+ if err := sender.SendProgress(&plugin_pb.JobProgressUpdate{
JobId: request.Job.JobId,
JobType: request.Job.JobType,
State: plugin_pb.JobState_JOB_STATE_RUNNING,
@@ -442,7 +444,9 @@ func (h *VacuumHandler) Execute(ctx context.Context, request *plugin_pb.ExecuteJ
Activities: []*plugin_pb.ActivityEvent{
BuildExecutorActivity(stage, message),
},
- })
+ }); err != nil {
+ execCancel()
+ }
})
if err := sender.SendProgress(&plugin_pb.JobProgressUpdate{
@@ -459,7 +463,7 @@ func (h *VacuumHandler) Execute(ctx context.Context, request *plugin_pb.ExecuteJ
return err
}
- if err := task.Execute(ctx, params); err != nil {
+ if err := task.Execute(execCtx, params); err != nil {
_ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
JobId: request.Job.JobId,
JobType: request.Job.JobType,
diff --git a/weed/plugin/worker/volume_balance_handler.go b/weed/plugin/worker/volume_balance_handler.go
index 1a3af2b0d1..01b8bc1d31 100644
--- a/weed/plugin/worker/volume_balance_handler.go
+++ b/weed/plugin/worker/volume_balance_handler.go
@@ -2,9 +2,12 @@ package pluginworker
import (
"context"
+ "crypto/sha256"
+ "encoding/hex"
"fmt"
"sort"
"strings"
+ "sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/admin/topology"
@@ -19,6 +22,7 @@ import (
const (
defaultBalanceTimeoutSeconds = int32(10 * 60)
+ maxProposalStringLength = 200
)
func init() {
@@ -35,6 +39,8 @@ func init() {
type volumeBalanceWorkerConfig struct {
TaskConfig *balancetask.Config
MinIntervalSeconds int
+ MaxConcurrentMoves int
+ BatchSize int
}
// VolumeBalanceHandler is the plugin job handler for volume balancing.
@@ -133,6 +139,31 @@ func (h *VolumeBalanceHandler) Descriptor() *plugin_pb.JobTypeDescriptor {
},
},
},
+ {
+ SectionId: "batch_execution",
+ Title: "Batch Execution",
+ Description: "Controls for running multiple volume moves per job. The worker coordinates moves via gRPC and is not on the data path.",
+ Fields: []*plugin_pb.ConfigField{
+ {
+ Name: "max_concurrent_moves",
+ Label: "Max Concurrent Moves",
+ Description: "Maximum number of volume moves to run concurrently within a single batch job.",
+ FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_INT64,
+ Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_NUMBER,
+ MinValue: &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 1}},
+ MaxValue: &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 50}},
+ },
+ {
+ Name: "batch_size",
+ Label: "Batch Size",
+ Description: "Maximum number of volume moves to group into a single job. Set to 1 to disable batching.",
+ FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_INT64,
+ Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_NUMBER,
+ MinValue: &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 1}},
+ MaxValue: &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 100}},
+ },
+ },
+ },
},
DefaultValues: map[string]*plugin_pb.ConfigValue{
"imbalance_threshold": {
@@ -144,6 +175,12 @@ func (h *VolumeBalanceHandler) Descriptor() *plugin_pb.JobTypeDescriptor {
"min_interval_seconds": {
Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 30 * 60},
},
+ "max_concurrent_moves": {
+ Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: int64(defaultMaxConcurrentMoves)},
+ },
+ "batch_size": {
+ Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 20},
+ },
},
},
AdminRuntimeDefaults: &plugin_pb.AdminRuntimeDefaults{
@@ -167,6 +204,12 @@ func (h *VolumeBalanceHandler) Descriptor() *plugin_pb.JobTypeDescriptor {
"min_interval_seconds": {
Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 30 * 60},
},
+ "max_concurrent_moves": {
+ Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: int64(defaultMaxConcurrentMoves)},
+ },
+ "batch_size": {
+ Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 20},
+ },
},
}
}
@@ -234,14 +277,19 @@ func (h *VolumeBalanceHandler) Detect(
glog.Warningf("Plugin worker failed to emit volume_balance detection trace: %v", traceErr)
}
- proposals := make([]*plugin_pb.JobProposal, 0, len(results))
- for _, result := range results {
- proposal, proposalErr := buildVolumeBalanceProposal(result)
- if proposalErr != nil {
- glog.Warningf("Plugin worker skip invalid volume_balance proposal: %v", proposalErr)
- continue
+ var proposals []*plugin_pb.JobProposal
+ if workerConfig.BatchSize > 1 && len(results) > 1 {
+ proposals = buildBatchVolumeBalanceProposals(results, workerConfig.BatchSize, workerConfig.MaxConcurrentMoves)
+ } else {
+ proposals = make([]*plugin_pb.JobProposal, 0, len(results))
+ for _, result := range results {
+ proposal, proposalErr := buildVolumeBalanceProposal(result)
+ if proposalErr != nil {
+ glog.Warningf("Plugin worker skip invalid volume_balance proposal: %v", proposalErr)
+ continue
+ }
+ proposals = append(proposals, proposal)
}
- proposals = append(proposals, proposal)
}
if err := sender.SendProposals(&plugin_pb.DetectionProposals{
@@ -511,6 +559,12 @@ func countBalanceDiskTypes(metrics []*workertypes.VolumeHealthMetrics) int {
return len(diskTypes)
}
+const (
+ defaultMaxConcurrentMoves = 5
+ maxConcurrentMovesLimit = 50
+ maxBatchMoves = 100
+)
+
func (h *VolumeBalanceHandler) Execute(
ctx context.Context,
request *plugin_pb.ExecuteJobRequest,
@@ -530,6 +584,24 @@ func (h *VolumeBalanceHandler) Execute(
if err != nil {
return err
}
+
+ applyBalanceExecutionDefaults(params)
+
+ // Batch path: if BalanceTaskParams has moves, execute them concurrently
+ if bp := params.GetBalanceParams(); bp != nil && len(bp.Moves) > 0 {
+ return h.executeBatchMoves(ctx, request, params, sender)
+ }
+
+ // Single-move path (backward compatible)
+ return h.executeSingleMove(ctx, request, params, sender)
+}
+
+func (h *VolumeBalanceHandler) executeSingleMove(
+ ctx context.Context,
+ request *plugin_pb.ExecuteJobRequest,
+ params *worker_pb.TaskParams,
+ sender ExecutionSender,
+) error {
if len(params.Sources) == 0 || strings.TrimSpace(params.Sources[0].Node) == "" {
return fmt.Errorf("volume balance source node is required")
}
@@ -537,8 +609,6 @@ func (h *VolumeBalanceHandler) Execute(
return fmt.Errorf("volume balance target node is required")
}
- applyBalanceExecutionDefaults(params)
-
task := balancetask.NewBalanceTask(
request.Job.JobId,
params.Sources[0].Node,
@@ -546,12 +616,14 @@ func (h *VolumeBalanceHandler) Execute(
params.Collection,
h.grpcDialOption,
)
+ execCtx, execCancel := context.WithCancel(ctx)
+ defer execCancel()
task.SetProgressCallback(func(progress float64, stage string) {
message := fmt.Sprintf("balance progress %.0f%%", progress)
if strings.TrimSpace(stage) != "" {
message = stage
}
- _ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
+ if err := sender.SendProgress(&plugin_pb.JobProgressUpdate{
JobId: request.Job.JobId,
JobType: request.Job.JobType,
State: plugin_pb.JobState_JOB_STATE_RUNNING,
@@ -561,7 +633,9 @@ func (h *VolumeBalanceHandler) Execute(
Activities: []*plugin_pb.ActivityEvent{
BuildExecutorActivity(stage, message),
},
- })
+ }); err != nil {
+ execCancel()
+ }
})
if err := sender.SendProgress(&plugin_pb.JobProgressUpdate{
@@ -578,7 +652,7 @@ func (h *VolumeBalanceHandler) Execute(
return err
}
- if err := task.Execute(ctx, params); err != nil {
+ if err := task.Execute(execCtx, params); err != nil {
_ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
JobId: request.Job.JobId,
JobType: request.Job.JobType,
@@ -621,6 +695,233 @@ func (h *VolumeBalanceHandler) Execute(
})
}
+// executeBatchMoves runs multiple volume moves concurrently within a single job.
+func (h *VolumeBalanceHandler) executeBatchMoves(
+ ctx context.Context,
+ request *plugin_pb.ExecuteJobRequest,
+ params *worker_pb.TaskParams,
+ sender ExecutionSender,
+) error {
+ bp := params.GetBalanceParams()
+ if len(bp.Moves) == 0 {
+ return fmt.Errorf("batch balance job has no moves")
+ }
+ if len(bp.Moves) > maxBatchMoves {
+ return fmt.Errorf("batch balance job has %d moves, exceeding limit of %d", len(bp.Moves), maxBatchMoves)
+ }
+
+ // Filter out nil or incomplete moves before scheduling.
+ validMoves := make([]*worker_pb.BalanceMoveSpec, 0, len(bp.Moves))
+ for _, m := range bp.Moves {
+ if m == nil {
+ continue
+ }
+ if strings.TrimSpace(m.SourceNode) == "" || strings.TrimSpace(m.TargetNode) == "" || m.VolumeId == 0 {
+ glog.Warningf("batch balance: skipping invalid move (vol:%d src:%q tgt:%q)", m.VolumeId, m.SourceNode, m.TargetNode)
+ continue
+ }
+ validMoves = append(validMoves, m)
+ }
+ if len(validMoves) == 0 {
+ return fmt.Errorf("batch balance job has no valid moves after validation")
+ }
+ moves := validMoves
+
+ maxConcurrent := int(bp.MaxConcurrentMoves)
+ if maxConcurrent <= 0 {
+ maxConcurrent = defaultMaxConcurrentMoves
+ }
+ // Clamp to the worker-side upper bound so a stale or malicious job
+ // cannot request unbounded fan-out of concurrent volume moves.
+ if maxConcurrent > maxConcurrentMovesLimit {
+ maxConcurrent = maxConcurrentMovesLimit
+ }
+
+ totalMoves := len(moves)
+ glog.Infof("batch volume balance: %d moves, max concurrent %d", totalMoves, maxConcurrent)
+
+ if err := sender.SendProgress(&plugin_pb.JobProgressUpdate{
+ JobId: request.Job.JobId,
+ JobType: request.Job.JobType,
+ State: plugin_pb.JobState_JOB_STATE_ASSIGNED,
+ ProgressPercent: 0,
+ Stage: "assigned",
+ Message: fmt.Sprintf("batch volume balance accepted: %d moves", totalMoves),
+ Activities: []*plugin_pb.ActivityEvent{
+ BuildExecutorActivity("assigned", fmt.Sprintf("batch volume balance: %d moves, concurrency %d", totalMoves, maxConcurrent)),
+ },
+ }); err != nil {
+ return err
+ }
+
+ // Derive a cancellable context so we can abort remaining moves if the
+ // progress stream breaks (client disconnect, context cancelled).
+ batchCtx, batchCancel := context.WithCancel(ctx)
+ defer batchCancel()
+
+ // Per-move progress tracking. The mutex serializes both the progress
+ // bookkeeping and the sender.SendProgress call, since the underlying
+ // gRPC stream is not safe for concurrent writes.
+ var progressMu sync.Mutex
+ moveProgress := make([]float64, totalMoves)
+ var sendErr error // first progress send error
+
+ reportAggregate := func(moveIndex int, progress float64, stage string) {
+ progressMu.Lock()
+ defer progressMu.Unlock()
+
+ if sendErr != nil {
+ return // stream already broken, skip further sends
+ }
+
+ moveProgress[moveIndex] = progress
+ total := 0.0
+ for _, p := range moveProgress {
+ total += p
+ }
+
+ aggregate := total / float64(totalMoves)
+ move := moves[moveIndex]
+ message := fmt.Sprintf("[Move %d/%d vol:%d] %s", moveIndex+1, totalMoves, move.VolumeId, stage)
+
+ if err := sender.SendProgress(&plugin_pb.JobProgressUpdate{
+ JobId: request.Job.JobId,
+ JobType: request.Job.JobType,
+ State: plugin_pb.JobState_JOB_STATE_RUNNING,
+ ProgressPercent: aggregate,
+ Stage: fmt.Sprintf("move %d/%d", moveIndex+1, totalMoves),
+ Message: message,
+ Activities: []*plugin_pb.ActivityEvent{
+ BuildExecutorActivity(fmt.Sprintf("move-%d", moveIndex+1), message),
+ },
+ }); err != nil {
+ sendErr = err
+ batchCancel() // cancel in-flight and pending moves
+ }
+ }
+
+ type moveResult struct {
+ index int
+ volumeID uint32
+ source string
+ target string
+ err error
+ }
+
+ sem := make(chan struct{}, maxConcurrent)
+ results := make(chan moveResult, totalMoves)
+
+ for i, move := range moves {
+ sem <- struct{}{} // acquire slot
+ go func(idx int, m *worker_pb.BalanceMoveSpec) {
+ defer func() { <-sem }() // release slot
+
+ task := balancetask.NewBalanceTask(
+ fmt.Sprintf("%s-move-%d", request.Job.JobId, idx),
+ m.SourceNode,
+ m.VolumeId,
+ m.Collection,
+ h.grpcDialOption,
+ )
+ task.SetProgressCallback(func(progress float64, stage string) {
+ reportAggregate(idx, progress, stage)
+ })
+
+ moveParams := buildMoveTaskParams(m, bp)
+ err := task.Execute(batchCtx, moveParams)
+ results <- moveResult{
+ index: idx,
+ volumeID: m.VolumeId,
+ source: m.SourceNode,
+ target: m.TargetNode,
+ err: err,
+ }
+ }(i, move)
+ }
+
+ // Collect all results
+ var succeeded, failed int
+ var errMessages []string
+ for range moves {
+ r := <-results
+ if r.err != nil {
+ failed++
+ errMessages = append(errMessages, fmt.Sprintf("volume %d (%s→%s): %v", r.volumeID, r.source, r.target, r.err))
+ glog.Warningf("batch balance move %d failed: volume %d %s→%s: %v", r.index, r.volumeID, r.source, r.target, r.err)
+ } else {
+ succeeded++
+ }
+ }
+
+ summary := fmt.Sprintf("%d/%d volumes moved successfully", succeeded, totalMoves)
+ if failed > 0 {
+ summary += fmt.Sprintf("; %d failed", failed)
+ }
+
+ // Mark the job as successful if at least one move succeeded. This avoids
+ // the standard retry path re-running already-completed moves. The failed
+ // move details are available in ErrorMessage and result metadata so a
+ // retry mechanism can operate only on the failed items.
+ success := succeeded > 0 || failed == 0
+ var errMsg string
+ if failed > 0 {
+ errMsg = strings.Join(errMessages, "; ")
+ }
+
+ return sender.SendCompleted(&plugin_pb.JobCompleted{
+ JobId: request.Job.JobId,
+ JobType: request.Job.JobType,
+ Success: success,
+ ErrorMessage: errMsg,
+ Result: &plugin_pb.JobResult{
+ Summary: summary,
+ OutputValues: map[string]*plugin_pb.ConfigValue{
+ "total_moves": {
+ Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: int64(totalMoves)},
+ },
+ "succeeded": {
+ Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: int64(succeeded)},
+ },
+ "failed": {
+ Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: int64(failed)},
+ },
+ },
+ },
+ Activities: []*plugin_pb.ActivityEvent{
+ BuildExecutorActivity("completed", summary),
+ },
+ })
+}
+
+// buildMoveTaskParams constructs a TaskParams for a single move within a batch.
+func buildMoveTaskParams(move *worker_pb.BalanceMoveSpec, outerParams *worker_pb.BalanceTaskParams) *worker_pb.TaskParams {
+ timeoutSeconds := defaultBalanceTimeoutSeconds
+ forceMove := false
+ if outerParams != nil {
+ if outerParams.TimeoutSeconds > 0 {
+ timeoutSeconds = outerParams.TimeoutSeconds
+ }
+ forceMove = outerParams.ForceMove
+ }
+ return &worker_pb.TaskParams{
+ VolumeId: move.VolumeId,
+ Collection: move.Collection,
+ VolumeSize: move.VolumeSize,
+ Sources: []*worker_pb.TaskSource{
+ {Node: move.SourceNode, VolumeId: move.VolumeId},
+ },
+ Targets: []*worker_pb.TaskTarget{
+ {Node: move.TargetNode, VolumeId: move.VolumeId},
+ },
+ TaskParams: &worker_pb.TaskParams_BalanceParams{
+ BalanceParams: &worker_pb.BalanceTaskParams{
+ ForceMove: forceMove,
+ TimeoutSeconds: timeoutSeconds,
+ },
+ },
+ }
+}
+
func (h *VolumeBalanceHandler) collectVolumeMetrics(
ctx context.Context,
masterAddresses []string,
@@ -654,9 +955,29 @@ func deriveBalanceWorkerConfig(values map[string]*plugin_pb.ConfigValue) *volume
minIntervalSeconds = 0
}
+ maxConcurrentMoves64 := readInt64Config(values, "max_concurrent_moves", int64(defaultMaxConcurrentMoves))
+ if maxConcurrentMoves64 < 1 {
+ maxConcurrentMoves64 = 1
+ }
+ if maxConcurrentMoves64 > 50 {
+ maxConcurrentMoves64 = 50
+ }
+ maxConcurrentMoves := int(maxConcurrentMoves64)
+
+ batchSize64 := readInt64Config(values, "batch_size", 20)
+ if batchSize64 < 1 {
+ batchSize64 = 1
+ }
+ if batchSize64 > 100 {
+ batchSize64 = 100
+ }
+ batchSize := int(batchSize64)
+
return &volumeBalanceWorkerConfig{
TaskConfig: taskConfig,
MinIntervalSeconds: minIntervalSeconds,
+ MaxConcurrentMoves: maxConcurrentMoves,
+ BatchSize: batchSize,
}
}
@@ -738,6 +1059,163 @@ func buildVolumeBalanceProposal(
}, nil
}
+// buildBatchVolumeBalanceProposals groups detection results into batch proposals.
+// Each batch proposal encodes multiple moves in BalanceTaskParams.Moves.
+func buildBatchVolumeBalanceProposals(
+ results []*workertypes.TaskDetectionResult,
+ batchSize int,
+ maxConcurrentMoves int,
+) []*plugin_pb.JobProposal {
+ if batchSize <= 0 {
+ batchSize = 1
+ }
+ if maxConcurrentMoves <= 0 {
+ maxConcurrentMoves = defaultMaxConcurrentMoves
+ }
+
+ var proposals []*plugin_pb.JobProposal
+
+ for batchStart := 0; batchStart < len(results); batchStart += batchSize {
+ batchEnd := batchStart + batchSize
+ if batchEnd > len(results) {
+ batchEnd = len(results)
+ }
+ batch := results[batchStart:batchEnd]
+
+ // If only one result in this batch, emit a single-move proposal
+ if len(batch) == 1 {
+ proposal, err := buildVolumeBalanceProposal(batch[0])
+ if err != nil {
+ glog.Warningf("Plugin worker skip invalid volume_balance proposal: %v", err)
+ continue
+ }
+ proposals = append(proposals, proposal)
+ continue
+ }
+
+ // Build batch proposal with BalanceMoveSpec entries
+ moves := make([]*worker_pb.BalanceMoveSpec, 0, len(batch))
+ var volumeIDs []string
+ var dedupeKeys []string
+ highestPriority := workertypes.TaskPriorityLow
+
+ for _, result := range batch {
+ if result == nil || result.TypedParams == nil {
+ continue
+ }
+ sourceNode := ""
+ targetNode := ""
+ if len(result.TypedParams.Sources) > 0 {
+ sourceNode = result.TypedParams.Sources[0].Node
+ }
+ if len(result.TypedParams.Targets) > 0 {
+ targetNode = result.TypedParams.Targets[0].Node
+ }
+ // Skip moves with missing required fields that would fail at execution time.
+ if result.VolumeID == 0 || sourceNode == "" || targetNode == "" {
+ glog.Warningf("Plugin worker skip invalid batch move: volume=%d source=%q target=%q", result.VolumeID, sourceNode, targetNode)
+ continue
+ }
+ moves = append(moves, &worker_pb.BalanceMoveSpec{
+ VolumeId: uint32(result.VolumeID),
+ SourceNode: sourceNode,
+ TargetNode: targetNode,
+ Collection: result.Collection,
+ VolumeSize: result.TypedParams.VolumeSize,
+ })
+ volumeIDs = append(volumeIDs, fmt.Sprintf("%d", result.VolumeID))
+
+ dedupeKey := fmt.Sprintf("volume_balance:%d", result.VolumeID)
+ if result.Collection != "" {
+ dedupeKey += ":" + result.Collection
+ }
+ dedupeKeys = append(dedupeKeys, dedupeKey)
+
+ if result.Priority > highestPriority {
+ highestPriority = result.Priority
+ }
+ }
+
+ if len(moves) == 0 {
+ continue
+ }
+
+ // After filtering, if only one valid move remains, emit a single-move
+ // proposal instead of a batch to preserve the simpler execution path.
+ if len(moves) == 1 {
+ // Find the matching result for the single valid move
+ for _, result := range batch {
+ if result != nil && uint32(result.VolumeID) == moves[0].VolumeId {
+ proposal, err := buildVolumeBalanceProposal(result)
+ if err != nil {
+ glog.Warningf("Plugin worker skip invalid volume_balance proposal: %v", err)
+ } else {
+ proposals = append(proposals, proposal)
+ }
+ break
+ }
+ }
+ continue
+ }
+
+ // Serialize batch params
+ taskParams := &worker_pb.TaskParams{
+ TaskParams: &worker_pb.TaskParams_BalanceParams{
+ BalanceParams: &worker_pb.BalanceTaskParams{
+ TimeoutSeconds: defaultBalanceTimeoutSeconds,
+ MaxConcurrentMoves: int32(maxConcurrentMoves),
+ Moves: moves,
+ },
+ },
+ }
+ payload, err := proto.Marshal(taskParams)
+ if err != nil {
+ glog.Warningf("Plugin worker failed to marshal batch balance proposal: %v", err)
+ continue
+ }
+
+ proposalID := fmt.Sprintf("volume-balance-batch-%d-%d", batchStart, time.Now().UnixNano())
+ summary := fmt.Sprintf("Batch balance %d volumes (%s)", len(moves), strings.Join(volumeIDs, ","))
+ if len(summary) > maxProposalStringLength {
+ summary = fmt.Sprintf("Batch balance %d volumes", len(moves))
+ }
+
+ // Use composite dedupe key for the batch. When the full key exceeds
+ // the length limit, fall back to a deterministic hash of the sorted
+ // keys so the same batch always produces the same dedupe key.
+ sort.Strings(dedupeKeys)
+ compositeDedupeKey := fmt.Sprintf("volume_balance_batch:%s", strings.Join(dedupeKeys, "+"))
+ if len(compositeDedupeKey) > maxProposalStringLength {
+ h := sha256.Sum256([]byte(strings.Join(dedupeKeys, "+")))
+ compositeDedupeKey = fmt.Sprintf("volume_balance_batch:%d-%s", batchStart, hex.EncodeToString(h[:12]))
+ }
+
+ proposals = append(proposals, &plugin_pb.JobProposal{
+ ProposalId: proposalID,
+ DedupeKey: compositeDedupeKey,
+ JobType: "volume_balance",
+ Priority: mapTaskPriority(highestPriority),
+ Summary: summary,
+ Detail: fmt.Sprintf("Batch of %d volume moves with concurrency %d", len(moves), maxConcurrentMoves),
+ Parameters: map[string]*plugin_pb.ConfigValue{
+ "task_params_pb": {
+ Kind: &plugin_pb.ConfigValue_BytesValue{BytesValue: payload},
+ },
+ "batch_size": {
+ Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: int64(len(moves))},
+ },
+ },
+ Labels: map[string]string{
+ "task_type": "balance",
+ "batch": "true",
+ "batch_size": fmt.Sprintf("%d", len(moves)),
+ },
+ })
+ }
+
+ return proposals
+}
+
func decodeVolumeBalanceTaskParams(job *plugin_pb.JobSpec) (*worker_pb.TaskParams, error) {
if job == nil {
return nil, fmt.Errorf("job spec is nil")
diff --git a/weed/plugin/worker/volume_balance_handler_test.go b/weed/plugin/worker/volume_balance_handler_test.go
index ace71ae3a4..ccfdd5a7c4 100644
--- a/weed/plugin/worker/volume_balance_handler_test.go
+++ b/weed/plugin/worker/volume_balance_handler_test.go
@@ -2,7 +2,9 @@ package pluginworker
import (
"context"
+ "fmt"
"strings"
+ "sync"
"testing"
"time"
@@ -111,6 +113,167 @@ func TestDeriveBalanceWorkerConfig(t *testing.T) {
if cfg.MinIntervalSeconds != 33 {
t.Fatalf("expected min_interval_seconds 33, got %d", cfg.MinIntervalSeconds)
}
+ // Defaults for batch config when not specified
+ if cfg.MaxConcurrentMoves != defaultMaxConcurrentMoves {
+ t.Fatalf("expected default max_concurrent_moves %d, got %d", defaultMaxConcurrentMoves, cfg.MaxConcurrentMoves)
+ }
+ if cfg.BatchSize != 20 {
+ t.Fatalf("expected default batch_size 20, got %d", cfg.BatchSize)
+ }
+}
+
+func TestDeriveBalanceWorkerConfigBatchFields(t *testing.T) {
+ values := map[string]*plugin_pb.ConfigValue{
+ "max_concurrent_moves": {
+ Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 10},
+ },
+ "batch_size": {
+ Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 50},
+ },
+ }
+
+ cfg := deriveBalanceWorkerConfig(values)
+ if cfg.MaxConcurrentMoves != 10 {
+ t.Fatalf("expected max_concurrent_moves 10, got %d", cfg.MaxConcurrentMoves)
+ }
+ if cfg.BatchSize != 50 {
+ t.Fatalf("expected batch_size 50, got %d", cfg.BatchSize)
+ }
+}
+
+func TestDeriveBalanceWorkerConfigBatchClamping(t *testing.T) {
+ values := map[string]*plugin_pb.ConfigValue{
+ "max_concurrent_moves": {
+ Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 999},
+ },
+ "batch_size": {
+ Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0},
+ },
+ }
+
+ cfg := deriveBalanceWorkerConfig(values)
+ if cfg.MaxConcurrentMoves != 50 {
+ t.Fatalf("expected max_concurrent_moves clamped to 50, got %d", cfg.MaxConcurrentMoves)
+ }
+ if cfg.BatchSize != 1 {
+ t.Fatalf("expected batch_size clamped to 1, got %d", cfg.BatchSize)
+ }
+}
+
+func makeDetectionResult(volumeID uint32, source, target, collection string) *workertypes.TaskDetectionResult {
+ return &workertypes.TaskDetectionResult{
+ TaskID: fmt.Sprintf("balance-%d", volumeID),
+ TaskType: workertypes.TaskTypeBalance,
+ VolumeID: volumeID,
+ Server: source,
+ Collection: collection,
+ Priority: workertypes.TaskPriorityNormal,
+ Reason: "imbalanced",
+ TypedParams: &worker_pb.TaskParams{
+ VolumeId: volumeID,
+ Collection: collection,
+ VolumeSize: 1024,
+ Sources: []*worker_pb.TaskSource{
+ {Node: source, VolumeId: volumeID},
+ },
+ Targets: []*worker_pb.TaskTarget{
+ {Node: target, VolumeId: volumeID},
+ },
+ TaskParams: &worker_pb.TaskParams_BalanceParams{
+ BalanceParams: &worker_pb.BalanceTaskParams{TimeoutSeconds: 600},
+ },
+ },
+ }
+}
+
+func TestBuildBatchVolumeBalanceProposals_SingleBatch(t *testing.T) {
+ results := []*workertypes.TaskDetectionResult{
+ makeDetectionResult(1, "s1:8080", "t1:8080", "c1"),
+ makeDetectionResult(2, "s2:8080", "t2:8080", "c1"),
+ makeDetectionResult(3, "s1:8080", "t2:8080", "c1"),
+ }
+
+ proposals := buildBatchVolumeBalanceProposals(results, 10, 5)
+ if len(proposals) != 1 {
+ t.Fatalf("expected 1 batch proposal, got %d", len(proposals))
+ }
+
+ p := proposals[0]
+ if p.Labels["batch"] != "true" {
+ t.Fatalf("expected batch label")
+ }
+ if p.Labels["batch_size"] != "3" {
+ t.Fatalf("expected batch_size label '3', got %q", p.Labels["batch_size"])
+ }
+
+ // Decode and verify moves
+ payload := p.Parameters["task_params_pb"].GetBytesValue()
+ if len(payload) == 0 {
+ t.Fatalf("expected task_params_pb payload")
+ }
+ decoded := &worker_pb.TaskParams{}
+ if err := proto.Unmarshal(payload, decoded); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ moves := decoded.GetBalanceParams().GetMoves()
+ if len(moves) != 3 {
+ t.Fatalf("expected 3 moves, got %d", len(moves))
+ }
+ if moves[0].VolumeId != 1 || moves[1].VolumeId != 2 || moves[2].VolumeId != 3 {
+ t.Fatalf("unexpected volume IDs: %v", moves)
+ }
+ if decoded.GetBalanceParams().MaxConcurrentMoves != 5 {
+ t.Fatalf("expected MaxConcurrentMoves 5, got %d", decoded.GetBalanceParams().MaxConcurrentMoves)
+ }
+}
+
+func TestBuildBatchVolumeBalanceProposals_MultipleBatches(t *testing.T) {
+ results := make([]*workertypes.TaskDetectionResult, 5)
+ for i := range results {
+ results[i] = makeDetectionResult(uint32(i+1), "s1:8080", "t1:8080", "c1")
+ }
+
+ proposals := buildBatchVolumeBalanceProposals(results, 2, 3)
+ // 5 results / batch_size 2 = 3 proposals (2, 2, 1)
+ if len(proposals) != 3 {
+ t.Fatalf("expected 3 proposals, got %d", len(proposals))
+ }
+
+ // First two should be batch proposals
+ if proposals[0].Labels["batch"] != "true" {
+ t.Fatalf("first proposal should be batch")
+ }
+ if proposals[1].Labels["batch"] != "true" {
+ t.Fatalf("second proposal should be batch")
+ }
+ // Last one has only 1 result, should fall back to single-move proposal
+ if proposals[2].Labels["batch"] == "true" {
+ t.Fatalf("last proposal with 1 result should be single-move, not batch")
+ }
+}
+
+func TestBuildBatchVolumeBalanceProposals_BatchSizeOne(t *testing.T) {
+ results := []*workertypes.TaskDetectionResult{
+ makeDetectionResult(1, "s1:8080", "t1:8080", "c1"),
+ makeDetectionResult(2, "s2:8080", "t2:8080", "c1"),
+ }
+
+ // batch_size=1 should not be called (Detect guards this), but test the function directly
+ proposals := buildBatchVolumeBalanceProposals(results, 1, 5)
+ // Each result becomes its own single-move proposal
+ if len(proposals) != 2 {
+ t.Fatalf("expected 2 proposals, got %d", len(proposals))
+ }
+}
+
+func TestVolumeBalanceDescriptorHasBatchFields(t *testing.T) {
+ descriptor := NewVolumeBalanceHandler(nil).Descriptor()
+ if !workerConfigFormHasField(descriptor.WorkerConfigForm, "max_concurrent_moves") {
+ t.Fatalf("expected max_concurrent_moves in worker config form")
+ }
+ if !workerConfigFormHasField(descriptor.WorkerConfigForm, "batch_size") {
+ t.Fatalf("expected batch_size in worker config form")
+ }
}
func TestBuildVolumeBalanceProposal(t *testing.T) {
@@ -265,6 +428,207 @@ func TestVolumeBalanceDescriptorOmitsExecutionTuningFields(t *testing.T) {
}
}
+type recordingExecutionSender struct {
+ mu sync.Mutex
+ progress []*plugin_pb.JobProgressUpdate
+ completed *plugin_pb.JobCompleted
+}
+
+func (r *recordingExecutionSender) SendProgress(p *plugin_pb.JobProgressUpdate) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.progress = append(r.progress, proto.Clone(p).(*plugin_pb.JobProgressUpdate))
+ return nil
+}
+
+func (r *recordingExecutionSender) SendCompleted(c *plugin_pb.JobCompleted) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.completed = proto.Clone(c).(*plugin_pb.JobCompleted)
+ return nil
+}
+
+func TestBuildMoveTaskParams(t *testing.T) {
+ move := &worker_pb.BalanceMoveSpec{
+ VolumeId: 42,
+ SourceNode: "10.0.0.1:8080",
+ TargetNode: "10.0.0.2:8080",
+ Collection: "photos",
+ VolumeSize: 1024 * 1024,
+ }
+
+ outerParams := &worker_pb.BalanceTaskParams{
+ ForceMove: true,
+ TimeoutSeconds: 300,
+ }
+ params := buildMoveTaskParams(move, outerParams)
+ if params.VolumeId != 42 {
+ t.Fatalf("expected volume_id 42, got %d", params.VolumeId)
+ }
+ if params.Collection != "photos" {
+ t.Fatalf("expected collection photos, got %s", params.Collection)
+ }
+ if params.VolumeSize != 1024*1024 {
+ t.Fatalf("expected volume_size %d, got %d", 1024*1024, params.VolumeSize)
+ }
+ if len(params.Sources) != 1 || params.Sources[0].Node != "10.0.0.1:8080" {
+ t.Fatalf("unexpected sources: %+v", params.Sources)
+ }
+ if len(params.Targets) != 1 || params.Targets[0].Node != "10.0.0.2:8080" {
+ t.Fatalf("unexpected targets: %+v", params.Targets)
+ }
+ bp := params.GetBalanceParams()
+ if bp == nil {
+ t.Fatalf("expected balance params")
+ }
+ if bp.TimeoutSeconds != 300 {
+ t.Fatalf("expected timeout 300, got %d", bp.TimeoutSeconds)
+ }
+ if !bp.ForceMove {
+ t.Fatalf("expected force_move to be propagated from outer params")
+ }
+}
+
+func TestBuildMoveTaskParamsDefaultTimeout(t *testing.T) {
+ move := &worker_pb.BalanceMoveSpec{
+ VolumeId: 1,
+ SourceNode: "a:8080",
+ TargetNode: "b:8080",
+ }
+ params := buildMoveTaskParams(move, nil)
+ if params.GetBalanceParams().TimeoutSeconds != defaultBalanceTimeoutSeconds {
+ t.Fatalf("expected default timeout %d, got %d", defaultBalanceTimeoutSeconds, params.GetBalanceParams().TimeoutSeconds)
+ }
+ if params.GetBalanceParams().ForceMove {
+ t.Fatalf("expected force_move to default to false with nil outer params")
+ }
+}
+
+func TestExecuteDispatchesBatchPath(t *testing.T) {
+ // Build a job with batch moves in BalanceTaskParams
+ bp := &worker_pb.BalanceTaskParams{
+ TimeoutSeconds: 60,
+ MaxConcurrentMoves: 2,
+ Moves: []*worker_pb.BalanceMoveSpec{
+ {VolumeId: 1, SourceNode: "s1:8080", TargetNode: "t1:8080", Collection: "c1"},
+ {VolumeId: 2, SourceNode: "s2:8080", TargetNode: "t2:8080", Collection: "c1"},
+ },
+ }
+ taskParams := &worker_pb.TaskParams{
+ TaskId: "batch-1",
+ TaskParams: &worker_pb.TaskParams_BalanceParams{
+ BalanceParams: bp,
+ },
+ }
+ payload, err := proto.Marshal(taskParams)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+
+ job := &plugin_pb.JobSpec{
+ JobId: "batch-job-1",
+ JobType: "volume_balance",
+ Parameters: map[string]*plugin_pb.ConfigValue{
+ "task_params_pb": {Kind: &plugin_pb.ConfigValue_BytesValue{BytesValue: payload}},
+ },
+ }
+
+ handler := NewVolumeBalanceHandler(nil)
+ sender := &recordingExecutionSender{}
+
+ // Execute will enter the batch path. It will fail because there's no real gRPC server,
+ // but we verify it sends the assigned progress and eventually a completion.
+ err = handler.Execute(context.Background(), &plugin_pb.ExecuteJobRequest{
+ Job: job,
+ }, sender)
+
+ // Expect an error since no real volume servers exist
+ // But verify the batch path was taken by checking the assigned message
+ sender.mu.Lock()
+ defer sender.mu.Unlock()
+
+ if len(sender.progress) == 0 {
+ t.Fatalf("expected progress messages from batch path")
+ }
+
+ // First progress should be "assigned" with batch info
+ first := sender.progress[0]
+ if first.Stage != "assigned" {
+ t.Fatalf("expected first stage 'assigned', got %q", first.Stage)
+ }
+ if !strings.Contains(first.Message, "batch") || !strings.Contains(first.Message, "2 moves") {
+ t.Fatalf("expected batch assigned message, got %q", first.Message)
+ }
+
+ // Should have a completion with failure details (since no servers)
+ if sender.completed == nil {
+ t.Fatalf("expected completion message")
+ }
+ if sender.completed.Success {
+ t.Fatalf("expected failure since no real gRPC servers")
+ }
+ // Should report 0 succeeded, 2 failed
+ if v, ok := sender.completed.Result.OutputValues["failed"]; !ok || v.GetInt64Value() != 2 {
+ t.Fatalf("expected 2 failed moves, got %+v", sender.completed.Result.OutputValues)
+ }
+}
+
+func TestExecuteSingleMovePathUnchanged(t *testing.T) {
+ // Build a single-move job (no batch moves)
+ taskParams := &worker_pb.TaskParams{
+ TaskId: "single-1",
+ VolumeId: 99,
+ Collection: "videos",
+ Sources: []*worker_pb.TaskSource{
+ {Node: "src:8080", VolumeId: 99},
+ },
+ Targets: []*worker_pb.TaskTarget{
+ {Node: "dst:8080", VolumeId: 99},
+ },
+ TaskParams: &worker_pb.TaskParams_BalanceParams{
+ BalanceParams: &worker_pb.BalanceTaskParams{
+ TimeoutSeconds: 60,
+ },
+ },
+ }
+ payload, err := proto.Marshal(taskParams)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+
+ job := &plugin_pb.JobSpec{
+ JobId: "single-job-1",
+ JobType: "volume_balance",
+ Parameters: map[string]*plugin_pb.ConfigValue{
+ "task_params_pb": {Kind: &plugin_pb.ConfigValue_BytesValue{BytesValue: payload}},
+ },
+ }
+
+ handler := NewVolumeBalanceHandler(nil)
+ sender := &recordingExecutionSender{}
+
+ // Execute single-move path. Will fail on gRPC but verify it takes the single-move path.
+ _ = handler.Execute(context.Background(), &plugin_pb.ExecuteJobRequest{
+ Job: job,
+ }, sender)
+
+ sender.mu.Lock()
+ defer sender.mu.Unlock()
+
+ if len(sender.progress) == 0 {
+ t.Fatalf("expected progress messages")
+ }
+
+ // Single-move path sends "volume balance job accepted" not "batch volume balance"
+ first := sender.progress[0]
+ if first.Stage != "assigned" {
+ t.Fatalf("expected first stage 'assigned', got %q", first.Stage)
+ }
+ if strings.Contains(first.Message, "batch") {
+ t.Fatalf("single-move path should not mention batch, got %q", first.Message)
+ }
+}
+
func workerConfigFormHasField(form *plugin_pb.ConfigForm, fieldName string) bool {
if form == nil {
return false
diff --git a/weed/worker/tasks/balance/balance_task.go b/weed/worker/tasks/balance/balance_task.go
index ae7af01f36..140e5db06f 100644
--- a/weed/worker/tasks/balance/balance_task.go
+++ b/weed/worker/tasks/balance/balance_task.go
@@ -82,38 +82,70 @@ func (t *BalanceTask) Execute(ctx context.Context, params *worker_pb.TaskParams)
// Step 1: Mark volume readonly
t.ReportProgress(10.0)
t.GetLogger().Info("Marking volume readonly for move")
- if err := t.markVolumeReadonly(sourceServer, volumeId); err != nil {
+ if err := t.markVolumeReadonly(ctx, sourceServer, volumeId); err != nil {
return fmt.Errorf("failed to mark volume readonly: %v", err)
}
+ // Restore source writability if any subsequent step fails, so the
+ // source volume is not left permanently readonly on abort.
+ sourceMarkedReadonly := true
+ defer func() {
+ if sourceMarkedReadonly {
+ cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cleanupCancel()
+ if wErr := t.markVolumeWritable(cleanupCtx, sourceServer, volumeId); wErr != nil {
+ glog.Warningf("failed to restore volume %d writability on %s: %v", volumeId, sourceServer, wErr)
+ }
+ }
+ }()
+
+ // Step 2: Read source volume size before copy (for post-copy verification)
+ t.ReportProgress(15.0)
+ sourceStatus, err := t.readVolumeFileStatus(ctx, sourceServer, volumeId)
+ if err != nil {
+ return fmt.Errorf("failed to read source volume status: %v", err)
+ }
- // Step 2: Copy volume to destination
+ // Step 3: Copy volume to destination (VolumeCopy also mounts the volume)
t.ReportProgress(20.0)
t.GetLogger().Info("Copying volume to destination")
- lastAppendAtNs, err := t.copyVolume(sourceServer, targetServer, volumeId)
+ lastAppendAtNs, err := t.copyVolume(ctx, sourceServer, targetServer, volumeId)
if err != nil {
return fmt.Errorf("failed to copy volume: %v", err)
}
- // Step 3: Mount volume on target and mark it readonly
- t.ReportProgress(60.0)
- t.GetLogger().Info("Mounting volume on target server")
- if err := t.mountVolume(targetServer, volumeId); err != nil {
- return fmt.Errorf("failed to mount volume on target: %v", err)
- }
-
// Step 4: Tail for updates
t.ReportProgress(70.0)
t.GetLogger().Info("Syncing final updates")
- if err := t.tailVolume(sourceServer, targetServer, volumeId, lastAppendAtNs); err != nil {
+ if err := t.tailVolume(ctx, sourceServer, targetServer, volumeId, lastAppendAtNs); err != nil {
glog.Warningf("Tail operation failed (may be normal): %v", err)
}
- // Step 5: Delete from source
+ // Step 5: Verify the volume on target before deleting source.
+ // This is a critical safety check — once the source is deleted, data loss
+ // is irreversible. We verify the target has the volume with matching size.
+ t.ReportProgress(85.0)
+ t.GetLogger().Info("Verifying volume on target before deleting source")
+ targetStatus, err := t.readVolumeFileStatus(ctx, targetServer, volumeId)
+ if err != nil {
+ return fmt.Errorf("aborting: cannot verify volume %d on target %s before deleting source: %v", volumeId, targetServer, err)
+ }
+ if targetStatus.DatFileSize != sourceStatus.DatFileSize {
+ return fmt.Errorf("aborting: volume %d .dat size mismatch — source %d bytes, target %d bytes",
+ volumeId, sourceStatus.DatFileSize, targetStatus.DatFileSize)
+ }
+ if targetStatus.FileCount != sourceStatus.FileCount {
+ return fmt.Errorf("aborting: volume %d file count mismatch — source %d, target %d",
+ volumeId, sourceStatus.FileCount, targetStatus.FileCount)
+ }
+
+ // Step 6: Delete from source — after this, the move is committed.
+ // Clear the readonly flag so the defer doesn't try to restore writability.
t.ReportProgress(90.0)
t.GetLogger().Info("Deleting volume from source server")
- if err := t.deleteVolume(sourceServer, volumeId); err != nil {
+ if err := t.deleteVolume(ctx, sourceServer, volumeId); err != nil {
return fmt.Errorf("failed to delete volume from source: %v", err)
}
+ sourceMarkedReadonly = false
t.ReportProgress(100.0)
glog.Infof("Balance task completed successfully: volume %d moved from %s to %s",
@@ -164,24 +196,35 @@ func (t *BalanceTask) GetProgress() float64 {
// Helper methods for real balance operations
-// markVolumeReadonly marks the volume readonly
-func (t *BalanceTask) markVolumeReadonly(server pb.ServerAddress, volumeId needle.VolumeId) error {
+// markVolumeReadonly marks the volume readonly on the source server.
+func (t *BalanceTask) markVolumeReadonly(ctx context.Context, server pb.ServerAddress, volumeId needle.VolumeId) error {
return operation.WithVolumeServerClient(false, server, t.grpcDialOption,
func(client volume_server_pb.VolumeServerClient) error {
- _, err := client.VolumeMarkReadonly(context.Background(), &volume_server_pb.VolumeMarkReadonlyRequest{
+ _, err := client.VolumeMarkReadonly(ctx, &volume_server_pb.VolumeMarkReadonlyRequest{
VolumeId: uint32(volumeId),
})
return err
})
}
-// copyVolume copies volume from source to target server
-func (t *BalanceTask) copyVolume(sourceServer, targetServer pb.ServerAddress, volumeId needle.VolumeId) (uint64, error) {
+// markVolumeWritable restores the volume to writable on the source server.
+func (t *BalanceTask) markVolumeWritable(ctx context.Context, server pb.ServerAddress, volumeId needle.VolumeId) error {
+ return operation.WithVolumeServerClient(false, server, t.grpcDialOption,
+ func(client volume_server_pb.VolumeServerClient) error {
+ _, err := client.VolumeMarkWritable(ctx, &volume_server_pb.VolumeMarkWritableRequest{
+ VolumeId: uint32(volumeId),
+ })
+ return err
+ })
+}
+
+// copyVolume copies volume from source to target server.
+func (t *BalanceTask) copyVolume(ctx context.Context, sourceServer, targetServer pb.ServerAddress, volumeId needle.VolumeId) (uint64, error) {
var lastAppendAtNs uint64
err := operation.WithVolumeServerClient(true, targetServer, t.grpcDialOption,
func(client volume_server_pb.VolumeServerClient) error {
- stream, err := client.VolumeCopy(context.Background(), &volume_server_pb.VolumeCopyRequest{
+ stream, err := client.VolumeCopy(ctx, &volume_server_pb.VolumeCopyRequest{
VolumeId: uint32(volumeId),
SourceDataNode: string(sourceServer),
})
@@ -213,22 +256,11 @@ func (t *BalanceTask) copyVolume(sourceServer, targetServer pb.ServerAddress, vo
return lastAppendAtNs, err
}
-// mountVolume mounts the volume on the target server
-func (t *BalanceTask) mountVolume(server pb.ServerAddress, volumeId needle.VolumeId) error {
- return operation.WithVolumeServerClient(false, server, t.grpcDialOption,
- func(client volume_server_pb.VolumeServerClient) error {
- _, err := client.VolumeMount(context.Background(), &volume_server_pb.VolumeMountRequest{
- VolumeId: uint32(volumeId),
- })
- return err
- })
-}
-
-// tailVolume syncs remaining updates from source to target
-func (t *BalanceTask) tailVolume(sourceServer, targetServer pb.ServerAddress, volumeId needle.VolumeId, sinceNs uint64) error {
+// tailVolume syncs remaining updates from source to target.
+func (t *BalanceTask) tailVolume(ctx context.Context, sourceServer, targetServer pb.ServerAddress, volumeId needle.VolumeId, sinceNs uint64) error {
return operation.WithVolumeServerClient(true, targetServer, t.grpcDialOption,
func(client volume_server_pb.VolumeServerClient) error {
- _, err := client.VolumeTailReceiver(context.Background(), &volume_server_pb.VolumeTailReceiverRequest{
+ _, err := client.VolumeTailReceiver(ctx, &volume_server_pb.VolumeTailReceiverRequest{
VolumeId: uint32(volumeId),
SinceNs: sinceNs,
IdleTimeoutSeconds: 60, // 1 minute timeout
@@ -238,11 +270,26 @@ func (t *BalanceTask) tailVolume(sourceServer, targetServer pb.ServerAddress, vo
})
}
-// deleteVolume deletes the volume from the server
-func (t *BalanceTask) deleteVolume(server pb.ServerAddress, volumeId needle.VolumeId) error {
+// readVolumeFileStatus reads the volume's file status (sizes, file count) from a server.
+func (t *BalanceTask) readVolumeFileStatus(ctx context.Context, server pb.ServerAddress, volumeId needle.VolumeId) (*volume_server_pb.ReadVolumeFileStatusResponse, error) {
+ var resp *volume_server_pb.ReadVolumeFileStatusResponse
+ err := operation.WithVolumeServerClient(false, server, t.grpcDialOption,
+ func(client volume_server_pb.VolumeServerClient) error {
+ var err error
+ resp, err = client.ReadVolumeFileStatus(ctx,
+ &volume_server_pb.ReadVolumeFileStatusRequest{
+ VolumeId: uint32(volumeId),
+ })
+ return err
+ })
+ return resp, err
+}
+
+// deleteVolume deletes the volume from the server.
+func (t *BalanceTask) deleteVolume(ctx context.Context, server pb.ServerAddress, volumeId needle.VolumeId) error {
return operation.WithVolumeServerClient(false, server, t.grpcDialOption,
func(client volume_server_pb.VolumeServerClient) error {
- _, err := client.VolumeDelete(context.Background(), &volume_server_pb.VolumeDeleteRequest{
+ _, err := client.VolumeDelete(ctx, &volume_server_pb.VolumeDeleteRequest{
VolumeId: uint32(volumeId),
OnlyEmpty: false,
})
diff --git a/weed/worker/tasks/balance/detection.go b/weed/worker/tasks/balance/detection.go
index ac1ad488f0..d10033dd36 100644
--- a/weed/worker/tasks/balance/detection.go
+++ b/weed/worker/tasks/balance/detection.go
@@ -230,6 +230,33 @@ func detectForDiskType(diskType string, diskMetrics []*types.VolumeHealthMetrics
break
}
+ // When the global max and min effective counts differ by at most 1,
+ // no single move can improve balance — it would just swap which server
+ // is min vs max. Stop here to avoid infinite oscillation when the
+ // threshold is unachievable (e.g., 11 vols across 4 servers: best is
+ // 3/3/3/2, imbalance=36%). We scan ALL servers' effective counts so the
+ // check works regardless of whether utilization or raw counts are used.
+ globalMaxCount, globalMinCount := 0, math.MaxInt
+ for _, c := range effectiveCounts {
+ if c > globalMaxCount {
+ globalMaxCount = c
+ }
+ if c < globalMinCount {
+ globalMinCount = c
+ }
+ }
+ if globalMaxCount-globalMinCount <= 1 {
+ if len(results) == 0 {
+ glog.Infof("BALANCE [%s]: No tasks created - cluster as balanced as possible. Imbalance=%.1f%% (threshold=%.1f%%), but max-min diff is %d",
+ diskType, imbalanceRatio*100, balanceConfig.ImbalanceThreshold*100, globalMaxCount-globalMinCount)
+ } else {
+ glog.Infof("BALANCE [%s]: Created %d task(s), cluster as balanced as possible. Imbalance=%.1f%% (threshold=%.1f%%), max-min diff=%d",
+ diskType, len(results), imbalanceRatio*100, balanceConfig.ImbalanceThreshold*100, globalMaxCount-globalMinCount)
+ }
+ balanced = true
+ break
+ }
+
// Select a volume from the overloaded server using per-server cursor
var selectedVolume *types.VolumeHealthMetrics
serverVols := volumesByServer[maxServer]
@@ -252,11 +279,13 @@ func detectForDiskType(diskType string, diskMetrics []*types.VolumeHealthMetrics
continue
}
- // Plan destination and create task.
- // On failure, continue to the next volume on the same server rather
- // than exhausting the entire server — the failure may be per-volume
- // (e.g., volume not found in topology, AddPendingTask failed).
- task, destServerID := createBalanceTask(diskType, selectedVolume, clusterInfo)
+ // Create task targeting minServer — the greedy algorithm's natural choice.
+ // Using minServer instead of letting planBalanceDestination independently
+ // pick a destination ensures that the detection loop's effective counts
+ // and the destination selection stay in sync. Without this, the topology's
+ // LoadCount-based scoring can diverge from the adjustment-based effective
+ // counts, causing moves to pile onto one server or oscillate (A→B, B→A).
+ task, destServerID := createBalanceTask(diskType, selectedVolume, clusterInfo, minServer)
if task == nil {
glog.V(1).Infof("BALANCE [%s]: Cannot plan task for volume %d on server %s, trying next volume", diskType, selectedVolume.VolumeID, maxServer)
continue
@@ -264,10 +293,18 @@ func detectForDiskType(diskType string, diskMetrics []*types.VolumeHealthMetrics
results = append(results, task)
- // Adjust effective counts for the next iteration
+ // Adjust effective counts for the next iteration.
adjustments[maxServer]--
if destServerID != "" {
adjustments[destServerID]++
+ // If the destination server wasn't in serverVolumeCounts (e.g., a
+ // server with 0 volumes not seeded from topology), add it so
+ // subsequent iterations include it in effective/average/min/max.
+ if _, exists := serverVolumeCounts[destServerID]; !exists {
+ serverVolumeCounts[destServerID] = 0
+ sortedServers = append(sortedServers, destServerID)
+ sort.Strings(sortedServers)
+ }
}
}
@@ -277,9 +314,10 @@ func detectForDiskType(diskType string, diskMetrics []*types.VolumeHealthMetrics
}
// createBalanceTask creates a single balance task for the selected volume.
+// targetServer is the server ID chosen by the detection loop's greedy algorithm.
// Returns (nil, "") if destination planning fails.
// On success, returns the task result and the canonical destination server ID.
-func createBalanceTask(diskType string, selectedVolume *types.VolumeHealthMetrics, clusterInfo *types.ClusterInfo) (*types.TaskDetectionResult, string) {
+func createBalanceTask(diskType string, selectedVolume *types.VolumeHealthMetrics, clusterInfo *types.ClusterInfo, targetServer string) (*types.TaskDetectionResult, string) {
taskID := fmt.Sprintf("balance_vol_%d_%d", selectedVolume.VolumeID, time.Now().UnixNano())
task := &types.TaskDetectionResult{
@@ -300,10 +338,19 @@ func createBalanceTask(diskType string, selectedVolume *types.VolumeHealthMetric
return nil, ""
}
- destinationPlan, err := planBalanceDestination(clusterInfo.ActiveTopology, selectedVolume)
+ // Resolve the target server chosen by the detection loop's effective counts.
+ // This keeps destination selection in sync with the greedy algorithm rather
+ // than relying on topology LoadCount which can diverge across iterations.
+ destinationPlan, err := resolveBalanceDestination(clusterInfo.ActiveTopology, selectedVolume, targetServer)
if err != nil {
- glog.Warningf("Failed to plan balance destination for volume %d: %v", selectedVolume.VolumeID, err)
- return nil, ""
+ // Fall back to score-based planning if the preferred target can't be resolved
+ glog.V(1).Infof("BALANCE [%s]: Cannot resolve target %s for volume %d, falling back to score-based planning: %v",
+ diskType, targetServer, selectedVolume.VolumeID, err)
+ destinationPlan, err = planBalanceDestination(clusterInfo.ActiveTopology, selectedVolume)
+ if err != nil {
+ glog.Warningf("Failed to plan balance destination for volume %d: %v", selectedVolume.VolumeID, err)
+ return nil, ""
+ }
}
// Find the actual disk containing the volume on the source server
@@ -383,8 +430,54 @@ func createBalanceTask(diskType string, selectedVolume *types.VolumeHealthMetric
return task, destinationPlan.TargetNode
}
-// planBalanceDestination plans the destination for a balance operation
-// This function implements destination planning logic directly in the detection phase
+// resolveBalanceDestination resolves the destination for a balance operation
+// when the target server is already known (chosen by the detection loop's
+// effective volume counts). It finds the appropriate disk and address for the
+// target server in the topology.
+func resolveBalanceDestination(activeTopology *topology.ActiveTopology, selectedVolume *types.VolumeHealthMetrics, targetServer string) (*topology.DestinationPlan, error) {
+ topologyInfo := activeTopology.GetTopologyInfo()
+ if topologyInfo == nil {
+ return nil, fmt.Errorf("no topology info available")
+ }
+
+ // Find the target node in the topology and get its disk info
+ for _, dc := range topologyInfo.DataCenterInfos {
+ for _, rack := range dc.RackInfos {
+ for _, node := range rack.DataNodeInfos {
+ if node.Id != targetServer {
+ continue
+ }
+ // Find an available disk matching the volume's disk type
+ for diskTypeName, diskInfo := range node.DiskInfos {
+ if diskTypeName != selectedVolume.DiskType {
+ continue
+ }
+ if diskInfo.MaxVolumeCount > 0 && diskInfo.VolumeCount >= diskInfo.MaxVolumeCount {
+ continue // disk is full
+ }
+ targetAddress, err := util.ResolveServerAddress(node.Id, activeTopology)
+ if err != nil {
+ return nil, fmt.Errorf("failed to resolve address for target server %s: %v", node.Id, err)
+ }
+ return &topology.DestinationPlan{
+ TargetNode: node.Id,
+ TargetAddress: targetAddress,
+ TargetDisk: diskInfo.DiskId,
+ TargetRack: rack.Id,
+ TargetDC: dc.Id,
+ ExpectedSize: selectedVolume.Size,
+ }, nil
+ }
+ return nil, fmt.Errorf("target server %s has no available disk of type %s", targetServer, selectedVolume.DiskType)
+ }
+ }
+ }
+ return nil, fmt.Errorf("target server %s not found in topology", targetServer)
+}
+
+// planBalanceDestination plans the destination for a balance operation using
+// score-based selection. Used as a fallback when the preferred target cannot
+// be resolved, and for single-move scenarios outside the detection loop.
func planBalanceDestination(activeTopology *topology.ActiveTopology, selectedVolume *types.VolumeHealthMetrics) (*topology.DestinationPlan, error) {
// Get source node information from topology
var sourceRack, sourceDC string
diff --git a/weed/worker/tasks/balance/detection_test.go b/weed/worker/tasks/balance/detection_test.go
index af7b5bc9f5..aee5b5420e 100644
--- a/weed/worker/tasks/balance/detection_test.go
+++ b/weed/worker/tasks/balance/detection_test.go
@@ -917,3 +917,86 @@ func TestDetection_HeterogeneousCapacity(t *testing.T) {
}
t.Logf("First balance task: move from %s (correct: highest utilization)", firstSource)
}
+
+// TestDetection_ZeroVolumeServerIncludedInBalance verifies that a server
+// with zero volumes (seeded from topology with a matching disk type) is
+// correctly included in the balance calculation and receives moves to
+// equalize the distribution.
+func TestDetection_ZeroVolumeServerIncludedInBalance(t *testing.T) {
+ // 4 servers total, but only 3 have volumes.
+ // node-d has a disk of the same type but zero volumes, so it appears in the
+ // topology and is seeded into serverVolumeCounts with count=0.
+
+ servers := []serverSpec{
+ {id: "node-a", diskType: "hdd", diskID: 1, dc: "dc1", rack: "rack1", maxVolumes: 20},
+ {id: "node-b", diskType: "hdd", diskID: 2, dc: "dc1", rack: "rack1", maxVolumes: 20},
+ {id: "node-c", diskType: "hdd", diskID: 3, dc: "dc1", rack: "rack1", maxVolumes: 20},
+ {id: "node-d", diskType: "hdd", diskID: 4, dc: "dc1", rack: "rack1", maxVolumes: 20},
+ }
+
+ // node-a: 8 volumes, node-b: 2, node-c: 1, node-d: 0
+ var metrics []*types.VolumeHealthMetrics
+ metrics = append(metrics, makeVolumes("node-a", "hdd", "dc1", "rack1", "", 1, 8)...)
+ metrics = append(metrics, makeVolumes("node-b", "hdd", "dc1", "rack1", "", 20, 2)...)
+ metrics = append(metrics, makeVolumes("node-c", "hdd", "dc1", "rack1", "", 30, 1)...)
+ // node-d has 0 volumes — no metrics
+
+ at := buildTopology(servers, metrics)
+ clusterInfo := &types.ClusterInfo{ActiveTopology: at}
+
+ tasks, _, err := Detection(metrics, clusterInfo, defaultConf(), 100)
+ if err != nil {
+ t.Fatalf("Detection failed: %v", err)
+ }
+
+ if len(tasks) == 0 {
+ t.Fatal("Expected balance tasks for 8/2/1/0 distribution, got 0")
+ }
+
+ assertNoDuplicateVolumes(t, tasks)
+
+ // With 11 volumes across 4 servers, the best achievable is 3/3/3/2
+ // (imbalance=36.4%), which exceeds the 20% threshold. The algorithm should
+ // stop when max-min<=1 rather than oscillating endlessly.
+ effective := computeEffectiveCounts(servers, metrics, tasks)
+ total := 0
+ maxC, minC := 0, len(metrics)
+ for _, c := range effective {
+ total += c
+ if c > maxC {
+ maxC = c
+ }
+ if c < minC {
+ minC = c
+ }
+ }
+
+ // The diff between max and min should be at most 1 (as balanced as possible)
+ if maxC-minC > 1 {
+ t.Errorf("After %d moves, distribution not optimally balanced: effective=%v, max-min=%d (want ≤1)",
+ len(tasks), effective, maxC-minC)
+ }
+
+ // Count destinations — moves should spread, not pile onto one server
+ destCounts := make(map[string]int)
+ for _, task := range tasks {
+ if task.TypedParams != nil && len(task.TypedParams.Targets) > 0 {
+ destCounts[task.TypedParams.Targets[0].Node]++
+ }
+ }
+
+ // Moves should go to at least 2 different destinations
+ if len(destCounts) < 2 {
+ t.Errorf("Expected moves to spread across destinations, but got: %v", destCounts)
+ }
+
+ // Should need only ~5 moves for 8/2/1/0 → 3/3/3/2, not 8+ (oscillation)
+ if len(tasks) > 8 {
+ t.Errorf("Too many moves (%d) — likely oscillating; expected ≤8 for this distribution", len(tasks))
+ }
+
+ avg := float64(total) / float64(len(effective))
+ imbalance := float64(maxC-minC) / avg
+ t.Logf("Distribution 8/2/1/0 → %v after %d moves (imbalance=%.1f%%)",
+ effective, len(tasks), imbalance*100)
+}