build.cc 118 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650
  1. #include "config.h"
  2. #include "references.hh"
  3. #include "pathlocks.hh"
  4. #include "misc.hh"
  5. #include "globals.hh"
  6. #include "local-store.hh"
  7. #include "util.hh"
  8. #include "archive.hh"
  9. #include "affinity.hh"
  10. #include "builtins.hh"
  11. #include <map>
  12. #include <sstream>
  13. #include <algorithm>
  14. #include <limits.h>
  15. #include <time.h>
  16. #include <sys/time.h>
  17. #include <sys/wait.h>
  18. #include <sys/types.h>
  19. #include <sys/stat.h>
  20. #include <sys/utsname.h>
  21. #include <fcntl.h>
  22. #include <unistd.h>
  23. #include <errno.h>
  24. #include <stdio.h>
  25. #include <cstring>
  26. #include <stdint.h>
  27. #include <pwd.h>
  28. #include <grp.h>
  29. #include <zlib.h>
  30. #if HAVE_BZLIB_H
  31. # include <bzlib.h>
  32. #endif
  33. /* Includes required for chroot support. */
  34. #if HAVE_SYS_PARAM_H
  35. #include <sys/param.h>
  36. #endif
  37. #if HAVE_SYS_MOUNT_H
  38. #include <sys/mount.h>
  39. #endif
  40. #if HAVE_SYS_SYSCALL_H
  41. #include <sys/syscall.h>
  42. #endif
  43. #if HAVE_SCHED_H
  44. #include <sched.h>
  45. #endif
  46. /* In GNU libc 2.11, <sys/mount.h> does not define `MS_PRIVATE', but
  47. <linux/fs.h> does. */
  48. #if !defined MS_PRIVATE && defined HAVE_LINUX_FS_H
  49. #include <linux/fs.h>
  50. #endif
  51. #define CHROOT_ENABLED HAVE_CHROOT && HAVE_SYS_MOUNT_H && defined(MS_BIND) && defined(MS_PRIVATE) && defined(CLONE_NEWNS) && defined(SYS_pivot_root)
  52. #if CHROOT_ENABLED
  53. #include <sys/socket.h>
  54. #include <sys/ioctl.h>
  55. #include <net/if.h>
  56. #include <netinet/ip.h>
  57. #endif
  58. #if __linux__
  59. #include <sys/personality.h>
  60. #endif
  61. #if HAVE_STATVFS
  62. #include <sys/statvfs.h>
  63. #endif
  64. namespace nix {
  65. using std::map;
  66. static string pathNullDevice = "/dev/null";
  67. /* Forward definition. */
  68. class Worker;
  69. struct HookInstance;
  70. /* A pointer to a goal. */
  71. class Goal;
  72. class DerivationGoal;
  73. typedef std::shared_ptr<Goal> GoalPtr;
  74. typedef std::weak_ptr<Goal> WeakGoalPtr;
  75. struct CompareGoalPtrs {
  76. bool operator() (const GoalPtr & a, const GoalPtr & b);
  77. };
  78. /* Set of goals. */
  79. typedef set<GoalPtr, CompareGoalPtrs> Goals;
  80. typedef list<WeakGoalPtr> WeakGoals;
  81. /* A map of paths to goals (and the other way around). */
  82. typedef map<Path, WeakGoalPtr> WeakGoalMap;
  83. class Goal : public std::enable_shared_from_this<Goal>
  84. {
  85. public:
  86. typedef enum {ecBusy, ecSuccess, ecFailed, ecNoSubstituters, ecIncompleteClosure} ExitCode;
  87. protected:
  88. /* Backlink to the worker. */
  89. Worker & worker;
  90. /* Goals that this goal is waiting for. */
  91. Goals waitees;
  92. /* Goals waiting for this one to finish. Must use weak pointers
  93. here to prevent cycles. */
  94. WeakGoals waiters;
  95. /* Number of goals we are/were waiting for that have failed. */
  96. unsigned int nrFailed;
  97. /* Number of substitution goals we are/were waiting for that
  98. failed because there are no substituters. */
  99. unsigned int nrNoSubstituters;
  100. /* Number of substitution goals we are/were waiting for that
  101. failed because othey had unsubstitutable references. */
  102. unsigned int nrIncompleteClosure;
  103. /* Name of this goal for debugging purposes. */
  104. string name;
  105. /* Whether the goal is finished. */
  106. ExitCode exitCode;
  107. Goal(Worker & worker) : worker(worker)
  108. {
  109. nrFailed = nrNoSubstituters = nrIncompleteClosure = 0;
  110. exitCode = ecBusy;
  111. }
  112. virtual ~Goal()
  113. {
  114. trace("goal destroyed");
  115. }
  116. public:
  117. virtual void work() = 0;
  118. void addWaitee(GoalPtr waitee);
  119. virtual void waiteeDone(GoalPtr waitee, ExitCode result);
  120. virtual void handleChildOutput(int fd, const string & data)
  121. {
  122. abort();
  123. }
  124. virtual void handleEOF(int fd)
  125. {
  126. abort();
  127. }
  128. void trace(const format & f);
  129. string getName()
  130. {
  131. return name;
  132. }
  133. ExitCode getExitCode()
  134. {
  135. return exitCode;
  136. }
  137. /* Callback in case of a timeout. It should wake up its waiters,
  138. get rid of any running child processes that are being monitored
  139. by the worker (important!), etc. */
  140. virtual void timedOut() = 0;
  141. virtual string key() = 0;
  142. protected:
  143. void amDone(ExitCode result);
  144. };
  145. bool CompareGoalPtrs::operator() (const GoalPtr & a, const GoalPtr & b) {
  146. string s1 = a->key();
  147. string s2 = b->key();
  148. return s1 < s2;
  149. }
  150. /* A mapping used to remember for each child process to what goal it
  151. belongs, and file descriptors for receiving log data and output
  152. path creation commands. */
  153. struct Child
  154. {
  155. WeakGoalPtr goal;
  156. set<int> fds;
  157. bool respectTimeouts;
  158. bool inBuildSlot;
  159. time_t lastOutput; /* time we last got output on stdout/stderr */
  160. time_t timeStarted;
  161. };
  162. typedef map<pid_t, Child> Children;
  163. /* The worker class. */
  164. class Worker
  165. {
  166. private:
  167. /* Note: the worker should only have strong pointers to the
  168. top-level goals. */
  169. /* The top-level goals of the worker. */
  170. Goals topGoals;
  171. /* Goals that are ready to do some work. */
  172. WeakGoals awake;
  173. /* Goals waiting for a build slot. */
  174. WeakGoals wantingToBuild;
  175. /* Child processes currently running. */
  176. Children children;
  177. /* Number of build slots occupied. This includes local builds and
  178. substitutions but not remote builds via the build hook. */
  179. unsigned int nrLocalBuilds;
  180. /* Maps used to prevent multiple instantiations of a goal for the
  181. same derivation / path. */
  182. WeakGoalMap derivationGoals;
  183. WeakGoalMap substitutionGoals;
  184. /* Goals waiting for busy paths to be unlocked. */
  185. WeakGoals waitingForAnyGoal;
  186. /* Goals sleeping for a few seconds (polling a lock). */
  187. WeakGoals waitingForAWhile;
  188. /* Last time the goals in `waitingForAWhile' where woken up. */
  189. time_t lastWokenUp;
  190. public:
  191. /* Set if at least one derivation had a BuildError (i.e. permanent
  192. failure). */
  193. bool permanentFailure;
  194. /* Set if at least one derivation had a timeout. */
  195. bool timedOut;
  196. LocalStore & store;
  197. std::shared_ptr<HookInstance> hook;
  198. Worker(LocalStore & store);
  199. ~Worker();
  200. /* Make a goal (with caching). */
  201. GoalPtr makeDerivationGoal(const Path & drvPath, const StringSet & wantedOutputs, BuildMode buildMode = bmNormal);
  202. GoalPtr makeSubstitutionGoal(const Path & storePath, bool repair = false);
  203. /* Remove a dead goal. */
  204. void removeGoal(GoalPtr goal);
  205. /* Wake up a goal (i.e., there is something for it to do). */
  206. void wakeUp(GoalPtr goal);
  207. /* Return the number of local build and substitution processes
  208. currently running (but not remote builds via the build
  209. hook). */
  210. unsigned int getNrLocalBuilds();
  211. /* Registers a running child process. `inBuildSlot' means that
  212. the process counts towards the jobs limit. */
  213. void childStarted(GoalPtr goal, pid_t pid,
  214. const set<int> & fds, bool inBuildSlot, bool respectTimeouts);
  215. /* Unregisters a running child process. `wakeSleepers' should be
  216. false if there is no sense in waking up goals that are sleeping
  217. because they can't run yet (e.g., there is no free build slot,
  218. or the hook would still say `postpone'). */
  219. void childTerminated(pid_t pid, bool wakeSleepers = true);
  220. /* Put `goal' to sleep until a build slot becomes available (which
  221. might be right away). */
  222. void waitForBuildSlot(GoalPtr goal);
  223. /* Wait for any goal to finish. Pretty indiscriminate way to
  224. wait for some resource that some other goal is holding. */
  225. void waitForAnyGoal(GoalPtr goal);
  226. /* Wait for a few seconds and then retry this goal. Used when
  227. waiting for a lock held by another process. This kind of
  228. polling is inefficient, but POSIX doesn't really provide a way
  229. to wait for multiple locks in the main select() loop. */
  230. void waitForAWhile(GoalPtr goal);
  231. /* Loop until the specified top-level goals have finished. */
  232. void run(const Goals & topGoals);
  233. /* Wait for input to become available. */
  234. void waitForInput();
  235. unsigned int exitStatus();
  236. };
  237. //////////////////////////////////////////////////////////////////////
  238. void addToWeakGoals(WeakGoals & goals, GoalPtr p)
  239. {
  240. // FIXME: necessary?
  241. // FIXME: O(n)
  242. foreach (WeakGoals::iterator, i, goals)
  243. if (i->lock() == p) return;
  244. goals.push_back(p);
  245. }
  246. void Goal::addWaitee(GoalPtr waitee)
  247. {
  248. waitees.insert(waitee);
  249. addToWeakGoals(waitee->waiters, shared_from_this());
  250. }
  251. void Goal::waiteeDone(GoalPtr waitee, ExitCode result)
  252. {
  253. assert(waitees.find(waitee) != waitees.end());
  254. waitees.erase(waitee);
  255. trace(format("waitee `%1%' done; %2% left") %
  256. waitee->name % waitees.size());
  257. if (result == ecFailed || result == ecNoSubstituters || result == ecIncompleteClosure) ++nrFailed;
  258. if (result == ecNoSubstituters) ++nrNoSubstituters;
  259. if (result == ecIncompleteClosure) ++nrIncompleteClosure;
  260. if (waitees.empty() || (result == ecFailed && !settings.keepGoing)) {
  261. /* If we failed and keepGoing is not set, we remove all
  262. remaining waitees. */
  263. foreach (Goals::iterator, i, waitees) {
  264. GoalPtr goal = *i;
  265. WeakGoals waiters2;
  266. foreach (WeakGoals::iterator, j, goal->waiters)
  267. if (j->lock() != shared_from_this()) waiters2.push_back(*j);
  268. goal->waiters = waiters2;
  269. }
  270. waitees.clear();
  271. worker.wakeUp(shared_from_this());
  272. }
  273. }
  274. void Goal::amDone(ExitCode result)
  275. {
  276. trace("done");
  277. assert(exitCode == ecBusy);
  278. assert(result == ecSuccess || result == ecFailed || result == ecNoSubstituters || result == ecIncompleteClosure);
  279. exitCode = result;
  280. foreach (WeakGoals::iterator, i, waiters) {
  281. GoalPtr goal = i->lock();
  282. if (goal) goal->waiteeDone(shared_from_this(), result);
  283. }
  284. waiters.clear();
  285. worker.removeGoal(shared_from_this());
  286. }
  287. void Goal::trace(const format & f)
  288. {
  289. debug(format("%1%: %2%") % name % f);
  290. }
  291. //////////////////////////////////////////////////////////////////////
  292. /* Common initialisation performed in child processes. */
  293. static void commonChildInit(Pipe & logPipe)
  294. {
  295. /* Put the child in a separate session (and thus a separate
  296. process group) so that it has no controlling terminal (meaning
  297. that e.g. ssh cannot open /dev/tty) and it doesn't receive
  298. terminal signals. */
  299. if (setsid() == -1)
  300. throw SysError(format("creating a new session"));
  301. /* Dup the write side of the logger pipe into stderr. */
  302. if (dup2(logPipe.writeSide, STDERR_FILENO) == -1)
  303. throw SysError("cannot pipe standard error into log file");
  304. /* Dup stderr to stdout. */
  305. if (dup2(STDERR_FILENO, STDOUT_FILENO) == -1)
  306. throw SysError("cannot dup stderr into stdout");
  307. /* Reroute stdin to /dev/null. */
  308. int fdDevNull = open(pathNullDevice.c_str(), O_RDWR);
  309. if (fdDevNull == -1)
  310. throw SysError(format("cannot open `%1%'") % pathNullDevice);
  311. if (dup2(fdDevNull, STDIN_FILENO) == -1)
  312. throw SysError("cannot dup null device into stdin");
  313. close(fdDevNull);
  314. }
  315. /* Restore default handling of SIGPIPE, otherwise some programs will
  316. randomly say "Broken pipe". */
  317. static void restoreSIGPIPE()
  318. {
  319. struct sigaction act, oact;
  320. act.sa_handler = SIG_DFL;
  321. act.sa_flags = 0;
  322. sigemptyset(&act.sa_mask);
  323. if (sigaction(SIGPIPE, &act, &oact)) throw SysError("resetting SIGPIPE");
  324. }
  325. //////////////////////////////////////////////////////////////////////
  326. class UserLock
  327. {
  328. private:
  329. /* POSIX locks suck. If we have a lock on a file, and we open and
  330. close that file again (without closing the original file
  331. descriptor), we lose the lock. So we have to be *very* careful
  332. not to open a lock file on which we are holding a lock. */
  333. static PathSet lockedPaths; /* !!! not thread-safe */
  334. Path fnUserLock;
  335. AutoCloseFD fdUserLock;
  336. string user;
  337. uid_t uid;
  338. gid_t gid;
  339. std::vector<gid_t> supplementaryGIDs;
  340. public:
  341. UserLock();
  342. ~UserLock();
  343. void acquire();
  344. void release();
  345. void kill();
  346. string getUser() { return user; }
  347. uid_t getUID() { return uid; }
  348. uid_t getGID() { return gid; }
  349. std::vector<gid_t> getSupplementaryGIDs() { return supplementaryGIDs; }
  350. bool enabled() { return uid != 0; }
  351. };
  352. PathSet UserLock::lockedPaths;
  353. UserLock::UserLock()
  354. {
  355. uid = gid = 0;
  356. }
  357. UserLock::~UserLock()
  358. {
  359. release();
  360. }
  361. void UserLock::acquire()
  362. {
  363. assert(uid == 0);
  364. assert(settings.buildUsersGroup != "");
  365. /* Get the members of the build-users-group. */
  366. struct group * gr = getgrnam(settings.buildUsersGroup.c_str());
  367. if (!gr)
  368. throw Error(format("the group `%1%' specified in `build-users-group' does not exist")
  369. % settings.buildUsersGroup);
  370. gid = gr->gr_gid;
  371. /* Copy the result of getgrnam. */
  372. Strings users;
  373. for (char * * p = gr->gr_mem; *p; ++p) {
  374. debug(format("found build user `%1%'") % *p);
  375. users.push_back(*p);
  376. }
  377. if (users.empty())
  378. throw Error(format("the build users group `%1%' has no members")
  379. % settings.buildUsersGroup);
  380. /* Find a user account that isn't currently in use for another
  381. build. */
  382. foreach (Strings::iterator, i, users) {
  383. debug(format("trying user `%1%'") % *i);
  384. struct passwd * pw = getpwnam(i->c_str());
  385. if (!pw)
  386. throw Error(format("the user `%1%' in the group `%2%' does not exist")
  387. % *i % settings.buildUsersGroup);
  388. createDirs(settings.nixStateDir + "/userpool");
  389. fnUserLock = (format("%1%/userpool/%2%") % settings.nixStateDir % pw->pw_uid).str();
  390. if (lockedPaths.find(fnUserLock) != lockedPaths.end())
  391. /* We already have a lock on this one. */
  392. continue;
  393. AutoCloseFD fd = open(fnUserLock.c_str(), O_RDWR | O_CREAT, 0600);
  394. if (fd == -1)
  395. throw SysError(format("opening user lock `%1%'") % fnUserLock);
  396. closeOnExec(fd);
  397. if (lockFile(fd, ltWrite, false)) {
  398. fdUserLock = fd.borrow();
  399. lockedPaths.insert(fnUserLock);
  400. user = *i;
  401. uid = pw->pw_uid;
  402. /* Sanity check... */
  403. if (uid == getuid() || uid == geteuid())
  404. throw Error(format("the Nix user should not be a member of `%1%'")
  405. % settings.buildUsersGroup);
  406. /* Get the list of supplementary groups of this build user. This
  407. is usually either empty or contains a group such as "kvm". */
  408. supplementaryGIDs.resize(10);
  409. int ngroups = supplementaryGIDs.size();
  410. int err = getgrouplist(pw->pw_name, pw->pw_gid,
  411. supplementaryGIDs.data(), &ngroups);
  412. if (err == -1)
  413. throw Error(format("failed to get list of supplementary groups for ‘%1%’") % pw->pw_name);
  414. supplementaryGIDs.resize(ngroups);
  415. return;
  416. }
  417. }
  418. throw Error(format("all build users are currently in use; "
  419. "consider creating additional users and adding them to the `%1%' group")
  420. % settings.buildUsersGroup);
  421. }
  422. void UserLock::release()
  423. {
  424. if (uid == 0) return;
  425. fdUserLock.close(); /* releases lock */
  426. assert(lockedPaths.find(fnUserLock) != lockedPaths.end());
  427. lockedPaths.erase(fnUserLock);
  428. fnUserLock = "";
  429. uid = 0;
  430. }
  431. void UserLock::kill()
  432. {
  433. assert(enabled());
  434. killUser(uid);
  435. }
  436. //////////////////////////////////////////////////////////////////////
  437. struct HookInstance
  438. {
  439. /* Pipes for talking to the build hook. */
  440. Pipe toHook;
  441. /* Pipe for the hook's standard output/error. */
  442. Pipe fromHook;
  443. /* Pipe for the builder's standard output/error. */
  444. Pipe builderOut;
  445. /* The process ID of the hook. */
  446. Pid pid;
  447. HookInstance();
  448. ~HookInstance();
  449. };
  450. HookInstance::HookInstance()
  451. {
  452. debug("starting build hook");
  453. Path buildHook = getEnv("NIX_BUILD_HOOK");
  454. if (string(buildHook, 0, 1) != "/") buildHook = settings.nixLibexecDir + "/nix/" + buildHook;
  455. buildHook = canonPath(buildHook);
  456. /* Create a pipe to get the output of the child. */
  457. fromHook.create();
  458. /* Create the communication pipes. */
  459. toHook.create();
  460. /* Create a pipe to get the output of the builder. */
  461. builderOut.create();
  462. /* Fork the hook. */
  463. pid = startProcess([&]() {
  464. commonChildInit(fromHook);
  465. if (chdir("/") == -1) throw SysError("changing into `/");
  466. /* Dup the communication pipes. */
  467. if (dup2(toHook.readSide, STDIN_FILENO) == -1)
  468. throw SysError("dupping to-hook read side");
  469. /* Use fd 4 for the builder's stdout/stderr. */
  470. if (dup2(builderOut.writeSide, 4) == -1)
  471. throw SysError("dupping builder's stdout/stderr");
  472. execl(buildHook.c_str(), buildHook.c_str(), settings.thisSystem.c_str(),
  473. (format("%1%") % settings.maxSilentTime).str().c_str(),
  474. (format("%1%") % settings.printBuildTrace).str().c_str(),
  475. (format("%1%") % settings.buildTimeout).str().c_str(),
  476. NULL);
  477. throw SysError(format("executing `%1%'") % buildHook);
  478. });
  479. pid.setSeparatePG(true);
  480. fromHook.writeSide.close();
  481. toHook.readSide.close();
  482. }
  483. HookInstance::~HookInstance()
  484. {
  485. try {
  486. toHook.writeSide.close();
  487. pid.kill(true);
  488. } catch (...) {
  489. ignoreException();
  490. }
  491. }
  492. //////////////////////////////////////////////////////////////////////
  493. typedef map<string, string> HashRewrites;
  494. string rewriteHashes(string s, const HashRewrites & rewrites)
  495. {
  496. foreach (HashRewrites::const_iterator, i, rewrites) {
  497. assert(i->first.size() == i->second.size());
  498. size_t j = 0;
  499. while ((j = s.find(i->first, j)) != string::npos) {
  500. debug(format("rewriting @ %1%") % j);
  501. s.replace(j, i->second.size(), i->second);
  502. }
  503. }
  504. return s;
  505. }
  506. //////////////////////////////////////////////////////////////////////
  507. typedef enum {rpAccept, rpDecline, rpPostpone} HookReply;
  508. class SubstitutionGoal;
  509. class DerivationGoal : public Goal
  510. {
  511. private:
  512. /* The path of the derivation. */
  513. Path drvPath;
  514. /* The specific outputs that we need to build. Empty means all of
  515. them. */
  516. StringSet wantedOutputs;
  517. /* Whether additional wanted outputs have been added. */
  518. bool needRestart;
  519. /* Whether to retry substituting the outputs after building the
  520. inputs. */
  521. bool retrySubstitution;
  522. /* The derivation stored at drvPath. */
  523. Derivation drv;
  524. /* The remainder is state held during the build. */
  525. /* Locks on the output paths. */
  526. PathLocks outputLocks;
  527. /* All input paths (that is, the union of FS closures of the
  528. immediate input paths). */
  529. PathSet inputPaths;
  530. /* Referenceable paths (i.e., input and output paths). */
  531. PathSet allPaths;
  532. /* Outputs that are already valid. If we're repairing, these are
  533. the outputs that are valid *and* not corrupt. */
  534. PathSet validPaths;
  535. /* Outputs that are corrupt or not valid. */
  536. PathSet missingPaths;
  537. /* User selected for running the builder. */
  538. UserLock buildUser;
  539. /* The process ID of the builder. */
  540. Pid pid;
  541. /* The temporary directory. */
  542. Path tmpDir;
  543. /* The path of the temporary directory in the sandbox. */
  544. Path tmpDirInSandbox;
  545. /* File descriptor for the log file. */
  546. FILE * fLogFile;
  547. gzFile gzLogFile;
  548. #if HAVE_BZLIB_H
  549. BZFILE * bzLogFile;
  550. #endif
  551. AutoCloseFD fdLogFile;
  552. /* Number of bytes received from the builder's stdout/stderr. */
  553. unsigned long logSize;
  554. /* Pipe for the builder's standard output/error. */
  555. Pipe builderOut;
  556. /* The build hook. */
  557. std::shared_ptr<HookInstance> hook;
  558. /* Whether we're currently doing a chroot build. */
  559. bool useChroot;
  560. Path chrootRootDir;
  561. /* RAII object to delete the chroot directory. */
  562. std::shared_ptr<AutoDelete> autoDelChroot;
  563. /* All inputs that are regular files. */
  564. PathSet regularInputPaths;
  565. /* Whether this is a fixed-output derivation. */
  566. bool fixedOutput;
  567. typedef void (DerivationGoal::*GoalState)();
  568. GoalState state;
  569. /* Stuff we need to pass to runChild(). */
  570. typedef map<Path, Path> DirsInChroot; // maps target path to source path
  571. DirsInChroot dirsInChroot;
  572. typedef map<string, string> Environment;
  573. Environment env;
  574. /* Hash rewriting. */
  575. HashRewrites rewritesToTmp, rewritesFromTmp;
  576. typedef map<Path, Path> RedirectedOutputs;
  577. RedirectedOutputs redirectedOutputs;
  578. BuildMode buildMode;
  579. /* If we're repairing without a chroot, there may be outputs that
  580. are valid but corrupt. So we redirect these outputs to
  581. temporary paths. */
  582. PathSet redirectedBadOutputs;
  583. /* The current round, if we're building multiple times. */
  584. unsigned int curRound = 1;
  585. unsigned int nrRounds;
  586. /* Path registration info from the previous round, if we're
  587. building multiple times. Since this contains the hash, it
  588. allows us to compare whether two rounds produced the same
  589. result. */
  590. ValidPathInfos prevInfos;
  591. BuildResult result;
  592. public:
  593. DerivationGoal(const Path & drvPath, const StringSet & wantedOutputs, Worker & worker, BuildMode buildMode = bmNormal);
  594. ~DerivationGoal();
  595. void timedOut() override;
  596. string key()
  597. {
  598. /* Ensure that derivations get built in order of their name,
  599. i.e. a derivation named "aardvark" always comes before
  600. "baboon". And substitution goals always happen before
  601. derivation goals (due to "b$"). */
  602. return "b$" + storePathToName(drvPath) + "$" + drvPath;
  603. }
  604. void work();
  605. Path getDrvPath()
  606. {
  607. return drvPath;
  608. }
  609. /* Add wanted outputs to an already existing derivation goal. */
  610. void addWantedOutputs(const StringSet & outputs);
  611. BuildResult getResult() { return result; }
  612. private:
  613. /* The states. */
  614. void init();
  615. void haveDerivation();
  616. void outputsSubstituted();
  617. void closureRepaired();
  618. void inputsRealised();
  619. void tryToBuild();
  620. void buildDone();
  621. /* Is the build hook willing to perform the build? */
  622. HookReply tryBuildHook();
  623. /* Start building a derivation. */
  624. void startBuilder();
  625. /* Run the builder's process. */
  626. void runChild();
  627. friend int childEntry(void *);
  628. /* Check that the derivation outputs all exist and register them
  629. as valid. */
  630. void registerOutputs();
  631. /* Open a log file and a pipe to it. */
  632. Path openLogFile();
  633. /* Close the log file. */
  634. void closeLogFile();
  635. /* Delete the temporary directory, if we have one. */
  636. void deleteTmpDir(bool force);
  637. /* Callback used by the worker to write to the log. */
  638. void handleChildOutput(int fd, const string & data);
  639. void handleEOF(int fd);
  640. /* Return the set of (in)valid paths. */
  641. PathSet checkPathValidity(bool returnValid, bool checkHash);
  642. /* Abort the goal if `path' failed to build. */
  643. bool pathFailed(const Path & path);
  644. /* Forcibly kill the child process, if any. */
  645. void killChild();
  646. Path addHashRewrite(const Path & path);
  647. void repairClosure();
  648. void done(BuildResult::Status status, const string & msg = "");
  649. };
  650. DerivationGoal::DerivationGoal(const Path & drvPath, const StringSet & wantedOutputs, Worker & worker, BuildMode buildMode)
  651. : Goal(worker)
  652. , wantedOutputs(wantedOutputs)
  653. , needRestart(false)
  654. , retrySubstitution(false)
  655. , fLogFile(0)
  656. , gzLogFile(0)
  657. #if HAVE_BZLIB_H
  658. , bzLogFile(0)
  659. #endif
  660. , useChroot(false)
  661. , buildMode(buildMode)
  662. {
  663. this->drvPath = drvPath;
  664. state = &DerivationGoal::init;
  665. name = (format("building of `%1%'") % drvPath).str();
  666. trace("created");
  667. /* Prevent the .chroot directory from being
  668. garbage-collected. (See isActiveTempFile() in gc.cc.) */
  669. worker.store.addTempRoot(drvPath);
  670. }
  671. DerivationGoal::~DerivationGoal()
  672. {
  673. /* Careful: we should never ever throw an exception from a
  674. destructor. */
  675. try { killChild(); } catch (...) { ignoreException(); }
  676. try { deleteTmpDir(false); } catch (...) { ignoreException(); }
  677. try { closeLogFile(); } catch (...) { ignoreException(); }
  678. }
  679. void DerivationGoal::killChild()
  680. {
  681. if (pid != -1) {
  682. worker.childTerminated(pid);
  683. if (buildUser.enabled()) {
  684. /* If we're using a build user, then there is a tricky
  685. race condition: if we kill the build user before the
  686. child has done its setuid() to the build user uid, then
  687. it won't be killed, and we'll potentially lock up in
  688. pid.wait(). So also send a conventional kill to the
  689. child. */
  690. ::kill(-pid, SIGKILL); /* ignore the result */
  691. buildUser.kill();
  692. pid.wait(true);
  693. } else
  694. pid.kill();
  695. assert(pid == -1);
  696. }
  697. hook.reset();
  698. }
  699. void DerivationGoal::timedOut()
  700. {
  701. if (settings.printBuildTrace)
  702. printMsg(lvlError, format("@ build-failed %1% - timeout") % drvPath);
  703. killChild();
  704. done(BuildResult::TimedOut);
  705. }
  706. void DerivationGoal::work()
  707. {
  708. (this->*state)();
  709. }
  710. void DerivationGoal::addWantedOutputs(const StringSet & outputs)
  711. {
  712. /* If we already want all outputs, there is nothing to do. */
  713. if (wantedOutputs.empty()) return;
  714. if (outputs.empty()) {
  715. wantedOutputs.clear();
  716. needRestart = true;
  717. } else
  718. foreach (StringSet::const_iterator, i, outputs)
  719. if (wantedOutputs.find(*i) == wantedOutputs.end()) {
  720. wantedOutputs.insert(*i);
  721. needRestart = true;
  722. }
  723. }
  724. void DerivationGoal::init()
  725. {
  726. trace("init");
  727. if (settings.readOnlyMode)
  728. throw Error(format("cannot build derivation `%1%' - no write access to the Nix store") % drvPath);
  729. /* The first thing to do is to make sure that the derivation
  730. exists. If it doesn't, it may be created through a
  731. substitute. */
  732. if (buildMode == bmNormal && worker.store.isValidPath(drvPath)) {
  733. haveDerivation();
  734. return;
  735. }
  736. addWaitee(worker.makeSubstitutionGoal(drvPath));
  737. state = &DerivationGoal::haveDerivation;
  738. }
  739. void DerivationGoal::haveDerivation()
  740. {
  741. trace("loading derivation");
  742. if (nrFailed != 0) {
  743. printMsg(lvlError, format("cannot build missing derivation ‘%1%’") % drvPath);
  744. done(BuildResult::MiscFailure);
  745. return;
  746. }
  747. /* `drvPath' should already be a root, but let's be on the safe
  748. side: if the user forgot to make it a root, we wouldn't want
  749. things being garbage collected while we're busy. */
  750. worker.store.addTempRoot(drvPath);
  751. assert(worker.store.isValidPath(drvPath));
  752. /* Get the derivation. */
  753. drv = derivationFromPath(worker.store, drvPath);
  754. foreach (DerivationOutputs::iterator, i, drv.outputs)
  755. worker.store.addTempRoot(i->second.path);
  756. /* Check what outputs paths are not already valid. */
  757. PathSet invalidOutputs = checkPathValidity(false, buildMode == bmRepair);
  758. /* If they are all valid, then we're done. */
  759. if (invalidOutputs.size() == 0 && buildMode == bmNormal) {
  760. done(BuildResult::AlreadyValid);
  761. return;
  762. }
  763. /* Check whether any output previously failed to build. If so,
  764. don't bother. */
  765. foreach (PathSet::iterator, i, invalidOutputs)
  766. if (pathFailed(*i)) return;
  767. /* We are first going to try to create the invalid output paths
  768. through substitutes. If that doesn't work, we'll build
  769. them. */
  770. if (settings.useSubstitutes && substitutesAllowed(drv))
  771. foreach (PathSet::iterator, i, invalidOutputs)
  772. addWaitee(worker.makeSubstitutionGoal(*i, buildMode == bmRepair));
  773. if (waitees.empty()) /* to prevent hang (no wake-up event) */
  774. outputsSubstituted();
  775. else
  776. state = &DerivationGoal::outputsSubstituted;
  777. }
  778. void DerivationGoal::outputsSubstituted()
  779. {
  780. trace("all outputs substituted (maybe)");
  781. if (nrFailed > 0 && nrFailed > nrNoSubstituters + nrIncompleteClosure && !settings.tryFallback)
  782. throw Error(format("some substitutes for the outputs of derivation `%1%' failed (usually happens due to networking issues); try `--fallback' to build derivation from source ") % drvPath);
  783. /* If the substitutes form an incomplete closure, then we should
  784. build the dependencies of this derivation, but after that, we
  785. can still use the substitutes for this derivation itself. */
  786. if (nrIncompleteClosure > 0 && !retrySubstitution) retrySubstitution = true;
  787. nrFailed = nrNoSubstituters = nrIncompleteClosure = 0;
  788. if (needRestart) {
  789. needRestart = false;
  790. haveDerivation();
  791. return;
  792. }
  793. unsigned int nrInvalid = checkPathValidity(false, buildMode == bmRepair).size();
  794. if (buildMode == bmNormal && nrInvalid == 0) {
  795. done(BuildResult::Substituted);
  796. return;
  797. }
  798. if (buildMode == bmRepair && nrInvalid == 0) {
  799. repairClosure();
  800. return;
  801. }
  802. if (buildMode == bmCheck && nrInvalid > 0)
  803. throw Error(format("some outputs of `%1%' are not valid, so checking is not possible") % drvPath);
  804. /* Otherwise, at least one of the output paths could not be
  805. produced using a substitute. So we have to build instead. */
  806. /* Make sure checkPathValidity() from now on checks all
  807. outputs. */
  808. wantedOutputs = PathSet();
  809. /* The inputs must be built before we can build this goal. */
  810. foreach (DerivationInputs::iterator, i, drv.inputDrvs)
  811. addWaitee(worker.makeDerivationGoal(i->first, i->second, buildMode == bmRepair ? bmRepair : bmNormal));
  812. foreach (PathSet::iterator, i, drv.inputSrcs)
  813. addWaitee(worker.makeSubstitutionGoal(*i));
  814. if (waitees.empty()) /* to prevent hang (no wake-up event) */
  815. inputsRealised();
  816. else
  817. state = &DerivationGoal::inputsRealised;
  818. }
  819. void DerivationGoal::repairClosure()
  820. {
  821. /* If we're repairing, we now know that our own outputs are valid.
  822. Now check whether the other paths in the outputs closure are
  823. good. If not, then start derivation goals for the derivations
  824. that produced those outputs. */
  825. /* Get the output closure. */
  826. PathSet outputClosure;
  827. foreach (DerivationOutputs::iterator, i, drv.outputs) {
  828. if (!wantOutput(i->first, wantedOutputs)) continue;
  829. computeFSClosure(worker.store, i->second.path, outputClosure);
  830. }
  831. /* Filter out our own outputs (which we have already checked). */
  832. foreach (DerivationOutputs::iterator, i, drv.outputs)
  833. outputClosure.erase(i->second.path);
  834. /* Get all dependencies of this derivation so that we know which
  835. derivation is responsible for which path in the output
  836. closure. */
  837. PathSet inputClosure;
  838. computeFSClosure(worker.store, drvPath, inputClosure);
  839. std::map<Path, Path> outputsToDrv;
  840. foreach (PathSet::iterator, i, inputClosure)
  841. if (isDerivation(*i)) {
  842. Derivation drv = derivationFromPath(worker.store, *i);
  843. foreach (DerivationOutputs::iterator, j, drv.outputs)
  844. outputsToDrv[j->second.path] = *i;
  845. }
  846. /* Check each path (slow!). */
  847. PathSet broken;
  848. foreach (PathSet::iterator, i, outputClosure) {
  849. if (worker.store.pathContentsGood(*i)) continue;
  850. printMsg(lvlError, format("found corrupted or missing path `%1%' in the output closure of `%2%'") % *i % drvPath);
  851. Path drvPath2 = outputsToDrv[*i];
  852. if (drvPath2 == "")
  853. addWaitee(worker.makeSubstitutionGoal(*i, true));
  854. else
  855. addWaitee(worker.makeDerivationGoal(drvPath2, PathSet(), bmRepair));
  856. }
  857. if (waitees.empty()) {
  858. done(BuildResult::AlreadyValid);
  859. return;
  860. }
  861. state = &DerivationGoal::closureRepaired;
  862. }
  863. void DerivationGoal::closureRepaired()
  864. {
  865. trace("closure repaired");
  866. if (nrFailed > 0)
  867. throw Error(format("some paths in the output closure of derivation ‘%1%’ could not be repaired") % drvPath);
  868. done(BuildResult::AlreadyValid);
  869. }
  870. void DerivationGoal::inputsRealised()
  871. {
  872. trace("all inputs realised");
  873. if (nrFailed != 0) {
  874. printMsg(lvlError,
  875. format("cannot build derivation `%1%': %2% dependencies couldn't be built")
  876. % drvPath % nrFailed);
  877. done(BuildResult::DependencyFailed);
  878. return;
  879. }
  880. if (retrySubstitution) {
  881. haveDerivation();
  882. return;
  883. }
  884. /* Gather information necessary for computing the closure and/or
  885. running the build hook. */
  886. /* The outputs are referenceable paths. */
  887. foreach (DerivationOutputs::iterator, i, drv.outputs) {
  888. debug(format("building path `%1%'") % i->second.path);
  889. allPaths.insert(i->second.path);
  890. }
  891. /* Determine the full set of input paths. */
  892. /* First, the input derivations. */
  893. foreach (DerivationInputs::iterator, i, drv.inputDrvs) {
  894. /* Add the relevant output closures of the input derivation
  895. `*i' as input paths. Only add the closures of output paths
  896. that are specified as inputs. */
  897. assert(worker.store.isValidPath(i->first));
  898. Derivation inDrv = derivationFromPath(worker.store, i->first);
  899. foreach (StringSet::iterator, j, i->second)
  900. if (inDrv.outputs.find(*j) != inDrv.outputs.end())
  901. computeFSClosure(worker.store, inDrv.outputs[*j].path, inputPaths);
  902. else
  903. throw Error(
  904. format("derivation `%1%' requires non-existent output `%2%' from input derivation `%3%'")
  905. % drvPath % *j % i->first);
  906. }
  907. /* Second, the input sources. */
  908. foreach (PathSet::iterator, i, drv.inputSrcs)
  909. computeFSClosure(worker.store, *i, inputPaths);
  910. debug(format("added input paths %1%") % showPaths(inputPaths));
  911. allPaths.insert(inputPaths.begin(), inputPaths.end());
  912. /* Is this a fixed-output derivation? */
  913. fixedOutput = true;
  914. for (auto & i : drv.outputs)
  915. if (i.second.hash == "") fixedOutput = false;
  916. /* Don't repeat fixed-output derivations since they're already
  917. verified by their output hash.*/
  918. nrRounds = fixedOutput ? 1 : settings.get("build-repeat", 0) + 1;
  919. /* Okay, try to build. Note that here we don't wait for a build
  920. slot to become available, since we don't need one if there is a
  921. build hook. */
  922. state = &DerivationGoal::tryToBuild;
  923. worker.wakeUp(shared_from_this());
  924. }
  925. static bool canBuildLocally(const string & platform)
  926. {
  927. return platform == settings.thisSystem
  928. #if __linux__
  929. || (platform == "i686-linux" && settings.thisSystem == "x86_64-linux")
  930. #endif
  931. ;
  932. }
  933. static string get(const StringPairs & map, const string & key, const string & def = "")
  934. {
  935. StringPairs::const_iterator i = map.find(key);
  936. return i == map.end() ? def : i->second;
  937. }
  938. bool willBuildLocally(const Derivation & drv)
  939. {
  940. return get(drv.env, "preferLocalBuild") == "1" && canBuildLocally(drv.platform);
  941. }
  942. bool substitutesAllowed(const Derivation & drv)
  943. {
  944. return get(drv.env, "allowSubstitutes", "1") == "1";
  945. }
  946. void DerivationGoal::tryToBuild()
  947. {
  948. trace("trying to build");
  949. /* Check for the possibility that some other goal in this process
  950. has locked the output since we checked in haveDerivation().
  951. (It can't happen between here and the lockPaths() call below
  952. because we're not allowing multi-threading.) If so, put this
  953. goal to sleep until another goal finishes, then try again. */
  954. foreach (DerivationOutputs::iterator, i, drv.outputs)
  955. if (pathIsLockedByMe(i->second.path)) {
  956. debug(format("putting derivation `%1%' to sleep because `%2%' is locked by another goal")
  957. % drvPath % i->second.path);
  958. worker.waitForAnyGoal(shared_from_this());
  959. return;
  960. }
  961. /* Obtain locks on all output paths. The locks are automatically
  962. released when we exit this function or Nix crashes. If we
  963. can't acquire the lock, then continue; hopefully some other
  964. goal can start a build, and if not, the main loop will sleep a
  965. few seconds and then retry this goal. */
  966. if (!outputLocks.lockPaths(outputPaths(drv), "", false)) {
  967. worker.waitForAWhile(shared_from_this());
  968. return;
  969. }
  970. /* Now check again whether the outputs are valid. This is because
  971. another process may have started building in parallel. After
  972. it has finished and released the locks, we can (and should)
  973. reuse its results. (Strictly speaking the first check can be
  974. omitted, but that would be less efficient.) Note that since we
  975. now hold the locks on the output paths, no other process can
  976. build this derivation, so no further checks are necessary. */
  977. validPaths = checkPathValidity(true, buildMode == bmRepair);
  978. if (buildMode != bmCheck && validPaths.size() == drv.outputs.size()) {
  979. debug(format("skipping build of derivation `%1%', someone beat us to it") % drvPath);
  980. outputLocks.setDeletion(true);
  981. done(BuildResult::AlreadyValid);
  982. return;
  983. }
  984. missingPaths = outputPaths(drv);
  985. if (buildMode != bmCheck)
  986. foreach (PathSet::iterator, i, validPaths) missingPaths.erase(*i);
  987. /* If any of the outputs already exist but are not valid, delete
  988. them. */
  989. foreach (DerivationOutputs::iterator, i, drv.outputs) {
  990. Path path = i->second.path;
  991. if (worker.store.isValidPath(path)) continue;
  992. if (!pathExists(path)) continue;
  993. debug(format("removing invalid path `%1%'") % path);
  994. deletePath(path);
  995. }
  996. /* Check again whether any output previously failed to build,
  997. because some other process may have tried and failed before we
  998. acquired the lock. */
  999. foreach (DerivationOutputs::iterator, i, drv.outputs)
  1000. if (pathFailed(i->second.path)) return;
  1001. /* Don't do a remote build if the derivation has the attribute
  1002. `preferLocalBuild' set. Also, check and repair modes are only
  1003. supported for local builds. */
  1004. bool buildLocally = buildMode != bmNormal || willBuildLocally(drv);
  1005. /* Is the build hook willing to accept this job? */
  1006. if (!buildLocally) {
  1007. switch (tryBuildHook()) {
  1008. case rpAccept:
  1009. /* Yes, it has started doing so. Wait until we get
  1010. EOF from the hook. */
  1011. state = &DerivationGoal::buildDone;
  1012. return;
  1013. case rpPostpone:
  1014. /* Not now; wait until at least one child finishes or
  1015. the wake-up timeout expires. */
  1016. worker.waitForAWhile(shared_from_this());
  1017. outputLocks.unlock();
  1018. return;
  1019. case rpDecline:
  1020. /* We should do it ourselves. */
  1021. break;
  1022. }
  1023. }
  1024. /* Make sure that we are allowed to start a build. If this
  1025. derivation prefers to be done locally, do it even if
  1026. maxBuildJobs is 0. */
  1027. unsigned int curBuilds = worker.getNrLocalBuilds();
  1028. if (curBuilds >= settings.maxBuildJobs && !(buildLocally && curBuilds == 0)) {
  1029. worker.waitForBuildSlot(shared_from_this());
  1030. outputLocks.unlock();
  1031. return;
  1032. }
  1033. try {
  1034. /* Okay, we have to build. */
  1035. startBuilder();
  1036. } catch (BuildError & e) {
  1037. printMsg(lvlError, e.msg());
  1038. outputLocks.unlock();
  1039. buildUser.release();
  1040. if (settings.printBuildTrace)
  1041. printMsg(lvlError, format("@ build-failed %1% - %2% %3%")
  1042. % drvPath % 0 % e.msg());
  1043. worker.permanentFailure = true;
  1044. done(BuildResult::InputRejected, e.msg());
  1045. return;
  1046. }
  1047. /* This state will be reached when we get EOF on the child's
  1048. log pipe. */
  1049. state = &DerivationGoal::buildDone;
  1050. }
  1051. void replaceValidPath(const Path & storePath, const Path tmpPath)
  1052. {
  1053. /* We can't atomically replace storePath (the original) with
  1054. tmpPath (the replacement), so we have to move it out of the
  1055. way first. We'd better not be interrupted here, because if
  1056. we're repairing (say) Glibc, we end up with a broken system. */
  1057. Path oldPath = (format("%1%.old-%2%-%3%") % storePath % getpid() % rand()).str();
  1058. if (pathExists(storePath))
  1059. rename(storePath.c_str(), oldPath.c_str());
  1060. if (rename(tmpPath.c_str(), storePath.c_str()) == -1)
  1061. throw SysError(format("moving `%1%' to `%2%'") % tmpPath % storePath);
  1062. if (pathExists(oldPath))
  1063. deletePath(oldPath);
  1064. }
  1065. MakeError(NotDeterministic, BuildError)
  1066. void DerivationGoal::buildDone()
  1067. {
  1068. trace("build done");
  1069. /* Since we got an EOF on the logger pipe, the builder is presumed
  1070. to have terminated. In fact, the builder could also have
  1071. simply have closed its end of the pipe --- just don't do that
  1072. :-) */
  1073. int status;
  1074. pid_t savedPid;
  1075. if (hook) {
  1076. savedPid = hook->pid;
  1077. status = hook->pid.wait(true);
  1078. } else {
  1079. /* !!! this could block! security problem! solution: kill the
  1080. child */
  1081. savedPid = pid;
  1082. status = pid.wait(true);
  1083. }
  1084. debug(format("builder process for `%1%' finished") % drvPath);
  1085. /* So the child is gone now. */
  1086. worker.childTerminated(savedPid);
  1087. /* Close the read side of the logger pipe. */
  1088. if (hook) {
  1089. hook->builderOut.readSide.close();
  1090. hook->fromHook.readSide.close();
  1091. }
  1092. else builderOut.readSide.close();
  1093. /* Close the log file. */
  1094. closeLogFile();
  1095. /* When running under a build user, make sure that all processes
  1096. running under that uid are gone. This is to prevent a
  1097. malicious user from leaving behind a process that keeps files
  1098. open and modifies them after they have been chown'ed to
  1099. root. */
  1100. if (buildUser.enabled()) buildUser.kill();
  1101. bool diskFull = false;
  1102. try {
  1103. /* Check the exit status. */
  1104. if (!statusOk(status)) {
  1105. /* Heuristically check whether the build failure may have
  1106. been caused by a disk full condition. We have no way
  1107. of knowing whether the build actually got an ENOSPC.
  1108. So instead, check if the disk is (nearly) full now. If
  1109. so, we don't mark this build as a permanent failure. */
  1110. #if HAVE_STATVFS
  1111. unsigned long long required = 8ULL * 1024 * 1024; // FIXME: make configurable
  1112. struct statvfs st;
  1113. if (statvfs(settings.nixStore.c_str(), &st) == 0 &&
  1114. (unsigned long long) st.f_bavail * st.f_bsize < required)
  1115. diskFull = true;
  1116. if (statvfs(tmpDir.c_str(), &st) == 0 &&
  1117. (unsigned long long) st.f_bavail * st.f_bsize < required)
  1118. diskFull = true;
  1119. #endif
  1120. deleteTmpDir(false);
  1121. /* Move paths out of the chroot for easier debugging of
  1122. build failures. */
  1123. if (useChroot && buildMode == bmNormal)
  1124. foreach (PathSet::iterator, i, missingPaths)
  1125. if (pathExists(chrootRootDir + *i))
  1126. rename((chrootRootDir + *i).c_str(), i->c_str());
  1127. if (diskFull)
  1128. printMsg(lvlError, "note: build failure may have been caused by lack of free disk space");
  1129. throw BuildError(format("builder for `%1%' %2%")
  1130. % drvPath % statusToString(status));
  1131. }
  1132. /* Compute the FS closure of the outputs and register them as
  1133. being valid. */
  1134. registerOutputs();
  1135. if (buildMode == bmCheck) {
  1136. done(BuildResult::Built);
  1137. return;
  1138. }
  1139. /* Delete unused redirected outputs (when doing hash rewriting). */
  1140. foreach (RedirectedOutputs::iterator, i, redirectedOutputs)
  1141. if (pathExists(i->second)) deletePath(i->second);
  1142. /* Delete the chroot (if we were using one). */
  1143. autoDelChroot.reset(); /* this runs the destructor */
  1144. deleteTmpDir(true);
  1145. /* Repeat the build if necessary. */
  1146. if (curRound++ < nrRounds) {
  1147. outputLocks.unlock();
  1148. buildUser.release();
  1149. state = &DerivationGoal::tryToBuild;
  1150. worker.wakeUp(shared_from_this());
  1151. return;
  1152. }
  1153. /* It is now safe to delete the lock files, since all future
  1154. lockers will see that the output paths are valid; they will
  1155. not create new lock files with the same names as the old
  1156. (unlinked) lock files. */
  1157. outputLocks.setDeletion(true);
  1158. outputLocks.unlock();
  1159. } catch (BuildError & e) {
  1160. if (!hook)
  1161. printMsg(lvlError, e.msg());
  1162. outputLocks.unlock();
  1163. buildUser.release();
  1164. BuildResult::Status st = BuildResult::MiscFailure;
  1165. if (hook && WIFEXITED(status) && WEXITSTATUS(status) == 101) {
  1166. if (settings.printBuildTrace)
  1167. printMsg(lvlError, format("@ build-failed %1% - timeout") % drvPath);
  1168. st = BuildResult::TimedOut;
  1169. }
  1170. else if (hook && (!WIFEXITED(status) || WEXITSTATUS(status) != 100)) {
  1171. if (settings.printBuildTrace)
  1172. printMsg(lvlError, format("@ hook-failed %1% - %2% %3%")
  1173. % drvPath % status % e.msg());
  1174. }
  1175. else {
  1176. if (settings.printBuildTrace)
  1177. printMsg(lvlError, format("@ build-failed %1% - %2% %3%")
  1178. % drvPath % 1 % e.msg());
  1179. st =
  1180. statusOk(status) ? BuildResult::OutputRejected :
  1181. fixedOutput || diskFull ? BuildResult::TransientFailure :
  1182. BuildResult::PermanentFailure;
  1183. /* Register the outputs of this build as "failed" so we
  1184. won't try to build them again (negative caching).
  1185. However, don't do this for fixed-output derivations,
  1186. since they're likely to fail for transient reasons
  1187. (e.g., fetchurl not being able to access the network).
  1188. Hook errors (like communication problems with the
  1189. remote machine) shouldn't be cached either. */
  1190. if (settings.cacheFailure && !fixedOutput && !diskFull)
  1191. foreach (DerivationOutputs::iterator, i, drv.outputs)
  1192. worker.store.registerFailedPath(i->second.path);
  1193. }
  1194. done(st, e.msg());
  1195. return;
  1196. }
  1197. /* Release the build user, if applicable. */
  1198. buildUser.release();
  1199. if (settings.printBuildTrace)
  1200. printMsg(lvlError, format("@ build-succeeded %1% -") % drvPath);
  1201. done(BuildResult::Built);
  1202. }
  1203. HookReply DerivationGoal::tryBuildHook()
  1204. {
  1205. if (!settings.useBuildHook || getEnv("NIX_BUILD_HOOK") == "") return rpDecline;
  1206. if (!worker.hook)
  1207. worker.hook = std::shared_ptr<HookInstance>(new HookInstance);
  1208. /* Tell the hook about system features (beyond the system type)
  1209. required from the build machine. (The hook could parse the
  1210. drv file itself, but this is easier.) */
  1211. Strings features = tokenizeString<Strings>(get(drv.env, "requiredSystemFeatures"));
  1212. foreach (Strings::iterator, i, features) checkStoreName(*i); /* !!! abuse */
  1213. /* Send the request to the hook. */
  1214. writeLine(worker.hook->toHook.writeSide, (format("%1% %2% %3% %4%")
  1215. % (worker.getNrLocalBuilds() < settings.maxBuildJobs ? "1" : "0")
  1216. % drv.platform % drvPath % concatStringsSep(",", features)).str());
  1217. /* Read the first line of input, which should be a word indicating
  1218. whether the hook wishes to perform the build. */
  1219. string reply;
  1220. while (true) {
  1221. string s = readLine(worker.hook->fromHook.readSide);
  1222. if (string(s, 0, 2) == "# ") {
  1223. reply = string(s, 2);
  1224. break;
  1225. }
  1226. s += "\n";
  1227. writeToStderr(s);
  1228. }
  1229. debug(format("hook reply is `%1%'") % reply);
  1230. if (reply == "decline" || reply == "postpone")
  1231. return reply == "decline" ? rpDecline : rpPostpone;
  1232. else if (reply != "accept")
  1233. throw Error(format("bad hook reply `%1%'") % reply);
  1234. printMsg(lvlTalkative, format("using hook to build path(s) %1%") % showPaths(missingPaths));
  1235. hook = worker.hook;
  1236. worker.hook.reset();
  1237. /* Tell the hook all the inputs that have to be copied to the
  1238. remote system. This unfortunately has to contain the entire
  1239. derivation closure to ensure that the validity invariant holds
  1240. on the remote system. (I.e., it's unfortunate that we have to
  1241. list it since the remote system *probably* already has it.) */
  1242. PathSet allInputs;
  1243. allInputs.insert(inputPaths.begin(), inputPaths.end());
  1244. computeFSClosure(worker.store, drvPath, allInputs);
  1245. string s;
  1246. foreach (PathSet::iterator, i, allInputs) { s += *i; s += ' '; }
  1247. writeLine(hook->toHook.writeSide, s);
  1248. /* Tell the hooks the missing outputs that have to be copied back
  1249. from the remote system. */
  1250. s = "";
  1251. foreach (PathSet::iterator, i, missingPaths) { s += *i; s += ' '; }
  1252. writeLine(hook->toHook.writeSide, s);
  1253. hook->toHook.writeSide.close();
  1254. /* Create the log file and pipe. */
  1255. Path logFile = openLogFile();
  1256. set<int> fds;
  1257. fds.insert(hook->fromHook.readSide);
  1258. fds.insert(hook->builderOut.readSide);
  1259. worker.childStarted(shared_from_this(), hook->pid, fds, false, false);
  1260. if (settings.printBuildTrace)
  1261. printMsg(lvlError, format("@ build-started %1% - %2% %3%")
  1262. % drvPath % drv.platform % logFile);
  1263. return rpAccept;
  1264. }
  1265. void chmod_(const Path & path, mode_t mode)
  1266. {
  1267. if (chmod(path.c_str(), mode) == -1)
  1268. throw SysError(format("setting permissions on `%1%'") % path);
  1269. }
  1270. int childEntry(void * arg)
  1271. {
  1272. ((DerivationGoal *) arg)->runChild();
  1273. return 1;
  1274. }
  1275. void DerivationGoal::startBuilder()
  1276. {
  1277. auto f = format(
  1278. buildMode == bmRepair ? "repairing path(s) %1%" :
  1279. buildMode == bmCheck ? "checking path(s) %1%" :
  1280. nrRounds > 1 ? "building path(s) %1% (round %2%/%3%)" :
  1281. "building path(s) %1%");
  1282. f.exceptions(boost::io::all_error_bits ^ boost::io::too_many_args_bit);
  1283. startNest(nest, lvlInfo, f % showPaths(missingPaths) % curRound % nrRounds);
  1284. /* Right platform? */
  1285. if (!canBuildLocally(drv.platform)) {
  1286. if (settings.printBuildTrace)
  1287. printMsg(lvlError, format("@ unsupported-platform %1% %2%") % drvPath % drv.platform);
  1288. throw Error(
  1289. format("a `%1%' is required to build `%3%', but I am a `%2%'")
  1290. % drv.platform % settings.thisSystem % drvPath);
  1291. }
  1292. /* Note: built-in builders are *not* running in a chroot environment so
  1293. that we can easily implement them in Guile without having it as a
  1294. derivation input (they are running under a separate build user,
  1295. though). */
  1296. useChroot = settings.useChroot && !isBuiltin(drv);
  1297. /* Construct the environment passed to the builder. */
  1298. env.clear();
  1299. /* Most shells initialise PATH to some default (/bin:/usr/bin:...) when
  1300. PATH is not set. We don't want this, so we fill it in with some dummy
  1301. value. */
  1302. env["PATH"] = "/path-not-set";
  1303. /* Set HOME to a non-existing path to prevent certain programs from using
  1304. /etc/passwd (or NIS, or whatever) to locate the home directory (for
  1305. example, wget looks for ~/.wgetrc). I.e., these tools use /etc/passwd
  1306. if HOME is not set, but they will just assume that the settings file
  1307. they are looking for does not exist if HOME is set but points to some
  1308. non-existing path. */
  1309. Path homeDir = "/homeless-shelter";
  1310. env["HOME"] = homeDir;
  1311. /* Tell the builder where the Nix store is. Usually they
  1312. shouldn't care, but this is useful for purity checking (e.g.,
  1313. the compiler or linker might only want to accept paths to files
  1314. in the store or in the build directory). */
  1315. env["NIX_STORE"] = settings.nixStore;
  1316. /* The maximum number of cores to utilize for parallel building. */
  1317. env["NIX_BUILD_CORES"] = (format("%d") % settings.buildCores).str();
  1318. /* Add all bindings specified in the derivation. */
  1319. foreach (StringPairs::iterator, i, drv.env)
  1320. env[i->first] = i->second;
  1321. /* Create a temporary directory where the build will take
  1322. place. */
  1323. auto drvName = storePathToName(drvPath);
  1324. tmpDir = createTempDir("", "guix-build-" + drvName, false, false, 0700);
  1325. /* In a sandbox, for determinism, always use the same temporary
  1326. directory. */
  1327. tmpDirInSandbox = useChroot ? canonPath("/tmp", true) + "/guix-build-" + drvName + "-0" : tmpDir;
  1328. /* For convenience, set an environment pointing to the top build
  1329. directory. */
  1330. env["NIX_BUILD_TOP"] = tmpDirInSandbox;
  1331. /* Also set TMPDIR and variants to point to this directory. */
  1332. env["TMPDIR"] = env["TEMPDIR"] = env["TMP"] = env["TEMP"] = tmpDirInSandbox;
  1333. /* Explicitly set PWD to prevent problems with chroot builds. In
  1334. particular, dietlibc cannot figure out the cwd because the
  1335. inode of the current directory doesn't appear in .. (because
  1336. getdents returns the inode of the mount point). */
  1337. env["PWD"] = tmpDirInSandbox;
  1338. /* Compatibility hack with Nix <= 0.7: if this is a fixed-output
  1339. derivation, tell the builder, so that for instance `fetchurl'
  1340. can skip checking the output. On older Nixes, this environment
  1341. variable won't be set, so `fetchurl' will do the check. */
  1342. if (fixedOutput) env["NIX_OUTPUT_CHECKED"] = "1";
  1343. /* *Only* if this is a fixed-output derivation, propagate the
  1344. values of the environment variables specified in the
  1345. `impureEnvVars' attribute to the builder. This allows for
  1346. instance environment variables for proxy configuration such as
  1347. `http_proxy' to be easily passed to downloaders like
  1348. `fetchurl'. Passing such environment variables from the caller
  1349. to the builder is generally impure, but the output of
  1350. fixed-output derivations is by definition pure (since we
  1351. already know the cryptographic hash of the output). */
  1352. if (fixedOutput) {
  1353. Strings varNames = tokenizeString<Strings>(get(drv.env, "impureEnvVars"));
  1354. foreach (Strings::iterator, i, varNames) env[*i] = getEnv(*i);
  1355. }
  1356. /* The `exportReferencesGraph' feature allows the references graph
  1357. to be passed to a builder. This attribute should be a list of
  1358. pairs [name1 path1 name2 path2 ...]. The references graph of
  1359. each `pathN' will be stored in a text file `nameN' in the
  1360. temporary build directory. The text files have the format used
  1361. by `nix-store --register-validity'. However, the deriver
  1362. fields are left empty. */
  1363. string s = get(drv.env, "exportReferencesGraph");
  1364. Strings ss = tokenizeString<Strings>(s);
  1365. if (ss.size() % 2 != 0)
  1366. throw BuildError(format("odd number of tokens in `exportReferencesGraph': `%1%'") % s);
  1367. for (Strings::iterator i = ss.begin(); i != ss.end(); ) {
  1368. string fileName = *i++;
  1369. checkStoreName(fileName); /* !!! abuse of this function */
  1370. /* Check that the store path is valid. */
  1371. Path storePath = *i++;
  1372. if (!isInStore(storePath))
  1373. throw BuildError(format("`exportReferencesGraph' contains a non-store path `%1%'")
  1374. % storePath);
  1375. storePath = toStorePath(storePath);
  1376. if (!worker.store.isValidPath(storePath))
  1377. throw BuildError(format("`exportReferencesGraph' contains an invalid path `%1%'")
  1378. % storePath);
  1379. /* If there are derivations in the graph, then include their
  1380. outputs as well. This is useful if you want to do things
  1381. like passing all build-time dependencies of some path to a
  1382. derivation that builds a NixOS DVD image. */
  1383. PathSet paths, paths2;
  1384. computeFSClosure(worker.store, storePath, paths);
  1385. paths2 = paths;
  1386. foreach (PathSet::iterator, j, paths2) {
  1387. if (isDerivation(*j)) {
  1388. Derivation drv = derivationFromPath(worker.store, *j);
  1389. foreach (DerivationOutputs::iterator, k, drv.outputs)
  1390. computeFSClosure(worker.store, k->second.path, paths);
  1391. }
  1392. }
  1393. /* Write closure info to `fileName'. */
  1394. writeFile(tmpDir + "/" + fileName,
  1395. worker.store.makeValidityRegistration(paths, false, false));
  1396. }
  1397. /* If `build-users-group' is not empty, then we have to build as
  1398. one of the members of that group. */
  1399. if (settings.buildUsersGroup != "") {
  1400. buildUser.acquire();
  1401. assert(buildUser.getUID() != 0);
  1402. assert(buildUser.getGID() != 0);
  1403. /* Make sure that no other processes are executing under this
  1404. uid. */
  1405. buildUser.kill();
  1406. /* Change ownership of the temporary build directory. */
  1407. if (chown(tmpDir.c_str(), buildUser.getUID(), buildUser.getGID()) == -1)
  1408. throw SysError(format("cannot change ownership of '%1%'") % tmpDir);
  1409. }
  1410. if (useChroot) {
  1411. #if CHROOT_ENABLED
  1412. /* Create a temporary directory in which we set up the chroot
  1413. environment using bind-mounts. We put it in the Nix store
  1414. to ensure that we can create hard-links to non-directory
  1415. inputs in the fake Nix store in the chroot (see below). */
  1416. chrootRootDir = drvPath + ".chroot";
  1417. if (pathExists(chrootRootDir)) deletePath(chrootRootDir);
  1418. /* Clean up the chroot directory automatically. */
  1419. autoDelChroot = std::shared_ptr<AutoDelete>(new AutoDelete(chrootRootDir));
  1420. printMsg(lvlChatty, format("setting up chroot environment in `%1%'") % chrootRootDir);
  1421. if (mkdir(chrootRootDir.c_str(), 0750) == -1)
  1422. throw SysError(format("cannot create ‘%1%’") % chrootRootDir);
  1423. if (chown(chrootRootDir.c_str(), 0, buildUser.getGID()) == -1)
  1424. throw SysError(format("cannot change ownership of ‘%1%’") % chrootRootDir);
  1425. /* Create a writable /tmp in the chroot. Many builders need
  1426. this. (Of course they should really respect $TMPDIR
  1427. instead.) */
  1428. Path chrootTmpDir = chrootRootDir + "/tmp";
  1429. createDirs(chrootTmpDir);
  1430. chmod_(chrootTmpDir, 01777);
  1431. /* Create a /etc/passwd with entries for the build user and the
  1432. nobody account. The latter is kind of a hack to support
  1433. Samba-in-QEMU. */
  1434. createDirs(chrootRootDir + "/etc");
  1435. writeFile(chrootRootDir + "/etc/passwd",
  1436. (format(
  1437. "nixbld:x:%1%:%2%:Nix build user:/:/noshell\n"
  1438. "nobody:x:65534:65534:Nobody:/:/noshell\n")
  1439. % (buildUser.enabled() ? buildUser.getUID() : getuid())
  1440. % (buildUser.enabled() ? buildUser.getGID() : getgid())).str());
  1441. /* Declare the build user's group so that programs get a consistent
  1442. view of the system (e.g., "id -gn"). */
  1443. writeFile(chrootRootDir + "/etc/group",
  1444. (format("nixbld:!:%1%:\n")
  1445. % (buildUser.enabled() ? buildUser.getGID() : getgid())).str());
  1446. /* Create /etc/hosts with localhost entry. */
  1447. if (!fixedOutput)
  1448. writeFile(chrootRootDir + "/etc/hosts", "127.0.0.1 localhost\n");
  1449. /* Bind-mount a user-configurable set of directories from the
  1450. host file system. */
  1451. PathSet dirs = tokenizeString<StringSet>(settings.get("build-chroot-dirs", string(DEFAULT_CHROOT_DIRS)));
  1452. PathSet dirs2 = tokenizeString<StringSet>(settings.get("build-extra-chroot-dirs", string("")));
  1453. dirs.insert(dirs2.begin(), dirs2.end());
  1454. for (auto & i : dirs) {
  1455. size_t p = i.find('=');
  1456. if (p == string::npos)
  1457. dirsInChroot[i] = i;
  1458. else
  1459. dirsInChroot[string(i, 0, p)] = string(i, p + 1);
  1460. }
  1461. dirsInChroot[tmpDirInSandbox] = tmpDir;
  1462. /* Make the closure of the inputs available in the chroot,
  1463. rather than the whole Nix store. This prevents any access
  1464. to undeclared dependencies. Directories are bind-mounted,
  1465. while other inputs are hard-linked (since only directories
  1466. can be bind-mounted). !!! As an extra security
  1467. precaution, make the fake Nix store only writable by the
  1468. build user. */
  1469. Path chrootStoreDir = chrootRootDir + settings.nixStore;
  1470. createDirs(chrootStoreDir);
  1471. chmod_(chrootStoreDir, 01775);
  1472. if (chown(chrootStoreDir.c_str(), 0, buildUser.getGID()) == -1)
  1473. throw SysError(format("cannot change ownership of ‘%1%’") % chrootStoreDir);
  1474. foreach (PathSet::iterator, i, inputPaths) {
  1475. struct stat st;
  1476. if (lstat(i->c_str(), &st))
  1477. throw SysError(format("getting attributes of path `%1%'") % *i);
  1478. if (S_ISDIR(st.st_mode))
  1479. dirsInChroot[*i] = *i;
  1480. else {
  1481. Path p = chrootRootDir + *i;
  1482. if (link(i->c_str(), p.c_str()) == -1) {
  1483. /* Hard-linking fails if we exceed the maximum
  1484. link count on a file (e.g. 32000 of ext3),
  1485. which is quite possible after a `nix-store
  1486. --optimise'. */
  1487. if (errno != EMLINK)
  1488. throw SysError(format("linking `%1%' to `%2%'") % p % *i);
  1489. StringSink sink;
  1490. dumpPath(*i, sink);
  1491. StringSource source(sink.s);
  1492. restorePath(p, source);
  1493. }
  1494. regularInputPaths.insert(*i);
  1495. }
  1496. }
  1497. /* If we're repairing, checking or rebuilding part of a
  1498. multiple-outputs derivation, it's possible that we're
  1499. rebuilding a path that is in settings.dirsInChroot
  1500. (typically the dependencies of /bin/sh). Throw them
  1501. out. */
  1502. for (auto & i : drv.outputs)
  1503. dirsInChroot.erase(i.second.path);
  1504. #else
  1505. throw Error("chroot builds are not supported on this platform");
  1506. #endif
  1507. }
  1508. else {
  1509. if (pathExists(homeDir))
  1510. throw Error(format("directory `%1%' exists; please remove it") % homeDir);
  1511. /* We're not doing a chroot build, but we have some valid
  1512. output paths. Since we can't just overwrite or delete
  1513. them, we have to do hash rewriting: i.e. in the
  1514. environment/arguments passed to the build, we replace the
  1515. hashes of the valid outputs with unique dummy strings;
  1516. after the build, we discard the redirected outputs
  1517. corresponding to the valid outputs, and rewrite the
  1518. contents of the new outputs to replace the dummy strings
  1519. with the actual hashes. */
  1520. if (validPaths.size() > 0)
  1521. foreach (PathSet::iterator, i, validPaths)
  1522. addHashRewrite(*i);
  1523. /* If we're repairing, then we don't want to delete the
  1524. corrupt outputs in advance. So rewrite them as well. */
  1525. if (buildMode == bmRepair)
  1526. foreach (PathSet::iterator, i, missingPaths)
  1527. if (worker.store.isValidPath(*i) && pathExists(*i)) {
  1528. addHashRewrite(*i);
  1529. redirectedBadOutputs.insert(*i);
  1530. }
  1531. }
  1532. /* Run the builder. */
  1533. printMsg(lvlChatty, format("executing builder `%1%'") % drv.builder);
  1534. /* Create the log file. */
  1535. Path logFile = openLogFile();
  1536. /* Create a pipe to get the output of the builder. */
  1537. builderOut.create();
  1538. /* Fork a child to build the package. Note that while we
  1539. currently use forks to run and wait for the children, it
  1540. shouldn't be hard to use threads for this on systems where
  1541. fork() is unavailable or inefficient.
  1542. If we're building in a chroot, then also set up private
  1543. namespaces for the build:
  1544. - The PID namespace causes the build to start as PID 1.
  1545. Processes outside of the chroot are not visible to those on
  1546. the inside, but processes inside the chroot are visible from
  1547. the outside (though with different PIDs).
  1548. - The private mount namespace ensures that all the bind mounts
  1549. we do will only show up in this process and its children, and
  1550. will disappear automatically when we're done.
  1551. - The private network namespace ensures that the builder cannot
  1552. talk to the outside world (or vice versa). It only has a
  1553. private loopback interface.
  1554. - The IPC namespace prevents the builder from communicating
  1555. with outside processes using SysV IPC mechanisms (shared
  1556. memory, message queues, semaphores). It also ensures that
  1557. all IPC objects are destroyed when the builder exits.
  1558. - The UTS namespace ensures that builders see a hostname of
  1559. localhost rather than the actual hostname.
  1560. */
  1561. #if CHROOT_ENABLED
  1562. if (useChroot) {
  1563. char stack[32 * 1024];
  1564. int flags = CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWIPC | CLONE_NEWUTS | SIGCHLD;
  1565. if (!fixedOutput) flags |= CLONE_NEWNET;
  1566. /* Ensure proper alignment on the stack. On aarch64, it has to be 16
  1567. bytes. */
  1568. pid = clone(childEntry,
  1569. (char *)(((uintptr_t)stack + sizeof(stack) - 8) & ~(uintptr_t)0xf),
  1570. flags, this);
  1571. if (pid == -1)
  1572. throw SysError("cloning builder process");
  1573. } else
  1574. #endif
  1575. {
  1576. pid = fork();
  1577. if (pid == 0) runChild();
  1578. }
  1579. if (pid == -1) throw SysError("unable to fork");
  1580. /* parent */
  1581. pid.setSeparatePG(true);
  1582. builderOut.writeSide.close();
  1583. worker.childStarted(shared_from_this(), pid,
  1584. singleton<set<int> >(builderOut.readSide), true, true);
  1585. /* Check if setting up the build environment failed. */
  1586. string msg = readLine(builderOut.readSide);
  1587. if (!msg.empty()) throw Error(msg);
  1588. if (settings.printBuildTrace) {
  1589. printMsg(lvlError, format("@ build-started %1% - %2% %3%")
  1590. % drvPath % drv.platform % logFile);
  1591. }
  1592. }
  1593. void DerivationGoal::runChild()
  1594. {
  1595. /* Warning: in the child we should absolutely not make any SQLite
  1596. calls! */
  1597. try { /* child */
  1598. _writeToStderr = 0;
  1599. restoreAffinity();
  1600. commonChildInit(builderOut);
  1601. #if CHROOT_ENABLED
  1602. if (useChroot) {
  1603. /* Initialise the loopback interface. */
  1604. AutoCloseFD fd(socket(PF_INET, SOCK_DGRAM, IPPROTO_IP));
  1605. if (fd == -1) throw SysError("cannot open IP socket");
  1606. struct ifreq ifr;
  1607. strcpy(ifr.ifr_name, "lo");
  1608. ifr.ifr_flags = IFF_UP | IFF_LOOPBACK | IFF_RUNNING;
  1609. if (ioctl(fd, SIOCSIFFLAGS, &ifr) == -1)
  1610. throw SysError("cannot set loopback interface flags");
  1611. fd.close();
  1612. /* Set the hostname etc. to fixed values. */
  1613. char hostname[] = "localhost";
  1614. if (sethostname(hostname, sizeof(hostname)) == -1)
  1615. throw SysError("cannot set host name");
  1616. char domainname[] = "(none)"; // kernel default
  1617. if (setdomainname(domainname, sizeof(domainname)) == -1)
  1618. throw SysError("cannot set domain name");
  1619. /* Make all filesystems private. This is necessary
  1620. because subtrees may have been mounted as "shared"
  1621. (MS_SHARED). (Systemd does this, for instance.) Even
  1622. though we have a private mount namespace, mounting
  1623. filesystems on top of a shared subtree still propagates
  1624. outside of the namespace. Making a subtree private is
  1625. local to the namespace, though, so setting MS_PRIVATE
  1626. does not affect the outside world. */
  1627. if (mount(0, "/", 0, MS_REC|MS_PRIVATE, 0) == -1) {
  1628. throw SysError("unable to make ‘/’ private mount");
  1629. }
  1630. /* Bind-mount chroot directory to itself, to treat it as a
  1631. different filesystem from /, as needed for pivot_root. */
  1632. if (mount(chrootRootDir.c_str(), chrootRootDir.c_str(), 0, MS_BIND, 0) == -1)
  1633. throw SysError(format("unable to bind mount ‘%1%’") % chrootRootDir);
  1634. /* Set up a nearly empty /dev, unless the user asked to
  1635. bind-mount the host /dev. */
  1636. Strings ss;
  1637. if (dirsInChroot.find("/dev") == dirsInChroot.end()) {
  1638. createDirs(chrootRootDir + "/dev/shm");
  1639. createDirs(chrootRootDir + "/dev/pts");
  1640. ss.push_back("/dev/full");
  1641. #ifdef __linux__
  1642. if (pathExists("/dev/kvm"))
  1643. ss.push_back("/dev/kvm");
  1644. #endif
  1645. ss.push_back("/dev/null");
  1646. ss.push_back("/dev/random");
  1647. ss.push_back("/dev/tty");
  1648. ss.push_back("/dev/urandom");
  1649. ss.push_back("/dev/zero");
  1650. createSymlink("/proc/self/fd", chrootRootDir + "/dev/fd");
  1651. createSymlink("/proc/self/fd/0", chrootRootDir + "/dev/stdin");
  1652. createSymlink("/proc/self/fd/1", chrootRootDir + "/dev/stdout");
  1653. createSymlink("/proc/self/fd/2", chrootRootDir + "/dev/stderr");
  1654. }
  1655. /* Fixed-output derivations typically need to access the
  1656. network, so give them access to /etc/resolv.conf and so
  1657. on. */
  1658. if (fixedOutput) {
  1659. ss.push_back("/etc/resolv.conf");
  1660. ss.push_back("/etc/nsswitch.conf");
  1661. ss.push_back("/etc/services");
  1662. ss.push_back("/etc/hosts");
  1663. }
  1664. for (auto & i : ss) dirsInChroot[i] = i;
  1665. /* Bind-mount all the directories from the "host"
  1666. filesystem that we want in the chroot
  1667. environment. */
  1668. foreach (DirsInChroot::iterator, i, dirsInChroot) {
  1669. struct stat st;
  1670. Path source = i->second;
  1671. Path target = chrootRootDir + i->first;
  1672. if (source == "/proc") continue; // backwards compatibility
  1673. debug(format("bind mounting `%1%' to `%2%'") % source % target);
  1674. if (stat(source.c_str(), &st) == -1)
  1675. throw SysError(format("getting attributes of path `%1%'") % source);
  1676. if (S_ISDIR(st.st_mode))
  1677. createDirs(target);
  1678. else {
  1679. createDirs(dirOf(target));
  1680. writeFile(target, "");
  1681. }
  1682. if (mount(source.c_str(), target.c_str(), "", MS_BIND, 0) == -1)
  1683. throw SysError(format("bind mount from `%1%' to `%2%' failed") % source % target);
  1684. }
  1685. /* Bind a new instance of procfs on /proc to reflect our
  1686. private PID namespace. */
  1687. createDirs(chrootRootDir + "/proc");
  1688. if (mount("none", (chrootRootDir + "/proc").c_str(), "proc", 0, 0) == -1)
  1689. throw SysError("mounting /proc");
  1690. /* Mount a new tmpfs on /dev/shm to ensure that whatever
  1691. the builder puts in /dev/shm is cleaned up automatically. */
  1692. if (pathExists("/dev/shm") && mount("none", (chrootRootDir + "/dev/shm").c_str(), "tmpfs", 0, 0) == -1)
  1693. throw SysError("mounting /dev/shm");
  1694. /* Mount a new devpts on /dev/pts. Note that this
  1695. requires the kernel to be compiled with
  1696. CONFIG_DEVPTS_MULTIPLE_INSTANCES=y (which is the case
  1697. if /dev/ptx/ptmx exists). */
  1698. if (pathExists("/dev/pts/ptmx") &&
  1699. !pathExists(chrootRootDir + "/dev/ptmx")
  1700. && dirsInChroot.find("/dev/pts") == dirsInChroot.end())
  1701. {
  1702. if (mount("none", (chrootRootDir + "/dev/pts").c_str(), "devpts", 0, "newinstance,mode=0620") == -1)
  1703. throw SysError("mounting /dev/pts");
  1704. createSymlink("/dev/pts/ptmx", chrootRootDir + "/dev/ptmx");
  1705. /* Make sure /dev/pts/ptmx is world-writable. With some
  1706. Linux versions, it is created with permissions 0. */
  1707. chmod_(chrootRootDir + "/dev/pts/ptmx", 0666);
  1708. }
  1709. /* Do the chroot(). */
  1710. if (chdir(chrootRootDir.c_str()) == -1)
  1711. throw SysError(format("cannot change directory to '%1%'") % chrootRootDir);
  1712. if (mkdir("real-root", 0) == -1)
  1713. throw SysError("cannot create real-root directory");
  1714. #define pivot_root(new_root, put_old) (syscall(SYS_pivot_root, new_root, put_old))
  1715. if (pivot_root(".", "real-root") == -1)
  1716. throw SysError(format("cannot pivot old root directory onto '%1%'") % (chrootRootDir + "/real-root"));
  1717. #undef pivot_root
  1718. if (chroot(".") == -1)
  1719. throw SysError(format("cannot change root directory to '%1%'") % chrootRootDir);
  1720. if (umount2("real-root", MNT_DETACH) == -1)
  1721. throw SysError("cannot unmount real root filesystem");
  1722. if (rmdir("real-root") == -1)
  1723. throw SysError("cannot remove real-root directory");
  1724. }
  1725. #endif
  1726. if (chdir(tmpDirInSandbox.c_str()) == -1)
  1727. throw SysError(format("changing into `%1%'") % tmpDir);
  1728. /* Close all other file descriptors. */
  1729. closeMostFDs(set<int>());
  1730. #if __linux__
  1731. /* Change the personality to 32-bit if we're doing an
  1732. i686-linux build on an x86_64-linux machine. */
  1733. struct utsname utsbuf;
  1734. uname(&utsbuf);
  1735. if (drv.platform == "i686-linux" &&
  1736. (settings.thisSystem == "x86_64-linux" ||
  1737. (!strcmp(utsbuf.sysname, "Linux") && !strcmp(utsbuf.machine, "x86_64")))) {
  1738. if (personality(PER_LINUX32) == -1)
  1739. throw SysError("cannot set i686-linux personality");
  1740. }
  1741. /* Impersonate a Linux 2.6 machine to get some determinism in
  1742. builds that depend on the kernel version. */
  1743. if ((drv.platform == "i686-linux" || drv.platform == "x86_64-linux") && settings.impersonateLinux26) {
  1744. int cur = personality(0xffffffff);
  1745. if (cur != -1) personality(cur | 0x0020000 /* == UNAME26 */);
  1746. }
  1747. /* Disable address space randomization for improved
  1748. determinism. */
  1749. int cur = personality(0xffffffff);
  1750. if (cur != -1) personality(cur | ADDR_NO_RANDOMIZE);
  1751. #endif
  1752. /* Fill in the environment. */
  1753. Strings envStrs;
  1754. foreach (Environment::const_iterator, i, env)
  1755. envStrs.push_back(rewriteHashes(i->first + "=" + i->second, rewritesToTmp));
  1756. /* If we are running in `build-users' mode, then switch to the
  1757. user we allocated above. Make sure that we drop all root
  1758. privileges. Note that above we have closed all file
  1759. descriptors except std*, so that's safe. Also note that
  1760. setuid() when run as root sets the real, effective and
  1761. saved UIDs. */
  1762. if (buildUser.enabled()) {
  1763. /* Preserve supplementary groups of the build user, to allow
  1764. admins to specify groups such as "kvm". */
  1765. if (setgroups(buildUser.getSupplementaryGIDs().size(),
  1766. buildUser.getSupplementaryGIDs().data()) == -1)
  1767. throw SysError("cannot set supplementary groups of build user");
  1768. if (setgid(buildUser.getGID()) == -1 ||
  1769. getgid() != buildUser.getGID() ||
  1770. getegid() != buildUser.getGID())
  1771. throw SysError("setgid failed");
  1772. if (setuid(buildUser.getUID()) == -1 ||
  1773. getuid() != buildUser.getUID() ||
  1774. geteuid() != buildUser.getUID())
  1775. throw SysError("setuid failed");
  1776. }
  1777. restoreSIGPIPE();
  1778. /* Indicate that we managed to set up the build environment. */
  1779. writeFull(STDERR_FILENO, "\n");
  1780. /* Execute the program. This should not return. */
  1781. if (isBuiltin(drv)) {
  1782. try {
  1783. logType = ltFlat;
  1784. auto buildDrv = lookupBuiltinBuilder(drv.builder);
  1785. if (buildDrv != NULL) {
  1786. /* Check what the output file name is. When doing a
  1787. 'bmCheck' build, the output file name is different from
  1788. that specified in DRV due to hash rewriting. */
  1789. Path output = drv.outputs["out"].path;
  1790. auto redirected = redirectedOutputs.find(output);
  1791. if (redirected != redirectedOutputs.end())
  1792. output = redirected->second;
  1793. buildDrv(drv, drvPath, output);
  1794. }
  1795. else
  1796. throw Error(format("unsupported builtin function '%1%'") % string(drv.builder, 8));
  1797. _exit(0);
  1798. } catch (std::exception & e) {
  1799. writeFull(STDERR_FILENO, "error: " + string(e.what()) + "\n");
  1800. _exit(1);
  1801. }
  1802. }
  1803. /* Fill in the arguments. */
  1804. Strings args;
  1805. string builderBasename = baseNameOf(drv.builder);
  1806. args.push_back(builderBasename);
  1807. foreach (Strings::iterator, i, drv.args)
  1808. args.push_back(rewriteHashes(*i, rewritesToTmp));
  1809. execve(drv.builder.c_str(), stringsToCharPtrs(args).data(), stringsToCharPtrs(envStrs).data());
  1810. throw SysError(format("executing `%1%'") % drv.builder);
  1811. } catch (std::exception & e) {
  1812. writeFull(STDERR_FILENO, "while setting up the build environment: " + string(e.what()) + "\n");
  1813. _exit(1);
  1814. }
  1815. abort(); /* never reached */
  1816. }
  1817. /* Parse a list of reference specifiers. Each element must either be
  1818. a store path, or the symbolic name of the output of the derivation
  1819. (such as `out'). */
  1820. PathSet parseReferenceSpecifiers(const Derivation & drv, string attr)
  1821. {
  1822. PathSet result;
  1823. Paths paths = tokenizeString<Paths>(attr);
  1824. foreach (Strings::iterator, i, paths) {
  1825. if (isStorePath(*i))
  1826. result.insert(*i);
  1827. else if (drv.outputs.find(*i) != drv.outputs.end())
  1828. result.insert(drv.outputs.find(*i)->second.path);
  1829. else throw BuildError(
  1830. format("derivation contains an illegal reference specifier `%1%'")
  1831. % *i);
  1832. }
  1833. return result;
  1834. }
  1835. void DerivationGoal::registerOutputs()
  1836. {
  1837. /* When using a build hook, the build hook can register the output
  1838. as valid (by doing `nix-store --import'). If so we don't have
  1839. to do anything here. */
  1840. if (hook) {
  1841. bool allValid = true;
  1842. foreach (DerivationOutputs::iterator, i, drv.outputs)
  1843. if (!worker.store.isValidPath(i->second.path)) allValid = false;
  1844. if (allValid) return;
  1845. }
  1846. ValidPathInfos infos;
  1847. /* Set of inodes seen during calls to canonicalisePathMetaData()
  1848. for this build's outputs. This needs to be shared between
  1849. outputs to allow hard links between outputs. */
  1850. InodesSeen inodesSeen;
  1851. Path checkSuffix = "-check";
  1852. /* Check whether the output paths were created, and grep each
  1853. output path to determine what other paths it references. Also make all
  1854. output paths read-only. */
  1855. foreach (DerivationOutputs::iterator, i, drv.outputs) {
  1856. Path path = i->second.path;
  1857. if (missingPaths.find(path) == missingPaths.end()) continue;
  1858. Path actualPath = path;
  1859. if (useChroot) {
  1860. actualPath = chrootRootDir + path;
  1861. if (pathExists(actualPath)) {
  1862. /* Move output paths from the chroot to the Nix store. */
  1863. if (buildMode == bmRepair)
  1864. replaceValidPath(path, actualPath);
  1865. else
  1866. if (buildMode != bmCheck && rename(actualPath.c_str(), path.c_str()) == -1)
  1867. throw SysError(format("moving build output `%1%' from the chroot to the Nix store") % path);
  1868. }
  1869. if (buildMode != bmCheck) actualPath = path;
  1870. } else {
  1871. Path redirected = redirectedOutputs[path];
  1872. if (buildMode == bmRepair
  1873. && redirectedBadOutputs.find(path) != redirectedBadOutputs.end()
  1874. && pathExists(redirected))
  1875. replaceValidPath(path, redirected);
  1876. if (buildMode == bmCheck && redirected != "")
  1877. actualPath = redirected;
  1878. }
  1879. struct stat st;
  1880. if (lstat(actualPath.c_str(), &st) == -1) {
  1881. if (errno == ENOENT)
  1882. throw BuildError(
  1883. format("builder for `%1%' failed to produce output path `%2%'")
  1884. % drvPath % path);
  1885. throw SysError(format("getting attributes of path `%1%'") % actualPath);
  1886. }
  1887. #ifndef __CYGWIN__
  1888. /* Check that the output is not group or world writable, as
  1889. that means that someone else can have interfered with the
  1890. build. Also, the output should be owned by the build
  1891. user. */
  1892. if ((!S_ISLNK(st.st_mode) && (st.st_mode & (S_IWGRP | S_IWOTH))) ||
  1893. (buildUser.enabled() && st.st_uid != buildUser.getUID()))
  1894. throw BuildError(format("suspicious ownership or permission on `%1%'; rejecting this build output") % path);
  1895. #endif
  1896. /* Apply hash rewriting if necessary. */
  1897. bool rewritten = false;
  1898. if (!rewritesFromTmp.empty()) {
  1899. printMsg(lvlError, format("warning: rewriting hashes in `%1%'; cross fingers") % path);
  1900. /* Canonicalise first. This ensures that the path we're
  1901. rewriting doesn't contain a hard link to /etc/shadow or
  1902. something like that. */
  1903. canonicalisePathMetaData(actualPath, buildUser.enabled() ? buildUser.getUID() : -1, inodesSeen);
  1904. /* FIXME: this is in-memory. */
  1905. StringSink sink;
  1906. dumpPath(actualPath, sink);
  1907. deletePath(actualPath);
  1908. sink.s = rewriteHashes(sink.s, rewritesFromTmp);
  1909. StringSource source(sink.s);
  1910. restorePath(actualPath, source);
  1911. rewritten = true;
  1912. }
  1913. startNest(nest, lvlTalkative,
  1914. format("scanning for references inside `%1%'") % path);
  1915. /* Check that fixed-output derivations produced the right
  1916. outputs (i.e., the content hash should match the specified
  1917. hash). */
  1918. if (i->second.hash != "") {
  1919. bool recursive; HashType ht; Hash h;
  1920. i->second.parseHashInfo(recursive, ht, h);
  1921. if (!recursive) {
  1922. /* The output path should be a regular file without
  1923. execute permission. */
  1924. if (!S_ISREG(st.st_mode) || (st.st_mode & S_IXUSR) != 0)
  1925. throw BuildError(
  1926. format("output path `%1% should be a non-executable regular file") % path);
  1927. }
  1928. /* Check the hash. */
  1929. Hash h2 = recursive ? hashPath(ht, actualPath).first : hashFile(ht, actualPath);
  1930. if (h != h2)
  1931. throw BuildError(
  1932. format("%1% hash mismatch for output path `%2%'\n"
  1933. " expected: %3%\n"
  1934. " actual: %4%")
  1935. % i->second.hashAlgo % path
  1936. % printHash16or32(h) % printHash16or32(h2));
  1937. }
  1938. /* Get rid of all weird permissions. This also checks that
  1939. all files are owned by the build user, if applicable. */
  1940. canonicalisePathMetaData(actualPath,
  1941. buildUser.enabled() && !rewritten ? buildUser.getUID() : -1, inodesSeen);
  1942. /* For this output path, find the references to other paths
  1943. contained in it. Compute the SHA-256 NAR hash at the same
  1944. time. The hash is stored in the database so that we can
  1945. verify later on whether nobody has messed with the store. */
  1946. HashResult hash;
  1947. PathSet references = scanForReferences(actualPath, allPaths, hash);
  1948. if (buildMode == bmCheck) {
  1949. if (!store->isValidPath(path)) continue;
  1950. ValidPathInfo info = worker.store.queryPathInfo(path);
  1951. if (hash.first != info.hash) {
  1952. if (settings.keepFailed) {
  1953. Path dst = path + checkSuffix;
  1954. if (pathExists(dst)) deletePath(dst);
  1955. if (rename(actualPath.c_str(), dst.c_str()))
  1956. throw SysError(format("renaming `%1%' to `%2%'") % actualPath % dst);
  1957. throw Error(format("derivation `%1%' may not be deterministic: output `%2%' differs from ‘%3%’")
  1958. % drvPath % path % dst);
  1959. } else
  1960. throw Error(format("derivation `%1%' may not be deterministic: output `%2%' differs")
  1961. % drvPath % path);
  1962. }
  1963. continue;
  1964. }
  1965. /* For debugging, print out the referenced and unreferenced
  1966. paths. */
  1967. foreach (PathSet::iterator, i, inputPaths) {
  1968. PathSet::iterator j = references.find(*i);
  1969. if (j == references.end())
  1970. debug(format("unreferenced input: `%1%'") % *i);
  1971. else
  1972. debug(format("referenced input: `%1%'") % *i);
  1973. }
  1974. /* Enforce `allowedReferences' and friends. */
  1975. auto checkRefs = [&](const string & attrName, bool allowed, bool recursive) {
  1976. if (drv.env.find(attrName) == drv.env.end()) return;
  1977. PathSet spec = parseReferenceSpecifiers(drv, get(drv.env, attrName));
  1978. PathSet used;
  1979. if (recursive) {
  1980. /* Our requisites are the union of the closures of our references. */
  1981. for (auto & i : references)
  1982. /* Don't call computeFSClosure on ourselves. */
  1983. if (actualPath != i)
  1984. computeFSClosure(worker.store, i, used);
  1985. } else
  1986. used = references;
  1987. for (auto & i : used)
  1988. if (allowed) {
  1989. if (spec.find(i) == spec.end())
  1990. throw BuildError(format("output (`%1%') is not allowed to refer to path `%2%'") % actualPath % i);
  1991. } else {
  1992. if (spec.find(i) != spec.end())
  1993. throw BuildError(format("output (`%1%') is not allowed to refer to path `%2%'") % actualPath % i);
  1994. }
  1995. };
  1996. checkRefs("allowedReferences", true, false);
  1997. checkRefs("allowedRequisites", true, true);
  1998. checkRefs("disallowedReferences", false, false);
  1999. checkRefs("disallowedRequisites", false, true);
  2000. if (curRound == nrRounds) {
  2001. worker.store.optimisePath(path); // FIXME: combine with scanForReferences()
  2002. worker.store.markContentsGood(path);
  2003. }
  2004. ValidPathInfo info;
  2005. info.path = path;
  2006. info.hash = hash.first;
  2007. info.narSize = hash.second;
  2008. info.references = references;
  2009. info.deriver = drvPath;
  2010. infos.push_back(info);
  2011. }
  2012. if (buildMode == bmCheck) return;
  2013. /* Compare the result with the previous round, and report which
  2014. path is different, if any.*/
  2015. if (curRound > 1 && prevInfos != infos) {
  2016. assert(prevInfos.size() == infos.size());
  2017. for (auto i = prevInfos.begin(), j = infos.begin(); i != prevInfos.end(); ++i, ++j)
  2018. if (!(*i == *j)) {
  2019. Path prev = i->path + checkSuffix;
  2020. if (pathExists(prev))
  2021. throw NotDeterministic(
  2022. format("output ‘%1%’ of ‘%2%’ differs from ‘%3%’ from previous round")
  2023. % i->path % drvPath % prev);
  2024. else
  2025. throw NotDeterministic(
  2026. format("output ‘%1%’ of ‘%2%’ differs from previous round")
  2027. % i->path % drvPath);
  2028. }
  2029. assert(false); // shouldn't happen
  2030. }
  2031. if (settings.keepFailed) {
  2032. for (auto & i : drv.outputs) {
  2033. Path prev = i.second.path + checkSuffix;
  2034. if (pathExists(prev)) deletePath(prev);
  2035. if (curRound < nrRounds) {
  2036. Path dst = i.second.path + checkSuffix;
  2037. if (rename(i.second.path.c_str(), dst.c_str()))
  2038. throw SysError(format("renaming ‘%1%’ to ‘%2%’") % i.second.path % dst);
  2039. }
  2040. }
  2041. }
  2042. if (curRound < nrRounds) {
  2043. prevInfos = infos;
  2044. return;
  2045. }
  2046. /* Register each output path as valid, and register the sets of
  2047. paths referenced by each of them. If there are cycles in the
  2048. outputs, this will fail. */
  2049. worker.store.registerValidPaths(infos);
  2050. }
  2051. string drvsLogDir = "drvs";
  2052. Path DerivationGoal::openLogFile()
  2053. {
  2054. logSize = 0;
  2055. if (!settings.keepLog) return "";
  2056. string baseName = baseNameOf(drvPath);
  2057. /* Create a log file. */
  2058. Path dir = (format("%1%/%2%/%3%/") % settings.nixLogDir % drvsLogDir % string(baseName, 0, 2)).str();
  2059. createDirs(dir);
  2060. switch (settings.logCompression)
  2061. {
  2062. case COMPRESSION_GZIP: {
  2063. Path logFileName = (format("%1%/%2%.gz") % dir % string(baseName, 2)).str();
  2064. AutoCloseFD fd = open(logFileName.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0666);
  2065. if (fd == -1) throw SysError(format("creating log file `%1%'") % logFileName);
  2066. closeOnExec(fd);
  2067. /* Note: FD will be closed by 'gzclose'. */
  2068. if (!(gzLogFile = gzdopen(fd.borrow(), "w")))
  2069. throw Error(format("cannot open compressed log file `%1%'") % logFileName);
  2070. gzbuffer(gzLogFile, 32768);
  2071. gzsetparams(gzLogFile, Z_BEST_COMPRESSION, Z_DEFAULT_STRATEGY);
  2072. return logFileName;
  2073. }
  2074. #if HAVE_BZLIB_H
  2075. case COMPRESSION_BZIP2: {
  2076. Path logFileName = (format("%1%/%2%.bz2") % dir % string(baseName, 2)).str();
  2077. AutoCloseFD fd = open(logFileName.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0666);
  2078. if (fd == -1) throw SysError(format("creating log file `%1%'") % logFileName);
  2079. closeOnExec(fd);
  2080. if (!(fLogFile = fdopen(fd.borrow(), "w")))
  2081. throw SysError(format("opening file `%1%'") % logFileName);
  2082. int err;
  2083. if (!(bzLogFile = BZ2_bzWriteOpen(&err, fLogFile, 9, 0, 0)))
  2084. throw Error(format("cannot open compressed log file `%1%'") % logFileName);
  2085. return logFileName;
  2086. }
  2087. #endif
  2088. case COMPRESSION_NONE: {
  2089. Path logFileName = (format("%1%/%2%") % dir % string(baseName, 2)).str();
  2090. fdLogFile = open(logFileName.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0666);
  2091. if (fdLogFile == -1) throw SysError(format("creating log file `%1%'") % logFileName);
  2092. closeOnExec(fdLogFile);
  2093. return logFileName;
  2094. }
  2095. }
  2096. abort();
  2097. }
  2098. void DerivationGoal::closeLogFile()
  2099. {
  2100. if (gzLogFile) {
  2101. int err;
  2102. err = gzclose(gzLogFile);
  2103. gzLogFile = NULL;
  2104. if (err != Z_OK) throw Error(format("cannot close compressed log file (gzip error = %1%)") % err);
  2105. }
  2106. #if HAVE_BZLIB_H
  2107. else if (bzLogFile) {
  2108. int err;
  2109. BZ2_bzWriteClose(&err, bzLogFile, 0, 0, 0);
  2110. bzLogFile = 0;
  2111. if (err != BZ_OK) throw Error(format("cannot close compressed log file (BZip2 error = %1%)") % err);
  2112. }
  2113. #endif
  2114. if (fLogFile) {
  2115. fclose(fLogFile);
  2116. fLogFile = 0;
  2117. }
  2118. fdLogFile.close();
  2119. }
  2120. static void _chown(const Path & path, uid_t uid, gid_t gid)
  2121. {
  2122. checkInterrupt();
  2123. if (lchown(path.c_str(), uid, gid) == -1) {
  2124. throw SysError(format("change owner and group of `%1%'") % path);
  2125. }
  2126. struct stat st = lstat(path);
  2127. if (S_ISDIR(st.st_mode)) {
  2128. for (auto & i : readDirectory(path))
  2129. _chown(path + "/" + i.name, uid, gid);
  2130. }
  2131. }
  2132. void DerivationGoal::deleteTmpDir(bool force)
  2133. {
  2134. if (tmpDir != "") {
  2135. if (settings.keepFailed && !force) {
  2136. printMsg(lvlError,
  2137. format("note: keeping build directory `%2%'")
  2138. % drvPath % tmpDir);
  2139. chmod(tmpDir.c_str(), 0755);
  2140. // Change the ownership if clientUid is set. Never change the
  2141. // ownership or the group to "root" for security reasons.
  2142. if (settings.clientUid != (uid_t) -1 && settings.clientUid != 0) {
  2143. _chown(tmpDir, settings.clientUid,
  2144. settings.clientGid != 0 ? settings.clientGid : -1);
  2145. }
  2146. }
  2147. else
  2148. deletePath(tmpDir);
  2149. tmpDir = "";
  2150. }
  2151. }
  2152. void DerivationGoal::handleChildOutput(int fd, const string & data)
  2153. {
  2154. if ((hook && fd == hook->builderOut.readSide) ||
  2155. (!hook && fd == builderOut.readSide))
  2156. {
  2157. logSize += data.size();
  2158. if (settings.maxLogSize && logSize > settings.maxLogSize) {
  2159. printMsg(lvlError,
  2160. format("%1% killed after writing more than %2% bytes of log output")
  2161. % getName() % settings.maxLogSize);
  2162. timedOut(); // not really a timeout, but close enough
  2163. return;
  2164. }
  2165. if (verbosity >= settings.buildVerbosity)
  2166. writeToStderr(data);
  2167. if (gzLogFile) {
  2168. if (data.size() > 0) {
  2169. int count, err;
  2170. count = gzwrite(gzLogFile, data.data(), data.size());
  2171. if (count == 0) throw Error(format("cannot write to compressed log file (gzip error = %1%)") % gzerror(gzLogFile, &err));
  2172. }
  2173. #if HAVE_BZLIB_H
  2174. } else if (bzLogFile) {
  2175. int err;
  2176. BZ2_bzWrite(&err, bzLogFile, (unsigned char *) data.data(), data.size());
  2177. if (err != BZ_OK) throw Error(format("cannot write to compressed log file (BZip2 error = %1%)") % err);
  2178. #endif
  2179. } else if (fdLogFile != -1)
  2180. writeFull(fdLogFile, data);
  2181. }
  2182. if (hook && fd == hook->fromHook.readSide)
  2183. writeToStderr(data);
  2184. }
  2185. void DerivationGoal::handleEOF(int fd)
  2186. {
  2187. worker.wakeUp(shared_from_this());
  2188. }
  2189. PathSet DerivationGoal::checkPathValidity(bool returnValid, bool checkHash)
  2190. {
  2191. PathSet result;
  2192. foreach (DerivationOutputs::iterator, i, drv.outputs) {
  2193. if (!wantOutput(i->first, wantedOutputs)) continue;
  2194. bool good =
  2195. worker.store.isValidPath(i->second.path) &&
  2196. (!checkHash || worker.store.pathContentsGood(i->second.path));
  2197. if (good == returnValid) result.insert(i->second.path);
  2198. }
  2199. return result;
  2200. }
  2201. bool DerivationGoal::pathFailed(const Path & path)
  2202. {
  2203. if (!settings.cacheFailure) return false;
  2204. if (!worker.store.hasPathFailed(path)) return false;
  2205. printMsg(lvlError, format("builder for `%1%' failed previously (cached)") % path);
  2206. if (settings.printBuildTrace)
  2207. printMsg(lvlError, format("@ build-failed %1% - cached") % drvPath);
  2208. done(BuildResult::CachedFailure);
  2209. return true;
  2210. }
  2211. Path DerivationGoal::addHashRewrite(const Path & path)
  2212. {
  2213. string h1 = string(path, settings.nixStore.size() + 1, 32);
  2214. string h2 = string(printHash32(hashString(htSHA256, "rewrite:" + drvPath + ":" + path)), 0, 32);
  2215. Path p = settings.nixStore + "/" + h2 + string(path, settings.nixStore.size() + 33);
  2216. if (pathExists(p)) deletePath(p);
  2217. assert(path.size() == p.size());
  2218. rewritesToTmp[h1] = h2;
  2219. rewritesFromTmp[h2] = h1;
  2220. redirectedOutputs[path] = p;
  2221. printMsg(lvlChatty, format("output '%1%' redirected to '%2%'")
  2222. % path % p);
  2223. return p;
  2224. }
  2225. void DerivationGoal::done(BuildResult::Status status, const string & msg)
  2226. {
  2227. result.status = status;
  2228. result.errorMsg = msg;
  2229. amDone(result.success() ? ecSuccess : ecFailed);
  2230. if (result.status == BuildResult::TimedOut)
  2231. worker.timedOut = true;
  2232. if (result.status == BuildResult::PermanentFailure || result.status == BuildResult::CachedFailure)
  2233. worker.permanentFailure = true;
  2234. }
  2235. //////////////////////////////////////////////////////////////////////
  2236. class SubstitutionGoal : public Goal
  2237. {
  2238. friend class Worker;
  2239. private:
  2240. /* The store path that should be realised through a substitute. */
  2241. Path storePath;
  2242. /* The remaining substituters. */
  2243. Paths subs;
  2244. /* The current substituter. */
  2245. Path sub;
  2246. /* Whether any substituter can realise this path */
  2247. bool hasSubstitute;
  2248. /* Path info returned by the substituter's query info operation. */
  2249. SubstitutablePathInfo info;
  2250. /* Pipe for the substituter's standard output. */
  2251. Pipe outPipe;
  2252. /* Pipe for the substituter's standard error. */
  2253. Pipe logPipe;
  2254. /* The process ID of the builder. */
  2255. Pid pid;
  2256. /* Lock on the store path. */
  2257. std::shared_ptr<PathLocks> outputLock;
  2258. /* Whether to try to repair a valid path. */
  2259. bool repair;
  2260. /* Location where we're downloading the substitute. Differs from
  2261. storePath when doing a repair. */
  2262. Path destPath;
  2263. typedef void (SubstitutionGoal::*GoalState)();
  2264. GoalState state;
  2265. public:
  2266. SubstitutionGoal(const Path & storePath, Worker & worker, bool repair = false);
  2267. ~SubstitutionGoal();
  2268. void timedOut();
  2269. string key()
  2270. {
  2271. /* "a$" ensures substitution goals happen before derivation
  2272. goals. */
  2273. return "a$" + storePathToName(storePath) + "$" + storePath;
  2274. }
  2275. void work();
  2276. /* The states. */
  2277. void init();
  2278. void tryNext();
  2279. void gotInfo();
  2280. void referencesValid();
  2281. void tryToRun();
  2282. void finished();
  2283. /* Callback used by the worker to write to the log. */
  2284. void handleChildOutput(int fd, const string & data);
  2285. void handleEOF(int fd);
  2286. Path getStorePath() { return storePath; }
  2287. };
  2288. SubstitutionGoal::SubstitutionGoal(const Path & storePath, Worker & worker, bool repair)
  2289. : Goal(worker)
  2290. , hasSubstitute(false)
  2291. , repair(repair)
  2292. {
  2293. this->storePath = storePath;
  2294. state = &SubstitutionGoal::init;
  2295. name = (format("substitution of `%1%'") % storePath).str();
  2296. trace("created");
  2297. }
  2298. SubstitutionGoal::~SubstitutionGoal()
  2299. {
  2300. if (pid != -1) worker.childTerminated(pid);
  2301. }
  2302. void SubstitutionGoal::timedOut()
  2303. {
  2304. if (settings.printBuildTrace)
  2305. printMsg(lvlError, format("@ substituter-failed %1% timeout") % storePath);
  2306. if (pid != -1) {
  2307. pid_t savedPid = pid;
  2308. pid.kill();
  2309. worker.childTerminated(savedPid);
  2310. }
  2311. amDone(ecFailed);
  2312. }
  2313. void SubstitutionGoal::work()
  2314. {
  2315. (this->*state)();
  2316. }
  2317. void SubstitutionGoal::init()
  2318. {
  2319. trace("init");
  2320. worker.store.addTempRoot(storePath);
  2321. /* If the path already exists we're done. */
  2322. if (!repair && worker.store.isValidPath(storePath)) {
  2323. amDone(ecSuccess);
  2324. return;
  2325. }
  2326. if (settings.readOnlyMode)
  2327. throw Error(format("cannot substitute path `%1%' - no write access to the Nix store") % storePath);
  2328. subs = settings.substituters;
  2329. tryNext();
  2330. }
  2331. void SubstitutionGoal::tryNext()
  2332. {
  2333. trace("trying next substituter");
  2334. if (subs.size() == 0) {
  2335. /* None left. Terminate this goal and let someone else deal
  2336. with it. */
  2337. debug(format("path `%1%' is required, but there is no substituter that can build it") % storePath);
  2338. /* Hack: don't indicate failure if there were no substituters.
  2339. In that case the calling derivation should just do a
  2340. build. */
  2341. amDone(hasSubstitute ? ecFailed : ecNoSubstituters);
  2342. return;
  2343. }
  2344. sub = subs.front();
  2345. subs.pop_front();
  2346. SubstitutablePathInfos infos;
  2347. PathSet dummy(singleton<PathSet>(storePath));
  2348. worker.store.querySubstitutablePathInfos(sub, dummy, infos);
  2349. SubstitutablePathInfos::iterator k = infos.find(storePath);
  2350. if (k == infos.end()) { tryNext(); return; }
  2351. info = k->second;
  2352. hasSubstitute = true;
  2353. /* To maintain the closure invariant, we first have to realise the
  2354. paths referenced by this one. */
  2355. foreach (PathSet::iterator, i, info.references)
  2356. if (*i != storePath) /* ignore self-references */
  2357. addWaitee(worker.makeSubstitutionGoal(*i));
  2358. if (waitees.empty()) /* to prevent hang (no wake-up event) */
  2359. referencesValid();
  2360. else
  2361. state = &SubstitutionGoal::referencesValid;
  2362. }
  2363. void SubstitutionGoal::referencesValid()
  2364. {
  2365. trace("all references realised");
  2366. if (nrFailed > 0) {
  2367. debug(format("some references of path `%1%' could not be realised") % storePath);
  2368. amDone(nrNoSubstituters > 0 || nrIncompleteClosure > 0 ? ecIncompleteClosure : ecFailed);
  2369. return;
  2370. }
  2371. foreach (PathSet::iterator, i, info.references)
  2372. if (*i != storePath) /* ignore self-references */
  2373. assert(worker.store.isValidPath(*i));
  2374. state = &SubstitutionGoal::tryToRun;
  2375. worker.wakeUp(shared_from_this());
  2376. }
  2377. void SubstitutionGoal::tryToRun()
  2378. {
  2379. trace("trying to run");
  2380. /* Make sure that we are allowed to start a build. Note that even
  2381. is maxBuildJobs == 0 (no local builds allowed), we still allow
  2382. a substituter to run. This is because substitutions cannot be
  2383. distributed to another machine via the build hook. */
  2384. if (worker.getNrLocalBuilds() >= (settings.maxBuildJobs == 0 ? 1 : settings.maxBuildJobs)) {
  2385. worker.waitForBuildSlot(shared_from_this());
  2386. return;
  2387. }
  2388. /* Maybe a derivation goal has already locked this path
  2389. (exceedingly unlikely, since it should have used a substitute
  2390. first, but let's be defensive). */
  2391. outputLock.reset(); // make sure this goal's lock is gone
  2392. if (pathIsLockedByMe(storePath)) {
  2393. debug(format("restarting substitution of `%1%' because it's locked by another goal")
  2394. % storePath);
  2395. worker.waitForAnyGoal(shared_from_this());
  2396. return; /* restart in the tryToRun() state when another goal finishes */
  2397. }
  2398. /* Acquire a lock on the output path. */
  2399. outputLock = std::shared_ptr<PathLocks>(new PathLocks);
  2400. if (!outputLock->lockPaths(singleton<PathSet>(storePath), "", false)) {
  2401. worker.waitForAWhile(shared_from_this());
  2402. return;
  2403. }
  2404. /* Check again whether the path is invalid. */
  2405. if (!repair && worker.store.isValidPath(storePath)) {
  2406. debug(format("store path `%1%' has become valid") % storePath);
  2407. outputLock->setDeletion(true);
  2408. amDone(ecSuccess);
  2409. return;
  2410. }
  2411. printMsg(lvlInfo, format("fetching path `%1%'...") % storePath);
  2412. outPipe.create();
  2413. logPipe.create();
  2414. destPath = repair ? storePath + ".tmp" : storePath;
  2415. /* Remove the (stale) output path if it exists. */
  2416. if (pathExists(destPath))
  2417. deletePath(destPath);
  2418. worker.store.setSubstituterEnv();
  2419. /* Fill in the arguments. */
  2420. Strings args;
  2421. args.push_back(baseNameOf(sub));
  2422. args.push_back("--substitute");
  2423. args.push_back(storePath);
  2424. args.push_back(destPath);
  2425. /* Fork the substitute program. */
  2426. pid = startProcess([&]() {
  2427. commonChildInit(logPipe);
  2428. if (dup2(outPipe.writeSide, STDOUT_FILENO) == -1)
  2429. throw SysError("cannot dup output pipe into stdout");
  2430. execv(sub.c_str(), stringsToCharPtrs(args).data());
  2431. throw SysError(format("executing `%1%'") % sub);
  2432. });
  2433. pid.setSeparatePG(true);
  2434. pid.setKillSignal(SIGTERM);
  2435. outPipe.writeSide.close();
  2436. logPipe.writeSide.close();
  2437. worker.childStarted(shared_from_this(),
  2438. pid, singleton<set<int> >(logPipe.readSide), true, true);
  2439. state = &SubstitutionGoal::finished;
  2440. if (settings.printBuildTrace)
  2441. printMsg(lvlError, format("@ substituter-started %1% %2%") % storePath % sub);
  2442. }
  2443. void SubstitutionGoal::finished()
  2444. {
  2445. trace("substitute finished");
  2446. /* Since we got an EOF on the logger pipe, the substitute is
  2447. presumed to have terminated. */
  2448. pid_t savedPid = pid;
  2449. int status = pid.wait(true);
  2450. /* So the child is gone now. */
  2451. worker.childTerminated(savedPid);
  2452. /* Close the read side of the logger pipe. */
  2453. logPipe.readSide.close();
  2454. /* Get the hash info from stdout. */
  2455. string dummy = readLine(outPipe.readSide);
  2456. string expectedHashStr = statusOk(status) ? readLine(outPipe.readSide) : "";
  2457. outPipe.readSide.close();
  2458. /* Check the exit status and the build result. */
  2459. HashResult hash;
  2460. try {
  2461. if (!statusOk(status))
  2462. throw SubstError(format("fetching path `%1%' %2%")
  2463. % storePath % statusToString(status));
  2464. if (!pathExists(destPath))
  2465. throw SubstError(format("substitute did not produce path `%1%'") % destPath);
  2466. hash = hashPath(htSHA256, destPath);
  2467. /* Verify the expected hash we got from the substituer. */
  2468. if (expectedHashStr != "") {
  2469. size_t n = expectedHashStr.find(':');
  2470. if (n == string::npos)
  2471. throw Error(format("bad hash from substituter: %1%") % expectedHashStr);
  2472. HashType hashType = parseHashType(string(expectedHashStr, 0, n));
  2473. if (hashType == htUnknown)
  2474. throw Error(format("unknown hash algorithm in `%1%'") % expectedHashStr);
  2475. Hash expectedHash = parseHash16or32(hashType, string(expectedHashStr, n + 1));
  2476. Hash actualHash = hashType == htSHA256 ? hash.first : hashPath(hashType, destPath).first;
  2477. if (expectedHash != actualHash)
  2478. throw SubstError(format("hash mismatch in downloaded path `%1%'\n"
  2479. " expected: %2%\n"
  2480. " actual: %3%")
  2481. % storePath % printHash(expectedHash) % printHash(actualHash));
  2482. }
  2483. } catch (SubstError & e) {
  2484. printMsg(lvlInfo, e.msg());
  2485. if (settings.printBuildTrace) {
  2486. printMsg(lvlError, format("@ substituter-failed %1% %2% %3%")
  2487. % storePath % status % e.msg());
  2488. }
  2489. /* Try the next substitute. */
  2490. state = &SubstitutionGoal::tryNext;
  2491. worker.wakeUp(shared_from_this());
  2492. return;
  2493. }
  2494. if (repair) replaceValidPath(storePath, destPath);
  2495. canonicalisePathMetaData(storePath, -1);
  2496. worker.store.optimisePath(storePath); // FIXME: combine with hashPath()
  2497. ValidPathInfo info2;
  2498. info2.path = storePath;
  2499. info2.hash = hash.first;
  2500. info2.narSize = hash.second;
  2501. info2.references = info.references;
  2502. info2.deriver = info.deriver;
  2503. worker.store.registerValidPath(info2);
  2504. outputLock->setDeletion(true);
  2505. outputLock.reset();
  2506. worker.store.markContentsGood(storePath);
  2507. printMsg(lvlChatty,
  2508. format("substitution of path `%1%' succeeded") % storePath);
  2509. if (settings.printBuildTrace)
  2510. printMsg(lvlError, format("@ substituter-succeeded %1%") % storePath);
  2511. amDone(ecSuccess);
  2512. }
  2513. void SubstitutionGoal::handleChildOutput(int fd, const string & data)
  2514. {
  2515. assert(fd == logPipe.readSide);
  2516. if (verbosity >= settings.buildVerbosity) writeToStderr(data);
  2517. /* Don't write substitution output to a log file for now. We
  2518. probably should, though. */
  2519. }
  2520. void SubstitutionGoal::handleEOF(int fd)
  2521. {
  2522. if (fd == logPipe.readSide) worker.wakeUp(shared_from_this());
  2523. }
  2524. //////////////////////////////////////////////////////////////////////
  2525. static bool working = false;
  2526. Worker::Worker(LocalStore & store)
  2527. : store(store)
  2528. {
  2529. /* Debugging: prevent recursive workers. */
  2530. if (working) abort();
  2531. working = true;
  2532. nrLocalBuilds = 0;
  2533. lastWokenUp = 0;
  2534. permanentFailure = false;
  2535. timedOut = false;
  2536. }
  2537. Worker::~Worker()
  2538. {
  2539. working = false;
  2540. /* Explicitly get rid of all strong pointers now. After this all
  2541. goals that refer to this worker should be gone. (Otherwise we
  2542. are in trouble, since goals may call childTerminated() etc. in
  2543. their destructors). */
  2544. topGoals.clear();
  2545. }
  2546. GoalPtr Worker::makeDerivationGoal(const Path & path,
  2547. const StringSet & wantedOutputs, BuildMode buildMode)
  2548. {
  2549. GoalPtr goal = derivationGoals[path].lock();
  2550. if (!goal) {
  2551. goal = GoalPtr(new DerivationGoal(path, wantedOutputs, *this, buildMode));
  2552. derivationGoals[path] = goal;
  2553. wakeUp(goal);
  2554. } else
  2555. (dynamic_cast<DerivationGoal *>(goal.get()))->addWantedOutputs(wantedOutputs);
  2556. return goal;
  2557. }
  2558. GoalPtr Worker::makeSubstitutionGoal(const Path & path, bool repair)
  2559. {
  2560. GoalPtr goal = substitutionGoals[path].lock();
  2561. if (!goal) {
  2562. goal = GoalPtr(new SubstitutionGoal(path, *this, repair));
  2563. substitutionGoals[path] = goal;
  2564. wakeUp(goal);
  2565. }
  2566. return goal;
  2567. }
  2568. static void removeGoal(GoalPtr goal, WeakGoalMap & goalMap)
  2569. {
  2570. /* !!! inefficient */
  2571. for (WeakGoalMap::iterator i = goalMap.begin();
  2572. i != goalMap.end(); )
  2573. if (i->second.lock() == goal) {
  2574. WeakGoalMap::iterator j = i; ++j;
  2575. goalMap.erase(i);
  2576. i = j;
  2577. }
  2578. else ++i;
  2579. }
  2580. void Worker::removeGoal(GoalPtr goal)
  2581. {
  2582. nix::removeGoal(goal, derivationGoals);
  2583. nix::removeGoal(goal, substitutionGoals);
  2584. if (topGoals.find(goal) != topGoals.end()) {
  2585. topGoals.erase(goal);
  2586. /* If a top-level goal failed, then kill all other goals
  2587. (unless keepGoing was set). */
  2588. if (goal->getExitCode() == Goal::ecFailed && !settings.keepGoing)
  2589. topGoals.clear();
  2590. }
  2591. /* Wake up goals waiting for any goal to finish. */
  2592. foreach (WeakGoals::iterator, i, waitingForAnyGoal) {
  2593. GoalPtr goal = i->lock();
  2594. if (goal) wakeUp(goal);
  2595. }
  2596. waitingForAnyGoal.clear();
  2597. }
  2598. void Worker::wakeUp(GoalPtr goal)
  2599. {
  2600. goal->trace("woken up");
  2601. addToWeakGoals(awake, goal);
  2602. }
  2603. unsigned Worker::getNrLocalBuilds()
  2604. {
  2605. return nrLocalBuilds;
  2606. }
  2607. void Worker::childStarted(GoalPtr goal,
  2608. pid_t pid, const set<int> & fds, bool inBuildSlot,
  2609. bool respectTimeouts)
  2610. {
  2611. Child child;
  2612. child.goal = goal;
  2613. child.fds = fds;
  2614. child.timeStarted = child.lastOutput = time(0);
  2615. child.inBuildSlot = inBuildSlot;
  2616. child.respectTimeouts = respectTimeouts;
  2617. children[pid] = child;
  2618. if (inBuildSlot) nrLocalBuilds++;
  2619. }
  2620. void Worker::childTerminated(pid_t pid, bool wakeSleepers)
  2621. {
  2622. assert(pid != -1); /* common mistake */
  2623. Children::iterator i = children.find(pid);
  2624. assert(i != children.end());
  2625. if (i->second.inBuildSlot) {
  2626. assert(nrLocalBuilds > 0);
  2627. nrLocalBuilds--;
  2628. }
  2629. children.erase(pid);
  2630. if (wakeSleepers) {
  2631. /* Wake up goals waiting for a build slot. */
  2632. foreach (WeakGoals::iterator, i, wantingToBuild) {
  2633. GoalPtr goal = i->lock();
  2634. if (goal) wakeUp(goal);
  2635. }
  2636. wantingToBuild.clear();
  2637. }
  2638. }
  2639. void Worker::waitForBuildSlot(GoalPtr goal)
  2640. {
  2641. debug("wait for build slot");
  2642. if (getNrLocalBuilds() < settings.maxBuildJobs)
  2643. wakeUp(goal); /* we can do it right away */
  2644. else
  2645. addToWeakGoals(wantingToBuild, goal);
  2646. }
  2647. void Worker::waitForAnyGoal(GoalPtr goal)
  2648. {
  2649. debug("wait for any goal");
  2650. addToWeakGoals(waitingForAnyGoal, goal);
  2651. }
  2652. void Worker::waitForAWhile(GoalPtr goal)
  2653. {
  2654. debug("wait for a while");
  2655. addToWeakGoals(waitingForAWhile, goal);
  2656. }
  2657. void Worker::run(const Goals & _topGoals)
  2658. {
  2659. foreach (Goals::iterator, i, _topGoals) topGoals.insert(*i);
  2660. startNest(nest, lvlDebug, format("entered goal loop"));
  2661. while (1) {
  2662. checkInterrupt();
  2663. /* Call every wake goal (in the ordering established by
  2664. CompareGoalPtrs). */
  2665. while (!awake.empty() && !topGoals.empty()) {
  2666. Goals awake2;
  2667. for (auto & i : awake) {
  2668. GoalPtr goal = i.lock();
  2669. if (goal) awake2.insert(goal);
  2670. }
  2671. awake.clear();
  2672. for (auto & goal : awake2) {
  2673. checkInterrupt();
  2674. goal->work();
  2675. if (topGoals.empty()) break; // stuff may have been cancelled
  2676. }
  2677. }
  2678. if (topGoals.empty()) break;
  2679. /* Wait for input. */
  2680. if (!children.empty() || !waitingForAWhile.empty())
  2681. waitForInput();
  2682. else {
  2683. if (awake.empty() && settings.maxBuildJobs == 0) throw Error(
  2684. "unable to start any build; either increase `--max-jobs' "
  2685. "or enable distributed builds");
  2686. assert(!awake.empty());
  2687. }
  2688. }
  2689. /* If --keep-going is not set, it's possible that the main goal
  2690. exited while some of its subgoals were still active. But if
  2691. --keep-going *is* set, then they must all be finished now. */
  2692. assert(!settings.keepGoing || awake.empty());
  2693. assert(!settings.keepGoing || wantingToBuild.empty());
  2694. assert(!settings.keepGoing || children.empty());
  2695. }
  2696. void Worker::waitForInput()
  2697. {
  2698. printMsg(lvlVomit, "waiting for children");
  2699. /* Process output from the file descriptors attached to the
  2700. children, namely log output and output path creation commands.
  2701. We also use this to detect child termination: if we get EOF on
  2702. the logger pipe of a build, we assume that the builder has
  2703. terminated. */
  2704. bool useTimeout = false;
  2705. struct timeval timeout;
  2706. timeout.tv_usec = 0;
  2707. time_t before = time(0);
  2708. /* If we're monitoring for silence on stdout/stderr, or if there
  2709. is a build timeout, then wait for input until the first
  2710. deadline for any child. */
  2711. assert(sizeof(time_t) >= sizeof(long));
  2712. time_t nearest = LONG_MAX; // nearest deadline
  2713. foreach (Children::iterator, i, children) {
  2714. if (!i->second.respectTimeouts) continue;
  2715. if (settings.maxSilentTime != 0)
  2716. nearest = std::min(nearest, i->second.lastOutput + settings.maxSilentTime);
  2717. if (settings.buildTimeout != 0)
  2718. nearest = std::min(nearest, i->second.timeStarted + settings.buildTimeout);
  2719. }
  2720. if (nearest != LONG_MAX) {
  2721. timeout.tv_sec = std::max((time_t) 1, nearest - before);
  2722. useTimeout = true;
  2723. printMsg(lvlVomit, format("sleeping %1% seconds") % timeout.tv_sec);
  2724. }
  2725. /* If we are polling goals that are waiting for a lock, then wake
  2726. up after a few seconds at most. */
  2727. if (!waitingForAWhile.empty()) {
  2728. useTimeout = true;
  2729. if (lastWokenUp == 0)
  2730. printMsg(lvlError, "waiting for locks or build slots...");
  2731. if (lastWokenUp == 0 || lastWokenUp > before) lastWokenUp = before;
  2732. timeout.tv_sec = std::max((time_t) 1, (time_t) (lastWokenUp + settings.pollInterval - before));
  2733. } else lastWokenUp = 0;
  2734. using namespace std;
  2735. /* Use select() to wait for the input side of any logger pipe to
  2736. become `available'. Note that `available' (i.e., non-blocking)
  2737. includes EOF. */
  2738. fd_set fds;
  2739. FD_ZERO(&fds);
  2740. int fdMax = 0;
  2741. foreach (Children::iterator, i, children) {
  2742. foreach (set<int>::iterator, j, i->second.fds) {
  2743. FD_SET(*j, &fds);
  2744. if (*j >= fdMax) fdMax = *j + 1;
  2745. }
  2746. }
  2747. if (select(fdMax, &fds, 0, 0, useTimeout ? &timeout : 0) == -1) {
  2748. if (errno == EINTR) return;
  2749. throw SysError("waiting for input");
  2750. }
  2751. time_t after = time(0);
  2752. /* Process all available file descriptors. */
  2753. /* Since goals may be canceled from inside the loop below (causing
  2754. them go be erased from the `children' map), we have to be
  2755. careful that we don't keep iterators alive across calls to
  2756. timedOut(). */
  2757. set<pid_t> pids;
  2758. foreach (Children::iterator, i, children) pids.insert(i->first);
  2759. foreach (set<pid_t>::iterator, i, pids) {
  2760. checkInterrupt();
  2761. Children::iterator j = children.find(*i);
  2762. if (j == children.end()) continue; // child destroyed
  2763. GoalPtr goal = j->second.goal.lock();
  2764. assert(goal);
  2765. set<int> fds2(j->second.fds);
  2766. foreach (set<int>::iterator, k, fds2) {
  2767. if (FD_ISSET(*k, &fds)) {
  2768. unsigned char buffer[4096];
  2769. ssize_t rd = read(*k, buffer, sizeof(buffer));
  2770. if (rd == -1) {
  2771. if (errno != EINTR)
  2772. throw SysError(format("reading from %1%")
  2773. % goal->getName());
  2774. } else if (rd == 0) {
  2775. debug(format("%1%: got EOF") % goal->getName());
  2776. goal->handleEOF(*k);
  2777. j->second.fds.erase(*k);
  2778. } else {
  2779. printMsg(lvlVomit, format("%1%: read %2% bytes")
  2780. % goal->getName() % rd);
  2781. string data((char *) buffer, rd);
  2782. j->second.lastOutput = after;
  2783. goal->handleChildOutput(*k, data);
  2784. }
  2785. }
  2786. }
  2787. if (goal->getExitCode() == Goal::ecBusy &&
  2788. settings.maxSilentTime != 0 &&
  2789. j->second.respectTimeouts &&
  2790. after - j->second.lastOutput >= (time_t) settings.maxSilentTime)
  2791. {
  2792. printMsg(lvlError,
  2793. format("%1% timed out after %2% seconds of silence")
  2794. % goal->getName() % settings.maxSilentTime);
  2795. goal->timedOut();
  2796. }
  2797. else if (goal->getExitCode() == Goal::ecBusy &&
  2798. settings.buildTimeout != 0 &&
  2799. j->second.respectTimeouts &&
  2800. after - j->second.timeStarted >= (time_t) settings.buildTimeout)
  2801. {
  2802. printMsg(lvlError,
  2803. format("%1% timed out after %2% seconds")
  2804. % goal->getName() % settings.buildTimeout);
  2805. goal->timedOut();
  2806. }
  2807. }
  2808. if (!waitingForAWhile.empty() && lastWokenUp + settings.pollInterval <= after) {
  2809. lastWokenUp = after;
  2810. foreach (WeakGoals::iterator, i, waitingForAWhile) {
  2811. GoalPtr goal = i->lock();
  2812. if (goal) wakeUp(goal);
  2813. }
  2814. waitingForAWhile.clear();
  2815. }
  2816. }
  2817. unsigned int Worker::exitStatus()
  2818. {
  2819. return timedOut ? 101 : (permanentFailure ? 100 : 1);
  2820. }
  2821. //////////////////////////////////////////////////////////////////////
  2822. void LocalStore::buildPaths(const PathSet & drvPaths, BuildMode buildMode)
  2823. {
  2824. startNest(nest, lvlDebug,
  2825. format("building %1%") % showPaths(drvPaths));
  2826. Worker worker(*this);
  2827. Goals goals;
  2828. foreach (PathSet::const_iterator, i, drvPaths) {
  2829. DrvPathWithOutputs i2 = parseDrvPathWithOutputs(*i);
  2830. if (isDerivation(i2.first))
  2831. goals.insert(worker.makeDerivationGoal(i2.first, i2.second, buildMode));
  2832. else
  2833. goals.insert(worker.makeSubstitutionGoal(*i, buildMode));
  2834. }
  2835. worker.run(goals);
  2836. PathSet failed;
  2837. foreach (Goals::iterator, i, goals)
  2838. if ((*i)->getExitCode() == Goal::ecFailed) {
  2839. DerivationGoal * i2 = dynamic_cast<DerivationGoal *>(i->get());
  2840. if (i2) failed.insert(i2->getDrvPath());
  2841. else failed.insert(dynamic_cast<SubstitutionGoal *>(i->get())->getStorePath());
  2842. }
  2843. if (!failed.empty())
  2844. throw Error(format("build of %1% failed") % showPaths(failed), worker.exitStatus());
  2845. }
  2846. void LocalStore::ensurePath(const Path & path)
  2847. {
  2848. /* If the path is already valid, we're done. */
  2849. if (isValidPath(path)) return;
  2850. Worker worker(*this);
  2851. GoalPtr goal = worker.makeSubstitutionGoal(path);
  2852. Goals goals = singleton<Goals>(goal);
  2853. worker.run(goals);
  2854. if (goal->getExitCode() != Goal::ecSuccess)
  2855. throw Error(format("path `%1%' does not exist and cannot be created") % path, worker.exitStatus());
  2856. }
  2857. void LocalStore::repairPath(const Path & path)
  2858. {
  2859. Worker worker(*this);
  2860. GoalPtr goal = worker.makeSubstitutionGoal(path, true);
  2861. Goals goals = singleton<Goals>(goal);
  2862. worker.run(goals);
  2863. if (goal->getExitCode() != Goal::ecSuccess) {
  2864. /* Since substituting the path didn't work, if we have a valid
  2865. deriver, then rebuild the deriver. */
  2866. Path deriver = queryDeriver(path);
  2867. if (deriver != "" && isValidPath(deriver)) {
  2868. goals.clear();
  2869. goals.insert(worker.makeDerivationGoal(deriver, StringSet(), bmRepair));
  2870. worker.run(goals);
  2871. } else
  2872. throw Error(format("cannot repair path `%1%'") % path, worker.exitStatus());
  2873. }
  2874. }
  2875. }