about summary refs log tree commit diff
path: root/third_party/nix/src/libstore/profiles.cc
blob: 0d44c60cc4e9be2c530f586fd12647698fea4f9c (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
#include "libstore/profiles.hh"

#include <cerrno>
#include <cstdio>

#include <absl/strings/numbers.h>
#include <absl/strings/string_view.h>
#include <absl/strings/strip.h>
#include <glog/logging.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include "libstore/store-api.hh"
#include "libutil/util.hh"

namespace nix {

static bool cmpGensByNumber(const Generation& a, const Generation& b) {
  return a.number < b.number;
}

// Parse a generation out of the format
// `<profilename>-<generation>-link'.
static int parseName(absl::string_view profileName, absl::string_view name) {
  // Consume the `<profilename>-' prefix and and `-link' suffix.
  if (!(absl::ConsumePrefix(&name, profileName) &&
        absl::ConsumePrefix(&name, "-") &&
        absl::ConsumeSuffix(&name, "-link"))) {
    return -1;
  }

  int n;
  if (!absl::SimpleAtoi(name, &n) || n < 0) {
    return -1;
  }

  return n;
}

Generations findGenerations(const Path& profile, int& curGen) {
  Generations gens;

  Path profileDir = dirOf(profile);
  std::string profileName = baseNameOf(profile);

  for (auto& i : readDirectory(profileDir)) {
    int n;
    if ((n = parseName(profileName, i.name)) != -1) {
      Generation gen;
      gen.path = profileDir + "/" + i.name;
      gen.number = n;
      struct stat st;
      if (lstat(gen.path.c_str(), &st) != 0) {
        throw SysError(format("statting '%1%'") % gen.path);
      }
      gen.creationTime = st.st_mtime;
      gens.push_back(gen);
    }
  }

  gens.sort(cmpGensByNumber);

  curGen = pathExists(profile) ? parseName(profileName, readLink(profile)) : -1;

  return gens;
}

static void makeName(const Path& profile, unsigned int num, Path& outLink) {
  Path prefix = (format("%1%-%2%") % profile % num).str();
  outLink = prefix + "-link";
}

Path createGeneration(const ref<LocalFSStore>& store, const Path& profile,
                      const Path& outPath) {
  /* The new generation number should be higher than old the
     previous ones. */
  int dummy;
  Generations gens = findGenerations(profile, dummy);

  unsigned int num;
  if (!gens.empty()) {
    Generation last = gens.back();

    if (readLink(last.path) == outPath) {
      /* We only create a new generation symlink if it differs
         from the last one.

         This helps keeping gratuitous installs/rebuilds from piling
         up uncontrolled numbers of generations, cluttering up the
         UI like grub. */
      return last.path;
    }

    num = gens.back().number;
  } else {
    num = 0;
  }

  /* Create the new generation.  Note that addPermRoot() blocks if
     the garbage collector is running to prevent the stuff we've
     built from moving from the temporary roots (which the GC knows)
     to the permanent roots (of which the GC would have a stale
     view).  If we didn't do it this way, the GC might remove the
     user environment etc. we've just built. */
  Path generation;
  makeName(profile, num + 1, generation);
  store->addPermRoot(outPath, generation, false, true);

  return generation;
}

static void removeFile(const Path& path) {
  if (remove(path.c_str()) == -1) {
    throw SysError(format("cannot unlink '%1%'") % path);
  }
}

void deleteGeneration(const Path& profile, unsigned int gen) {
  Path generation;
  makeName(profile, gen, generation);
  removeFile(generation);
}

static void deleteGeneration2(const Path& profile, unsigned int gen,
                              bool dryRun) {
  if (dryRun) {
    LOG(INFO) << "would remove generation " << gen;
  } else {
    LOG(INFO) << "removing generation " << gen;
    deleteGeneration(profile, gen);
  }
}

void deleteGenerations(const Path& profile,
                       const std::set<unsigned int>& gensToDelete,
                       bool dryRun) {
  PathLocks lock;
  lockProfile(lock, profile);

  int curGen;
  Generations gens = findGenerations(profile, curGen);

  if (gensToDelete.find(curGen) != gensToDelete.end()) {
    throw Error(format("cannot delete current generation of profile %1%'") %
                profile);
  }

  for (auto& i : gens) {
    if (gensToDelete.find(i.number) == gensToDelete.end()) {
      continue;
    }
    deleteGeneration2(profile, i.number, dryRun);
  }
}

void deleteGenerationsGreaterThan(const Path& profile, int max, bool dryRun) {
  PathLocks lock;
  lockProfile(lock, profile);

  int curGen;
  bool fromCurGen = false;
  Generations gens = findGenerations(profile, curGen);
  for (auto i = gens.rbegin(); i != gens.rend(); ++i) {
    if (i->number == curGen) {
      fromCurGen = true;
      max--;
      continue;
    }
    if (fromCurGen) {
      if (max != 0) {
        max--;
        continue;
      }
      deleteGeneration2(profile, i->number, dryRun);
    }
  }
}

void deleteOldGenerations(const Path& profile, bool dryRun) {
  PathLocks lock;
  lockProfile(lock, profile);

  int curGen;
  Generations gens = findGenerations(profile, curGen);

  for (auto& i : gens) {
    if (i.number != curGen) {
      deleteGeneration2(profile, i.number, dryRun);
    }
  }
}

void deleteGenerationsOlderThan(const Path& profile, time_t t, bool dryRun) {
  PathLocks lock;
  lockProfile(lock, profile);

  int curGen;
  Generations gens = findGenerations(profile, curGen);

  bool canDelete = false;
  for (auto i = gens.rbegin(); i != gens.rend(); ++i) {
    if (canDelete) {
      assert(i->creationTime < t);
      if (i->number != curGen) {
        deleteGeneration2(profile, i->number, dryRun);
      }
    } else if (i->creationTime < t) {
      /* We may now start deleting generations, but we don't
         delete this generation yet, because this generation was
         still the one that was active at the requested point in
         time. */
      canDelete = true;
    }
  }
}

void deleteGenerationsOlderThan(const Path& profile,
                                const std::string& timeSpec, bool dryRun) {
  time_t curTime = time(nullptr);
  std::string strDays = std::string(timeSpec, 0, timeSpec.size() - 1);
  int days;

  if (!absl::SimpleAtoi(strDays, &days) || days < 1) {
    throw Error(format("invalid number of days specifier '%1%'") % timeSpec);
  }

  time_t oldTime = curTime - days * 24 * 3600;

  deleteGenerationsOlderThan(profile, oldTime, dryRun);
}

void switchLink(const Path& link, Path target) {
  /* Hacky. */
  if (dirOf(target) == dirOf(link)) {
    target = baseNameOf(target);
  }

  replaceSymlink(target, link);
}

void lockProfile(PathLocks& lock, const Path& profile) {
  lock.lockPaths({profile},
                 (format("waiting for lock on profile '%1%'") % profile).str());
  lock.setDeletion(true);
}

std::string optimisticLockProfile(const Path& profile) {
  return pathExists(profile) ? readLink(profile) : "";
}

}  // namespace nix