Support log proxy for the distributed engine.
[pachi/ann.git] / distributed / distributed.c
blob33f6cc43fbbc04dee2180c5fe0b7c651806b3fdb
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 the pachi-genmoves gtp command 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 /* The master trusts the majority of slaves for time control:
10 * it picks the move when half the slaves have replied, except
11 * when the allowed time is already passed. In this case the
12 * master picks among the available replies, or waits for just
13 * one reply if there is none yet. */
15 /* This first version does not send tree updates between slaves,
16 * but it has fault tolerance. If a slave is out of sync, the master
17 * sends it the whole command history. */
19 /* Pass me arguments like a=b,c=d,...
20 * Supported arguments:
21 * slave_port=SLAVE_PORT slaves connect to this port; this parameter is mandatory.
22 * max_slaves=MAX_SLAVES default 100
23 * slaves_quit=0|1 quit gtp command also sent to slaves, default false.
24 * proxy_port=PROXY_PORT slaves optionally send their logs to this port.
25 * Warning: with proxy_port, the master stderr mixes the logs of all
26 * machines but you can separate them again:
27 * slave logs: sed -n '/< .*:/s/.*< /< /p' logfile
28 * master logs: perl -0777 -pe 's/<[ <].*:.*\n//g' logfile
31 /* A configuration without proxy would have one master run on masterhost as:
32 * zzgo -e distributed slave_port=1234
33 * and N slaves running as:
34 * zzgo -e uct -g masterhost:1234 slave
35 * With log proxy:
36 * zzgo -e distributed slave_port=1234,proxy_port=1235
37 * zzgo -e uct -g masterhost:1234 -l masterhost:1235 slave
38 * If the master itself runs on a machine other than that running gogui,
39 * gogui-twogtp, kgsGtp or cgosGtp, it can redirect its gtp port:
40 * zzgo -e distributed -g 10000 slave_port=1234,proxy_port=1235
43 #include <assert.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <pthread.h>
48 #include <limits.h>
49 #include <ctype.h>
50 #include <time.h>
51 #include <alloca.h>
52 #include <sys/types.h>
53 #include <sys/socket.h>
54 #include <arpa/inet.h>
56 #define DEBUG
58 #include "board.h"
59 #include "engine.h"
60 #include "move.h"
61 #include "timeinfo.h"
62 #include "network.h"
63 #include "playout.h"
64 #include "random.h"
65 #include "stats.h"
66 #include "mq.h"
67 #include "debug.h"
68 #include "distributed/distributed.h"
70 /* Internal engine state. */
71 struct distributed {
72 char *slave_port;
73 char *proxy_port;
74 int max_slaves;
75 bool slaves_quit;
76 struct move my_last_move;
77 struct move_stats my_last_stats;
80 #define get_value(value, color) \
81 ((color) == S_BLACK ? (value) : 1 - (value))
83 /* Max size for one reply or slave log. */
84 #define BSIZE 4096
86 /* Max size of all gtp commands for one game */
87 #define CMDS_SIZE (40*MAX_GAMELEN)
89 /* All gtp commands for current game separated by \n */
90 char gtp_cmds[CMDS_SIZE];
92 /* Latest gtp command sent to slaves. */
93 char *gtp_cmd = NULL;
95 /* Number of active slave machines working for this master. */
96 int active_slaves = 0;
98 /* Number of replies to last gtp command already received. */
99 int reply_count = 0;
101 /* All replies to latest gtp command are in gtp_replies[0..reply_count-1]. */
102 char **gtp_replies;
104 /* Mutex protecting gtp_cmds, gtp_cmd, active_slaves, reply_count & gtp_replies */
105 pthread_mutex_t slave_lock = PTHREAD_MUTEX_INITIALIZER;
107 /* Condition signaled when a new gtp command is available. */
108 static pthread_cond_t cmd_cond = PTHREAD_COND_INITIALIZER;
110 /* Condition signaled when reply_count increases. */
111 static pthread_cond_t reply_cond = PTHREAD_COND_INITIALIZER;
113 /* Mutex protecting stderr. Must not be held at same time as slave_lock. */
114 pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER;
116 /* Absolute time when this program was started.
117 * For debugging only. */
118 double start_time;
120 /* Write the time, client address, prefix, and string s to stderr atomically.
121 * s should end with a \n */
122 static void
123 logline(struct in_addr *client, char *prefix, char *s)
125 double now = time_now();
126 char addr[INET_ADDRSTRLEN];
127 if (client) {
128 inet_ntop(AF_INET, client, addr, sizeof(addr));
129 } else {
130 addr[0] = '\0';
132 pthread_mutex_lock(&log_lock);
133 fprintf(stderr, "%s%s %9.3f: %s", prefix, addr, now - start_time, s);
134 pthread_mutex_unlock(&log_lock);
137 /* Thread opening a connection on the given socket and copying input
138 * from there to stderr. */
139 static void *
140 proxy_thread(void *arg)
142 int proxy_sock = (long)arg;
143 assert(proxy_sock >= 0);
144 for (;;) {
145 struct in_addr client;
146 int conn = open_server_connection(proxy_sock, &client);
147 FILE *f = fdopen(conn, "r");
148 char buf[BSIZE];
149 while (fgets(buf, BSIZE, f)) {
150 logline(&client, "< ", buf);
152 fclose(f);
156 /* Main loop of a slave thread.
157 * Send the current command to the slave machine and wait for a reply.
158 * Resend the whole command history if the slave machine is out of sync.
159 * Returns when the connection with the slave machine is cut.
160 * slave_lock is held on both entry and exit of this function. */
161 static void
162 slave_loop(FILE *f, struct in_addr client, char *buf, bool resend)
164 char *to_send = gtp_cmd;
165 int cmd_id = -1;
166 int reply_id = -1;
167 for (;;) {
168 while (cmd_id == reply_id && !resend) {
169 // Wait for a new gtp command.
170 pthread_cond_wait(&cmd_cond, &slave_lock);
171 if (gtp_cmd)
172 cmd_id = atoi(gtp_cmd);
173 to_send = gtp_cmd;
176 /* Command available, send it to slave machine.
177 * If slave was out of sync, send all the history. */
178 assert(to_send && gtp_cmd);
179 strncpy(buf, to_send, CMDS_SIZE);
180 cmd_id = atoi(gtp_cmd);
182 pthread_mutex_unlock(&slave_lock);
183 if (DEBUGL(2))
184 logline(&client, ">>", buf);
185 fputs(buf, f);
186 fflush(f);
188 /* Read the reply, which always ends with \n\n
189 * The slave machine sends "=id reply" or "?id reply"
190 * with id == cmd_id if it is in sync. */
191 *buf = '\0';
192 reply_id = -1;
193 char *line = buf;
194 while (fgets(line, buf + CMDS_SIZE - line, f) && *line != '\n') {
195 if (DEBUGL(2))
196 logline(&client, "<<", line);
197 if (reply_id < 0 && (*line == '=' || *line == '?') && isdigit(line[1]))
198 reply_id = atoi(line+1);
199 line += strlen(line);
202 pthread_mutex_lock(&slave_lock);
203 if (*line != '\n') return;
204 if (reply_id == cmd_id && *buf == '=') {
205 gtp_replies[reply_count++] = buf;
206 pthread_cond_signal(&reply_cond);
207 } else {
208 /* The slave was out of sync or had an incorrect board.
209 * Send the whole command history without wait.
210 * The slave will send a single reply with the
211 * id of the last command. */
212 to_send = gtp_cmds;
213 resend = true;
214 if (DEBUGL(1))
215 logline(&client, "? ", "Resending all history\n");
220 /* Thread sending gtp commands to one slave machine, and
221 * reading replies. If a slave machine dies, this thread waits
222 * for a connection from another slave. */
223 static void *
224 slave_thread(void *arg)
226 int slave_sock = (long)arg;
227 assert(slave_sock >= 0);
228 char slave_buf[CMDS_SIZE];
229 bool resend = false;
231 for (;;) {
232 /* Wait for a connection from any slave. */
233 struct in_addr client;
234 int conn = open_server_connection(slave_sock, &client);
236 FILE *f = fdopen(conn, "r+");
237 if (DEBUGL(2))
238 logline(&client, "= ", "new slave\n");
240 /* Minimal check of the slave identity. */
241 fputs("name\n", f);
242 if (!fgets(slave_buf, sizeof(slave_buf), f)
243 || strncasecmp(slave_buf, "= Pachi", 7)
244 || !fgets(slave_buf, sizeof(slave_buf), f)
245 || strcmp(slave_buf, "\n")) {
246 logline(&client, "? ", "bad slave\n");
247 fclose(f);
248 continue;
251 pthread_mutex_lock(&slave_lock);
252 active_slaves++;
253 slave_loop(f, client, slave_buf, resend);
255 assert(active_slaves > 0);
256 active_slaves--;
257 pthread_mutex_unlock(&slave_lock);
259 resend = true;
260 if (DEBUGL(2))
261 logline(&client, "= ", "lost slave\n");
262 fclose(f);
266 /* Create a new gtp command for all slaves. The slave lock is held
267 * upon entry and upon return, so the command will actually be
268 * sent when the lock is released. The last command is overwritten
269 * if gtp_cmd points to a non-empty string. cmd is a single word;
270 * args has all arguments and is empty or has a trailing \n */
271 static void
272 update_cmd(struct board *b, char *cmd, char *args)
274 assert(gtp_cmd);
275 /* To make sure the slaves are in sync, we ignore the original id
276 * and use the board number plus some random bits as gtp id.
277 * Make sure the new command has a new id otherwise slaves
278 * won't send it. */
279 static int gtp_id = -1;
280 int id;
281 int moves = is_reset(cmd) ? 0 : b->moves;
282 do {
283 /* fast_random() is 16-bit only so the multiplication can't overflow. */
284 id = force_reply(moves + fast_random(65535) * DIST_GAMELEN);
285 } while (id == gtp_id);
286 gtp_id = id;
287 snprintf(gtp_cmd, gtp_cmds + CMDS_SIZE - gtp_cmd, "%d %s %s",
288 id, cmd, *args ? args : "\n");
289 reply_count = 0;
292 /* Wait for slave replies until we get at least 50% of the
293 * slaves or the given absolute time (if non zero) is passed.
294 * If we get 50% of the slaves, we wait another 0.5s to get
295 * as many slaves as possible while not wasting time waiting
296 * for stuck or dead slaves.
297 * The replies are returned in gtp_replies[0..reply_count-1]
298 * slave_lock is held on entry and on return. */
299 static void
300 get_replies(double time_limit)
302 #define EXTRA_TIME 0.5
303 while (reply_count == 0 || reply_count < active_slaves) {
304 if (time_limit && reply_count > 0) {
305 struct timespec ts;
306 double sec;
307 ts.tv_nsec = (int)(modf(time_limit, &sec)*1000000000.0);
308 ts.tv_sec = (int)sec;
309 pthread_cond_timedwait(&reply_cond, &slave_lock, &ts);
310 } else {
311 pthread_cond_wait(&reply_cond, &slave_lock);
313 if (reply_count == 0) continue;
314 if (reply_count >= active_slaves) break;
315 double now = time_now();
316 if (time_limit && now >= time_limit) break;
317 if (reply_count >= active_slaves / 2
318 && (!time_limit || now + EXTRA_TIME < time_limit))
319 time_limit = now + EXTRA_TIME;
321 assert(reply_count > 0);
324 /* Dispatch a new gtp command to all slaves.
325 * The slave lock must not be held upon entry and is released upon return.
326 * args is empty or ends with '\n' */
327 static enum parse_code
328 distributed_notify(struct engine *e, struct board *b, int id, char *cmd, char *args, char **reply)
330 struct distributed *dist = e->data;
332 if ((!strcasecmp(cmd, "quit") && !dist->slaves_quit)
333 || !strcasecmp(cmd, "uct_genbook")
334 || !strcasecmp(cmd, "uct_dumpbook")
335 || !strcasecmp(cmd, "kgs-chat"))
336 return P_OK;
338 pthread_mutex_lock(&slave_lock);
340 // Clear the history when a new game starts:
341 if (!gtp_cmd || is_gamestart(cmd)) {
342 gtp_cmd = gtp_cmds;
343 } else {
344 /* Preserve command history for new slaves.
345 * To indicate that the slave should only reply to
346 * the last command we force the id of previous
347 * commands to be just the move number. */
348 int id = prevent_reply(atoi(gtp_cmd));
349 int len = strspn(gtp_cmd, "0123456789");
350 char buf[32];
351 snprintf(buf, sizeof(buf), "%0*d", len, id);
352 memcpy(gtp_cmd, buf, len);
354 gtp_cmd += strlen(gtp_cmd);
357 if (!strcasecmp(cmd, "genmove")) {
358 cmd = "pachi-genmoves";
359 } else if (!strcasecmp(cmd, "kgs-genmove_cleanup")) {
360 cmd = "pachi-genmoves_cleanup";
361 } else if (!strcasecmp(cmd, "final_score")) {
362 cmd = "final_status_list";
365 // Let the slaves send the new gtp command:
366 update_cmd(b, cmd, args);
367 pthread_cond_broadcast(&cmd_cond);
369 /* Wait for replies here except for specific commands
370 * handled by the engine later. If we don't wait, we run
371 * the risk of getting out of sync with most slaves and
372 * sending complete command history too frequently. */
373 if (strcasecmp(cmd, "pachi-genmoves")
374 && strcasecmp(cmd, "pachi-genmoves_cleanup")
375 && strcasecmp(cmd, "final_status_list"))
376 get_replies(0);
378 pthread_mutex_unlock(&slave_lock);
379 return P_OK;
382 /* pachi-genmoves returns a line "=id total_playouts threads[ reserved]" then a list of lines
383 * "coord playouts value". Keep this function in sync with uct_notify().
384 * Return the move with most playouts, its average value, and stats for debugging.
385 * slave_lock is held on entry and on return. */
386 static coord_t
387 select_best_move(struct board *b, struct move_stats *best_stats,
388 int *total_playouts, int *total_threads)
390 assert(reply_count > 0);
392 /* +2 for pass and resign. */
393 struct move_stats *stats = alloca((board_size2(b)+2) * sizeof(struct move_stats));
394 memset(stats, 0, (board_size2(b)+2) * sizeof(*stats));
395 stats += 2;
397 coord_t best_move = pass;
398 int best_playouts = -1;
399 *total_playouts = *total_threads = 0;
401 for (int reply = 0; reply < reply_count; reply++) {
402 char *r = gtp_replies[reply];
403 int id, playouts, threads;
404 if (sscanf(r, "=%d %d %d", &id, &playouts, &threads) != 3) continue;
405 *total_playouts += playouts;
406 *total_threads += threads;
407 // Skip the rest of the firt line if any (allow future extensions)
408 r = strchr(r, '\n');
410 char move[64];
411 struct move_stats s;
412 while (r && sscanf(++r, "%63s %d %f", move, &s.playouts, &s.value) == 3) {
413 coord_t *c = str2coord(move, board_size(b));
414 stats_add_result(&stats[*c], s.value, s.playouts);
415 if (stats[*c].playouts > best_playouts) {
416 best_playouts = stats[*c].playouts;
417 best_move = *c;
419 coord_done(c);
420 r = strchr(r, '\n');
423 *best_stats = stats[best_move];
424 return best_move;
427 /* Time control is mostly done by the slaves, so we use default values here. */
428 #define FUSEKI_END 20
429 #define YOSE_START 40
431 static coord_t *
432 distributed_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive)
434 struct distributed *dist = e->data;
435 double start = time_now();
437 /* If we do not have time constraints we just wait for
438 * slaves to reply as they have been configured by default. */
439 long time_limit = 0;
440 if (ti->period != TT_NULL && ti->dim == TD_WALLTIME) {
441 struct time_stop stop;
442 time_stop_conditions(ti, b, FUSEKI_END, YOSE_START, &stop);
443 time_limit = ti->len.t.timer_start + stop.worst.time;
446 pthread_mutex_lock(&slave_lock);
447 get_replies(time_limit);
448 int replies = reply_count;
450 int playouts, threads;
451 dist->my_last_move.color = color;
452 dist->my_last_move.coord = select_best_move(b, &dist->my_last_stats, &playouts, &threads);
454 /* Tell the slaves to commit to the selected move, overwriting
455 * the last "pachi-genmoves" in the command history. */
456 char args[64];
457 char *coord = coord2str(dist->my_last_move.coord, b);
458 snprintf(args, sizeof(args), "%s %s\n", stone2str(color), coord);
459 update_cmd(b, "play", args);
460 pthread_cond_broadcast(&cmd_cond);
461 pthread_mutex_unlock(&slave_lock);
463 if (DEBUGL(1)) {
464 char buf[BSIZE];
465 enum stone color = dist->my_last_move.color;
466 double time = time_now() - start + 0.000001; /* avoid divide by zero */
467 snprintf(buf, sizeof(buf),
468 "GLOBAL WINNER is %s %s with score %1.4f (%d/%d games)\n"
469 "genmove in %0.2fs (%d games/s, %d games/s/slave, %d games/s/thread)\n",
470 stone2str(color), coord, get_value(dist->my_last_stats.value, color),
471 dist->my_last_stats.playouts, playouts, time,
472 (int)(playouts/time), (int)(playouts/time/replies),
473 (int)(playouts/time/threads));
474 logline(NULL, "*** ", buf);
476 free(coord);
477 return coord_copy(dist->my_last_move.coord);
480 static char *
481 distributed_chat(struct engine *e, struct board *b, char *cmd)
483 struct distributed *dist = e->data;
484 static char reply[BSIZE];
486 cmd += strspn(cmd, " \n\t");
487 if (!strncasecmp(cmd, "winrate", 7)) {
488 enum stone color = dist->my_last_move.color;
489 snprintf(reply, BSIZE, "In %d playouts at %d machines, %s %s can win with %.2f%% probability.",
490 dist->my_last_stats.playouts, active_slaves, stone2str(color),
491 coord2sstr(dist->my_last_move.coord, b),
492 100 * get_value(dist->my_last_stats.value, color));
493 return reply;
495 return NULL;
498 static int
499 scmp(const void *p1, const void *p2)
501 return strcasecmp(*(char * const *)p1, *(char * const *)p2);
504 static void
505 distributed_dead_group_list(struct engine *e, struct board *b, struct move_queue *mq)
507 pthread_mutex_lock(&slave_lock);
508 get_replies(0);
510 /* Find the most popular reply. */
511 qsort(gtp_replies, reply_count, sizeof(char *), scmp);
512 int best_reply = 0;
513 int best_count = 1;
514 int count = 1;
515 for (int reply = 1; reply < reply_count; reply++) {
516 if (!strcmp(gtp_replies[reply], gtp_replies[reply-1])) {
517 count++;
518 } else {
519 count = 1;
521 if (count > best_count) {
522 best_count = count;
523 best_reply = reply;
527 /* Pick the first move of each line as group. */
528 char *dead = gtp_replies[best_reply];
529 dead = strchr(dead, ' '); // skip "id "
530 while (dead && *++dead != '\n') {
531 coord_t *c = str2coord(dead, board_size(b));
532 mq_add(mq, *c);
533 coord_done(c);
534 dead = strchr(dead, '\n');
536 pthread_mutex_unlock(&slave_lock);
539 static struct distributed *
540 distributed_state_init(char *arg, struct board *b)
542 struct distributed *dist = calloc(1, sizeof(struct distributed));
544 dist->max_slaves = 100;
545 if (arg) {
546 char *optspec, *next = arg;
547 while (*next) {
548 optspec = next;
549 next += strcspn(next, ",");
550 if (*next) { *next++ = 0; } else { *next = 0; }
552 char *optname = optspec;
553 char *optval = strchr(optspec, '=');
554 if (optval) *optval++ = 0;
556 if (!strcasecmp(optname, "slave_port") && optval) {
557 dist->slave_port = strdup(optval);
558 } else if (!strcasecmp(optname, "proxy_port") && optval) {
559 dist->proxy_port = strdup(optval);
560 } else if (!strcasecmp(optname, "max_slaves") && optval) {
561 dist->max_slaves = atoi(optval);
562 } else if (!strcasecmp(optname, "slaves_quit")) {
563 dist->slaves_quit = !optval || atoi(optval);
564 } else {
565 fprintf(stderr, "distributed: Invalid engine argument %s or missing value\n", optname);
570 gtp_replies = calloc(dist->max_slaves, sizeof(char *));
572 if (!dist->slave_port) {
573 fprintf(stderr, "distributed: missing slave_port\n");
574 exit(1);
576 int slave_sock = port_listen(dist->slave_port, dist->max_slaves);
577 pthread_t thread;
578 for (int id = 0; id < dist->max_slaves; id++) {
579 pthread_create(&thread, NULL, slave_thread, (void *)(long)slave_sock);
582 if (dist->proxy_port) {
583 int proxy_sock = port_listen(dist->proxy_port, dist->max_slaves);
584 for (int id = 0; id < dist->max_slaves; id++) {
585 pthread_create(&thread, NULL, proxy_thread, (void *)(long)proxy_sock);
588 return dist;
591 struct engine *
592 engine_distributed_init(char *arg, struct board *b)
594 start_time = time_now();
595 struct distributed *dist = distributed_state_init(arg, b);
596 struct engine *e = calloc(1, sizeof(struct engine));
597 e->name = "Distributed Engine";
598 e->comment = "I'm playing the distributed engine. When I'm losing, I will resign, "
599 "if I think I win, I play until you pass. "
600 "Anyone can send me 'winrate' in private chat to get my assessment of the position.";
601 e->notify = distributed_notify;
602 e->genmove = distributed_genmove;
603 e->dead_group_list = distributed_dead_group_list;
604 e->chat = distributed_chat;
605 e->data = dist;
606 // Keep the threads and the open socket connections:
607 e->keep_on_clear = true;
609 return e;