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

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

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

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

	mu         sync.Mutex
H
Helin Wang 已提交
22
	initDone   bool
23 24 25 26 27 28 29 30 31
	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 已提交
32
func partition(chunks []Chunk, chunksPerTask int) []taskEntry {
33
	id := 0
H
Helin Wang 已提交
34 35
	if chunksPerTask <= 0 {
		chunksPerTask = 1
36 37 38 39 40
	}

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

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

// 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 已提交
102
func getChunks(globPaths []string) ([]Chunk, error) {
103 104 105 106 107 108
	var chunks []Chunk
	var paths []string

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

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

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

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

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

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

	chunks, err := getChunks(globPaths)
	if err != nil {
		return err
	}

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

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

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

181 182
// GetTask gets a new task from the service.
func (s *Service) GetTask(dummy int, task *Task) error {
183 184 185 186
	select {
	case <-s.ready:
	}

187 188 189 190
	s.mu.Lock()
	defer s.mu.Unlock()

	if len(s.taskQueues.Todo) == 0 {
191 192 193 194 195 196 197 198
		if len(s.taskQueues.Done) == 0 {
			if len(s.taskQueues.Pending) == 0 {
				return errors.New("all task failed")
			}

			// TODO(helin): client need to retry in this
			// error case. Gotcha: RPC client can't
			// compare returned error with predefined
H
Helin Wang 已提交
199
			// errors like io.EOF. Because interface don't
200 201 202 203 204 205
			// have same dynamic value when in different
			// process.
			return errors.New("no more available task")
		}
		s.taskQueues.Todo = s.taskQueues.Done
		s.taskQueues.Todo = nil
206 207 208 209 210 211 212 213 214 215 216
	}

	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
	}

217 218
	*task = t.Task

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
	time.AfterFunc(s.timeoutDur, func(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.Println(err)
				}
			}()

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

			t.NumTimeout++
			if t.NumTimeout > s.timeoutMax {
				s.taskQueues.Failed = append(s.taskQueues.Failed, t.Task)
				return
			}

			s.taskQueues.Todo = append(s.taskQueues.Todo, t)
		}
	}(t.Task.ID, t.Epoch))
	return nil
}

// TaskFinished tell the service that a task is finished.
func (s *Service) TaskFinished(taskID int, dummy *int) error {
258 259 260 261
	select {
	case <-s.ready:
	}

262 263 264 265 266
	s.mu.Lock()
	defer s.mu.Unlock()

	t, ok := s.taskQueues.Pending[taskID]
	if !ok {
267
		return errors.New("pending task not found")
268 269 270 271 272 273
	}

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

275 276
	if len(s.taskQueues.Pending) == 0 {
		s.taskQueues.Todo = append(s.taskQueues.Todo, s.taskQueues.Done...)
277 278 279
		s.taskQueues.Done = nil
	}

280 281
	return s.snapshot()
}