Nix 2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Loading...
Searching...
No Matches
local-store.hh
Go to the documentation of this file.
1#pragma once
3
4#include "nix/store/sqlite.hh"
5
9#include "nix/util/sync.hh"
11
12#include <chrono>
13#include <future>
14#include <list>
15#include <string>
16#include <boost/unordered/unordered_flat_set.hpp>
17
18namespace nix {
19
28const int nixSchemaVersion = 10;
29
31{
32 unsigned long filesLinked = 0;
33 uint64_t bytesFreed = 0;
34};
35
36struct LocalSettings;
37
38struct LocalBuildStoreConfig : virtual LocalFSStoreConfig
39{
40private:
41 void anchor() override;
42
47 this,
48 std::nullopt,
49 "build-dir",
50 R"(
51 The directory on the host, in which derivations' temporary build directories are created.
52
53 If not set, Nix will use the `builds` subdirectory of its configured state directory.
54
55 Note that builds are often performed by the Nix daemon, so its `build-dir` applies.
56
57 Nix will create this directory automatically with suitable permissions if it does not exist.
58 Otherwise its permissions must allow all users to traverse the directory (i.e. it must have `o+x` set, in unix parlance) for non-sandboxed builds to work correctly.
59
60 This is also the location where [`--keep-failed`](@docroot@/command-ref/opt-common.md#opt-keep-failed) leaves its files.
61
62 If Nix runs without sandbox, or if the platform does not support sandboxing with bind mounts (e.g. macOS), then the [`builder`](@docroot@/language/derivations.md#attr-builder)'s environment will contain this directory, instead of the virtual location [`sandbox-build-dir`](@docroot@/command-ref/conf-file.md#conf-sandbox-build-dir).
63
64 > **Warning**
65 >
66 > `build-dir` must not be set to a world-writable directory.
67 > Placing temporary build directories in a world-writable place allows other users to access or modify build data that is currently in use.
68 > This alone is merely an impurity, but combined with another factor this has allowed malicious derivations to escape the build sandbox.
69
70 See also the global [`build-dir`](@docroot@/command-ref/conf-file.md#conf-build-dir) setting.
71 )"};
72public:
77 const LocalSettings & getLocalSettings() const;
78
79 std::filesystem::path getBuildDir() const;
80};
81
82struct LocalStoreConfig : std::enable_shared_from_this<LocalStoreConfig>,
83 virtual LocalFSStoreConfig,
85{
86 LocalStoreConfig(const Params & params)
88 , LocalFSStoreConfig(params)
89 {
90 }
91
92 LocalStoreConfig(const std::filesystem::path & path, const Params & params);
93
94private:
95 void anchor() override;
96
101 bool getDefaultRequireSigs();
102
103public:
104 Setting<bool> requireSigs{
105 this,
106 getDefaultRequireSigs(),
107 "require-sigs",
108 "Whether store paths copied into this store should have a trusted signature."};
109
110 Setting<bool> readOnly{
111 this,
112 false,
113 "read-only",
114 R"(
115 Allow this store to be opened when its [database](@docroot@/glossary.md#gloss-nix-database) is on a read-only filesystem.
116
117 Normally Nix attempts to open the store database in read-write mode, even for querying (when write access is not needed), causing it to fail if the database is on a read-only filesystem.
118
119 Enable read-only mode to disable locking and open the SQLite database with the [`immutable` parameter](https://www.sqlite.org/c3ref/open.html) set.
120
121 > **Warning**
122 > Do not use this unless the filesystem is read-only.
123 >
124 > Using it when the filesystem is writable can cause incorrect query results or corruption errors if the database is changed by another process.
125 > While the filesystem the database resides on might appear to be read-only, consider whether another user or system might have write access to it.
126 )"};
127
128 bool getReadOnly() const override;
129
130 Setting<bool> ignoreGcDeleteFailure{
131 this,
132 false,
133 "ignore-gc-delete-failure",
134 R"(
135 Whether to ignore failures when deleting items with the garbage collector.
136
137 Normally the garbage collector will fail with an error if the nix daemon cannot delete a file, with this setting such errors will only be printed as warnings.
138 )",
139 {},
140 true,
141 Xp::LocalOverlayStore,
142 };
143
144 Setting<bool> useRootsDaemon{
145 this,
146 false,
147 "use-roots-daemon",
148 R"(
149 Whether to request garbage collector roots from an external daemon.
150
151 When enabled, the garbage collector connects to a Unix domain socket
152 at [`<state-dir>`](@docroot@/store/types/local-store.md#store-local-store-state)`/gc-roots-socket/socket` to discover additional roots
153 that should not be collected. This is useful when the Nix daemon runs
154 without root privileges and cannot scan `/proc` for runtime roots.
155
156 The daemon can be started with [`nix store roots-daemon`](@docroot@/command-ref/new-cli/nix3-store-roots-daemon.md).
157 )",
158 {},
159 true,
160 Xp::LocalOverlayStore,
161 };
162
163 std::filesystem::path getRootsSocketPath() const;
164
165 static const std::string name()
166 {
167 return "Local Store";
168 }
169
170 static StringSet uriSchemes()
171 {
172 return {"local"};
173 }
174
175 static std::string doc();
176
177 ref<Store> openStore() const override;
178
179 StoreReference getReference() const override;
180};
181
182MakeError(PathInUse, Error);
183
184class LocalStore : public virtual IndirectRootStore, public virtual GcStore
185{
186 void anchor() override;
187
188public:
189
190 using Config = LocalStoreConfig;
191
193
194private:
195
199 AutoCloseFD globalLock;
200
201 struct State
202 {
206 SQLite db;
207
208 struct Stmts;
209 std::unique_ptr<Stmts> stmts;
210
215 std::chrono::time_point<std::chrono::steady_clock> lastGCCheck;
216
221 bool gcRunning = false;
222 std::shared_future<void> gcFuture;
223 std::thread gcThread;
224
231 uint64_t availAfterGC = std::numeric_limits<uint64_t>::max();
232
233 std::unique_ptr<PublicKeys> publicKeys;
234 };
235
240 ref<Sync<State>> _state;
241
242public:
243
244 const std::filesystem::path dbDir;
245 const std::filesystem::path linksDir;
246 const std::filesystem::path reservedPath;
247 const std::filesystem::path schemaPath;
248 const std::filesystem::path tempRootsDir;
249 const std::filesystem::path fnTempRoots;
250
251private:
252
253 const PublicKeys & getPublicKeys();
254
255public:
256
260 PathSet locksHeld;
261
267
268 ~LocalStore();
269
273
274 bool isValidPathUncached(const StorePath & path) override;
275
276 StorePathSet queryValidPaths(const StorePathSet & paths, SubstituteFlag maybeSubstitute = NoSubstitute) override;
277
278 StorePathSet queryAllValidPaths() override;
279
280 void queryPathInfoUncached(
281 const StorePath & path, Callback<std::shared_ptr<const ValidPathInfo>> callback) noexcept override;
282
283 void queryReferrers(const StorePath & path, StorePathSet & referrers) override;
284
285 StorePathSet queryValidDerivers(const StorePath & path) override;
286
287 std::map<std::string, std::optional<StorePath>>
289
290 std::optional<StorePath>
291 queryStaticPartialDerivationOutput(const StorePath & path, const std::string & outputName) override;
292
293 std::optional<StorePath> queryPathFromHashPart(const std::string & hashPart) override;
294
295 bool pathInfoIsUntrusted(const ValidPathInfo &) override;
296 bool realisationIsUntrusted(const Realisation &) override;
297
298 void addToStore(const ValidPathInfo & info, Source & source, RepairFlag repair, CheckSigsFlag checkSigs) override;
299
301 Source & dump,
302 std::string_view name,
303 FileSerialisationMethod dumpMethod,
304 ContentAddressMethod hashMethod,
305 HashAlgorithm hashAlgo,
306 const StorePathSet & references,
307 RepairFlag repair) override;
308
309 // Designed to be used from RestrictedStore,
310 // allows filtering the references while scanning.
311 // Not an entirely separate function in order to reduce duplication
313 Source & dump,
314 std::string_view name,
315 FileSerialisationMethod dumpMethod,
316 ContentAddressMethod hashMethod,
317 HashAlgorithm hashAlgo,
318 const StorePathSet & references,
319 RepairFlag repair,
320 bool filterReferences);
321
322 void addTempRoots(const StorePathSet & paths) override;
323
324private:
325
326 void createTempRootsFile();
327
331 Sync<AutoCloseFD> _fdTempRoots;
332
336 Sync<AutoCloseFD> _fdGCLock;
337
341 Sync<AutoCloseFD> _fdRootsSocket;
342
343public:
344
351 void addIndirectRoot(const std::filesystem::path & path) override;
352
353private:
354
355 void findTempRoots(Roots & roots, bool censor);
356
357 AutoCloseFD openGCLock();
358
359public:
360
361 Roots findRoots(bool censor) override;
362
363 void collectGarbage(const GCOptions & options, GCResults & results) override;
364
365 void deleteBuildTraces(const std::set<DrvOutput> & keys) override;
366
374 virtual void queryGCReferrers(const StorePath & path, StorePathSet & referrers)
375 {
376 return queryReferrers(path, referrers);
377 }
378
392 virtual void deleteStorePath(const std::filesystem::path & path, uint64_t & bytesFreed, bool isKnownPath);
393
398 void optimiseStore(OptimiseStats & stats);
399
400 void optimiseStore() override;
401
406 void optimisePath(const std::filesystem::path & path, RepairFlag repair);
407
408 bool verifyStore(bool checkContents, RepairFlag repair) override;
409
410protected:
411
416 {
420 bool errors;
421
426 StorePathSet validPaths;
427 };
428
432 virtual VerificationResult verifyAllValidPaths(RepairFlag repair);
433
434public:
435
444 void registerValidPath(const ValidPathInfo & info);
445
446 virtual void registerValidPaths(const ValidPathInfos & infos);
447
448 unsigned int getProtocol() override;
449
450 std::optional<TrustedFlag> isTrustedClient() override;
451
452 void vacuumDB();
453
454 void addSignatures(const StorePath & storePath, const std::set<Signature> & sigs) override;
455
460 void autoGC(bool sync = true);
461
466 void registerDrvOutputUnchecked(const Realisation & info) override;
467 void registerDrvOutput(const Realisation & info, CheckSigsFlag checkSigs) override;
468 void cacheDrvOutputMapping(
469 State & state, const uint64_t deriver, const std::string & outputName, const StorePath & output);
470
471 std::optional<const UnkeyedRealisation> queryRealisation_(State & state, const DrvOutput & id);
472 std::optional<std::pair<int64_t, UnkeyedRealisation>> queryRealisationCore_(State & state, const DrvOutput & id);
473 void queryRealisationUncached(
474 const DrvOutput &, Callback<std::shared_ptr<const UnkeyedRealisation>> callback) noexcept override;
475
476 std::optional<std::string> getVersion() override;
477
478protected:
479
480 void verifyPath(
481 const StorePath & path,
482 fun<bool(const StorePath &)> existsInStoreDir,
483 StorePathSet & done,
484 StorePathSet & validPaths,
485 RepairFlag repair,
486 bool & errors);
487
488private:
489
494 int getSchema();
495
496 void openDB(State & state, bool create);
497
503 bool upgradeDBSchema(State & state, bool dryRun);
504
505 void makeStoreWritable();
506
507 uint64_t queryValidPathId(State & state, const StorePath & path);
508
509 uint64_t addValidPath(State & state, const ValidPathInfo & info);
510
511 void invalidatePath(State & state, const StorePath & path);
512
516 void invalidatePathChecked(const StorePath & path);
517
518 std::shared_ptr<const ValidPathInfo> queryPathInfoInternal(State & state, const StorePath & path);
519
520 void updatePathInfo(State & state, const ValidPathInfo & info);
521
522 void findRoots(const std::filesystem::path & path, std::filesystem::file_type type, Roots & roots);
523
524 void findRootsNoTemp(Roots & roots, bool censor);
525
526 void findRuntimeRoots(Roots & roots, bool censor);
527
528 std::pair<std::filesystem::path, AutoCloseFD> createTempDirInStore();
529
530 typedef boost::unordered_flat_set<ino_t> InodeHash;
531
532 InodeHash loadInodeHash();
533 std::list<OsFilename> readDirectoryIgnoringInodes(const std::filesystem::path & path, const InodeHash & inodeHash);
534 void optimisePath_(
535 Activity * act,
536 OptimiseStats & stats,
537 const std::filesystem::path & path,
538 InodeHash & inodeHash,
539 RepairFlag repair);
540
541 // Internal versions that are not wrapped in retry_sqlite.
542 bool isValidPath_(State & state, const StorePath & path);
543 void queryReferrers(State & state, const StorePath & path, StorePathSet & referrers);
544
545 void addBuildLog(const StorePath & drvPath, std::string_view log) override;
546
547 friend class PathSubstitutionGoal;
548 friend struct DerivationGoal;
549 /* Only used for createTempDirInStore. */
550 friend class DerivationBuilderImpl;
551};
552
553} // namespace nix
Definition file-descriptor.hh:265
Definition callback.hh:19
Definition error.hh:310
virtual VerificationResult verifyAllValidPaths(RepairFlag repair)
Definition local-store.cc:1558
StorePathSet queryValidPaths(const StorePathSet &paths, SubstituteFlag maybeSubstitute=NoSubstitute) override
Definition local-store.cc:852
virtual void deleteStorePath(const std::filesystem::path &path, uint64_t &bytesFreed, bool isKnownPath)
Definition local-store.cc:400
StorePathSet queryAllValidPaths() override
Definition local-store.cc:861
Roots findRoots(bool censor) override
Definition gc.cc:320
void addIndirectRoot(const std::filesystem::path &path) override
Definition gc.cc:48
std::optional< TrustedFlag > isTrustedClient() override
Definition local-store.cc:1652
void queryReferrers(const StorePath &path, StorePathSet &referrers) override
Definition local-store.cc:881
bool pathInfoIsUntrusted(const ValidPathInfo &) override
Definition local-store.cc:1052
void deleteBuildTraces(const std::set< DrvOutput > &keys) override
Definition local-store.cc:696
void optimisePath(const std::filesystem::path &path, RepairFlag repair)
Definition optimise-store.cc:335
StorePathSet queryValidDerivers(const StorePath &path) override
Definition local-store.cc:886
void addToStore(const ValidPathInfo &info, Source &source, RepairFlag repair, CheckSigsFlag checkSigs) override
Definition local-store.cc:1062
void collectGarbage(const GCOptions &options, GCResults &results) override
Definition gc.cc:372
void registerValidPath(const ValidPathInfo &info)
Definition local-store.cc:960
std::optional< StorePath > queryStaticPartialDerivationOutput(const StorePath &path, const std::string &outputName) override
Definition local-store.cc:918
bool verifyStore(bool checkContents, RepairFlag repair) override
Definition local-store.cc:1459
unsigned int getProtocol() override
Definition local-store.cc:1647
void addSignatures(const StorePath &storePath, const std::set< Signature > &sigs) override
Definition local-store.cc:1662
StorePath addToStoreFromDump(Source &dump, std::string_view name, FileSerialisationMethod dumpMethod, ContentAddressMethod hashMethod, HashAlgorithm hashAlgo, const StorePathSet &references, RepairFlag repair) override
Definition local-store.cc:1202
bool isValidPathUncached(const StorePath &path) override
Definition local-store.cc:847
virtual void queryGCReferrers(const StorePath &path, StorePathSet &referrers)
Definition local-store.hh:374
void registerDrvOutputUnchecked(const Realisation &info) override
Definition local-store.cc:661
void addTempRoots(const StorePathSet &paths) override
Definition gc.cc:85
PathSet locksHeld
Definition local-store.hh:260
std::map< std::string, std::optional< StorePath > > queryStaticPartialDerivationOutputMap(const StorePath &path) override
Definition local-store.cc:902
void optimiseStore() override
Definition optimise-store.cc:326
void autoGC(bool sync=true)
Definition gc.cc:924
LocalStore(ref< const Config > params)
Definition local-store.cc:126
std::optional< StorePath > queryPathFromHashPart(const std::string &hashPart) override
Definition local-store.cc:938
Definition configuration.hh:476
Definition path.hh:33
Definition fun.hh:19
Definition ref.hh:58
FileSerialisationMethod
Definition file-content-address.hh:20
std::map< std::string, PublicKey > PublicKeys
Definition local-keys.hh:120
const int nixSchemaVersion
Definition local-store.hh:28
Definition logging.hh:221
Definition content-address.hh:32
Definition realisation.hh:26
Definition gc-store.hh:38
Definition gc-store.hh:78
Definition gc-store.hh:118
Definition indirect-root-store.hh:40
Definition local-store.hh:39
const LocalSettings & getLocalSettings() const
Definition local-store.cc:81
Definition local-settings.hh:179
Definition local-store.hh:85
bool getReadOnly() const override
Definition local-store.cc:477
ref< Store > openStore() const override
Definition local-store.cc:95
StoreReference getReference() const override
Definition local-store.cc:459
Definition local-store.hh:416
StorePathSet validPaths
Definition local-store.hh:426
bool errors
Definition local-store.hh:420
Definition local-store.hh:31
Definition realisation.hh:103
Definition sqlite.hh:46
Definition serialise.hh:95
@ Native
Definition store-api.hh:163
Definition store-api.hh:240
Definition path-info.hh:159
std::set< std::string, std::less<> > StringSet
Definition types.hh:45