aboutsummaryrefslogtreecommitdiff
path: root/src/zencompute/deferreddeleter.cpp
blob: 00977d9fafc24efd95cc1682c35e84bff72d449b (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
// Copyright Epic Games, Inc. All Rights Reserved.

#include "deferreddeleter.h"

#if ZEN_WITH_COMPUTE_SERVICES

#	include <zencore/filesystem.h>
#	include <zencore/fmtutils.h>
#	include <zencore/logging.h>
#	include <zencore/thread.h>

#	include <algorithm>
#	include <chrono>

namespace zen::compute {

using namespace std::chrono_literals;

using Clock = std::chrono::steady_clock;

// Default deferral: how long to wait before attempting deletion.
// This gives memory-mapped file handles time to close naturally.
static constexpr auto DeferralPeriod = 60s;

// Shortened deferral after MarkReady(): the client has collected results
// so handles should be released soon, but we still wait briefly.
static constexpr auto ReadyGracePeriod = 5s;

// Interval between retry attempts for directories that failed deletion.
static constexpr auto RetryInterval = 5s;

static constexpr int MaxRetries = 10;

DeferredDirectoryDeleter::DeferredDirectoryDeleter() : m_Thread(&DeferredDirectoryDeleter::ThreadFunction, this)
{
}

DeferredDirectoryDeleter::~DeferredDirectoryDeleter()
{
	Shutdown();
}

void
DeferredDirectoryDeleter::Enqueue(int ActionLsn, std::filesystem::path Path)
{
	{
		std::lock_guard Lock(m_Mutex);
		m_Queue.push_back({ActionLsn, std::move(Path)});
	}
	m_Cv.notify_one();
}

void
DeferredDirectoryDeleter::MarkReady(int ActionLsn)
{
	{
		std::lock_guard Lock(m_Mutex);
		m_ReadyLsns.push_back(ActionLsn);
	}
	m_Cv.notify_one();
}

void
DeferredDirectoryDeleter::Shutdown()
{
	{
		std::lock_guard Lock(m_Mutex);
		m_Done = true;
	}
	m_Cv.notify_one();

	if (m_Thread.joinable())
	{
		m_Thread.join();
	}
}

void
DeferredDirectoryDeleter::ThreadFunction()
{
	SetCurrentThreadName("ZenDirCleanup");

	struct PendingEntry
	{
		int					  ActionLsn;
		std::filesystem::path Path;
		Clock::time_point	  ReadyTime;
		int					  Attempts = 0;
	};

	std::vector<PendingEntry> PendingList;

	auto TryDelete = [](PendingEntry& Entry) -> bool {
		std::error_code Ec;
		std::filesystem::remove_all(Entry.Path, Ec);
		return !Ec;
	};

	for (;;)
	{
		bool Shutting = false;

		// Drain the incoming queue and process MarkReady signals

		{
			std::unique_lock Lock(m_Mutex);

			if (m_Queue.empty() && m_ReadyLsns.empty() && !m_Done)
			{
				if (PendingList.empty())
				{
					m_Cv.wait(Lock, [this] { return !m_Queue.empty() || !m_ReadyLsns.empty() || m_Done; });
				}
				else
				{
					auto NextReady = PendingList.front().ReadyTime;
					for (const auto& Entry : PendingList)
					{
						if (Entry.ReadyTime < NextReady)
						{
							NextReady = Entry.ReadyTime;
						}
					}

					m_Cv.wait_until(Lock, NextReady, [this] { return !m_Queue.empty() || !m_ReadyLsns.empty() || m_Done; });
				}
			}

			// Move new items into PendingList with the full deferral deadline
			auto Now = Clock::now();
			for (auto& Entry : m_Queue)
			{
				PendingList.push_back({Entry.ActionLsn, std::move(Entry.Path), Now + DeferralPeriod, 0});
			}
			m_Queue.clear();

			// Apply MarkReady: shorten ReadyTime for matching entries
			for (int Lsn : m_ReadyLsns)
			{
				for (auto& Entry : PendingList)
				{
					if (Entry.ActionLsn == Lsn)
					{
						auto NewReady = Now + ReadyGracePeriod;
						if (NewReady < Entry.ReadyTime)
						{
							Entry.ReadyTime = NewReady;
						}
					}
				}
			}
			m_ReadyLsns.clear();

			Shutting = m_Done;
		}

		// Process items whose deferral period has elapsed (or all items on shutdown)

		auto Now = Clock::now();

		for (size_t i = 0; i < PendingList.size();)
		{
			auto& Entry = PendingList[i];

			if (!Shutting && Now < Entry.ReadyTime)
			{
				++i;
				continue;
			}

			if (TryDelete(Entry))
			{
				if (Entry.Attempts > 0)
				{
					ZEN_INFO("Retry succeeded for directory '{}'", Entry.Path);
				}

				PendingList[i] = std::move(PendingList.back());
				PendingList.pop_back();
			}
			else
			{
				++Entry.Attempts;

				if (Entry.Attempts >= MaxRetries)
				{
					ZEN_WARN("Giving up on deleting '{}' after {} attempts", Entry.Path, Entry.Attempts);
					PendingList[i] = std::move(PendingList.back());
					PendingList.pop_back();
				}
				else
				{
					ZEN_WARN("Unable to delete directory '{}' (attempt {}), will retry", Entry.Path, Entry.Attempts);
					Entry.ReadyTime = Now + RetryInterval;
					++i;
				}
			}
		}

		// Exit once shutdown is requested and nothing remains

		if (Shutting && PendingList.empty())
		{
			return;
		}
	}
}

}  // namespace zen::compute

#endif

#if ZEN_WITH_TESTS

#	include <zencore/testing.h>

namespace zen::compute {

void
deferreddeleter_forcelink()
{
}

}  // namespace zen::compute

#endif

#if ZEN_WITH_TESTS && ZEN_WITH_COMPUTE_SERVICES

#	include <zencore/testutils.h>

namespace zen::compute {

TEST_CASE("DeferredDirectoryDeleter.DeletesSingleDirectory")
{
	ScopedTemporaryDirectory TempDir;
	std::filesystem::path	 DirToDelete = TempDir.Path() / "subdir";
	CreateDirectories(DirToDelete / "nested");

	CHECK(std::filesystem::exists(DirToDelete));

	{
		DeferredDirectoryDeleter Deleter;
		Deleter.Enqueue(1, DirToDelete);
	}

	CHECK(!std::filesystem::exists(DirToDelete));
}

TEST_CASE("DeferredDirectoryDeleter.DeletesMultipleDirectories")
{
	ScopedTemporaryDirectory TempDir;

	constexpr int					   NumDirs = 10;
	std::vector<std::filesystem::path> Dirs;

	for (int i = 0; i < NumDirs; ++i)
	{
		auto Dir = TempDir.Path() / std::to_string(i);
		CreateDirectories(Dir / "child");
		Dirs.push_back(std::move(Dir));
	}

	{
		DeferredDirectoryDeleter Deleter;
		for (int i = 0; i < NumDirs; ++i)
		{
			CHECK(std::filesystem::exists(Dirs[i]));
			Deleter.Enqueue(100 + i, Dirs[i]);
		}
	}

	for (const auto& Dir : Dirs)
	{
		CHECK(!std::filesystem::exists(Dir));
	}
}

TEST_CASE("DeferredDirectoryDeleter.ShutdownIsIdempotent")
{
	ScopedTemporaryDirectory TempDir;
	std::filesystem::path	 Dir = TempDir.Path() / "idempotent";
	CreateDirectories(Dir);

	DeferredDirectoryDeleter Deleter;
	Deleter.Enqueue(42, Dir);
	Deleter.Shutdown();
	Deleter.Shutdown();

	CHECK(!std::filesystem::exists(Dir));
}

TEST_CASE("DeferredDirectoryDeleter.HandlesNonExistentPath")
{
	ScopedTemporaryDirectory TempDir;
	std::filesystem::path	 NoSuchDir = TempDir.Path() / "does_not_exist";

	{
		DeferredDirectoryDeleter Deleter;
		Deleter.Enqueue(99, NoSuchDir);
	}
}

TEST_CASE("DeferredDirectoryDeleter.ExplicitShutdownBeforeDestruction")
{
	ScopedTemporaryDirectory TempDir;
	std::filesystem::path	 Dir = TempDir.Path() / "explicit";
	CreateDirectories(Dir / "inner");

	DeferredDirectoryDeleter Deleter;
	Deleter.Enqueue(7, Dir);
	Deleter.Shutdown();

	CHECK(!std::filesystem::exists(Dir));
}

TEST_CASE("DeferredDirectoryDeleter.MarkReadyShortensDeferral")
{
	ScopedTemporaryDirectory TempDir;
	std::filesystem::path	 Dir = TempDir.Path() / "markready";
	CreateDirectories(Dir / "child");

	DeferredDirectoryDeleter Deleter;
	Deleter.Enqueue(50, Dir);

	// Without MarkReady the full deferral (60s) would apply.
	// MarkReady shortens it to 5s, and shutdown bypasses even that.
	Deleter.MarkReady(50);
	Deleter.Shutdown();

	CHECK(!std::filesystem::exists(Dir));
}

}  // namespace zen::compute

#endif	// ZEN_WITH_TESTS && ZEN_WITH_COMPUTE_SERVICES