Distributed engine: force waiting for a new command after a successful reply is received.
[pachi/derm.git] / distributed / distributed.c
blobeb220931226fddca1b29f13620d29975d92bc7e1
1 /* This is a master for the "distributed" engine. It receives connections
2 * from slave machines, sends them gtp commands, then aggregates the
3 * results. It can also act as a proxy for the logs of all slave machines.
4 * The slave machines must run with engine "uct" (not "distributed").
5 * The master sends pachi-genmoves gtp commands regularly to each slave,
6 * gets as replies a list of candidate moves, their number of playouts
7 * and their value. The master then picks the most popular move. */
9 /* With time control, the master waits for all slaves, except
10 * when the allowed time is already passed. In this case the
11 * master picks among the available replies, or waits for just
12 * one reply if there is none yet.
13 * Without time control, the master waits until the desired
14 * number of games have been simulated. In this case the -t
15 * parameter for the master should be the sum of the parameters
16 * for all slaves. */
18 /* The master sends updated statistics for the best moves
19 * in each genmoves command. In this version only the
20 * children of the root node are updated. The slaves
21 * reply with just their own stats; they remember what was
22 * previously received from or sent to the master, to
23 * distinguish their own contribution from that of other slaves. */
25 /* The master-slave protocol has has fault tolerance. If a slave is
26 * out of sync, the master sends it the appropriate command history. */
28 /* Pass me arguments like a=b,c=d,...
29 * Supported arguments:
30 * slave_port=SLAVE_PORT slaves connect to this port; this parameter is mandatory.
31 * max_slaves=MAX_SLAVES default 100
32 * slaves_quit=0|1 quit gtp command also sent to slaves, default false.
33 * proxy_port=PROXY_PORT slaves optionally send their logs to this port.
34 * Warning: with proxy_port, the master stderr mixes the logs of all
35 * machines but you can separate them again:
36 * slave logs: sed -n '/< .*:/s/.*< /< /p' logfile
37 * master logs: perl -0777 -pe 's/<[ <].*:.*\n//g' logfile
40 /* A configuration without proxy would have one master run on masterhost as:
41 * zzgo -e distributed slave_port=1234
42 * and N slaves running as:
43 * zzgo -e uct -g masterhost:1234 slave
44 * With log proxy:
45 * zzgo -e distributed slave_port=1234,proxy_port=1235
46 * zzgo -e uct -g masterhost:1234 -l masterhost:1235 slave
47 * If the master itself runs on a machine other than that running gogui,
48 * gogui-twogtp, kgsGtp or cgosGtp, it can redirect its gtp port:
49 * zzgo -e distributed -g 10000 slave_port=1234,proxy_port=1235
52 #include <assert.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <pthread.h>
57 #include <limits.h>
58 #include <ctype.h>
59 #include <time.h>
60 #include <alloca.h>
61 #include <sys/types.h>
62 #include <sys/socket.h>
63 #include <arpa/inet.h>
65 #define DEBUG
67 #include "board.h"
68 #include "engine.h"
69 #include "move.h"
70 #include "timeinfo.h"
71 #include "network.h"
72 #include "playout.h"
73 #include "random.h"
74 #include "stats.h"
75 #include "mq.h"
76 #include "debug.h"
77 #include "distributed/distributed.h"
79 /* Internal engine state. */
80 struct distributed {
81 char *slave_port;
82 char *proxy_port;
83 int max_slaves;
84 bool slaves_quit;
85 struct move my_last_move;
86 struct move_stats my_last_stats;
89 /* Default number of simulations to perform per move.
90 * Note that this is in total over all slaves! */
91 #define DIST_GAMES 80000
92 static const struct time_info default_ti = {
93 .period = TT_MOVE,
94 .dim = TD_GAMES,
95 .len = { .games = DIST_GAMES },
98 #define get_value(value, color) \
99 ((color) == S_BLACK ? (value) : 1 - (value))
101 /* Max size for one line of reply or slave log. */
102 #define BSIZE 4096
104 /* Max size of all gtp commands for one game.
105 * 60 chars for the first line of genmoves plus 100 lines
106 * of 30 chars each for the stats at last move. */
107 #define CMDS_SIZE (60*MAX_GAMELEN + 30*100)
109 /* All gtp commands for current game separated by \n */
110 static char gtp_cmds[CMDS_SIZE];
112 /* Latest gtp command sent to slaves. */
113 static char *gtp_cmd = NULL;
115 /* Slaves send gtp_cmd when cmd_count changes. */
116 static int cmd_count = 0;
118 /* Remember at most 12 gtp ids per move: play pass,
119 * 10 genmoves (1s), play pass.
120 * For move 0 we always resend the whole history. */
121 #define MAX_CMDS_PER_MOVE 12
123 /* History of gtp commands sent for current game, indexed by move. */
124 static int id_history[MAX_GAMELEN][MAX_CMDS_PER_MOVE];
125 static char *cmd_history[MAX_GAMELEN][MAX_CMDS_PER_MOVE];
127 /* Number of active slave machines working for this master. */
128 static int active_slaves = 0;
130 /* Number of replies to last gtp command already received. */
131 static int reply_count = 0;
133 /* All replies to latest gtp command are in gtp_replies[0..reply_count-1]. */
134 static char **gtp_replies;
136 /* Mutex protecting gtp_cmds, gtp_cmd, id_history, cmd_history,
137 * cmd_count, active_slaves, reply_count & gtp_replies */
138 static pthread_mutex_t slave_lock = PTHREAD_MUTEX_INITIALIZER;
140 /* Condition signaled when a new gtp command is available. */
141 static pthread_cond_t cmd_cond = PTHREAD_COND_INITIALIZER;
143 /* Condition signaled when reply_count increases. */
144 static pthread_cond_t reply_cond = PTHREAD_COND_INITIALIZER;
146 /* Mutex protecting stderr. Must not be held at same time as slave_lock. */
147 static pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER;
149 /* Absolute time when this program was started.
150 * For debugging only. */
151 static double start_time;
153 /* Write the time, client address, prefix, and string s to stderr atomically.
154 * s should end with a \n */
155 static void
156 logline(struct in_addr *client, char *prefix, char *s)
158 double now = time_now();
159 char addr[INET_ADDRSTRLEN];
160 if (client) {
161 inet_ntop(AF_INET, client, addr, sizeof(addr));
162 } else {
163 addr[0] = '\0';
165 pthread_mutex_lock(&log_lock);
166 fprintf(stderr, "%s%15s %9.3f: %s", prefix, addr, now - start_time, s);
167 pthread_mutex_unlock(&log_lock);
170 /* Thread opening a connection on the given socket and copying input
171 * from there to stderr. */
172 static void *
173 proxy_thread(void *arg)
175 int proxy_sock = (long)arg;
176 assert(proxy_sock >= 0);
177 for (;;) {
178 struct in_addr client;
179 int conn = open_server_connection(proxy_sock, &client);
180 FILE *f = fdopen(conn, "r");
181 char buf[BSIZE];
182 while (fgets(buf, BSIZE, f)) {
183 logline(&client, "< ", buf);
185 fclose(f);
189 /* Get a reply to one gtp command. Return the gtp command id,
190 * or -1 if error. reply must have at least CMDS_SIZE bytes.
191 * slave_lock is not held on either entry or exit of this function. */
192 static int
193 get_reply(FILE *f, struct in_addr client, char *reply)
195 int reply_id = -1;
196 *reply = '\0';
197 char *line = reply;
198 while (fgets(line, reply + CMDS_SIZE - line, f) && *line != '\n') {
199 if (DEBUGL(2))
200 logline(&client, "<<", line);
201 if (reply_id < 0 && (*line == '=' || *line == '?') && isdigit(line[1]))
202 reply_id = atoi(line+1);
203 line += strlen(line);
205 if (*line != '\n') return -1;
206 return reply_id;
209 /* Main loop of a slave thread.
210 * Send the current command to the slave machine and wait for a reply.
211 * Resend command history if the slave machine is out of sync.
212 * Returns when the connection with the slave machine is cut.
213 * slave_lock is held on both entry and exit of this function. */
214 static void
215 slave_loop(FILE *f, struct in_addr client, char *reply_buf, bool resend)
217 char *to_send = gtp_cmd;
218 int last_cmd_sent = 0;
219 int last_reply_id = -1;
220 int reply_slot = -1;
221 for (;;) {
222 while (last_cmd_sent == cmd_count && !resend) {
223 // Wait for a new gtp command.
224 pthread_cond_wait(&cmd_cond, &slave_lock);
225 to_send = gtp_cmd;
228 /* Command available, send it to slave machine.
229 * If slave was out of sync, send the history. */
230 assert(to_send && gtp_cmd);
231 char buf[CMDS_SIZE];
232 strncpy(buf, to_send, CMDS_SIZE);
233 last_cmd_sent = cmd_count;
235 pthread_mutex_unlock(&slave_lock);
237 if (DEBUGL(1) && resend) {
238 if (to_send == gtp_cmds) {
239 logline(&client, "? ", "Slave out-of-sync, resending all history\n");
240 } else {
241 logline(&client, "? ", "Slave behind, partial resend\n");
244 if (DEBUGL(2))
245 logline(&client, ">>", buf);
246 fputs(buf, f);
247 fflush(f);
249 /* Read the reply, which always ends with \n\n
250 * The slave machine sends "=id reply" or "?id reply"
251 * with id == cmd_id if it is in sync. */
252 int reply_id = get_reply(f, client, buf);
254 pthread_mutex_lock(&slave_lock);
255 if (reply_id == -1) return;
257 /* Make sure we are still in sync. cmd_count may have
258 * changed but the reply is valid as long as cmd_id didn't
259 * change (this only occurs for consecutive genmoves). */
260 int cmd_id = atoi(gtp_cmd);
261 if (reply_id == cmd_id && *buf == '=') {
262 resend = false;
263 strncpy(reply_buf, buf, CMDS_SIZE);
264 if (reply_id != last_reply_id)
265 reply_slot = reply_count++;
266 gtp_replies[reply_slot] = reply_buf;
267 last_reply_id = reply_id;
269 pthread_cond_signal(&reply_cond);
271 /* Force waiting for a new command. The next genmoves
272 * stats we will send must include those just received
273 * (this assumed by the slave). */
274 last_cmd_sent = cmd_count;
275 continue;
277 resend = true;
278 to_send = gtp_cmds;
279 /* Resend everything if slave got latest command,
280 * but doesn't have a correct board. */
281 if (reply_id == cmd_id) continue;
283 /* The slave is ouf-of-sync. Check whether the last command
284 * it received belongs to the current game. If so resend
285 * starting at the last move known by slave, otherwise
286 * resend the whole history. */
287 int reply_move = move_number(reply_id);
288 if (reply_move > move_number(cmd_id)) continue;
290 for (int slot = 0; slot < MAX_CMDS_PER_MOVE; slot++) {
291 if (reply_id == id_history[reply_move][slot]) {
292 to_send = cmd_history[reply_move][slot];
293 break;
299 /* Thread sending gtp commands to one slave machine, and
300 * reading replies. If a slave machine dies, this thread waits
301 * for a connection from another slave. */
302 static void *
303 slave_thread(void *arg)
305 int slave_sock = (long)arg;
306 assert(slave_sock >= 0);
307 char reply_buf[CMDS_SIZE];
308 bool resend = false;
310 for (;;) {
311 /* Wait for a connection from any slave. */
312 struct in_addr client;
313 int conn = open_server_connection(slave_sock, &client);
315 FILE *f = fdopen(conn, "r+");
316 if (DEBUGL(2))
317 logline(&client, "= ", "new slave\n");
319 /* Minimal check of the slave identity. */
320 fputs("name\n", f);
321 if (!fgets(reply_buf, sizeof(reply_buf), f)
322 || strncasecmp(reply_buf, "= Pachi", 7)
323 || !fgets(reply_buf, sizeof(reply_buf), f)
324 || strcmp(reply_buf, "\n")) {
325 logline(&client, "? ", "bad slave\n");
326 fclose(f);
327 continue;
330 pthread_mutex_lock(&slave_lock);
331 active_slaves++;
332 slave_loop(f, client, reply_buf, resend);
334 assert(active_slaves > 0);
335 active_slaves--;
336 // Unblock main thread if it was waiting for this slave.
337 pthread_cond_signal(&reply_cond);
338 pthread_mutex_unlock(&slave_lock);
340 resend = true;
341 if (DEBUGL(2))
342 logline(&client, "= ", "lost slave\n");
343 fclose(f);
347 /* Create a new gtp command for all slaves. The slave lock is held
348 * upon entry and upon return, so the command will actually be
349 * sent when the lock is released. The last command is overwritten
350 * if gtp_cmd points to a non-empty string. cmd is a single word;
351 * args has all arguments and is empty or has a trailing \n */
352 static void
353 update_cmd(struct board *b, char *cmd, char *args, bool new_id)
355 assert(gtp_cmd);
356 /* To make sure the slaves are in sync, we ignore the original id
357 * and use the board number plus some random bits as gtp id. */
358 static int gtp_id = -1;
359 int moves = is_reset(cmd) ? 0 : b->moves;
360 if (new_id) {
361 /* fast_random() is 16-bit only so the multiplication can't overflow. */
362 gtp_id = force_reply(moves + fast_random(65535) * DIST_GAMELEN);
363 reply_count = 0;
365 snprintf(gtp_cmd, gtp_cmds + CMDS_SIZE - gtp_cmd, "%d %s %s",
366 gtp_id, cmd, *args ? args : "\n");
367 cmd_count++;
369 /* Remember history for out-of-sync slaves. */
370 static int slot = 0;
371 slot = (slot + 1) % MAX_CMDS_PER_MOVE;
372 id_history[moves][slot] = gtp_id;
373 cmd_history[moves][slot] = gtp_cmd;
375 // Notify the slave threads about the new command.
376 pthread_cond_broadcast(&cmd_cond);
379 /* Update the command history, then create a new gtp command
380 * for all slaves. The slave lock is held upon entry and
381 * upon return, so the command will actually be sent when the
382 * lock is released. cmd is a single word; args has all
383 * arguments and is empty or has a trailing \n */
384 static void
385 new_cmd(struct board *b, char *cmd, char *args)
387 // Clear the history when a new game starts:
388 if (!gtp_cmd || is_gamestart(cmd)) {
389 gtp_cmd = gtp_cmds;
390 } else {
391 /* Preserve command history for new slaves.
392 * To indicate that the slave should only reply to
393 * the last command we force the id of previous
394 * commands to be just the move number. */
395 int id = prevent_reply(atoi(gtp_cmd));
396 int len = strspn(gtp_cmd, "0123456789");
397 char buf[32];
398 snprintf(buf, sizeof(buf), "%0*d", len, id);
399 memcpy(gtp_cmd, buf, len);
401 gtp_cmd += strlen(gtp_cmd);
404 // Let the slave threads send the new gtp command:
405 update_cmd(b, cmd, args, true);
408 /* Wait for at least one new reply. Return when all slaves have
409 * replied, or when the given absolute time is passed.
410 * The replies are returned in gtp_replies[0..reply_count-1]
411 * slave_lock is held on entry and on return. */
412 static void
413 get_replies(double time_limit)
415 for (;;) {
416 if (reply_count > 0) {
417 struct timespec ts;
418 double sec;
419 ts.tv_nsec = (int)(modf(time_limit, &sec)*1000000000.0);
420 ts.tv_sec = (int)sec;
421 pthread_cond_timedwait(&reply_cond, &slave_lock, &ts);
422 } else {
423 pthread_cond_wait(&reply_cond, &slave_lock);
425 if (reply_count == 0) continue;
426 if (reply_count >= active_slaves) return;
427 if (time_now() >= time_limit) break;
429 if (DEBUGL(1)) {
430 char buf[1024];
431 snprintf(buf, sizeof(buf),
432 "get_replies timeout %.3f >= %.3f, replies %d < active %d\n",
433 time_now() - start_time, time_limit - start_time,
434 reply_count, active_slaves);
435 logline(NULL, "? ", buf);
437 assert(reply_count > 0);
440 /* Maximum time (seconds) to wait for answers to fast gtp commands
441 * (all commands except pachi-genmoves and final_status_list). */
442 #define MAX_FAST_CMD_WAIT 1.0
444 /* How often to send a stats update to slaves (seconds) */
445 #define STATS_UPDATE_INTERVAL 0.1 /* 100ms */
447 /* Maximum time (seconds) to wait between genmoves
448 * (all commands except pachi-genmoves and final_status_list). */
449 #define MAX_FAST_CMD_WAIT 1.0
451 /* Dispatch a new gtp command to all slaves.
452 * The slave lock must not be held upon entry and is released upon return.
453 * args is empty or ends with '\n' */
454 static enum parse_code
455 distributed_notify(struct engine *e, struct board *b, int id, char *cmd, char *args, char **reply)
457 struct distributed *dist = e->data;
459 /* Commands that should not be sent to slaves.
460 * time_left will be part of next pachi-genmoves,
461 * we reduce latency by not forwarding it here. */
462 if ((!strcasecmp(cmd, "quit") && !dist->slaves_quit)
463 || !strcasecmp(cmd, "uct_genbook")
464 || !strcasecmp(cmd, "uct_dumpbook")
465 || !strcasecmp(cmd, "kgs-chat")
466 || !strcasecmp(cmd, "time_left")
468 /* and commands that will be sent to slaves later */
469 || !strcasecmp(cmd, "genmove")
470 || !strcasecmp(cmd, "kgs-genmove_cleanup")
471 || !strcasecmp(cmd, "final_score")
472 || !strcasecmp(cmd, "final_status_list"))
473 return P_OK;
475 pthread_mutex_lock(&slave_lock);
477 // Create a new command to be sent by the slave threads.
478 new_cmd(b, cmd, args);
480 /* Wait for replies here. If we don't wait, we run the
481 * risk of getting out of sync with most slaves and
482 * sending command history too frequently. */
483 get_replies(time_now() + MAX_FAST_CMD_WAIT);
485 pthread_mutex_unlock(&slave_lock);
486 return P_OK;
489 /* genmoves returns a line "=id total_playouts threads keep_looking[ reserved]"
490 * then a list of lines "coord playouts value".
491 * Return the move with most playouts, and additional stats.
492 * all_stats gathers the stats from all slaves except for
493 * pass and resign; it must have room up to end and upon return
494 * ends with an empty line.
495 * Keep this code in sync with uct_getstats().
496 * slave_lock is held on entry and on return. */
497 static coord_t
498 select_best_move(struct board *b, struct move_stats *best_stats,
499 int *total_playouts, int *total_threads,
500 char *all_stats, char *end, bool *keep_looking)
502 assert(reply_count > 0);
504 /* +2 for pass and resign. */
505 struct move_stats *stats = alloca((board_size2(b)+2) * sizeof(struct move_stats));
506 memset(stats, 0, (board_size2(b)+2) * sizeof(*stats));
507 stats += 2;
509 coord_t best_move = pass;
510 int best_playouts = -1;
511 *total_playouts = 0;
512 *total_threads = 0;
513 int keep = 0;
515 for (int reply = 0; reply < reply_count; reply++) {
516 char *r = gtp_replies[reply];
517 int id, p, t, k;
518 if (sscanf(r, "=%d %d %d %d", &id, &p, &t, &k) != 4) continue;
519 *total_playouts += p;
520 *total_threads += t;
521 keep += k;
522 // Skip the rest of the firt line if any (allow future extensions)
523 r = strchr(r, '\n');
525 char move[64];
526 struct move_stats s;
527 while (r && sscanf(++r, "%63s %d %f", move, &s.playouts, &s.value) == 3) {
528 coord_t *c = str2coord(move, board_size(b));
529 stats_add_result(&stats[*c], s.value, s.playouts);
530 if (stats[*c].playouts > best_playouts) {
531 best_playouts = stats[*c].playouts;
532 best_move = *c;
534 coord_done(c);
535 r = strchr(r, '\n');
538 char *s = all_stats;
539 int min_playouts = best_playouts / 100;
540 /* Send stats for all moves except pass and resign. */
541 foreach_point(b) {
542 if (stats[c].playouts <= min_playouts) continue;
543 s += snprintf(s, end - s, "%s %d %.7f\n",
544 coord2sstr(c, b),
545 stats[c].playouts, stats[c].value);
546 } foreach_point_end;
547 s += snprintf(s, end - s, "\n");
549 *best_stats = stats[best_move];
550 *keep_looking = keep > reply_count / 2;
551 return best_move;
554 /* Time control is mostly done by the slaves, so we use default values here. */
555 #define FUSEKI_END 20
556 #define YOSE_START 40
558 static coord_t *
559 distributed_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
561 struct distributed *dist = e->data;
562 double now = time_now();
563 double first = now;
565 char *cmd = pass_all_alive ? "pachi-genmoves_cleanup" : "pachi-genmoves";
566 char args[CMDS_SIZE];
567 char *end = args + sizeof(args);
569 coord_t best;
570 int playouts, threads;
571 struct move_stats best_stats;
573 if (ti->period == TT_NULL) *ti = default_ti;
574 struct time_stop stop;
575 time_stop_conditions(ti, b, FUSEKI_END, YOSE_START, &stop);
576 struct time_info saved_ti = *ti;
578 /* Send the first genmoves without stats. This is
579 * a multi-line command ending with \n\n.
580 * Keep this code in sync with uct_genmoves(). */
581 char *col = args + snprintf(args, sizeof(args), "%s", stone2str(color));
582 char *s = col;
583 if (ti->dim == TD_WALLTIME) {
584 s += snprintf(s, end - s, " %.3f %.3f %d %d",
585 ti->len.t.main_time, ti->len.t.byoyomi_time,
586 ti->len.t.byoyomi_periods, ti->len.t.byoyomi_stones);
588 s += snprintf(s, end - s, "\n\n");
590 pthread_mutex_lock(&slave_lock);
591 new_cmd(b, cmd, args);
593 /* Loop until most slaves want to quit or time elapsed. */
594 for (;;) {
595 double start = now;
596 get_replies(now + STATS_UPDATE_INTERVAL);
597 now = time_now();
598 s = col;
599 if (ti->dim == TD_WALLTIME) {
600 time_sub(ti, now - start);
601 s += snprintf(s, end - s, " %.3f %.3f %d %d",
602 ti->len.t.main_time, ti->len.t.byoyomi_time,
603 ti->len.t.byoyomi_periods, ti->len.t.byoyomi_stones);
605 s += snprintf(s, end - s, "\n");
606 bool keep_looking;
607 best = select_best_move(b, &best_stats, &playouts,
608 &threads, s, end, &keep_looking);
610 if (!keep_looking) break;
611 if (ti->dim == TD_WALLTIME) {
612 if (now - ti->len.t.timer_start >= stop.worst.time) break;
613 } else {
614 if (playouts >= stop.worst.playouts) break;
616 if (DEBUGL(2)) {
617 char buf[BSIZE];
618 char *coord = coord2sstr(best, b);
619 snprintf(buf, sizeof(buf),
620 "temp winner is %s %s with score %1.4f (%d/%d games)"
621 " %d slaves %d threads\n",
622 stone2str(color), coord, get_value(best_stats.value, color),
623 best_stats.playouts, playouts, reply_count, threads);
624 logline(NULL, "* ", buf);
626 /* Send the command with the same gtp id, to avoid discarding
627 * a reply to a previous genmoves at the same move. */
628 update_cmd(b, cmd, args, false);
630 int replies = reply_count;
632 /* Do not subtract time spent twice (see gtp_parse). */
633 *ti = saved_ti;
635 dist->my_last_move.color = color;
636 dist->my_last_move.coord = best;
637 dist->my_last_stats = best_stats;
639 /* Tell the slaves to commit to the selected move, overwriting
640 * the last "pachi-genmoves" in the command history. */
641 char *coord = coord2str(best, b);
642 snprintf(args, sizeof(args), "%s %s\n", stone2str(color), coord);
643 update_cmd(b, "play", args, true);
644 pthread_mutex_unlock(&slave_lock);
646 if (DEBUGL(1)) {
647 char buf[BSIZE];
648 double time = now - first + 0.000001; /* avoid divide by zero */
649 snprintf(buf, sizeof(buf),
650 "GLOBAL WINNER is %s %s with score %1.4f (%d/%d games)\n"
651 "genmove in %0.2fs %d slaves %d threads (%d games/s,"
652 " %d games/s/slave, %d games/s/thread)\n",
653 stone2str(color), coord, get_value(best_stats.value, color),
654 best_stats.playouts, playouts, time, replies, threads,
655 (int)(playouts/time), (int)(playouts/time/replies),
656 (int)(playouts/time/threads));
657 logline(NULL, "* ", buf);
659 free(coord);
660 return coord_copy(best);
663 static char *
664 distributed_chat(struct engine *e, struct board *b, char *cmd)
666 struct distributed *dist = e->data;
667 static char reply[BSIZE];
669 cmd += strspn(cmd, " \n\t");
670 if (!strncasecmp(cmd, "winrate", 7)) {
671 enum stone color = dist->my_last_move.color;
672 snprintf(reply, BSIZE, "In %d playouts at %d machines, %s %s can win with %.2f%% probability.",
673 dist->my_last_stats.playouts, active_slaves, stone2str(color),
674 coord2sstr(dist->my_last_move.coord, b),
675 100 * get_value(dist->my_last_stats.value, color));
676 return reply;
678 return NULL;
681 static int
682 scmp(const void *p1, const void *p2)
684 return strcasecmp(*(char * const *)p1, *(char * const *)p2);
687 static void
688 distributed_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
690 pthread_mutex_lock(&slave_lock);
692 new_cmd(b, "final_status_list", "dead\n");
693 get_replies(time_now() + MAX_FAST_CMD_WAIT);
695 /* Find the most popular reply. */
696 qsort(gtp_replies, reply_count, sizeof(char *), scmp);
697 int best_reply = 0;
698 int best_count = 1;
699 int count = 1;
700 for (int reply = 1; reply < reply_count; reply++) {
701 if (!strcmp(gtp_replies[reply], gtp_replies[reply-1])) {
702 count++;
703 } else {
704 count = 1;
706 if (count > best_count) {
707 best_count = count;
708 best_reply = reply;
712 /* Pick the first move of each line as group. */
713 char *dead = gtp_replies[best_reply];
714 dead = strchr(dead, ' '); // skip "id "
715 while (dead && *++dead != '\n') {
716 coord_t *c = str2coord(dead, board_size(b));
717 mq_add(mq, *c);
718 coord_done(c);
719 dead = strchr(dead, '\n');
721 pthread_mutex_unlock(&slave_lock);
724 static struct distributed *
725 distributed_state_init(char *arg, struct board *b)
727 struct distributed *dist = calloc(1, sizeof(struct distributed));
729 dist->max_slaves = 100;
730 if (arg) {
731 char *optspec, *next = arg;
732 while (*next) {
733 optspec = next;
734 next += strcspn(next, ",");
735 if (*next) { *next++ = 0; } else { *next = 0; }
737 char *optname = optspec;
738 char *optval = strchr(optspec, '=');
739 if (optval) *optval++ = 0;
741 if (!strcasecmp(optname, "slave_port") && optval) {
742 dist->slave_port = strdup(optval);
743 } else if (!strcasecmp(optname, "proxy_port") && optval) {
744 dist->proxy_port = strdup(optval);
745 } else if (!strcasecmp(optname, "max_slaves") && optval) {
746 dist->max_slaves = atoi(optval);
747 } else if (!strcasecmp(optname, "slaves_quit")) {
748 dist->slaves_quit = !optval || atoi(optval);
749 } else {
750 fprintf(stderr, "distributed: Invalid engine argument %s or missing value\n", optname);
755 gtp_replies = calloc(dist->max_slaves, sizeof(char *));
757 if (!dist->slave_port) {
758 fprintf(stderr, "distributed: missing slave_port\n");
759 exit(1);
761 int slave_sock = port_listen(dist->slave_port, dist->max_slaves);
762 pthread_t thread;
763 for (int id = 0; id < dist->max_slaves; id++) {
764 pthread_create(&thread, NULL, slave_thread, (void *)(long)slave_sock);
767 if (dist->proxy_port) {
768 int proxy_sock = port_listen(dist->proxy_port, dist->max_slaves);
769 for (int id = 0; id < dist->max_slaves; id++) {
770 pthread_create(&thread, NULL, proxy_thread, (void *)(long)proxy_sock);
773 return dist;
776 struct engine *
777 engine_distributed_init(char *arg, struct board *b)
779 start_time = time_now();
780 struct distributed *dist = distributed_state_init(arg, b);
781 struct engine *e = calloc(1, sizeof(struct engine));
782 e->name = "Distributed Engine";
783 e->comment = "I'm playing the distributed engine. When I'm losing, I will resign, "
784 "if I think I win, I play until you pass. "
785 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
786 e->notify = distributed_notify;
787 e->genmove = distributed_genmove;
788 e->dead_group_list = distributed_dead_group_list;
789 e->chat = distributed_chat;
790 e->data = dist;
791 // Keep the threads and the open socket connections:
792 e->keep_on_clear = true;
794 return e;