aboutsummaryrefslogtreecommitdiff
path: root/weed/worker/registry.go
blob: 0b40ddec4b52116d544ba0d0b0f8268834d4a663 (plain)
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package worker

import (
	"fmt"
	"sync"
	"time"

	"github.com/seaweedfs/seaweedfs/weed/worker/types"
)

// Registry manages workers and their statistics
type Registry struct {
	workers map[string]*types.WorkerData
	stats   *types.RegistryStats
	mutex   sync.RWMutex
}

// NewRegistry creates a new worker registry
func NewRegistry() *Registry {
	return &Registry{
		workers: make(map[string]*types.WorkerData),
		stats: &types.RegistryStats{
			TotalWorkers:   0,
			ActiveWorkers:  0,
			BusyWorkers:    0,
			IdleWorkers:    0,
			TotalTasks:     0,
			CompletedTasks: 0,
			FailedTasks:    0,
			StartTime:      time.Now(),
		},
	}
}

// RegisterWorker registers a new worker
func (r *Registry) RegisterWorker(worker *types.WorkerData) error {
	r.mutex.Lock()
	defer r.mutex.Unlock()

	if _, exists := r.workers[worker.ID]; exists {
		return fmt.Errorf("worker %s already registered", worker.ID)
	}

	r.workers[worker.ID] = worker
	r.updateStats()
	return nil
}

// UnregisterWorker removes a worker from the registry
func (r *Registry) UnregisterWorker(workerID string) error {
	r.mutex.Lock()
	defer r.mutex.Unlock()

	if _, exists := r.workers[workerID]; !exists {
		return fmt.Errorf("worker %s not found", workerID)
	}

	delete(r.workers, workerID)
	r.updateStats()
	return nil
}

// GetWorker returns a worker by ID
func (r *Registry) GetWorker(workerID string) (*types.WorkerData, bool) {
	r.mutex.RLock()
	defer r.mutex.RUnlock()

	worker, exists := r.workers[workerID]
	return worker, exists
}

// ListWorkers returns all registered workers
func (r *Registry) ListWorkers() []*types.WorkerData {
	r.mutex.RLock()
	defer r.mutex.RUnlock()

	workers := make([]*types.WorkerData, 0, len(r.workers))
	for _, worker := range r.workers {
		workers = append(workers, worker)
	}
	return workers
}

// GetWorkersByCapability returns workers that support a specific capability
func (r *Registry) GetWorkersByCapability(capability types.TaskType) []*types.WorkerData {
	r.mutex.RLock()
	defer r.mutex.RUnlock()

	var workers []*types.WorkerData
	for _, worker := range r.workers {
		for _, cap := range worker.Capabilities {
			if cap == capability {
				workers = append(workers, worker)
				break
			}
		}
	}
	return workers
}

// GetAvailableWorkers returns workers that are available for new tasks
func (r *Registry) GetAvailableWorkers() []*types.WorkerData {
	r.mutex.RLock()
	defer r.mutex.RUnlock()

	var workers []*types.WorkerData
	for _, worker := range r.workers {
		if worker.Status == "active" && worker.CurrentLoad < worker.MaxConcurrent {
			workers = append(workers, worker)
		}
	}
	return workers
}

// GetBestWorkerForTask returns the best worker for a specific task
func (r *Registry) GetBestWorkerForTask(taskType types.TaskType) *types.WorkerData {
	r.mutex.RLock()
	defer r.mutex.RUnlock()

	var bestWorker *types.WorkerData
	var bestScore float64

	for _, worker := range r.workers {
		// Check if worker supports this task type
		supportsTask := false
		for _, cap := range worker.Capabilities {
			if cap == taskType {
				supportsTask = true
				break
			}
		}

		if !supportsTask {
			continue
		}

		// Check if worker is available
		if worker.Status != "active" || worker.CurrentLoad >= worker.MaxConcurrent {
			continue
		}

		// Calculate score based on current load and capacity
		score := float64(worker.MaxConcurrent-worker.CurrentLoad) / float64(worker.MaxConcurrent)
		if bestWorker == nil || score > bestScore {
			bestWorker = worker
			bestScore = score
		}
	}

	return bestWorker
}

// UpdateWorkerHeartbeat updates the last heartbeat time for a worker
func (r *Registry) UpdateWorkerHeartbeat(workerID string) error {
	r.mutex.Lock()
	defer r.mutex.Unlock()

	worker, exists := r.workers[workerID]
	if !exists {
		return fmt.Errorf("worker %s not found", workerID)
	}

	worker.LastHeartbeat = time.Now()
	return nil
}

// UpdateWorkerLoad updates the current load for a worker
func (r *Registry) UpdateWorkerLoad(workerID string, load int) error {
	r.mutex.Lock()
	defer r.mutex.Unlock()

	worker, exists := r.workers[workerID]
	if !exists {
		return fmt.Errorf("worker %s not found", workerID)
	}

	worker.CurrentLoad = load
	if load >= worker.MaxConcurrent {
		worker.Status = "busy"
	} else {
		worker.Status = "active"
	}

	r.updateStats()
	return nil
}

// UpdateWorkerStatus updates the status of a worker
func (r *Registry) UpdateWorkerStatus(workerID string, status string) error {
	r.mutex.Lock()
	defer r.mutex.Unlock()

	worker, exists := r.workers[workerID]
	if !exists {
		return fmt.Errorf("worker %s not found", workerID)
	}

	worker.Status = status
	r.updateStats()
	return nil
}

// CleanupStaleWorkers removes workers that haven't sent heartbeats recently
func (r *Registry) CleanupStaleWorkers(timeout time.Duration) int {
	r.mutex.Lock()
	defer r.mutex.Unlock()

	var removedCount int
	cutoff := time.Now().Add(-timeout)

	for workerID, worker := range r.workers {
		if worker.LastHeartbeat.Before(cutoff) {
			delete(r.workers, workerID)
			removedCount++
		}
	}

	if removedCount > 0 {
		r.updateStats()
	}

	return removedCount
}

// GetStats returns current registry statistics
func (r *Registry) GetStats() *types.RegistryStats {
	r.mutex.RLock()
	defer r.mutex.RUnlock()

	// Create a copy of the stats to avoid race conditions
	stats := *r.stats
	return &stats
}

// updateStats updates the registry statistics (must be called with lock held)
func (r *Registry) updateStats() {
	r.stats.TotalWorkers = len(r.workers)
	r.stats.ActiveWorkers = 0
	r.stats.BusyWorkers = 0
	r.stats.IdleWorkers = 0

	for _, worker := range r.workers {
		switch worker.Status {
		case "active":
			if worker.CurrentLoad > 0 {
				r.stats.ActiveWorkers++
			} else {
				r.stats.IdleWorkers++
			}
		case "busy":
			r.stats.BusyWorkers++
		}
	}

	r.stats.Uptime = time.Since(r.stats.StartTime)
	r.stats.LastUpdated = time.Now()
}

// GetTaskCapabilities returns all task capabilities available in the registry
func (r *Registry) GetTaskCapabilities() []types.TaskType {
	r.mutex.RLock()
	defer r.mutex.RUnlock()

	capabilitySet := make(map[types.TaskType]bool)
	for _, worker := range r.workers {
		for _, cap := range worker.Capabilities {
			capabilitySet[cap] = true
		}
	}

	var capabilities []types.TaskType
	for cap := range capabilitySet {
		capabilities = append(capabilities, cap)
	}

	return capabilities
}

// GetWorkersByStatus returns workers filtered by status
func (r *Registry) GetWorkersByStatus(status string) []*types.WorkerData {
	r.mutex.RLock()
	defer r.mutex.RUnlock()

	var workers []*types.WorkerData
	for _, worker := range r.workers {
		if worker.Status == status {
			workers = append(workers, worker)
		}
	}
	return workers
}

// GetWorkerCount returns the total number of registered workers
func (r *Registry) GetWorkerCount() int {
	r.mutex.RLock()
	defer r.mutex.RUnlock()
	return len(r.workers)
}

// GetWorkerIDs returns all worker IDs
func (r *Registry) GetWorkerIDs() []string {
	r.mutex.RLock()
	defer r.mutex.RUnlock()

	ids := make([]string, 0, len(r.workers))
	for id := range r.workers {
		ids = append(ids, id)
	}
	return ids
}

// GetWorkerSummary returns a summary of all workers
func (r *Registry) GetWorkerSummary() *types.WorkerSummary {
	r.mutex.RLock()
	defer r.mutex.RUnlock()

	summary := &types.WorkerSummary{
		TotalWorkers: len(r.workers),
		ByStatus:     make(map[string]int),
		ByCapability: make(map[types.TaskType]int),
		TotalLoad:    0,
		MaxCapacity:  0,
	}

	for _, worker := range r.workers {
		summary.ByStatus[worker.Status]++
		summary.TotalLoad += worker.CurrentLoad
		summary.MaxCapacity += worker.MaxConcurrent

		for _, cap := range worker.Capabilities {
			summary.ByCapability[cap]++
		}
	}

	return summary
}

// Default global registry instance
var defaultRegistry *Registry
var registryOnce sync.Once

// GetDefaultRegistry returns the default global registry
func GetDefaultRegistry() *Registry {
	registryOnce.Do(func() {
		defaultRegistry = NewRegistry()
	})
	return defaultRegistry
}