about summary refs log tree commit diff
path: root/src/normalise.cc
blob: 0dfc9f8e4d12f251c67081957bfce7fc29a9a9f0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
#include <map>

#include "normalise.hh"
#include "references.hh"
#include "db.hh"
#include "exec.hh"
#include "pathlocks.hh"
#include "globals.hh"


static Path useSuccessor(const Path & path)
{
    string pathSucc;
    if (nixDB.queryString(noTxn, dbSuccessors, path, pathSucc)) {
        debug(format("successor %1% -> %2%") % (string) path % pathSucc);
        return pathSucc;
    } else
        return path;
}


#if 0
/* Return a path whose contents have the given hash.  If target is
   not empty, ensure that such a path is realised in target (if
   necessary by copying from another location).  If prefix is not
   empty, only return a path that is an descendent of prefix. */

string expandId(const FSId & id, const string & target = "",
    const string & prefix = "/", FSIdSet pending = FSIdSet(),
    bool ignoreSubstitutes = false)
{
    xxx
}


string expandId(const FSId & id, const string & target,
    const string & prefix, FSIdSet pending, bool ignoreSubstitutes)
{
    Nest nest(lvlDebug, format("expanding %1%") % (string) id);

    Strings paths;

    if (!target.empty() && !isInPrefix(target, prefix))
        abort();

    nixDB.queryStrings(noTxn, dbId2Paths, id, paths);

    /* Pick one equal to `target'. */
    if (!target.empty()) {

        for (Strings::iterator i = paths.begin();
             i != paths.end(); i++)
        {
            string path = *i;
            if (path == target && pathExists(path))
                return path;
        }
        
    }

    /* Arbitrarily pick the first one that exists and isn't stale. */
    for (Strings::iterator it = paths.begin();
         it != paths.end(); it++)
    {
        string path = *it;
        if (isInPrefix(path, prefix) && pathExists(path)) {
            if (target.empty())
                return path;
            else {
                /* Acquire a lock on the target path. */
                Strings lockPaths;
                lockPaths.push_back(target);
                PathLocks outputLock(lockPaths);

                /* Copy. */
                copyPath(path, target);

                /* Register the target path. */
                Transaction txn(nixDB);
                registerPath(txn, target, id);
                txn.commit();

                return target;
            }
        }
    }

    if (!ignoreSubstitutes) {
        
        if (pending.find(id) != pending.end())
            throw Error(format("id %1% already being expanded") % (string) id);
        pending.insert(id);

        /* Try to realise the substitutes, but only if this id is not
           already being realised by a substitute. */
        Strings subs;
        nixDB.queryStrings(noTxn, dbSubstitutes, id, subs); /* non-existence = ok */

        for (Strings::iterator it = subs.begin(); it != subs.end(); it++) {
            FSId subId = parseHash(*it);

            debug(format("trying substitute %1%") % (string) subId);

            realiseClosure(normaliseNixExpr(subId, pending), pending);

            return expandId(id, target, prefix, pending);
        }

    }
    
    throw Error(format("cannot expand id `%1%'") % (string) id);
}
#endif

    
Path normaliseNixExpr(const Path & _nePath, PathSet pending)
{
    Nest nest(lvlTalkative,
        format("normalising expression in `%1%'") % (string) _nePath);

    /* Try to substitute the expression by any known successors in
       order to speed up the rewrite process. */
    Path nePath = useSuccessor(_nePath);

    /* Get the Nix expression. */
    NixExpr ne = parseNixExpr(termFromPath(nePath));

    /* If this is a normal form (i.e., a closure) we are done. */
    if (ne.type == NixExpr::neClosure) return nePath;
    if (ne.type != NixExpr::neDerivation) abort();
    

    /* Otherwise, it's a derivation expression, and we have to build it to
       determine its normal form. */


    /* Some variables. */

    /* Input paths, with their closure elements. */
    ClosureElems inClosures; 

    /* Referenceable paths (i.e., input and output paths). */
    PathSet allPaths;

    /* The environment to be passed to the builder. */
    Environment env; 

    /* The result. */
    NixExpr nf;
    nf.type = NixExpr::neClosure;


    /* The outputs are referenceable paths. */
    for (PathSet::iterator i = ne.derivation.outputs.begin();
         i != ne.derivation.outputs.end(); i++)
    {
        debug(format("building path `%1%'") % *i);
        allPaths.insert(*i);
    }

    /* Obtain locks on all output paths.  The locks are automatically
       released when we exit this function or Nix crashes. */
    PathLocks outputLocks(ne.derivation.outputs);

    /* Now check again whether there is a successor.  This is because
       another process may have started building in parallel.  After
       it has finished and released the locks, we can (and should)
       reuse its results.  (Strictly speaking the first successor
       check above can be omitted, but that would be less efficient.)
       Note that since we now hold the locks on the output paths, no
       other process can build this expression, so no further checks
       are necessary. */
    {
        Path nePath2 = useSuccessor(nePath);
        if (nePath != nePath2) {
            NixExpr ne = parseNixExpr(termFromPath(nePath2));
            debug(format("skipping build of expression `%1%', someone beat us to it")
		  % (string) nePath);
            if (ne.type != NixExpr::neClosure) abort();
            return nePath2;
        }
    }

    /* Right platform? */
    if (ne.derivation.platform != thisSystem)
        throw Error(format("a `%1%' is required, but I am a `%2%'")
		    % ne.derivation.platform % thisSystem);
        
    /* Realise inputs (and remember all input paths). */
    for (PathSet::iterator i = ne.derivation.inputs.begin();
         i != ne.derivation.inputs.end(); i++)
    {
        Path nfPath = normaliseNixExpr(*i, pending);
        realiseClosure(nfPath, pending);
        /* !!! nfPath should be a root of the garbage collector while
           we are building */
        NixExpr ne = parseNixExpr(termFromPath(nfPath));
        if (ne.type != NixExpr::neClosure) abort();
        for (ClosureElems::iterator j = ne.closure.elems.begin();
             j != ne.closure.elems.end(); j++)
	{
            inClosures[j->first] = j->second;
	    allPaths.insert(j->first);
	}
    }

    /* Most shells initialise PATH to some default (/bin:/usr/bin:...) when
       PATH is not set.  We don't want this, so we fill it in with some dummy
       value. */
    env["PATH"] = "/path-not-set";

    /* Set HOME to a non-existing path to prevent certain programs from using
       /etc/passwd (or NIS, or whatever) to locate the home directory (for
       example, wget looks for ~/.wgetrc).  I.e., these tools use /etc/passwd
       if HOME is not set, but they will just assume that the settings file
       they are looking for does not exist if HOME is set but points to some
       non-existing path. */
    env["HOME"] = "/homeless-shelter";

    /* Build the environment. */
    for (StringPairs::iterator i = ne.derivation.env.begin();
         i != ne.derivation.env.end(); i++)
        env[i->first] = i->second;

    /* We can skip running the builder if we can expand all output
       paths from their ids. */
    bool fastBuild = false;
#if 0
    bool fastBuild = true;
    for (PathSet::iterator i = ne.derivation.outputs.begin();
         i != ne.derivation.outputs.end(); i++)
    {
        try {
            expandId(i->second, i->first, "/", pending);
        } catch (Error & e) {
            debug(format("fast build failed for `%1%': %2%")
		  % i->first % e.what());
            fastBuild = false;
            break;
        }
    }
#endif

    if (!fastBuild) {

        /* If any of the outputs already exist but are not registered,
           delete them. */
        for (PathSet::iterator i = ne.derivation.outputs.begin(); 
             i != ne.derivation.outputs.end(); i++)
        {
            Path path = *i;
            if (isValidPath(path))
                throw Error(format("obstructed build: path `%1%' exists") % path);
            if (pathExists(path)) {
                debug(format("removing unregistered path `%1%'") % path);
                deletePath(path);
            }
        }

        /* Run the builder. */
        msg(lvlChatty, format("building..."));
        runProgram(ne.derivation.builder, ne.derivation.args, env);
        msg(lvlChatty, format("build completed"));
        
    } else
        msg(lvlChatty, format("fast build succesful"));

    /* Check whether the output paths were created, and grep each
       output path to determine what other paths it references.  Also make all
       output paths read-only. */
    PathSet usedPaths;
    for (PathSet::iterator i = ne.derivation.outputs.begin(); 
         i != ne.derivation.outputs.end(); i++)
    {
        Path path = *i;
        if (!pathExists(path))
            throw Error(format("path `%1%' does not exist") % path);
        nf.closure.roots.insert(path);

	makePathReadOnly(path);

	/* For this output path, find the references to other paths contained
	   in it. */
        Strings refPaths = filterReferences(path, 
            Strings(allPaths.begin(), allPaths.end()));

	/* Construct a closure element for this output path. */
        ClosureElem elem;

	/* For each path referenced by this output path, add its id to the
	   closure element and add the id to the `usedPaths' set (so that the
	   elements referenced by *its* closure are added below). */
        for (Paths::iterator j = refPaths.begin();
	     j != refPaths.end(); j++)
	{
	    Path path = *j;
	    elem.refs.insert(path);
            if (inClosures.find(path) != inClosures.end())
                usedPaths.insert(path);
	    else if (ne.derivation.outputs.find(path) == ne.derivation.outputs.end())
		abort();
        }

        nf.closure.elems[path] = elem;
    }

    /* Close the closure.  That is, for any referenced path, add the paths
       referenced by it. */
    PathSet donePaths;

    while (!usedPaths.empty()) {
	PathSet::iterator i = usedPaths.begin();
	Path path = *i;
	usedPaths.erase(i);

	if (donePaths.find(path) != donePaths.end()) continue;
	donePaths.insert(path);

	ClosureElems::iterator j = inClosures.find(path);
	if (j == inClosures.end()) abort();

	nf.closure.elems[path] = j->second;

	for (PathSet::iterator k = j->second.refs.begin();
	     k != j->second.refs.end(); k++)
	    usedPaths.insert(*k);
    }

    /* For debugging, print out the referenced and unreferenced paths. */
    for (ClosureElems::iterator i = inClosures.begin();
         i != inClosures.end(); i++)
    {
        PathSet::iterator j = donePaths.find(i->first);
        if (j == donePaths.end())
            debug(format("NOT referenced: `%1%'") % i->first);
        else
            debug(format("referenced: `%1%'") % i->first);
    }

    /* Write the normal form.  This does not have to occur in the
       transaction below because writing terms is idem-potent. */
    ATerm nfTerm = unparseNixExpr(nf);
    msg(lvlVomit, format("normal form: %1%") % printTerm(nfTerm));
    Path nfPath = writeTerm(nfTerm, "-s");

    /* Register each outpat path, and register the normal form.  This
       is wrapped in one database transaction to ensure that if we
       crash, either everything is registered or nothing is.  This is
       for recoverability: unregistered paths in the store can be
       deleted arbitrarily, while registered paths can only be deleted
       by running the garbage collector. */
    Transaction txn(nixDB);
    for (PathSet::iterator i = ne.derivation.outputs.begin(); 
         i != ne.derivation.outputs.end(); i++)
        registerValidPath(txn, *i);
    registerSuccessor(txn, nePath, nfPath);
    txn.commit();

    return nfPath;
}


void realiseClosure(const Path & nePath, PathSet pending)
{
    Nest nest(lvlDebug, format("realising closure `%1%'") % nePath);

    NixExpr ne = parseNixExpr(termFromPath(nePath));
    if (ne.type != NixExpr::neClosure)
        throw Error(format("expected closure in `%1%'") % nePath);
    
    for (ClosureElems::const_iterator i = ne.closure.elems.begin();
         i != ne.closure.elems.end(); i++)
        assert(isValidPath(i->first));
#if 0
        expandId(i->second.id, i->first, "/", pending);
#endif
}


PathSet nixExprRoots(const Path & nePath)
{
    PathSet paths;

    NixExpr ne = parseNixExpr(termFromPath(nePath));

    if (ne.type == NixExpr::neClosure)
        paths.insert(ne.closure.roots.begin(), ne.closure.roots.end());
    else if (ne.type == NixExpr::neDerivation)
        paths.insert(ne.derivation.outputs.begin(),
            ne.derivation.outputs.end());
    else abort();

    return paths;
}


static void requisitesWorker(const Path & nePath,
    bool includeExprs, bool includeSuccessors,
    PathSet & paths, PathSet & doneSet)
{
    if (doneSet.find(nePath) != doneSet.end()) return;
    doneSet.insert(nePath);

    NixExpr ne = parseNixExpr(termFromPath(nePath));

    if (ne.type == NixExpr::neClosure)
        for (ClosureElems::iterator i = ne.closure.elems.begin();
             i != ne.closure.elems.end(); i++)
            paths.insert(i->first);
    
    else if (ne.type == NixExpr::neDerivation)
        for (PathSet::iterator i = ne.derivation.inputs.begin();
             i != ne.derivation.inputs.end(); i++)
            requisitesWorker(*i,
                includeExprs, includeSuccessors, paths, doneSet);

    else abort();

    if (includeExprs) paths.insert(nePath);

    string nfPath;
    if (includeSuccessors && (nfPath = useSuccessor(nePath)) != nePath)
        requisitesWorker(nfPath, includeExprs, includeSuccessors,
            paths, doneSet);
}


PathSet nixExprRequisites(const Path & nePath,
    bool includeExprs, bool includeSuccessors)
{
    PathSet paths;
    PathSet doneSet;
    requisitesWorker(nePath, includeExprs, includeSuccessors,
        paths, doneSet);
    return paths;
}


#if 0
PathSet findGenerators(const PathSet & outputs)
{
    FSIdSet ids(_ids.begin(), _ids.end());
    FSIds generators;

    /* !!! hack; for performance, we just look at the rhs of successor
       mappings, since we know that those are Nix expressions. */

    Strings sucs;
    nixDB.enumTable(noTxn, dbSuccessors, sucs);

    for (Strings::iterator i = sucs.begin();
         i != sucs.end(); i++)
    {
        string s;
        if (!nixDB.queryString(noTxn, dbSuccessors, *i, s)) continue;
        FSId id = parseHash(s);

        NixExpr ne;
        try {
            /* !!! should substitutes be used? */
            ne = parseNixExpr(termFromId(id));
        } catch (...) { /* !!! only catch parse errors */
            continue;
        }

        if (ne.type != NixExpr::neClosure) continue;
        
        bool okay = true;
        for (ClosureElems::const_iterator i = ne.closure.elems.begin();
             i != ne.closure.elems.end(); i++)
            if (ids.find(i->second.id) == ids.end()) {
                okay = false;
                break;
            }
        
        if (!okay) continue;
        
        generators.push_back(id);
    }

    return generators;
}
#endif