Distributed engine: accept reply to a previous genmoves at same move.
[pachi.git] / distributed / distributed.c
blobc4dfbf1f24c0a6b1f93079ab8cd6d10a72f9cbb3
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 static coord_t select_best_move(struct board *b, struct move_stats *best_stats,
90 int *total_playouts, int *total_threads,
91 char *all_stats, char *end, bool *keep_looking);
93 /* Default number of simulations to perform per move.
94 * Note that this is in total over all slaves! */
95 #define DIST_GAMES 80000
96 static const struct time_info default_ti = {
97 .period = TT_MOVE,
98 .dim = TD_GAMES,
99 .len = { .games = DIST_GAMES },
102 #define get_value(value, color) \
103 ((color) == S_BLACK ? (value) : 1 - (value))
105 /* Max size for one line of reply or slave log. */
106 #define BSIZE 4096
108 /* Max size of all gtp commands for one game.
109 * 60 chars for the first line of genmoves plus 100 lines
110 * of 30 chars each for the stats at last move. */
111 #define CMDS_SIZE (60*MAX_GAMELEN + 30*100)
113 /* All gtp commands for current game separated by \n */
114 static char gtp_cmds[CMDS_SIZE];
116 /* Latest gtp command sent to slaves. */
117 static char *gtp_cmd = NULL;
119 /* Slaves send gtp_cmd when cmd_count changes. */
120 static int cmd_count = 0;
122 /* Remember at most 12 gtp ids per move: play pass,
123 * 10 genmoves (1s), play pass.
124 * For move 0 we always resend the whole history. */
125 #define MAX_CMDS_PER_MOVE 12
127 /* History of gtp commands sent for current game, indexed by move. */
128 static int id_history[MAX_GAMELEN][MAX_CMDS_PER_MOVE];
129 static char *cmd_history[MAX_GAMELEN][MAX_CMDS_PER_MOVE];
131 /* Number of active slave machines working for this master. */
132 static int active_slaves = 0;
134 /* Number of replies to last gtp command already received. */
135 static int reply_count = 0;
137 /* All replies to latest gtp command are in gtp_replies[0..reply_count-1]. */
138 static char **gtp_replies;
140 /* Mutex protecting gtp_cmds, gtp_cmd, id_history, cmd_history,
141 * cmd_count, active_slaves, reply_count & gtp_replies */
142 static pthread_mutex_t slave_lock = PTHREAD_MUTEX_INITIALIZER;
144 /* Condition signaled when a new gtp command is available. */
145 static pthread_cond_t cmd_cond = PTHREAD_COND_INITIALIZER;
147 /* Condition signaled when reply_count increases. */
148 static pthread_cond_t reply_cond = PTHREAD_COND_INITIALIZER;
150 /* Mutex protecting stderr. Must not be held at same time as slave_lock. */
151 static pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER;
153 /* Absolute time when this program was started.
154 * For debugging only. */
155 static double start_time;
157 /* Write the time, client address, prefix, and string s to stderr atomically.
158 * s should end with a \n */
159 static void
160 logline(struct in_addr *client, char *prefix, char *s)
162 double now = time_now();
163 char addr[INET_ADDRSTRLEN];
164 if (client) {
165 inet_ntop(AF_INET, client, addr, sizeof(addr));
166 } else {
167 addr[0] = '\0';
169 pthread_mutex_lock(&log_lock);
170 fprintf(stderr, "%s%15s %9.3f: %s", prefix, addr, now - start_time, s);
171 pthread_mutex_unlock(&log_lock);
174 /* Thread opening a connection on the given socket and copying input
175 * from there to stderr. */
176 static void *
177 proxy_thread(void *arg)
179 int proxy_sock = (long)arg;
180 assert(proxy_sock >= 0);
181 for (;;) {
182 struct in_addr client;
183 int conn = open_server_connection(proxy_sock, &client);
184 FILE *f = fdopen(conn, "r");
185 char buf[BSIZE];
186 while (fgets(buf, BSIZE, f)) {
187 logline(&client, "< ", buf);
189 fclose(f);
193 /* Get a reply to one gtp command. Return the gtp command id,
194 * or -1 if error. reply must have at least CMDS_SIZE bytes.
195 * slave_lock is not held on either entry or exit of this function. */
196 static int
197 get_reply(FILE *f, struct in_addr client, char *reply)
199 int reply_id = -1;
200 *reply = '\0';
201 char *line = reply;
202 while (fgets(line, reply + CMDS_SIZE - line, f) && *line != '\n') {
203 if (DEBUGL(2))
204 logline(&client, "<<", line);
205 if (reply_id < 0 && (*line == '=' || *line == '?') && isdigit(line[1]))
206 reply_id = atoi(line+1);
207 line += strlen(line);
209 if (*line != '\n') return -1;
210 return reply_id;
213 /* Main loop of a slave thread.
214 * Send the current command to the slave machine and wait for a reply.
215 * Resend command history if the slave machine is out of sync.
216 * Returns when the connection with the slave machine is cut.
217 * slave_lock is held on both entry and exit of this function. */
218 static void
219 slave_loop(FILE *f, struct in_addr client, char *reply_buf, bool resend)
221 char *to_send = gtp_cmd;
222 int last_cmd_sent = 0;
223 int last_reply_id = -1;
224 int reply_slot = -1;
225 for (;;) {
226 while (last_cmd_sent == cmd_count && !resend) {
227 // Wait for a new gtp command.
228 pthread_cond_wait(&cmd_cond, &slave_lock);
229 to_send = gtp_cmd;
232 /* Command available, send it to slave machine.
233 * If slave was out of sync, send the history. */
234 assert(to_send && gtp_cmd);
235 char buf[CMDS_SIZE];
236 strncpy(buf, to_send, CMDS_SIZE);
237 last_cmd_sent = cmd_count;
239 pthread_mutex_unlock(&slave_lock);
241 if (DEBUGL(1) && resend) {
242 if (to_send == gtp_cmds) {
243 logline(&client, "? ", "Slave out-of-sync, resending all history\n");
244 } else {
245 logline(&client, "? ", "Slave behind, partial resend\n");
248 if (DEBUGL(2))
249 logline(&client, ">>", buf);
250 fputs(buf, f);
251 fflush(f);
253 /* Read the reply, which always ends with \n\n
254 * The slave machine sends "=id reply" or "?id reply"
255 * with id == cmd_id if it is in sync. */
256 int reply_id = get_reply(f, client, buf);
258 pthread_mutex_lock(&slave_lock);
259 if (reply_id == -1) return;
261 /* Make sure we are still in sync. cmd_count may have
262 * changed but the reply is valid as long as cmd_id didn't
263 * change (this only occurs for consecutive genmoves). */
264 int cmd_id = atoi(gtp_cmd);
265 if (reply_id == cmd_id && *buf == '=') {
266 resend = false;
267 strncpy(reply_buf, buf, CMDS_SIZE);
268 if (reply_id != last_reply_id)
269 reply_slot = reply_count++;
270 gtp_replies[reply_slot] = reply_buf;
271 last_reply_id = reply_id;
273 pthread_cond_signal(&reply_cond);
274 continue;
276 resend = true;
277 to_send = gtp_cmds;
278 /* Resend everything if slave got latest command,
279 * but doesn't have a correct board. */
280 if (reply_id == cmd_id) continue;
282 /* The slave is ouf-of-sync. Check whether the last command
283 * it received belongs to the current game. If so resend
284 * starting at the last move known by slave, otherwise
285 * resend the whole history. */
286 int reply_move = move_number(reply_id);
287 if (reply_move > move_number(cmd_id)) continue;
289 for (int slot = 0; slot < MAX_CMDS_PER_MOVE; slot++) {
290 if (reply_id == id_history[reply_move][slot]) {
291 to_send = cmd_history[reply_move][slot];
292 break;
298 /* Thread sending gtp commands to one slave machine, and
299 * reading replies. If a slave machine dies, this thread waits
300 * for a connection from another slave. */
301 static void *
302 slave_thread(void *arg)
304 int slave_sock = (long)arg;
305 assert(slave_sock >= 0);
306 char reply_buf[CMDS_SIZE];
307 bool resend = false;
309 for (;;) {
310 /* Wait for a connection from any slave. */
311 struct in_addr client;
312 int conn = open_server_connection(slave_sock, &client);
314 FILE *f = fdopen(conn, "r+");
315 if (DEBUGL(2))
316 logline(&client, "= ", "new slave\n");
318 /* Minimal check of the slave identity. */
319 fputs("name\n", f);
320 if (!fgets(reply_buf, sizeof(reply_buf), f)
321 || strncasecmp(reply_buf, "= Pachi", 7)
322 || !fgets(reply_buf, sizeof(reply_buf), f)
323 || strcmp(reply_buf, "\n")) {
324 logline(&client, "? ", "bad slave\n");
325 fclose(f);
326 continue;
329 pthread_mutex_lock(&slave_lock);
330 active_slaves++;
331 slave_loop(f, client, reply_buf, resend);
333 assert(active_slaves > 0);
334 active_slaves--;
335 // Unblock main thread if it was waiting for this slave.
336 pthread_cond_signal(&reply_cond);
337 pthread_mutex_unlock(&slave_lock);
339 resend = true;
340 if (DEBUGL(2))
341 logline(&client, "= ", "lost slave\n");
342 fclose(f);
346 /* Create a new gtp command for all slaves. The slave lock is held
347 * upon entry and upon return, so the command will actually be
348 * sent when the lock is released. The last command is overwritten
349 * if gtp_cmd points to a non-empty string. cmd is a single word;
350 * args has all arguments and is empty or has a trailing \n */
351 static void
352 update_cmd(struct board *b, char *cmd, char *args, bool new_id)
354 assert(gtp_cmd);
355 /* To make sure the slaves are in sync, we ignore the original id
356 * and use the board number plus some random bits as gtp id. */
357 static int gtp_id = -1;
358 int moves = is_reset(cmd) ? 0 : b->moves;
359 if (new_id) {
360 /* fast_random() is 16-bit only so the multiplication can't overflow. */
361 gtp_id = force_reply(moves + fast_random(65535) * DIST_GAMELEN);
362 reply_count = 0;
364 snprintf(gtp_cmd, gtp_cmds + CMDS_SIZE - gtp_cmd, "%d %s %s",
365 gtp_id, cmd, *args ? args : "\n");
366 cmd_count++;
368 /* Remember history for out-of-sync slaves. */
369 static int slot = 0;
370 slot = (slot + 1) % MAX_CMDS_PER_MOVE;
371 id_history[moves][slot] = gtp_id;
372 cmd_history[moves][slot] = gtp_cmd;
374 // Notify the slave threads about the new command.
375 pthread_cond_broadcast(&cmd_cond);
378 /* Update the command history, then create a new gtp command
379 * for all slaves. The slave lock is held upon entry and
380 * upon return, so the command will actually be sent when the
381 * lock is released. cmd is a single word; args has all
382 * arguments and is empty or has a trailing \n */
383 static void
384 new_cmd(struct board *b, char *cmd, char *args)
386 // Clear the history when a new game starts:
387 if (!gtp_cmd || is_gamestart(cmd)) {
388 gtp_cmd = gtp_cmds;
389 } else {
390 /* Preserve command history for new slaves.
391 * To indicate that the slave should only reply to
392 * the last command we force the id of previous
393 * commands to be just the move number. */
394 int id = prevent_reply(atoi(gtp_cmd));
395 int len = strspn(gtp_cmd, "0123456789");
396 char buf[32];
397 snprintf(buf, sizeof(buf), "%0*d", len, id);
398 memcpy(gtp_cmd, buf, len);
400 gtp_cmd += strlen(gtp_cmd);
403 // Let the slave threads send the new gtp command:
404 update_cmd(b, cmd, args, true);
407 /* If time_limit > 0, wait until all slaves have replied, or if the
408 * given absolute time is passed, wait for at least one reply.
409 * If time_limit == 0, wait until we get at least min_playouts games
410 * simulated in total by all the slaves, or until all slaves have replied.
411 * The replies are returned in gtp_replies[0..reply_count-1]
412 * slave_lock is held on entry and on return. */
413 static void
414 get_replies(double time_limit, int min_playouts, struct board *b)
416 while (reply_count == 0 || reply_count < active_slaves) {
417 if (time_limit && reply_count > 0) {
418 struct timespec ts;
419 double sec;
420 ts.tv_nsec = (int)(modf(time_limit, &sec)*1000000000.0);
421 ts.tv_sec = (int)sec;
422 pthread_cond_timedwait(&reply_cond, &slave_lock, &ts);
423 } else {
424 pthread_cond_wait(&reply_cond, &slave_lock);
426 if (reply_count == 0) continue;
427 if (reply_count >= active_slaves) return;
428 if (time_limit) {
429 if (time_now() >= time_limit) break;
430 } else {
431 int playouts;
432 select_best_move(b, NULL, &playouts, NULL, NULL, NULL, NULL);
433 if (playouts >= min_playouts) return;
436 if (DEBUGL(1)) {
437 char buf[1024];
438 snprintf(buf, sizeof(buf),
439 "get_replies timeout %.3f >= %.3f, replies %d < active %d\n",
440 time_now() - start_time, time_limit - start_time,
441 reply_count, active_slaves);
442 logline(NULL, "? ", buf);
444 assert(reply_count > 0);
447 /* Maximum time (seconds) to wait for answers to fast gtp commands
448 * (all commands except pachi-genmoves and final_status_list). */
449 #define MAX_FAST_CMD_WAIT 1.0
451 /* How often to send a stats update to slaves (seconds) */
452 #define STATS_UPDATE_INTERVAL 0.1 /* 100ms */
454 /* Maximum time (seconds) to wait between genmoves
455 * (all commands except pachi-genmoves and final_status_list). */
456 #define MAX_FAST_CMD_WAIT 1.0
458 /* Dispatch a new gtp command to all slaves.
459 * The slave lock must not be held upon entry and is released upon return.
460 * args is empty or ends with '\n' */
461 static enum parse_code
462 distributed_notify(struct engine *e, struct board *b, int id, char *cmd, char *args, char **reply)
464 struct distributed *dist = e->data;
466 /* Commands that should not be sent to slaves.
467 * time_left will be part of next pachi-genmoves,
468 * we reduce latency by not forwarding it here. */
469 if ((!strcasecmp(cmd, "quit") && !dist->slaves_quit)
470 || !strcasecmp(cmd, "uct_genbook")
471 || !strcasecmp(cmd, "uct_dumpbook")
472 || !strcasecmp(cmd, "kgs-chat")
473 || !strcasecmp(cmd, "time_left")
475 /* and commands that will be sent to slaves later */
476 || !strcasecmp(cmd, "genmove")
477 || !strcasecmp(cmd, "kgs-genmove_cleanup")
478 || !strcasecmp(cmd, "final_score")
479 || !strcasecmp(cmd, "final_status_list"))
480 return P_OK;
482 pthread_mutex_lock(&slave_lock);
484 // Create a new command to be sent by the slave threads.
485 new_cmd(b, cmd, args);
487 /* Wait for replies here. If we don't wait, we run the
488 * risk of getting out of sync with most slaves and
489 * sending command history too frequently. */
490 get_replies(time_now() + MAX_FAST_CMD_WAIT, 0, b);
492 pthread_mutex_unlock(&slave_lock);
493 return P_OK;
496 /* genmoves returns a line "=id total_playouts threads keep_looking[ reserved]"
497 * then a list of lines "coord playouts value".
498 * Return the move with most playouts, and optional additional info.
499 * If set, all_stats gathers the stats from all slaves except for
500 * pass and resign; it must have room up to end and upon return
501 * ends with an empty line.
502 * Keep this code in sync with uct_getstats().
503 * slave_lock is held on entry and on return. */
504 static coord_t
505 select_best_move(struct board *b, struct move_stats *best_stats,
506 int *total_playouts, int *total_threads,
507 char *all_stats, char *end, bool *keep_looking)
509 assert(reply_count > 0);
511 /* +2 for pass and resign. */
512 struct move_stats *stats = alloca((board_size2(b)+2) * sizeof(struct move_stats));
513 memset(stats, 0, (board_size2(b)+2) * sizeof(*stats));
514 stats += 2;
516 coord_t best_move = pass;
517 int best_playouts = -1;
518 int playouts = 0;
519 int threads = 0;
520 int keep = 0;
522 for (int reply = 0; reply < reply_count; reply++) {
523 char *r = gtp_replies[reply];
524 int id, p, t, k;
525 if (sscanf(r, "=%d %d %d %d", &id, &p, &t, &k) != 4) continue;
526 playouts += p;
527 threads += t;
528 keep += k;
529 // Skip the rest of the firt line if any (allow future extensions)
530 r = strchr(r, '\n');
532 char move[64];
533 struct move_stats s;
534 while (r && sscanf(++r, "%63s %d %f", move, &s.playouts, &s.value) == 3) {
535 coord_t *c = str2coord(move, board_size(b));
536 stats_add_result(&stats[*c], s.value, s.playouts);
537 if (stats[*c].playouts > best_playouts) {
538 best_playouts = stats[*c].playouts;
539 best_move = *c;
541 coord_done(c);
542 r = strchr(r, '\n');
545 if (all_stats) {
546 char *s = all_stats;
547 int min_playouts = best_playouts / 100;
548 /* Send stats for all moves except pass and resign. */
549 foreach_point(b) {
550 if (stats[c].playouts <= min_playouts) continue;
551 s += snprintf(s, end - s, "%s %d %.7f\n",
552 coord2sstr(c, b),
553 stats[c].playouts, stats[c].value);
554 } foreach_point_end;
555 s += snprintf(s, end - s, "\n");
557 if (best_stats) *best_stats = stats[best_move];
558 if (total_playouts) *total_playouts = playouts;
559 if (total_threads) *total_threads = threads;
560 if (keep_looking) *keep_looking = keep > reply_count / 2;
561 return best_move;
564 /* Time control is mostly done by the slaves, so we use default values here. */
565 #define FUSEKI_END 20
566 #define YOSE_START 40
568 static coord_t *
569 distributed_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
571 struct distributed *dist = e->data;
572 double now = time_now();
573 double first = now;
575 char *cmd = pass_all_alive ? "pachi-genmoves_cleanup" : "pachi-genmoves";
576 char args[CMDS_SIZE];
577 char *end = args + sizeof(args);
579 coord_t best;
580 int playouts, threads;
581 struct move_stats best_stats;
583 if (ti->period == TT_NULL) *ti = default_ti;
584 struct time_stop stop;
585 time_stop_conditions(ti, b, FUSEKI_END, YOSE_START, &stop);
586 struct time_info saved_ti = *ti;
588 /* Send the first genmoves without stats. This is
589 * a multi-line command ending with \n\n.
590 * Keep this code in sync with uct_genmoves(). */
591 char *col = args + snprintf(args, sizeof(args), "%s", stone2str(color));
592 char *s = col;
593 if (ti->dim == TD_WALLTIME) {
594 s += snprintf(s, end - s, " %.3f %.3f %d %d",
595 ti->len.t.main_time, ti->len.t.byoyomi_time,
596 ti->len.t.byoyomi_periods, ti->len.t.byoyomi_stones);
598 s += snprintf(s, end - s, "\n\n");
600 pthread_mutex_lock(&slave_lock);
601 new_cmd(b, cmd, args);
603 /* Loop until most slaves want to quit or time elapsed. */
604 for (;;) {
605 double start = now;
606 get_replies(now + STATS_UPDATE_INTERVAL, 0, b);
607 now = time_now();
608 s = col;
609 if (ti->dim == TD_WALLTIME) {
610 time_sub(ti, now - start);
611 s += snprintf(s, end - s, " %.3f %.3f %d %d",
612 ti->len.t.main_time, ti->len.t.byoyomi_time,
613 ti->len.t.byoyomi_periods, ti->len.t.byoyomi_stones);
615 s += snprintf(s, end - s, "\n");
616 bool keep_looking;
617 best = select_best_move(b, &best_stats, &playouts,
618 &threads, s, end, &keep_looking);
620 if (!keep_looking) break;
621 if (ti->dim == TD_WALLTIME) {
622 if (now - ti->len.t.timer_start >= stop.worst.time) break;
623 } else {
624 if (playouts >= stop.worst.playouts) break;
626 if (DEBUGL(2)) {
627 char buf[BSIZE];
628 char *coord = coord2sstr(best, b);
629 snprintf(buf, sizeof(buf),
630 "temp winner is %s %s with score %1.4f (%d/%d games)"
631 " %d slaves %d threads\n",
632 stone2str(color), coord, get_value(best_stats.value, color),
633 best_stats.playouts, playouts, reply_count, threads);
634 logline(NULL, "* ", buf);
636 /* Send the command with the same gtp id, to avoid discarding
637 * a reply to a previous genmoves at the same move. */
638 update_cmd(b, cmd, args, false);
640 int replies = reply_count;
642 /* Do not subtract time spent twice (see gtp_parse). */
643 *ti = saved_ti;
645 dist->my_last_move.color = color;
646 dist->my_last_move.coord = best;
647 dist->my_last_stats = best_stats;
649 /* Tell the slaves to commit to the selected move, overwriting
650 * the last "pachi-genmoves" in the command history. */
651 char *coord = coord2str(best, b);
652 snprintf(args, sizeof(args), "%s %s\n", stone2str(color), coord);
653 update_cmd(b, "play", args, true);
654 pthread_mutex_unlock(&slave_lock);
656 if (DEBUGL(1)) {
657 char buf[BSIZE];
658 double time = now - first + 0.000001; /* avoid divide by zero */
659 snprintf(buf, sizeof(buf),
660 "GLOBAL WINNER is %s %s with score %1.4f (%d/%d games)\n"
661 "genmove in %0.2fs %d slaves %d threads (%d games/s,"
662 " %d games/s/slave, %d games/s/thread)\n",
663 stone2str(color), coord, get_value(best_stats.value, color),
664 best_stats.playouts, playouts, time, replies, threads,
665 (int)(playouts/time), (int)(playouts/time/replies),
666 (int)(playouts/time/threads));
667 logline(NULL, "* ", buf);
669 free(coord);
670 return coord_copy(best);
673 static char *
674 distributed_chat(struct engine *e, struct board *b, char *cmd)
676 struct distributed *dist = e->data;
677 static char reply[BSIZE];
679 cmd += strspn(cmd, " \n\t");
680 if (!strncasecmp(cmd, "winrate", 7)) {
681 enum stone color = dist->my_last_move.color;
682 snprintf(reply, BSIZE, "In %d playouts at %d machines, %s %s can win with %.2f%% probability.",
683 dist->my_last_stats.playouts, active_slaves, stone2str(color),
684 coord2sstr(dist->my_last_move.coord, b),
685 100 * get_value(dist->my_last_stats.value, color));
686 return reply;
688 return NULL;
691 static int
692 scmp(const void *p1, const void *p2)
694 return strcasecmp(*(char * const *)p1, *(char * const *)p2);
697 static void
698 distributed_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
700 pthread_mutex_lock(&slave_lock);
702 new_cmd(b, "final_status_list", "dead\n");
703 get_replies(time_now() + MAX_FAST_CMD_WAIT, 0, b);
705 /* Find the most popular reply. */
706 qsort(gtp_replies, reply_count, sizeof(char *), scmp);
707 int best_reply = 0;
708 int best_count = 1;
709 int count = 1;
710 for (int reply = 1; reply < reply_count; reply++) {
711 if (!strcmp(gtp_replies[reply], gtp_replies[reply-1])) {
712 count++;
713 } else {
714 count = 1;
716 if (count > best_count) {
717 best_count = count;
718 best_reply = reply;
722 /* Pick the first move of each line as group. */
723 char *dead = gtp_replies[best_reply];
724 dead = strchr(dead, ' '); // skip "id "
725 while (dead && *++dead != '\n') {
726 coord_t *c = str2coord(dead, board_size(b));
727 mq_add(mq, *c);
728 coord_done(c);
729 dead = strchr(dead, '\n');
731 pthread_mutex_unlock(&slave_lock);
734 static struct distributed *
735 distributed_state_init(char *arg, struct board *b)
737 struct distributed *dist = calloc(1, sizeof(struct distributed));
739 dist->max_slaves = 100;
740 if (arg) {
741 char *optspec, *next = arg;
742 while (*next) {
743 optspec = next;
744 next += strcspn(next, ",");
745 if (*next) { *next++ = 0; } else { *next = 0; }
747 char *optname = optspec;
748 char *optval = strchr(optspec, '=');
749 if (optval) *optval++ = 0;
751 if (!strcasecmp(optname, "slave_port") && optval) {
752 dist->slave_port = strdup(optval);
753 } else if (!strcasecmp(optname, "proxy_port") && optval) {
754 dist->proxy_port = strdup(optval);
755 } else if (!strcasecmp(optname, "max_slaves") && optval) {
756 dist->max_slaves = atoi(optval);
757 } else if (!strcasecmp(optname, "slaves_quit")) {
758 dist->slaves_quit = !optval || atoi(optval);
759 } else {
760 fprintf(stderr, "distributed: Invalid engine argument %s or missing value\n", optname);
765 gtp_replies = calloc(dist->max_slaves, sizeof(char *));
767 if (!dist->slave_port) {
768 fprintf(stderr, "distributed: missing slave_port\n");
769 exit(1);
771 int slave_sock = port_listen(dist->slave_port, dist->max_slaves);
772 pthread_t thread;
773 for (int id = 0; id < dist->max_slaves; id++) {
774 pthread_create(&thread, NULL, slave_thread, (void *)(long)slave_sock);
777 if (dist->proxy_port) {
778 int proxy_sock = port_listen(dist->proxy_port, dist->max_slaves);
779 for (int id = 0; id < dist->max_slaves; id++) {
780 pthread_create(&thread, NULL, proxy_thread, (void *)(long)proxy_sock);
783 return dist;
786 struct engine *
787 engine_distributed_init(char *arg, struct board *b)
789 start_time = time_now();
790 struct distributed *dist = distributed_state_init(arg, b);
791 struct engine *e = calloc(1, sizeof(struct engine));
792 e->name = "Distributed Engine";
793 e->comment = "I'm playing the distributed engine. When I'm losing, I will resign, "
794 "if I think I win, I play until you pass. "
795 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
796 e->notify = distributed_notify;
797 e->genmove = distributed_genmove;
798 e->dead_group_list = distributed_dead_group_list;
799 e->chat = distributed_chat;
800 e->data = dist;
801 // Keep the threads and the open socket connections:
802 e->keep_on_clear = true;
804 return e;