client.go 5.2 KB
Newer Older
D
dongzhihong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15 16 17
package master

import (
H
Helin Wang 已提交
18
	"os"
19
	"sync"
20
	"time"
21 22

	"github.com/PaddlePaddle/Paddle/go/connection"
H
Helin Wang 已提交
23
	"github.com/PaddlePaddle/recordio"
24
	"github.com/coreos/etcd/clientv3"
H
Helin Wang 已提交
25
	log "github.com/sirupsen/logrus"
26 27 28 29
)

// Client is the client of the master server.
type Client struct {
30 31 32
	conn       *connection.Conn
	ch         chan record
	initChOnce sync.Once
G
gongweibao 已提交
33 34 35 36 37
}

type record struct {
	r   []byte
	err error
38 39
}

40
// WithBuffer sets the client to buffer the training record.
41 42 43
//
// bufSize is the record buffer size. NextRecord will read from this
// buffer.
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
func WithBuffer(bufSize int) func(*Client) error {
	return func(c *Client) error {
		if bufSize <= 0 {
			return nil
		}

		c.initChOnce.Do(func() {
			c.ch = make(chan record, bufSize)
			go c.getRecords()
		})
		return nil
	}
}

// WithAddr sets the client to use fixed master address.
func WithAddr(addr string) func(c *Client) error {
	return func(c *Client) error {
		ch := make(chan string, 1)
		ch <- addr
		go c.monitorMaster(ch)
		return nil
	}
}

// WithEtcd sets the client to use etcd for master discovery.
func WithEtcd(endpoints []string, timeout time.Duration) func(*Client) error {
	return func(c *Client) error {
		cli, err := clientv3.New(clientv3.Config{
			Endpoints:   endpoints,
			DialTimeout: timeout,
		})
		if err != nil {
			return err
		}

		ch := make(chan string, 1)
		a, err := GetKey(cli, DefaultAddrPath, timeout)
		if err != nil {
			return err
		}

		if a != "" {
			// Master is registered, send to the master address
			// channel.
			ch <- a
		}

		go watchKey(cli, DefaultAddrPath, ch)
		go c.monitorMaster(ch)
		return nil
	}
}

// NewClient creates a new Client.
func NewClient(opts ...func(*Client) error) (*Client, error) {
99 100
	c := &Client{}
	c.conn = connection.New()
101 102 103 104 105 106 107 108 109 110

	for _, opt := range opts {
		err := opt(c)
		if err != nil {
			return nil, err
		}

	}

	return c, nil
111 112
}

H
Helin Wang 已提交
113 114 115 116
func (c *Client) getRecords() {
	for {
		t, err := c.getTask()
		if err != nil {
117 118
			log.Errorf("Get task failed, sleep 3 seconds and continue, %s", err)
			time.Sleep(3 * time.Second)
H
Helin Wang 已提交
119 120 121 122 123 124
			continue
		}

		for _, chunk := range t.Chunks {
			f, err := os.Open(chunk.Path)
			if err != nil {
H
Helin Wang 已提交
125
				log.Errorln(err)
H
Helin Wang 已提交
126 127 128 129 130
				continue
			}

			s := recordio.NewRangeScanner(f, &chunk.Index, -1, -1)
			for s.Scan() {
G
gongweibao 已提交
131
				c.ch <- record{s.Record(), nil}
H
Helin Wang 已提交
132 133
			}

134
			if s.Err() != nil {
G
gongweibao 已提交
135
				c.ch <- record{nil, s.Err()}
H
Helin Wang 已提交
136
				log.Errorln(err, chunk.Path)
137 138
			}

H
Helin Wang 已提交
139 140
			err = f.Close()
			if err != nil {
H
Helin Wang 已提交
141
				log.Errorln(err)
H
Helin Wang 已提交
142 143
			}
		}
144 145 146 147

		// We treat a task as finished whenever the last data
		// instance of the task is read. This is not exactly
		// correct, but a reasonable approximation.
H
Helin Wang 已提交
148 149 150 151
		err = c.taskFinished(t.Meta.ID)
		if err != nil {
			log.Errorln(err)
		}
H
Helin Wang 已提交
152 153 154
	}
}

155
func (c *Client) monitorMaster(addrCh <-chan string) {
156
	lastMaster := ""
157
	for curMaster := range addrCh {
H
Helin Wang 已提交
158
		// connect to the new address once address changed.
159 160 161 162
		if curMaster != lastMaster {
			if curMaster == "" {
				err := c.conn.Close()
				if err != nil {
H
Helin Wang 已提交
163
					log.Errorln(err)
164 165 166 167
				}
			} else {
				err := c.conn.Connect(curMaster)
				if err != nil {
H
Helin Wang 已提交
168
					log.Errorln(err)
169 170 171 172 173 174 175 176 177 178 179 180

					// connect to addr failed, set
					// to last known addr in order
					// to retry next time.
					curMaster = lastMaster
				}
			}
		}
		lastMaster = curMaster
	}
}

181 182 183 184 185 186 187 188
// SetDataset set dataset for the master server to dispatch.
//
// SetDataset can be call multiple times from different nodes. But
// only the first call will be honored.
func (c *Client) SetDataset(globPaths []string) error {
	return c.conn.Call("Service.SetDataset", globPaths, nil)
}

H
Helin Wang 已提交
189 190
// getTask gets a new task from the master server.
func (c *Client) getTask() (Task, error) {
191
	var t Task
192
	err := c.conn.Call("Service.GetTask", 0, &t)
193 194 195 196
	return t, err
}

// TaskFinished tells the master server a task is finished.
H
Helin Wang 已提交
197
func (c *Client) taskFinished(taskID int) error {
198
	return c.conn.Call("Service.TaskFinished", taskID, nil)
199
}
H
Helin Wang 已提交
200

G
gongweibao 已提交
201
// TaskFailed tell the master server as task is failed.
G
gongweibao 已提交
202
func (c *Client) taskFailed(meta TaskMeta) error {
G
gongweibao 已提交
203
	return c.conn.Call("Service.TaskFailed", meta, nil)
G
gongweibao 已提交
204 205
}

H
Helin Wang 已提交
206 207
// NextRecord returns next record in the dataset.
//
H
Helin Wang 已提交
208
// NextRecord will block until the next record is available. It is
H
Helin Wang 已提交
209
// thread-safe.
G
gongweibao 已提交
210
func (c *Client) NextRecord() ([]byte, error) {
211 212 213 214 215 216
	c.initChOnce.Do(func() {
		// initialize with in case WithBuffer is not used.
		c.ch = make(chan record, 0)
		go c.getRecords()
	})

G
gongweibao 已提交
217 218
	r := <-c.ch
	return r.r, r.err
H
Helin Wang 已提交
219
}
220 221 222 223 224 225 226 227

// RequestSaveModel requests the master server to approve the caller
// to save the model.
func (c *Client) RequestSaveModel(trainerID string, blockDur time.Duration) (bool, error) {
	var need bool
	err := c.conn.Call("Service.RequestSaveModel", SaveModelRequest{TrainerID: trainerID, BlockDur: blockDur}, &need)
	return need, err
}