mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * shell: share ec.balance's flag set and report whether its arguments apply the plan Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * shell, plugin/worker: move admin_script command tokenizing into the shell package Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * shell: report whether volume.balance arguments apply its plan Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * shell: report whether volume.vacuum accepts its arguments Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * admin: show each maintenance overlap on the plugin pages Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1e4739f97a
commit
b53f6d4b5e
18 files changed
+608
-107
No files matched your search
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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, "<div id=\"plugin-scheduler-blockers\" aria-live=\"polite\"></div><script>\n window.renderPluginSchedulerStatus = function(data) {\n const root = document.getElementById('plugin-scheduler-blockers');\n if (!root) return;\n root.replaceChildren();\n const lock = data.lock || {};\n const waiters = lock.waiters || [];\n if (waiters.length) {\n const alert = document.createElement('div');\n alert.className = 'alert alert-warning';\n const title = document.createElement('strong');\n title.textContent = 'Waiting for the maintenance lock';\n alert.appendChild(title);\n const owner = document.createElement('div');\n owner.textContent = lock.holder ? 'Lock owner: ' + lock.holder : (lock.holder_error || 'Lock owner not reported');\n if (lock.holder_message) owner.textContent += ' — ' + lock.holder_message;\n alert.appendChild(owner);\n waiters.forEach(function(waiter) {\n const line = document.createElement('div');\n const since = new Date(waiter.since);\n const now = new Date((data.scheduler || {}).now || Date.now());\n const seconds = Math.max(0, Math.floor((now - since) / 1000));\n line.textContent = waiter.reason + ' · since ' + since.toLocaleString() +\n ' (local time) · waiting ' + Math.floor(seconds / 60) + 'm ' + (seconds % 60) + 's';\n alert.appendChild(line);\n });\n const note = document.createElement('div');\n note.className = 'small mt-1';\n note.textContent = 'This lane cannot advance until the lock becomes available. A scheduled check time is not a guaranteed start time.';\n alert.appendChild(note);\n root.appendChild(alert);\n }\n const scheduler = data.scheduler || {};\n const now = new Date(scheduler.now || Date.now());\n (scheduler.job_types || []).forEach(function(job) {\n if (data.job_type ? job.job_type !== data.job_type : !job.enabled) return;\n const until = job.detection_eligible_at ? new Date(job.detection_eligible_at) : null;\n const cooling = until && until > now;\n if (!job.cooldown_error && !cooling && !(data.job_type && job.cooldown_seconds)) return;\n const box = document.createElement('div');\n box.className = 'alert ' + (job.cooldown_error ? 'alert-warning' : 'alert-info');\n const title = document.createElement('strong');\n title.textContent = job.job_type + ': ' + (job.cooldown_error || (cooling ? 'Cooldown after successful job' : until ? 'Cooldown elapsed' : 'No successful job yet'));\n box.appendChild(title);\n const line = document.createElement('div');\n const seconds = job.cooldown_seconds || 0;\n const duration = seconds >= 3600 ? (seconds / 3600) + ' hours' : seconds >= 60 ? (seconds / 60) + ' minutes' : seconds + ' seconds';\n line.textContent = 'Configured cooldown: ' + duration + ' (' + seconds + ' seconds).';\n if (job.last_successful_run_at) line.textContent += ' Last success: ' + new Date(job.last_successful_run_at).toLocaleString() + '.';\n if (until) line.textContent += ' Eligible after: ' + until.toLocaleString() + '.';\n if (cooling) line.textContent += ' Remaining: ' + Math.ceil((until - now) / 60000) + ' minutes.';\n box.appendChild(line);\n const note = document.createElement('div');\n note.className = 'small mt-1';\n note.textContent = 'Applies across this job type. Locks and other jobs in the lane can delay the actual start.';\n box.appendChild(note);\n root.appendChild(box);\n });\n };\n </script>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<div id=\"plugin-scheduler-blockers\" aria-live=\"polite\"></div><script>\n window.renderPluginSchedulerStatus = function(data) {\n const root = document.getElementById('plugin-scheduler-blockers');\n if (!root) return;\n root.replaceChildren();\n (data.maintenance_overlaps || []).forEach(function(overlap) {\n const runners = overlap.runners || [];\n const box = document.createElement('div');\n box.className = 'alert alert-warning';\n const heading = document.createElement('strong');\n heading.textContent = overlap.work + ' has ' + runners.length + ' independent runners';\n box.appendChild(heading);\n runners.forEach(function(name) {\n const line = document.createElement('div');\n line.textContent = name;\n box.appendChild(line);\n });\n const hint = document.createElement('div');\n hint.className = 'small mt-1';\n hint.textContent = 'Each one plans from the same topology without knowing about the others, so their changes can collide. Keep only one enabled.';\n box.appendChild(hint);\n root.appendChild(box);\n });\n const lock = data.lock || {};\n const waiters = lock.waiters || [];\n if (waiters.length) {\n const alert = document.createElement('div');\n alert.className = 'alert alert-warning';\n const title = document.createElement('strong');\n title.textContent = 'Waiting for the maintenance lock';\n alert.appendChild(title);\n const owner = document.createElement('div');\n owner.textContent = lock.holder ? 'Lock owner: ' + lock.holder : (lock.holder_error || 'Lock owner not reported');\n if (lock.holder_message) owner.textContent += ' — ' + lock.holder_message;\n alert.appendChild(owner);\n waiters.forEach(function(waiter) {\n const line = document.createElement('div');\n const since = new Date(waiter.since);\n const now = new Date((data.scheduler || {}).now || Date.now());\n const seconds = Math.max(0, Math.floor((now - since) / 1000));\n line.textContent = waiter.reason + ' · since ' + since.toLocaleString() +\n ' (local time) · waiting ' + Math.floor(seconds / 60) + 'm ' + (seconds % 60) + 's';\n alert.appendChild(line);\n });\n const note = document.createElement('div');\n note.className = 'small mt-1';\n note.textContent = 'This lane cannot advance until the lock becomes available. A scheduled check time is not a guaranteed start time.';\n alert.appendChild(note);\n root.appendChild(alert);\n }\n const scheduler = data.scheduler || {};\n const now = new Date(scheduler.now || Date.now());\n (scheduler.job_types || []).forEach(function(job) {\n if (data.job_type ? job.job_type !== data.job_type : !job.enabled) return;\n const until = job.detection_eligible_at ? new Date(job.detection_eligible_at) : null;\n const cooling = until && until > now;\n if (!job.cooldown_error && !cooling && !(data.job_type && job.cooldown_seconds)) return;\n const box = document.createElement('div');\n box.className = 'alert ' + (job.cooldown_error ? 'alert-warning' : 'alert-info');\n const title = document.createElement('strong');\n title.textContent = job.job_type + ': ' + (job.cooldown_error || (cooling ? 'Cooldown after successful job' : until ? 'Cooldown elapsed' : 'No successful job yet'));\n box.appendChild(title);\n const line = document.createElement('div');\n const seconds = job.cooldown_seconds || 0;\n const duration = seconds >= 3600 ? (seconds / 3600) + ' hours' : seconds >= 60 ? (seconds / 60) + ' minutes' : seconds + ' seconds';\n line.textContent = 'Configured cooldown: ' + duration + ' (' + seconds + ' seconds).';\n if (job.last_successful_run_at) line.textContent += ' Last success: ' + new Date(job.last_successful_run_at).toLocaleString() + '.';\n if (until) line.textContent += ' Eligible after: ' + until.toLocaleString() + '.';\n if (cooling) line.textContent += ' Remaining: ' + Math.ceil((until - now) / 60000) + ' minutes.';\n box.appendChild(line);\n const note = document.createElement('div');\n note.className = 'small mt-1';\n note.textContent = 'Applies across this job type. Locks and other jobs in the lane can delay the actual start.';\n box.appendChild(note);\n root.appendChild(box);\n });\n };\n </script>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -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, "<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 scheduled check</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=\"bi bi-bar-chart 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=\"bi bi-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=\"bi bi-people 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=\"bi bi-sliders 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=\"bi bi-cloud-download 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=\"bi bi-floppy me-1\"></i>Save Config</button> <button type=\"button\" class=\"btn btn-outline-primary\" id=\"plugin-trigger-detection-btn\"><i class=\"bi bi-search me-1\"></i>Run Detection</button> <button type=\"button\" class=\"btn btnLine truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "<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 scheduled check</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=\"bi bi-bar-chart 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=\"bi bi-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=\"bi bi-people 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=\"bi bi-sliders 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=\"bi bi-cloud-download 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=\"bi bi-floppy me-1\"></i>Save Config</button> <button type=\"button\" class=\"btn btn-outline-primary\" id=\"plugin-trigger-detection-btn\"><i class=\"bi bi-search me-1\"></i>Run Detection</button> <button type=\"button\" class=\"btn btnLine truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user