]> git.ipfire.org Git - thirdparty/git.git/blame - parallel-checkout.c
alloc.h: move ALLOC_GROW() functions from cache.h
[thirdparty/git.git] / parallel-checkout.c
CommitLineData
04155bda 1#include "cache.h"
36bf1958 2#include "alloc.h"
7531e4b6 3#include "config.h"
04155bda
MT
4#include "entry.h"
5#include "parallel-checkout.h"
e9e8adf1 6#include "pkt-line.h"
1c4d6f46 7#include "progress.h"
e9e8adf1
MT
8#include "run-command.h"
9#include "sigchain.h"
04155bda 10#include "streaming.h"
7531e4b6 11#include "thread-utils.h"
6a7bc9d1 12#include "trace2.h"
04155bda 13
e9e8adf1
MT
14struct pc_worker {
15 struct child_process cp;
16 size_t next_item_to_complete, nr_items_to_complete;
04155bda
MT
17};
18
19struct parallel_checkout {
20 enum pc_status status;
21 struct parallel_checkout_item *items; /* The parallel checkout queue. */
22 size_t nr, alloc;
1c4d6f46
MT
23 struct progress *progress;
24 unsigned int *progress_cnt;
04155bda
MT
25};
26
27static struct parallel_checkout parallel_checkout;
28
29enum pc_status parallel_checkout_status(void)
30{
31 return parallel_checkout.status;
32}
33
7531e4b6
MT
34static const int DEFAULT_THRESHOLD_FOR_PARALLELISM = 100;
35static const int DEFAULT_NUM_WORKERS = 1;
36
37void get_parallel_checkout_configs(int *num_workers, int *threshold)
38{
87094fc2
MT
39 char *env_workers = getenv("GIT_TEST_CHECKOUT_WORKERS");
40
41 if (env_workers && *env_workers) {
42 if (strtol_i(env_workers, 10, num_workers)) {
1a8aea85
JNA
43 die(_("invalid value for '%s': '%s'"),
44 "GIT_TEST_CHECKOUT_WORKERS", env_workers);
87094fc2
MT
45 }
46 if (*num_workers < 1)
47 *num_workers = online_cpus();
48
49 *threshold = 0;
50 return;
51 }
52
7531e4b6
MT
53 if (git_config_get_int("checkout.workers", num_workers))
54 *num_workers = DEFAULT_NUM_WORKERS;
55 else if (*num_workers < 1)
56 *num_workers = online_cpus();
57
58 if (git_config_get_int("checkout.thresholdForParallelism", threshold))
59 *threshold = DEFAULT_THRESHOLD_FOR_PARALLELISM;
60}
61
04155bda
MT
62void init_parallel_checkout(void)
63{
64 if (parallel_checkout.status != PC_UNINITIALIZED)
65 BUG("parallel checkout already initialized");
66
67 parallel_checkout.status = PC_ACCEPTING_ENTRIES;
68}
69
70static void finish_parallel_checkout(void)
71{
72 if (parallel_checkout.status == PC_UNINITIALIZED)
73 BUG("cannot finish parallel checkout: not initialized yet");
74
75 free(parallel_checkout.items);
76 memset(&parallel_checkout, 0, sizeof(parallel_checkout));
77}
78
79static int is_eligible_for_parallel_checkout(const struct cache_entry *ce,
80 const struct conv_attrs *ca)
81{
82 enum conv_attrs_classification c;
e9e8adf1 83 size_t packed_item_size;
04155bda
MT
84
85 /*
86 * Symlinks cannot be checked out in parallel as, in case of path
87 * collision, they could racily replace leading directories of other
88 * entries being checked out. Submodules are checked out in child
89 * processes, which have their own parallel checkout queues.
90 */
91 if (!S_ISREG(ce->ce_mode))
92 return 0;
93
e9e8adf1
MT
94 packed_item_size = sizeof(struct pc_item_fixed_portion) + ce->ce_namelen +
95 (ca->working_tree_encoding ? strlen(ca->working_tree_encoding) : 0);
96
97 /*
98 * The amount of data we send to the workers per checkout item is
99 * typically small (75~300B). So unless we find an insanely huge path
100 * of 64KB, we should never reach the 65KB limit of one pkt-line. If
101 * that does happen, we let the sequential code handle the item.
102 */
103 if (packed_item_size > LARGE_PACKET_DATA_MAX)
104 return 0;
105
04155bda
MT
106 c = classify_conv_attrs(ca);
107 switch (c) {
108 case CA_CLASS_INCORE:
109 return 1;
110
111 case CA_CLASS_INCORE_FILTER:
112 /*
113 * It would be safe to allow concurrent instances of
114 * single-file smudge filters, like rot13, but we should not
115 * assume that all filters are parallel-process safe. So we
116 * don't allow this.
117 */
118 return 0;
119
120 case CA_CLASS_INCORE_PROCESS:
121 /*
122 * The parallel queue and the delayed queue are not compatible,
123 * so they must be kept completely separated. And we can't tell
124 * if a long-running process will delay its response without
125 * actually asking it to perform the filtering. Therefore, this
126 * type of filter is not allowed in parallel checkout.
127 *
128 * Furthermore, there should only be one instance of the
129 * long-running process filter as we don't know how it is
130 * managing its own concurrency. So, spreading the entries that
131 * requisite such a filter among the parallel workers would
132 * require a lot more inter-process communication. We would
133 * probably have to designate a single process to interact with
134 * the filter and send all the necessary data to it, for each
135 * entry.
136 */
137 return 0;
138
139 case CA_CLASS_STREAMABLE:
140 return 1;
141
142 default:
143 BUG("unsupported conv_attrs classification '%d'", c);
144 }
145}
146
611c7785
MT
147int enqueue_checkout(struct cache_entry *ce, struct conv_attrs *ca,
148 int *checkout_counter)
04155bda
MT
149{
150 struct parallel_checkout_item *pc_item;
151
152 if (parallel_checkout.status != PC_ACCEPTING_ENTRIES ||
153 !is_eligible_for_parallel_checkout(ce, ca))
154 return -1;
155
156 ALLOC_GROW(parallel_checkout.items, parallel_checkout.nr + 1,
157 parallel_checkout.alloc);
158
e9e8adf1 159 pc_item = &parallel_checkout.items[parallel_checkout.nr];
04155bda
MT
160 pc_item->ce = ce;
161 memcpy(&pc_item->ca, ca, sizeof(pc_item->ca));
162 pc_item->status = PC_ITEM_PENDING;
e9e8adf1 163 pc_item->id = parallel_checkout.nr;
611c7785 164 pc_item->checkout_counter = checkout_counter;
e9e8adf1 165 parallel_checkout.nr++;
04155bda
MT
166
167 return 0;
168}
169
1c4d6f46
MT
170size_t pc_queue_size(void)
171{
172 return parallel_checkout.nr;
173}
174
175static void advance_progress_meter(void)
176{
177 if (parallel_checkout.progress) {
178 (*parallel_checkout.progress_cnt)++;
179 display_progress(parallel_checkout.progress,
180 *parallel_checkout.progress_cnt);
181 }
182}
183
04155bda
MT
184static int handle_results(struct checkout *state)
185{
186 int ret = 0;
187 size_t i;
188 int have_pending = 0;
189
190 /*
191 * We first update the successfully written entries with the collected
192 * stat() data, so that they can be found by mark_colliding_entries(),
193 * in the next loop, when necessary.
194 */
195 for (i = 0; i < parallel_checkout.nr; i++) {
196 struct parallel_checkout_item *pc_item = &parallel_checkout.items[i];
197 if (pc_item->status == PC_ITEM_WRITTEN)
198 update_ce_after_write(state, pc_item->ce, &pc_item->st);
199 }
200
201 for (i = 0; i < parallel_checkout.nr; i++) {
202 struct parallel_checkout_item *pc_item = &parallel_checkout.items[i];
203
204 switch(pc_item->status) {
205 case PC_ITEM_WRITTEN:
611c7785
MT
206 if (pc_item->checkout_counter)
207 (*pc_item->checkout_counter)++;
04155bda
MT
208 break;
209 case PC_ITEM_COLLIDED:
210 /*
211 * The entry could not be checked out due to a path
212 * collision with another entry. Since there can only
213 * be one entry of each colliding group on the disk, we
214 * could skip trying to check out this one and move on.
215 * However, this would leave the unwritten entries with
216 * null stat() fields on the index, which could
217 * potentially slow down subsequent operations that
218 * require refreshing it: git would not be able to
219 * trust st_size and would have to go to the filesystem
220 * to see if the contents match (see ie_modified()).
221 *
222 * Instead, let's pay the overhead only once, now, and
223 * call checkout_entry_ca() again for this file, to
224 * have its stat() data stored in the index. This also
225 * has the benefit of adding this entry and its
226 * colliding pair to the collision report message.
227 * Additionally, this overwriting behavior is consistent
228 * with what the sequential checkout does, so it doesn't
229 * add any extra overhead.
230 */
231 ret |= checkout_entry_ca(pc_item->ce, &pc_item->ca,
611c7785
MT
232 state, NULL,
233 pc_item->checkout_counter);
1c4d6f46 234 advance_progress_meter();
04155bda
MT
235 break;
236 case PC_ITEM_PENDING:
237 have_pending = 1;
238 /* fall through */
239 case PC_ITEM_FAILED:
240 ret = -1;
241 break;
242 default:
243 BUG("unknown checkout item status in parallel checkout");
244 }
245 }
246
247 if (have_pending)
248 error("parallel checkout finished with pending entries");
249
250 return ret;
251}
252
253static int reset_fd(int fd, const char *path)
254{
255 if (lseek(fd, 0, SEEK_SET) != 0)
256 return error_errno("failed to rewind descriptor of '%s'", path);
257 if (ftruncate(fd, 0))
258 return error_errno("failed to truncate file '%s'", path);
259 return 0;
260}
261
262static int write_pc_item_to_fd(struct parallel_checkout_item *pc_item, int fd,
263 const char *path)
264{
265 int ret;
266 struct stream_filter *filter;
267 struct strbuf buf = STRBUF_INIT;
268 char *blob;
e9aa762c 269 size_t size;
04155bda
MT
270 ssize_t wrote;
271
272 /* Sanity check */
273 assert(is_eligible_for_parallel_checkout(pc_item->ce, &pc_item->ca));
274
275 filter = get_stream_filter_ca(&pc_item->ca, &pc_item->ce->oid);
276 if (filter) {
277 if (stream_blob_to_fd(fd, &pc_item->ce->oid, filter, 1)) {
278 /* On error, reset fd to try writing without streaming */
279 if (reset_fd(fd, path))
280 return -1;
281 } else {
282 return 0;
283 }
284 }
285
286 blob = read_blob_entry(pc_item->ce, &size);
287 if (!blob)
288 return error("cannot read object %s '%s'",
289 oid_to_hex(&pc_item->ce->oid), pc_item->ce->name);
290
291 /*
292 * checkout metadata is used to give context for external process
293 * filters. Files requiring such filters are not eligible for parallel
e9e8adf1
MT
294 * checkout, so pass NULL. Note: if that changes, the metadata must also
295 * be passed from the main process to the workers.
04155bda
MT
296 */
297 ret = convert_to_working_tree_ca(&pc_item->ca, pc_item->ce->name,
298 blob, size, &buf, NULL);
299
300 if (ret) {
301 size_t newsize;
302 free(blob);
303 blob = strbuf_detach(&buf, &newsize);
304 size = newsize;
305 }
306
307 wrote = write_in_full(fd, blob, size);
308 free(blob);
309 if (wrote < 0)
310 return error("unable to write file '%s'", path);
311
312 return 0;
313}
314
315static int close_and_clear(int *fd)
316{
317 int ret = 0;
318
319 if (*fd >= 0) {
320 ret = close(*fd);
321 *fd = -1;
322 }
323
324 return ret;
325}
326
e9e8adf1
MT
327void write_pc_item(struct parallel_checkout_item *pc_item,
328 struct checkout *state)
04155bda
MT
329{
330 unsigned int mode = (pc_item->ce->ce_mode & 0100) ? 0777 : 0666;
331 int fd = -1, fstat_done = 0;
332 struct strbuf path = STRBUF_INIT;
333 const char *dir_sep;
334
335 strbuf_add(&path, state->base_dir, state->base_dir_len);
336 strbuf_add(&path, pc_item->ce->name, pc_item->ce->ce_namelen);
337
338 dir_sep = find_last_dir_sep(path.buf);
339
340 /*
341 * The leading dirs should have been already created by now. But, in
342 * case of path collisions, one of the dirs could have been replaced by
343 * a symlink (checked out after we enqueued this entry for parallel
344 * checkout). Thus, we must check the leading dirs again.
345 */
346 if (dir_sep && !has_dirs_only_path(path.buf, dir_sep - path.buf,
347 state->base_dir_len)) {
348 pc_item->status = PC_ITEM_COLLIDED;
6a7bc9d1 349 trace2_data_string("pcheckout", NULL, "collision/dirname", path.buf);
04155bda
MT
350 goto out;
351 }
352
353 fd = open(path.buf, O_WRONLY | O_CREAT | O_EXCL, mode);
354
355 if (fd < 0) {
356 if (errno == EEXIST || errno == EISDIR) {
357 /*
358 * Errors which probably represent a path collision.
359 * Suppress the error message and mark the item to be
360 * retried later, sequentially. ENOTDIR and ENOENT are
361 * also interesting, but the above has_dirs_only_path()
362 * call should have already caught these cases.
363 */
364 pc_item->status = PC_ITEM_COLLIDED;
6a7bc9d1
MT
365 trace2_data_string("pcheckout", NULL,
366 "collision/basename", path.buf);
04155bda
MT
367 } else {
368 error_errno("failed to open file '%s'", path.buf);
369 pc_item->status = PC_ITEM_FAILED;
370 }
371 goto out;
372 }
373
374 if (write_pc_item_to_fd(pc_item, fd, path.buf)) {
375 /* Error was already reported. */
376 pc_item->status = PC_ITEM_FAILED;
377 close_and_clear(&fd);
378 unlink(path.buf);
379 goto out;
380 }
381
382 fstat_done = fstat_checkout_output(fd, state, &pc_item->st);
383
384 if (close_and_clear(&fd)) {
385 error_errno("unable to close file '%s'", path.buf);
386 pc_item->status = PC_ITEM_FAILED;
387 goto out;
388 }
389
390 if (state->refresh_cache && !fstat_done && lstat(path.buf, &pc_item->st) < 0) {
391 error_errno("unable to stat just-written file '%s'", path.buf);
392 pc_item->status = PC_ITEM_FAILED;
393 goto out;
394 }
395
396 pc_item->status = PC_ITEM_WRITTEN;
397
398out:
399 strbuf_release(&path);
400}
401
e9e8adf1
MT
402static void send_one_item(int fd, struct parallel_checkout_item *pc_item)
403{
404 size_t len_data;
405 char *data, *variant;
406 struct pc_item_fixed_portion *fixed_portion;
407 const char *working_tree_encoding = pc_item->ca.working_tree_encoding;
408 size_t name_len = pc_item->ce->ce_namelen;
409 size_t working_tree_encoding_len = working_tree_encoding ?
410 strlen(working_tree_encoding) : 0;
411
412 /*
413 * Any changes in the calculation of the message size must also be made
414 * in is_eligible_for_parallel_checkout().
415 */
416 len_data = sizeof(struct pc_item_fixed_portion) + name_len +
417 working_tree_encoding_len;
418
3d20ed27 419 data = xmalloc(len_data);
e9e8adf1
MT
420
421 fixed_portion = (struct pc_item_fixed_portion *)data;
422 fixed_portion->id = pc_item->id;
423 fixed_portion->ce_mode = pc_item->ce->ce_mode;
424 fixed_portion->crlf_action = pc_item->ca.crlf_action;
425 fixed_portion->ident = pc_item->ca.ident;
426 fixed_portion->name_len = name_len;
427 fixed_portion->working_tree_encoding_len = working_tree_encoding_len;
428 /*
3d20ed27
MT
429 * We pad the unused bytes in the hash array because, otherwise,
430 * Valgrind would complain about passing uninitialized bytes to a
431 * write() syscall. The warning doesn't represent any real risk here,
432 * but it could hinder the detection of actual errors.
e9e8adf1 433 */
3d20ed27 434 oidcpy_with_padding(&fixed_portion->oid, &pc_item->ce->oid);
e9e8adf1
MT
435
436 variant = data + sizeof(*fixed_portion);
437 if (working_tree_encoding_len) {
438 memcpy(variant, working_tree_encoding, working_tree_encoding_len);
439 variant += working_tree_encoding_len;
440 }
441 memcpy(variant, pc_item->ce->name, name_len);
442
443 packet_write(fd, data, len_data);
444
445 free(data);
446}
447
448static void send_batch(int fd, size_t start, size_t nr)
449{
450 size_t i;
451 sigchain_push(SIGPIPE, SIG_IGN);
452 for (i = 0; i < nr; i++)
453 send_one_item(fd, &parallel_checkout.items[start + i]);
454 packet_flush(fd);
455 sigchain_pop(SIGPIPE);
456}
457
458static struct pc_worker *setup_workers(struct checkout *state, int num_workers)
459{
460 struct pc_worker *workers;
461 int i, workers_with_one_extra_item;
462 size_t base_batch_size, batch_beginning = 0;
463
464 ALLOC_ARRAY(workers, num_workers);
465
466 for (i = 0; i < num_workers; i++) {
467 struct child_process *cp = &workers[i].cp;
468
469 child_process_init(cp);
470 cp->git_cmd = 1;
471 cp->in = -1;
472 cp->out = -1;
473 cp->clean_on_exit = 1;
474 strvec_push(&cp->args, "checkout--worker");
475 if (state->base_dir_len)
476 strvec_pushf(&cp->args, "--prefix=%s", state->base_dir);
477 if (start_command(cp))
478 die("failed to spawn checkout worker");
479 }
480
481 base_batch_size = parallel_checkout.nr / num_workers;
482 workers_with_one_extra_item = parallel_checkout.nr % num_workers;
483
484 for (i = 0; i < num_workers; i++) {
485 struct pc_worker *worker = &workers[i];
486 size_t batch_size = base_batch_size;
487
488 /* distribute the extra work evenly */
489 if (i < workers_with_one_extra_item)
490 batch_size++;
491
492 send_batch(worker->cp.in, batch_beginning, batch_size);
493 worker->next_item_to_complete = batch_beginning;
494 worker->nr_items_to_complete = batch_size;
495
496 batch_beginning += batch_size;
497 }
498
499 return workers;
500}
501
502static void finish_workers(struct pc_worker *workers, int num_workers)
503{
504 int i;
505
506 /*
507 * Close pipes before calling finish_command() to let the workers
508 * exit asynchronously and avoid spending extra time on wait().
509 */
510 for (i = 0; i < num_workers; i++) {
511 struct child_process *cp = &workers[i].cp;
512 if (cp->in >= 0)
513 close(cp->in);
514 if (cp->out >= 0)
515 close(cp->out);
516 }
517
518 for (i = 0; i < num_workers; i++) {
519 int rc = finish_command(&workers[i].cp);
520 if (rc > 128) {
521 /*
522 * For a normal non-zero exit, the worker should have
523 * already printed something useful to stderr. But a
524 * death by signal should be mentioned to the user.
525 */
526 error("checkout worker %d died of signal %d", i, rc - 128);
527 }
528 }
529
530 free(workers);
531}
532
533static inline void assert_pc_item_result_size(int got, int exp)
534{
535 if (got != exp)
536 BUG("wrong result size from checkout worker (got %dB, exp %dB)",
537 got, exp);
538}
539
540static void parse_and_save_result(const char *buffer, int len,
541 struct pc_worker *worker)
542{
543 struct pc_item_result *res;
544 struct parallel_checkout_item *pc_item;
545 struct stat *st = NULL;
546
547 if (len < PC_ITEM_RESULT_BASE_SIZE)
548 BUG("too short result from checkout worker (got %dB, exp >=%dB)",
549 len, (int)PC_ITEM_RESULT_BASE_SIZE);
550
551 res = (struct pc_item_result *)buffer;
552
553 /*
554 * Worker should send either the full result struct on success, or
555 * just the base (i.e. no stat data), otherwise.
556 */
557 if (res->status == PC_ITEM_WRITTEN) {
558 assert_pc_item_result_size(len, (int)sizeof(struct pc_item_result));
559 st = &res->st;
560 } else {
561 assert_pc_item_result_size(len, (int)PC_ITEM_RESULT_BASE_SIZE);
562 }
563
564 if (!worker->nr_items_to_complete)
565 BUG("received result from supposedly finished checkout worker");
566 if (res->id != worker->next_item_to_complete)
567 BUG("unexpected item id from checkout worker (got %"PRIuMAX", exp %"PRIuMAX")",
568 (uintmax_t)res->id, (uintmax_t)worker->next_item_to_complete);
569
570 worker->next_item_to_complete++;
571 worker->nr_items_to_complete--;
572
573 pc_item = &parallel_checkout.items[res->id];
574 pc_item->status = res->status;
575 if (st)
576 pc_item->st = *st;
1c4d6f46
MT
577
578 if (res->status != PC_ITEM_COLLIDED)
579 advance_progress_meter();
e9e8adf1
MT
580}
581
582static void gather_results_from_workers(struct pc_worker *workers,
583 int num_workers)
584{
585 int i, active_workers = num_workers;
586 struct pollfd *pfds;
587
588 CALLOC_ARRAY(pfds, num_workers);
589 for (i = 0; i < num_workers; i++) {
590 pfds[i].fd = workers[i].cp.out;
591 pfds[i].events = POLLIN;
592 }
593
594 while (active_workers) {
595 int nr = poll(pfds, num_workers, -1);
596
597 if (nr < 0) {
598 if (errno == EINTR)
599 continue;
600 die_errno("failed to poll checkout workers");
601 }
602
603 for (i = 0; i < num_workers && nr > 0; i++) {
604 struct pc_worker *worker = &workers[i];
605 struct pollfd *pfd = &pfds[i];
606
607 if (!pfd->revents)
608 continue;
609
610 if (pfd->revents & POLLIN) {
ec9a37d6 611 int len = packet_read(pfd->fd, packet_buffer,
e9e8adf1
MT
612 sizeof(packet_buffer), 0);
613
614 if (len < 0) {
615 BUG("packet_read() returned negative value");
616 } else if (!len) {
617 pfd->fd = -1;
618 active_workers--;
619 } else {
620 parse_and_save_result(packet_buffer,
621 len, worker);
622 }
623 } else if (pfd->revents & POLLHUP) {
624 pfd->fd = -1;
625 active_workers--;
626 } else if (pfd->revents & (POLLNVAL | POLLERR)) {
627 die("error polling from checkout worker");
628 }
629
630 nr--;
631 }
632 }
633
634 free(pfds);
635}
636
04155bda
MT
637static void write_items_sequentially(struct checkout *state)
638{
639 size_t i;
640
1c4d6f46
MT
641 for (i = 0; i < parallel_checkout.nr; i++) {
642 struct parallel_checkout_item *pc_item = &parallel_checkout.items[i];
643 write_pc_item(pc_item, state);
644 if (pc_item->status != PC_ITEM_COLLIDED)
645 advance_progress_meter();
646 }
04155bda
MT
647}
648
1c4d6f46
MT
649int run_parallel_checkout(struct checkout *state, int num_workers, int threshold,
650 struct progress *progress, unsigned int *progress_cnt)
04155bda 651{
7531e4b6 652 int ret;
04155bda
MT
653
654 if (parallel_checkout.status != PC_ACCEPTING_ENTRIES)
655 BUG("cannot run parallel checkout: uninitialized or already running");
656
657 parallel_checkout.status = PC_RUNNING;
1c4d6f46
MT
658 parallel_checkout.progress = progress;
659 parallel_checkout.progress_cnt = progress_cnt;
04155bda 660
e9e8adf1
MT
661 if (parallel_checkout.nr < num_workers)
662 num_workers = parallel_checkout.nr;
663
7531e4b6 664 if (num_workers <= 1 || parallel_checkout.nr < threshold) {
e9e8adf1
MT
665 write_items_sequentially(state);
666 } else {
667 struct pc_worker *workers = setup_workers(state, num_workers);
668 gather_results_from_workers(workers, num_workers);
669 finish_workers(workers, num_workers);
670 }
671
04155bda
MT
672 ret = handle_results(state);
673
674 finish_parallel_checkout();
675 return ret;
676}