build.cc 119 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683
  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 build 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 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. || (platform == "armhf-linux" && settings.thisSystem == "aarch64-linux")
  931. #endif
  932. ;
  933. }
  934. static string get(const StringPairs & map, const string & key, const string & def = "")
  935. {
  936. StringPairs::const_iterator i = map.find(key);
  937. return i == map.end() ? def : i->second;
  938. }
  939. bool willBuildLocally(const Derivation & drv)
  940. {
  941. return get(drv.env, "preferLocalBuild") == "1" && canBuildLocally(drv.platform);
  942. }
  943. bool substitutesAllowed(const Derivation & drv)
  944. {
  945. return get(drv.env, "allowSubstitutes", "1") == "1";
  946. }
  947. void DerivationGoal::tryToBuild()
  948. {
  949. trace("trying to build");
  950. /* Check for the possibility that some other goal in this process
  951. has locked the output since we checked in haveDerivation().
  952. (It can't happen between here and the lockPaths() call below
  953. because we're not allowing multi-threading.) If so, put this
  954. goal to sleep until another goal finishes, then try again. */
  955. foreach (DerivationOutputs::iterator, i, drv.outputs)
  956. if (pathIsLockedByMe(i->second.path)) {
  957. debug(format("putting derivation `%1%' to sleep because `%2%' is locked by another goal")
  958. % drvPath % i->second.path);
  959. worker.waitForAnyGoal(shared_from_this());
  960. return;
  961. }
  962. /* Obtain locks on all output paths. The locks are automatically
  963. released when we exit this function or the client crashes. If we
  964. can't acquire the lock, then continue; hopefully some other
  965. goal can start a build, and if not, the main loop will sleep a
  966. few seconds and then retry this goal. */
  967. if (!outputLocks.lockPaths(outputPaths(drv), "", false)) {
  968. worker.waitForAWhile(shared_from_this());
  969. return;
  970. }
  971. /* Now check again whether the outputs are valid. This is because
  972. another process may have started building in parallel. After
  973. it has finished and released the locks, we can (and should)
  974. reuse its results. (Strictly speaking the first check can be
  975. omitted, but that would be less efficient.) Note that since we
  976. now hold the locks on the output paths, no other process can
  977. build this derivation, so no further checks are necessary. */
  978. validPaths = checkPathValidity(true, buildMode == bmRepair);
  979. if (buildMode != bmCheck && validPaths.size() == drv.outputs.size()) {
  980. debug(format("skipping build of derivation `%1%', someone beat us to it") % drvPath);
  981. outputLocks.setDeletion(true);
  982. done(BuildResult::AlreadyValid);
  983. return;
  984. }
  985. missingPaths = outputPaths(drv);
  986. if (buildMode != bmCheck)
  987. foreach (PathSet::iterator, i, validPaths) missingPaths.erase(*i);
  988. /* If any of the outputs already exist but are not valid, delete
  989. them. */
  990. foreach (DerivationOutputs::iterator, i, drv.outputs) {
  991. Path path = i->second.path;
  992. if (worker.store.isValidPath(path)) continue;
  993. if (!pathExists(path)) continue;
  994. debug(format("removing invalid path `%1%'") % path);
  995. deletePath(path);
  996. }
  997. /* Check again whether any output previously failed to build,
  998. because some other process may have tried and failed before we
  999. acquired the lock. */
  1000. foreach (DerivationOutputs::iterator, i, drv.outputs)
  1001. if (pathFailed(i->second.path)) return;
  1002. /* Don't do a remote build if the derivation has the attribute
  1003. `preferLocalBuild' set. Also, check and repair modes are only
  1004. supported for local builds. */
  1005. bool buildLocally = buildMode != bmNormal || willBuildLocally(drv);
  1006. /* Is the build hook willing to accept this job? */
  1007. if (!buildLocally) {
  1008. switch (tryBuildHook()) {
  1009. case rpAccept:
  1010. /* Yes, it has started doing so. Wait until we get
  1011. EOF from the hook. */
  1012. state = &DerivationGoal::buildDone;
  1013. return;
  1014. case rpPostpone:
  1015. /* Not now; wait until at least one child finishes or
  1016. the wake-up timeout expires. */
  1017. worker.waitForAWhile(shared_from_this());
  1018. outputLocks.unlock();
  1019. return;
  1020. case rpDecline:
  1021. /* We should do it ourselves. */
  1022. break;
  1023. }
  1024. }
  1025. /* Make sure that we are allowed to start a build. If this
  1026. derivation prefers to be done locally, do it even if
  1027. maxBuildJobs is 0. */
  1028. unsigned int curBuilds = worker.getNrLocalBuilds();
  1029. if (curBuilds >= settings.maxBuildJobs && !(buildLocally && curBuilds == 0)) {
  1030. worker.waitForBuildSlot(shared_from_this());
  1031. outputLocks.unlock();
  1032. return;
  1033. }
  1034. try {
  1035. /* Okay, we have to build. */
  1036. startBuilder();
  1037. } catch (BuildError & e) {
  1038. printMsg(lvlError, e.msg());
  1039. outputLocks.unlock();
  1040. buildUser.release();
  1041. if (settings.printBuildTrace)
  1042. printMsg(lvlError, format("@ build-failed %1% - %2% %3%")
  1043. % drvPath % 0 % e.msg());
  1044. worker.permanentFailure = true;
  1045. done(BuildResult::InputRejected, e.msg());
  1046. return;
  1047. }
  1048. /* This state will be reached when we get EOF on the child's
  1049. log pipe. */
  1050. state = &DerivationGoal::buildDone;
  1051. }
  1052. void replaceValidPath(const Path & storePath, const Path tmpPath)
  1053. {
  1054. /* We can't atomically replace storePath (the original) with
  1055. tmpPath (the replacement), so we have to move it out of the
  1056. way first. We'd better not be interrupted here, because if
  1057. we're repairing (say) Glibc, we end up with a broken system. */
  1058. Path oldPath = (format("%1%.old-%2%-%3%") % storePath % getpid() % rand()).str();
  1059. if (pathExists(storePath))
  1060. rename(storePath.c_str(), oldPath.c_str());
  1061. if (rename(tmpPath.c_str(), storePath.c_str()) == -1)
  1062. throw SysError(format("moving `%1%' to `%2%'") % tmpPath % storePath);
  1063. if (pathExists(oldPath))
  1064. deletePath(oldPath);
  1065. }
  1066. MakeError(NotDeterministic, BuildError)
  1067. void DerivationGoal::buildDone()
  1068. {
  1069. trace("build done");
  1070. /* Since we got an EOF on the logger pipe, the builder is presumed
  1071. to have terminated. In fact, the builder could also have
  1072. simply have closed its end of the pipe --- just don't do that
  1073. :-) */
  1074. int status;
  1075. pid_t savedPid;
  1076. if (hook) {
  1077. savedPid = hook->pid;
  1078. status = hook->pid.wait(true);
  1079. } else {
  1080. /* !!! this could block! security problem! solution: kill the
  1081. child */
  1082. savedPid = pid;
  1083. status = pid.wait(true);
  1084. }
  1085. debug(format("builder process for `%1%' finished") % drvPath);
  1086. /* So the child is gone now. */
  1087. worker.childTerminated(savedPid);
  1088. /* Close the read side of the logger pipe. */
  1089. if (hook) {
  1090. hook->builderOut.readSide.close();
  1091. hook->fromHook.readSide.close();
  1092. }
  1093. else builderOut.readSide.close();
  1094. /* Close the log file. */
  1095. closeLogFile();
  1096. /* When running under a build user, make sure that all processes
  1097. running under that uid are gone. This is to prevent a
  1098. malicious user from leaving behind a process that keeps files
  1099. open and modifies them after they have been chown'ed to
  1100. root. */
  1101. if (buildUser.enabled()) buildUser.kill();
  1102. bool diskFull = false;
  1103. try {
  1104. /* Check the exit status. */
  1105. if (!statusOk(status)) {
  1106. /* Heuristically check whether the build failure may have
  1107. been caused by a disk full condition. We have no way
  1108. of knowing whether the build actually got an ENOSPC.
  1109. So instead, check if the disk is (nearly) full now. If
  1110. so, we don't mark this build as a permanent failure. */
  1111. #if HAVE_STATVFS
  1112. unsigned long long required = 8ULL * 1024 * 1024; // FIXME: make configurable
  1113. struct statvfs st;
  1114. if (statvfs(settings.nixStore.c_str(), &st) == 0 &&
  1115. (unsigned long long) st.f_bavail * st.f_bsize < required)
  1116. diskFull = true;
  1117. if (statvfs(tmpDir.c_str(), &st) == 0 &&
  1118. (unsigned long long) st.f_bavail * st.f_bsize < required)
  1119. diskFull = true;
  1120. #endif
  1121. deleteTmpDir(false);
  1122. /* Move paths out of the chroot for easier debugging of
  1123. build failures. */
  1124. if (useChroot && buildMode == bmNormal)
  1125. foreach (PathSet::iterator, i, missingPaths)
  1126. if (pathExists(chrootRootDir + *i))
  1127. rename((chrootRootDir + *i).c_str(), i->c_str());
  1128. if (diskFull)
  1129. printMsg(lvlError, "note: build failure may have been caused by lack of free disk space");
  1130. throw BuildError(format("builder for `%1%' %2%")
  1131. % drvPath % statusToString(status));
  1132. }
  1133. /* Compute the FS closure of the outputs and register them as
  1134. being valid. */
  1135. registerOutputs();
  1136. if (buildMode == bmCheck) {
  1137. done(BuildResult::Built);
  1138. return;
  1139. }
  1140. /* Delete unused redirected outputs (when doing hash rewriting). */
  1141. foreach (RedirectedOutputs::iterator, i, redirectedOutputs)
  1142. if (pathExists(i->second)) deletePath(i->second);
  1143. /* Delete the chroot (if we were using one). */
  1144. autoDelChroot.reset(); /* this runs the destructor */
  1145. deleteTmpDir(true);
  1146. /* Repeat the build if necessary. */
  1147. if (curRound++ < nrRounds) {
  1148. outputLocks.unlock();
  1149. buildUser.release();
  1150. state = &DerivationGoal::tryToBuild;
  1151. worker.wakeUp(shared_from_this());
  1152. return;
  1153. }
  1154. /* It is now safe to delete the lock files, since all future
  1155. lockers will see that the output paths are valid; they will
  1156. not create new lock files with the same names as the old
  1157. (unlinked) lock files. */
  1158. outputLocks.setDeletion(true);
  1159. outputLocks.unlock();
  1160. } catch (BuildError & e) {
  1161. if (!hook)
  1162. printMsg(lvlError, e.msg());
  1163. outputLocks.unlock();
  1164. buildUser.release();
  1165. BuildResult::Status st = BuildResult::MiscFailure;
  1166. if (hook && WIFEXITED(status) && WEXITSTATUS(status) == 101) {
  1167. if (settings.printBuildTrace)
  1168. printMsg(lvlError, format("@ build-failed %1% - timeout") % drvPath);
  1169. st = BuildResult::TimedOut;
  1170. }
  1171. else if (hook && (!WIFEXITED(status) || WEXITSTATUS(status) != 100)) {
  1172. if (settings.printBuildTrace)
  1173. printMsg(lvlError, format("@ hook-failed %1% - %2% %3%")
  1174. % drvPath % status % e.msg());
  1175. }
  1176. else {
  1177. if (settings.printBuildTrace)
  1178. printMsg(lvlError, format("@ build-failed %1% - %2% %3%")
  1179. % drvPath % 1 % e.msg());
  1180. st =
  1181. statusOk(status) ? BuildResult::OutputRejected :
  1182. fixedOutput || diskFull ? BuildResult::TransientFailure :
  1183. BuildResult::PermanentFailure;
  1184. /* Register the outputs of this build as "failed" so we
  1185. won't try to build them again (negative caching).
  1186. However, don't do this for fixed-output derivations,
  1187. since they're likely to fail for transient reasons
  1188. (e.g., fetchurl not being able to access the network).
  1189. Hook errors (like communication problems with the
  1190. remote machine) shouldn't be cached either. */
  1191. if (settings.cacheFailure && !fixedOutput && !diskFull)
  1192. foreach (DerivationOutputs::iterator, i, drv.outputs)
  1193. worker.store.registerFailedPath(i->second.path);
  1194. }
  1195. done(st, e.msg());
  1196. return;
  1197. }
  1198. /* Release the build user, if applicable. */
  1199. buildUser.release();
  1200. if (settings.printBuildTrace)
  1201. printMsg(lvlError, format("@ build-succeeded %1% -") % drvPath);
  1202. done(BuildResult::Built);
  1203. }
  1204. HookReply DerivationGoal::tryBuildHook()
  1205. {
  1206. if (!settings.useBuildHook || getEnv("NIX_BUILD_HOOK") == "") return rpDecline;
  1207. if (!worker.hook)
  1208. worker.hook = std::shared_ptr<HookInstance>(new HookInstance);
  1209. /* Tell the hook about system features (beyond the system type)
  1210. required from the build machine. (The hook could parse the
  1211. drv file itself, but this is easier.) */
  1212. Strings features = tokenizeString<Strings>(get(drv.env, "requiredSystemFeatures"));
  1213. foreach (Strings::iterator, i, features) checkStoreName(*i); /* !!! abuse */
  1214. /* Send the request to the hook. */
  1215. writeLine(worker.hook->toHook.writeSide, (format("%1% %2% %3% %4%")
  1216. % (worker.getNrLocalBuilds() < settings.maxBuildJobs ? "1" : "0")
  1217. % drv.platform % drvPath % concatStringsSep(",", features)).str());
  1218. /* Read the first line of input, which should be a word indicating
  1219. whether the hook wishes to perform the build. */
  1220. string reply;
  1221. while (true) {
  1222. string s = readLine(worker.hook->fromHook.readSide);
  1223. if (string(s, 0, 2) == "# ") {
  1224. reply = string(s, 2);
  1225. break;
  1226. }
  1227. s += "\n";
  1228. writeToStderr(s);
  1229. }
  1230. debug(format("hook reply is `%1%'") % reply);
  1231. if (reply == "decline" || reply == "postpone")
  1232. return reply == "decline" ? rpDecline : rpPostpone;
  1233. else if (reply != "accept")
  1234. throw Error(format("bad hook reply `%1%'") % reply);
  1235. printMsg(lvlTalkative, format("using hook to build path(s) %1%") % showPaths(missingPaths));
  1236. hook = worker.hook;
  1237. worker.hook.reset();
  1238. /* Tell the hook all the inputs that have to be copied to the
  1239. remote system. This unfortunately has to contain the entire
  1240. derivation closure to ensure that the validity invariant holds
  1241. on the remote system. (I.e., it's unfortunate that we have to
  1242. list it since the remote system *probably* already has it.) */
  1243. PathSet allInputs;
  1244. allInputs.insert(inputPaths.begin(), inputPaths.end());
  1245. computeFSClosure(worker.store, drvPath, allInputs);
  1246. string s;
  1247. foreach (PathSet::iterator, i, allInputs) { s += *i; s += ' '; }
  1248. writeLine(hook->toHook.writeSide, s);
  1249. /* Tell the hooks the missing outputs that have to be copied back
  1250. from the remote system. */
  1251. s = "";
  1252. foreach (PathSet::iterator, i, missingPaths) { s += *i; s += ' '; }
  1253. writeLine(hook->toHook.writeSide, s);
  1254. hook->toHook.writeSide.close();
  1255. /* Create the log file and pipe. */
  1256. Path logFile = openLogFile();
  1257. set<int> fds;
  1258. fds.insert(hook->fromHook.readSide);
  1259. fds.insert(hook->builderOut.readSide);
  1260. worker.childStarted(shared_from_this(), hook->pid, fds, false, false);
  1261. if (settings.printBuildTrace)
  1262. printMsg(lvlError, format("@ build-started %1% - %2% %3% %4%")
  1263. % drvPath % drv.platform % logFile % hook->pid);
  1264. return rpAccept;
  1265. }
  1266. void chmod_(const Path & path, mode_t mode)
  1267. {
  1268. if (chmod(path.c_str(), mode) == -1)
  1269. throw SysError(format("setting permissions on `%1%'") % path);
  1270. }
  1271. int childEntry(void * arg)
  1272. {
  1273. ((DerivationGoal *) arg)->runChild();
  1274. return 1;
  1275. }
  1276. void DerivationGoal::startBuilder()
  1277. {
  1278. auto f = format(
  1279. buildMode == bmRepair ? "repairing path(s) %1%" :
  1280. buildMode == bmCheck ? "checking path(s) %1%" :
  1281. nrRounds > 1 ? "building path(s) %1% (round %2%/%3%)" :
  1282. "building path(s) %1%");
  1283. f.exceptions(boost::io::all_error_bits ^ boost::io::too_many_args_bit);
  1284. startNest(nest, lvlInfo, f % showPaths(missingPaths) % curRound % nrRounds);
  1285. /* Note: built-in builders are *not* running in a chroot environment so
  1286. that we can easily implement them in Guile without having it as a
  1287. derivation input (they are running under a separate build user,
  1288. though). */
  1289. useChroot = settings.useChroot && !isBuiltin(drv);
  1290. /* Construct the environment passed to the builder. */
  1291. env.clear();
  1292. /* Most shells initialise PATH to some default (/bin:/usr/bin:...) when
  1293. PATH is not set. We don't want this, so we fill it in with some dummy
  1294. value. */
  1295. env["PATH"] = "/path-not-set";
  1296. /* Set HOME to a non-existing path to prevent certain programs from using
  1297. /etc/passwd (or NIS, or whatever) to locate the home directory (for
  1298. example, wget looks for ~/.wgetrc). I.e., these tools use /etc/passwd
  1299. if HOME is not set, but they will just assume that the settings file
  1300. they are looking for does not exist if HOME is set but points to some
  1301. non-existing path. */
  1302. Path homeDir = "/homeless-shelter";
  1303. env["HOME"] = homeDir;
  1304. /* Tell the builder where the store is. Usually they
  1305. shouldn't care, but this is useful for purity checking (e.g.,
  1306. the compiler or linker might only want to accept paths to files
  1307. in the store or in the build directory). */
  1308. env["NIX_STORE"] = settings.nixStore;
  1309. /* The maximum number of cores to utilize for parallel building. */
  1310. env["NIX_BUILD_CORES"] = (format("%d") % settings.buildCores).str();
  1311. /* Add all bindings specified in the derivation. */
  1312. foreach (StringPairs::iterator, i, drv.env)
  1313. env[i->first] = i->second;
  1314. /* Create a temporary directory where the build will take
  1315. place. */
  1316. auto drvName = storePathToName(drvPath);
  1317. tmpDir = createTempDir("", "guix-build-" + drvName, false, false, 0700);
  1318. /* In a sandbox, for determinism, always use the same temporary
  1319. directory. */
  1320. tmpDirInSandbox = useChroot ? canonPath("/tmp", true) + "/guix-build-" + drvName + "-0" : tmpDir;
  1321. /* For convenience, set an environment pointing to the top build
  1322. directory. */
  1323. env["NIX_BUILD_TOP"] = tmpDirInSandbox;
  1324. /* Also set TMPDIR and variants to point to this directory. */
  1325. env["TMPDIR"] = env["TEMPDIR"] = env["TMP"] = env["TEMP"] = tmpDirInSandbox;
  1326. /* Explicitly set PWD to prevent problems with chroot builds. In
  1327. particular, dietlibc cannot figure out the cwd because the
  1328. inode of the current directory doesn't appear in .. (because
  1329. getdents returns the inode of the mount point). */
  1330. env["PWD"] = tmpDirInSandbox;
  1331. /* Compatibility hack with Nix <= 0.7: if this is a fixed-output
  1332. derivation, tell the builder, so that for instance `fetchurl'
  1333. can skip checking the output. On older Nixes, this environment
  1334. variable won't be set, so `fetchurl' will do the check. */
  1335. if (fixedOutput) env["NIX_OUTPUT_CHECKED"] = "1";
  1336. /* *Only* if this is a fixed-output derivation, propagate the
  1337. values of the environment variables specified in the
  1338. `impureEnvVars' attribute to the builder. This allows for
  1339. instance environment variables for proxy configuration such as
  1340. `http_proxy' to be easily passed to downloaders like
  1341. `fetchurl'. Passing such environment variables from the caller
  1342. to the builder is generally impure, but the output of
  1343. fixed-output derivations is by definition pure (since we
  1344. already know the cryptographic hash of the output). */
  1345. if (fixedOutput) {
  1346. Strings varNames = tokenizeString<Strings>(get(drv.env, "impureEnvVars"));
  1347. foreach (Strings::iterator, i, varNames) env[*i] = getEnv(*i);
  1348. }
  1349. /* The `exportReferencesGraph' feature allows the references graph
  1350. to be passed to a builder. This attribute should be a list of
  1351. pairs [name1 path1 name2 path2 ...]. The references graph of
  1352. each `pathN' will be stored in a text file `nameN' in the
  1353. temporary build directory. The text files have the format used
  1354. by `nix-store --register-validity'. However, the deriver
  1355. fields are left empty. */
  1356. string s = get(drv.env, "exportReferencesGraph");
  1357. Strings ss = tokenizeString<Strings>(s);
  1358. if (ss.size() % 2 != 0)
  1359. throw BuildError(format("odd number of tokens in `exportReferencesGraph': `%1%'") % s);
  1360. for (Strings::iterator i = ss.begin(); i != ss.end(); ) {
  1361. string fileName = *i++;
  1362. checkStoreName(fileName); /* !!! abuse of this function */
  1363. /* Check that the store path is valid. */
  1364. Path storePath = *i++;
  1365. if (!isInStore(storePath))
  1366. throw BuildError(format("`exportReferencesGraph' contains a non-store path `%1%'")
  1367. % storePath);
  1368. storePath = toStorePath(storePath);
  1369. if (!worker.store.isValidPath(storePath))
  1370. throw BuildError(format("`exportReferencesGraph' contains an invalid path `%1%'")
  1371. % storePath);
  1372. /* If there are derivations in the graph, then include their
  1373. outputs as well. This is useful if you want to do things
  1374. like passing all build-time dependencies of some path to a
  1375. derivation that builds a NixOS DVD image. */
  1376. PathSet paths, paths2;
  1377. computeFSClosure(worker.store, storePath, paths);
  1378. paths2 = paths;
  1379. foreach (PathSet::iterator, j, paths2) {
  1380. if (isDerivation(*j)) {
  1381. Derivation drv = derivationFromPath(worker.store, *j);
  1382. foreach (DerivationOutputs::iterator, k, drv.outputs)
  1383. computeFSClosure(worker.store, k->second.path, paths);
  1384. }
  1385. }
  1386. /* Write closure info to `fileName'. */
  1387. writeFile(tmpDir + "/" + fileName,
  1388. worker.store.makeValidityRegistration(paths, false, false));
  1389. }
  1390. /* If `build-users-group' is not empty, then we have to build as
  1391. one of the members of that group. */
  1392. if (settings.buildUsersGroup != "") {
  1393. buildUser.acquire();
  1394. assert(buildUser.getUID() != 0);
  1395. assert(buildUser.getGID() != 0);
  1396. /* Make sure that no other processes are executing under this
  1397. uid. */
  1398. buildUser.kill();
  1399. /* Change ownership of the temporary build directory. */
  1400. if (chown(tmpDir.c_str(), buildUser.getUID(), buildUser.getGID()) == -1)
  1401. throw SysError(format("cannot change ownership of '%1%'") % tmpDir);
  1402. }
  1403. if (useChroot) {
  1404. #if CHROOT_ENABLED
  1405. /* Create a temporary directory in which we set up the chroot
  1406. environment using bind-mounts. We put it in the store
  1407. to ensure that we can create hard-links to non-directory
  1408. inputs in the fake store in the chroot (see below). */
  1409. chrootRootDir = drvPath + ".chroot";
  1410. if (pathExists(chrootRootDir)) deletePath(chrootRootDir);
  1411. /* Clean up the chroot directory automatically. */
  1412. autoDelChroot = std::shared_ptr<AutoDelete>(new AutoDelete(chrootRootDir));
  1413. printMsg(lvlChatty, format("setting up chroot environment in `%1%'") % chrootRootDir);
  1414. if (mkdir(chrootRootDir.c_str(), 0750) == -1)
  1415. throw SysError(format("cannot create ‘%1%’") % chrootRootDir);
  1416. if (chown(chrootRootDir.c_str(), 0, buildUser.getGID()) == -1)
  1417. throw SysError(format("cannot change ownership of ‘%1%’") % chrootRootDir);
  1418. /* Create a writable /tmp in the chroot. Many builders need
  1419. this. (Of course they should really respect $TMPDIR
  1420. instead.) */
  1421. Path chrootTmpDir = chrootRootDir + "/tmp";
  1422. createDirs(chrootTmpDir);
  1423. chmod_(chrootTmpDir, 01777);
  1424. /* Create a /etc/passwd with entries for the build user and the
  1425. nobody account. The latter is kind of a hack to support
  1426. Samba-in-QEMU. */
  1427. createDirs(chrootRootDir + "/etc");
  1428. writeFile(chrootRootDir + "/etc/passwd",
  1429. (format(
  1430. "nixbld:x:%1%:%2%:Nix build user:/:/noshell\n"
  1431. "nobody:x:65534:65534:Nobody:/:/noshell\n")
  1432. % (buildUser.enabled() ? buildUser.getUID() : getuid())
  1433. % (buildUser.enabled() ? buildUser.getGID() : getgid())).str());
  1434. /* Declare the build user's group so that programs get a consistent
  1435. view of the system (e.g., "id -gn"). */
  1436. writeFile(chrootRootDir + "/etc/group",
  1437. (format("nixbld:!:%1%:\n")
  1438. % (buildUser.enabled() ? buildUser.getGID() : getgid())).str());
  1439. /* Create /etc/hosts with localhost entry. */
  1440. if (!fixedOutput)
  1441. writeFile(chrootRootDir + "/etc/hosts", "127.0.0.1 localhost\n");
  1442. /* Bind-mount a user-configurable set of directories from the
  1443. host file system. */
  1444. PathSet dirs = tokenizeString<StringSet>(settings.get("build-chroot-dirs", string(DEFAULT_CHROOT_DIRS)));
  1445. PathSet dirs2 = tokenizeString<StringSet>(settings.get("build-extra-chroot-dirs", string("")));
  1446. dirs.insert(dirs2.begin(), dirs2.end());
  1447. for (auto & i : dirs) {
  1448. size_t p = i.find('=');
  1449. if (p == string::npos)
  1450. dirsInChroot[i] = i;
  1451. else
  1452. dirsInChroot[string(i, 0, p)] = string(i, p + 1);
  1453. }
  1454. dirsInChroot[tmpDirInSandbox] = tmpDir;
  1455. /* Make the closure of the inputs available in the chroot,
  1456. rather than the whole store. This prevents any access
  1457. to undeclared dependencies. Directories are bind-mounted,
  1458. while other inputs are hard-linked (since only directories
  1459. can be bind-mounted). !!! As an extra security
  1460. precaution, make the fake store only writable by the
  1461. build user. */
  1462. Path chrootStoreDir = chrootRootDir + settings.nixStore;
  1463. createDirs(chrootStoreDir);
  1464. chmod_(chrootStoreDir, 01775);
  1465. if (chown(chrootStoreDir.c_str(), 0, buildUser.getGID()) == -1)
  1466. throw SysError(format("cannot change ownership of ‘%1%’") % chrootStoreDir);
  1467. foreach (PathSet::iterator, i, inputPaths) {
  1468. struct stat st;
  1469. if (lstat(i->c_str(), &st))
  1470. throw SysError(format("getting attributes of path `%1%'") % *i);
  1471. if (S_ISDIR(st.st_mode))
  1472. dirsInChroot[*i] = *i;
  1473. else {
  1474. Path p = chrootRootDir + *i;
  1475. if (link(i->c_str(), p.c_str()) == -1) {
  1476. /* Hard-linking fails if we exceed the maximum
  1477. link count on a file (e.g. 32000 of ext3),
  1478. which is quite possible after a `nix-store
  1479. --optimise'. */
  1480. if (errno != EMLINK)
  1481. throw SysError(format("linking `%1%' to `%2%'") % p % *i);
  1482. StringSink sink;
  1483. dumpPath(*i, sink);
  1484. StringSource source(sink.s);
  1485. restorePath(p, source);
  1486. }
  1487. regularInputPaths.insert(*i);
  1488. }
  1489. }
  1490. /* If we're repairing, checking or rebuilding part of a
  1491. multiple-outputs derivation, it's possible that we're
  1492. rebuilding a path that is in settings.dirsInChroot
  1493. (typically the dependencies of /bin/sh). Throw them
  1494. out. */
  1495. for (auto & i : drv.outputs)
  1496. dirsInChroot.erase(i.second.path);
  1497. #else
  1498. throw Error("chroot builds are not supported on this platform");
  1499. #endif
  1500. }
  1501. else {
  1502. if (pathExists(homeDir))
  1503. throw Error(format("directory `%1%' exists; please remove it") % homeDir);
  1504. /* We're not doing a chroot build, but we have some valid
  1505. output paths. Since we can't just overwrite or delete
  1506. them, we have to do hash rewriting: i.e. in the
  1507. environment/arguments passed to the build, we replace the
  1508. hashes of the valid outputs with unique dummy strings;
  1509. after the build, we discard the redirected outputs
  1510. corresponding to the valid outputs, and rewrite the
  1511. contents of the new outputs to replace the dummy strings
  1512. with the actual hashes. */
  1513. if (validPaths.size() > 0)
  1514. foreach (PathSet::iterator, i, validPaths)
  1515. addHashRewrite(*i);
  1516. /* If we're repairing, then we don't want to delete the
  1517. corrupt outputs in advance. So rewrite them as well. */
  1518. if (buildMode == bmRepair)
  1519. foreach (PathSet::iterator, i, missingPaths)
  1520. if (worker.store.isValidPath(*i) && pathExists(*i)) {
  1521. addHashRewrite(*i);
  1522. redirectedBadOutputs.insert(*i);
  1523. }
  1524. }
  1525. /* Run the builder. */
  1526. printMsg(lvlChatty, format("executing builder `%1%'") % drv.builder);
  1527. /* Create the log file. */
  1528. Path logFile = openLogFile();
  1529. /* Create a pipe to get the output of the builder. */
  1530. builderOut.create();
  1531. /* Fork a child to build the package. Note that while we
  1532. currently use forks to run and wait for the children, it
  1533. shouldn't be hard to use threads for this on systems where
  1534. fork() is unavailable or inefficient.
  1535. If we're building in a chroot, then also set up private
  1536. namespaces for the build:
  1537. - The PID namespace causes the build to start as PID 1.
  1538. Processes outside of the chroot are not visible to those on
  1539. the inside, but processes inside the chroot are visible from
  1540. the outside (though with different PIDs).
  1541. - The private mount namespace ensures that all the bind mounts
  1542. we do will only show up in this process and its children, and
  1543. will disappear automatically when we're done.
  1544. - The private network namespace ensures that the builder cannot
  1545. talk to the outside world (or vice versa). It only has a
  1546. private loopback interface.
  1547. - The IPC namespace prevents the builder from communicating
  1548. with outside processes using SysV IPC mechanisms (shared
  1549. memory, message queues, semaphores). It also ensures that
  1550. all IPC objects are destroyed when the builder exits.
  1551. - The UTS namespace ensures that builders see a hostname of
  1552. localhost rather than the actual hostname.
  1553. */
  1554. #if CHROOT_ENABLED
  1555. if (useChroot) {
  1556. char stack[32 * 1024];
  1557. int flags = CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWIPC | CLONE_NEWUTS | SIGCHLD;
  1558. if (!fixedOutput) flags |= CLONE_NEWNET;
  1559. /* Ensure proper alignment on the stack. On aarch64, it has to be 16
  1560. bytes. */
  1561. pid = clone(childEntry,
  1562. (char *)(((uintptr_t)stack + sizeof(stack) - 8) & ~(uintptr_t)0xf),
  1563. flags, this);
  1564. if (pid == -1)
  1565. throw SysError("cloning builder process");
  1566. } else
  1567. #endif
  1568. {
  1569. pid = fork();
  1570. if (pid == 0) runChild();
  1571. }
  1572. if (pid == -1) throw SysError("unable to fork");
  1573. /* parent */
  1574. pid.setSeparatePG(true);
  1575. builderOut.writeSide.close();
  1576. worker.childStarted(shared_from_this(), pid,
  1577. singleton<set<int> >(builderOut.readSide), true, true);
  1578. /* Check if setting up the build environment failed. */
  1579. string msg = readLine(builderOut.readSide);
  1580. if (!msg.empty()) throw Error(msg);
  1581. if (settings.printBuildTrace) {
  1582. printMsg(lvlError, format("@ build-started %1% - %2% %3% %4%")
  1583. % drvPath % drv.platform % logFile % pid);
  1584. }
  1585. }
  1586. void DerivationGoal::runChild()
  1587. {
  1588. /* Warning: in the child we should absolutely not make any SQLite
  1589. calls! */
  1590. try { /* child */
  1591. _writeToStderr = 0;
  1592. restoreAffinity();
  1593. commonChildInit(builderOut);
  1594. #if CHROOT_ENABLED
  1595. if (useChroot) {
  1596. /* Initialise the loopback interface. */
  1597. AutoCloseFD fd(socket(PF_INET, SOCK_DGRAM, IPPROTO_IP));
  1598. if (fd == -1) throw SysError("cannot open IP socket");
  1599. struct ifreq ifr;
  1600. strcpy(ifr.ifr_name, "lo");
  1601. ifr.ifr_flags = IFF_UP | IFF_LOOPBACK | IFF_RUNNING;
  1602. if (ioctl(fd, SIOCSIFFLAGS, &ifr) == -1)
  1603. throw SysError("cannot set loopback interface flags");
  1604. fd.close();
  1605. /* Set the hostname etc. to fixed values. */
  1606. char hostname[] = "localhost";
  1607. if (sethostname(hostname, sizeof(hostname)) == -1)
  1608. throw SysError("cannot set host name");
  1609. char domainname[] = "(none)"; // kernel default
  1610. if (setdomainname(domainname, sizeof(domainname)) == -1)
  1611. throw SysError("cannot set domain name");
  1612. /* Make all filesystems private. This is necessary
  1613. because subtrees may have been mounted as "shared"
  1614. (MS_SHARED). (Systemd does this, for instance.) Even
  1615. though we have a private mount namespace, mounting
  1616. filesystems on top of a shared subtree still propagates
  1617. outside of the namespace. Making a subtree private is
  1618. local to the namespace, though, so setting MS_PRIVATE
  1619. does not affect the outside world. */
  1620. if (mount(0, "/", 0, MS_REC|MS_PRIVATE, 0) == -1) {
  1621. throw SysError("unable to make ‘/’ private mount");
  1622. }
  1623. /* Bind-mount chroot directory to itself, to treat it as a
  1624. different filesystem from /, as needed for pivot_root. */
  1625. if (mount(chrootRootDir.c_str(), chrootRootDir.c_str(), 0, MS_BIND, 0) == -1)
  1626. throw SysError(format("unable to bind mount ‘%1%’") % chrootRootDir);
  1627. /* Set up a nearly empty /dev, unless the user asked to
  1628. bind-mount the host /dev. */
  1629. Strings ss;
  1630. if (dirsInChroot.find("/dev") == dirsInChroot.end()) {
  1631. createDirs(chrootRootDir + "/dev/shm");
  1632. createDirs(chrootRootDir + "/dev/pts");
  1633. ss.push_back("/dev/full");
  1634. #ifdef __linux__
  1635. if (pathExists("/dev/kvm"))
  1636. ss.push_back("/dev/kvm");
  1637. #endif
  1638. ss.push_back("/dev/null");
  1639. ss.push_back("/dev/random");
  1640. ss.push_back("/dev/tty");
  1641. ss.push_back("/dev/urandom");
  1642. ss.push_back("/dev/zero");
  1643. createSymlink("/proc/self/fd", chrootRootDir + "/dev/fd");
  1644. createSymlink("/proc/self/fd/0", chrootRootDir + "/dev/stdin");
  1645. createSymlink("/proc/self/fd/1", chrootRootDir + "/dev/stdout");
  1646. createSymlink("/proc/self/fd/2", chrootRootDir + "/dev/stderr");
  1647. }
  1648. /* Fixed-output derivations typically need to access the
  1649. network, so give them access to /etc/resolv.conf and so
  1650. on. */
  1651. if (fixedOutput) {
  1652. ss.push_back("/etc/resolv.conf");
  1653. ss.push_back("/etc/nsswitch.conf");
  1654. ss.push_back("/etc/services");
  1655. ss.push_back("/etc/hosts");
  1656. }
  1657. for (auto & i : ss) dirsInChroot[i] = i;
  1658. /* Bind-mount all the directories from the "host"
  1659. filesystem that we want in the chroot
  1660. environment. */
  1661. foreach (DirsInChroot::iterator, i, dirsInChroot) {
  1662. struct stat st;
  1663. Path source = i->second;
  1664. Path target = chrootRootDir + i->first;
  1665. if (source == "/proc") continue; // backwards compatibility
  1666. debug(format("bind mounting `%1%' to `%2%'") % source % target);
  1667. if (stat(source.c_str(), &st) == -1)
  1668. throw SysError(format("getting attributes of path `%1%'") % source);
  1669. if (S_ISDIR(st.st_mode))
  1670. createDirs(target);
  1671. else {
  1672. createDirs(dirOf(target));
  1673. writeFile(target, "");
  1674. }
  1675. if (mount(source.c_str(), target.c_str(), "", MS_BIND, 0) == -1)
  1676. throw SysError(format("bind mount from `%1%' to `%2%' failed") % source % target);
  1677. }
  1678. /* Bind a new instance of procfs on /proc to reflect our
  1679. private PID namespace. */
  1680. createDirs(chrootRootDir + "/proc");
  1681. if (mount("none", (chrootRootDir + "/proc").c_str(), "proc", 0, 0) == -1)
  1682. throw SysError("mounting /proc");
  1683. /* Mount a new tmpfs on /dev/shm to ensure that whatever
  1684. the builder puts in /dev/shm is cleaned up automatically. */
  1685. if (pathExists("/dev/shm") && mount("none", (chrootRootDir + "/dev/shm").c_str(), "tmpfs", 0, 0) == -1)
  1686. throw SysError("mounting /dev/shm");
  1687. /* Mount a new devpts on /dev/pts. Note that this
  1688. requires the kernel to be compiled with
  1689. CONFIG_DEVPTS_MULTIPLE_INSTANCES=y (which is the case
  1690. if /dev/ptx/ptmx exists). */
  1691. if (pathExists("/dev/pts/ptmx") &&
  1692. !pathExists(chrootRootDir + "/dev/ptmx")
  1693. && dirsInChroot.find("/dev/pts") == dirsInChroot.end())
  1694. {
  1695. if (mount("none", (chrootRootDir + "/dev/pts").c_str(), "devpts", 0, "newinstance,mode=0620") == -1)
  1696. throw SysError("mounting /dev/pts");
  1697. createSymlink("/dev/pts/ptmx", chrootRootDir + "/dev/ptmx");
  1698. /* Make sure /dev/pts/ptmx is world-writable. With some
  1699. Linux versions, it is created with permissions 0. */
  1700. chmod_(chrootRootDir + "/dev/pts/ptmx", 0666);
  1701. }
  1702. /* Do the chroot(). */
  1703. if (chdir(chrootRootDir.c_str()) == -1)
  1704. throw SysError(format("cannot change directory to '%1%'") % chrootRootDir);
  1705. if (mkdir("real-root", 0) == -1)
  1706. throw SysError("cannot create real-root directory");
  1707. #define pivot_root(new_root, put_old) (syscall(SYS_pivot_root, new_root, put_old))
  1708. if (pivot_root(".", "real-root") == -1)
  1709. throw SysError(format("cannot pivot old root directory onto '%1%'") % (chrootRootDir + "/real-root"));
  1710. #undef pivot_root
  1711. if (chroot(".") == -1)
  1712. throw SysError(format("cannot change root directory to '%1%'") % chrootRootDir);
  1713. if (umount2("real-root", MNT_DETACH) == -1)
  1714. throw SysError("cannot unmount real root filesystem");
  1715. if (rmdir("real-root") == -1)
  1716. throw SysError("cannot remove real-root directory");
  1717. }
  1718. #endif
  1719. if (chdir(tmpDirInSandbox.c_str()) == -1)
  1720. throw SysError(format("changing into `%1%'") % tmpDir);
  1721. /* Close all other file descriptors. */
  1722. closeMostFDs(set<int>());
  1723. #if __linux__
  1724. /* Change the personality to 32-bit if we're doing an
  1725. i686-linux build on an x86_64-linux machine. */
  1726. struct utsname utsbuf;
  1727. uname(&utsbuf);
  1728. if (drv.platform == "i686-linux" &&
  1729. (settings.thisSystem == "x86_64-linux" ||
  1730. (!strcmp(utsbuf.sysname, "Linux") && !strcmp(utsbuf.machine, "x86_64")))) {
  1731. if (personality(PER_LINUX32) == -1)
  1732. throw SysError("cannot set i686-linux personality");
  1733. }
  1734. if (drv.platform == "armhf-linux" &&
  1735. (settings.thisSystem == "aarch64-linux" ||
  1736. (!strcmp(utsbuf.sysname, "Linux") && !strcmp(utsbuf.machine, "aarch64")))) {
  1737. if (personality(PER_LINUX32) == -1)
  1738. throw SysError("cannot set armhf-linux personality");
  1739. }
  1740. /* Impersonate a Linux 2.6 machine to get some determinism in
  1741. builds that depend on the kernel version. */
  1742. if ((drv.platform == "i686-linux" || drv.platform == "x86_64-linux") && settings.impersonateLinux26) {
  1743. int cur = personality(0xffffffff);
  1744. if (cur != -1) personality(cur | 0x0020000 /* == UNAME26 */);
  1745. }
  1746. /* Disable address space randomization for improved
  1747. determinism. */
  1748. int cur = personality(0xffffffff);
  1749. if (cur != -1) personality(cur | ADDR_NO_RANDOMIZE);
  1750. #endif
  1751. /* Fill in the environment. */
  1752. Strings envStrs;
  1753. foreach (Environment::const_iterator, i, env)
  1754. envStrs.push_back(rewriteHashes(i->first + "=" + i->second, rewritesToTmp));
  1755. /* If we are running in `build-users' mode, then switch to the
  1756. user we allocated above. Make sure that we drop all root
  1757. privileges. Note that above we have closed all file
  1758. descriptors except std*, so that's safe. Also note that
  1759. setuid() when run as root sets the real, effective and
  1760. saved UIDs. */
  1761. if (buildUser.enabled()) {
  1762. /* Preserve supplementary groups of the build user, to allow
  1763. admins to specify groups such as "kvm". */
  1764. if (setgroups(buildUser.getSupplementaryGIDs().size(),
  1765. buildUser.getSupplementaryGIDs().data()) == -1)
  1766. throw SysError("cannot set supplementary groups of build user");
  1767. if (setgid(buildUser.getGID()) == -1 ||
  1768. getgid() != buildUser.getGID() ||
  1769. getegid() != buildUser.getGID())
  1770. throw SysError("setgid failed");
  1771. if (setuid(buildUser.getUID()) == -1 ||
  1772. getuid() != buildUser.getUID() ||
  1773. geteuid() != buildUser.getUID())
  1774. throw SysError("setuid failed");
  1775. }
  1776. restoreSIGPIPE();
  1777. /* Indicate that we managed to set up the build environment. */
  1778. writeFull(STDERR_FILENO, "\n");
  1779. /* Execute the program. This should not return. */
  1780. if (isBuiltin(drv)) {
  1781. try {
  1782. logType = ltFlat;
  1783. auto buildDrv = lookupBuiltinBuilder(drv.builder);
  1784. if (buildDrv != NULL) {
  1785. /* Check what the output file name is. When doing a
  1786. 'bmCheck' build, the output file name is different from
  1787. that specified in DRV due to hash rewriting. */
  1788. Path output = drv.outputs["out"].path;
  1789. auto redirected = redirectedOutputs.find(output);
  1790. if (redirected != redirectedOutputs.end())
  1791. output = redirected->second;
  1792. buildDrv(drv, drvPath, output);
  1793. }
  1794. else
  1795. throw Error(format("unsupported builtin function '%1%'") % string(drv.builder, 8));
  1796. _exit(0);
  1797. } catch (std::exception & e) {
  1798. writeFull(STDERR_FILENO, "error: " + string(e.what()) + "\n");
  1799. _exit(1);
  1800. }
  1801. }
  1802. /* Fill in the arguments. */
  1803. Strings args;
  1804. string builderBasename = baseNameOf(drv.builder);
  1805. args.push_back(builderBasename);
  1806. foreach (Strings::iterator, i, drv.args)
  1807. args.push_back(rewriteHashes(*i, rewritesToTmp));
  1808. execve(drv.builder.c_str(), stringsToCharPtrs(args).data(), stringsToCharPtrs(envStrs).data());
  1809. int error = errno;
  1810. /* Right platform? Check this after we've tried 'execve' to allow for
  1811. transparent emulation of different platforms with binfmt_misc
  1812. handlers that invoke QEMU. */
  1813. if (error == ENOEXEC && !canBuildLocally(drv.platform)) {
  1814. if (settings.printBuildTrace)
  1815. printMsg(lvlError, format("@ unsupported-platform %1% %2%") % drvPath % drv.platform);
  1816. throw Error(
  1817. format("a `%1%' is required to build `%3%', but I am a `%2%'")
  1818. % drv.platform % settings.thisSystem % drvPath);
  1819. }
  1820. errno = error;
  1821. throw SysError(format("executing `%1%'") % drv.builder);
  1822. } catch (std::exception & e) {
  1823. writeFull(STDERR_FILENO, "while setting up the build environment: " + string(e.what()) + "\n");
  1824. _exit(1);
  1825. }
  1826. abort(); /* never reached */
  1827. }
  1828. /* Parse a list of reference specifiers. Each element must either be
  1829. a store path, or the symbolic name of the output of the derivation
  1830. (such as `out'). */
  1831. PathSet parseReferenceSpecifiers(const Derivation & drv, string attr)
  1832. {
  1833. PathSet result;
  1834. Paths paths = tokenizeString<Paths>(attr);
  1835. foreach (Strings::iterator, i, paths) {
  1836. if (isStorePath(*i))
  1837. result.insert(*i);
  1838. else if (drv.outputs.find(*i) != drv.outputs.end())
  1839. result.insert(drv.outputs.find(*i)->second.path);
  1840. else throw BuildError(
  1841. format("derivation contains an illegal reference specifier `%1%'")
  1842. % *i);
  1843. }
  1844. return result;
  1845. }
  1846. void DerivationGoal::registerOutputs()
  1847. {
  1848. /* When using a build hook, the build hook can register the output
  1849. as valid (by doing `nix-store --import'). If so we don't have
  1850. to do anything here. */
  1851. if (hook) {
  1852. bool allValid = true;
  1853. foreach (DerivationOutputs::iterator, i, drv.outputs)
  1854. if (!worker.store.isValidPath(i->second.path)) allValid = false;
  1855. if (allValid) return;
  1856. }
  1857. ValidPathInfos infos;
  1858. /* Set of inodes seen during calls to canonicalisePathMetaData()
  1859. for this build's outputs. This needs to be shared between
  1860. outputs to allow hard links between outputs. */
  1861. InodesSeen inodesSeen;
  1862. Path checkSuffix = "-check";
  1863. /* Check whether the output paths were created, and grep each
  1864. output path to determine what other paths it references. Also make all
  1865. output paths read-only. */
  1866. foreach (DerivationOutputs::iterator, i, drv.outputs) {
  1867. Path path = i->second.path;
  1868. if (missingPaths.find(path) == missingPaths.end()) continue;
  1869. Path actualPath = path;
  1870. if (useChroot) {
  1871. actualPath = chrootRootDir + path;
  1872. if (pathExists(actualPath)) {
  1873. /* Move output paths from the chroot to the store. */
  1874. if (buildMode == bmRepair)
  1875. replaceValidPath(path, actualPath);
  1876. else
  1877. if (buildMode != bmCheck && rename(actualPath.c_str(), path.c_str()) == -1)
  1878. throw SysError(format("moving build output `%1%' from the chroot to the store") % path);
  1879. }
  1880. if (buildMode != bmCheck) actualPath = path;
  1881. } else {
  1882. Path redirected = redirectedOutputs[path];
  1883. if (buildMode == bmRepair
  1884. && redirectedBadOutputs.find(path) != redirectedBadOutputs.end()
  1885. && pathExists(redirected))
  1886. replaceValidPath(path, redirected);
  1887. if (buildMode == bmCheck && redirected != "")
  1888. actualPath = redirected;
  1889. }
  1890. struct stat st;
  1891. if (lstat(actualPath.c_str(), &st) == -1) {
  1892. if (errno == ENOENT)
  1893. throw BuildError(
  1894. format("builder for `%1%' failed to produce output path `%2%'")
  1895. % drvPath % path);
  1896. throw SysError(format("getting attributes of path `%1%'") % actualPath);
  1897. }
  1898. #ifndef __CYGWIN__
  1899. /* Check that the output is not group or world writable, as
  1900. that means that someone else can have interfered with the
  1901. build. Also, the output should be owned by the build
  1902. user. */
  1903. if ((!S_ISLNK(st.st_mode) && (st.st_mode & (S_IWGRP | S_IWOTH))) ||
  1904. (buildUser.enabled() && st.st_uid != buildUser.getUID()))
  1905. throw BuildError(format("suspicious ownership or permission on `%1%'; rejecting this build output") % path);
  1906. #endif
  1907. /* Apply hash rewriting if necessary. */
  1908. bool rewritten = false;
  1909. if (!rewritesFromTmp.empty()) {
  1910. printMsg(lvlError, format("warning: rewriting hashes in `%1%'; cross fingers") % path);
  1911. /* Canonicalise first. This ensures that the path we're
  1912. rewriting doesn't contain a hard link to /etc/shadow or
  1913. something like that. */
  1914. canonicalisePathMetaData(actualPath, buildUser.enabled() ? buildUser.getUID() : -1, inodesSeen);
  1915. /* FIXME: this is in-memory. */
  1916. StringSink sink;
  1917. dumpPath(actualPath, sink);
  1918. deletePath(actualPath);
  1919. sink.s = rewriteHashes(sink.s, rewritesFromTmp);
  1920. StringSource source(sink.s);
  1921. restorePath(actualPath, source);
  1922. rewritten = true;
  1923. }
  1924. startNest(nest, lvlTalkative,
  1925. format("scanning for references inside `%1%'") % path);
  1926. /* Check that fixed-output derivations produced the right
  1927. outputs (i.e., the content hash should match the specified
  1928. hash). */
  1929. if (i->second.hash != "") {
  1930. bool recursive; HashType ht; Hash h;
  1931. i->second.parseHashInfo(recursive, ht, h);
  1932. if (!recursive) {
  1933. /* The output path should be a regular file without
  1934. execute permission. */
  1935. if (!S_ISREG(st.st_mode) || (st.st_mode & S_IXUSR) != 0)
  1936. throw BuildError(
  1937. format("output path `%1% should be a non-executable regular file") % path);
  1938. }
  1939. /* Check the hash. */
  1940. Hash h2 = recursive ? hashPath(ht, actualPath).first : hashFile(ht, actualPath);
  1941. if (h != h2) {
  1942. if (settings.printBuildTrace)
  1943. printMsg(lvlError, format("@ hash-mismatch %1% %2% %3% %4%")
  1944. % path % i->second.hashAlgo
  1945. % printHash16or32(h) % printHash16or32(h2));
  1946. throw BuildError(format("hash mismatch for store item '%1%'") % path);
  1947. }
  1948. }
  1949. /* Get rid of all weird permissions. This also checks that
  1950. all files are owned by the build user, if applicable. */
  1951. canonicalisePathMetaData(actualPath,
  1952. buildUser.enabled() && !rewritten ? buildUser.getUID() : -1, inodesSeen);
  1953. /* For this output path, find the references to other paths
  1954. contained in it. Compute the SHA-256 NAR hash at the same
  1955. time. The hash is stored in the database so that we can
  1956. verify later on whether nobody has messed with the store. */
  1957. HashResult hash;
  1958. PathSet references = scanForReferences(actualPath, allPaths, hash);
  1959. if (buildMode == bmCheck) {
  1960. if (!store->isValidPath(path)) continue;
  1961. ValidPathInfo info = worker.store.queryPathInfo(path);
  1962. if (hash.first != info.hash) {
  1963. if (settings.keepFailed) {
  1964. Path dst = path + checkSuffix;
  1965. if (pathExists(dst)) deletePath(dst);
  1966. if (rename(actualPath.c_str(), dst.c_str()))
  1967. throw SysError(format("renaming `%1%' to `%2%'") % actualPath % dst);
  1968. throw Error(format("derivation `%1%' may not be deterministic: output `%2%' differs from ‘%3%’")
  1969. % drvPath % path % dst);
  1970. } else
  1971. throw Error(format("derivation `%1%' may not be deterministic: output `%2%' differs")
  1972. % drvPath % path);
  1973. }
  1974. if (settings.printBuildTrace)
  1975. printMsg(lvlError, format("@ build-succeeded %1% -") % drvPath);
  1976. continue;
  1977. }
  1978. /* For debugging, print out the referenced and unreferenced
  1979. paths. */
  1980. foreach (PathSet::iterator, i, inputPaths) {
  1981. PathSet::iterator j = references.find(*i);
  1982. if (j == references.end())
  1983. debug(format("unreferenced input: `%1%'") % *i);
  1984. else
  1985. debug(format("referenced input: `%1%'") % *i);
  1986. }
  1987. /* Enforce `allowedReferences' and friends. */
  1988. auto checkRefs = [&](const string & attrName, bool allowed, bool recursive) {
  1989. if (drv.env.find(attrName) == drv.env.end()) return;
  1990. PathSet spec = parseReferenceSpecifiers(drv, get(drv.env, attrName));
  1991. PathSet used;
  1992. if (recursive) {
  1993. /* Our requisites are the union of the closures of our references. */
  1994. for (auto & i : references)
  1995. /* Don't call computeFSClosure on ourselves. */
  1996. if (actualPath != i)
  1997. computeFSClosure(worker.store, i, used);
  1998. } else
  1999. used = references;
  2000. for (auto & i : used)
  2001. if (allowed) {
  2002. if (spec.find(i) == spec.end())
  2003. throw BuildError(format("output (`%1%') is not allowed to refer to path `%2%'") % actualPath % i);
  2004. } else {
  2005. if (spec.find(i) != spec.end())
  2006. throw BuildError(format("output (`%1%') is not allowed to refer to path `%2%'") % actualPath % i);
  2007. }
  2008. };
  2009. checkRefs("allowedReferences", true, false);
  2010. checkRefs("allowedRequisites", true, true);
  2011. checkRefs("disallowedReferences", false, false);
  2012. checkRefs("disallowedRequisites", false, true);
  2013. if (curRound == nrRounds) {
  2014. worker.store.optimisePath(path); // FIXME: combine with scanForReferences()
  2015. worker.store.markContentsGood(path);
  2016. }
  2017. ValidPathInfo info;
  2018. info.path = path;
  2019. info.hash = hash.first;
  2020. info.narSize = hash.second;
  2021. info.references = references;
  2022. info.deriver = drvPath;
  2023. infos.push_back(info);
  2024. }
  2025. if (buildMode == bmCheck) return;
  2026. /* Compare the result with the previous round, and report which
  2027. path is different, if any.*/
  2028. if (curRound > 1 && prevInfos != infos) {
  2029. assert(prevInfos.size() == infos.size());
  2030. for (auto i = prevInfos.begin(), j = infos.begin(); i != prevInfos.end(); ++i, ++j)
  2031. if (!(*i == *j)) {
  2032. Path prev = i->path + checkSuffix;
  2033. if (pathExists(prev))
  2034. throw NotDeterministic(
  2035. format("output ‘%1%’ of ‘%2%’ differs from ‘%3%’ from previous round")
  2036. % i->path % drvPath % prev);
  2037. else
  2038. throw NotDeterministic(
  2039. format("output ‘%1%’ of ‘%2%’ differs from previous round")
  2040. % i->path % drvPath);
  2041. }
  2042. assert(false); // shouldn't happen
  2043. }
  2044. if (settings.keepFailed) {
  2045. for (auto & i : drv.outputs) {
  2046. Path prev = i.second.path + checkSuffix;
  2047. if (pathExists(prev)) deletePath(prev);
  2048. if (curRound < nrRounds) {
  2049. Path dst = i.second.path + checkSuffix;
  2050. if (rename(i.second.path.c_str(), dst.c_str()))
  2051. throw SysError(format("renaming ‘%1%’ to ‘%2%’") % i.second.path % dst);
  2052. }
  2053. }
  2054. }
  2055. if (curRound < nrRounds) {
  2056. prevInfos = infos;
  2057. return;
  2058. }
  2059. /* Register each output path as valid, and register the sets of
  2060. paths referenced by each of them. If there are cycles in the
  2061. outputs, this will fail. */
  2062. worker.store.registerValidPaths(infos);
  2063. }
  2064. string drvsLogDir = "drvs";
  2065. Path DerivationGoal::openLogFile()
  2066. {
  2067. logSize = 0;
  2068. if (!settings.keepLog) return "";
  2069. string baseName = baseNameOf(drvPath);
  2070. /* Create a log file. */
  2071. Path dir = (format("%1%/%2%/%3%/") % settings.nixLogDir % drvsLogDir % string(baseName, 0, 2)).str();
  2072. createDirs(dir);
  2073. switch (settings.logCompression)
  2074. {
  2075. case COMPRESSION_GZIP: {
  2076. Path logFileName = (format("%1%/%2%.gz") % 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. /* Note: FD will be closed by 'gzclose'. */
  2081. if (!(gzLogFile = gzdopen(fd.borrow(), "w")))
  2082. throw Error(format("cannot open compressed log file `%1%'") % logFileName);
  2083. gzbuffer(gzLogFile, 32768);
  2084. gzsetparams(gzLogFile, Z_BEST_COMPRESSION, Z_DEFAULT_STRATEGY);
  2085. return logFileName;
  2086. }
  2087. #if HAVE_BZLIB_H
  2088. case COMPRESSION_BZIP2: {
  2089. Path logFileName = (format("%1%/%2%.bz2") % dir % string(baseName, 2)).str();
  2090. AutoCloseFD fd = open(logFileName.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0666);
  2091. if (fd == -1) throw SysError(format("creating log file `%1%'") % logFileName);
  2092. closeOnExec(fd);
  2093. if (!(fLogFile = fdopen(fd.borrow(), "w")))
  2094. throw SysError(format("opening file `%1%'") % logFileName);
  2095. int err;
  2096. if (!(bzLogFile = BZ2_bzWriteOpen(&err, fLogFile, 9, 0, 0)))
  2097. throw Error(format("cannot open compressed log file `%1%'") % logFileName);
  2098. return logFileName;
  2099. }
  2100. #endif
  2101. case COMPRESSION_NONE: {
  2102. Path logFileName = (format("%1%/%2%") % dir % string(baseName, 2)).str();
  2103. fdLogFile = open(logFileName.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0666);
  2104. if (fdLogFile == -1) throw SysError(format("creating log file `%1%'") % logFileName);
  2105. closeOnExec(fdLogFile);
  2106. return logFileName;
  2107. }
  2108. }
  2109. abort();
  2110. }
  2111. void DerivationGoal::closeLogFile()
  2112. {
  2113. if (gzLogFile) {
  2114. int err;
  2115. err = gzclose(gzLogFile);
  2116. gzLogFile = NULL;
  2117. if (err != Z_OK) throw Error(format("cannot close compressed log file (gzip error = %1%)") % err);
  2118. }
  2119. #if HAVE_BZLIB_H
  2120. else if (bzLogFile) {
  2121. int err;
  2122. BZ2_bzWriteClose(&err, bzLogFile, 0, 0, 0);
  2123. bzLogFile = 0;
  2124. if (err != BZ_OK) throw Error(format("cannot close compressed log file (BZip2 error = %1%)") % err);
  2125. }
  2126. #endif
  2127. if (fLogFile) {
  2128. fclose(fLogFile);
  2129. fLogFile = 0;
  2130. }
  2131. fdLogFile.close();
  2132. }
  2133. static void _chown(const Path & path, uid_t uid, gid_t gid)
  2134. {
  2135. checkInterrupt();
  2136. if (lchown(path.c_str(), uid, gid) == -1) {
  2137. throw SysError(format("change owner and group of `%1%'") % path);
  2138. }
  2139. struct stat st = lstat(path);
  2140. if (S_ISDIR(st.st_mode)) {
  2141. for (auto & i : readDirectory(path))
  2142. _chown(path + "/" + i.name, uid, gid);
  2143. }
  2144. }
  2145. void DerivationGoal::deleteTmpDir(bool force)
  2146. {
  2147. if (tmpDir != "") {
  2148. if (settings.keepFailed && !force) {
  2149. printMsg(lvlError,
  2150. format("note: keeping build directory `%2%'")
  2151. % drvPath % tmpDir);
  2152. chmod(tmpDir.c_str(), 0755);
  2153. // Change the ownership if clientUid is set. Never change the
  2154. // ownership or the group to "root" for security reasons.
  2155. if (settings.clientUid != (uid_t) -1 && settings.clientUid != 0) {
  2156. _chown(tmpDir, settings.clientUid,
  2157. settings.clientGid != 0 ? settings.clientGid : -1);
  2158. }
  2159. }
  2160. else
  2161. deletePath(tmpDir);
  2162. tmpDir = "";
  2163. }
  2164. }
  2165. void DerivationGoal::handleChildOutput(int fd, const string & data)
  2166. {
  2167. string prefix;
  2168. if (settings.multiplexedBuildOutput) {
  2169. /* Print a prefix that allows clients to determine whether a message
  2170. comes from the daemon or from a build process, and in the latter
  2171. case, which build process it comes from. The PID here matches the
  2172. one given in "@ build-started" traces; it's shorter that the
  2173. derivation file name, hence this choice. */
  2174. prefix = "@ build-log "
  2175. + std::to_string(pid < 0 ? hook->pid : pid)
  2176. + " " + std::to_string(data.size()) + "\n";
  2177. }
  2178. if ((hook && fd == hook->builderOut.readSide) ||
  2179. (!hook && fd == builderOut.readSide))
  2180. {
  2181. logSize += data.size();
  2182. if (settings.maxLogSize && logSize > settings.maxLogSize) {
  2183. printMsg(lvlError,
  2184. format("%1% killed after writing more than %2% bytes of log output")
  2185. % getName() % settings.maxLogSize);
  2186. timedOut(); // not really a timeout, but close enough
  2187. return;
  2188. }
  2189. if (verbosity >= settings.buildVerbosity)
  2190. writeToStderr(prefix + data);
  2191. if (gzLogFile) {
  2192. if (data.size() > 0) {
  2193. int count, err;
  2194. count = gzwrite(gzLogFile, data.data(), data.size());
  2195. if (count == 0) throw Error(format("cannot write to compressed log file (gzip error = %1%)") % gzerror(gzLogFile, &err));
  2196. }
  2197. #if HAVE_BZLIB_H
  2198. } else if (bzLogFile) {
  2199. int err;
  2200. BZ2_bzWrite(&err, bzLogFile, (unsigned char *) data.data(), data.size());
  2201. if (err != BZ_OK) throw Error(format("cannot write to compressed log file (BZip2 error = %1%)") % err);
  2202. #endif
  2203. } else if (fdLogFile != -1)
  2204. writeFull(fdLogFile, data);
  2205. }
  2206. if (hook && fd == hook->fromHook.readSide)
  2207. writeToStderr(prefix + data);
  2208. }
  2209. void DerivationGoal::handleEOF(int fd)
  2210. {
  2211. worker.wakeUp(shared_from_this());
  2212. }
  2213. PathSet DerivationGoal::checkPathValidity(bool returnValid, bool checkHash)
  2214. {
  2215. PathSet result;
  2216. foreach (DerivationOutputs::iterator, i, drv.outputs) {
  2217. if (!wantOutput(i->first, wantedOutputs)) continue;
  2218. bool good =
  2219. worker.store.isValidPath(i->second.path) &&
  2220. (!checkHash || worker.store.pathContentsGood(i->second.path));
  2221. if (good == returnValid) result.insert(i->second.path);
  2222. }
  2223. return result;
  2224. }
  2225. bool DerivationGoal::pathFailed(const Path & path)
  2226. {
  2227. if (!settings.cacheFailure) return false;
  2228. if (!worker.store.hasPathFailed(path)) return false;
  2229. printMsg(lvlError, format("builder for `%1%' failed previously (cached)") % path);
  2230. if (settings.printBuildTrace)
  2231. printMsg(lvlError, format("@ build-failed %1% - cached") % drvPath);
  2232. done(BuildResult::CachedFailure);
  2233. return true;
  2234. }
  2235. Path DerivationGoal::addHashRewrite(const Path & path)
  2236. {
  2237. string h1 = string(path, settings.nixStore.size() + 1, 32);
  2238. string h2 = string(printHash32(hashString(htSHA256, "rewrite:" + drvPath + ":" + path)), 0, 32);
  2239. Path p = settings.nixStore + "/" + h2 + string(path, settings.nixStore.size() + 33);
  2240. if (pathExists(p)) deletePath(p);
  2241. assert(path.size() == p.size());
  2242. rewritesToTmp[h1] = h2;
  2243. rewritesFromTmp[h2] = h1;
  2244. redirectedOutputs[path] = p;
  2245. printMsg(lvlChatty, format("output '%1%' redirected to '%2%'")
  2246. % path % p);
  2247. return p;
  2248. }
  2249. void DerivationGoal::done(BuildResult::Status status, const string & msg)
  2250. {
  2251. result.status = status;
  2252. result.errorMsg = msg;
  2253. amDone(result.success() ? ecSuccess : ecFailed);
  2254. if (result.status == BuildResult::TimedOut)
  2255. worker.timedOut = true;
  2256. if (result.status == BuildResult::PermanentFailure || result.status == BuildResult::CachedFailure)
  2257. worker.permanentFailure = true;
  2258. }
  2259. //////////////////////////////////////////////////////////////////////
  2260. class SubstitutionGoal : public Goal
  2261. {
  2262. friend class Worker;
  2263. private:
  2264. /* The store path that should be realised through a substitute. */
  2265. Path storePath;
  2266. /* The remaining substituters. */
  2267. Paths subs;
  2268. /* The current substituter. */
  2269. Path sub;
  2270. /* Whether any substituter can realise this path */
  2271. bool hasSubstitute;
  2272. /* Path info returned by the substituter's query info operation. */
  2273. SubstitutablePathInfo info;
  2274. /* Pipe for the substituter's standard output. */
  2275. Pipe outPipe;
  2276. /* Pipe for the substituter's standard error. */
  2277. Pipe logPipe;
  2278. /* The process ID of the builder. */
  2279. Pid pid;
  2280. /* Lock on the store path. */
  2281. std::shared_ptr<PathLocks> outputLock;
  2282. /* Whether to try to repair a valid path. */
  2283. bool repair;
  2284. /* Location where we're downloading the substitute. Differs from
  2285. storePath when doing a repair. */
  2286. Path destPath;
  2287. typedef void (SubstitutionGoal::*GoalState)();
  2288. GoalState state;
  2289. public:
  2290. SubstitutionGoal(const Path & storePath, Worker & worker, bool repair = false);
  2291. ~SubstitutionGoal();
  2292. void timedOut();
  2293. string key()
  2294. {
  2295. /* "a$" ensures substitution goals happen before derivation
  2296. goals. */
  2297. return "a$" + storePathToName(storePath) + "$" + storePath;
  2298. }
  2299. void work();
  2300. /* The states. */
  2301. void init();
  2302. void tryNext();
  2303. void gotInfo();
  2304. void referencesValid();
  2305. void tryToRun();
  2306. void finished();
  2307. /* Callback used by the worker to write to the log. */
  2308. void handleChildOutput(int fd, const string & data);
  2309. void handleEOF(int fd);
  2310. Path getStorePath() { return storePath; }
  2311. };
  2312. SubstitutionGoal::SubstitutionGoal(const Path & storePath, Worker & worker, bool repair)
  2313. : Goal(worker)
  2314. , hasSubstitute(false)
  2315. , repair(repair)
  2316. {
  2317. this->storePath = storePath;
  2318. state = &SubstitutionGoal::init;
  2319. name = (format("substitution of `%1%'") % storePath).str();
  2320. trace("created");
  2321. }
  2322. SubstitutionGoal::~SubstitutionGoal()
  2323. {
  2324. if (pid != -1) worker.childTerminated(pid);
  2325. }
  2326. void SubstitutionGoal::timedOut()
  2327. {
  2328. if (settings.printBuildTrace)
  2329. printMsg(lvlError, format("@ substituter-failed %1% timeout") % storePath);
  2330. if (pid != -1) {
  2331. pid_t savedPid = pid;
  2332. pid.kill();
  2333. worker.childTerminated(savedPid);
  2334. }
  2335. amDone(ecFailed);
  2336. }
  2337. void SubstitutionGoal::work()
  2338. {
  2339. (this->*state)();
  2340. }
  2341. void SubstitutionGoal::init()
  2342. {
  2343. trace("init");
  2344. worker.store.addTempRoot(storePath);
  2345. /* If the path already exists we're done. */
  2346. if (!repair && worker.store.isValidPath(storePath)) {
  2347. amDone(ecSuccess);
  2348. return;
  2349. }
  2350. if (settings.readOnlyMode)
  2351. throw Error(format("cannot substitute path `%1%' - no write access to the store") % storePath);
  2352. subs = settings.substituters;
  2353. tryNext();
  2354. }
  2355. void SubstitutionGoal::tryNext()
  2356. {
  2357. trace("trying next substituter");
  2358. if (subs.size() == 0) {
  2359. /* None left. Terminate this goal and let someone else deal
  2360. with it. */
  2361. debug(format("path `%1%' is required, but there is no substituter that can build it") % storePath);
  2362. /* Hack: don't indicate failure if there were no substituters.
  2363. In that case the calling derivation should just do a
  2364. build. */
  2365. amDone(hasSubstitute ? ecFailed : ecNoSubstituters);
  2366. return;
  2367. }
  2368. sub = subs.front();
  2369. subs.pop_front();
  2370. SubstitutablePathInfos infos;
  2371. PathSet dummy(singleton<PathSet>(storePath));
  2372. worker.store.querySubstitutablePathInfos(sub, dummy, infos);
  2373. SubstitutablePathInfos::iterator k = infos.find(storePath);
  2374. if (k == infos.end()) { tryNext(); return; }
  2375. info = k->second;
  2376. hasSubstitute = true;
  2377. /* To maintain the closure invariant, we first have to realise the
  2378. paths referenced by this one. */
  2379. foreach (PathSet::iterator, i, info.references)
  2380. if (*i != storePath) /* ignore self-references */
  2381. addWaitee(worker.makeSubstitutionGoal(*i));
  2382. if (waitees.empty()) /* to prevent hang (no wake-up event) */
  2383. referencesValid();
  2384. else
  2385. state = &SubstitutionGoal::referencesValid;
  2386. }
  2387. void SubstitutionGoal::referencesValid()
  2388. {
  2389. trace("all references realised");
  2390. if (nrFailed > 0) {
  2391. debug(format("some references of path `%1%' could not be realised") % storePath);
  2392. amDone(nrNoSubstituters > 0 || nrIncompleteClosure > 0 ? ecIncompleteClosure : ecFailed);
  2393. return;
  2394. }
  2395. foreach (PathSet::iterator, i, info.references)
  2396. if (*i != storePath) /* ignore self-references */
  2397. assert(worker.store.isValidPath(*i));
  2398. state = &SubstitutionGoal::tryToRun;
  2399. worker.wakeUp(shared_from_this());
  2400. }
  2401. void SubstitutionGoal::tryToRun()
  2402. {
  2403. trace("trying to run");
  2404. /* Make sure that we are allowed to start a build. Note that even
  2405. is maxBuildJobs == 0 (no local builds allowed), we still allow
  2406. a substituter to run. This is because substitutions cannot be
  2407. distributed to another machine via the build hook. */
  2408. if (worker.getNrLocalBuilds() >= (settings.maxBuildJobs == 0 ? 1 : settings.maxBuildJobs)) {
  2409. worker.waitForBuildSlot(shared_from_this());
  2410. return;
  2411. }
  2412. /* Maybe a derivation goal has already locked this path
  2413. (exceedingly unlikely, since it should have used a substitute
  2414. first, but let's be defensive). */
  2415. outputLock.reset(); // make sure this goal's lock is gone
  2416. if (pathIsLockedByMe(storePath)) {
  2417. debug(format("restarting substitution of `%1%' because it's locked by another goal")
  2418. % storePath);
  2419. worker.waitForAnyGoal(shared_from_this());
  2420. return; /* restart in the tryToRun() state when another goal finishes */
  2421. }
  2422. /* Acquire a lock on the output path. */
  2423. outputLock = std::shared_ptr<PathLocks>(new PathLocks);
  2424. if (!outputLock->lockPaths(singleton<PathSet>(storePath), "", false)) {
  2425. worker.waitForAWhile(shared_from_this());
  2426. return;
  2427. }
  2428. /* Check again whether the path is invalid. */
  2429. if (!repair && worker.store.isValidPath(storePath)) {
  2430. debug(format("store path `%1%' has become valid") % storePath);
  2431. outputLock->setDeletion(true);
  2432. amDone(ecSuccess);
  2433. return;
  2434. }
  2435. printMsg(lvlInfo, format("fetching path `%1%'...") % storePath);
  2436. outPipe.create();
  2437. logPipe.create();
  2438. destPath = repair ? storePath + ".tmp" : storePath;
  2439. /* Remove the (stale) output path if it exists. */
  2440. if (pathExists(destPath))
  2441. deletePath(destPath);
  2442. worker.store.setSubstituterEnv();
  2443. /* Fill in the arguments. */
  2444. Strings args;
  2445. args.push_back(baseNameOf(sub));
  2446. args.push_back("--substitute");
  2447. args.push_back(storePath);
  2448. args.push_back(destPath);
  2449. /* Fork the substitute program. */
  2450. pid = startProcess([&]() {
  2451. commonChildInit(logPipe);
  2452. if (dup2(outPipe.writeSide, STDOUT_FILENO) == -1)
  2453. throw SysError("cannot dup output pipe into stdout");
  2454. execv(sub.c_str(), stringsToCharPtrs(args).data());
  2455. throw SysError(format("executing `%1%'") % sub);
  2456. });
  2457. pid.setSeparatePG(true);
  2458. pid.setKillSignal(SIGTERM);
  2459. outPipe.writeSide.close();
  2460. logPipe.writeSide.close();
  2461. worker.childStarted(shared_from_this(),
  2462. pid, singleton<set<int> >(logPipe.readSide), true, true);
  2463. state = &SubstitutionGoal::finished;
  2464. if (settings.printBuildTrace)
  2465. printMsg(lvlError, format("@ substituter-started %1% %2%") % storePath % sub);
  2466. }
  2467. void SubstitutionGoal::finished()
  2468. {
  2469. trace("substitute finished");
  2470. /* Since we got an EOF on the logger pipe, the substitute is
  2471. presumed to have terminated. */
  2472. pid_t savedPid = pid;
  2473. int status = pid.wait(true);
  2474. /* So the child is gone now. */
  2475. worker.childTerminated(savedPid);
  2476. /* Close the read side of the logger pipe. */
  2477. logPipe.readSide.close();
  2478. /* Get the hash info from stdout. */
  2479. string dummy = readLine(outPipe.readSide);
  2480. string expectedHashStr = statusOk(status) ? readLine(outPipe.readSide) : "";
  2481. outPipe.readSide.close();
  2482. /* Check the exit status and the build result. */
  2483. HashResult hash;
  2484. try {
  2485. if (!statusOk(status))
  2486. throw SubstError(format("fetching path `%1%' %2%")
  2487. % storePath % statusToString(status));
  2488. if (!pathExists(destPath))
  2489. throw SubstError(format("substitute did not produce path `%1%'") % destPath);
  2490. hash = hashPath(htSHA256, destPath);
  2491. /* Verify the expected hash we got from the substituer. */
  2492. if (expectedHashStr != "") {
  2493. size_t n = expectedHashStr.find(':');
  2494. if (n == string::npos)
  2495. throw Error(format("bad hash from substituter: %1%") % expectedHashStr);
  2496. HashType hashType = parseHashType(string(expectedHashStr, 0, n));
  2497. if (hashType == htUnknown)
  2498. throw Error(format("unknown hash algorithm in `%1%'") % expectedHashStr);
  2499. Hash expectedHash = parseHash16or32(hashType, string(expectedHashStr, n + 1));
  2500. Hash actualHash = hashType == htSHA256 ? hash.first : hashPath(hashType, destPath).first;
  2501. if (expectedHash != actualHash) {
  2502. if (settings.printBuildTrace)
  2503. printMsg(lvlError, format("@ hash-mismatch %1% %2% %3% %4%")
  2504. % storePath % "sha256"
  2505. % printHash16or32(expectedHash)
  2506. % printHash16or32(actualHash));
  2507. throw SubstError(format("hash mismatch for substituted item `%1%'") % storePath);
  2508. }
  2509. }
  2510. } catch (SubstError & e) {
  2511. printMsg(lvlInfo, e.msg());
  2512. if (settings.printBuildTrace) {
  2513. printMsg(lvlError, format("@ substituter-failed %1% %2% %3%")
  2514. % storePath % status % e.msg());
  2515. }
  2516. /* Try the next substitute. */
  2517. state = &SubstitutionGoal::tryNext;
  2518. worker.wakeUp(shared_from_this());
  2519. return;
  2520. }
  2521. if (repair) replaceValidPath(storePath, destPath);
  2522. canonicalisePathMetaData(storePath, -1);
  2523. worker.store.optimisePath(storePath); // FIXME: combine with hashPath()
  2524. ValidPathInfo info2;
  2525. info2.path = storePath;
  2526. info2.hash = hash.first;
  2527. info2.narSize = hash.second;
  2528. info2.references = info.references;
  2529. info2.deriver = info.deriver;
  2530. worker.store.registerValidPath(info2);
  2531. outputLock->setDeletion(true);
  2532. outputLock.reset();
  2533. worker.store.markContentsGood(storePath);
  2534. printMsg(lvlChatty,
  2535. format("substitution of path `%1%' succeeded") % storePath);
  2536. if (settings.printBuildTrace)
  2537. printMsg(lvlError, format("@ substituter-succeeded %1%") % storePath);
  2538. amDone(ecSuccess);
  2539. }
  2540. void SubstitutionGoal::handleChildOutput(int fd, const string & data)
  2541. {
  2542. assert(fd == logPipe.readSide);
  2543. if (verbosity >= settings.buildVerbosity) writeToStderr(data);
  2544. /* Don't write substitution output to a log file for now. We
  2545. probably should, though. */
  2546. }
  2547. void SubstitutionGoal::handleEOF(int fd)
  2548. {
  2549. if (fd == logPipe.readSide) worker.wakeUp(shared_from_this());
  2550. }
  2551. //////////////////////////////////////////////////////////////////////
  2552. static bool working = false;
  2553. Worker::Worker(LocalStore & store)
  2554. : store(store)
  2555. {
  2556. /* Debugging: prevent recursive workers. */
  2557. if (working) abort();
  2558. working = true;
  2559. nrLocalBuilds = 0;
  2560. lastWokenUp = 0;
  2561. permanentFailure = false;
  2562. timedOut = false;
  2563. }
  2564. Worker::~Worker()
  2565. {
  2566. working = false;
  2567. /* Explicitly get rid of all strong pointers now. After this all
  2568. goals that refer to this worker should be gone. (Otherwise we
  2569. are in trouble, since goals may call childTerminated() etc. in
  2570. their destructors). */
  2571. topGoals.clear();
  2572. }
  2573. GoalPtr Worker::makeDerivationGoal(const Path & path,
  2574. const StringSet & wantedOutputs, BuildMode buildMode)
  2575. {
  2576. GoalPtr goal = derivationGoals[path].lock();
  2577. if (!goal) {
  2578. goal = GoalPtr(new DerivationGoal(path, wantedOutputs, *this, buildMode));
  2579. derivationGoals[path] = goal;
  2580. wakeUp(goal);
  2581. } else
  2582. (dynamic_cast<DerivationGoal *>(goal.get()))->addWantedOutputs(wantedOutputs);
  2583. return goal;
  2584. }
  2585. GoalPtr Worker::makeSubstitutionGoal(const Path & path, bool repair)
  2586. {
  2587. GoalPtr goal = substitutionGoals[path].lock();
  2588. if (!goal) {
  2589. goal = GoalPtr(new SubstitutionGoal(path, *this, repair));
  2590. substitutionGoals[path] = goal;
  2591. wakeUp(goal);
  2592. }
  2593. return goal;
  2594. }
  2595. static void removeGoal(GoalPtr goal, WeakGoalMap & goalMap)
  2596. {
  2597. /* !!! inefficient */
  2598. for (WeakGoalMap::iterator i = goalMap.begin();
  2599. i != goalMap.end(); )
  2600. if (i->second.lock() == goal) {
  2601. WeakGoalMap::iterator j = i; ++j;
  2602. goalMap.erase(i);
  2603. i = j;
  2604. }
  2605. else ++i;
  2606. }
  2607. void Worker::removeGoal(GoalPtr goal)
  2608. {
  2609. nix::removeGoal(goal, derivationGoals);
  2610. nix::removeGoal(goal, substitutionGoals);
  2611. if (topGoals.find(goal) != topGoals.end()) {
  2612. topGoals.erase(goal);
  2613. /* If a top-level goal failed, then kill all other goals
  2614. (unless keepGoing was set). */
  2615. if (goal->getExitCode() == Goal::ecFailed && !settings.keepGoing)
  2616. topGoals.clear();
  2617. }
  2618. /* Wake up goals waiting for any goal to finish. */
  2619. foreach (WeakGoals::iterator, i, waitingForAnyGoal) {
  2620. GoalPtr goal = i->lock();
  2621. if (goal) wakeUp(goal);
  2622. }
  2623. waitingForAnyGoal.clear();
  2624. }
  2625. void Worker::wakeUp(GoalPtr goal)
  2626. {
  2627. goal->trace("woken up");
  2628. addToWeakGoals(awake, goal);
  2629. }
  2630. unsigned Worker::getNrLocalBuilds()
  2631. {
  2632. return nrLocalBuilds;
  2633. }
  2634. void Worker::childStarted(GoalPtr goal,
  2635. pid_t pid, const set<int> & fds, bool inBuildSlot,
  2636. bool respectTimeouts)
  2637. {
  2638. Child child;
  2639. child.goal = goal;
  2640. child.fds = fds;
  2641. child.timeStarted = child.lastOutput = time(0);
  2642. child.inBuildSlot = inBuildSlot;
  2643. child.respectTimeouts = respectTimeouts;
  2644. children[pid] = child;
  2645. if (inBuildSlot) nrLocalBuilds++;
  2646. }
  2647. void Worker::childTerminated(pid_t pid, bool wakeSleepers)
  2648. {
  2649. assert(pid != -1); /* common mistake */
  2650. Children::iterator i = children.find(pid);
  2651. assert(i != children.end());
  2652. if (i->second.inBuildSlot) {
  2653. assert(nrLocalBuilds > 0);
  2654. nrLocalBuilds--;
  2655. }
  2656. children.erase(pid);
  2657. if (wakeSleepers) {
  2658. /* Wake up goals waiting for a build slot. */
  2659. foreach (WeakGoals::iterator, i, wantingToBuild) {
  2660. GoalPtr goal = i->lock();
  2661. if (goal) wakeUp(goal);
  2662. }
  2663. wantingToBuild.clear();
  2664. }
  2665. }
  2666. void Worker::waitForBuildSlot(GoalPtr goal)
  2667. {
  2668. debug("wait for build slot");
  2669. if (getNrLocalBuilds() < settings.maxBuildJobs)
  2670. wakeUp(goal); /* we can do it right away */
  2671. else
  2672. addToWeakGoals(wantingToBuild, goal);
  2673. }
  2674. void Worker::waitForAnyGoal(GoalPtr goal)
  2675. {
  2676. debug("wait for any goal");
  2677. addToWeakGoals(waitingForAnyGoal, goal);
  2678. }
  2679. void Worker::waitForAWhile(GoalPtr goal)
  2680. {
  2681. debug("wait for a while");
  2682. addToWeakGoals(waitingForAWhile, goal);
  2683. }
  2684. void Worker::run(const Goals & _topGoals)
  2685. {
  2686. foreach (Goals::iterator, i, _topGoals) topGoals.insert(*i);
  2687. startNest(nest, lvlDebug, format("entered goal loop"));
  2688. while (1) {
  2689. checkInterrupt();
  2690. /* Call every wake goal (in the ordering established by
  2691. CompareGoalPtrs). */
  2692. while (!awake.empty() && !topGoals.empty()) {
  2693. Goals awake2;
  2694. for (auto & i : awake) {
  2695. GoalPtr goal = i.lock();
  2696. if (goal) awake2.insert(goal);
  2697. }
  2698. awake.clear();
  2699. for (auto & goal : awake2) {
  2700. checkInterrupt();
  2701. goal->work();
  2702. if (topGoals.empty()) break; // stuff may have been cancelled
  2703. }
  2704. }
  2705. if (topGoals.empty()) break;
  2706. /* Wait for input. */
  2707. if (!children.empty() || !waitingForAWhile.empty())
  2708. waitForInput();
  2709. else {
  2710. if (awake.empty() && settings.maxBuildJobs == 0) throw Error(
  2711. "unable to start any build; either increase `--max-jobs' "
  2712. "or enable distributed builds");
  2713. assert(!awake.empty());
  2714. }
  2715. }
  2716. /* If --keep-going is not set, it's possible that the main goal
  2717. exited while some of its subgoals were still active. But if
  2718. --keep-going *is* set, then they must all be finished now. */
  2719. assert(!settings.keepGoing || awake.empty());
  2720. assert(!settings.keepGoing || wantingToBuild.empty());
  2721. assert(!settings.keepGoing || children.empty());
  2722. }
  2723. void Worker::waitForInput()
  2724. {
  2725. printMsg(lvlVomit, "waiting for children");
  2726. /* Process output from the file descriptors attached to the
  2727. children, namely log output and output path creation commands.
  2728. We also use this to detect child termination: if we get EOF on
  2729. the logger pipe of a build, we assume that the builder has
  2730. terminated. */
  2731. bool useTimeout = false;
  2732. struct timeval timeout;
  2733. timeout.tv_usec = 0;
  2734. time_t before = time(0);
  2735. /* If we're monitoring for silence on stdout/stderr, or if there
  2736. is a build timeout, then wait for input until the first
  2737. deadline for any child. */
  2738. assert(sizeof(time_t) >= sizeof(long));
  2739. time_t nearest = LONG_MAX; // nearest deadline
  2740. foreach (Children::iterator, i, children) {
  2741. if (!i->second.respectTimeouts) continue;
  2742. if (settings.maxSilentTime != 0)
  2743. nearest = std::min(nearest, i->second.lastOutput + settings.maxSilentTime);
  2744. if (settings.buildTimeout != 0)
  2745. nearest = std::min(nearest, i->second.timeStarted + settings.buildTimeout);
  2746. }
  2747. if (nearest != LONG_MAX) {
  2748. timeout.tv_sec = std::max((time_t) 1, nearest - before);
  2749. useTimeout = true;
  2750. printMsg(lvlVomit, format("sleeping %1% seconds") % timeout.tv_sec);
  2751. }
  2752. /* If we are polling goals that are waiting for a lock, then wake
  2753. up after a few seconds at most. */
  2754. if (!waitingForAWhile.empty()) {
  2755. useTimeout = true;
  2756. if (lastWokenUp == 0)
  2757. printMsg(lvlError, "waiting for locks or build slots...");
  2758. if (lastWokenUp == 0 || lastWokenUp > before) lastWokenUp = before;
  2759. timeout.tv_sec = std::max((time_t) 1, (time_t) (lastWokenUp + settings.pollInterval - before));
  2760. } else lastWokenUp = 0;
  2761. using namespace std;
  2762. /* Use select() to wait for the input side of any logger pipe to
  2763. become `available'. Note that `available' (i.e., non-blocking)
  2764. includes EOF. */
  2765. fd_set fds;
  2766. FD_ZERO(&fds);
  2767. int fdMax = 0;
  2768. foreach (Children::iterator, i, children) {
  2769. foreach (set<int>::iterator, j, i->second.fds) {
  2770. FD_SET(*j, &fds);
  2771. if (*j >= fdMax) fdMax = *j + 1;
  2772. }
  2773. }
  2774. if (select(fdMax, &fds, 0, 0, useTimeout ? &timeout : 0) == -1) {
  2775. if (errno == EINTR) return;
  2776. throw SysError("waiting for input");
  2777. }
  2778. time_t after = time(0);
  2779. /* Process all available file descriptors. */
  2780. /* Since goals may be canceled from inside the loop below (causing
  2781. them go be erased from the `children' map), we have to be
  2782. careful that we don't keep iterators alive across calls to
  2783. timedOut(). */
  2784. set<pid_t> pids;
  2785. foreach (Children::iterator, i, children) pids.insert(i->first);
  2786. foreach (set<pid_t>::iterator, i, pids) {
  2787. checkInterrupt();
  2788. Children::iterator j = children.find(*i);
  2789. if (j == children.end()) continue; // child destroyed
  2790. GoalPtr goal = j->second.goal.lock();
  2791. assert(goal);
  2792. set<int> fds2(j->second.fds);
  2793. foreach (set<int>::iterator, k, fds2) {
  2794. if (FD_ISSET(*k, &fds)) {
  2795. unsigned char buffer[4096];
  2796. ssize_t rd = read(*k, buffer, sizeof(buffer));
  2797. if (rd == -1) {
  2798. if (errno != EINTR)
  2799. throw SysError(format("reading from %1%")
  2800. % goal->getName());
  2801. } else if (rd == 0) {
  2802. debug(format("%1%: got EOF") % goal->getName());
  2803. goal->handleEOF(*k);
  2804. j->second.fds.erase(*k);
  2805. } else {
  2806. printMsg(lvlVomit, format("%1%: read %2% bytes")
  2807. % goal->getName() % rd);
  2808. string data((char *) buffer, rd);
  2809. j->second.lastOutput = after;
  2810. goal->handleChildOutput(*k, data);
  2811. }
  2812. }
  2813. }
  2814. if (goal->getExitCode() == Goal::ecBusy &&
  2815. settings.maxSilentTime != 0 &&
  2816. j->second.respectTimeouts &&
  2817. after - j->second.lastOutput >= (time_t) settings.maxSilentTime)
  2818. {
  2819. printMsg(lvlError,
  2820. format("%1% timed out after %2% seconds of silence")
  2821. % goal->getName() % settings.maxSilentTime);
  2822. goal->timedOut();
  2823. }
  2824. else if (goal->getExitCode() == Goal::ecBusy &&
  2825. settings.buildTimeout != 0 &&
  2826. j->second.respectTimeouts &&
  2827. after - j->second.timeStarted >= (time_t) settings.buildTimeout)
  2828. {
  2829. printMsg(lvlError,
  2830. format("%1% timed out after %2% seconds")
  2831. % goal->getName() % settings.buildTimeout);
  2832. goal->timedOut();
  2833. }
  2834. }
  2835. if (!waitingForAWhile.empty() && lastWokenUp + settings.pollInterval <= after) {
  2836. lastWokenUp = after;
  2837. foreach (WeakGoals::iterator, i, waitingForAWhile) {
  2838. GoalPtr goal = i->lock();
  2839. if (goal) wakeUp(goal);
  2840. }
  2841. waitingForAWhile.clear();
  2842. }
  2843. }
  2844. unsigned int Worker::exitStatus()
  2845. {
  2846. return timedOut ? 101 : (permanentFailure ? 100 : 1);
  2847. }
  2848. //////////////////////////////////////////////////////////////////////
  2849. void LocalStore::buildPaths(const PathSet & drvPaths, BuildMode buildMode)
  2850. {
  2851. startNest(nest, lvlDebug,
  2852. format("building %1%") % showPaths(drvPaths));
  2853. Worker worker(*this);
  2854. Goals goals;
  2855. foreach (PathSet::const_iterator, i, drvPaths) {
  2856. DrvPathWithOutputs i2 = parseDrvPathWithOutputs(*i);
  2857. if (isDerivation(i2.first))
  2858. goals.insert(worker.makeDerivationGoal(i2.first, i2.second, buildMode));
  2859. else
  2860. goals.insert(worker.makeSubstitutionGoal(*i, buildMode));
  2861. }
  2862. worker.run(goals);
  2863. PathSet failed;
  2864. foreach (Goals::iterator, i, goals)
  2865. if ((*i)->getExitCode() == Goal::ecFailed) {
  2866. DerivationGoal * i2 = dynamic_cast<DerivationGoal *>(i->get());
  2867. if (i2) failed.insert(i2->getDrvPath());
  2868. else failed.insert(dynamic_cast<SubstitutionGoal *>(i->get())->getStorePath());
  2869. }
  2870. if (!failed.empty())
  2871. throw Error(format("build of %1% failed") % showPaths(failed), worker.exitStatus());
  2872. }
  2873. void LocalStore::ensurePath(const Path & path)
  2874. {
  2875. /* If the path is already valid, we're done. */
  2876. if (isValidPath(path)) return;
  2877. Worker worker(*this);
  2878. GoalPtr goal = worker.makeSubstitutionGoal(path);
  2879. Goals goals = singleton<Goals>(goal);
  2880. worker.run(goals);
  2881. if (goal->getExitCode() != Goal::ecSuccess)
  2882. throw Error(format("path `%1%' does not exist and cannot be created") % path, worker.exitStatus());
  2883. }
  2884. void LocalStore::repairPath(const Path & path)
  2885. {
  2886. Worker worker(*this);
  2887. GoalPtr goal = worker.makeSubstitutionGoal(path, true);
  2888. Goals goals = singleton<Goals>(goal);
  2889. worker.run(goals);
  2890. if (goal->getExitCode() != Goal::ecSuccess) {
  2891. /* Since substituting the path didn't work, if we have a valid
  2892. deriver, then rebuild the deriver. */
  2893. Path deriver = queryDeriver(path);
  2894. if (deriver != "" && isValidPath(deriver)) {
  2895. goals.clear();
  2896. goals.insert(worker.makeDerivationGoal(deriver, StringSet(), bmRepair));
  2897. worker.run(goals);
  2898. } else
  2899. throw Error(format("cannot repair path `%1%'") % path, worker.exitStatus());
  2900. }
  2901. }
  2902. }