Distributed engine: Define hook to get stats received from slaves
[pachi/json.git] / distributed / protocol.c
blob9107f06ed387856c5d11478f11c00a887555b129
1 /* The functions implementing the master-slave protocol of the
2 * distributed engine are grouped here. They are independent
3 * of the gtp protocol. See the comments at the top of distributed.c
4 * for a general introduction to the distributed engine. */
6 #include <assert.h>
7 #include <stdio.h>
8 #include <pthread.h>
9 #include <ctype.h>
11 #define DEBUG
13 #include "random.h"
14 #include "timeinfo.h"
15 #include "playout.h"
16 #include "network.h"
17 #include "debug.h"
18 #include "distributed/distributed.h"
19 #include "distributed/protocol.h"
21 /* All gtp commands for current game separated by \n */
22 static char gtp_cmds[CMDS_SIZE];
24 /* Latest gtp command sent to slaves. */
25 static char *gtp_cmd = NULL;
27 /* Slaves send gtp_cmd when cmd_count changes. */
28 static int cmd_count = 0;
30 /* Remember at most 10 gtp ids per move: kgs-rules, boardsize, clear_board,
31 * time_settings, komi, handicap, genmoves, play pass, play pass, final_status_list */
32 #define MAX_CMDS_PER_MOVE 10
34 /* History of gtp commands sent for current game, indexed by move. */
35 static struct cmd_history {
36 int gtp_id;
37 char *next_cmd;
38 } history[MAX_GAMELEN][MAX_CMDS_PER_MOVE];
40 /* Number of active slave machines working for this master. */
41 int active_slaves = 0;
43 /* Number of replies to last gtp command already received. */
44 int reply_count = 0;
46 /* All replies to latest gtp command are in gtp_replies[0..reply_count-1]. */
47 char **gtp_replies;
50 struct receive_buf *receive_queue;
51 int queue_length = 0;
52 static int queue_max_length;
54 /* Mutex protecting all variables above. receive_queue may be
55 * read without the lock but is only written with lock held. */
56 static pthread_mutex_t slave_lock = PTHREAD_MUTEX_INITIALIZER;
58 /* Condition signaled when a new gtp command is available. */
59 static pthread_cond_t cmd_cond = PTHREAD_COND_INITIALIZER;
61 /* Condition signaled when reply_count increases. */
62 static pthread_cond_t reply_cond = PTHREAD_COND_INITIALIZER;
64 /* Mutex protecting stderr. Must not be held at same time as slave_lock. */
65 static pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER;
67 /* Absolute time when this program was started.
68 * For debugging only. */
69 static double start_time;
71 /* Default slave state. */
72 struct slave_state default_sstate;
75 /* Get exclusive access to the threads and commands state. */
76 void
77 protocol_lock(void)
79 pthread_mutex_lock(&slave_lock);
82 /* Release exclusive access to the threads and commands state. */
83 void
84 protocol_unlock(void)
86 pthread_mutex_unlock(&slave_lock);
89 /* Write the time, client address, prefix, and string s to stderr atomically.
90 * s should end with a \n */
91 void
92 logline(struct in_addr *client, char *prefix, char *s)
94 double now = time_now();
96 char addr[INET_ADDRSTRLEN];
97 if (client) {
98 inet_ntop(AF_INET, client, addr, sizeof(addr));
99 } else {
100 addr[0] = '\0';
102 pthread_mutex_lock(&log_lock);
103 fprintf(stderr, "%s%15s %9.3f: %s", prefix, addr, now - start_time, s);
104 pthread_mutex_unlock(&log_lock);
107 /* Thread opening a connection on the given socket and copying input
108 * from there to stderr. */
109 static void *
110 proxy_thread(void *arg)
112 int proxy_sock = (long)arg;
113 assert(proxy_sock >= 0);
114 for (;;) {
115 struct in_addr client;
116 int conn = open_server_connection(proxy_sock, &client);
117 FILE *f = fdopen(conn, "r");
118 char buf[BSIZE];
119 while (fgets(buf, BSIZE, f)) {
120 logline(&client, "< ", buf);
122 fclose(f);
126 /* Get a reply to one gtp command. Return the gtp command id,
127 * or -1 if error. reply must have at least CMDS_SIZE bytes.
128 * The ascii reply ends with an empty line; if the first line
129 * contains "@size", a binary reply of size bytes follows the
130 * empty line. @size is not standard gtp, it is only used
131 * internally by Pachi for the genmoves command; it must be the
132 * last parameter on the line.
133 * *bin_size is the maximum size upon entry, actual size on return.
134 * slave_lock is not held on either entry or exit of this function. */
135 static int
136 get_reply(FILE *f, struct in_addr client, char *reply, void *bin_reply, int *bin_size)
138 int reply_id = -1;
139 *reply = '\0';
140 if (!fgets(reply, CMDS_SIZE, f)) return -1;
142 /* Check for binary reply. */
143 char *s = strchr(reply, '@');
144 int size = 0;
145 if (s) size = atoi(s+1);
146 assert(size <= *bin_size);
147 *bin_size = size;
149 if (DEBUGV(s, 2))
150 logline(&client, "<<", reply);
151 if ((*reply == '=' || *reply == '?') && isdigit(reply[1]))
152 reply_id = atoi(reply+1);
154 /* Read the rest of the ascii reply */
155 char *line = reply + strlen(reply);
156 while (fgets(line, reply + CMDS_SIZE - line, f) && *line != '\n') {
157 if (DEBUGL(3))
158 logline(&client, "<<", line);
159 line += strlen(line);
161 if (*line != '\n') return -1;
163 /* Read the binary reply if any. */
164 double start = time_now();
165 int len;
166 while (size && (len = fread(bin_reply, 1, size, f)) > 0) {
167 bin_reply = (char *)bin_reply + len;
168 size -= len;
170 if (*bin_size && DEBUGVV(2)) {
171 char buf[1024];
172 snprintf(buf, sizeof(buf), "read reply %d bytes in %.4fms\n", *bin_size,
173 (time_now() - start)*1000);
174 logline(&client, "= ", buf);
176 return size ? -1 : reply_id;
179 /* Send the gtp command to_send and get a reply from the slave machine.
180 * Write the reply in buf which must have at least CMDS_SIZE bytes.
181 * If *bin_size > 0, send bin_buf after the gtp command.
182 * Return any binary reply in bin_buf and set its size in bin_size.
183 * bin_buf is private to the slave and need not be copied.
184 * Return the gtp command id, or -1 if error.
185 * slave_lock is held on both entry and exit of this function. */
186 static int
187 send_command(char *to_send, void *bin_buf, int *bin_size,
188 FILE *f, struct slave_state *sstate, char *buf)
190 assert(to_send && gtp_cmd && bin_buf && bin_size);
191 strncpy(buf, to_send, CMDS_SIZE);
192 bool resend = to_send != gtp_cmd;
194 pthread_mutex_unlock(&slave_lock);
196 if (DEBUGL(1) && resend)
197 logline(&sstate->client, "? ",
198 to_send == gtp_cmds ? "resend all\n" : "partial resend\n");
199 fputs(buf, f);
201 double start = time_now();
202 if (*bin_size)
203 fwrite(bin_buf, 1, *bin_size, f);
204 fflush(f);
206 if (DEBUGV(strchr(buf, '@'), 2)) {
207 double ms = (time_now() - start) * 1000.0;
208 if (!DEBUGL(3)) {
209 char *s = strchr(buf, '\n');
210 if (s) s[1] = '\0';
212 logline(&sstate->client, ">>", buf);
213 if (*bin_size) {
214 char b[1024];
215 snprintf(b, sizeof(b),
216 "sent args %d bytes in %.4fms\n", *bin_size, ms);
217 logline(&sstate->client, "= ", b);
221 /* Reuse the buffers for the reply. */
222 *bin_size = sstate->max_buf_size;
223 int reply_id = get_reply(f, sstate->client, buf, bin_buf, bin_size);
225 pthread_mutex_lock(&slave_lock);
226 return reply_id;
229 /* Return the command sent after that with the given gtp id,
230 * or gtp_cmds if the id wasn't used in this game. If a play command
231 * has overwritten a genmoves command, return the play command.
232 * slave_lock is held on both entry and exit of this function. */
233 static char *
234 next_command(int cmd_id)
236 if (cmd_id == -1) return gtp_cmds;
238 int last_id = atoi(gtp_cmd);
239 int reply_move = move_number(cmd_id);
240 if (reply_move > move_number(last_id)) return gtp_cmds;
242 int slot;
243 for (slot = 0; slot < MAX_CMDS_PER_MOVE; slot++) {
244 if (cmd_id == history[reply_move][slot].gtp_id) break;
246 if (slot == MAX_CMDS_PER_MOVE) return gtp_cmds;
248 char *next = history[reply_move][slot].next_cmd;
249 assert(next);
250 return next;
253 /* Allocate buffers for a slave thread. The state should have been
254 * initialized already as a copy of the default slave state.
255 * slave_lock is not held on either entry or exit of this function. */
256 static void
257 slave_state_alloc(struct slave_state *sstate)
259 for (int n = 0; n < BUFFERS_PER_SLAVE; n++) {
260 sstate->b[n].buf = malloc2(sstate->max_buf_size);
262 if (sstate->alloc_hook) sstate->alloc_hook(sstate);
265 /* Get a free binary buffer, first invalidating it in the receive
266 * queue if necessary. In practice all buffers should be used
267 * before they are invalidated, if BUFFERS_PER_SLAVE is large enough.
268 * slave_lock is held on both entry and exit of this function. */
269 static void *
270 get_free_buf(struct slave_state *sstate, bool new_id)
272 int newest = (sstate->newest_buf + 1) & (BUFFERS_PER_SLAVE - 1);
273 sstate->newest_buf = newest;
274 void *buf = sstate->b[newest].buf;
276 if (DEBUGVV(7)) {
277 char b[1024];
278 snprintf(b, sizeof(b), "get free %d index %d buf=%p qlength %d\n",
279 newest, sstate->b[newest].queue_index, buf, queue_length);
280 logline(&sstate->client, "? ", b);
283 /* For a new command, previous indices in receive_queue
284 * are now meaningless. In particular they may be
285 * beyond the current queue_length. */
286 if (new_id) {
287 sstate->last_processed = -1;
288 for (int n = 0; n < BUFFERS_PER_SLAVE; n++) {
289 sstate->b[n].queue_index = -1;
291 return buf;
294 int index = sstate->b[newest].queue_index;
295 if (index >= 0) {
296 assert(receive_queue[index].thread_id == sstate->thread_id);
297 assert(receive_queue[index].buf == buf);
298 /* Invalidate the buffer. */
299 receive_queue[index].buf = NULL;
300 sstate->b[newest].queue_index = -1;
302 return buf;
305 /* Insert a buffer in the receive queue. It should be the most
306 * recent buffer allocated by the calling thread.
307 * slave_lock is held on both entry and exit of this function. */
308 static void
309 insert_buf(struct slave_state *sstate, void *buf, int size)
311 assert(queue_length < queue_max_length);
313 int newest = sstate->newest_buf;
314 assert(buf == sstate->b[newest].buf);
316 /* Update the buffer if necessary before making it
317 * available to other threads. */
318 if (sstate->insert_hook) sstate->insert_hook(buf, size);
320 if (DEBUGVV(7)) {
321 char b[1024];
322 snprintf(b, sizeof(b), "insert newest %d rq[%d]->%p\n",
323 newest, queue_length, buf);
324 logline(&sstate->client, "? ", b);
326 receive_queue[queue_length].buf = buf;
327 receive_queue[queue_length].size = size;
328 receive_queue[queue_length].thread_id = sstate->thread_id;
329 sstate->b[newest].queue_index = queue_length;
330 queue_length++;
333 /* Process the reply received from a slave machine.
334 * Copy the ascii part to reply_buf and insert the binary part
335 * (if any) in the receive queue.
336 * Return false if ok, true if the slave is out of sync.
337 * slave_lock is held on both entry and exit of this function. */
338 static bool
339 process_reply(int reply_id, char *reply, char *reply_buf,
340 void *bin_reply, int bin_size, int *last_reply_id,
341 int *reply_slot, struct slave_state *sstate)
343 /* Resend everything if slave returned an error. */
344 if (*reply != '=') {
345 *last_reply_id = -1;
346 return true;
348 /* Make sure we are still in sync. cmd_count may have
349 * changed but the reply is valid as long as cmd_id didn't
350 * change (this only occurs for consecutive genmoves). */
351 int cmd_id = atoi(gtp_cmd);
352 if (reply_id != cmd_id) {
353 *last_reply_id = reply_id;
354 return true;
357 strncpy(reply_buf, reply, CMDS_SIZE);
358 if (reply_id != *last_reply_id)
359 *reply_slot = reply_count++;
360 gtp_replies[*reply_slot] = reply_buf;
362 if (bin_size) insert_buf(sstate, bin_reply, bin_size);
364 pthread_cond_signal(&reply_cond);
365 *last_reply_id = reply_id;
366 return false;
369 /* Get the binary arg for the given command, and update the command
370 * if necessary. For now, only genmoves has a binary argument, and
371 * we return the best stats increments from all other slaves.
372 * Set *bin_size to 0 if the command doesn't take binary arguments,
373 * but still return a buffer, to be used for the reply.
374 * Return NULL if the binary arg is obsolete by the time we have
375 * finished computing it, because a new command is available.
376 * This version only gets the buffer for the reply, to be completed
377 * in future commits.
378 * slave_lock is held on both entry and exit of this function. */
379 void *
380 get_binary_arg(struct slave_state *sstate, char *cmd, int cmd_size, int *bin_size)
382 int cmd_id = atoi(gtp_cmd);
383 void *buf = get_free_buf(sstate, cmd_id != sstate->last_cmd_id);
384 sstate->last_cmd_id = cmd_id;
386 *bin_size = 0;
387 char *s = strchr(cmd, '@');
388 if (!s || !sstate->args_hook) return buf;
390 int size = sstate->args_hook(buf, sstate, cmd_id);
392 /* Check that the command is still valid. */
393 if (atoi(gtp_cmd) != cmd_id) return NULL;
395 /* Set the correct binary size for this slave.
396 * cmd may have been overwritten with new parameters. */
397 *bin_size = size;
398 s = strchr(cmd, '@');
399 assert(s);
400 snprintf(s, cmd + cmd_size - s, "@%d\n", size);
401 return buf;
404 /* Main loop of a slave thread.
405 * Send the current command to the slave machine and wait for a reply.
406 * Resend command history if the slave machine is out of sync.
407 * Returns when the connection with the slave machine is cut.
408 * slave_lock is held on both entry and exit of this function. */
409 static void
410 slave_loop(FILE *f, char *reply_buf, struct slave_state *sstate, bool resend)
412 char *to_send;
413 int last_cmd_count = 0;
414 int last_reply_id = -1;
415 int reply_slot = -1;
416 for (;;) {
417 if (resend) {
418 /* Resend complete or partial history */
419 to_send = next_command(last_reply_id);
420 } else {
421 /* Wait for a new command. */
422 while (last_cmd_count == cmd_count)
423 pthread_cond_wait(&cmd_cond, &slave_lock);
424 to_send = gtp_cmd;
427 /* Command available, send it to slave machine.
428 * If slave was out of sync, send the history.
429 * But first get binary arguments if necessary. */
430 int bin_size = 0;
431 void *bin_buf = get_binary_arg(sstate, gtp_cmd,
432 gtp_cmds + CMDS_SIZE - gtp_cmd,
433 &bin_size);
434 /* Check that the command is still valid. */
435 resend = true;
436 if (!bin_buf) continue;
438 /* Send the command and get the reply, which always ends with \n\n
439 * The slave machine sends "=id reply" or "?id reply"
440 * with id == cmd_id if it is in sync. */
441 last_cmd_count = cmd_count;
442 char buf[CMDS_SIZE];
443 int reply_id = send_command(to_send, bin_buf, &bin_size, f,
444 sstate, buf);
445 if (reply_id == -1) return;
447 resend = process_reply(reply_id, buf, reply_buf, bin_buf, bin_size,
448 &last_reply_id, &reply_slot, sstate);
452 /* Thread sending gtp commands to one slave machine, and
453 * reading replies. If a slave machine dies, this thread waits
454 * for a connection from another slave.
455 * The large buffers are allocated only once we get a first
456 * connection, to avoid wasting memory if max_slaves is too large.
457 * We do not invalidate the received buffers if a slave disconnects;
458 * they are still useful for other slaves. */
459 static void *
460 slave_thread(void *arg)
462 struct slave_state sstate = default_sstate;
463 sstate.thread_id = (long)arg;
465 assert(sstate.slave_sock >= 0);
466 char reply_buf[CMDS_SIZE];
467 bool resend = false;
469 for (;;) {
470 /* Wait for a connection from any slave. */
471 struct in_addr client;
472 int conn = open_server_connection(sstate.slave_sock, &client);
474 FILE *f = fdopen(conn, "r+");
475 if (DEBUGL(2)) {
476 snprintf(reply_buf, sizeof(reply_buf),
477 "new slave, id %d\n", sstate.thread_id);
478 logline(&client, "= ", reply_buf);
481 /* Minimal check of the slave identity. */
482 fputs("name\n", f);
483 if (!fgets(reply_buf, sizeof(reply_buf), f)
484 || strncasecmp(reply_buf, "= Pachi", 7)
485 || !fgets(reply_buf, sizeof(reply_buf), f)
486 || strcmp(reply_buf, "\n")) {
487 logline(&client, "? ", "bad slave\n");
488 fclose(f);
489 continue;
492 if (!resend) slave_state_alloc(&sstate);
493 sstate.client = client;
495 pthread_mutex_lock(&slave_lock);
496 active_slaves++;
497 slave_loop(f, reply_buf, &sstate, resend);
499 assert(active_slaves > 0);
500 active_slaves--;
501 // Unblock main thread if it was waiting for this slave.
502 pthread_cond_signal(&reply_cond);
503 pthread_mutex_unlock(&slave_lock);
505 resend = true;
506 if (DEBUGL(2))
507 logline(&client, "= ", "lost slave\n");
508 fclose(f);
512 /* Create a new gtp command for all slaves. The slave lock is held
513 * upon entry and upon return, so the command will actually be
514 * sent when the lock is released. The last command is overwritten
515 * if gtp_cmd points to a non-empty string. cmd is a single word;
516 * args has all arguments and is empty or has a trailing \n */
517 void
518 update_cmd(struct board *b, char *cmd, char *args, bool new_id)
520 assert(gtp_cmd);
521 /* To make sure the slaves are in sync, we ignore the original id
522 * and use the board number plus some random bits as gtp id. */
523 static int gtp_id = -1;
524 int moves = is_reset(cmd) ? 0 : b->moves;
525 if (new_id) {
526 int prev_id = gtp_id;
527 do {
528 /* fast_random() is 16-bit only so the multiplication can't overflow. */
529 gtp_id = force_reply(moves + fast_random(65535) * DIST_GAMELEN);
530 } while (gtp_id == prev_id);
531 reply_count = 0;
533 snprintf(gtp_cmd, gtp_cmds + CMDS_SIZE - gtp_cmd, "%d %s %s",
534 gtp_id, cmd, *args ? args : "\n");
535 cmd_count++;
537 /* Remember history for out-of-sync slaves. */
538 static int slot = 0;
539 static struct cmd_history *last = NULL;
540 if (new_id) {
541 if (last) last->next_cmd = gtp_cmd;
542 slot = (slot + 1) % MAX_CMDS_PER_MOVE;
543 last = &history[moves][slot];
544 last->gtp_id = gtp_id;
545 last->next_cmd = NULL;
547 // Notify the slave threads about the new command.
548 pthread_cond_broadcast(&cmd_cond);
551 /* Update the command history, then create a new gtp command
552 * for all slaves. The slave lock is held upon entry and
553 * upon return, so the command will actually be sent when the
554 * lock is released. cmd is a single word; args has all
555 * arguments and is empty or has a trailing \n */
556 void
557 new_cmd(struct board *b, char *cmd, char *args)
559 // Clear the history when a new game starts:
560 if (!gtp_cmd || is_gamestart(cmd)) {
561 gtp_cmd = gtp_cmds;
562 memset(history, 0, sizeof(history));
563 } else {
564 /* Preserve command history for new slaves.
565 * To indicate that the slave should only reply to
566 * the last command we force the id of previous
567 * commands to be just the move number. */
568 int id = prevent_reply(atoi(gtp_cmd));
569 int len = strspn(gtp_cmd, "0123456789");
570 char buf[32];
571 snprintf(buf, sizeof(buf), "%0*d", len, id);
572 memcpy(gtp_cmd, buf, len);
574 gtp_cmd += strlen(gtp_cmd);
577 // Let the slave threads send the new gtp command:
578 update_cmd(b, cmd, args, true);
581 /* Wait for at least one new reply. Return when at least
582 * min_replies slaves have already replied, or when the
583 * given absolute time is passed.
584 * The replies are returned in gtp_replies[0..reply_count-1]
585 * slave_lock is held on entry and on return. */
586 void
587 get_replies(double time_limit, int min_replies)
589 for (;;) {
590 if (reply_count > 0) {
591 struct timespec ts;
592 double sec;
593 ts.tv_nsec = (int)(modf(time_limit, &sec)*1000000000.0);
594 ts.tv_sec = (int)sec;
595 pthread_cond_timedwait(&reply_cond, &slave_lock, &ts);
596 } else {
597 pthread_cond_wait(&reply_cond, &slave_lock);
599 if (reply_count == 0) continue;
600 if (reply_count >= min_replies || reply_count >= active_slaves) return;
601 if (time_now() >= time_limit) break;
603 if (DEBUGL(1)) {
604 char buf[1024];
605 snprintf(buf, sizeof(buf),
606 "get_replies timeout %.3f >= %.3f, replies %d < min %d, active %d\n",
607 time_now() - start_time, time_limit - start_time,
608 reply_count, min_replies, active_slaves);
609 logline(NULL, "? ", buf);
611 assert(reply_count > 0);
614 /* In a 30s move with at least 5ms per genmoves we get at most
615 * 6000 genmoves per slave. */
616 #define MAX_GENMOVES_PER_SLAVE 6000
618 /* Allocate the receive queue, and create the slave and proxy threads.
619 * max_buf_size and the merge-related fields of default_sstate must
620 * already be initialized. */
621 void
622 protocol_init(char *slave_port, char *proxy_port, int max_slaves)
624 start_time = time_now();
626 queue_max_length = max_slaves * MAX_GENMOVES_PER_SLAVE;
627 receive_queue = calloc2(queue_max_length, sizeof(*receive_queue));
629 default_sstate.slave_sock = port_listen(slave_port, max_slaves);
630 default_sstate.last_processed = -1;
632 for (int n = 0; n < BUFFERS_PER_SLAVE; n++) {
633 default_sstate.b[n].queue_index = -1;
636 pthread_t thread;
637 for (int id = 0; id < max_slaves; id++) {
638 pthread_create(&thread, NULL, slave_thread, (void *)(long)id);
641 if (proxy_port) {
642 int proxy_sock = port_listen(proxy_port, max_slaves);
643 for (int id = 0; id < max_slaves; id++) {
644 pthread_create(&thread, NULL, proxy_thread, (void *)(long)proxy_sock);