1 /* 2 * Copyright (c) 2019-2020 The DragonFly Project. All rights reserved. 3 * 4 * This code is derived from software contributed to The DragonFly Project 5 * by Matthew Dillon <dillon@backplane.com> 6 * 7 * This code uses concepts and configuration based on 'synth', by 8 * John R. Marino <draco@marino.st>, which was written in ada. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 14 * 1. Redistributions of source code must retain the above copyright 15 * notice, this list of conditions and the following disclaimer. 16 * 2. Redistributions in binary form must reproduce the above copyright 17 * notice, this list of conditions and the following disclaimer in 18 * the documentation and/or other materials provided with the 19 * distribution. 20 * 3. Neither the name of The DragonFly Project nor the names of its 21 * contributors may be used to endorse or promote products derived 22 * from this software without specific, prior written permission. 23 * 24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 25 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 26 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 27 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 28 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 29 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, 30 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 32 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 33 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 34 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 35 * SUCH DAMAGE. 36 */ 37 #include "dsynth.h" 38 39 static worker_t WorkerAry[MAXWORKERS]; 40 static int BuildInitialized; 41 static int RunningWorkers; 42 int DynamicMaxWorkers; 43 static int FailedWorkers; 44 static long RunningPkgDepSize; 45 static pthread_mutex_t WorkerMutex; 46 static pthread_cond_t WorkerCond; 47 48 static int build_find_leaves(pkg_t *parent, pkg_t *pkg, 49 pkg_t ***build_tailp, int *app, int *hasworkp, 50 int depth, int first, int first_one_only); 51 static int buildCalculateDepiDepth(pkg_t *pkg); 52 static void build_clear_trav(pkg_t *pkg); 53 static void startbuild(pkg_t **build_listp, pkg_t ***build_tailp); 54 static int qsort_depi(const void *pkg1, const void *pkg2); 55 static int qsort_idep(const void *pkg1, const void *pkg2); 56 static void startworker(pkg_t *pkg, worker_t *work); 57 static void cleanworker(worker_t *work); 58 static void waitbuild(int whilematch, int dynamicmax); 59 static void workercomplete(worker_t *work); 60 static void *childBuilderThread(void *arg); 61 static int childInstallPkgDeps(worker_t *work); 62 static size_t childInstallPkgDeps_recurse(FILE *fp, pkglink_t *list, 63 int undoit, int depth, int first_one_only); 64 static void dophase(worker_t *work, wmsg_t *wmsg, 65 int wdog, int phaseid, const char *phase); 66 static void phaseReapAll(void); 67 static void phaseTerminateSignal(int sig); 68 static char *buildskipreason(pkglink_t *parent, pkg_t *pkg); 69 static int buildskipcount_dueto(pkg_t *pkg, int mode); 70 static int mptylogpoll(int ptyfd, int fdlog, wmsg_t *wmsg, 71 time_t *wdog_timep); 72 static void doHook(pkg_t *pkg, const char *id, const char *path, int waitfor); 73 static void childHookRun(bulk_t *bulk); 74 static void adjloadavg(double *dload); 75 static void check_packaged(const char *dbmpath, pkg_t *pkgs); 76 77 static worker_t *SigWork; 78 static int MasterPtyFd = -1; 79 static int CopyFileFd = -1; 80 static pid_t SigPid; 81 static const char *WorkerFlavorPrt = ""; /* "" or "@flavor" */ 82 static DBM *CheckDBM; 83 84 #define MPTY_FAILED -2 85 #define MPTY_AGAIN -1 86 #define MPTY_EOF 0 87 #define MPTY_DATA 1 88 89 int BuildTotal; 90 int BuildCount; 91 int BuildSkipCount; 92 int BuildIgnoreCount; 93 int BuildFailCount; 94 int BuildSuccessCount; 95 int BuildMissingCount; 96 int BuildMetaCount; 97 98 /* 99 * Initialize the WorkerAry[] 100 */ 101 void 102 DoInitBuild(int slot_override) 103 { 104 worker_t *work; 105 struct stat st; 106 int i; 107 108 ddassert(slot_override < 0 || MaxWorkers == 1); 109 110 bzero(WorkerAry, MaxWorkers * sizeof(worker_t)); 111 pthread_mutex_init(&WorkerMutex, NULL); 112 113 for (i = 0; i < MaxWorkers; ++i) { 114 work = &WorkerAry[i]; 115 work->index = (slot_override >= 0) ? slot_override : i; 116 work->state = WORKER_NONE; 117 asprintf(&work->basedir, "%s/SL%02d", BuildBase, work->index); 118 pthread_cond_init(&work->cond, NULL); 119 } 120 BuildCount = 0; 121 122 /* 123 * Create required sub-directories. The base directories must already 124 * exist as a dsynth configuration safety. 125 */ 126 if (stat(RepositoryPath, &st) < 0) { 127 if (mkdir(RepositoryPath, 0755) < 0) 128 dfatal("Cannot mkdir %s\n", RepositoryPath); 129 } 130 131 BuildInitialized = 1; 132 133 /* 134 * slow-start (increases at a rate of 1 per 5 seconds) 135 */ 136 if (SlowStartOpt > MaxWorkers) 137 DynamicMaxWorkers = MaxWorkers; 138 else if (SlowStartOpt > 0) 139 DynamicMaxWorkers = SlowStartOpt; 140 else 141 DynamicMaxWorkers = MaxWorkers; 142 } 143 144 /* 145 * Called by the frontend to clean-up any hanging mounts. 146 */ 147 void 148 DoCleanBuild(int resetlogs) 149 { 150 int i; 151 152 ddassert(BuildInitialized); 153 154 if (resetlogs) 155 dlogreset(); 156 for (i = 0; i < MaxWorkers; ++i) { 157 DoWorkerUnmounts(&WorkerAry[i]); 158 } 159 } 160 161 void 162 DoBuild(pkg_t *pkgs) 163 { 164 pkg_t *build_list = NULL; 165 pkg_t **build_tail = &build_list; 166 pkg_t *scan; 167 bulk_t *bulk; 168 int haswork = 1; 169 int first = 1; 170 int newtemplate; 171 time_t startTime; 172 time_t t; 173 int h, m, s; 174 char *dbmpath; 175 176 /* 177 * We use our bulk system to run hooks. This will be for 178 * Skipped and Ignored. Success and Failure are handled by 179 * WorkerProcess() which is a separately-exec'd dsynth. 180 */ 181 if (UsingHooks) 182 initbulk(childHookRun, MaxBulk); 183 184 /* 185 * Count up the packages, not counting dummies 186 */ 187 for (scan = pkgs; scan; scan = scan->bnext) { 188 if ((scan->flags & PKGF_DUMMY) == 0) 189 ++BuildTotal; 190 } 191 192 /* 193 * Remove binary package files for dports whos directory 194 * has changed. 195 */ 196 asprintf(&dbmpath, "%s/ports_crc", BuildBase); 197 CheckDBM = dbm_open(dbmpath, O_CREAT|O_RDWR, 0644); 198 check_packaged(dbmpath, pkgs); 199 200 doHook(NULL, "hook_run_start", HookRunStart, 1); 201 202 /* 203 * The pkg and pkg-static binaries are needed. If already present 204 * then assume that the template is also valid, otherwise add to 205 * the list and build both. 206 */ 207 scan = GetPkgPkg(&pkgs); 208 209 /* 210 * Create our template. The template will be missing pkg 211 * and pkg-static. 212 */ 213 if ((scan->flags & (PKGF_SUCCESS | PKGF_PACKAGED)) == 0) { 214 /* force a fresh template */ 215 newtemplate = DoCreateTemplate(1); 216 } else { 217 newtemplate = DoCreateTemplate(0); 218 } 219 220 /* 221 * This will clear the screen and set-up our gui, so sleep 222 * a little first in case the user wants to see what was 223 * printed before. 224 */ 225 sleep(2); 226 pthread_mutex_lock(&WorkerMutex); 227 startTime = time(NULL); 228 RunStatsInit(); 229 RunStatsReset(); 230 231 /* 232 * Build pkg/pkg-static. 233 */ 234 if ((scan->flags & (PKGF_SUCCESS | PKGF_PACKAGED)) == 0) { 235 build_list = scan; 236 build_tail = &scan->build_next; 237 startbuild(&build_list, &build_tail); 238 while (RunningWorkers == 1) 239 waitbuild(1, 0); 240 241 if (scan->flags & PKGF_NOBUILD) 242 dfatal("Unable to build 'pkg'"); 243 if (scan->flags & PKGF_ERROR) 244 dfatal("Error building 'pkg'"); 245 if ((scan->flags & PKGF_SUCCESS) == 0) 246 dfatal("Error building 'pkg'"); 247 newtemplate = 1; 248 } 249 250 /* 251 * Install pkg/pkg-static into the template 252 */ 253 if (newtemplate) { 254 char *buf; 255 int rc; 256 257 asprintf(&buf, 258 "cd %s/Template; " 259 "tar --exclude '+*' --exclude '*/man/*' " 260 "-xvzpf %s/%s > /dev/null 2>&1", 261 BuildBase, 262 RepositoryPath, 263 scan->pkgfile); 264 rc = system(buf); 265 if (rc) 266 dfatal("Command failed: %s\n", buf); 267 freestrp(&buf); 268 } 269 270 /* 271 * Calculate depi_depth, the longest chain of dependencies 272 * for who depends on me, weighted by powers of two. 273 */ 274 for (scan = pkgs; scan; scan = scan->bnext) { 275 buildCalculateDepiDepth(scan); 276 } 277 278 /* 279 * Nominal bulk build sequence 280 */ 281 while (haswork) { 282 haswork = 0; 283 fflush(stdout); 284 for (scan = pkgs; scan; scan = scan->bnext) { 285 ddprintf(0, "SCANLEAVES %08x %s\n", 286 scan->flags, scan->portdir); 287 scan->flags |= PKGF_BUILDLOOP; 288 /* 289 * NOTE: We must still find dependencies if PACKAGED 290 * to fill in the gaps, as some of them may 291 * need to be rebuilt. 292 */ 293 if (scan->flags & (PKGF_SUCCESS | PKGF_FAILURE | 294 PKGF_ERROR)) { 295 #if 0 296 ddprintf(0, "%s: already built\n", 297 scan->portdir); 298 #endif 299 } else { 300 int ap = 0; 301 build_find_leaves(NULL, scan, &build_tail, 302 &ap, &haswork, 0, first, 0); 303 ddprintf(0, "TOPLEVEL %s %08x\n", 304 scan->portdir, ap); 305 } 306 scan->flags &= ~PKGF_BUILDLOOP; 307 build_clear_trav(scan); 308 } 309 first = 0; 310 fflush(stdout); 311 startbuild(&build_list, &build_tail); 312 313 if (haswork == 0 && RunningWorkers) { 314 waitbuild(RunningWorkers, 1); 315 haswork = 1; 316 } 317 } 318 pthread_mutex_unlock(&WorkerMutex); 319 320 /* 321 * What is left that cannot be built? The list really ought to be 322 * empty at this point, report anything that remains. 323 */ 324 for (scan = pkgs; scan; scan = scan->bnext) { 325 if (scan->flags & (PKGF_SUCCESS | PKGF_FAILURE)) 326 continue; 327 dlog(DLOG_ABN, "[XXX] %s lost in the ether [flags=%08x]\n", 328 scan->portdir, scan->flags); 329 ++BuildMissingCount; 330 } 331 332 /* 333 * Final updates 334 */ 335 RunStatsUpdateTop(0); 336 RunStatsUpdateLogs(); 337 RunStatsSync(); 338 RunStatsDone(); 339 340 doHook(NULL, "hook_run_end", HookRunEnd, 1); 341 if (UsingHooks) { 342 while ((bulk = getbulk()) != NULL) 343 freebulk(bulk); 344 donebulk(); 345 } 346 347 t = time(NULL) - startTime; 348 h = t / 3600; 349 m = t / 60 % 60; 350 s = t % 60; 351 352 if (CheckDBM) { 353 dbm_close(CheckDBM); 354 CheckDBM = NULL; 355 } 356 357 dlog(DLOG_ALL|DLOG_STDOUT, 358 "\n" 359 "Initial queue size: %d\n" 360 " packages built: %d\n" 361 " ignored: %d\n" 362 " skipped: %d\n" 363 " failed: %d\n" 364 " missing: %d\n" 365 " meta-nodes: %d\n" 366 "\n" 367 "Duration: %02d:%02d:%02d\n" 368 "\n", 369 BuildTotal, 370 BuildSuccessCount, 371 BuildIgnoreCount, 372 BuildSkipCount, 373 BuildFailCount, 374 BuildMissingCount, 375 BuildMetaCount, 376 h, m, s); 377 } 378 379 /* 380 * Traverse the packages (pkg) depends on recursively until we find 381 * a leaf to build or report as unbuildable. Calculates and assigns a 382 * dependency count. Returns all parallel-buildable packages. 383 * 384 * (pkg) itself is only added to the list if it is immediately buildable. 385 */ 386 static 387 int 388 build_find_leaves(pkg_t *parent, pkg_t *pkg, pkg_t ***build_tailp, 389 int *app, int *hasworkp, int depth, int first, 390 int first_one_only) 391 { 392 pkglink_t *link; 393 pkg_t *scan; 394 int idep_count = 0; 395 int apsub; 396 int dfirst_one_only; 397 int ndepth; 398 char *buf; 399 400 ndepth = depth + 1; 401 402 /* 403 * Already on build list, possibly in-progress, tell caller that 404 * it is not ready. 405 */ 406 ddprintf(ndepth, "sbuild_find_leaves %d %s %08x {\n", 407 depth, pkg->portdir, pkg->flags); 408 if (pkg->flags & PKGF_BUILDLIST) { 409 ddprintf(ndepth, "} (already on build list)\n"); 410 *app |= PKGF_NOTREADY; 411 return (pkg->idep_count); 412 } 413 414 /* 415 * Check dependencies 416 */ 417 PKGLIST_FOREACH(link, &pkg->idepon_list) { 418 scan = link->pkg; 419 420 if (scan == NULL) { 421 if (first_one_only) 422 break; 423 continue; 424 } 425 ddprintf(ndepth, "check %s %08x\t", scan->portdir, scan->flags); 426 427 /* 428 * If this dependency is to a DUMMY node it is a dependency 429 * only on the default flavor which is only the first node 430 * under this one, not all of them. 431 * 432 * DUMMY nodes can be marked SUCCESS so the build skips past 433 * them, but this doesn't mean that their sub-nodes succeeded. 434 * We have to check, so recurse even if it is marked 435 * successful. 436 * 437 * NOTE: The depth is not being for complex dependency type 438 * tests like it is in childInstallPkgDeps_recurse(), 439 * so we don't have to hicup it like we do in that 440 * procedure. 441 */ 442 dfirst_one_only = (scan->flags & PKGF_DUMMY) ? 1 : 0; 443 if (dfirst_one_only) 444 goto skip_to_flavor; 445 446 /* 447 * When accounting for a successful build, just bump 448 * idep_count by one. scan->idep_count will heavily 449 * overlap packages that we count down multiple branches. 450 * 451 * We must still recurse through PACKAGED packages as 452 * some of their dependencies might be missing. 453 */ 454 if (scan->flags & PKGF_SUCCESS) { 455 ddprintf(0, "SUCCESS - OK\n"); 456 ++idep_count; 457 if (first_one_only) 458 break; 459 continue; 460 } 461 462 /* 463 * ERROR includes FAILURE, which is set in numerous situations 464 * including when NOBUILD state is finally processed. So 465 * check for NOBUILD state first. 466 * 467 * An ERROR in a sub-package causes a NOBUILD in packages 468 * that depend on it. 469 */ 470 if (scan->flags & PKGF_NOBUILD) { 471 ddprintf(0, "NOBUILD - OK " 472 "(propagate failure upward)\n"); 473 *app |= PKGF_NOBUILD_S; 474 if (first_one_only) 475 break; 476 continue; 477 } 478 if (scan->flags & PKGF_ERROR) { 479 ddprintf(0, "ERROR - OK (propagate failure upward)\n"); 480 *app |= PKGF_NOBUILD_S; 481 if (first_one_only) 482 break; 483 continue; 484 } 485 486 /* 487 * If already on build-list this dependency is not ready. 488 */ 489 if (scan->flags & PKGF_BUILDLIST) { 490 ddprintf(0, " [BUILDLIST]"); 491 *app |= PKGF_NOTREADY; 492 } 493 494 /* 495 * If not packaged this dependency is not ready for 496 * the caller. 497 */ 498 if ((scan->flags & PKGF_PACKAGED) == 0) { 499 ddprintf(0, " [NOT_PACKAGED]"); 500 *app |= PKGF_NOTREADY; 501 } 502 503 /* 504 * Reduce search complexity, if we have already processed 505 * scan in the traversal it will either already be on the 506 * build list or it will not be buildable. Either way 507 * the parent is not buildable. 508 */ 509 if (scan->flags & PKGF_BUILDTRAV) { 510 ddprintf(0, " [BUILDTRAV]\n"); 511 *app |= PKGF_NOTREADY; 512 if (first_one_only) 513 break; 514 continue; 515 } 516 skip_to_flavor: 517 518 /* 519 * Assert on dependency loop 520 */ 521 ++idep_count; 522 if (scan->flags & PKGF_BUILDLOOP) { 523 dfatal("pkg dependency loop %s -> %s", 524 parent->portdir, scan->portdir); 525 } 526 527 /* 528 * NOTE: For debug tabbing purposes we use (ndepth + 1) 529 * here (i.e. depth + 2) in our iteration. 530 */ 531 scan->flags |= PKGF_BUILDLOOP; 532 apsub = 0; 533 ddprintf(0, " SUBRECURSION {\n"); 534 idep_count += build_find_leaves(pkg, scan, build_tailp, 535 &apsub, hasworkp, 536 ndepth + 1, first, 537 dfirst_one_only); 538 scan->flags &= ~PKGF_BUILDLOOP; 539 *app |= apsub; 540 if (apsub & PKGF_NOBUILD) { 541 ddprintf(ndepth, "} (sub-nobuild)\n"); 542 } else if (apsub & PKGF_ERROR) { 543 ddprintf(ndepth, "} (sub-error)\n"); 544 } else if (apsub & PKGF_NOTREADY) { 545 ddprintf(ndepth, "} (sub-notready)\n"); 546 } else { 547 ddprintf(ndepth, "} (sub-ok)\n"); 548 } 549 if (first_one_only) 550 break; 551 } 552 pkg->idep_count = idep_count; 553 pkg->flags |= PKGF_BUILDTRAV; 554 555 /* 556 * Incorporate scan results into pkg state. 557 */ 558 if ((pkg->flags & PKGF_NOBUILD) == 0 && (*app & PKGF_NOBUILD)) { 559 *hasworkp = 1; 560 } else if ((pkg->flags & PKGF_ERROR) == 0 && (*app & PKGF_ERROR)) { 561 *hasworkp = 1; 562 } 563 pkg->flags |= *app & ~PKGF_NOTREADY; 564 565 /* 566 * Clear the PACKAGED bit if sub-dependencies aren't clean. 567 * 568 * NOTE: PKGF_NOTREADY is not stored in pkg->flags, only in *app, 569 * so incorporate *app to test for it. 570 */ 571 if ((pkg->flags & PKGF_PACKAGED) && 572 ((pkg->flags | *app) & (PKGF_NOTREADY|PKGF_ERROR|PKGF_NOBUILD))) { 573 pkg->flags &= ~PKGF_PACKAGED; 574 ddassert(pkg->pkgfile); 575 asprintf(&buf, "%s/%s", RepositoryPath, pkg->pkgfile); 576 if (OverridePkgDeleteOpt >= 1) { 577 pkg->flags |= PKGF_PACKAGED; 578 dlog(DLOG_ALL, 579 "[XXX] %s DELETE-PACKAGE %s " 580 "(OVERRIDE, NOT DELETED)\n", 581 pkg->portdir, buf); 582 } else if (remove(buf) < 0) { 583 dlog(DLOG_ALL, 584 "[XXX] %s DELETE-PACKAGE %s (failed)\n", 585 pkg->portdir, buf); 586 } else { 587 dlog(DLOG_ALL, 588 "[XXX] %s DELETE-PACKAGE %s " 589 "(due to dependencies)\n", 590 pkg->portdir, buf); 591 } 592 freestrp(&buf); 593 *hasworkp = 1; 594 } 595 596 /* 597 * Set PKGF_NOBUILD_I if there is IGNORE data 598 */ 599 if (pkg->ignore) { 600 pkg->flags |= PKGF_NOBUILD_I; 601 } 602 603 /* 604 * Handle propagated flags 605 */ 606 if (pkg->flags & PKGF_ERROR) { 607 /* 608 * This can only happen if the ERROR has already been 609 * processed and accounted for. 610 */ 611 ddprintf(depth, "} (ERROR - %s)\n", pkg->portdir); 612 } else if (*app & PKGF_NOTREADY) { 613 /* 614 * We don't set PKGF_NOTREADY in the pkg, it is strictly 615 * a transient flag propagated via build_find_leaves(). 616 * 617 * Just don't add the package to the list. 618 * 619 * NOTE: Even if NOBUILD is set (meaning we could list it 620 * and let startbuild() finish it up as a skip, we 621 * don't process it to the list because we want to 622 * process all the dependencies, so someone doing a 623 * manual build can get more complete information and 624 * does not have to iterate each failed dependency one 625 * at a time. 626 */ 627 ; 628 } else if (pkg->flags & PKGF_SUCCESS) { 629 ddprintf(depth, "} (SUCCESS - %s)\n", pkg->portdir); 630 } else if (pkg->flags & PKGF_DUMMY) { 631 /* 632 * Just mark dummy packages as successful when all of their 633 * sub-depends (flavors) complete successfully. Note that 634 * dummy packages are not counted in the total, so do not 635 * decrement BuildTotal. 636 * 637 * Do not propagate *app up for the dummy node or add it to 638 * the build list. The dummy node itself is not an actual 639 * dependency. Packages which depend on the default flavor 640 * (aka this dummy node) actually depend on the first flavor 641 * under this node. 642 * 643 * So if there is a generic dependency (i.e. no flavor 644 * specified), the upper recursion detects PKGF_DUMMY and 645 * traverses through the dummy node to the default flavor 646 * without checking the error/nobuild flags on this dummy 647 * node. 648 */ 649 if (pkg->flags & PKGF_NOBUILD) { 650 ddprintf(depth, "} (DUMMY/META - IGNORED " 651 "- MARK SUCCESS ANYWAY)\n"); 652 } else { 653 ddprintf(depth, "} (DUMMY/META - SUCCESS)\n"); 654 } 655 pkg->flags |= PKGF_SUCCESS; 656 *hasworkp = 1; 657 if (first) { 658 dlog(DLOG_ALL | DLOG_FILTER, 659 "[XXX] %s META-ALREADY-BUILT\n", 660 pkg->portdir); 661 } else { 662 dlog(DLOG_SUCC, "[XXX] %s meta-node complete\n", 663 pkg->portdir); 664 RunStatsUpdateCompletion(NULL, DLOG_SUCC, pkg, "", ""); 665 ++BuildMetaCount; /* Only for not built meta nodes */ 666 } 667 } else if (pkg->flags & PKGF_PACKAGED) { 668 /* 669 * We can just mark the pkg successful. If this is 670 * the first pass, we count this as an initial pruning 671 * pass and reduce BuildTotal. 672 */ 673 ddprintf(depth, "} (PACKAGED - SUCCESS)\n"); 674 pkg->flags |= PKGF_SUCCESS; 675 *hasworkp = 1; 676 if (first) { 677 dlog(DLOG_ALL | DLOG_FILTER, 678 "[XXX] %s Already-Built\n", 679 pkg->portdir); 680 --BuildTotal; 681 } else { 682 dlog(DLOG_ABN | DLOG_FILTER, 683 "[XXX] %s flags=%08x Packaged Unexpectedly\n", 684 pkg->portdir, pkg->flags); 685 /* ++BuildSuccessTotal; XXX not sure */ 686 goto addlist; 687 } 688 } else { 689 /* 690 * All dependencies are successful, queue new work 691 * and indicate not-ready to the parent (since our 692 * package has to be built). 693 * 694 * NOTE: The NOBUILD case propagates to here as well 695 * and is ultimately handled by startbuild(). 696 */ 697 addlist: 698 *hasworkp = 1; 699 if (pkg->flags & PKGF_NOBUILD_I) 700 ddprintf(depth, "} (ADDLIST(IGNORE/BROKEN) - %s)\n", 701 pkg->portdir); 702 else if (pkg->flags & PKGF_NOBUILD) 703 ddprintf(depth, "} (ADDLIST(NOBUILD) - %s)\n", 704 pkg->portdir); 705 else 706 ddprintf(depth, "} (ADDLIST - %s)\n", pkg->portdir); 707 pkg->flags |= PKGF_BUILDLIST; 708 **build_tailp = pkg; 709 *build_tailp = &pkg->build_next; 710 pkg->build_next = NULL; 711 *app |= PKGF_NOTREADY; 712 } 713 714 return idep_count; 715 } 716 717 static 718 void 719 build_clear_trav(pkg_t *pkg) 720 { 721 pkglink_t *link; 722 pkg_t *scan; 723 724 pkg->flags &= ~PKGF_BUILDTRAV; 725 PKGLIST_FOREACH(link, &pkg->idepon_list) { 726 scan = link->pkg; 727 if (scan && (scan->flags & PKGF_BUILDTRAV)) 728 build_clear_trav(scan); 729 } 730 } 731 732 /* 733 * Calculate the longest chain of packages that depend on me. The 734 * long the chain, the more important my package is to build earlier 735 * rather than later. 736 */ 737 static int 738 buildCalculateDepiDepth(pkg_t *pkg) 739 { 740 pkglink_t *link; 741 pkg_t *scan; 742 int best_depth = 0; 743 int res; 744 745 if (pkg->depi_depth) 746 return(pkg->depi_depth + 1); 747 pkg->flags |= PKGF_BUILDLOOP; 748 PKGLIST_FOREACH(link, &pkg->deponi_list) { 749 scan = link->pkg; 750 if (scan && (scan->flags & PKGF_BUILDLOOP) == 0) { 751 res = buildCalculateDepiDepth(scan); 752 if (best_depth < res) 753 best_depth = res; 754 } 755 } 756 pkg->flags &= ~PKGF_BUILDLOOP; 757 pkg->depi_depth = best_depth; 758 759 return (best_depth + 1); 760 } 761 762 /* 763 * Take a list of pkg ready to go, sort it, and assign it to worker 764 * slots. This routine blocks in waitbuild() until it can dispose of 765 * the entire list. 766 * 767 * WorkerMutex is held by the caller. 768 */ 769 static 770 void 771 startbuild(pkg_t **build_listp, pkg_t ***build_tailp) 772 { 773 pkg_t *pkg; 774 pkg_t **idep_ary; 775 pkg_t **depi_ary; 776 int count; 777 int idep_index; 778 int depi_index; 779 int i; 780 int n; 781 worker_t *work; 782 static int IterateWorker; 783 784 /* 785 * Nothing to do 786 */ 787 if (*build_listp == NULL) 788 return; 789 790 /* 791 * Sort 792 */ 793 count = 0; 794 for (pkg = *build_listp; pkg; pkg = pkg->build_next) 795 ++count; 796 idep_ary = calloc(count, sizeof(pkg_t *)); 797 depi_ary = calloc(count, sizeof(pkg_t *)); 798 799 count = 0; 800 for (pkg = *build_listp; pkg; pkg = pkg->build_next) { 801 idep_ary[count] = pkg; 802 depi_ary[count] = pkg; 803 ++count; 804 } 805 806 /* 807 * idep_ary - sorted by #of dependencies this pkg has. 808 * depi_ary - sorted by #of other packages that depend on this pkg. 809 */ 810 qsort(idep_ary, count, sizeof(pkg_t *), qsort_idep); 811 qsort(depi_ary, count, sizeof(pkg_t *), qsort_depi); 812 813 idep_index = 0; 814 depi_index = 0; 815 816 /* 817 * Half the workers build based on the highest depi count, 818 * the other half build based on the highest idep count. 819 * 820 * This is an attempt to get projects which many other projects 821 * depend on built first, but to also try to build large projects 822 * (which tend to have a lot of dependencies) earlier rather than 823 * later so the end of the bulk run doesn't inefficiently build 824 * the last few huge projects. 825 * 826 * Loop until we manage to assign slots to everyone. We do not 827 * wait for build completion. 828 * 829 * This is the point where we handle DUMMY packages (these are 830 * dummy unflavored packages which 'cover' all the flavors for 831 * a package). These are not real packages are marked SUCCESS 832 * at this time because their dependencies (the flavors) have all 833 * been built. 834 */ 835 while (idep_index != count || depi_index != count) { 836 pkg_t *pkgi; 837 pkg_t *ipkg; 838 839 /* 840 * Find candidate to start sorted by depi or idep. 841 */ 842 ipkg = NULL; 843 while (idep_index < count) { 844 ipkg = idep_ary[idep_index]; 845 if ((ipkg->flags & 846 (PKGF_SUCCESS | PKGF_FAILURE | 847 PKGF_ERROR | PKGF_RUNNING)) == 0) { 848 break; 849 } 850 ipkg = NULL; 851 ++idep_index; 852 } 853 854 pkgi = NULL; 855 while (depi_index < count) { 856 pkgi = depi_ary[depi_index]; 857 if ((pkgi->flags & 858 (PKGF_SUCCESS | PKGF_FAILURE | 859 PKGF_ERROR | PKGF_RUNNING)) == 0) { 860 break; 861 } 862 pkgi = NULL; 863 ++depi_index; 864 } 865 866 /* 867 * ipkg and pkgi must either both be NULL, or both 868 * be non-NULL. 869 */ 870 if (ipkg == NULL && pkgi == NULL) 871 break; 872 ddassert(ipkg && pkgi); 873 874 /* 875 * Handle the NOBUILD case right here, there's no point 876 * queueing it anywhere. 877 */ 878 if (ipkg->flags & PKGF_NOBUILD) { 879 char *reason; 880 char skipbuf[16]; 881 int scount; 882 883 scount = buildskipcount_dueto(ipkg, 1); 884 buildskipcount_dueto(ipkg, 0); 885 if (scount) { 886 snprintf(skipbuf, sizeof(skipbuf), " %d", 887 scount); 888 } else { 889 skipbuf[0] = 0; 890 } 891 892 ipkg->flags |= PKGF_FAILURE; 893 ipkg->flags &= ~PKGF_BUILDLIST; 894 895 reason = buildskipreason(NULL, ipkg); 896 if (ipkg->flags & PKGF_NOBUILD_I) { 897 ++BuildIgnoreCount; 898 dlog(DLOG_IGN, 899 "[XXX] %s%s ignored due to %s\n", 900 ipkg->portdir, skipbuf, reason); 901 RunStatsUpdateCompletion(NULL, DLOG_IGN, ipkg, 902 reason, skipbuf); 903 doHook(ipkg, "hook_pkg_ignored", 904 HookPkgIgnored, 0); 905 } else { 906 ++BuildSkipCount; 907 dlog(DLOG_SKIP, 908 "[XXX] %s%s skipped due to %s\n", 909 ipkg->portdir, skipbuf, reason); 910 RunStatsUpdateCompletion(NULL, DLOG_SKIP, ipkg, 911 reason, skipbuf); 912 doHook(ipkg, "hook_pkg_skipped", 913 HookPkgSkipped, 0); 914 } 915 free(reason); 916 ++BuildCount; 917 continue; 918 } 919 if (pkgi->flags & PKGF_NOBUILD) { 920 char *reason; 921 char skipbuf[16]; 922 int scount; 923 924 scount = buildskipcount_dueto(pkgi, 1); 925 buildskipcount_dueto(pkgi, 0); 926 if (scount) { 927 snprintf(skipbuf, sizeof(skipbuf), " %d", 928 scount); 929 } else { 930 skipbuf[0] = 0; 931 } 932 933 pkgi->flags |= PKGF_FAILURE; 934 pkgi->flags &= ~PKGF_BUILDLIST; 935 936 reason = buildskipreason(NULL, pkgi); 937 if (pkgi->flags & PKGF_NOBUILD_I) { 938 ++BuildIgnoreCount; 939 dlog(DLOG_IGN, "[XXX] %s%s ignored due to %s\n", 940 pkgi->portdir, skipbuf, reason); 941 RunStatsUpdateCompletion(NULL, DLOG_IGN, pkgi, 942 reason, skipbuf); 943 doHook(pkgi, "hook_pkg_ignored", 944 HookPkgIgnored, 0); 945 } else { 946 ++BuildSkipCount; 947 dlog(DLOG_SKIP, 948 "[XXX] %s%s skipped due to %s\n", 949 pkgi->portdir, skipbuf, reason); 950 RunStatsUpdateCompletion(NULL, DLOG_SKIP, pkgi, 951 reason, skipbuf); 952 doHook(pkgi, "hook_pkg_skipped", 953 HookPkgSkipped, 0); 954 } 955 free(reason); 956 ++BuildCount; 957 continue; 958 } 959 960 /* 961 * Block while no slots are available. waitbuild() 962 * will clean out any DONE states. 963 */ 964 while (RunningWorkers >= DynamicMaxWorkers || 965 RunningWorkers >= MaxWorkers - FailedWorkers) { 966 waitbuild(RunningWorkers, 1); 967 } 968 969 /* 970 * Find an available worker slot, there should be at 971 * least one. 972 */ 973 for (i = 0; i < MaxWorkers; ++i) { 974 n = IterateWorker % MaxWorkers; 975 work = &WorkerAry[n]; 976 977 if (work->state == WORKER_DONE || 978 work->state == WORKER_FAILED) { 979 workercomplete(work); 980 } 981 if (work->state == WORKER_NONE || 982 work->state == WORKER_IDLE) { 983 if (n <= MaxWorkers / 2) { 984 startworker(pkgi, work); 985 } else { 986 startworker(ipkg, work); 987 } 988 /*RunStatsUpdate(work);*/ 989 break; 990 } 991 ++IterateWorker; 992 } 993 ddassert(i != MaxWorkers); 994 } 995 RunStatsSync(); 996 997 /* 998 * We disposed of the whole list 999 */ 1000 free(idep_ary); 1001 free(depi_ary); 1002 *build_listp = NULL; 1003 *build_tailp = build_listp; 1004 } 1005 1006 typedef const pkg_t *pkg_tt; 1007 1008 static int 1009 qsort_idep(const void *pkg1_arg, const void *pkg2_arg) 1010 { 1011 const pkg_t *pkg1 = *(const pkg_tt *)pkg1_arg; 1012 const pkg_t *pkg2 = *(const pkg_tt *)pkg2_arg; 1013 1014 return (pkg2->idep_count - pkg1->idep_count); 1015 } 1016 1017 static int 1018 qsort_depi(const void *pkg1_arg, const void *pkg2_arg) 1019 { 1020 const pkg_t *pkg1 = *(const pkg_tt *)pkg1_arg; 1021 const pkg_t *pkg2 = *(const pkg_tt *)pkg2_arg; 1022 1023 return ((pkg2->depi_count * pkg2->depi_depth) - 1024 (pkg1->depi_count * pkg1->depi_depth)); 1025 } 1026 1027 /* 1028 * Frontend starts a pkg up on a worker 1029 * 1030 * WorkerMutex must be held. 1031 */ 1032 static void 1033 startworker(pkg_t *pkg, worker_t *work) 1034 { 1035 switch(work->state) { 1036 case WORKER_NONE: 1037 pthread_create(&work->td, NULL, childBuilderThread, work); 1038 work->state = WORKER_IDLE; 1039 /* fall through */ 1040 case WORKER_IDLE: 1041 work->pkg_dep_size = 1042 childInstallPkgDeps_recurse(NULL, &pkg->idepon_list, 0, 1, 0); 1043 childInstallPkgDeps_recurse(NULL, &pkg->idepon_list, 1, 1, 0); 1044 RunningPkgDepSize += work->pkg_dep_size; 1045 1046 dlog(DLOG_ALL, "[%03d] START %s " 1047 "##idep=%02d depi=%02d/%02d dep=%-4.2fG\n", 1048 work->index, pkg->portdir, 1049 pkg->idep_count, pkg->depi_count, pkg->depi_depth, 1050 (double)work->pkg_dep_size / (double)ONEGB); 1051 1052 cleanworker(work); 1053 pkg->flags |= PKGF_RUNNING; 1054 work->pkg = pkg; 1055 pthread_cond_signal(&work->cond); 1056 ++RunningWorkers; 1057 /*RunStatsUpdate(work);*/ 1058 break; 1059 case WORKER_PENDING: 1060 case WORKER_RUNNING: 1061 case WORKER_DONE: 1062 case WORKER_FAILED: 1063 case WORKER_FROZEN: 1064 case WORKER_EXITING: 1065 default: 1066 dfatal("startworker: [%03d] Unexpected state %d for worker %d", 1067 work->index, work->state, work->index); 1068 break; 1069 } 1070 } 1071 1072 static void 1073 cleanworker(worker_t *work) 1074 { 1075 work->state = WORKER_PENDING; 1076 work->flags = 0; 1077 work->accum_error = 0; 1078 work->start_time = time(NULL); 1079 } 1080 1081 /* 1082 * Frontend finishes up a completed pkg on a worker. 1083 * 1084 * If the worker is in a FAILED state we clean the pkg out but (for now) 1085 * leave it in its failed state so we can debug. At this point 1086 * workercomplete() will be called every once in a while on the state 1087 * and we have to deal with the NULL pkg. 1088 * 1089 * WorkerMutex must be held. 1090 */ 1091 static void 1092 workercomplete(worker_t *work) 1093 { 1094 pkg_t *pkg; 1095 time_t t; 1096 int h; 1097 int m; 1098 int s; 1099 1100 /* 1101 * Steady state FAILED case. 1102 */ 1103 if (work->state == WORKER_FAILED) { 1104 if (work->pkg == NULL) 1105 return; 1106 } 1107 1108 t = time(NULL) - work->start_time; 1109 h = t / 3600; 1110 m = t / 60 % 60; 1111 s = t % 60; 1112 1113 /* 1114 * Reduce total dep size 1115 */ 1116 RunningPkgDepSize -= work->pkg_dep_size; 1117 RunningPkgDepSize -= work->memuse; 1118 work->pkg_dep_size = 0; 1119 work->memuse = 0; 1120 1121 /* 1122 * Process pkg out of the worker 1123 */ 1124 pkg = work->pkg; 1125 if (pkg->flags & (PKGF_ERROR|PKGF_NOBUILD)) { 1126 char skipbuf[16]; 1127 int scount; 1128 1129 pkg->flags |= PKGF_FAILURE; 1130 1131 scount = buildskipcount_dueto(pkg, 1); 1132 buildskipcount_dueto(pkg, 0); 1133 if (scount) { 1134 snprintf(skipbuf, sizeof(skipbuf), " %d", 1135 scount); 1136 } else { 1137 skipbuf[0] = 0; 1138 } 1139 1140 /* 1141 * This NOBUILD condition XXX can occur if the package is 1142 * not allowed to be built. 1143 */ 1144 if (pkg->flags & PKGF_NOBUILD) { 1145 char *reason; 1146 1147 reason = buildskipreason(NULL, pkg); 1148 if (pkg->flags & PKGF_NOBUILD_I) { 1149 ++BuildIgnoreCount; 1150 dlog(DLOG_SKIP, "[%03d] IGNORD %s%s - %s\n", 1151 work->index, pkg->portdir, 1152 skipbuf, reason); 1153 RunStatsUpdateCompletion(work, DLOG_SKIP, pkg, 1154 reason, skipbuf); 1155 doHook(pkg, "hook_pkg_ignored", 1156 HookPkgIgnored, 0); 1157 } else { 1158 ++BuildSkipCount; 1159 dlog(DLOG_SKIP, "[%03d] SKIPPD %s%s - %s\n", 1160 work->index, pkg->portdir, 1161 skipbuf, reason); 1162 RunStatsUpdateCompletion(work, DLOG_SKIP, pkg, 1163 reason, skipbuf); 1164 doHook(pkg, "hook_pkg_skipped", 1165 HookPkgSkipped, 0); 1166 } 1167 free(reason); 1168 } else { 1169 ++BuildFailCount; 1170 dlog(DLOG_FAIL | DLOG_RED, 1171 "[%03d] FAILURE %s%s ##%16.16s %02d:%02d:%02d\n", 1172 work->index, pkg->portdir, skipbuf, 1173 getphasestr(work->phase), 1174 h, m, s); 1175 RunStatsUpdateCompletion(work, DLOG_FAIL, pkg, 1176 skipbuf, ""); 1177 doHook(pkg, "hook_pkg_failure", HookPkgFailure, 0); 1178 } 1179 } else { 1180 if (CheckDBM) { 1181 datum key; 1182 datum data; 1183 1184 key.dptr = pkg->portdir; 1185 key.dsize = strlen(pkg->portdir); 1186 data.dptr = &pkg->crc32; 1187 data.dsize = sizeof(pkg->crc32); 1188 dbm_store(CheckDBM, key, data, DBM_REPLACE); 1189 } 1190 pkg->flags |= PKGF_SUCCESS; 1191 ++BuildSuccessCount; 1192 dlog(DLOG_SUCC | DLOG_GRN, 1193 "[%03d] SUCCESS %s ##%02d:%02d:%02d\n", 1194 work->index, pkg->portdir, h, m, s); 1195 RunStatsUpdateCompletion(work, DLOG_SUCC, pkg, "", ""); 1196 doHook(pkg, "hook_pkg_success", HookPkgSuccess, 0); 1197 } 1198 ++BuildCount; 1199 pkg->flags &= ~PKGF_BUILDLIST; 1200 pkg->flags &= ~PKGF_RUNNING; 1201 work->pkg = NULL; 1202 --RunningWorkers; 1203 1204 if (work->state == WORKER_FAILED) { 1205 dlog(DLOG_ALL, "[%03d] XXX/XXX WORKER IS IN A FAILED STATE\n", 1206 work->index); 1207 ++FailedWorkers; 1208 } else if (work->flags & WORKERF_FREEZE) { 1209 dlog(DLOG_ALL, "[%03d] FROZEN(DEBUG) %s\n", 1210 work->index, pkg->portdir); 1211 work->state = WORKER_FROZEN; 1212 } else { 1213 work->state = WORKER_IDLE; 1214 } 1215 } 1216 1217 /* 1218 * Wait for one or more workers to complete. 1219 * 1220 * WorkerMutex must be held. 1221 */ 1222 static void 1223 waitbuild(int whilematch, int dynamicmax) 1224 { 1225 static time_t wblast_time; 1226 static time_t dmlast_time; 1227 struct timespec ts; 1228 worker_t *work; 1229 time_t t; 1230 int i; 1231 1232 if (whilematch == 0) 1233 whilematch = 1; 1234 1235 while (RunningWorkers == whilematch) { 1236 for (i = 0; i < MaxWorkers; ++i) { 1237 work = &WorkerAry[i]; 1238 if (work->state == WORKER_DONE || 1239 work->state == WORKER_FAILED) { 1240 workercomplete(work); 1241 } else { 1242 pthread_cond_signal(&work->cond); 1243 } 1244 RunStatsUpdate(work, NULL); 1245 } 1246 RunStatsUpdateTop(1); 1247 RunStatsUpdateLogs(); 1248 RunStatsSync(); 1249 if (RunningWorkers == whilematch) { 1250 clock_gettime(CLOCK_REALTIME, &ts); 1251 ts.tv_sec += 1; 1252 ts.tv_nsec = 0; 1253 pthread_cond_timedwait(&WorkerCond, &WorkerMutex, &ts); 1254 } 1255 1256 /* 1257 * Dynamically reduce MaxWorkers based on the load. When 1258 * the load exceeds 2 x ncpus we reduce the number of workers 1259 * up to 75% of MaxWorkers @ (5 x ncpus) load. 1260 * 1261 * Dynamically reduce MaxWorkers based on swap use, starting 1262 * at 10% swap and up to 75% of MaxWorkers at 40% swap. 1263 * 1264 * NOTE! Generally speaking this allows more workers to be 1265 * configured which helps in two ways. First it allows 1266 * a higher build rate for smaller packages. Second 1267 * it allows dsynth to ratchet-down the number of slots 1268 * when large packages are forcing the load up. 1269 * 1270 * A high load doesn't hurt efficiency, but swap usage 1271 * due to loading the tmpfs in lots of worker slots up 1272 * with tons of pkg install's (pre-reqs for a build) 1273 * does. Reducing the number of worker slots has a 1274 * huge beneficial effect on reducing swap use / paging. 1275 */ 1276 t = time(NULL); 1277 if (dynamicmax && (wblast_time == 0 || 1278 (unsigned)(t - wblast_time) >= 5)) { 1279 double min_load = 1.5 * NumCores; 1280 double max_load = 5.0 * NumCores; 1281 double min_swap = 0.10; 1282 double max_swap = 0.40; 1283 double dload[3]; 1284 double dswap; 1285 int max1; 1286 int max2; 1287 int max3; 1288 int max_sel; 1289 int noswap; 1290 1291 wblast_time = t; 1292 1293 /* 1294 * Cap based on load. This is back-loaded. 1295 */ 1296 getloadavg(dload, 3); 1297 adjloadavg(dload); 1298 if (dload[0] < min_load) { 1299 max1 = MaxWorkers; 1300 } else if (dload[0] <= max_load) { 1301 max1 = MaxWorkers - 1302 MaxWorkers * 0.75 * 1303 (dload[0] - min_load) / 1304 (max_load - min_load); 1305 } else { 1306 max1 = MaxWorkers * 25 / 100; 1307 } 1308 1309 /* 1310 * Cap based on swap use. This is back-loaded. 1311 */ 1312 dswap = getswappct(&noswap); 1313 if (dswap < min_swap) { 1314 max2 = MaxWorkers; 1315 } else if (dswap <= max_swap) { 1316 max2 = MaxWorkers - 1317 MaxWorkers * 0.75 * 1318 (dswap - min_swap) / 1319 (max_swap - min_swap); 1320 } else { 1321 max2 = MaxWorkers * 25 / 100; 1322 } 1323 1324 /* 1325 * Cap based on aggregate pkg-dependency memory 1326 * use installed in worker slots. This is 1327 * front-loaded. 1328 * 1329 * Since it can take a while for workers to retire 1330 * (to reduce RunningPkgDepSize), just set our 1331 * target 1 below the current run count to allow 1332 * jobs to retire without being replaced with new 1333 * jobs. 1334 * 1335 * In addition, in order to avoid a paging 'shock', 1336 * We enforce a 30 second-per-increment slow-start 1337 * once RunningPkgDepSize exceeds 1/2 the target. 1338 */ 1339 if (RunningPkgDepSize > PkgDepMemoryTarget) { 1340 max3 = RunningWorkers - 1; 1341 } else if (RunningPkgDepSize > PkgDepMemoryTarget / 2) { 1342 if (dmlast_time == 0 || 1343 (unsigned)(t - dmlast_time) >= 30) { 1344 dmlast_time = t; 1345 max3 = RunningWorkers + 1; 1346 } else { 1347 max3 = RunningWorkers; 1348 } 1349 } else { 1350 max3 = MaxWorkers; 1351 } 1352 1353 /* 1354 * Priority reduction, convert to DynamicMaxWorkers 1355 */ 1356 max_sel = max1; 1357 if (max_sel > max2) 1358 max_sel = max2; 1359 if (max_sel > max3) 1360 max_sel = max3; 1361 1362 /* 1363 * Restrict to allowed range, and also handle 1364 * slow-start. 1365 */ 1366 if (max_sel < 1) 1367 max_sel = 1; 1368 if (max_sel > DynamicMaxWorkers + 1) 1369 max_sel = DynamicMaxWorkers + 1; 1370 if (max_sel > MaxWorkers) 1371 max_sel = MaxWorkers; 1372 1373 /* 1374 * Stop waiting if DynamicMaxWorkers is going to 1375 * increase. 1376 */ 1377 if (DynamicMaxWorkers < max1) 1378 whilematch = -1; 1379 1380 /* 1381 * And adjust 1382 */ 1383 if (DynamicMaxWorkers != max1) { 1384 dlog(DLOG_ALL | DLOG_FILTER, 1385 "[XXX] Load=%-6.2f(%2d) " 1386 "Swap=%-3.2f%%(%2d) " 1387 "Mem=%3.2fG(%2d) " 1388 "Adjust Workers %d->%d\n", 1389 dload[0], max1, 1390 dswap * 100.0, max2, 1391 RunningPkgDepSize / (double)ONEGB, max3, 1392 DynamicMaxWorkers, max_sel); 1393 DynamicMaxWorkers = max_sel; 1394 } 1395 } 1396 } 1397 } 1398 1399 1400 /* 1401 * Worker pthread (WorkerAry) 1402 * 1403 * This thread belongs to the dsynth master process and handled a worker slot. 1404 * (this_thread) -> WORKER fork/exec (WorkerPocess) -> (pty) -> sub-processes. 1405 */ 1406 static void * 1407 childBuilderThread(void *arg) 1408 { 1409 char *envary[1] = { NULL }; 1410 worker_t *work = arg; 1411 wmsg_t wmsg; 1412 pkg_t *pkg; 1413 pid_t pid; 1414 int status; 1415 int flags; 1416 volatile int dowait; 1417 char slotbuf[8]; 1418 char fdbuf[8]; 1419 char flagsbuf[16]; 1420 1421 pthread_mutex_lock(&WorkerMutex); 1422 while (work->terminate == 0) { 1423 dowait = 1; 1424 1425 switch(work->state) { 1426 case WORKER_IDLE: 1427 break; 1428 case WORKER_PENDING: 1429 /* 1430 * Fork the management process for the pkg operation 1431 * on this worker slot. 1432 * 1433 * This process will set up the environment, do the 1434 * mounts, will become the reaper, and will process 1435 * pipe commands and handle chroot operations. 1436 * 1437 * NOTE: If SOCK_CLOEXEC is not supported WorkerMutex 1438 * is sufficient to interlock F_SETFD FD_CLOEXEC 1439 * operations. 1440 */ 1441 ddassert(work->pkg); 1442 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 1443 PF_UNSPEC, work->fds)) { 1444 dfatal_errno("socketpair() during worker fork"); 1445 } 1446 snprintf(slotbuf, sizeof(slotbuf), "%d", work->index); 1447 snprintf(fdbuf, sizeof(fdbuf), "3"); 1448 1449 /* 1450 * Pass global flags and add-in the DEBUGSTOP if 1451 * the package is flagged for debugging. 1452 */ 1453 flags = WorkerProcFlags; 1454 if (work->pkg->flags & PKGF_DEBUGSTOP) { 1455 flags |= WORKER_PROC_DEBUGSTOP; 1456 } else { 1457 flags &= ~WORKER_PROC_DEBUGSTOP; 1458 } 1459 snprintf(flagsbuf, sizeof(flagsbuf), "%d", flags); 1460 1461 /* 1462 * fds[0] - master 1463 * fds[1] - slave 1464 * 1465 * We pass the salve descriptor in fd 3 and close all 1466 * other descriptors for security. 1467 */ 1468 pthread_mutex_unlock(&WorkerMutex); 1469 pid = vfork(); 1470 if (pid == 0) { 1471 close(work->fds[0]); 1472 dup2(work->fds[1], 3); 1473 closefrom(4); 1474 fcntl(3, F_SETFD, 0); 1475 execle(DSynthExecPath, DSynthExecPath, 1476 "-p", Profile, 1477 "WORKER", slotbuf, fdbuf, 1478 work->pkg->portdir, work->pkg->pkgfile, 1479 flagsbuf, 1480 NULL, envary); 1481 write(2, "EXECLE FAILURE\n", 15); 1482 _exit(1); 1483 } 1484 pthread_mutex_lock(&WorkerMutex); 1485 close(work->fds[1]); 1486 work->phase = PHASE_PENDING; 1487 work->lines = 0; 1488 work->memuse = 0; 1489 work->pid = pid; 1490 work->state = WORKER_RUNNING; 1491 /* fall through */ 1492 case WORKER_RUNNING: 1493 /* 1494 * Poll for status updates, if NULL is returned 1495 * and status is non-zero, the communications link 1496 * failed unexpectedly. 1497 */ 1498 pkg = work->pkg; 1499 pthread_mutex_unlock(&WorkerMutex); 1500 status = ipcreadmsg(work->fds[0], &wmsg); 1501 pthread_mutex_lock(&WorkerMutex); 1502 1503 if (status == 0) { 1504 /* 1505 * Normal message, can include normal 1506 * termination which changes us over 1507 * to another state. 1508 */ 1509 dowait = 0; 1510 switch(wmsg.cmd) { 1511 case WMSG_CMD_INSTALL_PKGS: 1512 wmsg.cmd = WMSG_RES_INSTALL_PKGS; 1513 wmsg.status = childInstallPkgDeps(work); 1514 pthread_mutex_unlock(&WorkerMutex); 1515 ipcwritemsg(work->fds[0], &wmsg); 1516 pthread_mutex_lock(&WorkerMutex); 1517 break; 1518 case WMSG_CMD_STATUS_UPDATE: 1519 work->phase = wmsg.phase; 1520 work->lines = wmsg.lines; 1521 if (work->memuse != wmsg.memuse) { 1522 RunningPkgDepSize += 1523 wmsg.memuse - work->memuse; 1524 work->memuse = wmsg.memuse; 1525 } 1526 break; 1527 case WMSG_CMD_SUCCESS: 1528 work->flags |= WORKERF_SUCCESS; 1529 break; 1530 case WMSG_CMD_FAILURE: 1531 work->flags |= WORKERF_FAILURE; 1532 break; 1533 case WMSG_CMD_FREEZEWORKER: 1534 work->flags |= WORKERF_FREEZE; 1535 break; 1536 default: 1537 break; 1538 } 1539 RunStatsUpdate(work, NULL); 1540 RunStatsSync(); 1541 } else { 1542 close(work->fds[0]); 1543 pthread_mutex_unlock(&WorkerMutex); 1544 while (waitpid(work->pid, &status, 0) < 0 && 1545 errno == EINTR) { 1546 ; 1547 } 1548 pthread_mutex_lock(&WorkerMutex); 1549 1550 if (work->flags & WORKERF_SUCCESS) { 1551 pkg->flags |= PKGF_SUCCESS; 1552 work->state = WORKER_DONE; 1553 } else if (work->flags & WORKERF_FAILURE) { 1554 pkg->flags |= PKGF_FAILURE; 1555 work->state = WORKER_DONE; 1556 } else { 1557 pkg->flags |= PKGF_FAILURE; 1558 work->state = WORKER_FAILED; 1559 } 1560 work->flags |= WORKERF_STATUS_UPDATE; 1561 pthread_cond_signal(&WorkerCond); 1562 } 1563 break; 1564 case WORKER_DONE: 1565 /* 1566 * pkg remains attached until frontend processes the 1567 * completion. The frontend will then set the state 1568 * back to idle. 1569 */ 1570 break; 1571 case WORKER_FAILED: 1572 /* 1573 * A worker failure means that the worker did not 1574 * send us a WMSG_CMD_SUCCESS or WMSG_CMD_FAILURE 1575 * ipc before terminating. 1576 * 1577 * We just sit in this state until the front-end 1578 * does something about it. 1579 */ 1580 break; 1581 case WORKER_FROZEN: 1582 /* 1583 * A worker getting frozen is debug-related. We 1584 * just sit in this state (likely forever). 1585 */ 1586 break; 1587 default: 1588 dfatal("worker: [%03d] Unexpected state %d " 1589 "for worker %d", 1590 work->index, work->state, work->index); 1591 /* NOT REACHED */ 1592 break; 1593 } 1594 1595 /* 1596 * The dsynth frontend will poll us approximately once 1597 * a second (its variable). 1598 */ 1599 if (dowait) 1600 pthread_cond_wait(&work->cond, &WorkerMutex); 1601 } 1602 1603 /* 1604 * Scrap the comm socket if running, this should cause the worker 1605 * process to kill its sub-programs and cleanup. 1606 */ 1607 if (work->state == WORKER_RUNNING) { 1608 pthread_mutex_unlock(&WorkerMutex); 1609 close(work->fds[0]); 1610 while (waitpid(work->pid, &status, 0) < 0 && 1611 errno == EINTR); 1612 pthread_mutex_lock(&WorkerMutex); 1613 } 1614 1615 /* 1616 * Final handshake 1617 */ 1618 work->state = WORKER_EXITING; 1619 pthread_cond_signal(&WorkerCond); 1620 pthread_mutex_unlock(&WorkerMutex); 1621 1622 return NULL; 1623 } 1624 1625 /* 1626 * Install all the binary packages (we have already built them) that 1627 * the current work package depends on, without duplicates, in a script 1628 * which will be run from within the specified work jail. 1629 * 1630 * Locked by WorkerMutex (global) 1631 */ 1632 static int 1633 childInstallPkgDeps(worker_t *work) 1634 { 1635 char *buf; 1636 FILE *fp; 1637 1638 if (PKGLIST_EMPTY(&work->pkg->idepon_list)) 1639 return 0; 1640 1641 asprintf(&buf, "%s/tmp/dsynth_install_pkgs", work->basedir); 1642 fp = fopen(buf, "w"); 1643 ddassert(fp != NULL); 1644 fprintf(fp, "#!/bin/sh\n"); 1645 fprintf(fp, "#\n"); 1646 fchmod(fileno(fp), 0755); 1647 1648 childInstallPkgDeps_recurse(fp, &work->pkg->idepon_list, 0, 1, 0); 1649 childInstallPkgDeps_recurse(fp, &work->pkg->idepon_list, 1, 1, 0); 1650 fprintf(fp, "\nexit 0\n"); 1651 fclose(fp); 1652 freestrp(&buf); 1653 1654 return 1; 1655 } 1656 1657 /* 1658 * Recursive child install dependencies. 1659 * 1660 * first_one_only is only specified if the pkg the list comes from 1661 * is a generic unflavored package that has flavors, telling us to 1662 * dive the first flavor only. 1663 * 1664 * However, in nearly all cases this flag will now be zero because 1665 * this code now dives the first flavor when encountering a dummy node 1666 * and clears nfirst on success. Hence if you are asking why 'nfirst' 1667 * is set to 1, and then zero, instead of just being removed entirely, 1668 * it is because there might still be an edge case here. 1669 */ 1670 static size_t 1671 childInstallPkgDeps_recurse(FILE *fp, pkglink_t *list, int undoit, 1672 int depth, int first_one_only) 1673 { 1674 pkglink_t *link; 1675 pkg_t *pkg; 1676 size_t tot = 0; 1677 int ndepth; 1678 int nfirst; 1679 1680 PKGLIST_FOREACH(link, list) { 1681 pkg = link->pkg; 1682 1683 /* 1684 * We don't want to mess up our depth test just below if 1685 * a DUMMY node had to be inserted. The nodes under the 1686 * dummy node. 1687 * 1688 * The elements under a dummy node represent all the flabor, 1689 * a dependency that directly references a dummy node only 1690 * uses the first flavor (first_one_only / nfirst). 1691 */ 1692 ndepth = (pkg->flags & PKGF_DUMMY) ? depth : depth + 1; 1693 nfirst = (pkg->flags & PKGF_DUMMY) ? 1 : 0; 1694 1695 /* 1696 * We only need all packages for the top-level dependencies. 1697 * The deeper ones only need DEP_TYPE_LIB and DEP_TYPE_RUN 1698 * (types greater than DEP_TYPE_BUILD) since they are already 1699 * built. 1700 */ 1701 if (depth > 1 && link->dep_type <= DEP_TYPE_BUILD) { 1702 if (first_one_only) 1703 break; 1704 continue; 1705 } 1706 1707 /* 1708 * If this is a dummy node with no package, the originator 1709 * is requesting a flavored package. We select the default 1710 * flavor which we presume is the first one. 1711 */ 1712 if (pkg->pkgfile == NULL && (pkg->flags & PKGF_DUMMY)) { 1713 pkg_t *spkg = pkg->idepon_list.next->pkg; 1714 1715 if (spkg) { 1716 if (fp) { 1717 fprintf(fp, 1718 "echo 'UNFLAVORED %s -> use " 1719 "%s'\n", 1720 pkg->portdir, 1721 spkg->portdir); 1722 } 1723 pkg = spkg; 1724 nfirst = 0; 1725 } else { 1726 if (fp) { 1727 fprintf(fp, 1728 "echo 'CANNOT FIND DEFAULT " 1729 "FLAVOR FOR %s'\n", 1730 pkg->portdir); 1731 } 1732 } 1733 } 1734 1735 if (undoit) { 1736 if (pkg->dsynth_install_flg == 1) { 1737 pkg->dsynth_install_flg = 0; 1738 tot += childInstallPkgDeps_recurse(fp, 1739 &pkg->idepon_list, 1740 undoit, 1741 ndepth, nfirst); 1742 } 1743 if (first_one_only) 1744 break; 1745 continue; 1746 } 1747 1748 if (pkg->dsynth_install_flg) { 1749 if (DebugOpt >= 2 && pkg->pkgfile && fp) { 1750 fprintf(fp, "echo 'AlreadyHave %s'\n", 1751 pkg->pkgfile); 1752 } 1753 if (first_one_only) 1754 break; 1755 continue; 1756 } 1757 1758 tot += childInstallPkgDeps_recurse(fp, &pkg->idepon_list, 1759 undoit, ndepth, nfirst); 1760 if (pkg->dsynth_install_flg) { 1761 if (first_one_only) 1762 break; 1763 continue; 1764 } 1765 pkg->dsynth_install_flg = 1; 1766 1767 /* 1768 * Generate package installation command 1769 */ 1770 if (fp && pkg->pkgfile) { 1771 fprintf(fp, "echo 'Installing /packages/All/%s'\n", 1772 pkg->pkgfile); 1773 fprintf(fp, "pkg install -q -U -y /packages/All/%s " 1774 "|| exit 1\n", 1775 pkg->pkgfile); 1776 } else if (fp) { 1777 fprintf(fp, "echo 'CANNOT FIND PKG FOR %s'\n", 1778 pkg->portdir); 1779 } 1780 1781 if (pkg->pkgfile) { 1782 struct stat st; 1783 char *path; 1784 char *ptr; 1785 1786 asprintf(&path, "%s/%s", RepositoryPath, pkg->pkgfile); 1787 ptr = strrchr(pkg->pkgfile, '.'); 1788 if (stat(path, &st) == 0) { 1789 if (strcmp(ptr, ".tar") == 0) 1790 tot += st.st_size; 1791 else if (strcmp(ptr, ".tgz") == 0) 1792 tot += st.st_size * 3; 1793 else if (strcmp(ptr, ".txz") == 0) 1794 tot += st.st_size * 5; 1795 else if (strcmp(ptr, ".tzst") == 0) 1796 tot += st.st_size * 5; 1797 else if (strcmp(ptr, ".tbz") == 0) 1798 tot += st.st_size * 3; 1799 else 1800 tot += st.st_size * 2; 1801 } 1802 free(path); 1803 } 1804 if (first_one_only) 1805 break; 1806 } 1807 return tot; 1808 } 1809 1810 /* 1811 * Worker process interactions. 1812 * 1813 * The worker process is responsible for managing the build of a single 1814 * package. It is exec'd by the master dsynth and only loads the 1815 * configuration. 1816 * 1817 * This process does not run in the chroot. It will become the reaper for 1818 * all sub-processes and it will enter the chroot to execute various phases. 1819 * It catches SIGINTR, SIGHUP, and SIGPIPE and will iterate, terminate, and 1820 * reap all sub-process upon kill or exit. 1821 * 1822 * The command line forwarded to this function is: 1823 * 1824 * WORKER slot# socketfd portdir/subdir 1825 * 1826 * TERM=dumb 1827 * USER=root 1828 * HOME=/root 1829 * LANG=C 1830 * SSL_NO_VERIFY_PEER=1 1831 * USE_PACKAGE_DEPENDS_ONLY=1 1832 * PORTSDIR=/xports 1833 * PORT_DBDIR=/options For ports options 1834 * PACKAGE_BUILDING=yes Don't build packages that aren't legally 1835 * buildable for a binary repo. 1836 * PKG_DBDIR=/var/db/pkg 1837 * PKG_CACHEDIR=/var/cache/pkg 1838 * PKG_CREATE_VERBOSE=yes Ensure periodic output during packaging 1839 * (custom environment) 1840 * PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin 1841 * UNAME_s=DragonFly (example) 1842 * UNAME_v=DragonFly 5.7-SYNTH (example) 1843 * UNAME_p=x86_64 (example) 1844 * UNAME_m=x86_64 (example) 1845 * UNAME_r=5.7-SYNTH (example) 1846 * NO_DEPENDS=yes (conditional based on phase) 1847 * DISTDIR=/distfiles 1848 * WRKDIRPREFIX=/construction 1849 * BATCH=yes 1850 * MAKE_JOBS_NUMBER=n 1851 * 1852 * SETUP: 1853 * ldconfig -R 1854 * /usr/local/sbin/pkg-static install /packages/All/<the pkg pkg> 1855 * /usr/local/sbin/pkg-static install /packages/All/<pkg> 1856 * (for all dependencies) 1857 * 1858 * PHASES: make -C path FLAVOR=flavor <phase> 1859 * check-sanity 1860 * pkg-depends 1861 * fetch-depends 1862 * fetch 1863 * checksum 1864 * extract-depends 1865 * extract 1866 * patch-depends 1867 * patch 1868 * build-depends 1869 * lib-depends 1870 * configure 1871 * build 1872 * run-depends 1873 * stage 1874 * test (skipped) 1875 * check-plist ('dsynth test blahblah' or 'dsynth -D everything' only) 1876 * package e.g. /construction/lang/perl5.28/pkg/perl5-5.28.2.txz 1877 * install (skipped) 1878 * deinstall (skipped) 1879 */ 1880 void 1881 WorkerProcess(int ac, char **av) 1882 { 1883 wmsg_t wmsg; 1884 int fd; 1885 int slot; 1886 int tmpfd; 1887 int pkgpkg = 0; 1888 int status; 1889 int len; 1890 int do_install_phase; 1891 char *portdir; 1892 char *pkgfile; 1893 char *flavor; 1894 char *buf; 1895 worker_t *work; 1896 bulk_t *bulk; 1897 pkg_t pkg; 1898 buildenv_t *benv; 1899 FILE *fp; 1900 1901 /* 1902 * Parse arguments 1903 */ 1904 if (ac != 6) { 1905 dlog(DLOG_ALL, "WORKER PROCESS %d- bad arguments\n", getpid()); 1906 exit(1); 1907 } 1908 slot = strtol(av[1], NULL, 0); 1909 fd = strtol(av[2], NULL, 0); /* master<->slave messaging */ 1910 portdir = av[3]; 1911 pkgfile = av[4]; 1912 flavor = strchr(portdir, '@'); 1913 if (flavor) { 1914 *flavor++ = 0; 1915 asprintf(&buf, "@%s", flavor); 1916 WorkerFlavorPrt = buf; 1917 buf = NULL; /* safety */ 1918 } 1919 WorkerProcFlags = strtol(av[5], NULL, 0); 1920 1921 bzero(&wmsg, sizeof(wmsg)); 1922 1923 setproctitle("[%02d] WORKER STARTUP %s%s", 1924 slot, portdir, WorkerFlavorPrt); 1925 1926 if (strcmp(portdir, "ports-mgmt/pkg") == 0) 1927 pkgpkg = 1; 1928 1929 signal(SIGTERM, phaseTerminateSignal); 1930 signal(SIGINT, phaseTerminateSignal); 1931 signal(SIGHUP, phaseTerminateSignal); 1932 1933 /* 1934 * Set up the environment 1935 */ 1936 setenv("TERM", "dumb", 1); 1937 setenv("USER", "root", 1); 1938 setenv("HOME", "/root", 1); 1939 setenv("LANG", "C", 1); 1940 setenv("SSL_NO_VERIFY_PEER", "1", 1); 1941 1942 addbuildenv("USE_PACKAGE_DEPENDS_ONLY", "yes", BENV_MAKECONF); 1943 addbuildenv("PORTSDIR", "/xports", BENV_MAKECONF); 1944 addbuildenv("PORT_DBDIR", "/options", BENV_MAKECONF); 1945 addbuildenv("PKG_DBDIR", "/var/db/pkg", BENV_MAKECONF); 1946 addbuildenv("PKG_CACHEDIR", "/var/cache/pkg", BENV_MAKECONF); 1947 addbuildenv("PKG_SUFX", UsePkgSufx, BENV_MAKECONF); 1948 if (WorkerProcFlags & WORKER_PROC_DEVELOPER) 1949 addbuildenv("DEVELOPER", "1", BENV_MAKECONF); 1950 1951 /* 1952 * CCache is a horrible unreliable hack but... leave the 1953 * mechanism in-place in case someone has a death wish. 1954 */ 1955 if (UseCCache) { 1956 addbuildenv("WITH_CCACHE_BUILD", "yes", BENV_MAKECONF); 1957 addbuildenv("CCACHE_DIR", "/ccache", BENV_MAKECONF); 1958 } 1959 1960 addbuildenv("UID", "0", BENV_MAKECONF); 1961 addbuildenv("ARCH", ArchitectureName, BENV_MAKECONF); 1962 1963 /* 1964 * Always honor either the operating system detection or the 1965 * operating system selection in the config file. 1966 */ 1967 addbuildenv("OPSYS", OperatingSystemName, BENV_MAKECONF); 1968 1969 #ifdef __DragonFly__ 1970 addbuildenv("DFLYVERSION", VersionFromParamHeader, BENV_MAKECONF); 1971 addbuildenv("OSVERSION", "9999999", BENV_MAKECONF); 1972 #else 1973 #error "Need OS-specific data to generate make.conf" 1974 #endif 1975 1976 addbuildenv("OSREL", ReleaseName, BENV_MAKECONF); 1977 addbuildenv("_OSRELEASE", VersionOnlyName, BENV_MAKECONF); 1978 1979 setenv("PATH", 1980 "/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin", 1981 1); 1982 1983 setenv("UNAME_s", OperatingSystemName, 1); 1984 setenv("UNAME_v", VersionName, 1); 1985 setenv("UNAME_p", ArchitectureName, 1); 1986 setenv("UNAME_m", MachineName, 1); 1987 setenv("UNAME_r", ReleaseName, 1); 1988 1989 addbuildenv("DISTDIR", "/distfiles", BENV_MAKECONF); 1990 addbuildenv("WRKDIRPREFIX", "/construction", BENV_MAKECONF); 1991 addbuildenv("BATCH", "yes", BENV_MAKECONF); 1992 1993 /* 1994 * Special consideration 1995 * 1996 * PACKAGE_BUILDING - Disallow packaging ports which do not allow 1997 * for binary distribution. 1998 * 1999 * PKG_CREATE_VERBOSE - Ensure periodic output during the packaging 2000 * process to avoid a watchdog timeout. 2001 * 2002 */ 2003 addbuildenv("PACKAGE_BUILDING", "yes", BENV_MAKECONF); 2004 addbuildenv("PKG_CREATE_VERBOSE", "yes", BENV_MAKECONF); 2005 asprintf(&buf, "%d", MaxJobs); 2006 addbuildenv("MAKE_JOBS_NUMBER", buf, BENV_MAKECONF); 2007 freestrp(&buf); 2008 2009 if (flavor) 2010 setenv("FLAVOR", flavor, 1); 2011 2012 /* 2013 * Become the reaper 2014 */ 2015 if (procctl(P_PID, getpid(), PROC_REAP_ACQUIRE, NULL) < 0) 2016 dfatal_errno("procctl() - Cannot become reaper"); 2017 2018 /* 2019 * Initialize a worker structure 2020 */ 2021 DoInitBuild(slot); 2022 2023 bzero(&pkg, sizeof(pkg)); 2024 pkg.portdir = portdir; /* sans flavor */ 2025 pkg.pkgfile = pkgfile; 2026 if (strchr(portdir, '/')) 2027 len = strchr(portdir, '/') - portdir; 2028 else 2029 len = 0; 2030 2031 /* 2032 * Setup the logfile 2033 */ 2034 asprintf(&pkg.logfile, 2035 "%s/%*.*s___%s%s%s.log", 2036 LogsPath, len, len, portdir, 2037 ((portdir[len] == '/') ? portdir + len + 1 : portdir + len), 2038 (flavor ? "@" : ""), 2039 (flavor ? flavor : "")); 2040 tmpfd = open(pkg.logfile, O_RDWR|O_CREAT|O_TRUNC, 0666); 2041 if (tmpfd >= 0) { 2042 if (DebugOpt >= 2) { 2043 dlog(DLOG_ALL, "[%03d] %s LOGFILE %s\n", 2044 slot, pkg.portdir, pkg.logfile); 2045 } 2046 close(tmpfd); 2047 } else { 2048 dlog(DLOG_ALL, "[%03d] LOGFILE %s (create failed)\n", 2049 slot, pkg.logfile); 2050 } 2051 2052 /* 2053 * Setup the work structure. Because this is an exec'd sub-process, 2054 * there is only one work structure. 2055 */ 2056 work = &WorkerAry[0]; 2057 work->flavor = flavor; 2058 work->fds[0] = fd; 2059 work->pkg = &pkg; 2060 work->start_time = time(NULL); 2061 2062 /* 2063 * Do mounts 2064 */ 2065 SigWork = work; 2066 setproctitle("[%02d] WORKER MOUNTS %s%s", 2067 slot, portdir, WorkerFlavorPrt); 2068 DoWorkerMounts(work); 2069 2070 /* 2071 * Generate an /etc/make.conf in the build base 2072 */ 2073 asprintf(&buf, "%s/etc/make.conf", work->basedir); 2074 fp = fopen(buf, "w"); 2075 dassert_errno(fp, "Unable to create %s\n", buf); 2076 for (benv = BuildEnv; benv; benv = benv->next) { 2077 if (benv->type & BENV_PKGLIST) 2078 continue; 2079 if ((benv->type & BENV_CMDMASK) == BENV_MAKECONF) { 2080 if (DebugOpt >= 2) { 2081 dlog(DLOG_ALL, "[%03d] ENV %s=%s\n", 2082 slot, benv->label, benv->data); 2083 } 2084 fprintf(fp, "%s=%s\n", benv->label, benv->data); 2085 } 2086 } 2087 fclose(fp); 2088 freestrp(&buf); 2089 2090 /* 2091 * Set up our hooks 2092 */ 2093 if (UsingHooks) 2094 initbulk(childHookRun, MaxBulk); 2095 2096 /* 2097 * Start phases 2098 */ 2099 wmsg.cmd = WMSG_CMD_INSTALL_PKGS; 2100 ipcwritemsg(fd, &wmsg); 2101 status = ipcreadmsg(fd, &wmsg); 2102 if (status < 0 || wmsg.cmd != WMSG_RES_INSTALL_PKGS) 2103 dfatal("pkg installation handshake failed"); 2104 do_install_phase = wmsg.status; 2105 2106 wmsg.cmd = WMSG_CMD_STATUS_UPDATE; 2107 wmsg.phase = PHASE_INSTALL_PKGS; 2108 wmsg.lines = 0; 2109 2110 status = ipcwritemsg(fd, &wmsg); 2111 2112 if (pkgpkg) { 2113 dophase(work, &wmsg, 2114 WDOG5, PHASE_PACKAGE, "package"); 2115 } else { 2116 /* 2117 * Dump as much information of the build process as possible. 2118 * Will help troubleshooting port build breakages. 2119 * Only enabled when DEVELOPER is set. 2120 * 2121 * This sort of mimics what synth did. 2122 */ 2123 if (WorkerProcFlags & WORKER_PROC_DEVELOPER) { 2124 dophase(work, &wmsg, 2125 WDOG2, PHASE_DUMP_ENV, "Environment"); 2126 dophase(work, &wmsg, 2127 WDOG2, PHASE_SHOW_CONFIG, "showconfig"); 2128 dophase(work, &wmsg, 2129 WDOG2, PHASE_DUMP_VAR, "CONFIGURE_ENV"); 2130 dophase(work, &wmsg, 2131 WDOG2, PHASE_DUMP_VAR, "CONFIGURE_ARGS"); 2132 dophase(work, &wmsg, 2133 WDOG2, PHASE_DUMP_VAR, "MAKE_ENV"); 2134 dophase(work, &wmsg, 2135 WDOG2, PHASE_DUMP_VAR, "MAKE_ARGS"); 2136 dophase(work, &wmsg, 2137 WDOG2, PHASE_DUMP_VAR, "PLIST_SUB"); 2138 dophase(work, &wmsg, 2139 WDOG2, PHASE_DUMP_VAR, "SUB_LIST"); 2140 dophase(work, &wmsg, 2141 WDOG2, PHASE_DUMP_MAKECONF, "/etc/make.conf"); 2142 } 2143 2144 if (do_install_phase) { 2145 dophase(work, &wmsg, 2146 WDOG4, PHASE_INSTALL_PKGS, "setup"); 2147 } 2148 dophase(work, &wmsg, 2149 WDOG2, PHASE_CHECK_SANITY, "check-sanity"); 2150 dophase(work, &wmsg, 2151 WDOG2, PHASE_PKG_DEPENDS, "pkg-depends"); 2152 dophase(work, &wmsg, 2153 WDOG7, PHASE_FETCH_DEPENDS, "fetch-depends"); 2154 dophase(work, &wmsg, 2155 WDOG7, PHASE_FETCH, "fetch"); 2156 dophase(work, &wmsg, 2157 WDOG2, PHASE_CHECKSUM, "checksum"); 2158 dophase(work, &wmsg, 2159 WDOG3, PHASE_EXTRACT_DEPENDS, "extract-depends"); 2160 dophase(work, &wmsg, 2161 WDOG3, PHASE_EXTRACT, "extract"); 2162 dophase(work, &wmsg, 2163 WDOG2, PHASE_PATCH_DEPENDS, "patch-depends"); 2164 dophase(work, &wmsg, 2165 WDOG2, PHASE_PATCH, "patch"); 2166 dophase(work, &wmsg, 2167 WDOG5, PHASE_BUILD_DEPENDS, "build-depends"); 2168 dophase(work, &wmsg, 2169 WDOG5, PHASE_LIB_DEPENDS, "lib-depends"); 2170 dophase(work, &wmsg, 2171 WDOG3, PHASE_CONFIGURE, "configure"); 2172 dophase(work, &wmsg, 2173 WDOG9, PHASE_BUILD, "build"); 2174 dophase(work, &wmsg, 2175 WDOG5, PHASE_RUN_DEPENDS, "run-depends"); 2176 dophase(work, &wmsg, 2177 WDOG5, PHASE_STAGE, "stage"); 2178 #if 0 2179 dophase(work, &wmsg, 2180 WDOG5, PHASE_TEST, "test"); 2181 #endif 2182 if (WorkerProcFlags & WORKER_PROC_CHECK_PLIST) { 2183 dophase(work, &wmsg, 2184 WDOG1, PHASE_CHECK_PLIST, "check-plist"); 2185 } 2186 dophase(work, &wmsg, 2187 WDOG5, PHASE_PACKAGE, "package"); 2188 2189 if (WorkerProcFlags & WORKER_PROC_INSTALL) { 2190 dophase(work, &wmsg, 2191 WDOG5, PHASE_INSTALL, "install"); 2192 } 2193 2194 if (WorkerProcFlags & WORKER_PROC_DEINSTALL) { 2195 dophase(work, &wmsg, 2196 WDOG5, PHASE_DEINSTALL, "deinstall"); 2197 } 2198 } 2199 2200 if (MasterPtyFd >= 0) { 2201 close(MasterPtyFd); 2202 MasterPtyFd = -1; 2203 } 2204 2205 setproctitle("[%02d] WORKER CLEANUP %s%s", 2206 slot, portdir, WorkerFlavorPrt); 2207 2208 /* 2209 * Copy the package to the repo. 2210 */ 2211 if (work->accum_error == 0) { 2212 char *b1; 2213 char *b2; 2214 2215 asprintf(&b1, "%s/construction/%s/pkg/%s", 2216 work->basedir, pkg.portdir, pkg.pkgfile); 2217 asprintf(&b2, "%s/%s", RepositoryPath, pkg.pkgfile); 2218 if (copyfile(b1, b2)) { 2219 ++work->accum_error; 2220 dlog(DLOG_ALL, "[%03d] %s Unable to copy %s to %s\n", 2221 work->index, pkg.portdir, b1, b2); 2222 } 2223 free(b1); 2224 free(b2); 2225 } 2226 2227 /* 2228 * Unmount, unless we are in DebugStopMode. 2229 */ 2230 if ((WorkerProcFlags & WORKER_PROC_DEBUGSTOP) == 0) 2231 DoWorkerUnmounts(work); 2232 2233 /* 2234 * Send completion status to master dsynth worker thread. 2235 */ 2236 if (work->accum_error) { 2237 wmsg.cmd = WMSG_CMD_FAILURE; 2238 } else { 2239 wmsg.cmd = WMSG_CMD_SUCCESS; 2240 } 2241 ipcwritemsg(fd, &wmsg); 2242 if (WorkerProcFlags & WORKER_PROC_DEBUGSTOP) { 2243 wmsg.cmd = WMSG_CMD_FREEZEWORKER; 2244 ipcwritemsg(fd, &wmsg); 2245 } 2246 if (UsingHooks) { 2247 while ((bulk = getbulk()) != NULL) 2248 freebulk(bulk); 2249 donebulk(); 2250 } 2251 } 2252 2253 static void 2254 dophase(worker_t *work, wmsg_t *wmsg, int wdog, int phaseid, const char *phase) 2255 { 2256 pkg_t *pkg = work->pkg; 2257 char buf[1024]; 2258 pid_t pid; 2259 int status; 2260 int ms; 2261 pid_t wpid; 2262 int wpid_reaped; 2263 int fdlog; 2264 time_t start_time; 2265 time_t last_time; 2266 time_t next_time; 2267 time_t wdog_time; 2268 FILE *fp; 2269 2270 if (work->accum_error) 2271 return; 2272 setproctitle("[%02d] WORKER %-8.8s %s%s", 2273 work->index, phase, pkg->portdir, WorkerFlavorPrt); 2274 wmsg->phase = phaseid; 2275 if (ipcwritemsg(work->fds[0], wmsg) < 0) { 2276 dlog(DLOG_ALL, "[%03d] %s Lost Communication with dsynth, " 2277 "aborting worker\n", 2278 work->index, pkg->portdir); 2279 ++work->accum_error; 2280 return; 2281 } 2282 2283 /* 2284 * Execute the port make command in chroot on a pty. 2285 */ 2286 fflush(stdout); 2287 fflush(stderr); 2288 if (MasterPtyFd >= 0) { 2289 int slavefd; 2290 2291 /* 2292 * NOTE: We can't open the slave in the child because the 2293 * master may race a disconnection test. If we open 2294 * it in the parent our close() will flush any pending 2295 * output not read by the master (which is the same 2296 * parent process) and deadlock. 2297 * 2298 * Solve this by hand-shaking the slave tty to give 2299 * the master time to close its slavefd (after this 2300 * section). 2301 * 2302 * Leave the tty defaults intact, which also likely 2303 * means it will be in line-buffered mode, so handshake 2304 * with a full line. 2305 * 2306 * TODO: Our handshake probably echos back to the master pty 2307 * due to tty echo, and ends up in the log, so just 2308 * pass through a newline. 2309 */ 2310 slavefd = open(ptsname(MasterPtyFd), O_RDWR); 2311 dassert_errno(slavefd >= 0, "Cannot open slave pty"); 2312 2313 /* 2314 * Now do the fork. 2315 */ 2316 pid = fork(); 2317 if (pid == 0) { 2318 login_tty(slavefd); 2319 /* login_tty() closes slavefd */ 2320 } else { 2321 close(slavefd); 2322 } 2323 } else { 2324 /* 2325 * Initial MasterPtyFd for the slot, just use forkpty(). 2326 */ 2327 pid = forkpty(&MasterPtyFd, NULL, NULL, NULL); 2328 } 2329 2330 /* 2331 * The slave must make sure the master has time to close slavefd 2332 * in the re-use case before going its merry way. The master needs 2333 * to set terminal modes and the window as well. 2334 */ 2335 if (pid == 0) { 2336 /* 2337 * Slave nices itself and waits for handshake 2338 */ 2339 char ttybuf[2]; 2340 2341 /* 2342 * Self-nice to be nice (ignore any error) 2343 */ 2344 if (NiceOpt) 2345 setpriority(PRIO_PROCESS, 0, NiceOpt); 2346 2347 read(0, ttybuf, 1); 2348 } else { 2349 /* 2350 * We are going through a pty, so set the tty modes to 2351 * Set tty modes so we do not get ^M's in the log files. 2352 * 2353 * This isn't fatal if it doesn't work. Remember that 2354 * our output goes through the pty to the management 2355 * process which will log it. 2356 */ 2357 struct termios tio; 2358 struct winsize win; 2359 2360 if (tcgetattr(MasterPtyFd, &tio) == 0) { 2361 tio.c_oflag |= OPOST | ONOCR; 2362 tio.c_oflag &= ~(OCRNL | ONLCR); 2363 tio.c_iflag |= ICRNL; 2364 tio.c_iflag &= ~(INLCR | IGNCR); 2365 if (tcsetattr(MasterPtyFd, TCSANOW, &tio)) { 2366 printf("tcsetattr failed: %s\n", 2367 strerror(errno)); 2368 } 2369 2370 /* 2371 * Give the tty a non-zero columns field. 2372 * This fixes at least one port (textproc/po4a) 2373 */ 2374 if (ioctl(MasterPtyFd, TIOCGWINSZ, &win) == 0) { 2375 win.ws_col = 80; 2376 ioctl(MasterPtyFd, TIOCSWINSZ, &win); 2377 } else { 2378 printf("TIOCGWINSZ failed: %s\n", 2379 strerror(errno)); 2380 } 2381 2382 } else { 2383 printf("tcgetattr failed: %s\n", strerror(errno)); 2384 } 2385 2386 /* 2387 * Master issues handshake 2388 */ 2389 write(MasterPtyFd, "\n", 1); 2390 } 2391 2392 if (pid == 0) { 2393 /* 2394 * Additional phase-specific environment variables 2395 * 2396 * - Do not try to process missing depends outside of the 2397 * depends phases. Also relies on USE_PACKAGE_DEPENDS_ONLY 2398 * in the make.conf. 2399 */ 2400 switch(phaseid) { 2401 case PHASE_CHECK_SANITY: 2402 case PHASE_FETCH: 2403 case PHASE_CHECKSUM: 2404 case PHASE_EXTRACT: 2405 case PHASE_PATCH: 2406 case PHASE_CONFIGURE: 2407 case PHASE_STAGE: 2408 case PHASE_TEST: 2409 case PHASE_CHECK_PLIST: 2410 case PHASE_INSTALL: 2411 case PHASE_DEINSTALL: 2412 break; 2413 case PHASE_PKG_DEPENDS: 2414 case PHASE_FETCH_DEPENDS: 2415 case PHASE_EXTRACT_DEPENDS: 2416 case PHASE_PATCH_DEPENDS: 2417 case PHASE_BUILD_DEPENDS: 2418 case PHASE_LIB_DEPENDS: 2419 case PHASE_RUN_DEPENDS: 2420 break; 2421 default: 2422 setenv("NO_DEPENDS", "1", 1); 2423 break; 2424 } 2425 2426 /* 2427 * Clean-up, chdir, and chroot. 2428 */ 2429 closefrom(3); 2430 if (chdir(work->basedir) < 0) 2431 dfatal_errno("chdir in phase initialization"); 2432 if (chroot(work->basedir) < 0) 2433 dfatal_errno("chroot in phase initialization"); 2434 2435 /* 2436 * We have a choice here on how to handle stdin (fd 0). 2437 * We can leave it connected to the pty in which case 2438 * the build will just block if it tries to ask a 2439 * question (and the watchdog will kill it, eventually), 2440 * or we can try to EOF the pty, or we can attach /dev/null 2441 * to descriptor 0. 2442 */ 2443 if (NullStdinOpt) { 2444 int fd; 2445 2446 fd = open("/dev/null", O_RDWR); 2447 dassert_errno(fd >= 0, "cannot open /dev/null"); 2448 if (fd != 0) { 2449 dup2(fd, 0); 2450 close(fd); 2451 } 2452 } 2453 2454 /* 2455 * Execute the appropriate command. 2456 */ 2457 switch(phaseid) { 2458 case PHASE_INSTALL_PKGS: 2459 snprintf(buf, sizeof(buf), "/tmp/dsynth_install_pkgs"); 2460 execl(buf, buf, NULL); 2461 break; 2462 case PHASE_DUMP_ENV: 2463 snprintf(buf, sizeof(buf), "/usr/bin/env"); 2464 execl(buf, buf, NULL); 2465 break; 2466 case PHASE_DUMP_VAR: 2467 snprintf(buf, sizeof(buf), "/xports/%s", pkg->portdir); 2468 execl(MAKE_BINARY, MAKE_BINARY, "-C", buf, "-V", phase, 2469 NULL); 2470 break; 2471 case PHASE_DUMP_MAKECONF: 2472 snprintf(buf, sizeof(buf), "/bin/cat"); 2473 execl(buf, buf, "/etc/make.conf", NULL); 2474 break; 2475 case PHASE_SHOW_CONFIG: 2476 /* fall-through */ 2477 default: 2478 snprintf(buf, sizeof(buf), "/xports/%s", pkg->portdir); 2479 execl(MAKE_BINARY, MAKE_BINARY, "-C", buf, phase, NULL); 2480 break; 2481 } 2482 _exit(1); 2483 } 2484 fcntl(MasterPtyFd, F_SETFL, O_NONBLOCK); 2485 2486 if (pid < 0) { 2487 dlog(DLOG_ALL, "[%03d] %s Fork Failed: %s\n", 2488 work->index, pkg->logfile, strerror(errno)); 2489 ++work->accum_error; 2490 return; 2491 } 2492 2493 SigPid = pid; 2494 2495 fdlog = open(pkg->logfile, O_RDWR|O_CREAT|O_APPEND, 0644); 2496 if (fdlog < 0) { 2497 dlog(DLOG_ALL, "[%03d] %s Cannot open logfile '%s': %s\n", 2498 work->index, pkg->portdir, 2499 pkg->logfile, strerror(errno)); 2500 } 2501 2502 snprintf(buf, sizeof(buf), 2503 "----------------------------------------" 2504 "---------------------------------------\n" 2505 "-- Phase: %s\n" 2506 "----------------------------------------" 2507 "---------------------------------------\n", 2508 phase); 2509 write(fdlog, buf, strlen(buf)); 2510 2511 start_time = time(NULL); 2512 last_time = start_time; 2513 wdog_time = start_time; 2514 wpid_reaped = 0; 2515 2516 status = 0; 2517 for (;;) { 2518 ms = mptylogpoll(MasterPtyFd, fdlog, wmsg, &wdog_time); 2519 if (ms == MPTY_FAILED) { 2520 dlog(DLOG_ALL, 2521 "[%03d] %s lost pty in phase %s, terminating\n", 2522 work->index, pkg->portdir, phase); 2523 break; 2524 } 2525 if (ms == MPTY_EOF) 2526 break; 2527 2528 /* 2529 * Generally speaking update status once a second. 2530 * This also allows us to detect if the management 2531 * dsynth process has gone away. 2532 */ 2533 next_time = time(NULL); 2534 if (next_time != last_time) { 2535 double dload[3]; 2536 double dv; 2537 int wdog_scaled; 2538 2539 /* 2540 * Send status update to the worker management thread 2541 * in the master dsynth process. Remember, *WE* are 2542 * the worker management process sub-fork. 2543 */ 2544 if (ipcwritemsg(work->fds[0], wmsg) < 0) 2545 break; 2546 last_time = next_time; 2547 2548 /* 2549 * Watchdog scaling 2550 */ 2551 getloadavg(dload, 3); 2552 adjloadavg(dload); 2553 dv = dload[2] / NumCores; 2554 if (dv < (double)NumCores) { 2555 wdog_scaled = wdog; 2556 } else { 2557 if (dv > 4.0 * NumCores) 2558 dv = 4.0 * NumCores; 2559 wdog_scaled = wdog * dv / NumCores; 2560 } 2561 2562 /* 2563 * Watchdog 2564 */ 2565 if (next_time - wdog_time >= wdog_scaled * 60) { 2566 snprintf(buf, sizeof(buf), 2567 "\n--------\n" 2568 "WATCHDOG TIMEOUT FOR %s in %s " 2569 "after %d minutes\n" 2570 "Killing pid %d\n" 2571 "--------\n", 2572 pkg->portdir, phase, wdog_scaled, pid); 2573 if (fdlog >= 0) 2574 write(fdlog, buf, strlen(buf)); 2575 dlog(DLOG_ALL, 2576 "[%03d] %s WATCHDOG TIMEOUT in %s " 2577 "after %d minutes (%d min scaled)\n", 2578 work->index, pkg->portdir, phase, 2579 wdog, wdog_scaled); 2580 kill(pid, SIGKILL); 2581 ++work->accum_error; 2582 break; 2583 } 2584 } 2585 2586 /* 2587 * Check process exit. Normally the pty will EOF 2588 * but if background processes remain we need to 2589 * check here to see if our primary exec is done, 2590 * so we can break out and reap those processes. 2591 * 2592 * Generally reap any other processes we have inherited 2593 * while we are here. 2594 */ 2595 do { 2596 wpid = wait3(&status, WNOHANG, NULL); 2597 } while (wpid > 0 && wpid != pid); 2598 if (wpid == pid && WIFEXITED(status)) { 2599 wpid_reaped = 1; 2600 break; 2601 } 2602 } 2603 2604 next_time = time(NULL); 2605 2606 setproctitle("[%02d] WORKER EXITREAP %s%s", 2607 work->index, pkg->portdir, WorkerFlavorPrt); 2608 2609 /* 2610 * We usually get here due to a mpty EOF, but not always as there 2611 * could be persistent processes still holding the slave. Finish 2612 * up getting the exit status for the main process we are waiting 2613 * on and clean out any data left on the MasterPtyFd (as it could 2614 * be blocking the exit). 2615 */ 2616 while (wpid_reaped == 0) { 2617 (void)mptylogpoll(MasterPtyFd, fdlog, wmsg, &wdog_time); 2618 wpid = waitpid(pid, &status, WNOHANG); 2619 if (wpid == pid && WIFEXITED(status)) { 2620 wpid_reaped = 1; 2621 break; 2622 } 2623 if (wpid < 0 && errno != EINTR) { 2624 break; 2625 } 2626 2627 /* 2628 * Safety. The normal phase waits until the fork/exec'd 2629 * pid finishes, causing a pty EOF on exit (the slave 2630 * descriptor is closed by the kernel on exit so the 2631 * process should already have exited). 2632 * 2633 * However, it is also possible to get here if the pty fails 2634 * for some reason. In this case, make sure that the process 2635 * is killed. 2636 */ 2637 kill(pid, SIGKILL); 2638 } 2639 2640 /* 2641 * Clean out anything left on the pty but don't wait around 2642 * because there could be background processes preventing the 2643 * slave side from closing. 2644 */ 2645 while (mptylogpoll(MasterPtyFd, fdlog, wmsg, &wdog_time) == MPTY_DATA) 2646 ; 2647 2648 /* 2649 * Report on the exit condition. If the pid was somehow lost 2650 * (probably due to someone gdb'ing the process), assume an error. 2651 */ 2652 if (wpid_reaped) { 2653 if (WEXITSTATUS(status)) { 2654 dlog(DLOG_ALL | DLOG_FILTER, 2655 "[%03d] %s Build phase '%s' failed exit %d\n", 2656 work->index, pkg->portdir, phase, 2657 WEXITSTATUS(status)); 2658 ++work->accum_error; 2659 } 2660 } else { 2661 dlog(DLOG_ALL, "[%03d] %s Build phase '%s' failed - lost pid\n", 2662 work->index, pkg->portdir, phase); 2663 ++work->accum_error; 2664 } 2665 2666 /* 2667 * Kill any processes still running (sometimes processes end up in 2668 * the background during a dports build), and clean up any other 2669 * children that we have inherited. 2670 */ 2671 phaseReapAll(); 2672 2673 /* 2674 * After the extraction phase add the space used by /construction 2675 * to the memory use. This helps us reduce the amount of paging 2676 * we do due to extremely large package extractions (languages, 2677 * chromium, etc). 2678 * 2679 * (dsynth already estimated the space used by the package deps 2680 * up front, but this will help us further). 2681 */ 2682 if (work->accum_error == 0 && phaseid == PHASE_EXTRACT) { 2683 struct statfs sfs; 2684 char *b1; 2685 2686 asprintf(&b1, "%s/construction", work->basedir); 2687 if (statfs(b1, &sfs) == 0) { 2688 wmsg->memuse = (sfs.f_blocks - sfs.f_bfree) * 2689 sfs.f_bsize; 2690 ipcwritemsg(work->fds[0], wmsg); 2691 } 2692 } 2693 2694 /* 2695 * Update log 2696 */ 2697 if (fdlog >= 0) { 2698 struct stat st; 2699 int h; 2700 int m; 2701 int s; 2702 2703 last_time = next_time - start_time; 2704 s = last_time % 60; 2705 m = last_time / 60 % 60; 2706 h = last_time / 3600; 2707 2708 fp = fdopen(fdlog, "a"); 2709 if (fp == NULL) { 2710 dlog(DLOG_ALL, "[%03d] %s Cannot fdopen fdlog: %s %d\n", 2711 work->index, pkg->portdir, 2712 strerror(errno), fstat(fdlog, &st)); 2713 close(fdlog); 2714 goto skip; 2715 } 2716 2717 fprintf(fp, "\n"); 2718 if (work->accum_error) { 2719 fprintf(fp, "FAILED %02d:%02d:%02d\n", h, m, s); 2720 } else { 2721 if (phaseid == PHASE_EXTRACT && wmsg->memuse) { 2722 fprintf(fp, "Extracted Memory Use: %6.2fM\n", 2723 wmsg->memuse / (1024.0 * 1024.0)); 2724 } 2725 fprintf(fp, "SUCCEEDED %02d:%02d:%02d\n", h, m, s); 2726 } 2727 last_time = next_time - work->start_time; 2728 s = last_time % 60; 2729 m = last_time / 60 % 60; 2730 h = last_time / 3600; 2731 if (phaseid == PHASE_PACKAGE) { 2732 fprintf(fp, "TOTAL TIME %02d:%02d:%02d\n", h, m, s); 2733 } 2734 fprintf(fp, "\n"); 2735 fclose(fp); 2736 skip: 2737 ; 2738 } 2739 2740 } 2741 2742 static void 2743 phaseReapAll(void) 2744 { 2745 struct reaper_status rs; 2746 int status; 2747 2748 while (procctl(P_PID, getpid(), PROC_REAP_STATUS, &rs) == 0) { 2749 if ((rs.flags & PROC_REAP_ACQUIRE) == 0) 2750 break; 2751 if (rs.pid_head < 0) 2752 break; 2753 if (kill(rs.pid_head, SIGKILL) == 0) { 2754 while (waitpid(rs.pid_head, &status, 0) < 0) 2755 ; 2756 } 2757 } 2758 while (wait3(&status, 0, NULL) > 0) 2759 ; 2760 } 2761 2762 static void 2763 phaseTerminateSignal(int sig __unused) 2764 { 2765 if (CopyFileFd >= 0) 2766 close(CopyFileFd); 2767 if (MasterPtyFd >= 0) 2768 close(MasterPtyFd); 2769 if (SigPid > 1) 2770 kill(SigPid, SIGKILL); 2771 phaseReapAll(); 2772 if (SigWork) 2773 DoWorkerUnmounts(SigWork); 2774 exit(1); 2775 } 2776 2777 static 2778 char * 2779 buildskipreason(pkglink_t *parent, pkg_t *pkg) 2780 { 2781 pkglink_t *link; 2782 pkg_t *scan; 2783 char *reason = NULL; 2784 char *ptr; 2785 size_t tot; 2786 size_t len; 2787 pkglink_t stack; 2788 2789 if ((pkg->flags & PKGF_NOBUILD_I) && pkg->ignore) 2790 asprintf(&reason, "%s ", pkg->ignore); 2791 2792 tot = 0; 2793 PKGLIST_FOREACH(link, &pkg->idepon_list) { 2794 #if 0 2795 if (link->dep_type > DEP_TYPE_BUILD) 2796 continue; 2797 #endif 2798 scan = link->pkg; 2799 if (scan == NULL) 2800 continue; 2801 if ((scan->flags & (PKGF_ERROR | PKGF_NOBUILD)) == 0) 2802 continue; 2803 if (scan->flags & PKGF_NOBUILD) { 2804 stack.pkg = scan; 2805 stack.next = parent; 2806 ptr = buildskipreason(&stack, scan); 2807 len = strlen(scan->portdir) + strlen(ptr) + 8; 2808 reason = realloc(reason, tot + len); 2809 snprintf(reason + tot, len, "%s->%s", 2810 scan->portdir, ptr); 2811 free(ptr); 2812 } else { 2813 len = strlen(scan->portdir) + 8; 2814 reason = realloc(reason, tot + len); 2815 snprintf(reason + tot, len, "%s", scan->portdir); 2816 } 2817 2818 /* 2819 * Don't try to print the entire graph 2820 */ 2821 if (parent) 2822 break; 2823 tot += strlen(reason + tot); 2824 reason[tot++] = ' '; 2825 reason[tot] = 0; 2826 } 2827 return (reason); 2828 } 2829 2830 /* 2831 * Count number of packages that would be skipped due to the 2832 * specified package having failed. 2833 * 2834 * Call with mode 1 to count, and mode 0 to clear the 2835 * cumulative rscan flag (used to de-duplicate the count). 2836 * 2837 * Must be serialized. 2838 */ 2839 static int 2840 buildskipcount_dueto(pkg_t *pkg, int mode) 2841 { 2842 pkglink_t *link; 2843 pkg_t *scan; 2844 int total; 2845 2846 total = 0; 2847 PKGLIST_FOREACH(link, &pkg->deponi_list) { 2848 scan = link->pkg; 2849 if (scan == NULL || scan->rscan == mode) 2850 continue; 2851 scan->rscan = mode; 2852 ++total; 2853 total += buildskipcount_dueto(scan, mode); 2854 } 2855 return total; 2856 } 2857 2858 /* 2859 * The master ptyfd is in non-blocking mode. Drain up to 1024 bytes 2860 * and update wmsg->lines and *wdog_timep as appropriate. 2861 * 2862 * This function will poll, stalling up to 1 second. 2863 */ 2864 static int 2865 mptylogpoll(int ptyfd, int fdlog, wmsg_t *wmsg, time_t *wdog_timep) 2866 { 2867 struct pollfd pfd; 2868 char buf[1024]; 2869 ssize_t r; 2870 2871 pfd.fd = ptyfd; 2872 pfd.events = POLLIN; 2873 pfd.revents = 0; 2874 2875 poll(&pfd, 1, 1000); 2876 if (pfd.revents) { 2877 r = read(ptyfd, buf, sizeof(buf)); 2878 if (r > 0) { 2879 *wdog_timep = time(NULL); 2880 if (r > 0 && fdlog >= 0) 2881 write(fdlog, buf, r); 2882 while (--r >= 0) { 2883 if (buf[r] == '\n') 2884 ++wmsg->lines; 2885 } 2886 return MPTY_DATA; 2887 } else if (r < 0) { 2888 if (errno != EINTR && errno != EAGAIN) 2889 return MPTY_FAILED; 2890 return MPTY_AGAIN; 2891 } else if (r == 0) { 2892 return MPTY_EOF; 2893 } 2894 } 2895 return MPTY_AGAIN; 2896 } 2897 2898 /* 2899 * Copy a (package) file from (src) to (dst), use an intermediate file and 2900 * rename to ensure that interruption does not leave us with a corrupt 2901 * package file. 2902 * 2903 * This is called by the WORKER process. 2904 * 2905 * (dsynth management thread -> WORKER process -> sub-processes) 2906 */ 2907 #define COPYBLKSIZE 32768 2908 2909 int 2910 copyfile(char *src, char *dst) 2911 { 2912 char *tmp; 2913 char *buf; 2914 int fd1; 2915 int fd2; 2916 int error = 0; 2917 int mask; 2918 ssize_t r; 2919 2920 asprintf(&tmp, "%s.new", dst); 2921 buf = malloc(COPYBLKSIZE); 2922 2923 mask = sigsetmask(sigmask(SIGTERM)|sigmask(SIGINT)|sigmask(SIGHUP)); 2924 fd1 = open(src, O_RDONLY|O_CLOEXEC); 2925 fd2 = open(tmp, O_RDWR|O_CREAT|O_TRUNC|O_CLOEXEC, 0644); 2926 CopyFileFd = fd1; 2927 sigsetmask(mask); 2928 while ((r = read(fd1, buf, COPYBLKSIZE)) > 0) { 2929 if (write(fd2, buf, r) != r) 2930 error = 1; 2931 } 2932 if (r < 0) 2933 error = 1; 2934 mask = sigsetmask(sigmask(SIGTERM)|sigmask(SIGINT)|sigmask(SIGHUP)); 2935 CopyFileFd = -1; 2936 close(fd1); 2937 close(fd2); 2938 sigsetmask(mask); 2939 if (error) { 2940 remove(tmp); 2941 } else { 2942 if (rename(tmp, dst)) { 2943 error = 1; 2944 remove(tmp); 2945 } 2946 } 2947 2948 freestrp(&buf); 2949 freestrp(&tmp); 2950 2951 return error; 2952 } 2953 2954 /* 2955 * doHook() 2956 * 2957 * primary process (threaded) - run_start, run_end, pkg_ignored, pkg_skipped 2958 * worker process (threaded) - pkg_sucess, pkg_failure 2959 * 2960 * If waitfor is non-zero this hook will be serialized. 2961 */ 2962 static void 2963 doHook(pkg_t *pkg, const char *id, const char *path, int waitfor) 2964 { 2965 if (path == NULL) 2966 return; 2967 while (waitfor && getbulk() != NULL) 2968 ; 2969 if (pkg) 2970 queuebulk(pkg->portdir, id, path, pkg->pkgfile); 2971 else 2972 queuebulk(NULL, id, path, NULL); 2973 while (waitfor && getbulk() != NULL) 2974 ; 2975 } 2976 2977 /* 2978 * Execute hook (backend) 2979 * 2980 * s1 - portdir 2981 * s2 - id 2982 * s3 - script path 2983 * s4 - pkgfile (if applicable) 2984 */ 2985 static void 2986 childHookRun(bulk_t *bulk) 2987 { 2988 const char *cav[MAXCAC]; 2989 buildenv_t benv[MAXCAC]; 2990 char buf1[128]; 2991 char buf2[128]; 2992 char buf3[128]; 2993 char buf4[128]; 2994 FILE *fp; 2995 char *ptr; 2996 size_t len; 2997 pid_t pid; 2998 int cac; 2999 int bi; 3000 3001 cac = 0; 3002 bi = 0; 3003 bzero(benv, sizeof(benv)); 3004 3005 cav[cac++] = bulk->s3; 3006 3007 benv[bi].label = "PROFILE"; 3008 benv[bi].data = Profile; 3009 ++bi; 3010 3011 benv[bi].label = "DIR_PACKAGES"; 3012 benv[bi].data = PackagesPath; 3013 ++bi; 3014 3015 benv[bi].label = "DIR_REPOSITORY"; 3016 benv[bi].data = RepositoryPath; 3017 ++bi; 3018 3019 benv[bi].label = "DIR_PORTS"; 3020 benv[bi].data = DPortsPath; 3021 ++bi; 3022 3023 benv[bi].label = "DIR_OPTIONS"; 3024 benv[bi].data = OptionsPath; 3025 ++bi; 3026 3027 benv[bi].label = "DIR_DISTFILES"; 3028 benv[bi].data = DistFilesPath; 3029 ++bi; 3030 3031 benv[bi].label = "DIR_LOGS"; 3032 benv[bi].data = LogsPath; 3033 ++bi; 3034 3035 benv[bi].label = "DIR_BUILDBASE"; 3036 benv[bi].data = BuildBase; 3037 ++bi; 3038 3039 if (strcmp(bulk->s2, "hook_run_start") == 0) { 3040 snprintf(buf1, sizeof(buf1), "%d", BuildTotal); 3041 benv[bi].label = "PORTS_QUEUED"; 3042 benv[bi].data = buf1; 3043 ++bi; 3044 } else if (strcmp(bulk->s2, "hook_run_end") == 0) { 3045 snprintf(buf1, sizeof(buf1), "%d", BuildSuccessCount); 3046 benv[bi].label = "PORTS_BUILT"; 3047 benv[bi].data = buf1; 3048 ++bi; 3049 snprintf(buf2, sizeof(buf2), "%d", BuildFailCount); 3050 benv[bi].label = "PORTS_FAILED"; 3051 benv[bi].data = buf2; 3052 ++bi; 3053 snprintf(buf3, sizeof(buf3), "%d", BuildIgnoreCount); 3054 benv[bi].label = "PORTS_IGNORED"; 3055 benv[bi].data = buf3; 3056 ++bi; 3057 snprintf(buf4, sizeof(buf4), "%d", BuildSkipCount); 3058 benv[bi].label = "PORTS_SKIPPED"; 3059 benv[bi].data = buf4; 3060 ++bi; 3061 } else { 3062 /* 3063 * success, failure, ignored, skipped 3064 */ 3065 benv[bi].label = "RESULT"; 3066 if (strcmp(bulk->s2, "hook_pkg_success") == 0) { 3067 benv[bi].data = "success"; 3068 } else if (strcmp(bulk->s2, "hook_pkg_failure") == 0) { 3069 benv[bi].data = "failure"; 3070 } else if (strcmp(bulk->s2, "hook_pkg_ignored") == 0) { 3071 benv[bi].data = "ignored"; 3072 } else if (strcmp(bulk->s2, "hook_pkg_skipped") == 0) { 3073 benv[bi].data = "skipped"; 3074 } else { 3075 dfatal("Unknown hook id: %s", bulk->s2); 3076 /* NOT REACHED */ 3077 } 3078 ++bi; 3079 3080 /* 3081 * For compatibility with synth: 3082 * 3083 * ORIGIN does not include any @flavor, thus it is suitable 3084 * for finding the actual port directory/subdirectory. 3085 * 3086 * FLAVOR is set to ORIGIN if there is no flavor, otherwise 3087 * it is set to only the flavor sans the '@'. 3088 */ 3089 if ((ptr = strchr(bulk->s1, '@')) != NULL) { 3090 snprintf(buf1, sizeof(buf1), "%*.*s", 3091 (int)(ptr - bulk->s1), 3092 (int)(ptr - bulk->s1), 3093 bulk->s1); 3094 benv[bi].label = "ORIGIN"; 3095 benv[bi].data = buf1; 3096 ++bi; 3097 benv[bi].label = "FLAVOR"; 3098 benv[bi].data = ptr + 1; 3099 ++bi; 3100 } else { 3101 benv[bi].label = "ORIGIN"; 3102 benv[bi].data = bulk->s1; 3103 ++bi; 3104 benv[bi].label = "FLAVOR"; 3105 benv[bi].data = bulk->s1; 3106 ++bi; 3107 } 3108 benv[bi].label = "PKGNAME"; 3109 benv[bi].data = bulk->s4; 3110 ++bi; 3111 } 3112 3113 benv[bi].label = NULL; 3114 benv[bi].data = NULL; 3115 3116 fp = dexec_open(bulk->s1, cav, cac, &pid, benv, 0, 0); 3117 while ((ptr = fgetln(fp, &len)) != NULL) 3118 ; 3119 3120 if (dexec_close(fp, pid)) { 3121 dlog(DLOG_ALL, 3122 "[XXX] %s SCRIPT %s (%s)\n", 3123 bulk->s1, bulk->s2, bulk->s3); 3124 } 3125 } 3126 3127 /* 3128 * Adjusts dload[0] by adding in t_pw (processes waiting on page-fault). 3129 * We don't want load reductions due to e.g. thrashing to cause dsynth 3130 * to increase the dynamic limit because it thinks the load is low. 3131 * 3132 * This has a desirable property. If the system pager cannot keep up 3133 * with process demand t_pw will spike while loadavg will only drop 3134 * slowly, resulting in a high adjusted load calculation that causes 3135 * dsynth to quickly clamp-down the limit. If the condition alleviates, 3136 * the limit will then rise slowly again, possibly even before existing 3137 * jobs are retired to meet the clamp-down from the original spike. 3138 */ 3139 static void 3140 adjloadavg(double *dload) 3141 { 3142 #if defined(__DragonFly__) 3143 struct vmtotal total; 3144 size_t size; 3145 3146 size = sizeof(total); 3147 if (sysctlbyname("vm.vmtotal", &total, &size, NULL, 0) == 0) { 3148 dload[0] += (double)total.t_pw; 3149 } 3150 #else 3151 dload[0] += 0.0; /* just avoid compiler 'unused' warnings */ 3152 #endif 3153 } 3154 3155 /* 3156 * Check if the ports directory contents has changed and force a 3157 * package to be rebuilt if it has by clearing the PACKAGED bit. 3158 */ 3159 static 3160 void 3161 check_packaged(const char *dbmpath, pkg_t *pkgs) 3162 { 3163 pkg_t *scan; 3164 datum key; 3165 datum data; 3166 char *buf; 3167 3168 if (CheckDBM == NULL) { 3169 dlog(DLOG_ABN, "[XXX] Unable to open/create dbm %s\n", dbmpath); 3170 return; 3171 } 3172 for (scan = pkgs; scan; scan = scan->bnext) { 3173 if ((scan->flags & PKGF_PACKAGED) == 0) 3174 continue; 3175 key.dptr = scan->portdir; 3176 key.dsize = strlen(scan->portdir); 3177 data = dbm_fetch(CheckDBM, key); 3178 if (data.dptr && data.dsize == sizeof(uint32_t) && 3179 *(uint32_t *)data.dptr != scan->crc32) { 3180 scan->flags &= ~PKGF_PACKAGED; 3181 asprintf(&buf, "%s/%s", RepositoryPath, scan->pkgfile); 3182 if (OverridePkgDeleteOpt >= 2) { 3183 scan->flags |= PKGF_PACKAGED; 3184 dlog(DLOG_ALL, 3185 "[XXX] %s DELETE-PACKAGE %s " 3186 "(port content changed CRC %08x/%08x " 3187 "OVERRIDE, NOT DELETED)\n", 3188 scan->portdir, buf, 3189 *(uint32_t *)data.dptr, scan->crc32); 3190 } else if (remove(buf) < 0) { 3191 dlog(DLOG_ALL, 3192 "[XXX] %s DELETE-PACKAGE %s (failed)\n", 3193 scan->portdir, buf); 3194 } else { 3195 dlog(DLOG_ALL, 3196 "[XXX] %s DELETE-PACKAGE %s " 3197 "(port content changed CRC %08x/%08x)\n", 3198 scan->portdir, buf, 3199 *(uint32_t *)data.dptr, scan->crc32); 3200 } 3201 freestrp(&buf); 3202 } else if (data.dptr == NULL) { 3203 data.dptr = &scan->crc32; 3204 data.dsize = sizeof(scan->crc32); 3205 dbm_store(CheckDBM, key, data, DBM_REPLACE); 3206 } 3207 } 3208 } 3209