File: cache_pruning.d

package info (click to toggle)
ldc 1%3A1.30.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 59,248 kB
  • sloc: cpp: 61,598; ansic: 14,545; sh: 1,014; makefile: 972; asm: 510; objc: 135; exp: 48; python: 12
file content (227 lines) | stat: -rw-r--r-- 7,452 bytes parent folder | download | duplicates (4)
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
//===-- driver/cache_pruning.d ------------------------------------*- D -*-===//
//
//                         LDC – the LLVM D compiler
//
// This file is distributed under the BSD-style LDC license. See the LICENSE
// file for details.
//
//===----------------------------------------------------------------------===//
//
// Implements cache pruning scheme.
// 0. Check that the cache exists.
// 1. Check that minimum pruning interval has passed.
// 2. Prune files that have passed the expiry duration.
// 3. Prune files to reduce total cache size to below a set limit.
//
// This file is imported by the ldc-prune-cache tool and should therefore depend
// on as little LDC code as possible (currently none).
//
//===----------------------------------------------------------------------===//

module driver.cache_pruning;

import std.file;
import std.datetime: Clock, dur, Duration, SysTime;

// Creates a CachePruner and performs the pruning.
// This function is meant to take care of all C++ interfacing.
extern (C++) void pruneCache(const(char)* cacheDirectoryPtr,
    size_t cacheDirectoryLen, uint pruneIntervalSeconds,
    uint expireIntervalSeconds, ulong sizeLimitBytes, uint sizeLimitPercentage)
{
    import std.conv: to;

    auto pruner = CachePruner(to!(string)(cacheDirectoryPtr[0 .. cacheDirectoryLen]),
        pruneIntervalSeconds, expireIntervalSeconds, sizeLimitBytes, sizeLimitPercentage);

    pruner.doPrune();
}

void writeEmptyFile(string filename)
{
    import std.stdio: File;
    auto f = File(filename, "w");
    f.close();
}

// Returns ulong.max when the available disk space could not be determined.
ulong getAvailableDiskSpace(string path)
{
    import std.string: toStringz;
    version (Windows)
    {
        import std.path;
        import core.sys.windows.winbase;
        import core.sys.windows.winnt;
        import std.internal.cstring;

        ULARGE_INTEGER freeBytesAvailable;
        path ~= dirSeparator;
        auto success = GetDiskFreeSpaceExW(path.tempCStringW(), &freeBytesAvailable, null, null);
        return success ? freeBytesAvailable.QuadPart : ulong.max;
    }
    else
    {
        import core.sys.posix.sys.statvfs;

        statvfs_t stats;
        int err = statvfs(path.toStringz(), &stats);
        return !err ? stats.f_bavail * stats.f_frsize : ulong.max;
    }
}

struct CachePruner
{
    enum timestampFilename = "ircache_prune_timestamp";

    string cachePath; // absolute path
    Duration pruneInterval; // minimum time between pruning
    Duration expireDuration; // cache file expiration
    ulong sizeLimit; // in bytes
    uint sizeLimitPercentage; // Percentage limit of available space
    bool willPruneForSize; // true if we need to prune for absolute/relative size

    this(string cachePath, uint pruneIntervalSeconds, uint expireIntervalSeconds,
        ulong sizeLimit, uint sizeLimitPercentage)
    {
        import std.path;
        if (cachePath.isRooted())
            this.cachePath = cachePath.dup;
        else
            this.cachePath = absolutePath(expandTilde(cachePath));
        this.pruneInterval = dur!"seconds"(pruneIntervalSeconds);
        this.expireDuration = dur!"seconds"(expireIntervalSeconds);
        this.sizeLimit = sizeLimit;
        this.sizeLimitPercentage = sizeLimitPercentage < 100 ? sizeLimitPercentage : 100;
        this.willPruneForSize = (sizeLimit > 0) || (sizeLimitPercentage < 100);
    }

    void doPrune()
    {
        if (!exists(cachePath))
            return;

        if (!hasPruneIntervalPassed())
            return;

        // Only delete files that match LDC's cache file naming.
        // E.g.            "ircache_00a13b6f918d18f9f9de499fc661ec0d.o"
        auto filePattern = "ircache_????????????????????????????????.{o,obj}";
        auto cacheFiles = dirEntries(cachePath, filePattern, SpanMode.shallow, /+ followSymlink +/ false);

        // Delete all temporary files.
        deleteFiles(cachePath, filePattern ~ ".tmp???????");

        // Files that have not yet expired, may still be removed during pruning for size later.
        // This array holds the prune candidates after pruning for expiry.
        DirEntry[] pruneForSizeCandidates;
        ulong cacheSize;
        pruneForExpiry(cacheFiles, pruneForSizeCandidates, cacheSize);
        if (!willPruneForSize || !pruneForSizeCandidates.length)
            return;

        pruneForSize(pruneForSizeCandidates, cacheSize);
    }

private:
    void deleteFiles(string path, string filePattern)
    {
        foreach (DirEntry f; dirEntries(path, filePattern, SpanMode.shallow, /+ followSymlink +/ false))
        {
            try
            {
                remove(f.name);
            }
            catch (FileException)
            {
                // Simply skip the file when an error occurs.
                continue;
            }
        }
    }

    void pruneForExpiry(T)(T cacheFiles, out DirEntry[] remainingPruneCandidates, out ulong cacheSize)
    {
        foreach (DirEntry f; cacheFiles)
        {
            if (!f.isFile())
                continue;

            if (f.timeLastAccessed < (Clock.currTime - expireDuration))
            {
                try
                {
                    remove(f.name);
                }
                catch (FileException)
                {
                    // Simply skip the file when an error occurs.
                    continue;
                }
            }
            else if (willPruneForSize)
            {
                cacheSize += f.size;
                remainingPruneCandidates ~= f;
            }
        }
    }

    void pruneForSize(DirEntry[] candidates, ulong cacheSize)
    {
        ulong availableSpace = cacheSize + getAvailableDiskSpace(cachePath);
        if (!isSizeAboveMaximum(cacheSize, availableSpace))
            return;

        // Create heap ordered with most recently accessed files last.
        import std.container.binaryheap : heapify;
        auto candidateHeap = heapify!("a.timeLastAccessed > b.timeLastAccessed")(candidates);
        while (!candidateHeap.empty())
        {
            auto candidate = candidateHeap.front();
            candidateHeap.popFront();

            try
            {
                remove(candidate.name);
                // Update cache size
                cacheSize -= candidate.size;

                if (!isSizeAboveMaximum(cacheSize, availableSpace))
                    break;
            }
            catch (FileException)
            {
                // Simply skip the file when an error occurs.
            }
        }
    }

    // Checks if the prune interval has passed, and if so, creates/updates the pruning timestamp.
    bool hasPruneIntervalPassed()
    {
        import std.path: buildPath;
        auto fname = buildPath(cachePath, timestampFilename);
        if (pruneInterval == dur!"seconds"(0) || timeLastModified(fname,
                SysTime.min) < (Clock.currTime - pruneInterval))
        {
            writeEmptyFile(fname);
            return true;
        }
        return false;
    }

    bool isSizeAboveMaximum(ulong cacheSize, ulong availableSpace)
    {
        if (availableSpace == 0)
            return true;

        bool tooLarge = false;
        if (sizeLimit > 0)
            tooLarge = cacheSize > sizeLimit;

        tooLarge = tooLarge || ((100 * cacheSize) / availableSpace) > sizeLimitPercentage;

        return tooLarge;
    }
}