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
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
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
61 #include <sys/types.h>
62 #include <sys/socket.h>
63 #include <arpa/inet.h>
77 #include "distributed/distributed.h"
79 /* Internal engine state. */
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
= {
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. */
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 */
156 logline(struct in_addr
*client
, char *prefix
, char *s
)
158 double now
= time_now();
159 char addr
[INET_ADDRSTRLEN
];
161 inet_ntop(AF_INET
, client
, addr
, sizeof(addr
));
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. */
173 proxy_thread(void *arg
)
175 int proxy_sock
= (long)arg
;
176 assert(proxy_sock
>= 0);
178 struct in_addr client
;
179 int conn
= open_server_connection(proxy_sock
, &client
);
180 FILE *f
= fdopen(conn
, "r");
182 while (fgets(buf
, BSIZE
, f
)) {
183 logline(&client
, "< ", buf
);
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. */
193 get_reply(FILE *f
, struct in_addr client
, char *reply
)
198 while (fgets(line
, reply
+ CMDS_SIZE
- line
, f
) && *line
!= '\n') {
199 if (DEBUGL(3) || (DEBUGL(2) && line
== reply
))
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;
209 /* Send one gtp command and get a reply from the slave machine.
210 * Write the reply in buf which must have at least CMDS_SIZE bytes.
211 * Return the gtp command id, or -1 if error.
212 * slave_lock is held on both entry and exit of this function. */
214 send_command(char *to_send
, FILE *f
, struct in_addr client
, char *buf
)
216 assert(to_send
&& gtp_cmd
);
217 strncpy(buf
, to_send
, CMDS_SIZE
);
218 bool resend
= to_send
!= gtp_cmd
;
220 pthread_mutex_unlock(&slave_lock
);
222 if (DEBUGL(1) && resend
)
223 logline(&client
, "? ",
224 to_send
== gtp_cmds
? "resend all\n" : "partial resend\n");
229 char *s
= strchr(buf
, '\n');
232 logline(&client
, ">>", buf
);
235 int reply_id
= get_reply(f
, client
, buf
);
237 pthread_mutex_lock(&slave_lock
);
241 /* Process the reply received from a slave machine.
242 * Copy it to reply_buf and return NULL if ok, or return
243 * the command to be sent again if the slave is out of sync.
244 * slave_lock is held on both entry and exit of this function. */
246 process_reply(int reply_id
, char *reply
, char *reply_buf
,
247 int *last_reply_id
, int *reply_slot
)
249 /* Make sure we are still in sync. cmd_count may have
250 * changed but the reply is valid as long as cmd_id didn't
251 * change (this only occurs for consecutive genmoves). */
252 int cmd_id
= atoi(gtp_cmd
);
253 if (reply_id
== cmd_id
&& *reply
== '=') {
254 strncpy(reply_buf
, reply
, CMDS_SIZE
);
255 if (reply_id
!= *last_reply_id
)
256 *reply_slot
= reply_count
++;
257 gtp_replies
[*reply_slot
] = reply_buf
;
258 *last_reply_id
= reply_id
;
260 pthread_cond_signal(&reply_cond
);
263 /* Resend everything if slave got latest command,
264 * but doesn't have a correct board. */
265 if (reply_id
== cmd_id
) return gtp_cmds
;
267 /* The slave is ouf-of-sync. Check whether the last command
268 * it received belongs to the current game. If so resend
269 * starting at the last move known by slave, otherwise
270 * resend the whole history. */
271 int reply_move
= move_number(reply_id
);
272 if (reply_move
> move_number(cmd_id
)) return gtp_cmds
;
274 for (int slot
= 0; slot
< MAX_CMDS_PER_MOVE
; slot
++) {
275 if (reply_id
== id_history
[reply_move
][slot
]) {
276 char *to_send
= cmd_history
[reply_move
][slot
];
278 /* Do not resend same cmd if done successfully. */
279 if (*reply
!= '=') return to_send
;
280 to_send
= strchr(to_send
, '\n');
281 assert(to_send
&& to_send
[1]);
288 /* Main loop of a slave thread.
289 * Send the current command to the slave machine and wait for a reply.
290 * Resend command history if the slave machine is out of sync.
291 * Returns when the connection with the slave machine is cut.
292 * slave_lock is held on both entry and exit of this function. */
294 slave_loop(FILE *f
, struct in_addr client
, char *reply_buf
, bool resend
)
296 char *to_send
= gtp_cmd
;
297 int last_cmd_sent
= 0;
298 int last_reply_id
= -1;
301 while (last_cmd_sent
== cmd_count
&& !resend
) {
302 // Wait for a new gtp command.
303 pthread_cond_wait(&cmd_cond
, &slave_lock
);
307 /* Command available, send it to slave machine.
308 * If slave was out of sync, send the history. */
310 last_cmd_sent
= cmd_count
;
312 /* Send the command and get the reply, which always ends with \n\n
313 * The slave machine sends "=id reply" or "?id reply"
314 * with id == cmd_id if it is in sync. */
315 int reply_id
= send_command(to_send
, f
, client
, buf
);
316 if (reply_id
== -1) return;
318 to_send
= process_reply(reply_id
, buf
, reply_buf
,
319 &last_reply_id
, &reply_slot
);
321 /* Good reply. Force waiting for a new command.
322 * The next genmoves stats we send must include those
323 * just received (this is assumed by the slave). */
324 last_cmd_sent
= cmd_count
;
332 /* Thread sending gtp commands to one slave machine, and
333 * reading replies. If a slave machine dies, this thread waits
334 * for a connection from another slave. */
336 slave_thread(void *arg
)
338 int slave_sock
= (long)arg
;
339 assert(slave_sock
>= 0);
340 char reply_buf
[CMDS_SIZE
];
344 /* Wait for a connection from any slave. */
345 struct in_addr client
;
346 int conn
= open_server_connection(slave_sock
, &client
);
348 FILE *f
= fdopen(conn
, "r+");
350 logline(&client
, "= ", "new slave\n");
352 /* Minimal check of the slave identity. */
354 if (!fgets(reply_buf
, sizeof(reply_buf
), f
)
355 || strncasecmp(reply_buf
, "= Pachi", 7)
356 || !fgets(reply_buf
, sizeof(reply_buf
), f
)
357 || strcmp(reply_buf
, "\n")) {
358 logline(&client
, "? ", "bad slave\n");
363 pthread_mutex_lock(&slave_lock
);
365 slave_loop(f
, client
, reply_buf
, resend
);
367 assert(active_slaves
> 0);
369 // Unblock main thread if it was waiting for this slave.
370 pthread_cond_signal(&reply_cond
);
371 pthread_mutex_unlock(&slave_lock
);
375 logline(&client
, "= ", "lost slave\n");
380 /* Create a new gtp command for all slaves. The slave lock is held
381 * upon entry and upon return, so the command will actually be
382 * sent when the lock is released. The last command is overwritten
383 * if gtp_cmd points to a non-empty string. cmd is a single word;
384 * args has all arguments and is empty or has a trailing \n */
386 update_cmd(struct board
*b
, char *cmd
, char *args
, bool new_id
)
389 /* To make sure the slaves are in sync, we ignore the original id
390 * and use the board number plus some random bits as gtp id. */
391 static int gtp_id
= -1;
392 int moves
= is_reset(cmd
) ? 0 : b
->moves
;
394 /* fast_random() is 16-bit only so the multiplication can't overflow. */
395 gtp_id
= force_reply(moves
+ fast_random(65535) * DIST_GAMELEN
);
398 snprintf(gtp_cmd
, gtp_cmds
+ CMDS_SIZE
- gtp_cmd
, "%d %s %s",
399 gtp_id
, cmd
, *args
? args
: "\n");
402 /* Remember history for out-of-sync slaves. */
404 slot
= (slot
+ 1) % MAX_CMDS_PER_MOVE
;
405 id_history
[moves
][slot
] = gtp_id
;
406 cmd_history
[moves
][slot
] = gtp_cmd
;
408 // Notify the slave threads about the new command.
409 pthread_cond_broadcast(&cmd_cond
);
412 /* Update the command history, then create a new gtp command
413 * for all slaves. The slave lock is held upon entry and
414 * upon return, so the command will actually be sent when the
415 * lock is released. cmd is a single word; args has all
416 * arguments and is empty or has a trailing \n */
418 new_cmd(struct board
*b
, char *cmd
, char *args
)
420 // Clear the history when a new game starts:
421 if (!gtp_cmd
|| is_gamestart(cmd
)) {
424 /* Preserve command history for new slaves.
425 * To indicate that the slave should only reply to
426 * the last command we force the id of previous
427 * commands to be just the move number. */
428 int id
= prevent_reply(atoi(gtp_cmd
));
429 int len
= strspn(gtp_cmd
, "0123456789");
431 snprintf(buf
, sizeof(buf
), "%0*d", len
, id
);
432 memcpy(gtp_cmd
, buf
, len
);
434 gtp_cmd
+= strlen(gtp_cmd
);
437 // Let the slave threads send the new gtp command:
438 update_cmd(b
, cmd
, args
, true);
441 /* Wait for at least one new reply. Return when all slaves have
442 * replied, or when the given absolute time is passed.
443 * The replies are returned in gtp_replies[0..reply_count-1]
444 * slave_lock is held on entry and on return. */
446 get_replies(double time_limit
)
449 if (reply_count
> 0) {
452 ts
.tv_nsec
= (int)(modf(time_limit
, &sec
)*1000000000.0);
453 ts
.tv_sec
= (int)sec
;
454 pthread_cond_timedwait(&reply_cond
, &slave_lock
, &ts
);
456 pthread_cond_wait(&reply_cond
, &slave_lock
);
458 if (reply_count
== 0) continue;
459 if (reply_count
>= active_slaves
) return;
460 if (time_now() >= time_limit
) break;
464 snprintf(buf
, sizeof(buf
),
465 "get_replies timeout %.3f >= %.3f, replies %d < active %d\n",
466 time_now() - start_time
, time_limit
- start_time
,
467 reply_count
, active_slaves
);
468 logline(NULL
, "? ", buf
);
470 assert(reply_count
> 0);
473 /* Maximum time (seconds) to wait for answers to fast gtp commands
474 * (all commands except pachi-genmoves and final_status_list). */
475 #define MAX_FAST_CMD_WAIT 1.0
477 /* How often to send a stats update to slaves (seconds) */
478 #define STATS_UPDATE_INTERVAL 0.1 /* 100ms */
480 /* Maximum time (seconds) to wait between genmoves
481 * (all commands except pachi-genmoves and final_status_list). */
482 #define MAX_FAST_CMD_WAIT 1.0
484 /* Dispatch a new gtp command to all slaves.
485 * The slave lock must not be held upon entry and is released upon return.
486 * args is empty or ends with '\n' */
487 static enum parse_code
488 distributed_notify(struct engine
*e
, struct board
*b
, int id
, char *cmd
, char *args
, char **reply
)
490 struct distributed
*dist
= e
->data
;
492 /* Commands that should not be sent to slaves.
493 * time_left will be part of next pachi-genmoves,
494 * we reduce latency by not forwarding it here. */
495 if ((!strcasecmp(cmd
, "quit") && !dist
->slaves_quit
)
496 || !strcasecmp(cmd
, "uct_genbook")
497 || !strcasecmp(cmd
, "uct_dumpbook")
498 || !strcasecmp(cmd
, "kgs-chat")
499 || !strcasecmp(cmd
, "time_left")
501 /* and commands that will be sent to slaves later */
502 || !strcasecmp(cmd
, "genmove")
503 || !strcasecmp(cmd
, "kgs-genmove_cleanup")
504 || !strcasecmp(cmd
, "final_score")
505 || !strcasecmp(cmd
, "final_status_list"))
508 pthread_mutex_lock(&slave_lock
);
510 // Create a new command to be sent by the slave threads.
511 new_cmd(b
, cmd
, args
);
513 /* Wait for replies here. If we don't wait, we run the
514 * risk of getting out of sync with most slaves and
515 * sending command history too frequently. */
516 get_replies(time_now() + MAX_FAST_CMD_WAIT
);
518 pthread_mutex_unlock(&slave_lock
);
522 /* genmoves returns a line "=id played_own total_playouts threads keep_looking[ reserved]"
523 * then a list of lines "coord playouts value amaf_playouts amaf_value".
524 * Return the move with most playouts, and additional stats.
525 * Keep this code in sync with uct/slave.c:report_stats().
526 * slave_lock is held on entry and on return. */
528 select_best_move(struct board
*b
, struct move_stats2
*stats
, int *played
,
529 int *total_playouts
, int *total_threads
, bool *keep_looking
)
531 assert(reply_count
> 0);
533 /* +2 for pass and resign */
534 memset(stats
-2, 0, (board_size2(b
)+2) * sizeof(*stats
));
536 coord_t best_move
= pass
;
537 int best_playouts
= -1;
543 for (int reply
= 0; reply
< reply_count
; reply
++) {
544 char *r
= gtp_replies
[reply
];
546 if (sscanf(r
, "=%d %d %d %d %d", &id
, &o
, &p
, &t
, &k
) != 5) continue;
548 *total_playouts
+= p
;
551 // Skip the rest of the firt line if any (allow future extensions)
555 struct move_stats2 s
;
556 while (r
&& sscanf(++r
, "%63s %d %f %d %f", move
, &s
.u
.playouts
,
557 &s
.u
.value
, &s
.amaf
.playouts
, &s
.amaf
.value
) == 5) {
558 coord_t
*c
= str2coord(move
, board_size(b
));
559 stats_add_result(&stats
[*c
].u
, s
.u
.value
, s
.u
.playouts
);
560 stats_add_result(&stats
[*c
].amaf
, s
.amaf
.value
, s
.amaf
.playouts
);
562 if (stats
[*c
].u
.playouts
> best_playouts
) {
563 best_playouts
= stats
[*c
].u
.playouts
;
570 *keep_looking
= keep
> reply_count
/ 2;
574 /* Set the args for the genmoves command. If stats is not null,
575 * append the stats from all slaves above min_playouts, except
576 * for pass and resign. args must have CMDS_SIZE bytes and
577 * upon return ends with an empty line.
578 * Keep this code in sync with uct_genmoves().
579 * slave_lock is held on entry and on return. */
581 genmoves_args(char *args
, struct board
*b
, enum stone color
, int played
,
582 struct time_info
*ti
, struct move_stats2
*stats
, int min_playouts
)
584 char *end
= args
+ CMDS_SIZE
;
585 char *s
= args
+ snprintf(args
, CMDS_SIZE
, "%s %d", stone2str(color
), played
);
587 if (ti
->dim
== TD_WALLTIME
) {
588 s
+= snprintf(s
, end
- s
, " %.3f %.3f %d %d",
589 ti
->len
.t
.main_time
, ti
->len
.t
.byoyomi_time
,
590 ti
->len
.t
.byoyomi_periods
, ti
->len
.t
.byoyomi_stones
);
592 s
+= snprintf(s
, end
- s
, "\n");
595 if (stats
[c
].u
.playouts
<= min_playouts
) continue;
596 s
+= snprintf(s
, end
- s
, "%s %d %.7f %d %.7f\n",
598 stats
[c
].u
.playouts
, stats
[c
].u
.value
,
599 stats
[c
].amaf
.playouts
, stats
[c
].amaf
.value
);
602 s
+= snprintf(s
, end
- s
, "\n");
605 /* Time control is mostly done by the slaves, so we use default values here. */
606 #define FUSEKI_END 20
607 #define YOSE_START 40
610 distributed_genmove(struct engine
*e
, struct board
*b
, struct time_info
*ti
,
611 enum stone color
, bool pass_all_alive
)
613 struct distributed
*dist
= e
->data
;
614 double now
= time_now();
617 char *cmd
= pass_all_alive
? "pachi-genmoves_cleanup" : "pachi-genmoves";
618 char args
[CMDS_SIZE
];
621 int played
, playouts
, threads
;
623 if (ti
->period
== TT_NULL
) *ti
= default_ti
;
624 struct time_stop stop
;
625 time_stop_conditions(ti
, b
, FUSEKI_END
, YOSE_START
, &stop
);
626 struct time_info saved_ti
= *ti
;
628 /* Send the first genmoves without stats. */
629 genmoves_args(args
, b
, color
, 0, ti
, NULL
, 0);
631 /* Combined move stats from all slaves, only for children
632 * of the root node, plus 2 for pass and resign. */
633 struct move_stats2
*stats
= alloca((board_size2(b
)+2) * sizeof(struct move_stats2
));
636 pthread_mutex_lock(&slave_lock
);
637 new_cmd(b
, cmd
, args
);
639 /* Loop until most slaves want to quit or time elapsed. */
642 get_replies(now
+ STATS_UPDATE_INTERVAL
);
644 if (ti
->dim
== TD_WALLTIME
)
645 time_sub(ti
, now
- start
);
648 best
= select_best_move(b
, stats
, &played
, &playouts
, &threads
, &keep_looking
);
650 if (!keep_looking
) break;
651 if (ti
->dim
== TD_WALLTIME
) {
652 if (now
- ti
->len
.t
.timer_start
>= stop
.worst
.time
) break;
654 if (played
>= stop
.worst
.playouts
) break;
658 char *coord
= coord2sstr(best
, b
);
659 snprintf(buf
, sizeof(buf
),
660 "temp winner is %s %s with score %1.4f (%d/%d games)"
661 " %d slaves %d threads\n",
662 stone2str(color
), coord
, get_value(stats
[best
].u
.value
, color
),
663 stats
[best
].u
.playouts
, playouts
, reply_count
, threads
);
664 logline(NULL
, "* ", buf
);
666 /* Send the command with the same gtp id, to avoid discarding
667 * a reply to a previous genmoves at the same move. */
668 genmoves_args(args
, b
, color
, played
, ti
, stats
, stats
[best
].u
.playouts
/ 100);
669 update_cmd(b
, cmd
, args
, false);
671 int replies
= reply_count
;
673 /* Do not subtract time spent twice (see gtp_parse). */
676 dist
->my_last_move
.color
= color
;
677 dist
->my_last_move
.coord
= best
;
678 dist
->my_last_stats
= stats
[best
].u
;
680 /* Tell the slaves to commit to the selected move, overwriting
681 * the last "pachi-genmoves" in the command history. */
682 char *coord
= coord2str(best
, b
);
683 snprintf(args
, sizeof(args
), "%s %s\n", stone2str(color
), coord
);
684 update_cmd(b
, "play", args
, true);
685 pthread_mutex_unlock(&slave_lock
);
689 double time
= now
- first
+ 0.000001; /* avoid divide by zero */
690 snprintf(buf
, sizeof(buf
),
691 "GLOBAL WINNER is %s %s with score %1.4f (%d/%d games)\n"
692 "genmove %d games in %0.2fs %d slaves %d threads (%d games/s,"
693 " %d games/s/slave, %d games/s/thread)\n",
694 stone2str(color
), coord
, get_value(stats
[best
].u
.value
, color
),
695 stats
[best
].u
.playouts
, playouts
, played
, time
, replies
, threads
,
696 (int)(played
/time
), (int)(played
/time
/replies
),
697 (int)(played
/time
/threads
));
698 logline(NULL
, "* ", buf
);
701 return coord_copy(best
);
705 distributed_chat(struct engine
*e
, struct board
*b
, char *cmd
)
707 struct distributed
*dist
= e
->data
;
708 static char reply
[BSIZE
];
710 cmd
+= strspn(cmd
, " \n\t");
711 if (!strncasecmp(cmd
, "winrate", 7)) {
712 enum stone color
= dist
->my_last_move
.color
;
713 snprintf(reply
, BSIZE
, "In %d playouts at %d machines, %s %s can win with %.2f%% probability.",
714 dist
->my_last_stats
.playouts
, active_slaves
, stone2str(color
),
715 coord2sstr(dist
->my_last_move
.coord
, b
),
716 100 * get_value(dist
->my_last_stats
.value
, color
));
723 scmp(const void *p1
, const void *p2
)
725 return strcasecmp(*(char * const *)p1
, *(char * const *)p2
);
729 distributed_dead_group_list(struct engine
*e
, struct board
*b
, struct move_queue
*mq
)
731 pthread_mutex_lock(&slave_lock
);
733 new_cmd(b
, "final_status_list", "dead\n");
734 get_replies(time_now() + MAX_FAST_CMD_WAIT
);
736 /* Find the most popular reply. */
737 qsort(gtp_replies
, reply_count
, sizeof(char *), scmp
);
741 for (int reply
= 1; reply
< reply_count
; reply
++) {
742 if (!strcmp(gtp_replies
[reply
], gtp_replies
[reply
-1])) {
747 if (count
> best_count
) {
753 /* Pick the first move of each line as group. */
754 char *dead
= gtp_replies
[best_reply
];
755 dead
= strchr(dead
, ' '); // skip "id "
756 while (dead
&& *++dead
!= '\n') {
757 coord_t
*c
= str2coord(dead
, board_size(b
));
760 dead
= strchr(dead
, '\n');
762 pthread_mutex_unlock(&slave_lock
);
765 static struct distributed
*
766 distributed_state_init(char *arg
, struct board
*b
)
768 struct distributed
*dist
= calloc2(1, sizeof(struct distributed
));
770 dist
->max_slaves
= 100;
772 char *optspec
, *next
= arg
;
775 next
+= strcspn(next
, ",");
776 if (*next
) { *next
++ = 0; } else { *next
= 0; }
778 char *optname
= optspec
;
779 char *optval
= strchr(optspec
, '=');
780 if (optval
) *optval
++ = 0;
782 if (!strcasecmp(optname
, "slave_port") && optval
) {
783 dist
->slave_port
= strdup(optval
);
784 } else if (!strcasecmp(optname
, "proxy_port") && optval
) {
785 dist
->proxy_port
= strdup(optval
);
786 } else if (!strcasecmp(optname
, "max_slaves") && optval
) {
787 dist
->max_slaves
= atoi(optval
);
788 } else if (!strcasecmp(optname
, "slaves_quit")) {
789 dist
->slaves_quit
= !optval
|| atoi(optval
);
791 fprintf(stderr
, "distributed: Invalid engine argument %s or missing value\n", optname
);
796 gtp_replies
= calloc2(dist
->max_slaves
, sizeof(char *));
798 if (!dist
->slave_port
) {
799 fprintf(stderr
, "distributed: missing slave_port\n");
802 int slave_sock
= port_listen(dist
->slave_port
, dist
->max_slaves
);
804 for (int id
= 0; id
< dist
->max_slaves
; id
++) {
805 pthread_create(&thread
, NULL
, slave_thread
, (void *)(long)slave_sock
);
808 if (dist
->proxy_port
) {
809 int proxy_sock
= port_listen(dist
->proxy_port
, dist
->max_slaves
);
810 for (int id
= 0; id
< dist
->max_slaves
; id
++) {
811 pthread_create(&thread
, NULL
, proxy_thread
, (void *)(long)proxy_sock
);
818 engine_distributed_init(char *arg
, struct board
*b
)
820 start_time
= time_now();
821 struct distributed
*dist
= distributed_state_init(arg
, b
);
822 struct engine
*e
= calloc2(1, sizeof(struct engine
));
823 e
->name
= "Distributed Engine";
824 e
->comment
= "I'm playing the distributed engine. When I'm losing, I will resign, "
825 "if I think I win, I play until you pass. "
826 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
827 e
->notify
= distributed_notify
;
828 e
->genmove
= distributed_genmove
;
829 e
->dead_group_list
= distributed_dead_group_list
;
830 e
->chat
= distributed_chat
;
832 // Keep the threads and the open socket connections:
833 e
->keep_on_clear
= true;