File size: 6,556 Bytes
95d599c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | // _ _
// __ _____ __ ___ ___ __ _| |_ ___
// \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
// \ V V / __/ (_| |\ V /| | (_| | || __/
// \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
//
// Copyright © 2016 - 2025 Weaviate B.V. All rights reserved.
//
// CONTACT: hello@weaviate.io
//
package distributedtask
import (
"context"
"encoding/json"
"fmt"
"sync"
"time"
"github.com/jonboulle/clockwork"
"github.com/weaviate/weaviate/cluster/proto/api"
)
// Manager is responsible for managing distributed tasks across the cluster.
type Manager struct {
mu sync.Mutex
tasks map[string]map[string]*Task // namespace -> taskID -> Task
completedTaskTTL time.Duration
clock clockwork.Clock
}
type ManagerParameters struct {
Clock clockwork.Clock
CompletedTaskTTL time.Duration
}
func NewManager(params ManagerParameters) *Manager {
if params.Clock == nil {
params.Clock = clockwork.NewRealClock()
}
return &Manager{
tasks: make(map[string]map[string]*Task),
completedTaskTTL: params.CompletedTaskTTL,
clock: params.Clock,
}
}
func (m *Manager) AddTask(c *api.ApplyRequest, seqNum uint64) error {
var r api.AddDistributedTaskRequest
if err := json.Unmarshal(c.SubCommand, &r); err != nil {
return fmt.Errorf("unmarshal add task request: %w", err)
}
m.mu.Lock()
defer m.mu.Unlock()
task := m.findTaskWithLock(r.Namespace, r.Id)
if task != nil {
if task.Status == TaskStatusStarted {
return fmt.Errorf("task %s/%s is already running with version %d", r.Namespace, r.Id, task.Version)
}
if seqNum <= task.Version {
return fmt.Errorf("task %s/%s is already finished with version %d", r.Namespace, r.Id, task.Version)
}
}
m.setTaskWithLock(&Task{
Namespace: r.Namespace,
TaskDescriptor: TaskDescriptor{ID: r.Id, Version: seqNum},
Payload: r.Payload,
Status: TaskStatusStarted,
StartedAt: time.UnixMilli(r.SubmittedAtUnixMillis),
FinishedNodes: map[string]bool{},
})
return nil
}
func (m *Manager) RecordNodeCompletion(c *api.ApplyRequest, numberOfNodesInTheCluster int) error {
var r api.RecordDistributedTaskNodeCompletionRequest
if err := json.Unmarshal(c.SubCommand, &r); err != nil {
return fmt.Errorf("unmarshal record task node completion request: %w", err)
}
m.mu.Lock()
defer m.mu.Unlock()
task, err := m.findVersionedTaskWithLock(r.Namespace, r.Id, r.Version)
if err != nil {
return err
}
if task.Status != TaskStatusStarted {
return fmt.Errorf("task %s/%s/%d is no longer running", r.Namespace, r.Id, task.Version)
}
if r.Error != nil {
task.Status = TaskStatusFailed
task.Error = *r.Error
task.FinishedAt = time.UnixMilli(r.FinishedAtUnixMillis)
return nil
}
task.FinishedNodes[r.NodeId] = true
if len(task.FinishedNodes) == numberOfNodesInTheCluster {
task.Status = TaskStatusFinished
task.FinishedAt = time.UnixMilli(r.FinishedAtUnixMillis)
return nil
}
return nil
}
func (m *Manager) CancelTask(a *api.ApplyRequest) error {
var r api.CancelDistributedTaskRequest
if err := json.Unmarshal(a.SubCommand, &r); err != nil {
return fmt.Errorf("unmarshal cancel task request: %w", err)
}
m.mu.Lock()
defer m.mu.Unlock()
task, err := m.findVersionedTaskWithLock(r.Namespace, r.Id, r.Version)
if err != nil {
return err
}
if task.Status != TaskStatusStarted {
return fmt.Errorf("task %s/%s/%d is no longer running", r.Namespace, r.Id, task.Version)
}
task.Status = TaskStatusCancelled
task.FinishedAt = time.UnixMilli(r.CancelledAtUnixMillis)
return nil
}
func (m *Manager) CleanUpTask(a *api.ApplyRequest) error {
var r api.CleanUpDistributedTaskRequest
if err := json.Unmarshal(a.SubCommand, &r); err != nil {
return fmt.Errorf("unmarshal clean up task request: %w", err)
}
m.mu.Lock()
defer m.mu.Unlock()
task, err := m.findVersionedTaskWithLock(r.Namespace, r.Id, r.Version)
if err != nil {
return err
}
if task.Status == TaskStatusStarted {
return fmt.Errorf("task %s/%s/%d is still running", r.Namespace, r.Id, task.Version)
}
if m.clock.Since(task.FinishedAt) <= m.completedTaskTTL {
return fmt.Errorf("task %s/%s/%d is too fresh to clean up", r.Namespace, r.Id, task.Version)
}
delete(m.tasks[task.Namespace], task.ID)
return nil
}
func (m *Manager) ListDistributedTasks(_ context.Context) (map[string][]*Task, error) {
m.mu.Lock()
defer m.mu.Unlock()
result := make(map[string][]*Task, len(m.tasks))
for namespace, tasks := range m.tasks {
if len(tasks) == 0 {
continue
}
result[namespace] = make([]*Task, 0, len(tasks))
for _, task := range tasks {
result[namespace] = append(result[namespace], task.Clone())
}
}
return result, nil
}
func (m *Manager) ListDistributedTasksPayload(ctx context.Context) ([]byte, error) {
tasks, err := m.ListDistributedTasks(ctx)
if err != nil {
return nil, fmt.Errorf("list distributed tasks: %w", err)
}
return json.Marshal(&ListDistributedTasksResponse{
Tasks: tasks,
})
}
func (m *Manager) findVersionedTaskWithLock(namespace, taskID string, taskVersion uint64) (*Task, error) {
task := m.findTaskWithLock(namespace, taskID)
if task == nil || task.Version != taskVersion {
return nil, fmt.Errorf("task %s/%s/%d does not exist", namespace, taskID, taskVersion)
}
return task, nil
}
func (m *Manager) findTaskWithLock(namespace, taskID string) *Task {
tasksNamespace, ok := m.tasks[namespace]
if !ok {
return nil
}
task, ok := tasksNamespace[taskID]
if !ok {
return nil
}
return task
}
func (m *Manager) setTaskWithLock(task *Task) {
if _, ok := m.tasks[task.Namespace]; !ok {
m.tasks[task.Namespace] = make(map[string]*Task)
}
m.tasks[task.Namespace][task.ID] = task
}
type snapshot struct {
Tasks map[string][]*Task `json:"tasks,omitempty"`
}
func (m *Manager) Snapshot() ([]byte, error) {
tasks, err := m.ListDistributedTasks(context.Background())
if err != nil {
return nil, fmt.Errorf("list tasks: %w", err)
}
bytes, err := json.Marshal(&snapshot{
Tasks: tasks,
})
if err != nil {
return nil, fmt.Errorf("marshal snapshot: %w", err)
}
return bytes, nil
}
func (m *Manager) Restore(bytes []byte) error {
var s snapshot
if err := json.Unmarshal(bytes, &s); err != nil {
return fmt.Errorf("unmarshal snapshot: %w", err)
}
m.mu.Lock()
defer m.mu.Unlock()
for namespace, tasks := range s.Tasks {
for _, task := range tasks {
if _, ok := m.tasks[namespace]; !ok {
m.tasks[namespace] = make(map[string]*Task)
}
m.tasks[namespace][task.ID] = task
}
}
return nil
}
|