service.go 6.8 KB
Newer Older
1 2 3 4
package master

import (
	"errors"
5 6
	"os"
	"path/filepath"
7 8 9
	"sync"
	"time"

H
Helin Wang 已提交
10 11
	log "github.com/sirupsen/logrus"

12
	"github.com/PaddlePaddle/recordio"
13 14 15 16
)

// Service is the master server service.
type Service struct {
17 18 19 20
	chunksPerTask int
	timeoutDur    time.Duration
	timeoutMax    int
	ready         chan struct{}
21 22

	mu         sync.Mutex
H
Helin Wang 已提交
23
	initDone   bool
24 25 26 27 28 29 30 31 32
	taskQueues taskQueues
}

// Recover recovers service state from etcd.
func Recover() (*Service, error) {
	// TODO(helin): recover from snapshot state from etcd.
	return nil, nil
}

H
Helin Wang 已提交
33
func partition(chunks []Chunk, chunksPerTask int) []taskEntry {
34
	id := 0
H
Helin Wang 已提交
35 36
	if chunksPerTask <= 0 {
		chunksPerTask = 1
37 38 39 40 41
	}

	var result []taskEntry
	var cur taskEntry
	for i, c := range chunks {
H
Helin Wang 已提交
42
		if i%chunksPerTask == 0 && len(cur.Task.Chunks) > 0 {
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
			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.
61
func NewService(chunksPerTask int, timeoutDur time.Duration, timeoutMax int) *Service {
62
	s := &Service{}
63
	s.chunksPerTask = chunksPerTask
64 65 66 67
	s.timeoutDur = timeoutDur
	s.timeoutMax = timeoutMax
	s.taskQueues = taskQueues{}
	s.taskQueues.Pending = make(map[int]taskEntry)
68
	s.ready = make(chan struct{})
H
Helin Wang 已提交
69
	return s
70 71 72 73 74
}

// Chunk is a chunk of data consisted of several data instances.
type Chunk struct {
	Path  string
75
	Index recordio.Index // chunk index
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
}

// Task is the basic unit of data instances assigned to trainers.
type Task struct {
	ID     int
	Chunks []Chunk
}

type taskEntry struct {
	Epoch      int
	NumTimeout int
	Task       Task
}

type taskQueues struct {
	Todo    []taskEntry
	Pending map[int]taskEntry // map from task ID to task entry
	Done    []taskEntry
	Failed  []Task
}

// *must* be called with s.mu being held.
func (s *Service) snapshot() error {
	// TODO(helin): snapshot state on etcd.
	return nil
}

H
Helin Wang 已提交
103
func readChunks(globPaths []string) ([]Chunk, error) {
104 105 106 107 108 109
	var chunks []Chunk
	var paths []string

	for _, s := range globPaths {
		match, err := filepath.Glob(s)
		if err != nil {
H
Helin Wang 已提交
110
			return nil, err
111 112 113 114 115
		}
		paths = append(paths, match...)
	}

	if len(paths) == 0 {
H
Helin Wang 已提交
116
		return nil, errors.New("no valid dataset specified")
117 118 119 120 121
	}

	for _, path := range paths {
		f, err := os.Open(path)
		if err != nil {
H
Helin Wang 已提交
122
			return nil, err
123 124 125 126
		}

		index, err := recordio.LoadIndex(f)
		if err != nil {
H
Helin Wang 已提交
127
			return nil, err
128 129 130
		}
		err = f.Close()
		if err != nil {
H
Helin Wang 已提交
131
			return nil, err
132 133 134 135 136 137 138 139 140 141 142 143
		}

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

H
Helin Wang 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
	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 已提交
165
	chunks, err := readChunks(globPaths)
H
Helin Wang 已提交
166 167 168 169
	if err != nil {
		return err
	}

170 171
	s.taskQueues.Todo = partition(chunks, s.chunksPerTask)

H
Helin Wang 已提交
172
	err = s.snapshot()
173
	if err != nil {
H
Helin Wang 已提交
174
		log.Errorln(err)
175 176 177 178
		return err
	}

	close(s.ready)
H
Helin Wang 已提交
179
	s.initDone = true
180 181 182
	return nil
}

H
Helin Wang 已提交
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
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
		}

		if t.Epoch != epoch {
			// new epoch, task launched after the
			// schedule of this timeout check.
			return
		}

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

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

		t.NumTimeout++
		if t.NumTimeout > s.timeoutMax {
H
Helin Wang 已提交
210
			log.Warningf("Task %v timed out %d times, discard.\n", t.Task, t.NumTimeout)
H
Helin Wang 已提交
211 212 213 214
			s.taskQueues.Failed = append(s.taskQueues.Failed, t.Task)
			return
		}

H
Helin Wang 已提交
215
		log.Warningf("Task %v timed out %d times, retry.\n", t.Task, t.NumTimeout)
H
Helin Wang 已提交
216 217 218 219
		s.taskQueues.Todo = append(s.taskQueues.Todo, t)
	}
}

H
Helin Wang 已提交
220 221 222 223 224 225 226 227 228 229
// 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),
	}
}

230 231
// GetTask gets a new task from the service.
func (s *Service) GetTask(dummy int, task *Task) error {
232 233 234 235
	select {
	case <-s.ready:
	}

236 237 238 239
	s.mu.Lock()
	defer s.mu.Unlock()

	if len(s.taskQueues.Todo) == 0 {
240 241
		if len(s.taskQueues.Done) == 0 {
			if len(s.taskQueues.Pending) == 0 {
H
Helin Wang 已提交
242
				err := errors.New("all task failed")
H
Helin Wang 已提交
243
				log.WithFields(s.logFields()).Warningln("All tasks failed.")
H
Helin Wang 已提交
244
				return err
245 246 247 248 249
			}

			// TODO(helin): client need to retry in this
			// error case. Gotcha: RPC client can't
			// compare returned error with predefined
H
Helin Wang 已提交
250 251 252 253 254
			// 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 已提交
255
			err := errors.New("no more available task")
H
Helin Wang 已提交
256
			log.WithFields(s.logFields()).Warningln("No more available task.")
H
Helin Wang 已提交
257
			return err
258 259
		}
		s.taskQueues.Todo = s.taskQueues.Done
H
Helin Wang 已提交
260
		s.taskQueues.Done = nil
H
Helin Wang 已提交
261
		log.WithFields(s.logFields()).Infoln("No more todo task, but trainer is requesting task to do. Move all done task to todo.")
262 263 264 265 266 267 268 269 270 271 272
	}

	t := s.taskQueues.Todo[0]
	t.Epoch++
	s.taskQueues.Todo = s.taskQueues.Todo[1:]
	s.taskQueues.Pending[t.Task.ID] = t
	err := s.snapshot()
	if err != nil {
		return err
	}

273
	*task = t.Task
H
Helin Wang 已提交
274
	log.WithFields(s.logFields()).Infof("Task #%d dispatched.", task.ID)
275

H
Helin Wang 已提交
276
	time.AfterFunc(s.timeoutDur, s.checkTimeoutFunc(t.Task.ID, t.Epoch))
277 278 279 280 281
	return nil
}

// TaskFinished tell the service that a task is finished.
func (s *Service) TaskFinished(taskID int, dummy *int) error {
282 283 284 285
	select {
	case <-s.ready:
	}

286 287 288 289 290
	s.mu.Lock()
	defer s.mu.Unlock()

	t, ok := s.taskQueues.Pending[taskID]
	if !ok {
H
Helin Wang 已提交
291
		err := errors.New("pending task not found")
H
Helin Wang 已提交
292
		log.WithFields(s.logFields()).Warningln("Pending task #%d not found.", taskID)
H
Helin Wang 已提交
293
		return err
294 295 296 297 298 299
	}

	// task finished, reset timeout
	t.NumTimeout = 0
	s.taskQueues.Done = append(s.taskQueues.Done, t)
	delete(s.taskQueues.Pending, taskID)
300

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

H
Helin Wang 已提交
303
	if len(s.taskQueues.Pending) == 0 && len(s.taskQueues.Todo) == 0 {
H
Helin Wang 已提交
304
		log.WithFields(s.logFields()).Infoln("No more todo and pending task, start a new pass.")
305
		s.taskQueues.Todo = append(s.taskQueues.Todo, s.taskQueues.Done...)
306 307 308
		s.taskQueues.Done = nil
	}

H
Helin Wang 已提交
309 310 311 312 313
	err := s.snapshot()
	if err != nil {
		log.Errorln(err)
	}
	return err
314
}