controller_client.py 4.5 KB
Newer Older
W
wanghaoshuang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 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.

C
ceci3 已提交
15 16
import os
import time
W
wanghaoshuang 已提交
17 18
import logging
import socket
C
ceci3 已提交
19
from .log_helper import get_logger
W
wanghaoshuang 已提交
20 21 22 23 24 25 26 27 28

__all__ = ['ControllerClient']

_logger = get_logger(__name__, level=logging.INFO)


class ControllerClient(object):
    """
    Controller client.
29 30 31 32 33
    Args:
        server_ip(str): The ip that controller server listens on. None means getting the ip automatically. Default: None.
        server_port(int): The port that controller server listens on. 0 means getting usable port automatically. Default: 0.
        key(str): The key used to identify legal agent for controller server. Default: "light-nas"
        client_name(str): Current client name, random generate for counting client number. Default: None.
W
wanghaoshuang 已提交
34 35
    """

C
ceci3 已提交
36 37
    START = True

38 39 40 41 42
    def __init__(self,
                 server_ip=None,
                 server_port=None,
                 key=None,
                 client_name=None):
W
wanghaoshuang 已提交
43 44 45 46 47
        """
        """
        self.server_ip = server_ip
        self.server_port = server_port
        self._key = key
48
        self._client_name = client_name
W
wanghaoshuang 已提交
49

W
wanghaoshuang 已提交
50
    def update(self, tokens, reward, iter):
W
wanghaoshuang 已提交
51 52
        """
        Update the controller according to latest tokens and reward.
53

W
wanghaoshuang 已提交
54 55 56
        Args:
            tokens(list<int>): The tokens generated in last step.
            reward(float): The reward of tokens.
57
            iter(int): The iteration number of current client.
W
wanghaoshuang 已提交
58
        """
C
ceci3 已提交
59
        ControllerClient.START = False
W
wanghaoshuang 已提交
60
        socket_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
C
ceci3 已提交
61 62 63 64
        errno = socket_client.connect_ex((self.server_ip, self.server_port))
        if errno != 0:
            _logger.info("Server is closed!!!")
            os._exit(0)
65
        else:
C
ceci3 已提交
66 67 68 69 70 71 72 73 74 75 76 77
            tokens = ",".join([str(token) for token in tokens])
            socket_client.send("{}\t{}\t{}\t{}\t{}".format(
                self._key, tokens, reward, iter, self._client_name).encode())
            try:
                response = socket_client.recv(1024).decode()
                if "ok" in response.strip('\n').split("\t"):
                    return True
                else:
                    return False
            except Exception as err:
                _logger.error(err)
                os._exit(0)
W
wanghaoshuang 已提交
78 79 80 81 82

    def next_tokens(self):
        """
        Get next tokens.
        """
C
ceci3 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
        retry_cnt = 0

        if ControllerClient.START:
            while True:
                socket_client = socket.socket(socket.AF_INET,
                                              socket.SOCK_STREAM)
                errno = socket_client.connect_ex(
                    (self.server_ip, self.server_port))
                if errno != 0:
                    retry_cnt += 1
                    _logger.info("Server is NOT ready, wait 10 second to retry")
                    time.sleep(10)
                else:
                    break

                if retry_cnt == 6:
                    _logger.error(
                        "Server is NOT ready in 1 minute, please check if it start"
                    )
                    os._exit(errno)

        else:
            socket_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            errno = socket_client.connect_ex((self.server_ip, self.server_port))
            if errno != 0:
                _logger.info("Server is closed")
                os._exit(0)

W
wanghaoshuang 已提交
111 112 113 114
        socket_client.send("next_tokens".encode())
        tokens = socket_client.recv(1024).decode()
        tokens = [int(token) for token in tokens.strip("\n").split(",")]
        return tokens
C
ceci3 已提交
115 116 117 118 119 120

    def request_current_info(self):
        """
        Request for current information.
        """
        socket_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
C
ceci3 已提交
121 122 123 124 125 126 127 128
        errno = socket_client.connect_ex((self.server_ip, self.server_port))
        if errno != 0:
            _logger.info("Server is closed")
            return None
        else:
            socket_client.send("current_info".encode())
            current_info = socket_client.recv(1024).decode()
            return eval(current_info)