Files
UnrealEngineUWP/Engine/Source/Developer/DerivedDataCache/Private/FileSystemDerivedDataBackend.cpp
Bob Tellez b51555abf7 Copying //UE4/Fortnite-Staging to //UE4/Main
#lockdown nick.penwarden

==========================
MAJOR FEATURES + CHANGES
==========================

Change 2806454 on 2015/12/16 by Bob.Tellez

	#UE4 Getting crash reporting working again on linux servers. Since -Unattended is now being passed BEFORE the target folder, the cmd line parsing code was failing so now it parses tokens and switches in a more general way. Also, diagnostics.txt had the incorrect case, since the d is supposed to be capitolized and the crash report processor is case sensitive.

	#rb Ben.Zeigler

	#codereview Dmitry.Rekman

Change 2805502 on 2015/12/16 by Ben.Zeigler

	#UE4 Move ValidateEnumProperties into ValidateGeneratedClass, it was happening too early in the generation process so was being called at an invalid time.
	As a result of this ValidateEnumProperties will not be called correctly for compile on load blueprints, that issue is covered in UE-24569
	#codereview mike.beach, bob.tellez

Change 2805288 on 2015/12/16 by David.Nikdel

	#HTTP #HttpRetry
	- Add new Failed_ConnectionError code to EHttpRequestStatus to distinguish between connection errors and protocol errors.
	- Changed HTTP retry logic a little bit
	  * If a response was received, retry on service-specific explicit HTTP codes (defaults to empty)
	  * If a response was not received and we did not send a full request, automatically retry
	  * If a response was not received and a request may have been sent, retry if the verb is GET or HEAD (should be idempotent)
	- Adjusted Curl/IOS/Mac/PS4/WinInet to try and distinguish Failed_ConnectionError where possible
	  * Other systems will default to Failed which is ok (ConnectionError is an opportunistic categorization)
	  * Opened a PS4 ticket to try to improve detection, but unfortunately there's no way (currently) to distinguish between send timeout, connection timeout, and receive timeout, the latter being the problematic case.
	- Removed the concept of global/default HTTP retry status codes. No system has enough knowledge to set those globally.
	  * Individual requests still specify explicit "retryable" codes and McpServiceBase sets that on each request on a per-service basis
	#RB: Sam.Zamani
	#CodeReview: Sam.Zamani, Josh.Markiewicz, Alex.Fennell, Dmitry.Rekman, Sam.Spiro
	#Fixes: FORT-17804

Change 2803864 on 2015/12/15 by Bob.Tellez

	#UE4 Changed usage of !UE_SERVER to !IsRunningDedicatedServer in cases where we are preventing load attempts on UFonts. This is so running an editor build with -server works the same as running a cooked server.

	#rb Dmitry.Rekman

	#codereview Nick.Darnell

Change 2803677 on 2015/12/15 by Billy.Bramer

	- Expose equality and inequality operators for gameplay attributes

	#rb Todd.Eckert

Change 2802881 on 2015/12/14 by Bob.Tellez

	#UE4 InheritableComponentHandler no longer keeps records for components that we are no longer inheriting.

	#rb Phillip.Kavan, Maciej.Mroz

	#codereview Phillip.Kavan, Maciej.Mroz

Change 2801636 on 2015/12/14 by Bob.Tellez

	#UE4 Returning package insert order for non-imports back to being after those of matching priorities unconditionally since this is what you want even when you are not using the asset registry to preload packages.

	#codereview Graeme.Thornton

Change 2800400 on 2015/12/11 by Jonathan.Lindquist

	Submitting a new Pivot Painter Edition
	- now renders to textures
	- improved workflow
	- greater capabilities

Change 2799579 on 2015/12/11 by John.Abercrombie

	[AUTOMERGE]

	Fixed EQS BP query wrappers getting GCed before wrapped query finishes #UE4

	Fixes FORT-18649 - Patrols don't spawn consistently
	- The patrol blueprint was waiting (endlessly) for an EQS query to finish but because the wrapper could be GC-ed while the EQS query was running the delegate would never fire

	#rb me (this code was written by MieszkoZ)
	(removed code review for integration of Mieszko.Zielinski, Phil.Cole, Dominic.Barile)

	--------
	Integrated using branch UE4-Fortnite-To-UE4-FortniteReleases/0.10 (reversed) of change#2799575 by John.Abercrombie on 2015/12/11 09:55:11.

Change 2799018 on 2015/12/10 by Bob.Tellez

	#UE4 The asset registry tags stripped from cooked builds is now a blacklist by default that includes only the FiB tag. You can opt-in to using the whitelist by flipping the bUseAssetRegistryTagsWhitelistInsteadOfBlacklist flag.

	#rb Fred.Kimberley

	#codereview Peter.Knepley

Change 2798926 on 2015/12/10 by Bob.Tellez

	#UE4 Removed some showflags from the list of "Fixed" showflags since they were actually in use at runtime in Fortnite in a scene capture.

	#jira FORT-18514

	#codereview Martin.Mittring

Change 2797758 on 2015/12/10 by Mark.Satterthwaite

	Defer calls to AUGraphUpdate into FCoreAudioDevice::UpdateHardware - this call will synchronise the calling thread with the CoreAudio thread/run-loop so that the CoreAudio graph is safe to modify and this may incur a significant stall. This means it is far more efficient to amortise the cost of all changes to the graph with a single call. To ensure correctness the audio format conversion components are cached and disposed of after the call to AUGraphUpdate so that any existing operations on the CoreAudio thread are completed prior to disposal.

Change 2781204 on 2015/11/25 by Dmitry.Rekman

	Linux: use jemalloc by default if available.

	- Alleviates one of the reasons for player disconnect (FORT-18048), which was machines running OOM.

	#rb Bob.Tellez
	#codereview Bob.Tellez, Ben.Zeigler

Change 2779398 on 2015/11/24 by Mark.Satterthwaite

	Switch the default graphics API on Mac back to OpenGL, but allow Metal to run with -metal (or -metalsm5 for experimental SM5 support).
2016-01-08 19:10:43 -05:00

306 lines
11 KiB
C++

// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "Core.h"
#include "DerivedDataBackendInterface.h"
#include "DDCCleanup.h"
#include "DDCStatsHelper.h"
#define MAX_BACKEND_KEY_LENGTH (120)
#define MAX_BACKEND_NUMBERED_SUBFOLDER_LENGTH (9)
#if PLATFORM_LINUX // PATH_MAX on Linux is 4096 (getconf PATH_MAX /, also see limits.h), so this value can be larger (note that it is still arbitrary).
// This should not affect sharing the cache between platforms as the absolute paths will be different anyway.
#define MAX_CACHE_DIR_LEN (3119)
#else
#define MAX_CACHE_DIR_LEN (119)
#endif // PLATFORM_LINUX
#define MAX_CACHE_EXTENTION_LEN (4)
/**
* Cache server that uses the OS filesystem
* The entire API should be callable from any thread (except the singleton can be assumed to be called at least once before concurrent access).
**/
class FFileSystemDerivedDataBackend : public FDerivedDataBackendInterface
{
public:
/**
* Constructor that should only be called once by the singleton, grabs the cache path from the ini
* @param InCacheDirectory directory to store the cache in
* @param bForceReadOnly if true, do not attempt to write to this cache
*/
FFileSystemDerivedDataBackend(const TCHAR* InCacheDirectory, bool bForceReadOnly, bool bTouchFiles, bool bPurgeTransientData, bool bDeleteOldFiles, int32 InDaysToDeleteUnusedFiles, int32 InMaxNumFoldersToCheck, int32 InMaxContinuousFileChecks)
: CachePath(InCacheDirectory)
, bReadOnly(bForceReadOnly)
, bFailed(true)
, bTouch(bTouchFiles)
, bPurgeTransient(bPurgeTransientData)
, DaysToDeleteUnusedFiles(InDaysToDeleteUnusedFiles)
{
// If we find a platform that has more stingent limits, this needs to be rethought.
static_assert(MAX_BACKEND_KEY_LENGTH + MAX_CACHE_DIR_LEN + MAX_BACKEND_NUMBERED_SUBFOLDER_LENGTH + MAX_CACHE_EXTENTION_LEN < PLATFORM_MAX_FILEPATH_LENGTH,
"Not enough room left for cache keys in max path.");
const double SlowInitDuration = 10.0;
double AccessDuration = 0.0;
check(CachePath.Len());
FPaths::NormalizeFilename(CachePath);
const FString AbsoluteCachePath = IFileManager::Get().ConvertToAbsolutePathForExternalAppForRead(*CachePath);
if (AbsoluteCachePath.Len() > MAX_CACHE_DIR_LEN)
{
const FText ErrorMessage = FText::Format( NSLOCTEXT("DerivedDataCache", "PathTooLong", "Cache path {0} is longer than {1} characters...please adjust [DerivedDataBackendGraph] paths to be shorter (this leaves more room for cache keys)."), FText::FromString( AbsoluteCachePath ), FText::AsNumber( MAX_CACHE_DIR_LEN ) );
FMessageDialog::Open(EAppMsgType::Ok, ErrorMessage);
UE_LOG(LogDerivedDataCache, Fatal, TEXT("%s"), *ErrorMessage.ToString());
}
if (!bReadOnly)
{
double TestStart = FPlatformTime::Seconds();
FString TempFilename = CachePath / FGuid::NewGuid().ToString() + ".tmp";
FFileHelper::SaveStringToFile(FString("TEST"),*TempFilename);
int32 TestFileSize = IFileManager::Get().FileSize(*TempFilename);
if (TestFileSize < 4)
{
UE_LOG(LogDerivedDataCache, Warning, TEXT("Fail to write to %s, derived data cache to this directory will be read only."),*CachePath);
}
else
{
bFailed = false;
}
if (TestFileSize >= 0)
{
IFileManager::Get().Delete(*TempFilename, false, false, true);
}
AccessDuration = FPlatformTime::Seconds() - TestStart;
}
if (bFailed)
{
double StartTime = FPlatformTime::Seconds();
TArray<FString> FilesAndDirectories;
IFileManager::Get().FindFiles(FilesAndDirectories,*(CachePath / TEXT("*.*")), true, true);
AccessDuration = FPlatformTime::Seconds() - StartTime;
if (FilesAndDirectories.Num() > 0)
{
bReadOnly = true;
bFailed = false;
}
}
if (FString(FCommandLine::Get()).Contains(TEXT("DerivedDataCache")) )
{
bTouch = true; // we always touch files when running the DDC commandlet
}
// The command line (-ddctouch) enables touch on all filesystem backends if specified.
bTouch = bTouch || FParse::Param(FCommandLine::Get(), TEXT("DDCTOUCH"));
if (bReadOnly)
{
bTouch = false; // we won't touch read only paths
}
if (bTouch)
{
UE_LOG(LogDerivedDataCache, Display, TEXT("Files in %s will be touched."),*CachePath);
}
if (!bFailed && AccessDuration > SlowInitDuration)
{
UE_LOG(LogDerivedDataCache, Warning, TEXT("%s access is very slow (initialization took %.2lf seconds), consider disabling it."), *CachePath, AccessDuration);
}
if (!bReadOnly && !bFailed && bDeleteOldFiles && !FParse::Param(FCommandLine::Get(),TEXT("NODDCCLEANUP")) && FDDCCleanup::Get())
{
FDDCCleanup::Get()->AddFilesystem( CachePath, InDaysToDeleteUnusedFiles, InMaxNumFoldersToCheck, InMaxContinuousFileChecks );
}
}
/** return true if the cache is usable **/
bool IsUsable()
{
return !bFailed;
}
/** return true if this cache is writable **/
virtual bool IsWritable() override
{
return !bReadOnly;
}
/**
* Synchronous test for the existence of a cache item
*
* @param CacheKey Alphanumeric+underscore key of this cache item
* @return true if the data probably will be found, this can't be guaranteed because of concurrency in the backends, corruption, etc
*/
virtual bool CachedDataProbablyExists(const TCHAR* CacheKey) override
{
check(!bFailed);
FString Filename = BuildFilename(CacheKey);
FDateTime TimeStamp = IFileManager::Get().GetTimeStamp(*Filename);
bool bExists = TimeStamp > FDateTime::MinValue();
if (bExists)
{
// Update file timestamp to prevent it from being deleted by DDC Cleanup.
if (bTouch ||
(!bReadOnly && (FDateTime::UtcNow() - TimeStamp).GetDays() > (DaysToDeleteUnusedFiles / 4)))
{
IFileManager::Get().SetTimeStamp(*Filename, FDateTime::UtcNow());
}
}
return bExists;
}
/**
* Synchronous retrieve of a cache item
*
* @param CacheKey Alphanumeric+underscore key of this cache item
* @param OutData Buffer to receive the results, if any were found
* @return true if any data was found, and in this case OutData is non-empty
*/
virtual bool GetCachedData(const TCHAR* CacheKey, TArray<uint8>& Data) override
{
check(!bFailed);
FString Filename = BuildFilename(CacheKey);
double StartTime = FPlatformTime::Seconds();
if (FFileHelper::LoadFileToArray(Data,*Filename,FILEREAD_Silent))
{
double ReadDuration = FPlatformTime::Seconds() - StartTime;
double ReadSpeed = ReadDuration > 5.0 ? (Data.Num() / ReadDuration) / (1024.0 * 1024.0) : 100.0;
// Slower than 0.5MB/s?
UE_CLOG(ReadSpeed < 0.5, LogDerivedDataCache, Warning, TEXT("%s access is very slow (%.2lfMB/s), consider disabling it."), *CachePath, ReadSpeed);
UE_LOG(LogDerivedDataCache, Verbose, TEXT("FileSystemDerivedDataBackend: Cache hit on %s"),*Filename);
return true;
}
UE_LOG(LogDerivedDataCache, Verbose, TEXT("FileSystemDerivedDataBackend: Cache miss on %s"),*Filename);
Data.Empty();
return false;
}
/**
* Asynchronous, fire-and-forget placement of a cache item
*
* @param CacheKey Alphanumeric+underscore key of this cache item
* @param OutData Buffer containing the data to cache, can be destroyed after the call returns, immediately
* @param bPutEvenIfExists If true, then do not attempt skip the put even if CachedDataProbablyExists returns true
*/
virtual void PutCachedData(const TCHAR* CacheKey, TArray<uint8>& Data, bool bPutEvenIfExists) override
{
//static FName NAME_PutCachedData(TEXT("PutCachedData"));
//FDDCScopeStatHelper Stat(CacheKey, NAME_PutCachedData);
//static FName NAME_FileDDCPath(TEXT("FileDDCPath"));
//Stat.AddTag(NAME_FileDDCPath, CachePath);
check(!bFailed);
if (!bReadOnly)
{
if (bPutEvenIfExists || !CachedDataProbablyExists(CacheKey))
{
check(Data.Num());
FString Filename = BuildFilename(CacheKey);
FString TempFilename(TEXT("temp."));
TempFilename += FGuid::NewGuid().ToString();
TempFilename = FPaths::GetPath(Filename) / TempFilename;
bool bResult;
{
bResult = FFileHelper::SaveArrayToFile(Data, *TempFilename);
}
if (bResult)
{
if (IFileManager::Get().FileSize(*TempFilename) == Data.Num())
{
bool DoMove = !CachedDataProbablyExists(CacheKey);
if (bPutEvenIfExists && !DoMove)
{
DoMove = true;
RemoveCachedData(CacheKey, /*bTransient=*/ false);
}
if (DoMove)
{
if (!IFileManager::Get().Move(*Filename, *TempFilename, true, true, false, true))
{
UE_LOG(LogDerivedDataCache, Log, TEXT("FFileSystemDerivedDataBackend: Move collision, attempt at redundant update, OK %s."),*Filename);
}
else
{
UE_LOG(LogDerivedDataCache, Verbose, TEXT("FFileSystemDerivedDataBackend: Successful cache put to %s"),*Filename);
}
}
}
else
{
UE_LOG(LogDerivedDataCache, Warning, TEXT("FFileSystemDerivedDataBackend: Temp file is short %s!"),*TempFilename);
}
}
else
{
UE_LOG(LogDerivedDataCache, Warning, TEXT("FFileSystemDerivedDataBackend: Could not write temp file %s!"),*TempFilename);
}
// if everything worked, this is not necessary, but we will make every effort to avoid leaving junk in the cache
if (FPaths::FileExists(TempFilename))
{
IFileManager::Get().Delete(*TempFilename, false, false, true);
}
}
}
}
void RemoveCachedData(const TCHAR* CacheKey, bool bTransient) override
{
check(!bFailed);
if (!bReadOnly && (!bTransient || bPurgeTransient))
{
FString Filename = BuildFilename(CacheKey);
if (bTransient)
{
UE_LOG(LogDerivedDataCache,Verbose,TEXT("Deleting transient cached data. Key=%s Filename=%s"),CacheKey,*Filename);
}
IFileManager::Get().Delete(*Filename, false, false, true);
}
}
private:
/**
* Threadsafe method to compute the filename from the cachekey, currently just adds a path and an extension.
*
* @param CacheKey Alphanumeric+underscore key of this cache item
* @return filename built from the cache key
*/
FString BuildFilename(const TCHAR* CacheKey)
{
FString Key = FString(CacheKey).ToUpper();
for (int32 i = 0; i < Key.Len(); i++)
{
check(FChar::IsAlnum(Key[i]) || FChar::IsUnderscore(Key[i]) || Key[i] == L'$');
}
uint32 Hash = FCrc::StrCrc_DEPRECATED(*Key);
// this creates a tree of 1000 directories
FString HashPath = FString::Printf(TEXT("%1d/%1d/%1d/"),(Hash/100)%10,(Hash/10)%10,Hash%10);
return CachePath / HashPath / Key + TEXT(".udd");
}
/** Base path we are storing the cache files in. **/
FString CachePath;
/** If true, do not attempt to write to this cache **/
bool bReadOnly;
/** If true, we failed to write to this directory and it did not contain anything so we should not be used **/
bool bFailed;
/** If true, CachedDataProbablyExists will update the file timestamps. */
bool bTouch;
/** If true, allow transient data to be removed from the cache. */
bool bPurgeTransient;
/** Age of file when it should be deleted from DDC cache. */
int32 DaysToDeleteUnusedFiles;
};
FDerivedDataBackendInterface* CreateFileSystemDerivedDataBackend(const TCHAR* CacheDirectory, bool bForceReadOnly /*= false*/, bool bTouchFiles /*= false*/, bool bPurgeTransient /*= false*/, bool bDeleteOldFiles /*= false*/, int32 InDaysToDeleteUnusedFiles /*= 60*/, int32 InMaxNumFoldersToCheck /*= -1*/, int32 InMaxContinuousFileChecks /*= -1*/)
{
FFileSystemDerivedDataBackend* FileDDB = new FFileSystemDerivedDataBackend(CacheDirectory, bForceReadOnly, bTouchFiles, bPurgeTransient, bDeleteOldFiles, InDaysToDeleteUnusedFiles, InMaxNumFoldersToCheck, InMaxContinuousFileChecks);
if (!FileDDB->IsUsable())
{
delete FileDDB;
FileDDB = NULL;
}
return FileDDB;
}