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, ".tbz") == 0) 1796 tot += st.st_size * 3; 1797 else 1798 tot += st.st_size * 2; 1799 } 1800 free(path); 1801 } 1802 if (first_one_only) 1803 break; 1804 } 1805 return tot; 1806 } 1807 1808 /* 1809 * Worker process interactions. 1810 * 1811 * The worker process is responsible for managing the build of a single 1812 * package. It is exec'd by the master dsynth and only loads the 1813 * configuration. 1814 * 1815 * This process does not run in the chroot. It will become the reaper for 1816 * all sub-processes and it will enter the chroot to execute various phases. 1817 * It catches SIGINTR, SIGHUP, and SIGPIPE and will iterate, terminate, and 1818 * reap all sub-process upon kill or exit. 1819 * 1820 * The command line forwarded to this function is: 1821 * 1822 * WORKER slot# socketfd portdir/subdir 1823 * 1824 * TERM=dumb 1825 * USER=root 1826 * HOME=/root 1827 * LANG=C 1828 * SSL_NO_VERIFY_PEER=1 1829 * USE_PACKAGE_DEPENDS_ONLY=1 1830 * PORTSDIR=/xports 1831 * PORT_DBDIR=/options For ports options 1832 * PACKAGE_BUILDING=yes Don't build packages that aren't legally 1833 * buildable for a binary repo. 1834 * PKG_DBDIR=/var/db/pkg 1835 * PKG_CACHEDIR=/var/cache/pkg 1836 * PKG_CREATE_VERBOSE=yes Ensure periodic output during packaging 1837 * (custom environment) 1838 * PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin 1839 * UNAME_s=DragonFly (example) 1840 * UNAME_v=DragonFly 5.7-SYNTH (example) 1841 * UNAME_p=x86_64 (example) 1842 * UNAME_m=x86_64 (example) 1843 * UNAME_r=5.7-SYNTH (example) 1844 * NO_DEPENDS=yes (conditional based on phase) 1845 * DISTDIR=/distfiles 1846 * WRKDIRPREFIX=/construction 1847 * BATCH=yes 1848 * MAKE_JOBS_NUMBER=n 1849 * 1850 * SETUP: 1851 * ldconfig -R 1852 * /usr/local/sbin/pkg-static install /packages/All/<the pkg pkg> 1853 * /usr/local/sbin/pkg-static install /packages/All/<pkg> 1854 * (for all dependencies) 1855 * 1856 * PHASES: make -C path FLAVOR=flavor <phase> 1857 * check-sanity 1858 * pkg-depends 1859 * fetch-depends 1860 * fetch 1861 * checksum 1862 * extract-depends 1863 * extract 1864 * patch-depends 1865 * patch 1866 * build-depends 1867 * lib-depends 1868 * configure 1869 * build 1870 * run-depends 1871 * stage 1872 * test (skipped) 1873 * check-plist ('dsynth test blahblah' or 'dsynth -D everything' only) 1874 * package e.g. /construction/lang/perl5.28/pkg/perl5-5.28.2.txz 1875 * install (skipped) 1876 * deinstall (skipped) 1877 */ 1878 void 1879 WorkerProcess(int ac, char **av) 1880 { 1881 wmsg_t wmsg; 1882 int fd; 1883 int slot; 1884 int tmpfd; 1885 int pkgpkg = 0; 1886 int status; 1887 int len; 1888 int do_install_phase; 1889 char *portdir; 1890 char *pkgfile; 1891 char *flavor; 1892 char *buf; 1893 worker_t *work; 1894 bulk_t *bulk; 1895 pkg_t pkg; 1896 buildenv_t *benv; 1897 FILE *fp; 1898 1899 /* 1900 * Parse arguments 1901 */ 1902 if (ac != 6) { 1903 dlog(DLOG_ALL, "WORKER PROCESS %d- bad arguments\n", getpid()); 1904 exit(1); 1905 } 1906 slot = strtol(av[1], NULL, 0); 1907 fd = strtol(av[2], NULL, 0); /* master<->slave messaging */ 1908 portdir = av[3]; 1909 pkgfile = av[4]; 1910 flavor = strchr(portdir, '@'); 1911 if (flavor) { 1912 *flavor++ = 0; 1913 asprintf(&buf, "@%s", flavor); 1914 WorkerFlavorPrt = buf; 1915 buf = NULL; /* safety */ 1916 } 1917 WorkerProcFlags = strtol(av[5], NULL, 0); 1918 1919 bzero(&wmsg, sizeof(wmsg)); 1920 1921 setproctitle("[%02d] WORKER STARTUP %s%s", 1922 slot, portdir, WorkerFlavorPrt); 1923 1924 if (strcmp(portdir, "ports-mgmt/pkg") == 0) 1925 pkgpkg = 1; 1926 1927 signal(SIGTERM, phaseTerminateSignal); 1928 signal(SIGINT, phaseTerminateSignal); 1929 signal(SIGHUP, phaseTerminateSignal); 1930 1931 /* 1932 * Set up the environment 1933 */ 1934 setenv("TERM", "dumb", 1); 1935 setenv("USER", "root", 1); 1936 setenv("HOME", "/root", 1); 1937 setenv("LANG", "C", 1); 1938 setenv("SSL_NO_VERIFY_PEER", "1", 1); 1939 1940 addbuildenv("USE_PACKAGE_DEPENDS_ONLY", "yes", BENV_MAKECONF); 1941 addbuildenv("PORTSDIR", "/xports", BENV_MAKECONF); 1942 addbuildenv("PORT_DBDIR", "/options", BENV_MAKECONF); 1943 addbuildenv("PKG_DBDIR", "/var/db/pkg", BENV_MAKECONF); 1944 addbuildenv("PKG_CACHEDIR", "/var/cache/pkg", BENV_MAKECONF); 1945 addbuildenv("PKG_SUFX", UsePkgSufx, BENV_MAKECONF); 1946 if (WorkerProcFlags & WORKER_PROC_DEVELOPER) 1947 addbuildenv("DEVELOPER", "1", BENV_MAKECONF); 1948 1949 /* 1950 * CCache is a horrible unreliable hack but... leave the 1951 * mechanism in-place in case someone has a death wish. 1952 */ 1953 if (UseCCache) { 1954 addbuildenv("WITH_CCACHE_BUILD", "yes", BENV_MAKECONF); 1955 addbuildenv("CCACHE_DIR", "/ccache", BENV_MAKECONF); 1956 } 1957 1958 addbuildenv("UID", "0", BENV_MAKECONF); 1959 addbuildenv("ARCH", ArchitectureName, BENV_MAKECONF); 1960 1961 /* 1962 * Always honor either the operating system detection or the 1963 * operating system selection in the config file. 1964 */ 1965 addbuildenv("OPSYS", OperatingSystemName, BENV_MAKECONF); 1966 1967 #ifdef __DragonFly__ 1968 addbuildenv("DFLYVERSION", VersionFromParamHeader, BENV_MAKECONF); 1969 addbuildenv("OSVERSION", "9999999", BENV_MAKECONF); 1970 #else 1971 #error "Need OS-specific data to generate make.conf" 1972 #endif 1973 1974 addbuildenv("OSREL", ReleaseName, BENV_MAKECONF); 1975 addbuildenv("_OSRELEASE", VersionOnlyName, BENV_MAKECONF); 1976 1977 setenv("PATH", 1978 "/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin", 1979 1); 1980 1981 setenv("UNAME_s", OperatingSystemName, 1); 1982 setenv("UNAME_v", VersionName, 1); 1983 setenv("UNAME_p", ArchitectureName, 1); 1984 setenv("UNAME_m", MachineName, 1); 1985 setenv("UNAME_r", ReleaseName, 1); 1986 1987 addbuildenv("DISTDIR", "/distfiles", BENV_MAKECONF); 1988 addbuildenv("WRKDIRPREFIX", "/construction", BENV_MAKECONF); 1989 addbuildenv("BATCH", "yes", BENV_MAKECONF); 1990 1991 /* 1992 * Special consideration 1993 * 1994 * PACKAGE_BUILDING - Disallow packaging ports which do not allow 1995 * for binary distribution. 1996 * 1997 * PKG_CREATE_VERBOSE - Ensure periodic output during the packaging 1998 * process to avoid a watchdog timeout. 1999 * 2000 */ 2001 addbuildenv("PACKAGE_BUILDING", "yes", BENV_MAKECONF); 2002 addbuildenv("PKG_CREATE_VERBOSE", "yes", BENV_MAKECONF); 2003 asprintf(&buf, "%d", MaxJobs); 2004 addbuildenv("MAKE_JOBS_NUMBER", buf, BENV_MAKECONF); 2005 freestrp(&buf); 2006 2007 if (flavor) 2008 setenv("FLAVOR", flavor, 1); 2009 2010 /* 2011 * Become the reaper 2012 */ 2013 if (procctl(P_PID, getpid(), PROC_REAP_ACQUIRE, NULL) < 0) 2014 dfatal_errno("procctl() - Cannot become reaper"); 2015 2016 /* 2017 * Initialize a worker structure 2018 */ 2019 DoInitBuild(slot); 2020 2021 bzero(&pkg, sizeof(pkg)); 2022 pkg.portdir = portdir; /* sans flavor */ 2023 pkg.pkgfile = pkgfile; 2024 if (strchr(portdir, '/')) 2025 len = strchr(portdir, '/') - portdir; 2026 else 2027 len = 0; 2028 2029 /* 2030 * Setup the logfile 2031 */ 2032 asprintf(&pkg.logfile, 2033 "%s/%*.*s___%s%s%s.log", 2034 LogsPath, len, len, portdir, 2035 ((portdir[len] == '/') ? portdir + len + 1 : portdir + len), 2036 (flavor ? "@" : ""), 2037 (flavor ? flavor : "")); 2038 tmpfd = open(pkg.logfile, O_RDWR|O_CREAT|O_TRUNC, 0666); 2039 if (tmpfd >= 0) { 2040 if (DebugOpt >= 2) { 2041 dlog(DLOG_ALL, "[%03d] %s LOGFILE %s\n", 2042 slot, pkg.portdir, pkg.logfile); 2043 } 2044 close(tmpfd); 2045 } else { 2046 dlog(DLOG_ALL, "[%03d] LOGFILE %s (create failed)\n", 2047 slot, pkg.logfile); 2048 } 2049 2050 /* 2051 * Setup the work structure. Because this is an exec'd sub-process, 2052 * there is only one work structure. 2053 */ 2054 work = &WorkerAry[0]; 2055 work->flavor = flavor; 2056 work->fds[0] = fd; 2057 work->pkg = &pkg; 2058 work->start_time = time(NULL); 2059 2060 /* 2061 * Do mounts 2062 */ 2063 SigWork = work; 2064 setproctitle("[%02d] WORKER MOUNTS %s%s", 2065 slot, portdir, WorkerFlavorPrt); 2066 DoWorkerMounts(work); 2067 2068 /* 2069 * Generate an /etc/make.conf in the build base 2070 */ 2071 asprintf(&buf, "%s/etc/make.conf", work->basedir); 2072 fp = fopen(buf, "w"); 2073 dassert_errno(fp, "Unable to create %s\n", buf); 2074 for (benv = BuildEnv; benv; benv = benv->next) { 2075 if (benv->type & BENV_PKGLIST) 2076 continue; 2077 if ((benv->type & BENV_CMDMASK) == BENV_MAKECONF) { 2078 if (DebugOpt >= 2) { 2079 dlog(DLOG_ALL, "[%03d] ENV %s=%s\n", 2080 slot, benv->label, benv->data); 2081 } 2082 fprintf(fp, "%s=%s\n", benv->label, benv->data); 2083 } 2084 } 2085 fclose(fp); 2086 freestrp(&buf); 2087 2088 /* 2089 * Set up our hooks 2090 */ 2091 if (UsingHooks) 2092 initbulk(childHookRun, MaxBulk); 2093 2094 /* 2095 * Start phases 2096 */ 2097 wmsg.cmd = WMSG_CMD_INSTALL_PKGS; 2098 ipcwritemsg(fd, &wmsg); 2099 status = ipcreadmsg(fd, &wmsg); 2100 if (status < 0 || wmsg.cmd != WMSG_RES_INSTALL_PKGS) 2101 dfatal("pkg installation handshake failed"); 2102 do_install_phase = wmsg.status; 2103 2104 wmsg.cmd = WMSG_CMD_STATUS_UPDATE; 2105 wmsg.phase = PHASE_INSTALL_PKGS; 2106 wmsg.lines = 0; 2107 2108 status = ipcwritemsg(fd, &wmsg); 2109 2110 if (pkgpkg) { 2111 dophase(work, &wmsg, 2112 WDOG5, PHASE_PACKAGE, "package"); 2113 } else { 2114 /* 2115 * Dump as much information of the build process as possible. 2116 * Will help troubleshooting port build breakages. 2117 * Only enabled when DEVELOPER is set. 2118 * 2119 * This sort of mimics what synth did. 2120 */ 2121 if (WorkerProcFlags & WORKER_PROC_DEVELOPER) { 2122 dophase(work, &wmsg, 2123 WDOG2, PHASE_DUMP_ENV, "Environment"); 2124 dophase(work, &wmsg, 2125 WDOG2, PHASE_SHOW_CONFIG, "showconfig"); 2126 dophase(work, &wmsg, 2127 WDOG2, PHASE_DUMP_VAR, "CONFIGURE_ENV"); 2128 dophase(work, &wmsg, 2129 WDOG2, PHASE_DUMP_VAR, "CONFIGURE_ARGS"); 2130 dophase(work, &wmsg, 2131 WDOG2, PHASE_DUMP_VAR, "MAKE_ENV"); 2132 dophase(work, &wmsg, 2133 WDOG2, PHASE_DUMP_VAR, "MAKE_ARGS"); 2134 dophase(work, &wmsg, 2135 WDOG2, PHASE_DUMP_VAR, "PLIST_SUB"); 2136 dophase(work, &wmsg, 2137 WDOG2, PHASE_DUMP_VAR, "SUB_LIST"); 2138 dophase(work, &wmsg, 2139 WDOG2, PHASE_DUMP_MAKECONF, "/etc/make.conf"); 2140 } 2141 2142 if (do_install_phase) { 2143 dophase(work, &wmsg, 2144 WDOG4, PHASE_INSTALL_PKGS, "setup"); 2145 } 2146 dophase(work, &wmsg, 2147 WDOG2, PHASE_CHECK_SANITY, "check-sanity"); 2148 dophase(work, &wmsg, 2149 WDOG2, PHASE_PKG_DEPENDS, "pkg-depends"); 2150 dophase(work, &wmsg, 2151 WDOG7, PHASE_FETCH_DEPENDS, "fetch-depends"); 2152 dophase(work, &wmsg, 2153 WDOG7, PHASE_FETCH, "fetch"); 2154 dophase(work, &wmsg, 2155 WDOG2, PHASE_CHECKSUM, "checksum"); 2156 dophase(work, &wmsg, 2157 WDOG3, PHASE_EXTRACT_DEPENDS, "extract-depends"); 2158 dophase(work, &wmsg, 2159 WDOG3, PHASE_EXTRACT, "extract"); 2160 dophase(work, &wmsg, 2161 WDOG2, PHASE_PATCH_DEPENDS, "patch-depends"); 2162 dophase(work, &wmsg, 2163 WDOG2, PHASE_PATCH, "patch"); 2164 dophase(work, &wmsg, 2165 WDOG5, PHASE_BUILD_DEPENDS, "build-depends"); 2166 dophase(work, &wmsg, 2167 WDOG5, PHASE_LIB_DEPENDS, "lib-depends"); 2168 dophase(work, &wmsg, 2169 WDOG3, PHASE_CONFIGURE, "configure"); 2170 dophase(work, &wmsg, 2171 WDOG9, PHASE_BUILD, "build"); 2172 dophase(work, &wmsg, 2173 WDOG5, PHASE_RUN_DEPENDS, "run-depends"); 2174 dophase(work, &wmsg, 2175 WDOG5, PHASE_STAGE, "stage"); 2176 #if 0 2177 dophase(work, &wmsg, 2178 WDOG5, PHASE_TEST, "test"); 2179 #endif 2180 if (WorkerProcFlags & WORKER_PROC_CHECK_PLIST) { 2181 dophase(work, &wmsg, 2182 WDOG1, PHASE_CHECK_PLIST, "check-plist"); 2183 } 2184 dophase(work, &wmsg, 2185 WDOG5, PHASE_PACKAGE, "package"); 2186 2187 if (WorkerProcFlags & WORKER_PROC_INSTALL) { 2188 dophase(work, &wmsg, 2189 WDOG5, PHASE_INSTALL, "install"); 2190 } 2191 2192 if (WorkerProcFlags & WORKER_PROC_DEINSTALL) { 2193 dophase(work, &wmsg, 2194 WDOG5, PHASE_DEINSTALL, "deinstall"); 2195 } 2196 } 2197 2198 if (MasterPtyFd >= 0) { 2199 close(MasterPtyFd); 2200 MasterPtyFd = -1; 2201 } 2202 2203 setproctitle("[%02d] WORKER CLEANUP %s%s", 2204 slot, portdir, WorkerFlavorPrt); 2205 2206 /* 2207 * Copy the package to the repo. 2208 */ 2209 if (work->accum_error == 0) { 2210 char *b1; 2211 char *b2; 2212 2213 asprintf(&b1, "%s/construction/%s/pkg/%s", 2214 work->basedir, pkg.portdir, pkg.pkgfile); 2215 asprintf(&b2, "%s/%s", RepositoryPath, pkg.pkgfile); 2216 if (copyfile(b1, b2)) { 2217 ++work->accum_error; 2218 dlog(DLOG_ALL, "[%03d] %s Unable to copy %s to %s\n", 2219 work->index, pkg.portdir, b1, b2); 2220 } 2221 free(b1); 2222 free(b2); 2223 } 2224 2225 /* 2226 * Unmount, unless we are in DebugStopMode. 2227 */ 2228 if ((WorkerProcFlags & WORKER_PROC_DEBUGSTOP) == 0) 2229 DoWorkerUnmounts(work); 2230 2231 /* 2232 * Send completion status to master dsynth worker thread. 2233 */ 2234 if (work->accum_error) { 2235 wmsg.cmd = WMSG_CMD_FAILURE; 2236 } else { 2237 wmsg.cmd = WMSG_CMD_SUCCESS; 2238 } 2239 ipcwritemsg(fd, &wmsg); 2240 if (WorkerProcFlags & WORKER_PROC_DEBUGSTOP) { 2241 wmsg.cmd = WMSG_CMD_FREEZEWORKER; 2242 ipcwritemsg(fd, &wmsg); 2243 } 2244 if (UsingHooks) { 2245 while ((bulk = getbulk()) != NULL) 2246 freebulk(bulk); 2247 donebulk(); 2248 } 2249 } 2250 2251 static void 2252 dophase(worker_t *work, wmsg_t *wmsg, int wdog, int phaseid, const char *phase) 2253 { 2254 pkg_t *pkg = work->pkg; 2255 char buf[1024]; 2256 pid_t pid; 2257 int status; 2258 int ms; 2259 pid_t wpid; 2260 int wpid_reaped; 2261 int fdlog; 2262 time_t start_time; 2263 time_t last_time; 2264 time_t next_time; 2265 time_t wdog_time; 2266 FILE *fp; 2267 2268 if (work->accum_error) 2269 return; 2270 setproctitle("[%02d] WORKER %-8.8s %s%s", 2271 work->index, phase, pkg->portdir, WorkerFlavorPrt); 2272 wmsg->phase = phaseid; 2273 if (ipcwritemsg(work->fds[0], wmsg) < 0) { 2274 dlog(DLOG_ALL, "[%03d] %s Lost Communication with dsynth, " 2275 "aborting worker\n", 2276 work->index, pkg->portdir); 2277 ++work->accum_error; 2278 return; 2279 } 2280 2281 /* 2282 * Execute the port make command in chroot on a pty. 2283 */ 2284 fflush(stdout); 2285 fflush(stderr); 2286 if (MasterPtyFd >= 0) { 2287 int slavefd; 2288 2289 /* 2290 * NOTE: We can't open the slave in the child because the 2291 * master may race a disconnection test. If we open 2292 * it in the parent our close() will flush any pending 2293 * output not read by the master (which is the same 2294 * parent process) and deadlock. 2295 * 2296 * Solve this by hand-shaking the slave tty to give 2297 * the master time to close its slavefd (after this 2298 * section). 2299 * 2300 * Leave the tty defaults intact, which also likely 2301 * means it will be in line-buffered mode, so handshake 2302 * with a full line. 2303 * 2304 * TODO: Our handshake probably echos back to the master pty 2305 * due to tty echo, and ends up in the log, so just 2306 * pass through a newline. 2307 */ 2308 slavefd = open(ptsname(MasterPtyFd), O_RDWR); 2309 dassert_errno(slavefd >= 0, "Cannot open slave pty"); 2310 2311 /* 2312 * Now do the fork. 2313 */ 2314 pid = fork(); 2315 if (pid == 0) { 2316 login_tty(slavefd); 2317 /* login_tty() closes slavefd */ 2318 } else { 2319 close(slavefd); 2320 } 2321 } else { 2322 /* 2323 * Initial MasterPtyFd for the slot, just use forkpty(). 2324 */ 2325 pid = forkpty(&MasterPtyFd, NULL, NULL, NULL); 2326 } 2327 2328 /* 2329 * The slave must make sure the master has time to close slavefd 2330 * in the re-use case before going its merry way. The master needs 2331 * to set terminal modes and the window as well. 2332 */ 2333 if (pid == 0) { 2334 /* 2335 * Slave nices itself and waits for handshake 2336 */ 2337 char ttybuf[2]; 2338 2339 /* 2340 * Self-nice to be nice (ignore any error) 2341 */ 2342 if (NiceOpt) 2343 setpriority(PRIO_PROCESS, 0, NiceOpt); 2344 2345 read(0, ttybuf, 1); 2346 } else { 2347 /* 2348 * We are going through a pty, so set the tty modes to 2349 * Set tty modes so we do not get ^M's in the log files. 2350 * 2351 * This isn't fatal if it doesn't work. Remember that 2352 * our output goes through the pty to the management 2353 * process which will log it. 2354 */ 2355 struct termios tio; 2356 struct winsize win; 2357 2358 if (tcgetattr(MasterPtyFd, &tio) == 0) { 2359 tio.c_oflag |= OPOST | ONOCR; 2360 tio.c_oflag &= ~(OCRNL | ONLCR); 2361 tio.c_iflag |= ICRNL; 2362 tio.c_iflag &= ~(INLCR | IGNCR); 2363 if (tcsetattr(MasterPtyFd, TCSANOW, &tio)) { 2364 printf("tcsetattr failed: %s\n", 2365 strerror(errno)); 2366 } 2367 2368 /* 2369 * Give the tty a non-zero columns field. 2370 * This fixes at least one port (textproc/po4a) 2371 */ 2372 if (ioctl(MasterPtyFd, TIOCGWINSZ, &win) == 0) { 2373 win.ws_col = 80; 2374 ioctl(MasterPtyFd, TIOCSWINSZ, &win); 2375 } else { 2376 printf("TIOCGWINSZ failed: %s\n", 2377 strerror(errno)); 2378 } 2379 2380 } else { 2381 printf("tcgetattr failed: %s\n", strerror(errno)); 2382 } 2383 2384 /* 2385 * Master issues handshake 2386 */ 2387 write(MasterPtyFd, "\n", 1); 2388 } 2389 2390 if (pid == 0) { 2391 /* 2392 * Additional phase-specific environment variables 2393 * 2394 * - Do not try to process missing depends outside of the 2395 * depends phases. Also relies on USE_PACKAGE_DEPENDS_ONLY 2396 * in the make.conf. 2397 */ 2398 switch(phaseid) { 2399 case PHASE_CHECK_SANITY: 2400 case PHASE_FETCH: 2401 case PHASE_CHECKSUM: 2402 case PHASE_EXTRACT: 2403 case PHASE_PATCH: 2404 case PHASE_CONFIGURE: 2405 case PHASE_STAGE: 2406 case PHASE_TEST: 2407 case PHASE_CHECK_PLIST: 2408 case PHASE_INSTALL: 2409 case PHASE_DEINSTALL: 2410 break; 2411 case PHASE_PKG_DEPENDS: 2412 case PHASE_FETCH_DEPENDS: 2413 case PHASE_EXTRACT_DEPENDS: 2414 case PHASE_PATCH_DEPENDS: 2415 case PHASE_BUILD_DEPENDS: 2416 case PHASE_LIB_DEPENDS: 2417 case PHASE_RUN_DEPENDS: 2418 break; 2419 default: 2420 setenv("NO_DEPENDS", "1", 1); 2421 break; 2422 } 2423 2424 /* 2425 * Clean-up, chdir, and chroot. 2426 */ 2427 closefrom(3); 2428 if (chdir(work->basedir) < 0) 2429 dfatal_errno("chdir in phase initialization"); 2430 if (chroot(work->basedir) < 0) 2431 dfatal_errno("chroot in phase initialization"); 2432 2433 /* 2434 * We have a choice here on how to handle stdin (fd 0). 2435 * We can leave it connected to the pty in which case 2436 * the build will just block if it tries to ask a 2437 * question (and the watchdog will kill it, eventually), 2438 * or we can try to EOF the pty, or we can attach /dev/null 2439 * to descriptor 0. 2440 */ 2441 if (NullStdinOpt) { 2442 int fd; 2443 2444 fd = open("/dev/null", O_RDWR); 2445 dassert_errno(fd >= 0, "cannot open /dev/null"); 2446 if (fd != 0) { 2447 dup2(fd, 0); 2448 close(fd); 2449 } 2450 } 2451 2452 /* 2453 * Execute the appropriate command. 2454 */ 2455 switch(phaseid) { 2456 case PHASE_INSTALL_PKGS: 2457 snprintf(buf, sizeof(buf), "/tmp/dsynth_install_pkgs"); 2458 execl(buf, buf, NULL); 2459 break; 2460 case PHASE_DUMP_ENV: 2461 snprintf(buf, sizeof(buf), "/usr/bin/env"); 2462 execl(buf, buf, NULL); 2463 break; 2464 case PHASE_DUMP_VAR: 2465 snprintf(buf, sizeof(buf), "/xports/%s", pkg->portdir); 2466 execl(MAKE_BINARY, MAKE_BINARY, "-C", buf, "-V", phase, 2467 NULL); 2468 break; 2469 case PHASE_DUMP_MAKECONF: 2470 snprintf(buf, sizeof(buf), "/bin/cat"); 2471 execl(buf, buf, "/etc/make.conf", NULL); 2472 break; 2473 case PHASE_SHOW_CONFIG: 2474 /* fall-through */ 2475 default: 2476 snprintf(buf, sizeof(buf), "/xports/%s", pkg->portdir); 2477 execl(MAKE_BINARY, MAKE_BINARY, "-C", buf, phase, NULL); 2478 break; 2479 } 2480 _exit(1); 2481 } 2482 fcntl(MasterPtyFd, F_SETFL, O_NONBLOCK); 2483 2484 if (pid < 0) { 2485 dlog(DLOG_ALL, "[%03d] %s Fork Failed: %s\n", 2486 work->index, pkg->logfile, strerror(errno)); 2487 ++work->accum_error; 2488 return; 2489 } 2490 2491 SigPid = pid; 2492 2493 fdlog = open(pkg->logfile, O_RDWR|O_CREAT|O_APPEND, 0644); 2494 if (fdlog < 0) { 2495 dlog(DLOG_ALL, "[%03d] %s Cannot open logfile '%s': %s\n", 2496 work->index, pkg->portdir, 2497 pkg->logfile, strerror(errno)); 2498 } 2499 2500 snprintf(buf, sizeof(buf), 2501 "----------------------------------------" 2502 "---------------------------------------\n" 2503 "-- Phase: %s\n" 2504 "----------------------------------------" 2505 "---------------------------------------\n", 2506 phase); 2507 write(fdlog, buf, strlen(buf)); 2508 2509 start_time = time(NULL); 2510 last_time = start_time; 2511 wdog_time = start_time; 2512 wpid_reaped = 0; 2513 2514 status = 0; 2515 for (;;) { 2516 ms = mptylogpoll(MasterPtyFd, fdlog, wmsg, &wdog_time); 2517 if (ms == MPTY_FAILED) { 2518 dlog(DLOG_ALL, 2519 "[%03d] %s lost pty in phase %s, terminating\n", 2520 work->index, pkg->portdir, phase); 2521 break; 2522 } 2523 if (ms == MPTY_EOF) 2524 break; 2525 2526 /* 2527 * Generally speaking update status once a second. 2528 * This also allows us to detect if the management 2529 * dsynth process has gone away. 2530 */ 2531 next_time = time(NULL); 2532 if (next_time != last_time) { 2533 double dload[3]; 2534 double dv; 2535 int wdog_scaled; 2536 2537 /* 2538 * Send status update to the worker management thread 2539 * in the master dsynth process. Remember, *WE* are 2540 * the worker management process sub-fork. 2541 */ 2542 if (ipcwritemsg(work->fds[0], wmsg) < 0) 2543 break; 2544 last_time = next_time; 2545 2546 /* 2547 * Watchdog scaling 2548 */ 2549 getloadavg(dload, 3); 2550 adjloadavg(dload); 2551 dv = dload[2] / NumCores; 2552 if (dv < (double)NumCores) { 2553 wdog_scaled = wdog; 2554 } else { 2555 if (dv > 4.0 * NumCores) 2556 dv = 4.0 * NumCores; 2557 wdog_scaled = wdog * dv / NumCores; 2558 } 2559 2560 /* 2561 * Watchdog 2562 */ 2563 if (next_time - wdog_time >= wdog_scaled * 60) { 2564 snprintf(buf, sizeof(buf), 2565 "\n--------\n" 2566 "WATCHDOG TIMEOUT FOR %s in %s " 2567 "after %d minutes\n" 2568 "Killing pid %d\n" 2569 "--------\n", 2570 pkg->portdir, phase, wdog_scaled, pid); 2571 if (fdlog >= 0) 2572 write(fdlog, buf, strlen(buf)); 2573 dlog(DLOG_ALL, 2574 "[%03d] %s WATCHDOG TIMEOUT in %s " 2575 "after %d minutes (%d min scaled)\n", 2576 work->index, pkg->portdir, phase, 2577 wdog, wdog_scaled); 2578 kill(pid, SIGKILL); 2579 ++work->accum_error; 2580 break; 2581 } 2582 } 2583 2584 /* 2585 * Check process exit. Normally the pty will EOF 2586 * but if background processes remain we need to 2587 * check here to see if our primary exec is done, 2588 * so we can break out and reap those processes. 2589 * 2590 * Generally reap any other processes we have inherited 2591 * while we are here. 2592 */ 2593 do { 2594 wpid = wait3(&status, WNOHANG, NULL); 2595 } while (wpid > 0 && wpid != pid); 2596 if (wpid == pid && WIFEXITED(status)) { 2597 wpid_reaped = 1; 2598 break; 2599 } 2600 } 2601 2602 next_time = time(NULL); 2603 2604 setproctitle("[%02d] WORKER EXITREAP %s%s", 2605 work->index, pkg->portdir, WorkerFlavorPrt); 2606 2607 /* 2608 * We usually get here due to a mpty EOF, but not always as there 2609 * could be persistent processes still holding the slave. Finish 2610 * up getting the exit status for the main process we are waiting 2611 * on and clean out any data left on the MasterPtyFd (as it could 2612 * be blocking the exit). 2613 */ 2614 while (wpid_reaped == 0) { 2615 (void)mptylogpoll(MasterPtyFd, fdlog, wmsg, &wdog_time); 2616 wpid = waitpid(pid, &status, WNOHANG); 2617 if (wpid == pid && WIFEXITED(status)) { 2618 wpid_reaped = 1; 2619 break; 2620 } 2621 if (wpid < 0 && errno != EINTR) { 2622 break; 2623 } 2624 2625 /* 2626 * Safety. The normal phase waits until the fork/exec'd 2627 * pid finishes, causing a pty EOF on exit (the slave 2628 * descriptor is closed by the kernel on exit so the 2629 * process should already have exited). 2630 * 2631 * However, it is also possible to get here if the pty fails 2632 * for some reason. In this case, make sure that the process 2633 * is killed. 2634 */ 2635 kill(pid, SIGKILL); 2636 } 2637 2638 /* 2639 * Clean out anything left on the pty but don't wait around 2640 * because there could be background processes preventing the 2641 * slave side from closing. 2642 */ 2643 while (mptylogpoll(MasterPtyFd, fdlog, wmsg, &wdog_time) == MPTY_DATA) 2644 ; 2645 2646 /* 2647 * Report on the exit condition. If the pid was somehow lost 2648 * (probably due to someone gdb'ing the process), assume an error. 2649 */ 2650 if (wpid_reaped) { 2651 if (WEXITSTATUS(status)) { 2652 dlog(DLOG_ALL | DLOG_FILTER, 2653 "[%03d] %s Build phase '%s' failed exit %d\n", 2654 work->index, pkg->portdir, phase, 2655 WEXITSTATUS(status)); 2656 ++work->accum_error; 2657 } 2658 } else { 2659 dlog(DLOG_ALL, "[%03d] %s Build phase '%s' failed - lost pid\n", 2660 work->index, pkg->portdir, phase); 2661 ++work->accum_error; 2662 } 2663 2664 /* 2665 * Kill any processes still running (sometimes processes end up in 2666 * the background during a dports build), and clean up any other 2667 * children that we have inherited. 2668 */ 2669 phaseReapAll(); 2670 2671 /* 2672 * After the extraction phase add the space used by /construction 2673 * to the memory use. This helps us reduce the amount of paging 2674 * we do due to extremely large package extractions (languages, 2675 * chromium, etc). 2676 * 2677 * (dsynth already estimated the space used by the package deps 2678 * up front, but this will help us further). 2679 */ 2680 if (work->accum_error == 0 && phaseid == PHASE_EXTRACT) { 2681 struct statfs sfs; 2682 char *b1; 2683 2684 asprintf(&b1, "%s/construction", work->basedir); 2685 if (statfs(b1, &sfs) == 0) { 2686 wmsg->memuse = (sfs.f_blocks - sfs.f_bfree) * 2687 sfs.f_bsize; 2688 ipcwritemsg(work->fds[0], wmsg); 2689 } 2690 } 2691 2692 /* 2693 * Update log 2694 */ 2695 if (fdlog >= 0) { 2696 struct stat st; 2697 int h; 2698 int m; 2699 int s; 2700 2701 last_time = next_time - start_time; 2702 s = last_time % 60; 2703 m = last_time / 60 % 60; 2704 h = last_time / 3600; 2705 2706 fp = fdopen(fdlog, "a"); 2707 if (fp == NULL) { 2708 dlog(DLOG_ALL, "[%03d] %s Cannot fdopen fdlog: %s %d\n", 2709 work->index, pkg->portdir, 2710 strerror(errno), fstat(fdlog, &st)); 2711 close(fdlog); 2712 goto skip; 2713 } 2714 2715 fprintf(fp, "\n"); 2716 if (work->accum_error) { 2717 fprintf(fp, "FAILED %02d:%02d:%02d\n", h, m, s); 2718 } else { 2719 if (phaseid == PHASE_EXTRACT && wmsg->memuse) { 2720 fprintf(fp, "Extracted Memory Use: %6.2fM\n", 2721 wmsg->memuse / (1024.0 * 1024.0)); 2722 } 2723 fprintf(fp, "SUCCEEDED %02d:%02d:%02d\n", h, m, s); 2724 } 2725 last_time = next_time - work->start_time; 2726 s = last_time % 60; 2727 m = last_time / 60 % 60; 2728 h = last_time / 3600; 2729 if (phaseid == PHASE_PACKAGE) { 2730 fprintf(fp, "TOTAL TIME %02d:%02d:%02d\n", h, m, s); 2731 } 2732 fprintf(fp, "\n"); 2733 fclose(fp); 2734 skip: 2735 ; 2736 } 2737 2738 } 2739 2740 static void 2741 phaseReapAll(void) 2742 { 2743 struct reaper_status rs; 2744 int status; 2745 2746 while (procctl(P_PID, getpid(), PROC_REAP_STATUS, &rs) == 0) { 2747 if ((rs.flags & PROC_REAP_ACQUIRE) == 0) 2748 break; 2749 if (rs.pid_head < 0) 2750 break; 2751 if (kill(rs.pid_head, SIGKILL) == 0) { 2752 while (waitpid(rs.pid_head, &status, 0) < 0) 2753 ; 2754 } 2755 } 2756 while (wait3(&status, 0, NULL) > 0) 2757 ; 2758 } 2759 2760 static void 2761 phaseTerminateSignal(int sig __unused) 2762 { 2763 if (CopyFileFd >= 0) 2764 close(CopyFileFd); 2765 if (MasterPtyFd >= 0) 2766 close(MasterPtyFd); 2767 if (SigPid > 1) 2768 kill(SigPid, SIGKILL); 2769 phaseReapAll(); 2770 if (SigWork) 2771 DoWorkerUnmounts(SigWork); 2772 exit(1); 2773 } 2774 2775 static 2776 char * 2777 buildskipreason(pkglink_t *parent, pkg_t *pkg) 2778 { 2779 pkglink_t *link; 2780 pkg_t *scan; 2781 char *reason = NULL; 2782 char *ptr; 2783 size_t tot; 2784 size_t len; 2785 pkglink_t stack; 2786 2787 if ((pkg->flags & PKGF_NOBUILD_I) && pkg->ignore) 2788 asprintf(&reason, "%s ", pkg->ignore); 2789 2790 tot = 0; 2791 PKGLIST_FOREACH(link, &pkg->idepon_list) { 2792 #if 0 2793 if (link->dep_type > DEP_TYPE_BUILD) 2794 continue; 2795 #endif 2796 scan = link->pkg; 2797 if (scan == NULL) 2798 continue; 2799 if ((scan->flags & (PKGF_ERROR | PKGF_NOBUILD)) == 0) 2800 continue; 2801 if (scan->flags & PKGF_NOBUILD) { 2802 stack.pkg = scan; 2803 stack.next = parent; 2804 ptr = buildskipreason(&stack, scan); 2805 len = strlen(scan->portdir) + strlen(ptr) + 8; 2806 reason = realloc(reason, tot + len); 2807 snprintf(reason + tot, len, "%s->%s", 2808 scan->portdir, ptr); 2809 free(ptr); 2810 } else { 2811 len = strlen(scan->portdir) + 8; 2812 reason = realloc(reason, tot + len); 2813 snprintf(reason + tot, len, "%s", scan->portdir); 2814 } 2815 2816 /* 2817 * Don't try to print the entire graph 2818 */ 2819 if (parent) 2820 break; 2821 tot += strlen(reason + tot); 2822 reason[tot++] = ' '; 2823 reason[tot] = 0; 2824 } 2825 return (reason); 2826 } 2827 2828 /* 2829 * Count number of packages that would be skipped due to the 2830 * specified package having failed. 2831 * 2832 * Call with mode 1 to count, and mode 0 to clear the 2833 * cumulative rscan flag (used to de-duplicate the count). 2834 * 2835 * Must be serialized. 2836 */ 2837 static int 2838 buildskipcount_dueto(pkg_t *pkg, int mode) 2839 { 2840 pkglink_t *link; 2841 pkg_t *scan; 2842 int total; 2843 2844 total = 0; 2845 PKGLIST_FOREACH(link, &pkg->deponi_list) { 2846 scan = link->pkg; 2847 if (scan == NULL || scan->rscan == mode) 2848 continue; 2849 scan->rscan = mode; 2850 ++total; 2851 total += buildskipcount_dueto(scan, mode); 2852 } 2853 return total; 2854 } 2855 2856 /* 2857 * The master ptyfd is in non-blocking mode. Drain up to 1024 bytes 2858 * and update wmsg->lines and *wdog_timep as appropriate. 2859 * 2860 * This function will poll, stalling up to 1 second. 2861 */ 2862 static int 2863 mptylogpoll(int ptyfd, int fdlog, wmsg_t *wmsg, time_t *wdog_timep) 2864 { 2865 struct pollfd pfd; 2866 char buf[1024]; 2867 ssize_t r; 2868 2869 pfd.fd = ptyfd; 2870 pfd.events = POLLIN; 2871 pfd.revents = 0; 2872 2873 poll(&pfd, 1, 1000); 2874 if (pfd.revents) { 2875 r = read(ptyfd, buf, sizeof(buf)); 2876 if (r > 0) { 2877 *wdog_timep = time(NULL); 2878 if (r > 0 && fdlog >= 0) 2879 write(fdlog, buf, r); 2880 while (--r >= 0) { 2881 if (buf[r] == '\n') 2882 ++wmsg->lines; 2883 } 2884 return MPTY_DATA; 2885 } else if (r < 0) { 2886 if (errno != EINTR && errno != EAGAIN) 2887 return MPTY_FAILED; 2888 return MPTY_AGAIN; 2889 } else if (r == 0) { 2890 return MPTY_EOF; 2891 } 2892 } 2893 return MPTY_AGAIN; 2894 } 2895 2896 /* 2897 * Copy a (package) file from (src) to (dst), use an intermediate file and 2898 * rename to ensure that interruption does not leave us with a corrupt 2899 * package file. 2900 * 2901 * This is called by the WORKER process. 2902 * 2903 * (dsynth management thread -> WORKER process -> sub-processes) 2904 */ 2905 #define COPYBLKSIZE 32768 2906 2907 int 2908 copyfile(char *src, char *dst) 2909 { 2910 char *tmp; 2911 char *buf; 2912 int fd1; 2913 int fd2; 2914 int error = 0; 2915 int mask; 2916 ssize_t r; 2917 2918 asprintf(&tmp, "%s.new", dst); 2919 buf = malloc(COPYBLKSIZE); 2920 2921 mask = sigsetmask(sigmask(SIGTERM)|sigmask(SIGINT)|sigmask(SIGHUP)); 2922 fd1 = open(src, O_RDONLY|O_CLOEXEC); 2923 fd2 = open(tmp, O_RDWR|O_CREAT|O_TRUNC|O_CLOEXEC, 0644); 2924 CopyFileFd = fd1; 2925 sigsetmask(mask); 2926 while ((r = read(fd1, buf, COPYBLKSIZE)) > 0) { 2927 if (write(fd2, buf, r) != r) 2928 error = 1; 2929 } 2930 if (r < 0) 2931 error = 1; 2932 mask = sigsetmask(sigmask(SIGTERM)|sigmask(SIGINT)|sigmask(SIGHUP)); 2933 CopyFileFd = -1; 2934 close(fd1); 2935 close(fd2); 2936 sigsetmask(mask); 2937 if (error) { 2938 remove(tmp); 2939 } else { 2940 if (rename(tmp, dst)) { 2941 error = 1; 2942 remove(tmp); 2943 } 2944 } 2945 2946 freestrp(&buf); 2947 freestrp(&tmp); 2948 2949 return error; 2950 } 2951 2952 /* 2953 * doHook() 2954 * 2955 * primary process (threaded) - run_start, run_end, pkg_ignored, pkg_skipped 2956 * worker process (threaded) - pkg_sucess, pkg_failure 2957 * 2958 * If waitfor is non-zero this hook will be serialized. 2959 */ 2960 static void 2961 doHook(pkg_t *pkg, const char *id, const char *path, int waitfor) 2962 { 2963 if (path == NULL) 2964 return; 2965 while (waitfor && getbulk() != NULL) 2966 ; 2967 if (pkg) 2968 queuebulk(pkg->portdir, id, path, pkg->pkgfile); 2969 else 2970 queuebulk(NULL, id, path, NULL); 2971 while (waitfor && getbulk() != NULL) 2972 ; 2973 } 2974 2975 /* 2976 * Execute hook (backend) 2977 * 2978 * s1 - portdir 2979 * s2 - id 2980 * s3 - script path 2981 * s4 - pkgfile (if applicable) 2982 */ 2983 static void 2984 childHookRun(bulk_t *bulk) 2985 { 2986 const char *cav[MAXCAC]; 2987 buildenv_t benv[MAXCAC]; 2988 char buf1[128]; 2989 char buf2[128]; 2990 char buf3[128]; 2991 char buf4[128]; 2992 FILE *fp; 2993 char *ptr; 2994 size_t len; 2995 pid_t pid; 2996 int cac; 2997 int bi; 2998 2999 cac = 0; 3000 bi = 0; 3001 bzero(benv, sizeof(benv)); 3002 3003 cav[cac++] = bulk->s3; 3004 3005 benv[bi].label = "PROFILE"; 3006 benv[bi].data = Profile; 3007 ++bi; 3008 3009 benv[bi].label = "DIR_PACKAGES"; 3010 benv[bi].data = PackagesPath; 3011 ++bi; 3012 3013 benv[bi].label = "DIR_REPOSITORY"; 3014 benv[bi].data = RepositoryPath; 3015 ++bi; 3016 3017 benv[bi].label = "DIR_PORTS"; 3018 benv[bi].data = DPortsPath; 3019 ++bi; 3020 3021 benv[bi].label = "DIR_OPTIONS"; 3022 benv[bi].data = OptionsPath; 3023 ++bi; 3024 3025 benv[bi].label = "DIR_DISTFILES"; 3026 benv[bi].data = DistFilesPath; 3027 ++bi; 3028 3029 benv[bi].label = "DIR_LOGS"; 3030 benv[bi].data = LogsPath; 3031 ++bi; 3032 3033 benv[bi].label = "DIR_BUILDBASE"; 3034 benv[bi].data = BuildBase; 3035 ++bi; 3036 3037 if (strcmp(bulk->s2, "hook_run_start") == 0) { 3038 snprintf(buf1, sizeof(buf1), "%d", BuildTotal); 3039 benv[bi].label = "PORTS_QUEUED"; 3040 benv[bi].data = buf1; 3041 ++bi; 3042 } else if (strcmp(bulk->s2, "hook_run_end") == 0) { 3043 snprintf(buf1, sizeof(buf1), "%d", BuildSuccessCount); 3044 benv[bi].label = "PORTS_BUILT"; 3045 benv[bi].data = buf1; 3046 ++bi; 3047 snprintf(buf2, sizeof(buf2), "%d", BuildFailCount); 3048 benv[bi].label = "PORTS_FAILED"; 3049 benv[bi].data = buf2; 3050 ++bi; 3051 snprintf(buf3, sizeof(buf3), "%d", BuildIgnoreCount); 3052 benv[bi].label = "PORTS_IGNORED"; 3053 benv[bi].data = buf3; 3054 ++bi; 3055 snprintf(buf4, sizeof(buf4), "%d", BuildSkipCount); 3056 benv[bi].label = "PORTS_SKIPPED"; 3057 benv[bi].data = buf4; 3058 ++bi; 3059 } else { 3060 /* 3061 * success, failure, ignored, skipped 3062 */ 3063 benv[bi].label = "RESULT"; 3064 if (strcmp(bulk->s2, "hook_pkg_success") == 0) { 3065 benv[bi].data = "success"; 3066 } else if (strcmp(bulk->s2, "hook_pkg_failure") == 0) { 3067 benv[bi].data = "failure"; 3068 } else if (strcmp(bulk->s2, "hook_pkg_ignored") == 0) { 3069 benv[bi].data = "ignored"; 3070 } else if (strcmp(bulk->s2, "hook_pkg_skipped") == 0) { 3071 benv[bi].data = "skipped"; 3072 } else { 3073 dfatal("Unknown hook id: %s", bulk->s2); 3074 /* NOT REACHED */ 3075 } 3076 ++bi; 3077 3078 /* 3079 * For compatibility with synth: 3080 * 3081 * ORIGIN does not include any @flavor, thus it is suitable 3082 * for finding the actual port directory/subdirectory. 3083 * 3084 * FLAVOR is set to ORIGIN if there is no flavor, otherwise 3085 * it is set to only the flavor sans the '@'. 3086 */ 3087 if ((ptr = strchr(bulk->s1, '@')) != NULL) { 3088 snprintf(buf1, sizeof(buf1), "%*.*s", 3089 (int)(ptr - bulk->s1), 3090 (int)(ptr - bulk->s1), 3091 bulk->s1); 3092 benv[bi].label = "ORIGIN"; 3093 benv[bi].data = buf1; 3094 ++bi; 3095 benv[bi].label = "FLAVOR"; 3096 benv[bi].data = ptr + 1; 3097 ++bi; 3098 } else { 3099 benv[bi].label = "ORIGIN"; 3100 benv[bi].data = bulk->s1; 3101 ++bi; 3102 benv[bi].label = "FLAVOR"; 3103 benv[bi].data = bulk->s1; 3104 ++bi; 3105 } 3106 benv[bi].label = "PKGNAME"; 3107 benv[bi].data = bulk->s4; 3108 ++bi; 3109 } 3110 3111 benv[bi].label = NULL; 3112 benv[bi].data = NULL; 3113 3114 fp = dexec_open(bulk->s1, cav, cac, &pid, benv, 0, 0); 3115 while ((ptr = fgetln(fp, &len)) != NULL) 3116 ; 3117 3118 if (dexec_close(fp, pid)) { 3119 dlog(DLOG_ALL, 3120 "[XXX] %s SCRIPT %s (%s)\n", 3121 bulk->s1, bulk->s2, bulk->s3); 3122 } 3123 } 3124 3125 /* 3126 * Adjusts dload[0] by adding in t_pw (processes waiting on page-fault). 3127 * We don't want load reductions due to e.g. thrashing to cause dsynth 3128 * to increase the dynamic limit because it thinks the load is low. 3129 * 3130 * This has a desirable property. If the system pager cannot keep up 3131 * with process demand t_pw will spike while loadavg will only drop 3132 * slowly, resulting in a high adjusted load calculation that causes 3133 * dsynth to quickly clamp-down the limit. If the condition alleviates, 3134 * the limit will then rise slowly again, possibly even before existing 3135 * jobs are retired to meet the clamp-down from the original spike. 3136 */ 3137 static void 3138 adjloadavg(double *dload) 3139 { 3140 #if defined(__DragonFly__) 3141 struct vmtotal total; 3142 size_t size; 3143 3144 size = sizeof(total); 3145 if (sysctlbyname("vm.vmtotal", &total, &size, NULL, 0) == 0) { 3146 dload[0] += (double)total.t_pw; 3147 } 3148 #else 3149 dload[0] += 0.0; /* just avoid compiler 'unused' warnings */ 3150 #endif 3151 } 3152 3153 /* 3154 * Check if the ports directory contents has changed and force a 3155 * package to be rebuilt if it has by clearing the PACKAGED bit. 3156 */ 3157 static 3158 void 3159 check_packaged(const char *dbmpath, pkg_t *pkgs) 3160 { 3161 pkg_t *scan; 3162 datum key; 3163 datum data; 3164 char *buf; 3165 3166 if (CheckDBM == NULL) { 3167 dlog(DLOG_ABN, "[XXX] Unable to open/create dbm %s\n", dbmpath); 3168 return; 3169 } 3170 for (scan = pkgs; scan; scan = scan->bnext) { 3171 if ((scan->flags & PKGF_PACKAGED) == 0) 3172 continue; 3173 key.dptr = scan->portdir; 3174 key.dsize = strlen(scan->portdir); 3175 data = dbm_fetch(CheckDBM, key); 3176 if (data.dptr && data.dsize == sizeof(uint32_t) && 3177 *(uint32_t *)data.dptr != scan->crc32) { 3178 scan->flags &= ~PKGF_PACKAGED; 3179 asprintf(&buf, "%s/%s", RepositoryPath, scan->pkgfile); 3180 if (OverridePkgDeleteOpt >= 2) { 3181 scan->flags |= PKGF_PACKAGED; 3182 dlog(DLOG_ALL, 3183 "[XXX] %s DELETE-PACKAGE %s " 3184 "(port content changed CRC %08x/%08x " 3185 "OVERRIDE, NOT DELETED)\n", 3186 scan->portdir, buf, 3187 *(uint32_t *)data.dptr, scan->crc32); 3188 } else if (remove(buf) < 0) { 3189 dlog(DLOG_ALL, 3190 "[XXX] %s DELETE-PACKAGE %s (failed)\n", 3191 scan->portdir, buf); 3192 } else { 3193 dlog(DLOG_ALL, 3194 "[XXX] %s DELETE-PACKAGE %s " 3195 "(port content changed CRC %08x/%08x)\n", 3196 scan->portdir, buf, 3197 *(uint32_t *)data.dptr, scan->crc32); 3198 } 3199 freestrp(&buf); 3200 } else if (data.dptr == NULL) { 3201 data.dptr = &scan->crc32; 3202 data.dsize = sizeof(scan->crc32); 3203 dbm_store(CheckDBM, key, data, DBM_REPLACE); 3204 } 3205 } 3206 } 3207