etcd_client.go 6.0 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.

Q
Qiao Longfei 已提交
15 16 17 18
package client

import (
	"context"
19 20
	"errors"
	"fmt"
Q
Qiao Longfei 已提交
21 22 23 24 25 26
	"strconv"
	"strings"
	"time"

	"github.com/PaddlePaddle/Paddle/go/pserver"
	"github.com/coreos/etcd/clientv3"
27
	"github.com/coreos/etcd/clientv3/concurrency"
Q
Qiao Longfei 已提交
28 29 30 31
	log "github.com/sirupsen/logrus"
)

const (
H
Helin Wang 已提交
32
	defaultEtcdTimeout time.Duration = 5 * time.Second
33 34 35 36

	initLockPath = "/init_ps/lock"
	initDonePath = "/init_ps/done"
	initDoneVal  = "1"
Q
Qiao Longfei 已提交
37 38
)

39
// Etcd is used by pserver client that is a part of trainer process.
Q
Qiao Longfei 已提交
40
// TODO:
41 42
// 1. add watcher to watch the change state of pservers.
type Etcd struct {
Q
Qiao Longfei 已提交
43 44 45
	client    *clientv3.Client
	timeout   time.Duration
	endpoints []string
46
	lock      *concurrency.Mutex
Q
Qiao Longfei 已提交
47 48 49
}

// Desired read ps desired number from etcd.
50
func (e *Etcd) Desired() int {
Q
Qiao Longfei 已提交
51 52
	var psDesired int
	for {
53 54
		ctx, cancel := context.WithTimeout(context.Background(), e.timeout)
		resp, err := e.client.Get(ctx, pserver.PsDesired)
Q
Qiao Longfei 已提交
55 56 57
		cancel()
		if err != nil {
			log.Errorf("Get ps dresire number failed! recnnectiong..., %v", err)
58
			time.Sleep(e.timeout)
Q
Qiao Longfei 已提交
59 60 61 62 63 64
			continue
		}

		kvs := resp.Kvs
		if len(kvs) == 0 {
			log.Infoln("Waiting for ps desired registered ...")
65
			time.Sleep(e.timeout)
Q
Qiao Longfei 已提交
66 67 68 69 70
			continue
		}

		psDesired, err = strconv.Atoi(string(resp.Kvs[0].Value))
		if err != nil {
H
Helin Wang 已提交
71
			log.Errorf("psDesired %d invalid %v", psDesired, err)
72
			time.Sleep(e.timeout)
Q
Qiao Longfei 已提交
73 74 75 76 77 78 79 80 81 82
			continue
		}

		log.Debugf("Get psDesired number: %d", psDesired)
		break
	}
	return psDesired
}

// List return the pserver list read from etcd.
83 84
func (e *Etcd) List() []Server {
	psDesired := e.Desired()
Q
Qiao Longfei 已提交
85 86 87 88

	servers := make([]Server, psDesired)
	for {
		for i := 0; i < psDesired; i++ {
89
			ctx, cancel := context.WithTimeout(context.Background(), e.timeout)
Q
Qiao Longfei 已提交
90 91
			psKey := pserver.PsPath + strconv.Itoa(i)
			log.Debugf("checking %s", psKey)
92
			resp, err := e.client.Get(ctx, psKey)
93
			cancel()
Q
Qiao Longfei 已提交
94
			if err != nil {
H
Helin Wang 已提交
95
				log.Infof("Get psKey= %s error, %v", psKey, err)
96
				time.Sleep(e.timeout)
Q
Qiao Longfei 已提交
97 98 99 100 101
				continue
			}
			kvs := resp.Kvs
			if len(kvs) == 0 {
				log.Infof("Waiting for ps addr registered ...")
102
				time.Sleep(e.timeout)
Q
Qiao Longfei 已提交
103 104 105 106 107 108 109
				continue
			}

			psAddr := string(resp.Kvs[0].Value)
			// TODO(Longfei) check the ps address
			if psAddr == "" {
				log.Infof("Get psKey = %s, psAddr is empty", psKey)
110
				time.Sleep(e.timeout)
Q
Qiao Longfei 已提交
111 112
				continue
			}
113
			log.Debugf("got value (%s) for key: %s", psAddr, psKey)
Q
Qiao Longfei 已提交
114 115 116 117 118 119 120 121 122
			servers[i].Index = i
			servers[i].Addr = psAddr
		}
		break
	}
	return servers
}

// NewEtcd create a etcd client to return the state of pserver on etcd.
123
func NewEtcd(endpoints string) *Etcd {
Q
Qiao Longfei 已提交
124 125 126 127 128 129
	ep := strings.Split(endpoints, ",")
	var cli *clientv3.Client
	var err error
	for {
		cli, err = clientv3.New(clientv3.Config{
			Endpoints:   ep,
H
Helin Wang 已提交
130
			DialTimeout: defaultEtcdTimeout,
Q
Qiao Longfei 已提交
131 132 133
		})
		if err != nil {
			log.Errorf("Init etcd connection failed: %v", err)
H
Helin Wang 已提交
134
			time.Sleep(defaultEtcdTimeout)
Q
Qiao Longfei 已提交
135 136 137 138 139
			continue
		}
		break
	}
	log.Infof("Connected to etcd: %s\n", endpoints)
140
	client := &Etcd{
Q
Qiao Longfei 已提交
141
		client:    cli,
H
Helin Wang 已提交
142
		timeout:   defaultEtcdTimeout,
Q
Qiao Longfei 已提交
143 144 145 146
		endpoints: ep,
	}
	return client
}
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

// Select indicates if the current trainer is selected to initialize
// the pserver parameters.
func (e *Etcd) Select() (bool, error) {
	sess, err := concurrency.NewSession(e.client, concurrency.WithTTL(5))
	if err != nil {
		return false, err
	}

	lock := concurrency.NewMutex(sess, initLockPath)
	log.Infof("Trying to acquire lock at %s.", initLockPath)
	// Do not use timeout context here, since we don't know how
	// long does it take for other trainers to initialize the
	// parameters.
	err = lock.Lock(context.Background())
	if err != nil {
		return false, err
	}
	log.Infof("Successfully acquired lock at %s.", initLockPath)

	get := clientv3.OpGet(initDonePath)
	ctx, cancel := context.WithTimeout(context.Background(), e.timeout)
	tresp, err := e.client.Txn(ctx).If(lock.IsOwner()).Then(get).Commit()
	cancel()
	if err != nil {
		return false, err
	}

	if !tresp.Succeeded {
		return false, errors.New("no longer the owner of the lock")
	}

	resp := tresp.Responses[0].GetResponseRange()

	if len(resp.Kvs) == 0 {
		// Key value not set, select current trainer.
		e.lock = lock
		log.Infoln("Trainer selected.")
		return true, nil
	}

	if string(resp.Kvs[0].Value) == initDoneVal {
		log.Infoln("Initialization is already done.")
		ctx, cancel = context.WithTimeout(context.Background(), e.timeout)
		err = lock.Unlock(ctx)
		cancel()
		if err != nil {
			log.Errorln(err)
		}
		return false, nil
	}

	return false, fmt.Errorf("key %s have unexpected value: %v", initDonePath, resp.Kvs[0].Value)
}

// Done indicates the parameter initialization process is done.
func (e *Etcd) Done() error {
	if e.lock == nil {
		return errors.New("lock is nil, Done called unexpectedly")
	}

	put := clientv3.OpPut(initDonePath, initDoneVal)
	ctx, cancel := context.WithTimeout(context.Background(), e.timeout)
	tresp, err := e.client.Txn(ctx).If(e.lock.IsOwner()).Then(put).Commit()
	cancel()
	if err != nil {
		return err
	}

	if !tresp.Succeeded {
		return errors.New("no longer the owner of the lock")
	}

	ctx, cancel = context.WithTimeout(context.Background(), e.timeout)
	err = e.lock.Unlock(ctx)
	cancel()
	if err != nil {
		log.Errorln(err)
	} else {
		e.lock = nil
	}

	return nil
}

// Close closes the etcd client.
func (e *Etcd) Close() error {
	var err error
	if e.lock != nil {
		ctx, cancel := context.WithTimeout(context.Background(), e.timeout)
		err = e.lock.Unlock(ctx)
		cancel()
		if err == nil {
			e.lock = nil
		}
	}

	cErr := e.client.Close()
	if cErr != nil {
		if err != nil {
			log.Errorln(cErr)
			return err
		}
		return cErr
	}

	return err
}