Distributed engine: remove support for temp replies from slaves.
[pachi/json.git] / distributed / distributed.c
blobb0dd5b07b85a09d7450ac26749ca6a16a8743ecb
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 /* Remember at most 12 gtp ids per move: play pass,
120 * 10 genmoves (1s), play pass.
121 * For move 0 we always resend the whole history. */
122 #define MAX_CMDS_PER_MOVE 12
124 /* History of gtp commands sent for current game, indexed by move. */
125 static int id_history[MAX_GAMELEN][MAX_CMDS_PER_MOVE];
126 static char *cmd_history[MAX_GAMELEN][MAX_CMDS_PER_MOVE];
128 /* Number of active slave machines working for this master. */
129 static int active_slaves = 0;
131 /* Number of replies to last gtp command already received. */
132 static int reply_count = 0;
134 /* All replies to latest gtp command are in gtp_replies[0..reply_count-1]. */
135 static char **gtp_replies;
137 /* Mutex protecting gtp_cmds, gtp_cmd, id_history, cmd_history,
138 * active_slaves, reply_count & gtp_replies */
139 static pthread_mutex_t slave_lock = PTHREAD_MUTEX_INITIALIZER;
141 /* Condition signaled when a new gtp command is available. */
142 static pthread_cond_t cmd_cond = PTHREAD_COND_INITIALIZER;
144 /* Condition signaled when reply_count increases. */
145 static pthread_cond_t reply_cond = PTHREAD_COND_INITIALIZER;
147 /* Mutex protecting stderr. Must not be held at same time as slave_lock. */
148 static pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER;
150 /* Absolute time when this program was started.
151 * For debugging only. */
152 static double start_time;
154 /* Write the time, client address, prefix, and string s to stderr atomically.
155 * s should end with a \n */
156 static void
157 logline(struct in_addr *client, char *prefix, char *s)
159 double now = time_now();
160 char addr[INET_ADDRSTRLEN];
161 if (client) {
162 inet_ntop(AF_INET, client, addr, sizeof(addr));
163 } else {
164 addr[0] = '\0';
166 pthread_mutex_lock(&log_lock);
167 fprintf(stderr, "%s%15s %9.3f: %s", prefix, addr, now - start_time, s);
168 pthread_mutex_unlock(&log_lock);
171 /* Thread opening a connection on the given socket and copying input
172 * from there to stderr. */
173 static void *
174 proxy_thread(void *arg)
176 int proxy_sock = (long)arg;
177 assert(proxy_sock >= 0);
178 for (;;) {
179 struct in_addr client;
180 int conn = open_server_connection(proxy_sock, &client);
181 FILE *f = fdopen(conn, "r");
182 char buf[BSIZE];
183 while (fgets(buf, BSIZE, f)) {
184 logline(&client, "< ", buf);
186 fclose(f);
190 /* Get a reply to one gtp command. Return the gtp command id,
191 * or -1 if error. reply must have at least CMDS_SIZE bytes.
192 * slave_lock is not held on either entry or exit of this function. */
193 static int
194 get_reply(FILE *f, struct in_addr client, char *reply)
196 int reply_id = -1;
197 *reply = '\0';
198 char *line = reply;
199 while (fgets(line, reply + CMDS_SIZE - line, f) && *line != '\n') {
200 if (DEBUGL(2))
201 logline(&client, "<<", line);
202 if (reply_id < 0 && (*line == '=' || *line == '?') && isdigit(line[1]))
203 reply_id = atoi(line+1);
204 line += strlen(line);
206 if (*line != '\n') return -1;
207 return reply_id;
210 /* Main loop of a slave thread.
211 * Send the current command to the slave machine and wait for a reply.
212 * Resend command history if the slave machine is out of sync.
213 * Returns when the connection with the slave machine is cut.
214 * slave_lock is held on both entry and exit of this function. */
215 static void
216 slave_loop(FILE *f, struct in_addr client, char *buf, bool resend)
218 char *to_send = gtp_cmd;
219 int cmd_id = -1;
220 int reply_id = -1;
221 for (;;) {
222 while (cmd_id == reply_id && !resend) {
223 // Wait for a new gtp command.
224 pthread_cond_wait(&cmd_cond, &slave_lock);
225 if (gtp_cmd)
226 cmd_id = atoi(gtp_cmd);
227 to_send = gtp_cmd;
230 /* Command available, send it to slave machine.
231 * If slave was out of sync, send the history. */
232 assert(to_send && gtp_cmd);
233 strncpy(buf, to_send, CMDS_SIZE);
234 cmd_id = atoi(gtp_cmd);
236 pthread_mutex_unlock(&slave_lock);
238 if (DEBUGL(1) && resend) {
239 if (to_send == gtp_cmds) {
240 logline(&client, "? ", "Slave out-of-sync, resending all history\n");
241 } else {
242 logline(&client, "? ", "Slave behind, partial resend\n");
245 if (DEBUGL(2))
246 logline(&client, ">>", buf);
247 fputs(buf, f);
248 fflush(f);
250 /* Read the reply, which always ends with \n\n
251 * The slave machine sends "=id reply" or "?id reply"
252 * with id == cmd_id if it is in sync. */
253 char reply[CMDS_SIZE];
254 reply_id = get_reply(f, client, reply);
256 pthread_mutex_lock(&slave_lock);
257 if (reply_id == -1) return;
259 // Make sure we are still in sync:
260 cmd_id = atoi(gtp_cmd);
261 if (reply_id == cmd_id && *reply == '=') {
262 resend = false;
263 strncpy(buf, reply, CMDS_SIZE);
264 gtp_replies[reply_count++] = buf;
265 pthread_cond_signal(&reply_cond);
266 continue;
268 resend = true;
269 to_send = gtp_cmds;
270 /* Resend everything if slave got latest command,
271 * but doesn't have a correct board. */
272 if (reply_id == cmd_id) continue;
274 /* The slave is ouf-of-sync. Check whether the last command
275 * it received belongs to the current game. If so resend
276 * starting at the last move known by slave, otherwise
277 * resend the whole history. */
278 int reply_move = move_number(reply_id);
279 if (reply_move > move_number(cmd_id)) continue;
281 for (int slot = 0; slot < MAX_CMDS_PER_MOVE; slot++) {
282 if (reply_id == id_history[reply_move][slot]) {
283 to_send = cmd_history[reply_move][slot];
284 break;
290 /* Thread sending gtp commands to one slave machine, and
291 * reading replies. If a slave machine dies, this thread waits
292 * for a connection from another slave. */
293 static void *
294 slave_thread(void *arg)
296 int slave_sock = (long)arg;
297 assert(slave_sock >= 0);
298 char slave_buf[CMDS_SIZE];
299 bool resend = false;
301 for (;;) {
302 /* Wait for a connection from any slave. */
303 struct in_addr client;
304 int conn = open_server_connection(slave_sock, &client);
306 FILE *f = fdopen(conn, "r+");
307 if (DEBUGL(2))
308 logline(&client, "= ", "new slave\n");
310 /* Minimal check of the slave identity. */
311 fputs("name\n", f);
312 if (!fgets(slave_buf, sizeof(slave_buf), f)
313 || strncasecmp(slave_buf, "= Pachi", 7)
314 || !fgets(slave_buf, sizeof(slave_buf), f)
315 || strcmp(slave_buf, "\n")) {
316 logline(&client, "? ", "bad slave\n");
317 fclose(f);
318 continue;
321 pthread_mutex_lock(&slave_lock);
322 active_slaves++;
323 slave_loop(f, client, slave_buf, resend);
325 assert(active_slaves > 0);
326 active_slaves--;
327 // Unblock main thread if it was waiting for this slave.
328 pthread_cond_signal(&reply_cond);
329 pthread_mutex_unlock(&slave_lock);
331 resend = true;
332 if (DEBUGL(2))
333 logline(&client, "= ", "lost slave\n");
334 fclose(f);
338 /* Create a new gtp command for all slaves. The slave lock is held
339 * upon entry and upon return, so the command will actually be
340 * sent when the lock is released. The last command is overwritten
341 * if gtp_cmd points to a non-empty string. cmd is a single word;
342 * args has all arguments and is empty or has a trailing \n */
343 static void
344 update_cmd(struct board *b, char *cmd, char *args)
346 assert(gtp_cmd);
347 /* To make sure the slaves are in sync, we ignore the original id
348 * and use the board number plus some random bits as gtp id.
349 * Make sure the new command has a new id otherwise slaves
350 * won't send it. */
351 static int gtp_id = -1;
352 int id;
353 int moves = is_reset(cmd) ? 0 : b->moves;
354 do {
355 /* fast_random() is 16-bit only so the multiplication can't overflow. */
356 id = force_reply(moves + fast_random(65535) * DIST_GAMELEN);
357 } while (id == gtp_id);
358 gtp_id = id;
359 snprintf(gtp_cmd, gtp_cmds + CMDS_SIZE - gtp_cmd, "%d %s %s",
360 id, cmd, *args ? args : "\n");
361 reply_count = 0;
363 /* Remember history for out-of-sync slaves. */
364 static int slot = 0;
365 slot = (slot + 1) % MAX_CMDS_PER_MOVE;
366 id_history[moves][slot] = id;
367 cmd_history[moves][slot] = gtp_cmd;
369 // Notify the slave threads about the new command.
370 pthread_cond_broadcast(&cmd_cond);
373 /* Update the command history, then create a new gtp command
374 * for all slaves. The slave lock is held upon entry and
375 * upon return, so the command will actually be sent when the
376 * lock is released. cmd is a single word; args has all
377 * arguments and is empty or has a trailing \n */
378 static void
379 new_cmd(struct board *b, char *cmd, char *args)
381 // Clear the history when a new game starts:
382 if (!gtp_cmd || is_gamestart(cmd)) {
383 gtp_cmd = gtp_cmds;
384 } else {
385 /* Preserve command history for new slaves.
386 * To indicate that the slave should only reply to
387 * the last command we force the id of previous
388 * commands to be just the move number. */
389 int id = prevent_reply(atoi(gtp_cmd));
390 int len = strspn(gtp_cmd, "0123456789");
391 char buf[32];
392 snprintf(buf, sizeof(buf), "%0*d", len, id);
393 memcpy(gtp_cmd, buf, len);
395 gtp_cmd += strlen(gtp_cmd);
398 // Let the slave threads send the new gtp command:
399 update_cmd(b, cmd, args);
402 /* If time_limit > 0, wait until all slaves have replied, or if the
403 * given absolute time is passed, wait for at least one reply.
404 * If time_limit == 0, wait until we get at least min_playouts games
405 * simulated in total by all the slaves, or until all slaves have replied.
406 * The replies are returned in gtp_replies[0..reply_count-1]
407 * slave_lock is held on entry and on return. */
408 static void
409 get_replies(double time_limit, int min_playouts, struct board *b)
411 while (reply_count == 0 || reply_count < active_slaves) {
412 if (time_limit && reply_count > 0) {
413 struct timespec ts;
414 double sec;
415 ts.tv_nsec = (int)(modf(time_limit, &sec)*1000000000.0);
416 ts.tv_sec = (int)sec;
417 pthread_cond_timedwait(&reply_cond, &slave_lock, &ts);
418 } else {
419 pthread_cond_wait(&reply_cond, &slave_lock);
421 if (reply_count == 0) continue;
422 if (reply_count >= active_slaves) return;
423 if (time_limit) {
424 if (time_now() >= time_limit) break;
425 } else {
426 int playouts;
427 select_best_move(b, NULL, &playouts, NULL, NULL, NULL, NULL);
428 if (playouts >= min_playouts) return;
431 if (DEBUGL(1)) {
432 char buf[1024];
433 snprintf(buf, sizeof(buf),
434 "get_replies timeout %.3f >= %.3f, replies %d < active %d\n",
435 time_now() - start_time, time_limit - start_time,
436 reply_count, active_slaves);
437 logline(NULL, "? ", buf);
439 assert(reply_count > 0);
442 /* Maximum time (seconds) to wait for answers to fast gtp commands
443 * (all commands except pachi-genmoves and final_status_list). */
444 #define MAX_FAST_CMD_WAIT 1.0
446 /* How often to send a stats update to slaves (seconds) */
447 #define STATS_UPDATE_INTERVAL 0.1 /* 100ms */
449 /* Maximum time (seconds) to wait between genmoves
450 * (all commands except pachi-genmoves and final_status_list). */
451 #define MAX_FAST_CMD_WAIT 1.0
453 /* Dispatch a new gtp command to all slaves.
454 * The slave lock must not be held upon entry and is released upon return.
455 * args is empty or ends with '\n' */
456 static enum parse_code
457 distributed_notify(struct engine *e, struct board *b, int id, char *cmd, char *args, char **reply)
459 struct distributed *dist = e->data;
461 /* Commands that should not be sent to slaves.
462 * time_left will be part of next pachi-genmoves,
463 * we reduce latency by not forwarding it here. */
464 if ((!strcasecmp(cmd, "quit") && !dist->slaves_quit)
465 || !strcasecmp(cmd, "uct_genbook")
466 || !strcasecmp(cmd, "uct_dumpbook")
467 || !strcasecmp(cmd, "kgs-chat")
468 || !strcasecmp(cmd, "time_left")
470 /* and commands that will be sent to slaves later */
471 || !strcasecmp(cmd, "genmove")
472 || !strcasecmp(cmd, "kgs-genmove_cleanup")
473 || !strcasecmp(cmd, "final_score")
474 || !strcasecmp(cmd, "final_status_list"))
475 return P_OK;
477 pthread_mutex_lock(&slave_lock);
479 // Create a new command to be sent by the slave threads.
480 new_cmd(b, cmd, args);
482 /* Wait for replies here. If we don't wait, we run the
483 * risk of getting out of sync with most slaves and
484 * sending command history too frequently. */
485 get_replies(time_now() + MAX_FAST_CMD_WAIT, 0, b);
487 pthread_mutex_unlock(&slave_lock);
488 return P_OK;
491 /* genmoves returns a line "=id total_playouts threads keep_looking[ reserved]"
492 * then a list of lines "coord playouts value".
493 * Return the move with most playouts, and optional additional info.
494 * If set, all_stats gathers the stats from all slaves except for
495 * pass and resign; it must have room up to end and upon return
496 * ends with an empty line.
497 * Keep this code in sync with uct_getstats().
498 * slave_lock is held on entry and on return. */
499 static coord_t
500 select_best_move(struct board *b, struct move_stats *best_stats,
501 int *total_playouts, int *total_threads,
502 char *all_stats, char *end, bool *keep_looking)
504 assert(reply_count > 0);
506 /* +2 for pass and resign. */
507 struct move_stats *stats = alloca((board_size2(b)+2) * sizeof(struct move_stats));
508 memset(stats, 0, (board_size2(b)+2) * sizeof(*stats));
509 stats += 2;
511 coord_t best_move = pass;
512 int best_playouts = -1;
513 int playouts = 0;
514 int threads = 0;
515 int keep = 0;
517 for (int reply = 0; reply < reply_count; reply++) {
518 char *r = gtp_replies[reply];
519 int id, p, t, k;
520 if (sscanf(r, "=%d %d %d %d", &id, &p, &t, &k) != 4) continue;
521 playouts += p;
522 threads += t;
523 keep += k;
524 // Skip the rest of the firt line if any (allow future extensions)
525 r = strchr(r, '\n');
527 char move[64];
528 struct move_stats s;
529 while (r && sscanf(++r, "%63s %d %f", move, &s.playouts, &s.value) == 3) {
530 coord_t *c = str2coord(move, board_size(b));
531 stats_add_result(&stats[*c], s.value, s.playouts);
532 if (stats[*c].playouts > best_playouts) {
533 best_playouts = stats[*c].playouts;
534 best_move = *c;
536 coord_done(c);
537 r = strchr(r, '\n');
540 if (all_stats) {
541 char *s = all_stats;
542 int min_playouts = best_playouts /= 100;
543 /* Send stats for all moves except pass and resign. */
544 foreach_point(b) {
545 if (stats[c].playouts <= min_playouts) continue;
546 s += snprintf(s, end - s, "%s %d %.7f\n",
547 coord2sstr(c, b),
548 stats[c].playouts, stats[c].value);
549 } foreach_point_end;
550 s += snprintf(s, end - s, "\n");
552 if (best_stats) *best_stats = stats[best_move];
553 if (total_playouts) *total_playouts = playouts;
554 if (total_threads) *total_threads = threads;
555 if (keep_looking) *keep_looking = keep > reply_count / 2;
556 return best_move;
559 /* Time control is mostly done by the slaves, so we use default values here. */
560 #define FUSEKI_END 20
561 #define YOSE_START 40
563 static coord_t *
564 distributed_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
566 struct distributed *dist = e->data;
567 double now = time_now();
568 double first = now;
570 char *cmd = pass_all_alive ? "pachi-genmoves_cleanup" : "pachi-genmoves";
571 char args[CMDS_SIZE];
572 char *end = args + sizeof(args);
574 coord_t best;
575 int playouts, threads;
576 struct move_stats best_stats;
578 if (ti->period == TT_NULL) *ti = default_ti;
579 struct time_stop stop;
580 time_stop_conditions(ti, b, FUSEKI_END, YOSE_START, &stop);
581 struct time_info saved_ti = *ti;
583 /* Send the first genmoves without stats. This is
584 * a multi-line command ending with \n\n.
585 * Keep this code in sync with uct_genmoves(). */
586 char *col = args + snprintf(args, sizeof(args), "%s", stone2str(color));
587 char *s = col;
588 if (ti->dim == TD_WALLTIME) {
589 s += snprintf(s, end - s, " %.3f %.3f %d %d",
590 ti->len.t.main_time, ti->len.t.byoyomi_time,
591 ti->len.t.byoyomi_periods, ti->len.t.byoyomi_stones);
593 s += snprintf(s, end - s, "\n\n");
595 pthread_mutex_lock(&slave_lock);
596 new_cmd(b, cmd, args);
598 /* Loop until most slaves want to quit or time elapsed. */
599 for (;;) {
600 double start = now;
601 get_replies(now + STATS_UPDATE_INTERVAL, 0, b);
602 now = time_now();
603 s = col;
604 if (ti->dim == TD_WALLTIME) {
605 time_sub(ti, now - start);
606 s += snprintf(s, end - s, " %.3f %.3f %d %d",
607 ti->len.t.main_time, ti->len.t.byoyomi_time,
608 ti->len.t.byoyomi_periods, ti->len.t.byoyomi_stones);
610 s += snprintf(s, end - s, "\n");
611 bool keep_looking;
612 best = select_best_move(b, &best_stats, &playouts,
613 &threads, s, end, &keep_looking);
615 if (!keep_looking) break;
616 if (ti->dim == TD_WALLTIME) {
617 if (now - ti->len.t.timer_start >= stop.worst.time) break;
618 } else {
619 if (playouts >= stop.worst.playouts) break;
621 if (DEBUGL(2)) {
622 char buf[BSIZE];
623 char *coord = coord2sstr(best, b);
624 snprintf(buf, sizeof(buf),
625 "temp winner is %s %s with score %1.4f (%d/%d games)"
626 " %d slaves %d threads\n",
627 stone2str(color), coord, get_value(best_stats.value, color),
628 best_stats.playouts, playouts, reply_count, threads);
629 logline(NULL, "* ", buf);
631 update_cmd(b, cmd, args);
633 int replies = reply_count;
635 /* Do not subtract time spent twice (see gtp_parse). */
636 *ti = saved_ti;
638 dist->my_last_move.color = color;
639 dist->my_last_move.coord = best;
640 dist->my_last_stats = best_stats;
642 /* Tell the slaves to commit to the selected move, overwriting
643 * the last "pachi-genmoves" in the command history. */
644 char *coord = coord2str(best, b);
645 snprintf(args, sizeof(args), "%s %s\n", stone2str(color), coord);
646 update_cmd(b, "play", args);
647 pthread_mutex_unlock(&slave_lock);
649 if (DEBUGL(1)) {
650 char buf[BSIZE];
651 double time = now - first + 0.000001; /* avoid divide by zero */
652 snprintf(buf, sizeof(buf),
653 "GLOBAL WINNER is %s %s with score %1.4f (%d/%d games)\n"
654 "genmove in %0.2fs %d slaves %d threads (%d games/s,"
655 " %d games/s/slave, %d games/s/thread)\n",
656 stone2str(color), coord, get_value(best_stats.value, color),
657 best_stats.playouts, playouts, time, replies, threads,
658 (int)(playouts/time), (int)(playouts/time/replies),
659 (int)(playouts/time/threads));
660 logline(NULL, "* ", buf);
662 free(coord);
663 return coord_copy(best);
666 static char *
667 distributed_chat(struct engine *e, struct board *b, char *cmd)
669 struct distributed *dist = e->data;
670 static char reply[BSIZE];
672 cmd += strspn(cmd, " \n\t");
673 if (!strncasecmp(cmd, "winrate", 7)) {
674 enum stone color = dist->my_last_move.color;
675 snprintf(reply, BSIZE, "In %d playouts at %d machines, %s %s can win with %.2f%% probability.",
676 dist->my_last_stats.playouts, active_slaves, stone2str(color),
677 coord2sstr(dist->my_last_move.coord, b),
678 100 * get_value(dist->my_last_stats.value, color));
679 return reply;
681 return NULL;
684 static int
685 scmp(const void *p1, const void *p2)
687 return strcasecmp(*(char * const *)p1, *(char * const *)p2);
690 static void
691 distributed_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
693 pthread_mutex_lock(&slave_lock);
695 new_cmd(b, "final_status_list", "dead\n");
696 get_replies(time_now() + MAX_FAST_CMD_WAIT, 0, b);
698 /* Find the most popular reply. */
699 qsort(gtp_replies, reply_count, sizeof(char *), scmp);
700 int best_reply = 0;
701 int best_count = 1;
702 int count = 1;
703 for (int reply = 1; reply < reply_count; reply++) {
704 if (!strcmp(gtp_replies[reply], gtp_replies[reply-1])) {
705 count++;
706 } else {
707 count = 1;
709 if (count > best_count) {
710 best_count = count;
711 best_reply = reply;
715 /* Pick the first move of each line as group. */
716 char *dead = gtp_replies[best_reply];
717 dead = strchr(dead, ' '); // skip "id "
718 while (dead && *++dead != '\n') {
719 coord_t *c = str2coord(dead, board_size(b));
720 mq_add(mq, *c);
721 coord_done(c);
722 dead = strchr(dead, '\n');
724 pthread_mutex_unlock(&slave_lock);
727 static struct distributed *
728 distributed_state_init(char *arg, struct board *b)
730 struct distributed *dist = calloc(1, sizeof(struct distributed));
732 dist->max_slaves = 100;
733 if (arg) {
734 char *optspec, *next = arg;
735 while (*next) {
736 optspec = next;
737 next += strcspn(next, ",");
738 if (*next) { *next++ = 0; } else { *next = 0; }
740 char *optname = optspec;
741 char *optval = strchr(optspec, '=');
742 if (optval) *optval++ = 0;
744 if (!strcasecmp(optname, "slave_port") && optval) {
745 dist->slave_port = strdup(optval);
746 } else if (!strcasecmp(optname, "proxy_port") && optval) {
747 dist->proxy_port = strdup(optval);
748 } else if (!strcasecmp(optname, "max_slaves") && optval) {
749 dist->max_slaves = atoi(optval);
750 } else if (!strcasecmp(optname, "slaves_quit")) {
751 dist->slaves_quit = !optval || atoi(optval);
752 } else {
753 fprintf(stderr, "distributed: Invalid engine argument %s or missing value\n", optname);
758 gtp_replies = calloc(dist->max_slaves, sizeof(char *));
760 if (!dist->slave_port) {
761 fprintf(stderr, "distributed: missing slave_port\n");
762 exit(1);
764 int slave_sock = port_listen(dist->slave_port, dist->max_slaves);
765 pthread_t thread;
766 for (int id = 0; id < dist->max_slaves; id++) {
767 pthread_create(&thread, NULL, slave_thread, (void *)(long)slave_sock);
770 if (dist->proxy_port) {
771 int proxy_sock = port_listen(dist->proxy_port, dist->max_slaves);
772 for (int id = 0; id < dist->max_slaves; id++) {
773 pthread_create(&thread, NULL, proxy_thread, (void *)(long)proxy_sock);
776 return dist;
779 struct engine *
780 engine_distributed_init(char *arg, struct board *b)
782 start_time = time_now();
783 struct distributed *dist = distributed_state_init(arg, b);
784 struct engine *e = calloc(1, sizeof(struct engine));
785 e->name = "Distributed Engine";
786 e->comment = "I'm playing the distributed engine. When I'm losing, I will resign, "
787 "if I think I win, I play until you pass. "
788 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
789 e->notify = distributed_notify;
790 e->genmove = distributed_genmove;
791 e->dead_group_list = distributed_dead_group_list;
792 e->chat = distributed_chat;
793 e->data = dist;
794 // Keep the threads and the open socket connections:
795 e->keep_on_clear = true;
797 return e;