diff --git a/weed/admin/dash/worker_grpc_server.go b/weed/admin/dash/worker_grpc_server.go index a6e9294d87..e5c9a6616d 100644 --- a/weed/admin/dash/worker_grpc_server.go +++ b/weed/admin/dash/worker_grpc_server.go @@ -13,7 +13,6 @@ import ( "github.com/seaweedfs/seaweedfs/weed/admin/maintenance" "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/pb" - "github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb" "github.com/seaweedfs/seaweedfs/weed/pb/worker_pb" "github.com/seaweedfs/seaweedfs/weed/security" stats_collect "github.com/seaweedfs/seaweedfs/weed/stats" @@ -107,7 +106,7 @@ func (s *WorkerGrpcServer) StartWithTLS(bindIp string, port int, listener net.Li worker_pb.RegisterWorkerServiceServer(grpcServer, s) if plugin := s.adminServer.GetPlugin(); plugin != nil { - plugin_pb.RegisterPluginControlServiceServer(grpcServer, plugin) + plugin.RegisterGrpcServices(grpcServer) glog.V(0).Infof("Plugin gRPC service registered on worker gRPC server") } diff --git a/weed/admin/plugin/plugin.go b/weed/admin/plugin/plugin.go index ef11b0817b..f799e93cdc 100644 --- a/weed/admin/plugin/plugin.go +++ b/weed/admin/plugin/plugin.go @@ -79,6 +79,8 @@ type Plugin struct { lanes map[SchedulerLane]*schedulerLaneState + schedulerExtension schedulerExtension + // Execution slots this admin holds on workers, one entry per job in // flight; see executorLoadLocked for how they meet the heartbeat. execResMu sync.Mutex @@ -240,6 +242,7 @@ func New(options Options) (*Plugin, error) { shutdownCh: make(chan struct{}), } plugin.ctx, plugin.ctxCancel = context.WithCancel(context.Background()) + plugin.schedulerExtension = newSchedulerExtension(plugin) if err := plugin.loadPersistedMonitorState(); err != nil { glog.Warningf("Plugin failed to load persisted monitoring state: %v", err) diff --git a/weed/admin/plugin/plugin_scheduler.go b/weed/admin/plugin/plugin_scheduler.go index e0dfd525de..abfe1812db 100644 --- a/weed/admin/plugin/plugin_scheduler.go +++ b/weed/admin/plugin/plugin_scheduler.go @@ -143,6 +143,9 @@ func (r *Plugin) runLaneSchedulerIteration(ls *schedulerLaneState) bool { return false } + if hadJobs, handled := r.schedulerExt().runLane(ls, jobTypes); handled { + return hadJobs + } if LaneRequiresLock(ls.lane) { return r.runLaneSchedulerIterationSequential(ls, jobTypes) } @@ -871,6 +874,9 @@ func (r *Plugin) dispatchScheduledProposals( default: } job := buildScheduledJobSpec(jobType, proposal, index) + if !r.schedulerExt().admitJob(job) { + continue + } r.trackExecutionQueued(job) jobs = append(jobs, job) } @@ -947,8 +953,16 @@ func (r *Plugin) dispatchScheduledProposals( } blockedSince = time.Time{} + release, started := r.startScheduledJob(queues, item, executor, release) + if !started { + if !waitForShutdownOrTimerWithContext(r.shutdownCh, ctx, policy.ExecutorReserveBackoff) { + return + } + continue + } + var releaseJobLock func() - if jobsRequireLock { + if jobsRequireLock && r.schedulerExt().jobHoldsLock(item.job, executor) { var lockErr error releaseJobLock, lockErr = r.acquireAdminLock(fmt.Sprintf("plugin scheduler %s job %s", jobType, item.job.JobId)) if lockErr != nil { diff --git a/weed/admin/plugin/scheduler_extension.go b/weed/admin/plugin/scheduler_extension.go new file mode 100644 index 0000000000..c95dd36e2e --- /dev/null +++ b/weed/admin/plugin/scheduler_extension.go @@ -0,0 +1,95 @@ +package plugin + +import ( + "github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb" + "google.golang.org/grpc" +) + +// schedulerExtension is the set of points where scheduling policy can be +// layered on the lane scheduler. The default leaves every decision alone. +type schedulerExtension interface { + // runLane may take over one scheduling pass of a lane; handled reports + // whether it did. + runLane(ls *schedulerLaneState, jobTypes []string) (hadJobs, handled bool) + // admitJob reports whether a job built from a proposal is queued. + admitJob(job *plugin_pb.JobSpec) bool + // startJob decides whether a queued job starts on the executor a slot + // was just reserved on. If it does, done is called once the job has + // stopped running; done may be nil. + startJob(job *plugin_pb.JobSpec, executor *WorkerSession) (done func(), hold startHold) + // jobHoldsLock reports whether a job of a lane that needs the cluster + // admin lock holds it from start to finish on this executor. + jobHoldsLock(job *plugin_pb.JobSpec, executor *WorkerSession) bool + // registerServices adds what the extension serves to workers. + registerServices(server grpc.ServiceRegistrar) +} + +// startHold is what to do with a job that reached the head of its queue. +type startHold int + +const ( + // startNow runs the job. + startNow startHold = iota + // startRetry keeps the job at the head of its queue and asks again. + startRetry + // startOthersFirst moves the job behind the rest of its queue. + startOthersFirst +) + +type defaultSchedulerExtension struct{} + +func (defaultSchedulerExtension) runLane(*schedulerLaneState, []string) (bool, bool) { + return false, false +} + +func (defaultSchedulerExtension) admitJob(*plugin_pb.JobSpec) bool { return true } + +func (defaultSchedulerExtension) startJob(*plugin_pb.JobSpec, *WorkerSession) (func(), startHold) { + return nil, startNow +} + +func (defaultSchedulerExtension) jobHoldsLock(*plugin_pb.JobSpec, *WorkerSession) bool { + return true +} + +func (defaultSchedulerExtension) registerServices(grpc.ServiceRegistrar) {} + +// newSchedulerExtension builds the extension a Plugin schedules with. +var newSchedulerExtension = func(*Plugin) schedulerExtension { return defaultSchedulerExtension{} } + +// RegisterGrpcServices registers what the plugin serves to workers. +func (r *Plugin) RegisterGrpcServices(server grpc.ServiceRegistrar) { + plugin_pb.RegisterPluginControlServiceServer(server, r) + r.schedulerExt().registerServices(server) +} + +func (r *Plugin) schedulerExt() schedulerExtension { + if r.schedulerExtension == nil { + return defaultSchedulerExtension{} + } + return r.schedulerExtension +} + +// startScheduledJob asks the extension whether the job may run in the slot +// reserved for it. If not, the slot is given back and the job returns to its +// queue. If so, the release it returns also reports the job done. +func (r *Plugin) startScheduledJob(queues *workerJobQueues, item *queuedJob, executor *WorkerSession, release func()) (func(), bool) { + done, hold := r.schedulerExt().startJob(item.job, executor) + switch hold { + case startNow: + if done == nil { + return release, true + } + return func() { + release() + done() + }, true + case startOthersFirst: + release() + queues.push(item.home, item.job) + default: + release() + queues.pushFront(item) + } + return nil, false +} diff --git a/weed/admin/plugin/scheduler_extension_test.go b/weed/admin/plugin/scheduler_extension_test.go new file mode 100644 index 0000000000..514c505b2e --- /dev/null +++ b/weed/admin/plugin/scheduler_extension_test.go @@ -0,0 +1,292 @@ +package plugin + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb" + "google.golang.org/grpc" +) + +// recordingExtension answers from the funcs it is given and counts calls. +type recordingExtension struct { + defaultSchedulerExtension + + mu sync.Mutex + registered int + lanes []SchedulerLane + admitted []string + asked []string + done []string + + handleLane bool + admit func(job *plugin_pb.JobSpec) bool + hold func(job *plugin_pb.JobSpec, asked int) startHold + holdsLock *bool +} + +func (e *recordingExtension) runLane(ls *schedulerLaneState, jobTypes []string) (bool, bool) { + e.mu.Lock() + defer e.mu.Unlock() + e.lanes = append(e.lanes, ls.lane) + return false, e.handleLane +} + +func (e *recordingExtension) admitJob(job *plugin_pb.JobSpec) bool { + e.mu.Lock() + defer e.mu.Unlock() + if e.admit != nil && !e.admit(job) { + return false + } + e.admitted = append(e.admitted, job.DedupeKey) + return true +} + +func (e *recordingExtension) startJob(job *plugin_pb.JobSpec, executor *WorkerSession) (func(), startHold) { + e.mu.Lock() + defer e.mu.Unlock() + e.asked = append(e.asked, job.DedupeKey) + if e.hold != nil { + if hold := e.hold(job, len(e.asked)); hold != startNow { + return nil, hold + } + } + return func() { + e.mu.Lock() + e.done = append(e.done, job.DedupeKey) + e.mu.Unlock() + }, startNow +} + +func (e *recordingExtension) jobHoldsLock(job *plugin_pb.JobSpec, executor *WorkerSession) bool { + if e.holdsLock != nil { + return *e.holdsLock + } + return e.defaultSchedulerExtension.jobHoldsLock(job, executor) +} + +func (e *recordingExtension) registerServices(grpc.ServiceRegistrar) { + e.mu.Lock() + e.registered++ + e.mu.Unlock() +} + +func (e *recordingExtension) snapshot() (admitted, asked, done []string) { + e.mu.Lock() + defer e.mu.Unlock() + return append([]string(nil), e.admitted...), append([]string(nil), e.asked...), append([]string(nil), e.done...) +} + +// dispatchWithExtension runs three proposals of jobType against a worker +// that has capacity but no stream, so every started job fails at send. +func dispatchWithExtension(t *testing.T, ext schedulerExtension, lm LockManager, jobType string) (*Plugin, [3]int) { + t.Helper() + pluginSvc, err := New(Options{LockManager: lm}) + if err != nil { + t.Fatalf("New: %v", err) + } + t.Cleanup(pluginSvc.Shutdown) + pluginSvc.schedulerExtension = ext + + pluginSvc.registry.UpsertFromHello(&plugin_pb.WorkerHello{ + WorkerId: "worker-a", + Capabilities: []*plugin_pb.JobTypeCapability{ + {JobType: jobType, CanExecute: true, MaxExecutionConcurrency: 4}, + }, + }) + policy := schedulerPolicy{ + ExecutionConcurrency: 1, + PerWorkerConcurrency: 1, + ExecutionTimeout: time.Second, + ExecutorReserveBackoff: time.Millisecond, + } + proposals := []*plugin_pb.JobProposal{ + {ProposalId: "p1", JobType: jobType, DedupeKey: "k1"}, + {ProposalId: "p2", JobType: jobType, DedupeKey: "k2"}, + {ProposalId: "p3", JobType: jobType, DedupeKey: "k3"}, + } + success, errCount, canceled := pluginSvc.dispatchScheduledProposals( + context.Background(), jobType, proposals, &plugin_pb.ClusterContext{}, policy) + return pluginSvc, [3]int{success, errCount, canceled} +} + +func TestSchedulerExtensionDefaultsLeaveSchedulingAlone(t *testing.T) { + ext := (&Plugin{}).schedulerExt() + if hadJobs, handled := ext.runLane(newLaneState(LaneDefault), nil); hadJobs || handled { + t.Fatal("default extension took over a lane") + } + if !ext.admitJob(&plugin_pb.JobSpec{}) { + t.Fatal("default extension refused a job") + } + if done, hold := ext.startJob(&plugin_pb.JobSpec{}, nil); done != nil || hold != startNow { + t.Fatal("default extension held a job") + } + if !ext.jobHoldsLock(&plugin_pb.JobSpec{JobType: "volume_balance"}, nil) { + t.Fatal("default extension let a job run without the lock") + } +} + +func TestSchedulerExtensionAdmitsJobsBeforeTheyAreQueued(t *testing.T) { + ext := &recordingExtension{admit: func(job *plugin_pb.JobSpec) bool { return job.DedupeKey != "k2" }} + pluginSvc, counts := dispatchWithExtension(t, ext, nil, "s3_lifecycle") + if counts != [3]int{0, 2, 0} { + t.Fatalf("dispatch counts = %v, want two failed sends", counts) + } + pluginSvc.jobsMu.RLock() + defer pluginSvc.jobsMu.RUnlock() + if len(pluginSvc.jobs) != 2 { + t.Fatalf("tracked jobs = %d, want 2", len(pluginSvc.jobs)) + } + for _, job := range pluginSvc.jobs { + if job.DedupeKey == "k2" { + t.Fatal("a job the extension refused was tracked") + } + } +} + +func TestSchedulerExtensionHoldsAJobAtTheHeadOfItsQueue(t *testing.T) { + ext := &recordingExtension{hold: func(_ *plugin_pb.JobSpec, asked int) startHold { + if asked <= 3 { + return startRetry + } + return startNow + }} + _, counts := dispatchWithExtension(t, ext, nil, "s3_lifecycle") + if counts != [3]int{0, 3, 0} { + t.Fatalf("dispatch counts = %v", counts) + } + _, asked, done := ext.snapshot() + want := []string{"k1", "k1", "k1", "k1", "k2", "k3"} + if len(asked) != len(want) { + t.Fatalf("asked = %v, want %v", asked, want) + } + for i := range want { + if asked[i] != want[i] { + t.Fatalf("asked = %v, want %v", asked, want) + } + } + if len(done) != 3 || done[0] != "k1" || done[1] != "k2" || done[2] != "k3" { + t.Fatalf("done = %v, want each started job reported once in order", done) + } +} + +func TestSchedulerExtensionLetsOtherJobsOfTheQueueGoFirst(t *testing.T) { + ext := &recordingExtension{hold: func(job *plugin_pb.JobSpec, asked int) startHold { + if job.DedupeKey == "k1" && asked == 1 { + return startOthersFirst + } + return startNow + }} + _, counts := dispatchWithExtension(t, ext, nil, "s3_lifecycle") + if counts != [3]int{0, 3, 0} { + t.Fatalf("dispatch counts = %v", counts) + } + _, _, done := ext.snapshot() + if len(done) != 3 || done[0] != "k2" || done[1] != "k3" || done[2] != "k1" { + t.Fatalf("done = %v, want k1 behind the rest", done) + } +} + +func TestSchedulerExtensionReleasesTheSlotOfAHeldJob(t *testing.T) { + ext := &recordingExtension{hold: func(_ *plugin_pb.JobSpec, asked int) startHold { + if asked <= 5 { + return startRetry + } + return startNow + }} + pluginSvc, _ := dispatchWithExtension(t, ext, nil, "s3_lifecycle") + executors, err := pluginSvc.registry.ListExecutors("s3_lifecycle") + if err != nil || len(executors) != 1 { + t.Fatalf("executors = %v, %v", executors, err) + } + if load := pluginSvc.executorWorkerLoad(executors[0]); load != 0 { + t.Fatalf("worker load = %d after dispatch, held jobs kept their slots", load) + } +} + +func TestSchedulerExtensionDecidesWhetherAJobHoldsTheLock(t *testing.T) { + for _, holds := range []bool{true, false} { + lm := &trackingLockManager{} + holds := holds + _, counts := dispatchWithExtension(t, &recordingExtension{holdsLock: &holds}, lm, "volume_balance") + if counts != [3]int{0, 3, 0} { + t.Fatalf("dispatch counts = %v", counts) + } + want := 0 + if holds { + want = 3 + } + if got := lm.count(); got != want { + t.Fatalf("holds=%v: lock acquired %d times, want %d", holds, got, want) + } + } + + // A lane that needs no lock is not asked, and takes none. + lm := &trackingLockManager{} + holds := true + dispatchWithExtension(t, &recordingExtension{holdsLock: &holds}, lm, "s3_lifecycle") + if got := lm.count(); got != 0 { + t.Fatalf("lifecycle lane acquired the lock %d times", got) + } +} + +func TestSchedulerExtensionCanTakeOverALane(t *testing.T) { + for _, handle := range []bool{true, false} { + lm := &trackingLockManager{} + pluginSvc, err := New(Options{LockManager: lm}) + if err != nil { + t.Fatalf("New: %v", err) + } + ext := &recordingExtension{handleLane: handle} + pluginSvc.schedulerExtension = ext + pluginSvc.clusterContextProvider = func(context.Context) (*plugin_pb.ClusterContext, error) { + return &plugin_pb.ClusterContext{}, nil + } + pluginSvc.registry.UpsertFromHello(&plugin_pb.WorkerHello{ + WorkerId: "worker-a", + Capabilities: []*plugin_pb.JobTypeCapability{{JobType: "vacuum", CanDetect: true}}, + }) + if err := pluginSvc.SaveJobTypeConfig(&plugin_pb.PersistedJobTypeConfig{ + JobType: "vacuum", + AdminRuntime: &plugin_pb.AdminRuntimeConfig{Enabled: true, DetectionIntervalMinutes: 1}, + }); err != nil { + t.Fatalf("SaveJobTypeConfig: %v", err) + } + pluginSvc.schedulerMu.Lock() + pluginSvc.nextDetectionAt["vacuum"] = time.Now().UTC().Add(-time.Second) + pluginSvc.schedulerMu.Unlock() + + pluginSvc.runLaneSchedulerIteration(pluginSvc.lanes[LaneDefault]) + pluginSvc.Shutdown() + + if len(ext.lanes) != 1 || ext.lanes[0] != LaneDefault { + t.Fatalf("handle=%v: extension saw lanes %v", handle, ext.lanes) + } + // The built-in pass detects under the lock; a lane the extension + // took over never gets there. + if got := lm.count() > 0; got == handle { + t.Fatalf("handle=%v: built-in lane pass ran=%v", handle, got) + } + } +} + +func TestRegisterGrpcServicesIncludesTheExtension(t *testing.T) { + pluginSvc, err := New(Options{}) + if err != nil { + t.Fatalf("New: %v", err) + } + defer pluginSvc.Shutdown() + ext := &recordingExtension{} + pluginSvc.schedulerExtension = ext + + server := grpc.NewServer() + pluginSvc.RegisterGrpcServices(server) + if _, served := server.GetServiceInfo()[plugin_pb.PluginControlService_ServiceDesc.ServiceName]; !served { + t.Fatal("the worker stream service is not registered") + } + if ext.registered != 1 { + t.Fatalf("extension asked to register %d times, want once", ext.registered) + } +}