Skip to content

server

Server-side implementation of Toon Boon Harmony communication.

Server

Bases: Thread

Class for communication with Toon Boon Harmony.

Attributes:

Name Type Description
connection Socket

connection holding object.

received str

received data buffer.any(iterable)

port int

port number.

message_id int

index of last message going out.

queue dict

dictionary holding queue of incoming messages.

Source code in client/ayon_harmony/api/server.py
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 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
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
class Server(threading.Thread):
    """Class for communication with Toon Boon Harmony.

    Attributes:
        connection (Socket): connection holding object.
        received (str): received data buffer.any(iterable)
        port (int): port number.
        message_id (int): index of last message going out.
        queue (dict): dictionary holding queue of incoming messages.

    """

    def __init__(self, port):
        """Constructor."""
        super(Server, self).__init__()
        self.daemon = True
        self.connection = None
        self.received = ""
        self.port = port
        self.message_id = 1

        # Setup logging.
        self.log = logging.getLogger(__name__)
        self.log.setLevel(logging.DEBUG)

        # Create a TCP/IP socket
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # Bind the socket to the port
        server_address = ("127.0.0.1", port)
        self.log.debug(
            f"[{self.timestamp()}] Starting up on "
            f"{server_address[0]}:{server_address[1]}")
        self.socket.bind(server_address)

        # Listen for incoming connections
        self.socket.listen(1)
        self.queue = {}

    def process_request(self, request):
        """Process incoming request.

        Args:
            request (dict): {
                "module": (str),  # Module of method.
                "method" (str),  # Name of method in module.
                "args" (list),  # Arguments to pass to method.
                "kwargs" (dict),  # Keyword arguments to pass to method.
                "reply" (bool),  # Optional wait for method completion.
            }
        """
        pretty = self._pretty(request)
        self.log.debug(
            f"[{self.timestamp()}] Processing request:\n{pretty}")

        # TODO javascript should not define which module is imported and
        #   which function is called. It should send predefined requests.
        try:
            module = importlib.import_module(request["module"])
            method = getattr(module, request["method"])

            args = request.get("args", [])
            kwargs = request.get("kwargs", {})
            partial_method = functools.partial(method, *args, **kwargs)

            lib.ProcessContext.execute_in_main_thread(partial_method)
        except Exception:
            self.log.error(traceback.format_exc())

    def receive(self):
        """Receives data from `self.connection`.

        When the data is a json serializable string, a reply is sent then
        processing of the request.
        """
        current_time = time.time()
        while True:
            # Receive the data in small chunks and retransmit it
            request = None
            try:
                header = self.connection.recv(10)
            except OSError:
                # could happen on MacOS
                self.log.info("")
                break

            if len(header) == 0:
                # null data received, socket is closing.
                self.log.info(f"[{self.timestamp()}] Connection closing.")
                break

            if header[0:2] != b"AH":
                self.log.error("INVALID HEADER")
            content_length_str = header[2:].decode()

            length = int(content_length_str, 16)
            data = self.connection.recv(length)
            while (len(data) < length):
                # we didn't received everything in first try, lets wait for
                # all data.
                self.log.info("loop")
                time.sleep(0.1)
                if self.connection is None:
                    self.log.error(f"[{self.timestamp()}] "
                                   "Connection is broken")
                    break
                if time.time() > current_time + 30:
                    self.log.error(f"[{self.timestamp()}] Connection timeout.")
                    break

                data += self.connection.recv(length - len(data))
            self.log.debug("data:: {} {}".format(data, type(data)))
            self.received += data.decode("utf-8")
            pretty = self._pretty(self.received)
            self.log.debug(
                f"[{self.timestamp()}] Received:\n{pretty}")

            try:
                request = json.loads(self.received)
            except json.decoder.JSONDecodeError as e:
                self.log.error(f"[{self.timestamp()}] "
                               f"Invalid message received.\n{e}",
                               exc_info=True)

            self.received = ""
            if request is None:
                continue

            if "message_id" in request.keys():
                message_id = request["message_id"]
                self.message_id = message_id + 1
                self.log.debug(f"--- storing request as {message_id}")
                self.queue[message_id] = request
            if "reply" not in request.keys():
                request["reply"] = True
                self.send(request)
                self.process_request(request)

                if "message_id" in request.keys():
                    try:
                        self.log.debug(f"[{self.timestamp()}] "
                                       f"Removing from the queue {message_id}")
                        del self.queue[message_id]
                    except IndexError:
                        self.log.debug(f"[{self.timestamp()}] "
                                       f"{message_id} is no longer in queue")
            else:
                self.log.debug(f"[{self.timestamp()}] "
                               "received data was just a reply.")

    def run(self):
        """Entry method for server.

        Waits for a connection on `self.port` before going into listen mode.
        """
        # Wait for a connection
        timestamp = datetime.now().strftime("%H:%M:%S.%f")
        self.log.debug(f"[{timestamp}] Waiting for a connection.")
        self.connection, client_address = self.socket.accept()

        timestamp = datetime.now().strftime("%H:%M:%S.%f")
        self.log.debug(f"[{timestamp}] Connection from: {client_address}")

        self.receive()

    def stop(self):
        """Shutdown socket server gracefully."""
        timestamp = datetime.now().strftime("%H:%M:%S.%f")
        self.log.debug(f"[{timestamp}] Shutting down server.")
        if self.connection is None:
            self.log.debug("Connect to shutdown.")
            socket.socket(
                socket.AF_INET, socket.SOCK_STREAM
            ).connect(("localhost", self.port))

        self.connection.close()
        self.connection = None

        self.socket.close()

    def _send(self, message):
        """Send a message to Harmony.

        Args:
            message (str): Data to send to Harmony.
        """
        # Wait for a connection.
        while not self.connection:
            pass

        timestamp = datetime.now().strftime("%H:%M:%S.%f")
        encoded = message.encode("utf-8")
        coded_message = b"AH" + struct.pack('>I', len(encoded)) + encoded
        pretty = self._pretty(coded_message)
        self.log.debug(
            f"[{timestamp}] Sending [{self.message_id}]:\n{pretty}")
        self.log.debug(f"--- Message length: {len(encoded)}")
        self.connection.sendall(coded_message)
        self.message_id += 1

    def send(self, request):
        """Send a request in dictionary to Harmony.

        Waits for a reply from Harmony.

        Args:
            request (dict): Data to send to Harmony.
        """
        request["message_id"] = self.message_id
        self._send(json.dumps(request))
        if request.get("reply"):
            timestamp = datetime.now().strftime("%H:%M:%S.%f")
            self.log.debug(
                f"[{timestamp}] sent reply, not waiting for anything.")
            return None
        result = None
        current_time = time.time()
        try_index = 1
        while True:
            time.sleep(0.1)
            if time.time() > current_time + 30:
                timestamp = datetime.now().strftime("%H:%M:%S.%f")
                self.log.error((f"[{timestamp}][{self.message_id}] "
                                "No reply from Harmony in 30s. "
                                f"Retrying {try_index}"))
                try_index += 1
                current_time = time.time()
            if try_index > 30:
                break
            try:
                result = self.queue[request["message_id"]]
                timestamp = datetime.now().strftime("%H:%M:%S.%f")
                self.log.debug((f"[{timestamp}] Got request "
                                f"id {self.message_id}, "
                                "removing from queue"))
                del self.queue[request["message_id"]]
                break
            except KeyError:
                # response not in received queue yey
                pass
            try:
                result = json.loads(self.received)
                break
            except json.decoder.JSONDecodeError:
                pass

        self.received = ""

        return result

    def _pretty(self, message) -> str:
        # result = pformat(message, indent=2)
        # return result.replace("\\n", "\n")
        return "{}{}".format(4 * " ", message)

    def timestamp(self):
        """Return current timestamp as a string.

        Returns:
            str: current timestamp.

        """
        return datetime.now().strftime("%H:%M:%S.%f")

__init__(port)

Constructor.

Source code in client/ayon_harmony/api/server.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def __init__(self, port):
    """Constructor."""
    super(Server, self).__init__()
    self.daemon = True
    self.connection = None
    self.received = ""
    self.port = port
    self.message_id = 1

    # Setup logging.
    self.log = logging.getLogger(__name__)
    self.log.setLevel(logging.DEBUG)

    # Create a TCP/IP socket
    self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # Bind the socket to the port
    server_address = ("127.0.0.1", port)
    self.log.debug(
        f"[{self.timestamp()}] Starting up on "
        f"{server_address[0]}:{server_address[1]}")
    self.socket.bind(server_address)

    # Listen for incoming connections
    self.socket.listen(1)
    self.queue = {}

process_request(request)

Process incoming request.

Parameters:

Name Type Description Default
request dict

{ "module": (str), # Module of method. "method" (str), # Name of method in module. "args" (list), # Arguments to pass to method. "kwargs" (dict), # Keyword arguments to pass to method. "reply" (bool), # Optional wait for method completion.

required
Source code in client/ayon_harmony/api/server.py
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
def process_request(self, request):
    """Process incoming request.

    Args:
        request (dict): {
            "module": (str),  # Module of method.
            "method" (str),  # Name of method in module.
            "args" (list),  # Arguments to pass to method.
            "kwargs" (dict),  # Keyword arguments to pass to method.
            "reply" (bool),  # Optional wait for method completion.
        }
    """
    pretty = self._pretty(request)
    self.log.debug(
        f"[{self.timestamp()}] Processing request:\n{pretty}")

    # TODO javascript should not define which module is imported and
    #   which function is called. It should send predefined requests.
    try:
        module = importlib.import_module(request["module"])
        method = getattr(module, request["method"])

        args = request.get("args", [])
        kwargs = request.get("kwargs", {})
        partial_method = functools.partial(method, *args, **kwargs)

        lib.ProcessContext.execute_in_main_thread(partial_method)
    except Exception:
        self.log.error(traceback.format_exc())

receive()

Receives data from self.connection.

When the data is a json serializable string, a reply is sent then processing of the request.

Source code in client/ayon_harmony/api/server.py
 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def receive(self):
    """Receives data from `self.connection`.

    When the data is a json serializable string, a reply is sent then
    processing of the request.
    """
    current_time = time.time()
    while True:
        # Receive the data in small chunks and retransmit it
        request = None
        try:
            header = self.connection.recv(10)
        except OSError:
            # could happen on MacOS
            self.log.info("")
            break

        if len(header) == 0:
            # null data received, socket is closing.
            self.log.info(f"[{self.timestamp()}] Connection closing.")
            break

        if header[0:2] != b"AH":
            self.log.error("INVALID HEADER")
        content_length_str = header[2:].decode()

        length = int(content_length_str, 16)
        data = self.connection.recv(length)
        while (len(data) < length):
            # we didn't received everything in first try, lets wait for
            # all data.
            self.log.info("loop")
            time.sleep(0.1)
            if self.connection is None:
                self.log.error(f"[{self.timestamp()}] "
                               "Connection is broken")
                break
            if time.time() > current_time + 30:
                self.log.error(f"[{self.timestamp()}] Connection timeout.")
                break

            data += self.connection.recv(length - len(data))
        self.log.debug("data:: {} {}".format(data, type(data)))
        self.received += data.decode("utf-8")
        pretty = self._pretty(self.received)
        self.log.debug(
            f"[{self.timestamp()}] Received:\n{pretty}")

        try:
            request = json.loads(self.received)
        except json.decoder.JSONDecodeError as e:
            self.log.error(f"[{self.timestamp()}] "
                           f"Invalid message received.\n{e}",
                           exc_info=True)

        self.received = ""
        if request is None:
            continue

        if "message_id" in request.keys():
            message_id = request["message_id"]
            self.message_id = message_id + 1
            self.log.debug(f"--- storing request as {message_id}")
            self.queue[message_id] = request
        if "reply" not in request.keys():
            request["reply"] = True
            self.send(request)
            self.process_request(request)

            if "message_id" in request.keys():
                try:
                    self.log.debug(f"[{self.timestamp()}] "
                                   f"Removing from the queue {message_id}")
                    del self.queue[message_id]
                except IndexError:
                    self.log.debug(f"[{self.timestamp()}] "
                                   f"{message_id} is no longer in queue")
        else:
            self.log.debug(f"[{self.timestamp()}] "
                           "received data was just a reply.")

run()

Entry method for server.

Waits for a connection on self.port before going into listen mode.

Source code in client/ayon_harmony/api/server.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
def run(self):
    """Entry method for server.

    Waits for a connection on `self.port` before going into listen mode.
    """
    # Wait for a connection
    timestamp = datetime.now().strftime("%H:%M:%S.%f")
    self.log.debug(f"[{timestamp}] Waiting for a connection.")
    self.connection, client_address = self.socket.accept()

    timestamp = datetime.now().strftime("%H:%M:%S.%f")
    self.log.debug(f"[{timestamp}] Connection from: {client_address}")

    self.receive()

send(request)

Send a request in dictionary to Harmony.

Waits for a reply from Harmony.

Parameters:

Name Type Description Default
request dict

Data to send to Harmony.

required
Source code in client/ayon_harmony/api/server.py
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
255
256
257
258
259
260
261
262
263
264
265
def send(self, request):
    """Send a request in dictionary to Harmony.

    Waits for a reply from Harmony.

    Args:
        request (dict): Data to send to Harmony.
    """
    request["message_id"] = self.message_id
    self._send(json.dumps(request))
    if request.get("reply"):
        timestamp = datetime.now().strftime("%H:%M:%S.%f")
        self.log.debug(
            f"[{timestamp}] sent reply, not waiting for anything.")
        return None
    result = None
    current_time = time.time()
    try_index = 1
    while True:
        time.sleep(0.1)
        if time.time() > current_time + 30:
            timestamp = datetime.now().strftime("%H:%M:%S.%f")
            self.log.error((f"[{timestamp}][{self.message_id}] "
                            "No reply from Harmony in 30s. "
                            f"Retrying {try_index}"))
            try_index += 1
            current_time = time.time()
        if try_index > 30:
            break
        try:
            result = self.queue[request["message_id"]]
            timestamp = datetime.now().strftime("%H:%M:%S.%f")
            self.log.debug((f"[{timestamp}] Got request "
                            f"id {self.message_id}, "
                            "removing from queue"))
            del self.queue[request["message_id"]]
            break
        except KeyError:
            # response not in received queue yey
            pass
        try:
            result = json.loads(self.received)
            break
        except json.decoder.JSONDecodeError:
            pass

    self.received = ""

    return result

stop()

Shutdown socket server gracefully.

Source code in client/ayon_harmony/api/server.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def stop(self):
    """Shutdown socket server gracefully."""
    timestamp = datetime.now().strftime("%H:%M:%S.%f")
    self.log.debug(f"[{timestamp}] Shutting down server.")
    if self.connection is None:
        self.log.debug("Connect to shutdown.")
        socket.socket(
            socket.AF_INET, socket.SOCK_STREAM
        ).connect(("localhost", self.port))

    self.connection.close()
    self.connection = None

    self.socket.close()

timestamp()

Return current timestamp as a string.

Returns:

Name Type Description
str

current timestamp.

Source code in client/ayon_harmony/api/server.py
272
273
274
275
276
277
278
279
def timestamp(self):
    """Return current timestamp as a string.

    Returns:
        str: current timestamp.

    """
    return datetime.now().strftime("%H:%M:%S.%f")