From b53f6d4b5e1fd0b8a000cebbdecf567b818c5a8a Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Fri, 27 Nov 2026 17:46:34 -0800 Subject: [PATCH] admin: warn when more than one scheduler runs the same maintenance work (#13065) * admin/maintenance: report whether the running manager queues a task type Co-Authored-By: Claude Opus 5.5 * admin: list the EC balancers that are active at the same time The plugin ec_balance job, the legacy maintenance manager's ec_balance task and an admin_script job that runs ec.balance -apply each plan shard moves from the same topology without knowing about the others. Co-Authored-By: Claude Opus 5.5 * admin: log a warning while more than one EC balancer is active The check runs on the maintenance metrics tick and logs again only when the set of active balancers changes. The legacy maintenance entry names the admin.toml switch that turns it off. Co-Authored-By: Claude Opus 5.5 * admin: warn on the plugin pages when more than one EC balancer is active The scheduler status API returns the active EC balancers, and the scheduler banner on the plugin and lane pages lists them when there are two or more. Co-Authored-By: Claude Opus 5.5 * admin/maintenance: count a task type only when a registered worker can run it Only legacy maintenance workers pull tasks from the legacy queue. With plugin workers alone, the queued ec_balance tasks never run, so they do not compete with the plugin ec_balance job. Co-Authored-By: Claude Opus 5.5 * admin: parse ec.balance apply flags like the flag package A value counts only when strconv.ParseBool reads it as true, and a # token ends the arguments, as it does for the shell command's flag parser. Co-Authored-By: Claude Opus 5.5 * admin/maintenance: skip legacy workers past their heartbeat timeout A disconnected worker keeps its queue record until the cleanup loop removes it, so the capability check also requires a heartbeat within the worker timeout. Co-Authored-By: Claude Opus 5.5 * admin: count ec.balance only when its flags parse the way the command parses them An invalid boolean in -apply or -force fails the whole command, the last value of a flag wins, -force overrides -apply, and parsing stops at the first non-flag argument. Co-Authored-By: Claude Opus 5.5 * shell: share ec.balance's flag set and report whether its arguments apply the plan Co-Authored-By: Claude Opus 5.5 * admin: count an admin_script ec.balance only when ec.balance accepts its flags Unknown flags and invalid values of any flag fail the command before it can move shards, so they no longer count as an active balancer. Co-Authored-By: Claude Opus 5.5 * shell, plugin/worker: move admin_script command tokenizing into the shell package Co-Authored-By: Claude Opus 5.5 * admin: split admin_script ec.balance arguments with the executor's tokenizer A quoted value with spaces is one argument to ec.balance, so flags after it are still seen. Co-Authored-By: Claude Opus 5.5 * shell: report through one lookup whether a command's arguments change the cluster ec.balance now also rejects an invalid -volumeIds, as its Do does. Co-Authored-By: Claude Opus 5.5 * shell: report whether volume.balance arguments apply its plan Co-Authored-By: Claude Opus 5.5 * shell: report whether ec.encode accepts its arguments ec.encode has no dry run, so any accepted invocation changes the cluster. Co-Authored-By: Claude Opus 5.5 * shell: report whether volume.vacuum accepts its arguments Co-Authored-By: Claude Opus 5.5 * admin: report overlap for every maintenance work that more than one scheduler runs The plugin scheduler, the legacy maintenance manager, and an admin_script can each run volume balance, EC balance, EC encoding, and vacuum. Check all four from one table and report each work with two or more active runners, in the log and in the scheduler-status API as maintenance_overlaps. Co-Authored-By: Claude Opus 5.5 * admin: show each maintenance overlap on the plugin pages Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- weed/admin/dash/admin_server.go | 2 + weed/admin/dash/maintenance_overlap.go | 137 +++++++++++++++++ weed/admin/dash/maintenance_overlap_test.go | 108 ++++++++++++++ weed/admin/dash/plugin_api.go | 10 +- weed/admin/maintenance/maintenance_manager.go | 6 + .../maintenance/maintenance_manager_test.go | 34 +++++ weed/admin/maintenance/maintenance_queue.go | 20 +++ weed/admin/view/app/plugin.templ | 4 +- .../view/app/plugin_scheduler_status.templ | 18 +++ .../view/app/plugin_scheduler_status_templ.go | 2 +- weed/admin/view/app/plugin_templ.go | 2 +- weed/plugin/worker/admin_script_handler.go | 13 +- weed/shell/command_ec_balance.go | 65 +++++--- weed/shell/command_ec_encode.go | 60 ++++++-- weed/shell/command_volume_balance.go | 139 +++++++++++------- weed/shell/command_volume_vacuum.go | 23 ++- weed/shell/script_command.go | 36 +++++ weed/shell/script_command_test.go | 36 +++++ 18 files changed, 608 insertions(+), 107 deletions(-) create mode 100644 weed/admin/dash/maintenance_overlap.go create mode 100644 weed/admin/dash/maintenance_overlap_test.go create mode 100644 weed/shell/script_command.go create mode 100644 weed/shell/script_command_test.go diff --git a/weed/admin/dash/admin_server.go b/weed/admin/dash/admin_server.go index c79263ca24..d6ea2d63d9 100644 --- a/weed/admin/dash/admin_server.go +++ b/weed/admin/dash/admin_server.go @@ -443,6 +443,7 @@ func (s *AdminServer) publishMaintenanceMetrics(ctx context.Context) { // Seed one sample so the dashboard has something to draw before the first tick. s.recordDashboardSample() + var maintenanceOverlap string for { select { case <-ctx.Done(): @@ -450,6 +451,7 @@ func (s *AdminServer) publishMaintenanceMetrics(ctx context.Context) { case <-ticker.C: s.collectMaintenanceMetrics() s.recordDashboardSample() + maintenanceOverlap = s.warnOnMaintenanceOverlap(maintenanceOverlap) } } } diff --git a/weed/admin/dash/maintenance_overlap.go b/weed/admin/dash/maintenance_overlap.go new file mode 100644 index 0000000000..cd8694869d --- /dev/null +++ b/weed/admin/dash/maintenance_overlap.go @@ -0,0 +1,137 @@ +package dash + +import ( + "fmt" + "strings" + + "github.com/seaweedfs/seaweedfs/weed/admin/maintenance" + "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/shell" + "github.com/seaweedfs/seaweedfs/weed/worker/types" +) + +const pluginAdminScriptJobType = "admin_script" + +type maintenanceWork struct { + name string + pluginJobType string + legacyTaskType types.TaskType + shellCommand string +} + +// duplicableMaintenanceWork lists work that the plugin scheduler, the legacy +// maintenance manager, and an admin_script can each run on their own. +var duplicableMaintenanceWork = []maintenanceWork{ + {"volume balance", "volume_balance", types.TaskTypeBalance, "volume.balance"}, + {"EC balance", "ec_balance", types.TaskTypeECBalance, "ec.balance"}, + {"EC encoding", "erasure_coding", types.TaskTypeErasureCoding, "ec.encode"}, + {"vacuum", "vacuum", types.TaskTypeVacuum, "volume.vacuum"}, +} + +// MaintenanceOverlap names work that more than one scheduler runs. +type MaintenanceOverlap struct { + Work string `json:"work"` + Runners []string `json:"runners"` +} + +type maintenanceRunnerState struct { + PluginEnabled map[string]bool + LegacyEnabled map[types.TaskType]bool + AdminScriptEnabled bool + AdminScript string +} + +func maintenanceOverlaps(state maintenanceRunnerState) []MaintenanceOverlap { + var scriptCommands map[string]bool + if state.AdminScriptEnabled { + scriptCommands = scriptAppliedCommands(state.AdminScript) + } + var overlaps []MaintenanceOverlap + for _, work := range duplicableMaintenanceWork { + var runners []string + if state.PluginEnabled[work.pluginJobType] { + runners = append(runners, fmt.Sprintf("plugin %s job", work.pluginJobType)) + } + if state.LegacyEnabled[work.legacyTaskType] { + runners = append(runners, fmt.Sprintf("legacy maintenance %s task (turn off with enabled = false under [maintenance] in admin.toml)", work.legacyTaskType)) + } + if scriptCommands[work.shellCommand] { + runners = append(runners, fmt.Sprintf("%s job running %s", pluginAdminScriptJobType, work.shellCommand)) + } + if len(runners) > 1 { + overlaps = append(overlaps, MaintenanceOverlap{Work: work.name, Runners: runners}) + } + } + return overlaps +} + +func scriptAppliedCommands(script string) map[string]bool { + applied := make(map[string]bool) + for _, line := range strings.Split(strings.ReplaceAll(script, "\r\n", "\n"), "\n") { + line = strings.TrimSpace(line) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + for _, chunk := range strings.Split(line, ";") { + name, args, ok := shell.SplitScriptCommand(strings.TrimSpace(chunk)) + if ok && shell.CommandArgsApply(name, args) { + applied[name] = true + } + } + } + return applied +} + +func (s *AdminServer) collectMaintenanceRunnerState() maintenanceRunnerState { + state := maintenanceRunnerState{ + PluginEnabled: make(map[string]bool), + LegacyEnabled: make(map[types.TaskType]bool), + } + if s.maintenanceManager != nil { + for _, work := range duplicableMaintenanceWork { + state.LegacyEnabled[work.legacyTaskType] = s.maintenanceManager.IsTaskTypeEnabled(maintenance.MaintenanceTaskType(work.legacyTaskType)) + } + } + pluginSvc := s.GetPlugin() + if pluginSvc == nil { + return state + } + states, err := pluginSvc.ListSchedulerStates() + if err != nil { + glog.V(1).Infof("maintenance overlap check: list scheduler states: %v", err) + return state + } + for _, jobState := range states { + state.PluginEnabled[jobState.JobType] = jobState.Enabled + } + state.AdminScriptEnabled = state.PluginEnabled[pluginAdminScriptJobType] + if state.AdminScriptEnabled { + cfg, err := pluginSvc.LoadJobTypeConfig(pluginAdminScriptJobType) + if err != nil { + glog.V(1).Infof("maintenance overlap check: load %s config: %v", pluginAdminScriptJobType, err) + } else if cfg != nil { + state.AdminScript = cfg.GetAdminConfigValues()["script"].GetStringValue() + } + } + return state +} + +// MaintenanceOverlaps lists the work that more than one scheduler runs on its own. +// Each runner plans from the same topology without knowing about the others. +func (s *AdminServer) MaintenanceOverlaps() []MaintenanceOverlap { + return maintenanceOverlaps(s.collectMaintenanceRunnerState()) +} + +func (s *AdminServer) warnOnMaintenanceOverlap(previous string) string { + var lines []string + for _, overlap := range s.MaintenanceOverlaps() { + lines = append(lines, fmt.Sprintf("%s has %d independent runners: %s", overlap.Work, len(overlap.Runners), strings.Join(overlap.Runners, ", "))) + } + current := strings.Join(lines, "; ") + if current != previous { + for _, line := range lines { + glog.Warningf("%s. Keep only one enabled.", line) + } + } + return current +} diff --git a/weed/admin/dash/maintenance_overlap_test.go b/weed/admin/dash/maintenance_overlap_test.go new file mode 100644 index 0000000000..3f1d6e3f59 --- /dev/null +++ b/weed/admin/dash/maintenance_overlap_test.go @@ -0,0 +1,108 @@ +package dash + +import ( + "reflect" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/worker/types" +) + +func TestScriptAppliedCommands(t *testing.T) { + cases := []struct { + script string + want bool + }{ + {"", false}, + {"fs.log.purge -daysAgo=7\nvolume.fix.replication -apply", false}, + {"ec.balance", false}, + {"ec.balance -collection=x", false}, + {"ec.balance -apply", true}, + {"ec.balance -force", true}, + {"ec.balance --apply", true}, + {"ec.balance -apply=true", true}, + {"ec.balance -apply=false", false}, + {"ec.balance -apply=FALSE", false}, + {"ec.balance -apply=T", true}, + {"ec.balance -apply=maybe", false}, + {"ec.balance -collection=a # add -apply later", false}, + {"ec.balance -apply=false # use -apply for writes", false}, + {"# ec.balance -apply", false}, + {"volume.list; ec.balance -collection=a -apply", true}, + {"ec.rebuild -apply\r\nec.balance -apply\r\n", true}, + {"ec.balancer -apply", false}, + {"ec.balance -apply=maybe -force", false}, + {"ec.balance -apply -force=maybe", false}, + {"ec.balance -apply -force=false", false}, + {"ec.balance -force=false -apply", false}, + {"ec.balance -apply -apply=false", false}, + {"ec.balance -collection x -apply", true}, + {"ec.balance -collection -apply", false}, + {"ec.balance x -apply", false}, + {"ec.balance -collection \"a b\" -apply", true}, + {"ec.balance -collection 'a b' -force", true}, + {"ec.balance -collection #x -apply", true}, + {"ec.balance -bogus -apply", false}, + {"ec.balance -maxParallelization=x -apply", false}, + {"ec.balance -maxParallelization 4 -apply", true}, + {"ec.balance -volumeIds=x -apply", false}, + } + for _, c := range cases { + if got := scriptAppliedCommands(c.script)["ec.balance"]; got != c.want { + t.Errorf("scriptAppliedCommands(%q) has ec.balance = %v, want %v", c.script, got, c.want) + } + } +} + +func TestScriptAppliedCommandsAcrossWork(t *testing.T) { + got := scriptAppliedCommands("volume.balance -apply\nec.encode -collection=a\nvolume.vacuum -garbageThreshold=0.2\nvolume.fix.replication -apply\nvolume.list") + want := map[string]bool{"volume.balance": true, "ec.encode": true, "volume.vacuum": true} + if !reflect.DeepEqual(got, want) { + t.Errorf("scriptAppliedCommands = %v, want %v", got, want) + } + if got := scriptAppliedCommands("volume.balance\nec.encode -quietFor=soon"); len(got) != 0 { + t.Errorf("dry-run and rejected commands counted: %v", got) + } +} + +func TestMaintenanceOverlaps(t *testing.T) { + legacyEC := "legacy maintenance ec_balance task (turn off with enabled = false under [maintenance] in admin.toml)" + cases := []struct { + name string + state maintenanceRunnerState + want []MaintenanceOverlap + }{ + {"none", maintenanceRunnerState{}, nil}, + {"plugin only", maintenanceRunnerState{PluginEnabled: map[string]bool{"ec_balance": true, "vacuum": true}}, nil}, + {"disabled script ignored", maintenanceRunnerState{ + PluginEnabled: map[string]bool{"ec_balance": true}, + AdminScript: "ec.balance -apply", + }, nil}, + {"plugin and legacy on different work", maintenanceRunnerState{ + PluginEnabled: map[string]bool{"vacuum": true}, + LegacyEnabled: map[types.TaskType]bool{types.TaskTypeECBalance: true}, + }, nil}, + {"all three on EC balance", maintenanceRunnerState{ + PluginEnabled: map[string]bool{"ec_balance": true, "admin_script": true}, + LegacyEnabled: map[types.TaskType]bool{types.TaskTypeECBalance: true}, + AdminScriptEnabled: true, + AdminScript: "ec.balance -apply", + }, []MaintenanceOverlap{{Work: "EC balance", Runners: []string{"plugin ec_balance job", legacyEC, "admin_script job running ec.balance"}}}}, + {"script overlaps two plugin jobs", maintenanceRunnerState{ + PluginEnabled: map[string]bool{"volume_balance": true, "vacuum": true, "erasure_coding": true, "admin_script": true}, + AdminScriptEnabled: true, + AdminScript: "volume.balance -force\nvolume.vacuum", + }, []MaintenanceOverlap{ + {Work: "volume balance", Runners: []string{"plugin volume_balance job", "admin_script job running volume.balance"}}, + {Work: "vacuum", Runners: []string{"plugin vacuum job", "admin_script job running volume.vacuum"}}, + }}, + {"legacy and plugin encoding", maintenanceRunnerState{ + PluginEnabled: map[string]bool{"erasure_coding": true}, + LegacyEnabled: map[types.TaskType]bool{types.TaskTypeErasureCoding: true}, + }, []MaintenanceOverlap{{Work: "EC encoding", Runners: []string{"plugin erasure_coding job", "legacy maintenance erasure_coding task (turn off with enabled = false under [maintenance] in admin.toml)"}}}}, + } + for _, c := range cases { + if got := maintenanceOverlaps(c.state); !reflect.DeepEqual(got, c.want) { + t.Errorf("%s: maintenanceOverlaps = %v, want %v", c.name, got, c.want) + } + } +} diff --git a/weed/admin/dash/plugin_api.go b/weed/admin/dash/plugin_api.go index fdaafe11bc..1ed90db806 100644 --- a/weed/admin/dash/plugin_api.go +++ b/weed/admin/dash/plugin_api.go @@ -349,8 +349,9 @@ func (s *AdminServer) GetPluginSchedulerStatusAPI(w http.ResponseWriter, r *http if laneFilter != "" { lane := plugin.SchedulerLane(laneFilter) response := map[string]interface{}{ - "enabled": true, - "scheduler": pluginSvc.GetLaneSchedulerStatus(lane), + "enabled": true, + "scheduler": pluginSvc.GetLaneSchedulerStatus(lane), + "maintenance_overlaps": s.MaintenanceOverlaps(), } if s.pluginLock != nil { response["lock"] = lockStatus @@ -360,8 +361,9 @@ func (s *AdminServer) GetPluginSchedulerStatusAPI(w http.ResponseWriter, r *http } response := map[string]interface{}{ - "enabled": true, - "scheduler": pluginSvc.GetSchedulerStatus(), + "enabled": true, + "scheduler": pluginSvc.GetSchedulerStatus(), + "maintenance_overlaps": s.MaintenanceOverlaps(), } if s.pluginLock != nil { response["lock"] = lockStatus diff --git a/weed/admin/maintenance/maintenance_manager.go b/weed/admin/maintenance/maintenance_manager.go index 4d2a518e18..159f1a9695 100644 --- a/weed/admin/maintenance/maintenance_manager.go +++ b/weed/admin/maintenance/maintenance_manager.go @@ -176,6 +176,12 @@ func (mm *MaintenanceManager) IsRunning() bool { return mm.running } +// IsTaskTypeEnabled reports whether the running manager queues tasks of taskType +// and a registered worker can run them. +func (mm *MaintenanceManager) IsTaskTypeEnabled(taskType MaintenanceTaskType) bool { + return mm.IsRunning() && IsTaskEnabled(mm.scanner.policy, taskType) && mm.queue.hasWorkerFor(taskType, time.Duration(mm.config.WorkerTimeoutSeconds)*time.Second) +} + // Stop terminates the maintenance manager. It is a no-op when the manager is not // running, so a second call cannot close the already closed stop channel. func (mm *MaintenanceManager) Stop() { diff --git a/weed/admin/maintenance/maintenance_manager_test.go b/weed/admin/maintenance/maintenance_manager_test.go index 06b446baf0..539c997872 100644 --- a/weed/admin/maintenance/maintenance_manager_test.go +++ b/weed/admin/maintenance/maintenance_manager_test.go @@ -138,3 +138,37 @@ func TestMaintenanceManager_LogThrottling(t *testing.T) { t.Errorf("Expected error count to be 25, got %d", manager.errorCount) } } + +func TestMaintenanceManager_IsTaskTypeEnabled(t *testing.T) { + config := DefaultMaintenanceConfig() + config.Policy = &MaintenancePolicy{TaskPolicies: map[string]*TaskPolicy{ + "ec_balance": {Enabled: true}, + "vacuum": {Enabled: false}, + }} + manager := NewMaintenanceManager(nil, config, nil) + + if manager.IsTaskTypeEnabled("ec_balance") { + t.Fatal("a stopped manager queues nothing") + } + manager.mutex.Lock() + manager.running = true + manager.mutex.Unlock() + if manager.IsTaskTypeEnabled("ec_balance") { + t.Fatal("no registered worker can run ec_balance") + } + manager.queue.workers["w1"] = &MaintenanceWorker{ID: "w1", Status: "active", LastHeartbeat: time.Now(), Capabilities: []MaintenanceTaskType{"vacuum"}} + if manager.IsTaskTypeEnabled("ec_balance") { + t.Fatal("the only worker cannot run ec_balance") + } + manager.queue.workers["w2"] = &MaintenanceWorker{ID: "w2", Status: "active", LastHeartbeat: time.Now().Add(-time.Hour), Capabilities: []MaintenanceTaskType{"ec_balance"}} + if manager.IsTaskTypeEnabled("ec_balance") { + t.Fatal("a worker past its heartbeat timeout cannot run ec_balance") + } + manager.queue.workers["w3"] = &MaintenanceWorker{ID: "w3", Status: "busy", LastHeartbeat: time.Now(), Capabilities: []MaintenanceTaskType{"ec_balance"}} + if !manager.IsTaskTypeEnabled("ec_balance") { + t.Fatal("ec_balance is enabled and a worker can run it") + } + if manager.IsTaskTypeEnabled("vacuum") || manager.IsTaskTypeEnabled("balance") { + t.Fatal("disabled and missing task types are not enabled") + } +} diff --git a/weed/admin/maintenance/maintenance_queue.go b/weed/admin/maintenance/maintenance_queue.go index de4e2643b6..a77ad31225 100644 --- a/weed/admin/maintenance/maintenance_queue.go +++ b/weed/admin/maintenance/maintenance_queue.go @@ -925,6 +925,26 @@ func (mq *MaintenanceQueue) GetWorkers() []*MaintenanceWorker { return workers } +func (mq *MaintenanceQueue) hasWorkerFor(taskType MaintenanceTaskType, workerTimeout time.Duration) bool { + cutoff := time.Now().Add(-workerTimeout) + mq.mutex.RLock() + defer mq.mutex.RUnlock() + for _, worker := range mq.workers { + if worker.Status != "active" && worker.Status != "busy" { + continue + } + if workerTimeout > 0 && worker.LastHeartbeat.Before(cutoff) { + continue + } + for _, capability := range worker.Capabilities { + if capability == taskType { + return true + } + } + } + return false +} + // GetWorkerSlots returns used/max task slots per worker ID, snapshotted under // the lock so callers don't read live worker fields that task updates mutate. // Keyed by ID so callers can merge this registry with the plugin worker diff --git a/weed/admin/view/app/plugin.templ b/weed/admin/view/app/plugin.templ index cd0730ae50..d5e41029b3 100644 --- a/weed/admin/view/app/plugin.templ +++ b/weed/admin/view/app/plugin.templ @@ -618,6 +618,7 @@ templ Plugin(page string, initialJob string, lane string) { schedulerStates: [], schedulerStatus: null, schedulerLock: null, + schedulerOverlaps: [], allJobs: [], allActivities: [], monitorRowsScope: null, @@ -1626,7 +1627,7 @@ templ Plugin(page string, initialJob string, lane string) { } function renderSchedulerStatus() { - window.renderPluginSchedulerStatus({scheduler: state.schedulerStatus, lock: state.schedulerLock, job_type: monitorJobTypeScope()}); + window.renderPluginSchedulerStatus({scheduler: state.schedulerStatus, lock: state.schedulerLock, maintenance_overlaps: state.schedulerOverlaps, job_type: monitorJobTypeScope()}); var valueNodes = document.querySelectorAll('.plugin-scheduler-next-run'); if (!valueNodes.length) { return; @@ -3142,6 +3143,7 @@ templ Plugin(page string, initialJob string, lane string) { state.schedulerStates = Array.isArray(schedulerStates) ? schedulerStates : []; state.schedulerStatus = schedulerStatus && schedulerStatus.scheduler ? schedulerStatus.scheduler : null; state.schedulerLock = schedulerStatus && schedulerStatus.lock ? schedulerStatus.lock : null; + state.schedulerOverlaps = schedulerStatus && Array.isArray(schedulerStatus.maintenance_overlaps) ? schedulerStatus.maintenance_overlaps : []; renderQueueJobs(); renderDetectionJobs(); renderExecutionJobs(); diff --git a/weed/admin/view/app/plugin_scheduler_status.templ b/weed/admin/view/app/plugin_scheduler_status.templ index 936d1f58a8..95df83ba66 100644 --- a/weed/admin/view/app/plugin_scheduler_status.templ +++ b/weed/admin/view/app/plugin_scheduler_status.templ @@ -7,6 +7,24 @@ templ PluginSchedulerStatus() { const root = document.getElementById('plugin-scheduler-blockers'); if (!root) return; root.replaceChildren(); + (data.maintenance_overlaps || []).forEach(function(overlap) { + const runners = overlap.runners || []; + const box = document.createElement('div'); + box.className = 'alert alert-warning'; + const heading = document.createElement('strong'); + heading.textContent = overlap.work + ' has ' + runners.length + ' independent runners'; + box.appendChild(heading); + runners.forEach(function(name) { + const line = document.createElement('div'); + line.textContent = name; + box.appendChild(line); + }); + const hint = document.createElement('div'); + hint.className = 'small mt-1'; + hint.textContent = 'Each one plans from the same topology without knowing about the others, so their changes can collide. Keep only one enabled.'; + box.appendChild(hint); + root.appendChild(box); + }); const lock = data.lock || {}; const waiters = lock.waiters || []; if (waiters.length) { diff --git a/weed/admin/view/app/plugin_scheduler_status_templ.go b/weed/admin/view/app/plugin_scheduler_status_templ.go index 59b564d675..3cc7fcdcf2 100644 --- a/weed/admin/view/app/plugin_scheduler_status_templ.go +++ b/weed/admin/view/app/plugin_scheduler_status_templ.go @@ -26,7 +26,7 @@ func PluginSchedulerStatus() templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } diff --git a/weed/admin/view/app/plugin_templ.go b/weed/admin/view/app/plugin_templ.go index 3dab45b538..b571977c61 100644 --- a/weed/admin/view/app/plugin_templ.go +++ b/weed/admin/view/app/plugin_templ.go @@ -109,7 +109,7 @@ func Plugin(page string, initialJob string, lane string) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "
Workers

0

Active Jobs

0

Activities (recent)

0

Next scheduled check

-

Per Job Type Summary
Job TypeActive JobsRecent Activities
Loading...
Scheduler State
Sequential scheduler with per-job runtime limits
Job TypeEnabledDetectorIn FlightMax RuntimeExec GlobalExec/WorkerExecutor WorkersEffective ExecLast Run
Loading...
Workers
WorkerAddressCapabilitiesLoad
Loading...
Job Type Configuration
Not loaded
Selected Job Type
-
Descriptor
Select a job type to load schema and config.
Admin Config Form
No admin form loaded.
Worker Config Form
No worker form loaded.
Job Scheduling Settings
How often to check for new work.
Per-attempt deadline for one job. Size-aware tasks may extend this automatically.
Next scheduled check
Scheduler
-
Not scheduled
Run History
Keep last 10 success + last 10 errors
Successful Runs
TimeJob IDWorkerDuration
No data
Error Runs
TimeJob IDWorkerError
No data
Detection Results
Run detection to see proposals.
Job Queue
States: pending/assigned/running
Job IDTypeStateProgressWorkerUpdatedMessage
Loading...
Detection Jobs
Detection activities for selected job type
TimeJob TypeRequest IDWorkerStageSourceMessage
Loading...
Execution Jobs
Job IDTypeStateProgressWorkerUpdatedMessage
Loading...
Execution Activities
Non-detection events only
TimeJob TypeJob IDSourceStageMessage
Loading...
Job Detail
Select a job to view details.
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "
Workers

0

Active Jobs

0

Activities (recent)

0

Next scheduled check

-

Per Job Type Summary
Job TypeActive JobsRecent Activities
Loading...
Scheduler State
Sequential scheduler with per-job runtime limits
Job TypeEnabledDetectorIn FlightMax RuntimeExec GlobalExec/WorkerExecutor WorkersEffective ExecLast Run
Loading...
Workers
WorkerAddressCapabilitiesLoad
Loading...
Job Type Configuration
Not loaded
Selected Job Type
-
Descriptor
Select a job type to load schema and config.
Admin Config Form
No admin form loaded.
Worker Config Form
No worker form loaded.
Job Scheduling Settings
How often to check for new work.
Per-attempt deadline for one job. Size-aware tasks may extend this automatically.
Next scheduled check
Scheduler
-
Not scheduled
Run History
Keep last 10 success + last 10 errors
Successful Runs
TimeJob IDWorkerDuration
No data
Error Runs
TimeJob IDWorkerError
No data
Detection Results
Run detection to see proposals.
Job Queue
States: pending/assigned/running
Job IDTypeStateProgressWorkerUpdatedMessage
Loading...
Detection Jobs
Detection activities for selected job type
TimeJob TypeRequest IDWorkerStageSourceMessage
Loading...
Execution Jobs
Job IDTypeStateProgressWorkerUpdatedMessage
Loading...
Execution Activities
Non-detection events only
TimeJob TypeJob IDSourceStageMessage
Loading...
Job Detail
Select a job to view details.
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } diff --git a/weed/plugin/worker/admin_script_handler.go b/weed/plugin/worker/admin_script_handler.go index 256c46b4b1..b11bd420d8 100644 --- a/weed/plugin/worker/admin_script_handler.go +++ b/weed/plugin/worker/admin_script_handler.go @@ -6,7 +6,6 @@ import ( "crypto/sha256" "encoding/hex" "fmt" - "regexp" "strings" "time" @@ -30,8 +29,6 @@ volume.deleteEmpty -quietFor=24h -apply volume.fix.replication -apply s3.clean.uploads -timeAgo=24h` -var adminScriptTokenRegex = regexp.MustCompile(`'.*?'|".*?"|\S+`) - func init() { RegisterHandler(HandlerFactory{ JobType: "admin_script", @@ -430,16 +427,12 @@ func parseAdminScriptCommands(script string) []adminScriptCommand { if chunk == "" { continue } - parts := adminScriptTokenRegex.FindAllString(chunk, -1) - if len(parts) == 0 { + name, args, ok := shell.SplitScriptCommand(chunk) + if !ok { continue } - args := make([]string, 0, len(parts)-1) - for _, arg := range parts[1:] { - args = append(args, strings.Trim(arg, "\"'")) - } commands = append(commands, adminScriptCommand{ - Name: strings.TrimSpace(parts[0]), + Name: name, Args: args, Raw: chunk, }) diff --git a/weed/shell/command_ec_balance.go b/weed/shell/command_ec_balance.go index 3f9685104b..c5350dc6b2 100644 --- a/weed/shell/command_ec_balance.go +++ b/weed/shell/command_ec_balance.go @@ -42,28 +42,18 @@ func (c *commandEcBalance) HasTag(CommandTag) bool { } func (c *commandEcBalance) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) { - balanceCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError) - collection := balanceCommand.String("collection", string(wildcard.CollectionFilterEach), "comma-separated collection names, wildcards, or regex patterns, \""+CollectionDefault+"\" for the collection with no name, or \""+string(wildcard.CollectionFilterEach)+"\" for each collection") - dc := balanceCommand.String("dataCenter", "", "only apply the balancing for this dataCenter") - shardReplicaPlacement := balanceCommand.String("shardReplicaPlacement", "", "replica placement for EC shards, or master default if empty") - diskTypeStr := balanceCommand.String("diskType", "", "the disk type for EC shards (hdd, ssd, or empty for default hdd)") - volumeIdsStr := balanceCommand.String("volumeIds", "", "optional comma-separated list of ec volume ids to balance; defaults to all") - maxParallelization := balanceCommand.Int("maxParallelization", DefaultMaxParallelization, "run up to X tasks in parallel, whenever possible") - ioBytePerSecond := balanceCommand.Int64("ioBytePerSecond", 0, "limit the speed of each shard copy; 0 falls back to the volume server's maintenance rate") - applyBalancing := balanceCommand.Bool("apply", false, "apply the balancing plan") - // TODO: remove this alias - applyBalancingAlias := balanceCommand.Bool("force", false, "apply the balancing plan (alias for -apply)") + balanceCommand, f := newEcBalanceFlagSet(c.Name()) if err = balanceCommand.Parse(args); err != nil { return err } - handleDeprecatedForceFlag(writer, balanceCommand, applyBalancingAlias, applyBalancing) - infoAboutSimulationMode(writer, *applyBalancing, "-apply") + handleDeprecatedForceFlag(writer, balanceCommand, f.force, f.apply) + infoAboutSimulationMode(writer, *f.apply, "-apply") var volumeIds []needle.VolumeId - if *volumeIdsStr != "" { - if volumeIds, err = parseVolumeIdsFlag(*volumeIdsStr); err != nil { + if *f.volumeIds != "" { + if volumeIds, err = parseVolumeIdsFlag(*f.volumeIds); err != nil { return err } } @@ -72,18 +62,55 @@ func (c *commandEcBalance) Do(args []string, commandEnv *CommandEnv, writer io.W return } - collections, err := resolveEcCollections(commandEnv, *collection) + collections, err := resolveEcCollections(commandEnv, *f.collection) if err != nil { return err } glog.V(1).Infof("balanceEcVolumes collections %+v\n", len(collections)) - rp, err := parseReplicaPlacementArg(commandEnv, *shardReplicaPlacement) + rp, err := parseReplicaPlacementArg(commandEnv, *f.shardReplicaPlacement) if err != nil { return err } - diskType := types.ToDiskType(*diskTypeStr) + diskType := types.ToDiskType(*f.diskType) - return EcBalance(commandEnv, collections, *dc, rp, diskType, *maxParallelization, *ioBytePerSecond, *applyBalancing, nil, volumeIds) + return EcBalance(commandEnv, collections, *f.dc, rp, diskType, *f.maxParallelization, *f.ioBytePerSecond, *f.apply, nil, volumeIds) +} + +type ecBalanceFlags struct { + collection, dc, shardReplicaPlacement, diskType, volumeIds *string + maxParallelization *int + ioBytePerSecond *int64 + apply, force *bool +} + +func newEcBalanceFlagSet(name string) (*flag.FlagSet, *ecBalanceFlags) { + fs := flag.NewFlagSet(name, flag.ContinueOnError) + return fs, &ecBalanceFlags{ + collection: fs.String("collection", string(wildcard.CollectionFilterEach), "comma-separated collection names, wildcards, or regex patterns, \""+CollectionDefault+"\" for the collection with no name, or \""+string(wildcard.CollectionFilterEach)+"\" for each collection"), + dc: fs.String("dataCenter", "", "only apply the balancing for this dataCenter"), + shardReplicaPlacement: fs.String("shardReplicaPlacement", "", "replica placement for EC shards, or master default if empty"), + diskType: fs.String("diskType", "", "the disk type for EC shards (hdd, ssd, or empty for default hdd)"), + volumeIds: fs.String("volumeIds", "", "optional comma-separated list of ec volume ids to balance; defaults to all"), + maxParallelization: fs.Int("maxParallelization", DefaultMaxParallelization, "run up to X tasks in parallel, whenever possible"), + ioBytePerSecond: fs.Int64("ioBytePerSecond", 0, "limit the speed of each shard copy; 0 falls back to the volume server's maintenance rate"), + apply: fs.Bool("apply", false, "apply the balancing plan"), + force: fs.Bool("force", false, "apply the balancing plan (alias for -apply)"), + } +} + +func (c *commandEcBalance) argsApply(args []string) bool { + fs, f := newEcBalanceFlagSet(c.Name()) + fs.SetOutput(io.Discard) + if fs.Parse(args) != nil { + return false + } + handleDeprecatedForceFlag(io.Discard, fs, f.force, f.apply) + if *f.volumeIds != "" { + if _, err := parseVolumeIdsFlag(*f.volumeIds); err != nil { + return false + } + } + return *f.apply } diff --git a/weed/shell/command_ec_encode.go b/weed/shell/command_ec_encode.go index 5aab211eef..475362c91b 100644 --- a/weed/shell/command_ec_encode.go +++ b/weed/shell/command_ec_encode.go @@ -98,20 +98,10 @@ func (c *commandEcEncode) HasTag(CommandTag) bool { func (c *commandEcEncode) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) { - encodeCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError) - volumeId := encodeCommand.Int("volumeId", 0, "the volume id") - volumeIdsStr := encodeCommand.String("volumeIds", "", "comma-separated volume ids") - collection := encodeCommand.String("collection", "", "comma-separated collection names, wildcards, or regex patterns; empty matches the collection with no name") - fullPercentage := encodeCommand.Float64("fullPercent", 95, "the volume reaches the percentage of max volume size") - quietPeriod := encodeCommand.Duration("quietFor", time.Hour, "select volumes without no writes for this period") - maxParallelization := encodeCommand.Int("maxParallelization", DefaultMaxParallelization, "run up to X tasks in parallel, whenever possible") - batchSize := encodeCommand.Int("batchSize", DefaultEcBatchSize, "encode/re-balance/verify/delete up to this many volumes at a time (0 = all in one batch)") - forceChanges := encodeCommand.Bool("force", false, "force the encoding even if the cluster has less than recommended 4 nodes") - shardReplicaPlacement := encodeCommand.String("shardReplicaPlacement", "", "replica placement for EC shards, or master default if empty") - sourceDiskTypeStr := encodeCommand.String("sourceDiskType", "", "filter source volumes by disk type (hdd, ssd, or empty for all)") - diskTypeStr := encodeCommand.String("diskType", "", "target disk type for EC shards (hdd, ssd, or empty for default hdd)") - applyBalancing := encodeCommand.Bool("rebalance", true, "re-balance EC shards after creation (default: true)") - verbose := encodeCommand.Bool("verbose", false, "show detailed reasons why volumes are not selected for encoding") + encodeCommand, f := newEcEncodeFlagSet(c.Name()) + volumeId, volumeIdsStr, collection, fullPercentage, quietPeriod := f.volumeId, f.volumeIdsStr, f.collection, f.fullPercentage, f.quietPeriod + maxParallelization, batchSize, forceChanges, shardReplicaPlacement := f.maxParallelization, f.batchSize, f.forceChanges, f.shardReplicaPlacement + sourceDiskTypeStr, diskTypeStr, applyBalancing, verbose := f.sourceDiskTypeStr, f.diskTypeStr, f.applyBalancing, f.verbose if err = encodeCommand.Parse(args); err != nil { return err @@ -197,6 +187,48 @@ func (c *commandEcEncode) Do(args []string, commandEnv *CommandEnv, writer io.Wr return nil } + +type ecEncodeFlags struct { + volumeId *int + volumeIdsStr *string + collection *string + fullPercentage *float64 + quietPeriod *time.Duration + maxParallelization *int + batchSize *int + forceChanges *bool + shardReplicaPlacement *string + sourceDiskTypeStr *string + diskTypeStr *string + applyBalancing *bool + verbose *bool +} + +func newEcEncodeFlagSet(name string) (*flag.FlagSet, *ecEncodeFlags) { + fs := flag.NewFlagSet(name, flag.ContinueOnError) + return fs, &ecEncodeFlags{ + volumeId: fs.Int("volumeId", 0, "the volume id"), + volumeIdsStr: fs.String("volumeIds", "", "comma-separated volume ids"), + collection: fs.String("collection", "", "comma-separated collection names, wildcards, or regex patterns; empty matches the collection with no name"), + fullPercentage: fs.Float64("fullPercent", 95, "the volume reaches the percentage of max volume size"), + quietPeriod: fs.Duration("quietFor", time.Hour, "select volumes without no writes for this period"), + maxParallelization: fs.Int("maxParallelization", DefaultMaxParallelization, "run up to X tasks in parallel, whenever possible"), + batchSize: fs.Int("batchSize", DefaultEcBatchSize, "encode/re-balance/verify/delete up to this many volumes at a time (0 = all in one batch)"), + forceChanges: fs.Bool("force", false, "force the encoding even if the cluster has less than recommended 4 nodes"), + shardReplicaPlacement: fs.String("shardReplicaPlacement", "", "replica placement for EC shards, or master default if empty"), + sourceDiskTypeStr: fs.String("sourceDiskType", "", "filter source volumes by disk type (hdd, ssd, or empty for all)"), + diskTypeStr: fs.String("diskType", "", "target disk type for EC shards (hdd, ssd, or empty for default hdd)"), + applyBalancing: fs.Bool("rebalance", true, "re-balance EC shards after creation (default: true)"), + verbose: fs.Bool("verbose", false, "show detailed reasons why volumes are not selected for encoding"), + } +} + +func (c *commandEcEncode) argsApply(args []string) bool { + fs, _ := newEcEncodeFlagSet(c.Name()) + fs.SetOutput(io.Discard) + return fs.Parse(args) == nil +} + func collectVolumeIdsForEcEncode(commandEnv *CommandEnv, collectionPattern string, sourceDiskType *types.DiskType, fullPercentage float64, quietPeriod time.Duration, verbose bool) (vids []needle.VolumeId, matchedCollections []string, err error) { // compile regex pattern for collection matching collectionMatcher, err := compileCollectionPattern(collectionPattern) diff --git a/weed/shell/command_volume_balance.go b/weed/shell/command_volume_balance.go index 320c14d56d..77c086c07c 100644 --- a/weed/shell/command_volume_balance.go +++ b/weed/shell/command_volume_balance.go @@ -123,68 +123,35 @@ func (c *commandVolumeBalance) HasTag(CommandTag) bool { } func (c *commandVolumeBalance) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) { - allowedVolumeBy := map[string]*bool{ - "ALL": nil, - "ACTIVE": new(bool), - "FULL": new(bool), - } - *allowedVolumeBy["ACTIVE"] = true - balanceCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError) - verbose := balanceCommand.Bool("v", false, "verbose mode") - collection := balanceCommand.String("collection", "ALL_COLLECTIONS", "comma-separated collection names, wildcards, or regex patterns, or \"ALL_COLLECTIONS\" across collections, \"EACH_COLLECTION\" for each collection") - dc := balanceCommand.String("dataCenter", "", "only apply the balancing for this dataCenter") - racks := balanceCommand.String("racks", "", "only apply the balancing for this racks") - nodes := balanceCommand.String("nodes", "", "only apply the balancing for this nodes") - ioBytePerSecond := balanceCommand.Int64("ioBytePerSecond", 0, "limit volume-move copy speed in bytes per second (default 0 is unlimited)") - noLock := balanceCommand.Bool("noLock", false, "do not lock the admin shell at one's own risk") - applyBalancing := balanceCommand.Bool("apply", false, "apply the balancing plan.") - // TODO: remove this alias - applyBalancingAlias := balanceCommand.Bool("force", false, "apply the balancing plan (alias for -apply)") - volumesPerExec := balanceCommand.Int("volumesPerExec", 0, "how many volumes to move in one run (default is 0 for unlimited)") - maxParallelization := balanceCommand.Int("maxParallelization", 1, "run up to X volume moves in parallel, whenever possible") - byDiskUsage := balanceCommand.Bool("byDiskUsage", false, "rank servers by reported physical disk used percent instead of slot density; falls back to sum of volume sizes for all servers when any server does not report disk bytes. Use when maxVolumeCount is set too high for the disk.") - maxDiskUsagePercent := balanceCommand.Int("maxDiskUsagePercent", balancer.DefaultMaxDiskUsagePercent, "skip a move target whose physical disk used%% is at/above this; judged per server against its own disk, so heterogeneous disk sizes are fine. 0 or >=100 disables. Auto-skipped for servers that do not report disk bytes.") - - balanceCommand.Func("volumeBy", "only apply the balancing for ALL volumes and ACTIVE or FULL", func(flagValue string) error { - if flagValue == "" { - return nil - } - for allowed, volumeBy := range allowedVolumeBy { - if flagValue == allowed { - c.volumeByActive = volumeBy - return nil - } - } - return fmt.Errorf("use \"ALL\", \"ACTIVE\" or \"FULL\"") - }) + balanceCommand, f := newVolumeBalanceFlagSet(c.Name()) if err = balanceCommand.Parse(args); err != nil { return err } - handleDeprecatedForceFlag(writer, balanceCommand, applyBalancingAlias, applyBalancing) - c.applyBalancing = *applyBalancing - if *volumesPerExec < 0 { - return fmt.Errorf("volumesPerExec must be >= 0") + handleDeprecatedForceFlag(writer, balanceCommand, f.force, f.apply) + if err = f.validate(); err != nil { + return err } - if *maxParallelization < 1 { - return fmt.Errorf("maxParallelization must be >= 1") + if f.volumeBySet { + c.volumeByActive = f.volumeByActive } - c.ioBytePerSecond = *ioBytePerSecond - c.volumesPerExec = *volumesPerExec - c.maxParallelization = *maxParallelization + c.applyBalancing = *f.apply + c.ioBytePerSecond = *f.ioBytePerSecond + c.volumesPerExec = *f.volumesPerExec + c.maxParallelization = *f.maxParallelization c.movedCount = 0 - c.byDiskUsage = *byDiskUsage - c.diskUsageHighWaterPercent = *maxDiskUsagePercent + c.byDiskUsage = *f.byDiskUsage + c.diskUsageHighWaterPercent = *f.maxDiskUsagePercent infoAboutSimulationMode(writer, c.applyBalancing, "-apply") - if *noLock { + if *f.noLock { commandEnv.noLock = true } else { if err = commandEnv.confirmIsLocked(args); err != nil { return } } - commandEnv.verbose = *verbose + commandEnv.verbose = *f.verbose c.commandEnv = commandEnv // collect topology information @@ -194,11 +161,11 @@ func (c *commandVolumeBalance) Do(args []string, commandEnv *CommandEnv, writer return err } - volumeServers := collectVolumeServersByDcRackNode(topologyInfo, *dc, *racks, *nodes) + volumeServers := collectVolumeServersByDcRackNode(topologyInfo, *f.dc, *f.racks, *f.nodes) volumeReplicas, _ := collectVolumeReplicaLocations(topologyInfo) diskTypes := collectVolumeDiskTypes(topologyInfo) - if *collection == string(wildcard.CollectionFilterEach) { + if *f.collection == string(wildcard.CollectionFilterEach) { collections, err := ListCollectionNames(commandEnv, true, false) if err != nil { return err @@ -212,18 +179,18 @@ func (c *commandVolumeBalance) Do(args []string, commandEnv *CommandEnv, writer return err } } - } else if *collection == string(wildcard.CollectionFilterAll) || *collection == "*" { + } else if *f.collection == string(wildcard.CollectionFilterAll) || *f.collection == "*" { // Pass nil matcher for all collections if err = c.balanceVolumeServers(diskTypes, volumeReplicas, volumeServers, nil, string(wildcard.CollectionFilterAll)); err != nil { return err } } else { // Compile user-provided pattern - collectionMatcher, err := compileCollectionPattern(*collection) + collectionMatcher, err := compileCollectionPattern(*f.collection) if err != nil { - return fmt.Errorf("invalid collection pattern '%s': %v", *collection, err) + return fmt.Errorf("invalid collection pattern '%s': %v", *f.collection, err) } - if err = c.balanceVolumeServers(diskTypes, volumeReplicas, volumeServers, collectionMatcher, *collection); err != nil { + if err = c.balanceVolumeServers(diskTypes, volumeReplicas, volumeServers, collectionMatcher, *f.collection); err != nil { return err } } @@ -231,6 +198,72 @@ func (c *commandVolumeBalance) Do(args []string, commandEnv *CommandEnv, writer return nil } +type volumeBalanceFlags struct { + verbose, noLock, apply, force, byDiskUsage *bool + collection, dc, racks, nodes *string + ioBytePerSecond *int64 + volumesPerExec, maxParallelization, maxDiskUsagePercent *int + volumeBySet bool + volumeByActive *bool +} + +func newVolumeBalanceFlagSet(name string) (*flag.FlagSet, *volumeBalanceFlags) { + fs := flag.NewFlagSet(name, flag.ContinueOnError) + f := &volumeBalanceFlags{ + verbose: fs.Bool("v", false, "verbose mode"), + collection: fs.String("collection", "ALL_COLLECTIONS", "comma-separated collection names, wildcards, or regex patterns, or \"ALL_COLLECTIONS\" across collections, \"EACH_COLLECTION\" for each collection"), + dc: fs.String("dataCenter", "", "only apply the balancing for this dataCenter"), + racks: fs.String("racks", "", "only apply the balancing for this racks"), + nodes: fs.String("nodes", "", "only apply the balancing for this nodes"), + ioBytePerSecond: fs.Int64("ioBytePerSecond", 0, "limit volume-move copy speed in bytes per second (default 0 is unlimited)"), + noLock: fs.Bool("noLock", false, "do not lock the admin shell at one's own risk"), + apply: fs.Bool("apply", false, "apply the balancing plan."), + force: fs.Bool("force", false, "apply the balancing plan (alias for -apply)"), + volumesPerExec: fs.Int("volumesPerExec", 0, "how many volumes to move in one run (default is 0 for unlimited)"), + maxParallelization: fs.Int("maxParallelization", 1, "run up to X volume moves in parallel, whenever possible"), + byDiskUsage: fs.Bool("byDiskUsage", false, "rank servers by reported physical disk used percent instead of slot density; falls back to sum of volume sizes for all servers when any server does not report disk bytes. Use when maxVolumeCount is set too high for the disk."), + maxDiskUsagePercent: fs.Int("maxDiskUsagePercent", balancer.DefaultMaxDiskUsagePercent, "skip a move target whose physical disk used%% is at/above this; judged per server against its own disk, so heterogeneous disk sizes are fine. 0 or >=100 disables. Auto-skipped for servers that do not report disk bytes."), + } + fs.Func("volumeBy", "only apply the balancing for ALL volumes and ACTIVE or FULL", func(flagValue string) error { + switch flagValue { + case "": + return nil + case "ALL": + f.volumeByActive = nil + case "ACTIVE": + f.volumeByActive = new(bool) + *f.volumeByActive = true + case "FULL": + f.volumeByActive = new(bool) + default: + return fmt.Errorf("use \"ALL\", \"ACTIVE\" or \"FULL\"") + } + f.volumeBySet = true + return nil + }) + return fs, f +} + +func (f *volumeBalanceFlags) validate() error { + if *f.volumesPerExec < 0 { + return fmt.Errorf("volumesPerExec must be >= 0") + } + if *f.maxParallelization < 1 { + return fmt.Errorf("maxParallelization must be >= 1") + } + return nil +} + +func (c *commandVolumeBalance) argsApply(args []string) bool { + fs, f := newVolumeBalanceFlagSet(c.Name()) + fs.SetOutput(io.Discard) + if fs.Parse(args) != nil { + return false + } + handleDeprecatedForceFlag(io.Discard, fs, f.force, f.apply) + return f.validate() == nil && *f.apply +} + func (c *commandVolumeBalance) balanceVolumeServers(diskTypes []types.DiskType, volumeReplicas map[uint32][]*VolumeReplica, nodes []*Node, collectionMatcher *wildcard.CollectionMatcher, collectionName string) error { for _, diskType := range diskTypes { if c.volumesPerExec > 0 && c.movedCount >= c.volumesPerExec { diff --git a/weed/shell/command_volume_vacuum.go b/weed/shell/command_volume_vacuum.go index 965f7e3b99..131cc3b0cb 100644 --- a/weed/shell/command_volume_vacuum.go +++ b/weed/shell/command_volume_vacuum.go @@ -49,12 +49,27 @@ func (c *commandVacuum) HasTag(CommandTag) bool { return false } +func newVolumeVacuumFlagSet(name string) (fs *flag.FlagSet, garbageThreshold *float64, collection, volumeIds *string) { + fs = flag.NewFlagSet(name, flag.ContinueOnError) + garbageThreshold = fs.Float64("garbageThreshold", 0.3, "vacuum when garbage is more than this limit") + collection = fs.String("collection", "", "comma-separated collection names, wildcards, or regex patterns; empty or \"*\" matches all, \""+CollectionDefault+"\" the collection with no name") + volumeIds = fs.String("volumeId", "", "comma-separated list of volume IDs") + return +} + +func (c *commandVacuum) argsApply(args []string) bool { + fs, _, collection, _ := newVolumeVacuumFlagSet(c.Name()) + fs.SetOutput(io.Discard) + if fs.Parse(args) != nil { + return false + } + _, err := wildcard.CompileCollectionMatcher(*collection) + return err == nil +} + func (c *commandVacuum) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) { - volumeVacuumCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError) - garbageThreshold := volumeVacuumCommand.Float64("garbageThreshold", 0.3, "vacuum when garbage is more than this limit") - collection := volumeVacuumCommand.String("collection", "", "comma-separated collection names, wildcards, or regex patterns; empty or \"*\" matches all, \""+CollectionDefault+"\" the collection with no name") - volumeIds := volumeVacuumCommand.String("volumeId", "", "comma-separated list of volume IDs") + volumeVacuumCommand, garbageThreshold, collection, volumeIds := newVolumeVacuumFlagSet(c.Name()) if err = volumeVacuumCommand.Parse(args); err != nil { return err } diff --git a/weed/shell/script_command.go b/weed/shell/script_command.go new file mode 100644 index 0000000000..195a3072b3 --- /dev/null +++ b/weed/shell/script_command.go @@ -0,0 +1,36 @@ +package shell + +import ( + "regexp" + "strings" +) + +var scriptTokenRegex = regexp.MustCompile(`'.*?'|".*?"|\S+`) + +// SplitScriptCommand splits one admin script command into its name and unquoted arguments. +func SplitScriptCommand(chunk string) (name string, args []string, ok bool) { + parts := scriptTokenRegex.FindAllString(chunk, -1) + if len(parts) == 0 { + return "", nil, false + } + args = make([]string, 0, len(parts)-1) + for _, arg := range parts[1:] { + args = append(args, strings.Trim(arg, "\"'")) + } + return strings.TrimSpace(parts[0]), args, true +} + +type argsApplier interface { + argsApply(args []string) bool +} + +// CommandArgsApply reports whether the named command accepts args and changes the cluster with them. +func CommandArgsApply(name string, args []string) bool { + for _, c := range Commands { + if c.Name() == name { + applier, ok := c.(argsApplier) + return ok && applier.argsApply(args) + } + } + return false +} diff --git a/weed/shell/script_command_test.go b/weed/shell/script_command_test.go new file mode 100644 index 0000000000..045ea52670 --- /dev/null +++ b/weed/shell/script_command_test.go @@ -0,0 +1,36 @@ +package shell + +import "testing" + +func TestCommandArgsApply(t *testing.T) { + cases := []struct { + name string + args []string + want bool + }{ + {"ec.balance", nil, false}, + {"ec.balance", []string{"-apply"}, true}, + {"ec.balance", []string{"-volumeIds=1,2", "-apply"}, true}, + {"ec.balance", []string{"-volumeIds=not-a-volume-id", "-apply"}, false}, + {"ec.balance", []string{"-bogus", "-apply"}, false}, + {"volume.balance", nil, false}, + {"volume.balance", []string{"-force"}, true}, + {"volume.balance", []string{"-volumeBy=FULL", "-apply"}, true}, + {"volume.balance", []string{"-volumeBy=SOME", "-apply"}, false}, + {"volume.balance", []string{"-maxParallelization=0", "-apply"}, false}, + {"volume.balance", []string{"-apply", "-force=false"}, false}, + {"ec.encode", nil, true}, + {"ec.encode", []string{"-collection=a", "-quietFor=1h"}, true}, + {"ec.encode", []string{"-quietFor=soon"}, false}, + {"volume.vacuum", nil, true}, + {"volume.vacuum", []string{"-garbageThreshold=0.2"}, true}, + {"volume.vacuum", []string{"-apply"}, false}, + {"volume.list", []string{"-apply"}, false}, + {"no.such.command", []string{"-apply"}, false}, + } + for _, c := range cases { + if got := CommandArgsApply(c.name, c.args); got != c.want { + t.Errorf("CommandArgsApply(%q, %q) = %v, want %v", c.name, c.args, got, c.want) + } + } +}