master.py 10.5 KB
Newer Older
K
kuizhiqing 已提交
1
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
#
K
kuizhiqing 已提交
3 4 5
# 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
6
#
K
kuizhiqing 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
K
kuizhiqing 已提交
9 10 11 12 13 14
# 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
from paddle.distributed.launch.utils.kv_client import KVClient
from paddle.distributed.launch.utils.kv_server import KVServer
K
kuizhiqing 已提交
17 18 19 20 21 22 23 24 25 26

import time
import sys
import threading
import copy
import random

ETCD_PROTOCAL = 'etcd://'


27
class Master:
K
kuizhiqing 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
    '''
    Master is a distributed store design to exchange info among nodes
    '''

    MAIN = "main"
    STANDBY = "standby"
    PATICIPANT = "participant"

    def __init__(self, ctx):
        self.ctx = ctx
        self.server = None
        self.initialized = False
        self.endpoint = None

    def stop(self):
        raise NotImplementedError

45 46 47 48 49 50 51 52 53
    def set_status(self, status):
        pass

    def get_status(self):
        return None

    def restart_peer(self):
        pass

K
kuizhiqing 已提交
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
    def sync_peers(self, prefix, key, value, size, rank=-1) -> (list, int):
        raise NotImplementedError

    @classmethod
    def factory(cls, ctx):
        if ctx.args.master and ctx.args.master.startswith(ETCD_PROTOCAL):
            return ETCDMaster(ctx)
        else:
            return HTTPMaster(ctx)


class HTTPMaster(Master):
    def lazy_init(self):
        if self.initialized:
            return

        self.role = Master.PATICIPANT

        if self.ctx.args.master:
            self.endpoint = self.ctx.args.master
            ip, port = self.endpoint.split(':')
            if ip in ['127.0.0.1', self.ctx.node.ip]:
                time.sleep(2 * random.random())
                while not self.ctx.node.is_server_ready(ip, int(port)):
                    try:
                        self.server = KVServer(int(port))
                        self.role = Master.MAIN
                        break
                    except Exception as e:
83
                        self.ctx.logger.warning(
84 85
                            "start master failed {}".format(e)
                        )
K
kuizhiqing 已提交
86 87 88 89 90 91 92 93 94 95
                        time.sleep(0.1)
                        continue
        else:
            port = self.ctx.node.get_free_port()
            self.endpoint = "{}:{}".format(self.ctx.node.ip, port)
            self.server = KVServer(port)
            self.role = Master.MAIN

            print("Copy the following command to other nodes to run.")
            cmd = [
96 97 98
                sys.executable.split('/')[-1],
                "-m",
                "paddle.distributed.launch",
K
kuizhiqing 已提交
99 100 101 102 103 104 105
            ]
            cmd.extend(["--master", self.endpoint])
            cmd.extend(sys.argv[1:])
            print("-" * 80)
            print(" ".join(cmd))
            print("-" * 80)

K
kuizhiqing 已提交
106
            if int(self.ctx.args.rank) >= 0:
K
kuizhiqing 已提交
107
                self.ctx.logger.warning(
108 109
                    "--rank set in the command may not compatible in auto mode"
                )
K
kuizhiqing 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132

        if '127.0.0.1' in self.endpoint:
            self.endpoint = self.endpoint.replace('127.0.0.1', self.ctx.node.ip)
        self.client = KVClient(self.endpoint)

        self.initialized = True

        self._start_server()

    def _start_server(self):
        if self.server and not self.server.started:
            self.server.start()
            self.ctx.logger.debug("KV server start at {}".format(self.endpoint))

    def _stop_server(self):
        if self.server and not self.server.stopped:
            self.server.stop()
            self.ctx.logger.debug("KV server stopped")

    def stop(self):
        self._stop_server()

    def sync_peers(self, prefix, key, value, size, rank=-1) -> (list, int):
133

K
kuizhiqing 已提交
134 135 136
        if size < 2:
            return [value], 0

137
        self.ctx.logger.info("Waiting peer start...")
138

K
kuizhiqing 已提交
139 140 141 142 143 144 145 146 147
        self.lazy_init()

        while not self.ctx.status.is_done():
            if self.client.wait_server_ready(timeout=5):
                break
            else:
                self.ctx.logger.warning("master not ready")
                time.sleep(0.1)

148
        # 'aaaaaa' make sure main pod (master server) as rank 0
K
kuizhiqing 已提交
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
        ky = 'aaaaaa' if rank < 0 and self.role == Master.MAIN else key
        k = "{}/{}/{}".format(prefix, ky, rank)

        while not self.ctx.status.is_done():
            if not self.client.put(k, value):
                self.ctx.logger.warning("put value failed")
                time.sleep(0.1)
                continue

            rjson = self.client.get_prefix(prefix)
            self.ctx.logger.debug("sync peers {}".format(rjson))
            if rjson and len(rjson) == size:
                if rank < 0:
                    keys = list(rjson.keys())
                    keys.sort()
                    ret = [rjson[k] for k in keys]
                    idx = ret.index(value)
                    return ret, idx
                else:
                    ret = [None] * size
                    for k, v in rjson.items():
                        ret[int(k.split('/')[-1])] = v
                    return ret, rank
            else:
                time.sleep(0.5)
        return [], 0


class ETCDMaster(Master):
    def __init__(self, ctx):
        super().__init__(ctx)

        if self.ctx.args.master:
            # etcd://localhost:2379
            self.endpoint = self.ctx.args.master.strip("etcd://")

        import etcd3

        host, port = self.endpoint.split(':')
        self.client = etcd3.client(host=host, port=port)

    def sync_peers(self, prefix, key, value, size, rank=-1) -> (list, int):
        '''
        sync_peers gather all value for key under scope prefix
        result always be sorted either by rank or alphabet of pod.name
        '''
195 196 197 198

        if size < 2:
            return [value], 0

199
        self.ctx.logger.info("Waiting peer start...")
200

K
kuizhiqing 已提交
201 202 203 204 205 206 207
        path = "{}/{}/{}".format(prefix, key, rank)

        self.client.delete_prefix(prefix)

        self.ctx.logger.debug("sync path {} value {}".format(path, value))

        while not self.ctx.status.is_done():
208
            self.client.put(path, value.encode('latin-1'))
K
kuizhiqing 已提交
209 210 211 212 213 214 215

            result = [i for i in self.client.get_prefix(prefix)]
            result = copy.deepcopy(result)
            self.ctx.logger.debug("sync peers {}".format(result))

            if len(result) == size:
                if rank < 0:
216 217
                    keys = [i[1].key.decode() for i in result]
                    sorted_keys = [i[1].key.decode() for i in result]
K
kuizhiqing 已提交
218
                    sorted_keys.sort()
219
                    values = [i[0].decode() for i in result]
K
kuizhiqing 已提交
220 221 222 223 224 225
                    ret = [values[keys.index(k)] for k in sorted_keys]
                    idx = ret.index(value)
                    return ret, idx
                else:
                    ret = [None] * size
                    for v, k in result:
226
                        ii = int(k.key.decode().split('/')[-1])
K
kuizhiqing 已提交
227 228
                        if ii < 0:
                            self.ctx.logger.error(
229 230
                                "rank {} error in sync".format(ii)
                            )
231
                        ret[ii] = v.decode()
K
kuizhiqing 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245
                    return ret, rank
            else:
                time.sleep(0.5)

    def register_heartbeat(self, job_id, pod_id, ttl=10):
        if hasattr(self, 'heartbeat_prefix'):
            self.ctx.logger.warning("Heartbeat already done")
            return

        self.job_prefix = '/paddle/{}'.format(job_id)
        self.heartbeat_prefix = '{}/heartbeat'.format(self.job_prefix)

        lease = self.client.lease(ttl)

246
        # self.client.delete_prefix(self.job_prefix)
K
kuizhiqing 已提交
247 248

        beat_path = "{}/{}".format(self.heartbeat_prefix, pod_id)
249
        self.client.put(beat_path, pod_id.encode('latin-1'), lease=lease)
K
kuizhiqing 已提交
250 251 252 253 254

        def _beat_watch(event):
            self.ctx.status.restart()

        beat_watch = self.client.add_watch_prefix_callback(
255 256
            self.heartbeat_prefix, _beat_watch
        )
K
kuizhiqing 已提交
257 258 259 260 261 262

        def _heartbeat():
            while not self.ctx.status.is_done():
                try:
                    lease.refresh()
                    if pod_id not in self.fetch_peer_alive():
263 264 265
                        self.client.put(
                            beat_path, pod_id.encode('latin-1'), lease=lease
                        )
K
kuizhiqing 已提交
266 267 268 269 270 271 272
                        self.ctx.logger.debug("Heartbeat register again")
                except Exception as e:
                    self.ctx.logger.error("Heartbeat error {}".format(e))
                time.sleep(ttl / 2)
            self.ctx.logger.debug("Heartbeat done")
            self.client.cancel_watch(beat_watch)

273 274 275
        self.beat_thread = threading.Thread(
            name='heartbeat', target=_heartbeat, daemon=True
        )
K
kuizhiqing 已提交
276 277 278 279
        self.beat_thread.start()

    def fetch_peer_alive(self):
        peer_alive = [
280
            i[0].decode() for i in self.client.get_prefix(self.heartbeat_prefix)
K
kuizhiqing 已提交
281 282 283 284 285
        ]
        self.ctx.logger.debug("peer alive {}".format(peer_alive))
        return peer_alive

    def wait_peer_ready(self, replicas_min, replicas_max, timeout):
K
kuizhiqing 已提交
286 287
        timeout = timeout if timeout > 1 else 3

K
kuizhiqing 已提交
288
        end = time.time() + timeout
K
kuizhiqing 已提交
289
        np_pre = len(self.fetch_peer_alive())
K
kuizhiqing 已提交
290
        while not self.ctx.status.is_done() and time.time() < end:
K
kuizhiqing 已提交
291 292 293
            np = len(self.fetch_peer_alive())
            if np == replicas_max:
                # maximum replicas reached, return immediately
K
kuizhiqing 已提交
294
                return (True, replicas_max)
K
kuizhiqing 已提交
295 296 297 298 299
            elif np != np_pre:
                # replicas are changing, reset timeout
                end = time.time() + timeout
                np_pre = np
                time.sleep(0.2)
K
kuizhiqing 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312 313
            else:
                time.sleep(0.5)

        np = len(self.fetch_peer_alive())
        if np >= replicas_min and np <= replicas_max:
            return (True, np)
        else:
            return (False, np)

    def restart_peer(self):
        self.client.delete_prefix(self.heartbeat_prefix)

    def set_status(self, status):
        assert self.client.put(
314 315
            self.job_prefix,
            status.encode('latin-1'),
316 317
            lease=self.client.lease(600),
        ), "set status failed {}".format(status)
K
kuizhiqing 已提交
318 319

    def get_status(self):
320 321
        value = self.client.get(self.job_prefix)[0]
        return value.decode() if value is not None else ''
K
kuizhiqing 已提交
322 323 324 325

    def stop(self):
        if hasattr(self, 'beat_thread'):
            self.ctx.status.done()
K
kuizhiqing 已提交
326
            # daemon thread
327
            # self.beat_thread.join()