service.go 9.1 KB
Newer Older
1 2 3
package master

import (
4 5 6
	"bytes"
	"compress/gzip"
	"encoding/gob"
7
	"errors"
8 9
	"os"
	"path/filepath"
10 11 12
	"sync"
	"time"

H
Helin Wang 已提交
13 14
	log "github.com/sirupsen/logrus"

15
	"github.com/PaddlePaddle/recordio"
16 17
)

18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
const (
	dialTimeout = 5 * time.Second
)

// Store is the interface for save and load the master state.
type Store interface {
	Save([]byte) error
	Load() ([]byte, error)
}

// Chunk is a chunk of data consisted of several data instances.
type Chunk struct {
	Path  string
	Index recordio.Index // chunk index
}

// Task is the basic unit of data instances assigned to trainers.
type Task struct {
	ID     int
G
gongweibao 已提交
37
	Epoch  int
38 39 40 41 42 43
	Chunks []Chunk
}

type taskEntry struct {
	NumTimeout int
	Task       Task
G
gongweibao 已提交
44
	NumFailed  int
45 46 47 48 49 50
}

type taskQueues struct {
	Todo    []taskEntry
	Pending map[int]taskEntry // map from task ID to task entry
	Done    []taskEntry
G
gongweibao 已提交
51
	Failed  []taskEntry
52 53
}

54 55
// Service is the master server service.
type Service struct {
G
gongweibao 已提交
56 57 58 59 60
	chunksPerTask    int
	timeoutDur       time.Duration
	failortimeoutMax int
	ready            chan struct{}
	store            Store
61 62

	mu         sync.Mutex
H
Helin Wang 已提交
63
	initDone   bool
64 65 66
	taskQueues taskQueues
}

H
Helin Wang 已提交
67
func partition(chunks []Chunk, chunksPerTask int) []taskEntry {
68
	id := 0
H
Helin Wang 已提交
69 70
	if chunksPerTask <= 0 {
		chunksPerTask = 1
71 72 73 74 75
	}

	var result []taskEntry
	var cur taskEntry
	for i, c := range chunks {
H
Helin Wang 已提交
76
		if i%chunksPerTask == 0 && len(cur.Task.Chunks) > 0 {
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
			cur.Task.ID = id
			id++
			result = append(result, cur)
			cur.Task.Chunks = nil
		}

		cur.Task.Chunks = append(cur.Task.Chunks, c)
	}

	if len(cur.Task.Chunks) > 0 {
		cur.Task.ID = id
		result = append(result, cur)
	}

	return result
}

// NewService creates a new service.
G
gongweibao 已提交
95
func NewService(store Store, chunksPerTask int, timeoutDur time.Duration, failortimeoutMax int) (*Service, error) {
96
	s := &Service{}
97
	s.chunksPerTask = chunksPerTask
98
	s.timeoutDur = timeoutDur
G
gongweibao 已提交
99
	s.failortimeoutMax = failortimeoutMax
100 101
	s.taskQueues = taskQueues{}
	s.taskQueues.Pending = make(map[int]taskEntry)
102
	s.ready = make(chan struct{})
103 104 105 106 107
	s.store = store
	recovered, err := s.recover()
	if err != nil {
		return nil, err
	}
108

109 110 111 112 113
	if recovered {
		// Recovered. Now the state is already initialized,
		// and the master is ready.
		s.initDone = true
		close(s.ready)
114
		log.Info("Master recovered from saved state.")
115
	}
116

117
	return s, nil
118 119
}

120 121 122 123 124 125
// recover recovers service state from etcd.
func (s *Service) recover() (bool, error) {
	state, err := s.store.Load()
	if err != nil {
		return false, err
	}
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
	if state == nil {
		log.Infoln("No state exists, not recovered.")
		return false, nil
	}

	log.Infof("Loaded snapshot of size: %d bytes.", len(state))
	gr, err := gzip.NewReader(bytes.NewReader(state))
	if err != nil {
		return false, err
	}

	dec := gob.NewDecoder(gr)
	var tqs taskQueues
	err = dec.Decode(&tqs)
	if err != nil {
		return false, err
	}

	err = gr.Close()
	if err != nil {
		// Only close failed, recover actually succeed, so
		// just log error.
		log.Errorln(err)
	}

	s.taskQueues = tqs
	return true, nil
154 155
}

156
// snapshot *must* be called with s.mu being held.
157
func (s *Service) snapshot() error {
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
	// TOOD(helin): etcd request has a size limit, so the snapshot
	// size is limited by the max request size. We should either
	// divide the snapshot into smaller chunks and save under
	// different keys, or configure the request size to be big
	// enough:
	// https://github.com/coreos/etcd/blob/2f84f3d8d8ed8f9537ab6ffa44a3a1c7eddfa9b1/embed/config.go#L44
	var buf bytes.Buffer
	gw := gzip.NewWriter(&buf)
	enc := gob.NewEncoder(gw)
	err := enc.Encode(s.taskQueues)
	if err != nil {
		return err
	}
	err = gw.Close()
	if err != nil {
		return err
	}

	state := buf.Bytes()
	log.Infof("Saving snapshot of size: %d bytes.", len(state))
	return s.store.Save(state)
179 180
}

H
Helin Wang 已提交
181
func readChunks(globPaths []string) ([]Chunk, error) {
182 183 184 185 186 187
	var chunks []Chunk
	var paths []string

	for _, s := range globPaths {
		match, err := filepath.Glob(s)
		if err != nil {
H
Helin Wang 已提交
188
			return nil, err
189 190 191 192 193
		}
		paths = append(paths, match...)
	}

	if len(paths) == 0 {
H
Helin Wang 已提交
194
		return nil, errors.New("no valid dataset specified")
195 196 197 198 199
	}

	for _, path := range paths {
		f, err := os.Open(path)
		if err != nil {
H
Helin Wang 已提交
200
			return nil, err
201 202 203 204
		}

		index, err := recordio.LoadIndex(f)
		if err != nil {
H
Helin Wang 已提交
205
			return nil, err
206 207 208
		}
		err = f.Close()
		if err != nil {
H
Helin Wang 已提交
209
			return nil, err
210 211 212 213 214 215 216 217 218 219 220 221
		}

		count := index.NumChunks()
		for i := 0; i < count; i++ {
			chunk := Chunk{
				Path:  path,
				Index: *index.ChunkIndex(i),
			}
			chunks = append(chunks, chunk)
		}
	}

H
Helin Wang 已提交
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
	return chunks, nil
}

// SetDataset sets dataset to dispatch for the master server.
//
// SetDataset can be call multiple times. But only the first call will
// be honored.
func (s *Service) SetDataset(globPaths []string, dummy *int) error {
	if len(globPaths) == 0 {
		return errors.New("no dataset specified")
	}

	s.mu.Lock()
	defer s.mu.Unlock()
	if s.initDone {
		// Already initialized. All trainer will call
		// SetDataset, but we only handle the first one. Treat
		// other calls as successful but do nothing.
		return nil
	}

H
Helin Wang 已提交
243
	chunks, err := readChunks(globPaths)
H
Helin Wang 已提交
244 245 246 247
	if err != nil {
		return err
	}

248 249
	s.taskQueues.Todo = partition(chunks, s.chunksPerTask)

H
Helin Wang 已提交
250
	err = s.snapshot()
251
	if err != nil {
H
Helin Wang 已提交
252
		log.Errorln(err)
253 254 255 256
		return err
	}

	close(s.ready)
H
Helin Wang 已提交
257
	s.initDone = true
258 259 260
	return nil
}

G
gongweibao 已提交
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
func (s *Service) checkTaskStatus(t taskEntry, epoch int) {
	if t.Task.Epoch != epoch {
		// new epoch, task launched after the
		// schedule of this timeout check or failed status report.
		return
	}

	defer func() {
		err := s.snapshot()
		if err != nil {
			log.Errorln(err)
		}
	}()

	delete(s.taskQueues.Pending, t.Task.ID)

	t.NumTimeout++
G
gongweibao 已提交
278 279
	if t.NumTimeout+t.NumFailed > s.failortimeoutMax {
		log.Warningf("Task %v timed out %d times and failed %d times, discard.", t.Task, t.NumTimeout, t.NumFailed)
G
gongweibao 已提交
280 281 282 283
		s.taskQueues.Failed = append(s.taskQueues.Failed, t)
		return
	}

G
gongweibao 已提交
284
	log.Warningf("Task %v timed out %d times and failed %d times, discard.", t.Task, t.NumTimeout, t.NumFailed)
G
gongweibao 已提交
285 286 287 288
	s.taskQueues.Todo = append(s.taskQueues.Todo, t)
	return
}

H
Helin Wang 已提交
289 290 291 292 293 294 295 296 297 298
func (s *Service) checkTimeoutFunc(taskID int, epoch int) func() {
	return func() {
		s.mu.Lock()
		defer s.mu.Unlock()

		t, ok := s.taskQueues.Pending[taskID]
		if !ok {
			return
		}

G
gongweibao 已提交
299
		s.checkTaskStatus(t, epoch)
H
Helin Wang 已提交
300 301 302
	}
}

H
Helin Wang 已提交
303 304 305 306 307 308 309 310 311 312
// must be called with lock held.
func (s *Service) logFields() log.Fields {
	return log.Fields{
		"todoLen":    len(s.taskQueues.Todo),
		"pendingLen": len(s.taskQueues.Pending),
		"doneLen":    len(s.taskQueues.Done),
		"failedLen":  len(s.taskQueues.Failed),
	}
}

313 314
// GetTask gets a new task from the service.
func (s *Service) GetTask(dummy int, task *Task) error {
315 316 317 318
	select {
	case <-s.ready:
	}

319 320 321 322
	s.mu.Lock()
	defer s.mu.Unlock()

	if len(s.taskQueues.Todo) == 0 {
323 324
		if len(s.taskQueues.Done) == 0 {
			if len(s.taskQueues.Pending) == 0 {
H
Helin Wang 已提交
325
				err := errors.New("all task failed")
H
Helin Wang 已提交
326
				log.WithFields(s.logFields()).Warningln("All tasks failed.")
H
Helin Wang 已提交
327
				return err
328 329 330 331 332
			}

			// TODO(helin): client need to retry in this
			// error case. Gotcha: RPC client can't
			// compare returned error with predefined
H
Helin Wang 已提交
333 334 335 336 337
			// errors like io.EOF, because the error
			// instance deserialized from RPC is a
			// different instance than the error defined
			// in package. So we need to figure out a way
			// for client to check this error correctly.
H
Helin Wang 已提交
338
			err := errors.New("no more available task")
H
Helin Wang 已提交
339
			log.WithFields(s.logFields()).Warningln("No more available task.")
H
Helin Wang 已提交
340
			return err
341 342
		}
		s.taskQueues.Todo = s.taskQueues.Done
H
Helin Wang 已提交
343
		s.taskQueues.Done = nil
H
Helin Wang 已提交
344
		log.WithFields(s.logFields()).Infoln("No more todo task, but trainer is requesting task to do. Move all done task to todo.")
345 346 347
	}

	t := s.taskQueues.Todo[0]
G
gongweibao 已提交
348
	t.Task.Epoch++
349 350 351 352 353 354 355
	s.taskQueues.Todo = s.taskQueues.Todo[1:]
	s.taskQueues.Pending[t.Task.ID] = t
	err := s.snapshot()
	if err != nil {
		return err
	}

356
	*task = t.Task
G
gongweibao 已提交
357
	log.WithFields(s.logFields()).Infof("Task #%v dispatched.", t)
358

G
gongweibao 已提交
359
	time.AfterFunc(s.timeoutDur, s.checkTimeoutFunc(t.Task.ID, t.Task.Epoch))
360 361 362 363 364
	return nil
}

// TaskFinished tell the service that a task is finished.
func (s *Service) TaskFinished(taskID int, dummy *int) error {
365 366 367 368
	select {
	case <-s.ready:
	}

369 370 371 372 373
	s.mu.Lock()
	defer s.mu.Unlock()

	t, ok := s.taskQueues.Pending[taskID]
	if !ok {
H
Helin Wang 已提交
374
		err := errors.New("pending task not found")
H
Helin Wang 已提交
375
		log.WithFields(s.logFields()).Warningln("Pending task #%d not found.", taskID)
H
Helin Wang 已提交
376
		return err
377 378 379 380
	}

	// task finished, reset timeout
	t.NumTimeout = 0
G
gongweibao 已提交
381
	t.NumFailed = 0
382 383
	s.taskQueues.Done = append(s.taskQueues.Done, t)
	delete(s.taskQueues.Pending, taskID)
384

H
Helin Wang 已提交
385 386
	log.WithFields(s.logFields()).Infof("Task #%d finished.", taskID)

H
Helin Wang 已提交
387
	if len(s.taskQueues.Pending) == 0 && len(s.taskQueues.Todo) == 0 {
H
Helin Wang 已提交
388
		log.WithFields(s.logFields()).Infoln("No more todo and pending task, start a new pass.")
389
		s.taskQueues.Todo = append(s.taskQueues.Todo, s.taskQueues.Done...)
390 391 392
		s.taskQueues.Done = nil
	}

H
Helin Wang 已提交
393 394 395 396 397
	err := s.snapshot()
	if err != nil {
		log.Errorln(err)
	}
	return err
398
}
G
gongweibao 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418

// TaskFailed tell the service that a task is failed.
func (s *Service) TaskFailed(taskID int, epoch int) error {
	select {
	case <-s.ready:
	}

	s.mu.Lock()
	defer s.mu.Unlock()

	t, ok := s.taskQueues.Pending[taskID]
	if !ok {
		err := errors.New("pending task not found")
		log.WithFields(s.logFields()).Warningln("TaskFailed:Pending task #%d not found.", taskID)
		return err
	}

	s.checkTaskStatus(t, epoch)
	return nil
}