scripts.py 4.1 KB
Newer Older
F
fuyw 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#   Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# 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.

import click
import locale
B
Bo Zhou 已提交
17
import sys
F
fuyw 已提交
18 19 20 21 22
import os
import subprocess
import threading
import warnings
from multiprocessing import Process
B
Bo Zhou 已提交
23
from parl.utils import logger
F
fuyw 已提交
24 25 26 27 28 29 30 31

# A flag to mark if parl is started from a command line
os.environ['XPARL'] = 'True'

# Solve `Click will abort further execution because Python 3 was configured
# to use ASCII as encoding for the environment` error.
locale.setlocale(locale.LC_ALL, "en_US.UTF-8")

B
Bo Zhou 已提交
32 33 34
#TODO: this line will cause error in python2/macOS
if sys.version_info.major == 3:
    warnings.simplefilter("ignore", ResourceWarning)
F
fuyw 已提交
35 36


B
Bo Zhou 已提交
37
def is_port_available(port):
F
fuyw 已提交
38 39
    """ Check if a port is used.

B
Bo Zhou 已提交
40
    True if the port is available for connection.
F
fuyw 已提交
41
    """
B
Bo Zhou 已提交
42
    port = int(port)
F
fuyw 已提交
43
    import socket
B
Bo Zhou 已提交
44 45 46 47
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    available = sock.connect_ex(('localhost', port))
    sock.close()
    return available
F
fuyw 已提交
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


def is_master_started(address):
    import zmq
    ctx = zmq.Context()
    socket = ctx.socket(zmq.REQ)
    socket.linger = 0
    socket.setsockopt(zmq.RCVTIMEO, 500)
    socket.connect("tcp://{}".format(address))
    socket.send_multipart([b'[NORMAL]'])
    try:
        _ = socket.recv_multipart()
        socket.close(0)
        return True
    except zmq.error.Again as e:
        socket.close(0)
        return False


@click.group()
def cli():
    pass


@click.command("start", short_help="Start a master node.")
@click.option("--port", help="The port to bind to.", type=str, required=True)
@click.option(
    "--cpu_num",
    type=int,
    help="Set number of cpu manually. If not set, it will use all "
    "cpus of this machine.")
def start_master(port, cpu_num):
B
Bo Zhou 已提交
80
    if not is_port_available(port):
F
fuyw 已提交
81 82 83
        raise Exception(
            "The master address localhost:{} already in use.".format(port))
    cpu_num = str(cpu_num) if cpu_num else ''
B
Bo Zhou 已提交
84 85
    start_file = __file__.replace('scripts.pyc', 'start.py')
    start_file = start_file.replace('scripts.py', 'start.py')
B
Bo Zhou 已提交
86
    command = [sys.executable, start_file, "--name", "master", "--port", port]
F
fuyw 已提交
87 88 89
    p = subprocess.Popen(command)

    command = [
B
Bo Zhou 已提交
90
        sys.executable, start_file, "--name", "worker", "--address",
B
Bo Zhou 已提交
91
        "localhost:" + str(port), "--cpu_num",
F
fuyw 已提交
92 93
        str(cpu_num)
    ]
B
Bo Zhou 已提交
94 95 96 97
    # Redirect the output to DEVNULL to solve the warning log.
    FNULL = open(os.devnull, 'w')
    p = subprocess.Popen(command, stdout=FNULL, stderr=subprocess.STDOUT)
    FNULL.close()
F
fuyw 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114


@click.command("connect", short_help="Start a worker node.")
@click.option(
    "--address", help="IP address of the master node.", required=True)
@click.option(
    "--cpu_num",
    type=int,
    help="Set number of cpu manually. If not set, it will use all "
    "cpus of this machine.")
def start_worker(address, cpu_num):
    if not is_master_started(address):
        raise Exception("Worker can not connect to the master node, " +
                        "please check if the input address {} ".format(
                            address) + "is correct.")
    cpu_num = str(cpu_num) if cpu_num else ''
    command = [
B
Bo Zhou 已提交
115 116
        sys.executable, "{}/start.py".format(__file__[:-11]), "--name",
        "worker", "--address", address, "--cpu_num",
F
fuyw 已提交
117 118 119 120 121 122 123 124 125
        str(cpu_num)
    ]
    p = subprocess.Popen(command)


@click.command("stop", help="Exit the cluster.")
def stop():
    command = ("pkill -f remote/start.py")
    subprocess.call([command], shell=True)
B
Bo Zhou 已提交
126 127
    command = ("pkill -f remote/job.py")
    subprocess.call([command], shell=True)
F
fuyw 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140


cli.add_command(start_worker)
cli.add_command(start_master)
cli.add_command(stop)


def main():
    return cli()


if __name__ == "__main__":
    main()