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. */
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
{
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. */
46 /* All replies to latest gtp command are in gtp_replies[0..reply_count-1]. */
50 struct receive_buf
*receive_queue
;
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. */
79 pthread_mutex_lock(&slave_lock
);
82 /* Release exclusive access to the threads and commands state. */
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 */
92 logline(struct in_addr
*client
, char *prefix
, char *s
)
94 double now
= time_now();
96 char addr
[INET_ADDRSTRLEN
];
98 inet_ntop(AF_INET
, client
, addr
, sizeof(addr
));
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. */
110 proxy_thread(void *arg
)
112 int proxy_sock
= (long)arg
;
113 assert(proxy_sock
>= 0);
115 struct in_addr client
;
116 int conn
= open_server_connection(proxy_sock
, &client
);
117 FILE *f
= fdopen(conn
, "r");
119 while (fgets(buf
, BSIZE
, f
)) {
120 logline(&client
, "< ", buf
);
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. */
136 get_reply(FILE *f
, struct in_addr client
, char *reply
, void *bin_reply
, int *bin_size
)
140 if (!fgets(reply
, CMDS_SIZE
, f
)) return -1;
142 /* Check for binary reply. */
143 char *s
= strchr(reply
, '@');
145 if (s
) size
= atoi(s
+1);
146 assert(size
<= *bin_size
);
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') {
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();
166 while (size
&& (len
= fread(bin_reply
, 1, size
, f
)) > 0) {
167 bin_reply
= (char *)bin_reply
+ len
;
170 if (*bin_size
&& DEBUGVV(2)) {
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. */
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");
201 double start
= time_now();
203 fwrite(bin_buf
, 1, *bin_size
, f
);
206 if (DEBUGV(strchr(buf
, '@'), 2)) {
207 double ms
= (time_now() - start
) * 1000.0;
209 char *s
= strchr(buf
, '\n');
212 logline(&sstate
->client
, ">>", buf
);
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
);
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. */
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
;
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
;
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. */
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. */
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
;
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. */
287 sstate
->last_processed
= -1;
288 for (int n
= 0; n
< BUFFERS_PER_SLAVE
; n
++) {
289 sstate
->b
[n
].queue_index
= -1;
294 int index
= sstate
->b
[newest
].queue_index
;
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;
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. */
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
);
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
;
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. */
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. */
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
;
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
;
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
378 * slave_lock is held on both entry and exit of this function. */
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
;
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. */
398 s
= strchr(cmd
, '@');
400 snprintf(s
, cmd
+ cmd_size
- s
, "@%d\n", size
);
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. */
410 slave_loop(FILE *f
, char *reply_buf
, struct slave_state
*sstate
, bool resend
)
413 int last_cmd_count
= 0;
414 int last_reply_id
= -1;
418 /* Resend complete or partial history */
419 to_send
= next_command(last_reply_id
);
421 /* Wait for a new command. */
422 while (last_cmd_count
== cmd_count
)
423 pthread_cond_wait(&cmd_cond
, &slave_lock
);
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. */
431 void *bin_buf
= get_binary_arg(sstate
, gtp_cmd
,
432 gtp_cmds
+ CMDS_SIZE
- gtp_cmd
,
434 /* Check that the command is still valid. */
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
;
443 int reply_id
= send_command(to_send
, bin_buf
, &bin_size
, f
,
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. */
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
];
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+");
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. */
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");
492 if (!resend
) slave_state_alloc(&sstate
);
493 sstate
.client
= client
;
495 pthread_mutex_lock(&slave_lock
);
497 slave_loop(f
, reply_buf
, &sstate
, resend
);
499 assert(active_slaves
> 0);
501 // Unblock main thread if it was waiting for this slave.
502 pthread_cond_signal(&reply_cond
);
503 pthread_mutex_unlock(&slave_lock
);
507 logline(&client
, "= ", "lost slave\n");
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 */
518 update_cmd(struct board
*b
, char *cmd
, char *args
, bool new_id
)
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
;
526 int prev_id
= gtp_id
;
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
);
533 snprintf(gtp_cmd
, gtp_cmds
+ CMDS_SIZE
- gtp_cmd
, "%d %s %s",
534 gtp_id
, cmd
, *args
? args
: "\n");
537 /* Remember history for out-of-sync slaves. */
539 static struct cmd_history
*last
= NULL
;
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 */
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
)) {
562 memset(history
, 0, sizeof(history
));
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");
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. */
587 get_replies(double time_limit
, int min_replies
)
590 if (reply_count
> 0) {
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
);
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;
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. */
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;
637 for (int id
= 0; id
< max_slaves
; id
++) {
638 pthread_create(&thread
, NULL
, slave_thread
, (void *)(long)id
);
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
);