Distributed engine: Use larger receive queue to allow longer time settings
[pachi/derm.git] / distributed / protocol.c
blobcd360d93d38d48be2b022fd8a3619b51628bd2d9
1 /* The functions implementing the master-slave protocol of the
2 * distributed engine are grouped here. They are independent
3 * of the gtp protocol. See the comments at the top of distributed.c
4 * for a general introduction to the distributed engine. */
6 /* The receive queue is an array of pointers to binary buffers.
7 * These pointers are invalidated in one of two ways when a buffer
8 * is recycled: (1) the queue age is increased when the queue is
9 * emptied at a new move, (2) the pointer itself is set to NULL
10 * immmediately, and stays so until at least the next queue age
11 * increment. */
13 #include <assert.h>
14 #include <stdio.h>
15 #include <pthread.h>
16 #include <ctype.h>
17 #include <unistd.h>
19 #define DEBUG
21 #include "random.h"
22 #include "timeinfo.h"
23 #include "playout.h"
24 #include "network.h"
25 #include "debug.h"
26 #include "distributed/distributed.h"
27 #include "distributed/protocol.h"
29 /* All gtp commands for current game separated by \n */
30 static char gtp_cmds[CMDS_SIZE];
32 /* Latest gtp command sent to slaves. */
33 static char *gtp_cmd = NULL;
35 /* Slaves send gtp_cmd when cmd_count changes. */
36 static int cmd_count = 0;
38 /* Remember at most 10 gtp ids per move: kgs-rules, boardsize, clear_board,
39 * time_settings, komi, handicap, genmoves, play pass, play pass, final_status_list */
40 #define MAX_CMDS_PER_MOVE 10
42 /* History of gtp commands sent for current game, indexed by move. */
43 static struct cmd_history {
44 int gtp_id;
45 char *next_cmd;
46 } history[MAX_GAMELEN][MAX_CMDS_PER_MOVE];
48 /* Number of active slave machines working for this master. */
49 int active_slaves = 0;
51 /* Number of replies to last gtp command already received. */
52 int reply_count = 0;
54 /* All replies to latest gtp command are in gtp_replies[0..reply_count-1]. */
55 char **gtp_replies;
58 struct buf_state **receive_queue;
59 int queue_length = 0;
60 int queue_age = 0;
61 static int queue_max_length;
63 /* Mutex protecting all variables above. receive_queue may be
64 * read without the lock but is only written with lock held. */
65 static pthread_mutex_t slave_lock = PTHREAD_MUTEX_INITIALIZER;
67 /* Condition signaled when a new gtp command is available. */
68 static pthread_cond_t cmd_cond = PTHREAD_COND_INITIALIZER;
70 /* Condition signaled when reply_count increases. */
71 static pthread_cond_t reply_cond = PTHREAD_COND_INITIALIZER;
73 /* Mutex protecting stderr. Must not be held at same time as slave_lock. */
74 static pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER;
76 /* Absolute time when this program was started.
77 * For debugging only. */
78 static double start_time;
80 /* Default slave state. */
81 struct slave_state default_sstate;
84 /* Get exclusive access to the threads and commands state. */
85 void
86 protocol_lock(void)
88 pthread_mutex_lock(&slave_lock);
91 /* Release exclusive access to the threads and commands state. */
92 void
93 protocol_unlock(void)
95 pthread_mutex_unlock(&slave_lock);
98 /* Write the time, client address, prefix, and string s to stderr atomically.
99 * s should end with a \n */
100 void
101 logline(struct in_addr *client, char *prefix, char *s)
103 double now = time_now();
105 char addr[INET_ADDRSTRLEN];
106 if (client) {
107 inet_ntop(AF_INET, client, addr, sizeof(addr));
108 } else {
109 addr[0] = '\0';
111 pthread_mutex_lock(&log_lock);
112 fprintf(stderr, "%s%15s %9.3f: %s", prefix, addr, now - start_time, s);
113 pthread_mutex_unlock(&log_lock);
116 /* Thread opening a connection on the given socket and copying input
117 * from there to stderr. */
118 static void *
119 proxy_thread(void *arg)
121 int proxy_sock = (long)arg;
122 assert(proxy_sock >= 0);
123 for (;;) {
124 struct in_addr client;
125 int conn = open_server_connection(proxy_sock, &client);
126 FILE *f = fdopen(conn, "r");
127 char buf[BSIZE];
128 while (fgets(buf, BSIZE, f)) {
129 logline(&client, "< ", buf);
131 fclose(f);
135 /* Get a reply to one gtp command. Return the gtp command id,
136 * or -1 if error. reply must have at least CMDS_SIZE bytes.
137 * The ascii reply ends with an empty line; if the first line
138 * contains "@size", a binary reply of size bytes follows the
139 * empty line. @size is not standard gtp, it is only used
140 * internally by Pachi for the genmoves command; it must be the
141 * last parameter on the line.
142 * *bin_size is the maximum size upon entry, actual size on return.
143 * slave_lock is not held on either entry or exit of this function. */
144 static int
145 get_reply(FILE *f, struct in_addr client, char *reply, void *bin_reply, int *bin_size)
147 double start = time_now();
149 int reply_id = -1;
150 *reply = '\0';
151 if (!fgets(reply, CMDS_SIZE, f)) return -1;
153 /* Check for binary reply. */
154 char *s = strchr(reply, '@');
155 int size = 0;
156 if (s) size = atoi(s+1);
157 assert(size <= *bin_size);
158 *bin_size = size;
160 if (DEBUGV(s, 2))
161 logline(&client, "<<", reply);
162 if ((*reply == '=' || *reply == '?') && isdigit(reply[1]))
163 reply_id = atoi(reply+1);
165 /* Read the rest of the ascii reply */
166 char *line = reply + strlen(reply);
167 while (fgets(line, reply + CMDS_SIZE - line, f) && *line != '\n') {
168 if (DEBUGL(3))
169 logline(&client, "<<", line);
170 line += strlen(line);
172 if (*line != '\n') return -1;
174 /* Read the binary reply if any. */
175 int len;
176 while (size && (len = fread(bin_reply, 1, size, f)) > 0) {
177 bin_reply = (char *)bin_reply + len;
178 size -= len;
180 if (*bin_size && DEBUGVV(2)) {
181 char buf[1024];
182 snprintf(buf, sizeof(buf), "read reply %d+%d bytes in %.4fms\n",
183 (int)strlen(reply), *bin_size,
184 (time_now() - start)*1000);
185 logline(&client, "= ", buf);
187 return size ? -1 : reply_id;
190 /* Send the gtp command to_send and get a reply from the slave machine.
191 * Write the reply in buf which must have at least CMDS_SIZE bytes.
192 * If *bin_size > 0, send bin_buf after the gtp command.
193 * Return any binary reply in bin_buf and set its size in bin_size.
194 * bin_buf is private to the slave and need not be copied.
195 * Return the gtp command id, or -1 if error.
196 * slave_lock is held on both entry and exit of this function. */
197 static int
198 send_command(char *to_send, void *bin_buf, int *bin_size,
199 FILE *f, struct slave_state *sstate, char *buf)
201 assert(to_send && gtp_cmd && bin_buf && bin_size);
202 strncpy(buf, to_send, CMDS_SIZE);
203 bool resend = to_send != gtp_cmd;
205 pthread_mutex_unlock(&slave_lock);
207 if (DEBUGL(1) && resend)
208 logline(&sstate->client, "? ",
209 to_send == gtp_cmds ? "resend all\n" : "partial resend\n");
211 double start = time_now();
212 fputs(buf, f);
214 if (*bin_size)
215 fwrite(bin_buf, 1, *bin_size, f);
216 fflush(f);
218 if (DEBUGV(strchr(buf, '@'), 2)) {
219 double ms = (time_now() - start) * 1000.0;
220 if (!DEBUGL(3)) {
221 char *s = strchr(buf, '\n');
222 if (s) s[1] = '\0';
224 logline(&sstate->client, ">>", buf);
225 if (*bin_size) {
226 char b[1024];
227 snprintf(b, sizeof(b),
228 "sent cmd %d+%d bytes in %.4fms\n",
229 (int)strlen(buf), *bin_size, ms);
230 logline(&sstate->client, "= ", b);
234 /* Reuse the buffers for the reply. */
235 *bin_size = sstate->max_buf_size;
236 int reply_id = get_reply(f, sstate->client, buf, bin_buf, bin_size);
238 pthread_mutex_lock(&slave_lock);
239 return reply_id;
242 /* Return the command sent after that with the given gtp id,
243 * or gtp_cmds if the id wasn't used in this game. If a play command
244 * has overwritten a genmoves command, return the play command.
245 * slave_lock is held on both entry and exit of this function. */
246 static char *
247 next_command(int cmd_id)
249 if (cmd_id == -1) return gtp_cmds;
251 int last_id = atoi(gtp_cmd);
252 int reply_move = move_number(cmd_id);
253 if (reply_move > move_number(last_id)) return gtp_cmds;
255 int slot;
256 for (slot = 0; slot < MAX_CMDS_PER_MOVE; slot++) {
257 if (cmd_id == history[reply_move][slot].gtp_id) break;
259 if (slot == MAX_CMDS_PER_MOVE) return gtp_cmds;
261 char *next = history[reply_move][slot].next_cmd;
262 assert(next);
263 return next;
266 /* Allocate buffers for a slave thread. The state should have been
267 * initialized already as a copy of the default slave state.
268 * slave_lock is not held on either entry or exit of this function. */
269 static void
270 slave_state_alloc(struct slave_state *sstate)
272 for (int n = 0; n < BUFFERS_PER_SLAVE; n++) {
273 sstate->b[n].buf = malloc2(sstate->max_buf_size);
274 sstate->b[n].owner = sstate->thread_id;
276 if (sstate->alloc_hook) sstate->alloc_hook(sstate);
279 /* Get a free binary buffer, first invalidating it in the receive
280 * queue if necessary. In practice all buffers should be used
281 * before they are invalidated, if BUFFERS_PER_SLAVE is large enough.
282 * slave_lock is held on both entry and exit of this function. */
283 static void *
284 get_free_buf(struct slave_state *sstate)
286 int newest = (sstate->newest_buf + 1) & (BUFFERS_PER_SLAVE - 1);
287 sstate->newest_buf = newest;
288 void *buf = sstate->b[newest].buf;
290 if (DEBUGVV(7)) {
291 char b[1024];
292 snprintf(b, sizeof(b),
293 "get free %d index %d buf=%p age %d qlength %d\n", newest,
294 sstate->b[newest].queue_index, buf, queue_age, queue_length);
295 logline(&sstate->client, "? ", b);
298 int index = sstate->b[newest].queue_index;
299 if (index < 0) return buf;
301 /* Invalidate the buffer if the calling thread still owns its previous
302 * entry in the receive queue. The entry may have been overwritten by
303 * another thread, but only after a new move which invalidates the
304 * entire receive queue. */
305 if (receive_queue[index] && receive_queue[index]->owner == sstate->thread_id) {
306 receive_queue[index] = NULL;
308 sstate->b[newest].queue_index = -1;
309 return buf;
312 /* Insert a buffer in the receive queue. It should be the most
313 * recent buffer allocated by the calling thread.
314 * slave_lock is held on both entry and exit of this function. */
315 static void
316 insert_buf(struct slave_state *sstate, void *buf, int size)
318 assert(queue_length < queue_max_length);
320 int newest = sstate->newest_buf;
321 assert(buf == sstate->b[newest].buf);
323 /* Update the buffer if necessary before making it
324 * available to other threads. */
325 if (sstate->insert_hook) sstate->insert_hook(buf, size);
327 if (DEBUGVV(7)) {
328 char b[1024];
329 snprintf(b, sizeof(b),
330 "insert newest %d age %d rq[%d]->%p owner %d\n",
331 newest, queue_age, queue_length, buf, sstate->thread_id);
332 logline(&sstate->client, "? ", b);
334 receive_queue[queue_length] = &sstate->b[newest];
335 receive_queue[queue_length]->size = size;
336 receive_queue[queue_length]->queue_index = queue_length;
337 queue_length++;
340 /* Clear the receive queue. The buffer pointers do not have to be cleared
341 * here, this is done as each buffer is recycled.
342 * slave_lock is held on both entry and exit of this function. */
343 void
344 clear_receive_queue(void)
346 if (DEBUGL(3)) {
347 char buf[1024];
348 snprintf(buf, sizeof(buf), "clear queue, old length %d age %d\n",
349 queue_length, queue_age);
350 logline(NULL, "? ", buf);
352 queue_length = 0;
353 queue_age++;
356 /* Process the reply received from a slave machine.
357 * Copy the ascii part to reply_buf and insert the binary part
358 * (if any) in the receive queue.
359 * Return false if ok, true if the slave is out of sync.
360 * slave_lock is held on both entry and exit of this function. */
361 static bool
362 process_reply(int reply_id, char *reply, char *reply_buf,
363 void *bin_reply, int bin_size, int *last_reply_id,
364 int *reply_slot, struct slave_state *sstate)
366 /* Resend everything if slave returned an error. */
367 if (*reply != '=') {
368 *last_reply_id = -1;
369 return true;
371 /* Make sure we are still in sync. cmd_count may have
372 * changed but the reply is valid as long as cmd_id didn't
373 * change (this only occurs for consecutive genmoves). */
374 int cmd_id = atoi(gtp_cmd);
375 if (reply_id != cmd_id) {
376 *last_reply_id = reply_id;
377 return true;
380 strncpy(reply_buf, reply, CMDS_SIZE);
381 if (reply_id != *last_reply_id)
382 *reply_slot = reply_count++;
383 gtp_replies[*reply_slot] = reply_buf;
385 if (bin_size) insert_buf(sstate, bin_reply, bin_size);
387 pthread_cond_signal(&reply_cond);
388 *last_reply_id = reply_id;
389 return false;
392 /* Get the binary arg for the given command, and update the command
393 * if necessary. For now, only genmoves has a binary argument, and
394 * we return the best stats increments from all other slaves.
395 * Set *bin_size to 0 if the command doesn't take binary arguments,
396 * but still return a buffer, to be used for the reply.
397 * Return NULL if the binary arg is obsolete by the time we have
398 * finished computing it, because a new command is available.
399 * This version only gets the buffer for the reply, to be completed
400 * in future commits.
401 * slave_lock is held on both entry and exit of this function. */
402 void *
403 get_binary_arg(struct slave_state *sstate, char *cmd, int cmd_size, int *bin_size)
405 int cmd_id = atoi(gtp_cmd);
406 void *buf = get_free_buf(sstate);
408 *bin_size = 0;
409 char *s = strchr(cmd, '@');
410 if (!s || !sstate->args_hook) return buf;
412 int size = sstate->args_hook(buf, sstate, cmd_id);
414 /* Check that the command is still valid. */
415 if (atoi(gtp_cmd) != cmd_id) return NULL;
417 /* Set the correct binary size for this slave.
418 * cmd may have been overwritten with new parameters. */
419 *bin_size = size;
420 s = strchr(cmd, '@');
421 assert(s);
422 snprintf(s, cmd + cmd_size - s, "@%d\n", size);
423 return buf;
426 /* Main loop of a slave thread.
427 * Send the current command to the slave machine and wait for a reply.
428 * Resend command history if the slave machine is out of sync.
429 * Returns when the connection with the slave machine is cut.
430 * slave_lock is held on both entry and exit of this function. */
431 static void
432 slave_loop(FILE *f, char *reply_buf, struct slave_state *sstate, bool resend)
434 char *to_send;
435 int last_cmd_count = 0;
436 int last_reply_id = -1;
437 int reply_slot = -1;
438 for (;;) {
439 if (resend) {
440 /* Resend complete or partial history */
441 to_send = next_command(last_reply_id);
442 } else {
443 /* Wait for a new command. */
444 while (last_cmd_count == cmd_count)
445 pthread_cond_wait(&cmd_cond, &slave_lock);
446 to_send = gtp_cmd;
449 /* Command available, send it to slave machine.
450 * If slave was out of sync, send the history.
451 * But first get binary arguments if necessary. */
452 int bin_size = 0;
453 void *bin_buf = get_binary_arg(sstate, gtp_cmd,
454 gtp_cmds + CMDS_SIZE - gtp_cmd,
455 &bin_size);
456 /* Check that the command is still valid. */
457 resend = true;
458 if (!bin_buf) continue;
460 /* Send the command and get the reply, which always ends with \n\n
461 * The slave machine sends "=id reply" or "?id reply"
462 * with id == cmd_id if it is in sync. */
463 last_cmd_count = cmd_count;
464 char buf[CMDS_SIZE];
465 int reply_id = send_command(to_send, bin_buf, &bin_size, f,
466 sstate, buf);
467 if (reply_id == -1) return;
469 resend = process_reply(reply_id, buf, reply_buf, bin_buf, bin_size,
470 &last_reply_id, &reply_slot, sstate);
474 /* Minimimal check of slave identity. Close the file if error. */
475 static bool
476 is_pachi_slave(FILE *f, struct in_addr *client)
478 char buf[1024];
479 fputs("name\n", f);
480 if (!fgets(buf, sizeof(buf), f)
481 || strncasecmp(buf, "= Pachi", 7)
482 || !fgets(buf, sizeof(buf), f)
483 || strcmp(buf, "\n")) {
484 logline(client, "? ", "bad slave\n");
485 fclose(f);
486 sleep(1); // avoid busy loop if error
487 return false;
489 return true;
492 /* Thread sending gtp commands to one slave machine, and
493 * reading replies. If a slave machine dies, this thread waits
494 * for a connection from another slave.
495 * The large buffers are allocated only once we get a first
496 * connection, to avoid wasting memory if max_slaves is too large.
497 * We do not invalidate the received buffers if a slave disconnects;
498 * they are still useful for other slaves. */
499 static void *
500 slave_thread(void *arg)
502 struct slave_state sstate = default_sstate;
503 sstate.thread_id = (long)arg;
505 assert(sstate.slave_sock >= 0);
506 char reply_buf[CMDS_SIZE];
507 bool resend = false;
509 for (;;) {
510 /* Wait for a connection from any slave. */
511 struct in_addr client;
512 int conn = open_server_connection(sstate.slave_sock, &client);
514 FILE *f = fdopen(conn, "r+");
515 if (DEBUGL(2)) {
516 snprintf(reply_buf, sizeof(reply_buf),
517 "new slave, id %d\n", sstate.thread_id);
518 logline(&client, "= ", reply_buf);
520 if (!is_pachi_slave(f, &client)) continue;
522 if (!resend) slave_state_alloc(&sstate);
523 sstate.client = client;
525 pthread_mutex_lock(&slave_lock);
526 active_slaves++;
527 slave_loop(f, reply_buf, &sstate, resend);
529 assert(active_slaves > 0);
530 active_slaves--;
531 // Unblock main thread if it was waiting for this slave.
532 pthread_cond_signal(&reply_cond);
533 pthread_mutex_unlock(&slave_lock);
535 resend = true;
536 if (DEBUGL(2))
537 logline(&client, "= ", "lost slave\n");
538 fclose(f);
542 /* Create a new gtp command for all slaves. The slave lock is held
543 * upon entry and upon return, so the command will actually be
544 * sent when the lock is released. The last command is overwritten
545 * if gtp_cmd points to a non-empty string. cmd is a single word;
546 * args has all arguments and is empty or has a trailing \n */
547 void
548 update_cmd(struct board *b, char *cmd, char *args, bool new_id)
550 assert(gtp_cmd);
551 /* To make sure the slaves are in sync, we ignore the original id
552 * and use the board number plus some random bits as gtp id. */
553 static int gtp_id = -1;
554 int moves = is_reset(cmd) ? 0 : b->moves;
555 if (new_id) {
556 int prev_id = gtp_id;
557 do {
558 /* fast_random() is 16-bit only so the multiplication can't overflow. */
559 gtp_id = force_reply(moves + fast_random(65535) * DIST_GAMELEN);
560 } while (gtp_id == prev_id);
561 reply_count = 0;
563 snprintf(gtp_cmd, gtp_cmds + CMDS_SIZE - gtp_cmd, "%d %s %s",
564 gtp_id, cmd, *args ? args : "\n");
565 cmd_count++;
567 /* Remember history for out-of-sync slaves. */
568 static int slot = 0;
569 static struct cmd_history *last = NULL;
570 if (new_id) {
571 if (last) last->next_cmd = gtp_cmd;
572 slot = (slot + 1) % MAX_CMDS_PER_MOVE;
573 last = &history[moves][slot];
574 last->gtp_id = gtp_id;
575 last->next_cmd = NULL;
577 // Notify the slave threads about the new command.
578 pthread_cond_broadcast(&cmd_cond);
581 /* Update the command history, then create a new gtp command
582 * for all slaves. The slave lock is held upon entry and
583 * upon return, so the command will actually be sent when the
584 * lock is released. cmd is a single word; args has all
585 * arguments and is empty or has a trailing \n */
586 void
587 new_cmd(struct board *b, char *cmd, char *args)
589 // Clear the history when a new game starts:
590 if (!gtp_cmd || is_gamestart(cmd)) {
591 gtp_cmd = gtp_cmds;
592 memset(history, 0, sizeof(history));
593 } else {
594 /* Preserve command history for new slaves.
595 * To indicate that the slave should only reply to
596 * the last command we force the id of previous
597 * commands to be just the move number. */
598 int id = prevent_reply(atoi(gtp_cmd));
599 int len = strspn(gtp_cmd, "0123456789");
600 char buf[32];
601 snprintf(buf, sizeof(buf), "%0*d", len, id);
602 memcpy(gtp_cmd, buf, len);
604 gtp_cmd += strlen(gtp_cmd);
607 // Let the slave threads send the new gtp command:
608 update_cmd(b, cmd, args, true);
611 /* Wait for at least one new reply. Return when at least
612 * min_replies slaves have already replied, or when the
613 * given absolute time is passed.
614 * The replies are returned in gtp_replies[0..reply_count-1]
615 * slave_lock is held on entry and on return. */
616 void
617 get_replies(double time_limit, int min_replies)
619 for (;;) {
620 if (reply_count > 0) {
621 struct timespec ts;
622 double sec;
623 ts.tv_nsec = (int)(modf(time_limit, &sec)*1000000000.0);
624 ts.tv_sec = (int)sec;
625 pthread_cond_timedwait(&reply_cond, &slave_lock, &ts);
626 } else {
627 pthread_cond_wait(&reply_cond, &slave_lock);
629 if (reply_count == 0) continue;
630 if (reply_count >= min_replies || reply_count >= active_slaves) return;
631 if (time_now() >= time_limit) break;
633 if (DEBUGL(1)) {
634 char buf[1024];
635 snprintf(buf, sizeof(buf),
636 "get_replies timeout %.3f >= %.3f, replies %d < min %d, active %d\n",
637 time_now() - start_time, time_limit - start_time,
638 reply_count, min_replies, active_slaves);
639 logline(NULL, "? ", buf);
641 assert(reply_count > 0);
644 /* In a 5mn move with at least 5ms per genmoves we get at most
645 * 300*200=60000 genmoves per slave. */
646 #define MAX_GENMOVES_PER_SLAVE 60000
648 /* Allocate the receive queue, and create the slave and proxy threads.
649 * max_buf_size and the merge-related fields of default_sstate must
650 * already be initialized. */
651 void
652 protocol_init(char *slave_port, char *proxy_port, int max_slaves)
654 start_time = time_now();
656 queue_max_length = max_slaves * MAX_GENMOVES_PER_SLAVE;
657 receive_queue = calloc2(queue_max_length, sizeof(*receive_queue));
659 default_sstate.slave_sock = port_listen(slave_port, max_slaves);
660 default_sstate.last_processed = -1;
662 for (int n = 0; n < BUFFERS_PER_SLAVE; n++) {
663 default_sstate.b[n].queue_index = -1;
666 pthread_t thread;
667 for (int id = 0; id < max_slaves; id++) {
668 pthread_create(&thread, NULL, slave_thread, (void *)(long)id);
671 if (proxy_port) {
672 int proxy_sock = port_listen(proxy_port, max_slaves);
673 for (int id = 0; id < max_slaves; id++) {
674 pthread_create(&thread, NULL, proxy_thread, (void *)(long)proxy_sock);