22#include <sys/statvfs.h>
50Cache *Cache::m_instance =
nullptr;
77 const char *config_filename,
78 const char *parameters,
82 err.
Say(
"++++++ Proxy file cache initialization started.");
93 if (! instance.
Config(config_filename, parameters, env))
95 err.
Say(
"Config Proxy file cache initialization failed.");
98 err.
Say(
"++++++ Proxy file cache initialization completed.");
105 for (
int wti = 0; wti < instance.
RefConfiguration().m_wqueue_threads; ++wti)
117 env->
PutPtr(
"XrdFSCtl_PC*", pfcFSctl);
127 assert (m_instance == 0);
128 m_instance =
new Cache(logger, env);
139 if (! m_decisionpoints.empty())
142 std::string filename = url.
GetPath();
143 std::vector<Decision*>::const_iterator it;
144 for (it = m_decisionpoints.begin(); it != m_decisionpoints.end(); ++it)
148 if (! d->
Decide(filename, *m_oss))
161 m_log(logger,
"XrdPfc_"),
167 m_prefetch_condVar(0),
168 m_prefetch_enabled(false),
170 m_RAM_write_queue(0),
181 const char* tpfx =
"Attach() ";
206 TRACE(
Error, tpfx <<
"Failed opening local file, falling back to remote access " << io->
Path());
214 ((loc && loc[0] != 0) ? loc :
"<deferred open>"));
234 m_writeQ.condVar.Lock();
236 m_writeQ.queue.push_back(b);
238 m_writeQ.queue.push_front(b);
240 m_writeQ.condVar.Signal();
241 m_writeQ.condVar.UnLock();
246 std::list<Block*> removed_blocks;
247 long long sum_size = 0;
249 m_writeQ.condVar.Lock();
250 std::list<Block*>::iterator i = m_writeQ.queue.begin();
251 while (i != m_writeQ.queue.end())
253 if ((*i)->m_file == file)
255 TRACE(Dump,
"Remove entries for " << (
void*)(*i) <<
" path " << file->
lPath());
256 std::list<Block*>::iterator j = i++;
257 removed_blocks.push_back(*j);
258 sum_size += (*j)->get_size();
259 m_writeQ.queue.erase(j);
267 m_writeQ.condVar.UnLock();
271 m_RAM_write_queue -= sum_size;
279 std::vector<Block*> blks_to_write(m_configuration.m_wqueue_blocks);
283 m_writeQ.condVar.Lock();
284 while (m_writeQ.size == 0)
286 m_writeQ.condVar.Wait();
292 int n_pushed = std::min(m_writeQ.size, m_configuration.m_wqueue_blocks);
293 long long sum_size = 0;
295 for (
int bi = 0; bi < n_pushed; ++bi)
297 Block* block = m_writeQ.queue.front();
298 m_writeQ.queue.pop_front();
299 m_writeQ.writes_between_purges += block->
get_size();
302 blks_to_write[bi] = block;
304 TRACE(Dump,
"ProcessWriteTasks for block " << (
void*)(block) <<
" path " << block->
m_file->
lPath());
306 m_writeQ.size -= n_pushed;
308 m_writeQ.condVar.UnLock();
312 m_RAM_write_queue -= sum_size;
315 for (
int bi = 0; bi < n_pushed; ++bi)
317 Block* block = blks_to_write[bi];
328 long long ret = m_writeQ.writes_between_purges;
329 m_writeQ.writes_between_purges = 0;
337 static const size_t s_block_align = sysconf(_SC_PAGESIZE);
339 bool std_size = (size == m_configuration.m_bufferSize);
343 long long total = m_RAM_used + size;
345 if (total <= m_configuration.m_RamAbsAvailable)
348 if (std_size && m_RAM_std_size > 0)
350 char *buf = m_RAM_std_blocks.back();
351 m_RAM_std_blocks.pop_back();
354 m_RAM_mutex.UnLock();
360 m_RAM_mutex.UnLock();
362 if (posix_memalign((
void**) &buf, s_block_align, (
size_t) size))
371 m_RAM_mutex.UnLock();
377 bool std_size = (size == m_configuration.m_bufferSize);
383 if (std_size && m_RAM_std_size < m_configuration.m_RamKeepStdBlocks)
385 m_RAM_std_blocks.push_back(buf);
397 TRACE(
Debug,
"GetFile " << path <<
", io " << io);
406 it = m_active.find(path);
410 if (it == m_active.end())
412 it = m_active.insert(std::make_pair(path, (
File*) 0)).first;
418 it->second->AddIO(io);
419 inc_ref_cnt(it->second,
false,
true);
426 m_active_cond.Wait();
435 int res = io->
Fstat(st);
438 TRACE(
Error,
"GetFile, could not get valid stat");
439 }
else if (res > 0) {
441 TRACE(
Error,
"GetFile, stat returned positive value, this should NOT happen here");
443 filesize = st.st_size;
459 inc_ref_cnt(file,
false,
true);
469 m_active_cond.Broadcast();
486 dec_ref_cnt(f,
true);
493class DiskSyncer :
public XrdJob
500 DiskSyncer(
File *f,
bool high_debug,
const char *desc =
"") :
503 m_high_debug(high_debug)
515class CommandExecutor :
public XrdJob
518 std::string m_command_url;
521 CommandExecutor(
const std::string& command,
const char *desc =
"") :
523 m_command_url(command)
537void Cache::schedule_file_sync(
File* f,
bool ref_cnt_already_set,
bool high_debug)
539 DiskSyncer* ds =
new DiskSyncer(f, high_debug);
541 if ( ! ref_cnt_already_set) inc_ref_cnt(f,
true, high_debug);
548 dec_ref_cnt(f, high_debug);
551void Cache::inc_ref_cnt(
File* f,
bool lock,
bool high_debug)
557 if (lock) m_active_cond.
Lock();
559 if (lock) m_active_cond.
UnLock();
564void Cache::dec_ref_cnt(
File* f,
bool high_debug)
572 bool emergency_close =
false;
587 <<
" -- closing and deleting File object without further ado");
588 emergency_close =
true;
619 schedule_file_sync(f,
true,
true);
624 bool finished_p =
false;
627 XrdSysCondVarHelper lock(&m_active_cond);
630 TRACE_INT(tlvl,
"dec_ref_cnt " << f->
GetLocalPath() <<
", cnt after sync_check and dec_ref_cnt = " << cnt);
643 XrdSysCondVarHelper lock(&m_active_cond);
644 m_active.erase(act_it);
645 m_active_cond.Broadcast();
654 int len = snprintf(buf, 4096,
"{\"event\":\"file_close\","
655 "\"lfn\":\"%s\",\"size\":%lld,\"blk_size\":%d,\"n_blks\":%d,\"n_blks_done\":%d,"
656 "\"access_cnt\":%lu,\"attach_t\":%lld,\"detach_t\":%lld,\"remotes\":%s,"
657 "\"b_hit\":%lld,\"b_miss\":%lld,\"b_bypass\":%lld,"
658 "\"b_todisk\":%lld,\"b_prefetch\":%lld,\"n_cks_errs\":%d}",
669 suc = m_gstream->Insert(buf, len + 1);
673 TRACE(
Error,
"Failed g-stream insertion of file_close record, len=" << len);
685 return m_active.find(path) != m_active.end() ||
686 m_purge_delay_set.find(path) != m_purge_delay_set.end();
692 m_purge_delay_set.clear();
703 if ( ! m_prefetch_enabled)
708 m_prefetch_condVar.Lock();
709 m_prefetchList.push_back(file);
710 m_prefetch_condVar.Signal();
711 m_prefetch_condVar.UnLock();
719 if ( ! m_prefetch_enabled)
724 m_prefetch_condVar.Lock();
725 for (PrefetchList::iterator it = m_prefetchList.begin(); it != m_prefetchList.end(); ++it)
729 m_prefetchList.erase(it);
733 m_prefetch_condVar.UnLock();
739 m_prefetch_condVar.Lock();
740 while (m_prefetchList.empty())
742 m_prefetch_condVar.Wait();
747 size_t l = m_prefetchList.size();
748 int idx = rand() % l;
749 File* f = m_prefetchList[idx];
751 m_prefetch_condVar.UnLock();
758 const long long limit_RAM = m_configuration.m_RamAbsAvailable * 7 / 10;
763 bool doPrefetch = (m_RAM_used < limit_RAM);
764 m_RAM_mutex.UnLock();
801 static const mode_t groupReadable = S_IRUSR | S_IWUSR | S_IRGRP;
802 static const mode_t worldReadable = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
803 static const char *lfpReason[] = {
"ForAccess",
"ForInfo",
"ForPath" };
805 TRACE(
Debug,
"LocalFilePath '" << curl <<
"', why=" << lfpReason[why]);
807 if (buff && blen > 0) buff[0] = 0;
810 std::string f_name = url.
GetPath();
815 int ret = m_oss->Lfn2Pfn(f_name.c_str(), buff, blen);
816 TRACE(
Info,
"LocalFilePath '" << curl <<
"', why=" << lfpReason[why] <<
" -> " << ret);
822 m_purge_delay_set.insert(f_name);
825 struct stat sbuff, sbuff2;
826 if (m_oss->Stat(f_name.c_str(), &sbuff) ==
XrdOssOK &&
827 m_oss->Stat(i_name.c_str(), &sbuff2) ==
XrdOssOK)
829 if (S_ISDIR(sbuff.st_mode))
831 TRACE(
Info,
"LocalFilePath '" << curl <<
"', why=" << lfpReason[why] <<
" -> EISDIR");
836 bool read_ok =
false;
837 bool is_complete =
false;
849 m_active_cond.Lock();
851 bool is_active = m_active.find(f_name) != m_active.end();
853 if (is_active) m_active_cond.UnLock();
855 XrdOssDF* infoFile = m_oss->newFile(m_configuration.m_username.c_str());
857 int res = infoFile->
Open(i_name.c_str(), O_RDWR, 0600, myEnv);
860 Info info(m_trace, 0);
861 if (info.
Read(infoFile, i_name.c_str()))
868 if ( ! is_active && is_complete && why ==
ForAccess)
871 info.
Write(infoFile, i_name.c_str());
878 if ( ! is_active) m_active_cond.UnLock();
882 if ((is_complete || why ==
ForInfo) && buff != 0)
884 int res2 = m_oss->Lfn2Pfn(f_name.c_str(), buff, blen);
891 {mode_t mode = (forall ? worldReadable : groupReadable);
892 if (((sbuff.st_mode & worldReadable) != mode)
893 && (m_oss->Chmod(f_name.c_str(), mode) !=
XrdOssOK))
894 {is_complete =
false;
900 TRACE(
Info,
"LocalFilePath '" << curl <<
"', why=" << lfpReason[why] <<
901 (is_complete ?
" -> FILE_COMPLETE_IN_CACHE" :
" -> EREMOTE"));
903 return is_complete ? 0 : -EREMOTE;
908 TRACE(
Info,
"LocalFilePath '" << curl <<
"', why=" << lfpReason[why] <<
" -> ENOENT");
918 int res =
XrdSysXAttrActive->Set(
"pfc.fsize", &file_size,
sizeof(
long long), 0, cinfo_fd, 0);
920 TRACE(
Debug,
"WriteFileSizeXAttr error setting xattr " << res);
934 m_oss->Lfn2Pfn(cinfo_fname.c_str(), pfn, 4096);
935 long long fsize = -1ll;
937 if (res ==
sizeof(
long long))
943 TRACE(
Debug,
"DetermineFullFileSize error getting xattr " << res);
947 XrdOssDF *infoFile = m_oss->newFile(m_configuration.m_username.c_str());
950 int res = infoFile->
Open(cinfo_fname.c_str(), O_RDONLY, 0600, env);
954 Info info(m_trace, 0);
955 if ( ! info.
Read(infoFile, cinfo_fname.c_str())) {
973 if (file_size == 0 || bytes_on_disk >= file_size)
976 double frac_on_disk = (double) bytes_on_disk / file_size;
978 if (file_size <= m_configuration.m_onlyIfCachedMinSize)
980 if (frac_on_disk >= m_configuration.m_onlyIfCachedMinFrac)
985 if (bytes_on_disk >= m_configuration.m_onlyIfCachedMinSize &&
986 frac_on_disk >= m_configuration.m_onlyIfCachedMinFrac)
1006 static const char* tpfx =
"ConsiderCached ";
1011 std::string f_name = url.
GetPath();
1013 File *file =
nullptr;
1016 auto it = m_active.find(f_name);
1017 if (it != m_active.end()) {
1024 inc_ref_cnt(file,
false,
false);
1030 int res = file->
Fstat(sbuff);
1031 dec_ref_cnt(file,
false);
1035 return sbuff.st_atime > 0 ? 0 : -EREMOTE;
1039 int res = m_oss->Stat(f_name.c_str(), &sbuff);
1044 if (S_ISDIR(sbuff.st_mode))
1051 if (file_size < 0) {
1052 TRACE(
Debug, tpfx << curl <<
" -> " << file_size);
1053 return (
int) file_size;
1057 return is_cached ? 0 : -EREMOTE;
1073 std::string f_name = url.
GetPath();
1077 if ((oflags & O_ACCMODE) != O_RDONLY)
1083 TRACE(Warning,
"Prepare write access requested on file " << f_name <<
". Denying access.");
1088 if (m_configuration.m_allow_xrdpfc_command && strncmp(
"/xrdpfc_command/", f_name.c_str(), 16) == 0)
1092 CommandExecutor *ce =
new CommandExecutor(f_name,
"CommandExecutor");
1102 m_purge_delay_set.insert(f_name);
1106 if (m_oss->Stat(i_name.c_str(), &sbuff) ==
XrdOssOK)
1108 TRACE(Dump,
"Prepare defer open " << f_name);
1127 const char *tpfx =
"Stat ";
1130 std::string f_name = url.
GetPath();
1132 File *file =
nullptr;
1135 auto it = m_active.find(f_name);
1136 if (it != m_active.end()) {
1142 inc_ref_cnt(file,
false,
false);
1147 int res = file->
Fstat(sbuff);
1148 dec_ref_cnt(file,
false);
1149 TRACE(
Debug, tpfx <<
"from active file " << curl <<
" -> " << res);
1153 int res = m_oss->Stat(f_name.c_str(), &sbuff);
1158 if (S_ISDIR(sbuff.st_mode))
1165 if (file_size < 0) {
1166 TRACE(
Debug, tpfx << curl <<
" -> " << file_size);
1169 sbuff.st_size = file_size;
1174 TRACE(
Debug, tpfx <<
"from disk " << curl <<
" -> " << res);
1189 std::string f_name = url.
GetPath();
1198 static const char* trc_pfx =
"UnlinkFile ";
1201 long long st_blocks_to_purge = 0;
1205 it = m_active.find(f_name);
1207 if (it != m_active.end())
1211 TRACE(
Info, trc_pfx << f_name <<
", file currently open and force not requested - denying request");
1217 if (it->second == 0)
1219 TRACE(
Info, trc_pfx << f_name <<
", an operation on this file is ongoing - denying request");
1229 it = m_active.insert(std::make_pair(f_name, (
File*) 0)).first;
1237 if (m_oss->Stat(f_name.c_str(), &f_stat) ==
XrdOssOK)
1238 st_blocks_to_purge = f_stat.st_blocks;
1244 int f_ret = m_oss->Unlink(f_name.c_str());
1245 int i_ret = m_oss->Unlink(i_name.c_str());
1247 if (st_blocks_to_purge)
1248 m_res_mon->register_file_purge(f_name, st_blocks_to_purge);
1250 TRACE(
Debug, trc_pfx << f_name <<
", f_ret=" << f_ret <<
", i_ret=" << i_ret);
1255 m_active_cond.Broadcast();
1258 return std::min(f_ret, i_ret);
int DoIt(int argpnt, int argc, char **argv, bool singleshot)
std::string obfuscateAuth(const std::string &input)
#define TRACE_PC(act, pre_code, x)
#define TRACE_INT(act, x)
void * ProcessWriteTaskThread(void *)
XrdSysXAttr * XrdSysXAttrActive
void * ResourceMonitorThread(void *)
void * PrefetchThread(void *)
XrdOucCache * XrdOucGetCache(XrdSysLogger *logger, const char *config_filename, const char *parameters, XrdOucEnv *env)
const std::string & GetPath() const
Get the path.
virtual int Close(long long *retsz=0)=0
virtual int Open(const char *path, int Oflag, mode_t Mode, XrdOucEnv &env)
virtual int Fstat(struct stat &sbuff)
virtual const char * Path()=0
virtual const char * Location(bool refresh=false)
static const int optRW
File is read/write (o/w read/only)
XrdOucCache(const char *ctype)
void * GetPtr(const char *varname)
void PutPtr(const char *varname, void *value)
Attaches/creates and detaches/deletes cache-io objects for disk based cache.
long long DetermineFullFileSize(const std::string &cinfo_fname)
void FileSyncDone(File *, bool high_debug)
File * GetFile(const std::string &, IO *, long long off=0, long long filesize=0)
static const Configuration & Conf()
virtual int LocalFilePath(const char *url, char *buff=0, int blen=0, LFP_Reason why=ForAccess, bool forall=false)
virtual int Stat(const char *url, struct stat &sbuff)
const Configuration & RefConfiguration() const
Reference XrdPfc configuration.
static ResourceMonitor & ResMon()
bool IsFileActiveOrPurgeProtected(const std::string &) const
void ClearPurgeProtectedSet()
void ReleaseRAM(char *buf, long long size)
virtual int ConsiderCached(const char *url)
static Cache & GetInstance()
Singleton access.
bool Config(const char *config_filename, const char *parameters, XrdOucEnv *env)
Parse configuration file.
void DeRegisterPrefetchFile(File *)
void ExecuteCommandUrl(const std::string &command_url)
void RegisterPrefetchFile(File *)
void WriteFileSizeXAttr(int cinfo_fd, long long file_size)
void ReleaseFile(File *, IO *)
void AddWriteTask(Block *b, bool from_read)
Add downloaded block in write queue.
Cache(XrdSysLogger *logger, XrdOucEnv *env)
Constructor.
bool Decide(XrdOucCacheIO *)
Makes decision if the original XrdOucCacheIO should be cached.
int UnlinkFile(const std::string &f_name, bool fail_if_open)
Remove cinfo and data files from cache.
static XrdScheduler * schedP
File * GetNextFileToPrefetch()
long long WritesSinceLastCall()
void ProcessWriteTasks()
Separate task which writes blocks from ram to disk.
virtual int Unlink(const char *url)
void RemoveWriteQEntriesFor(File *f)
Remove blocks from write queue which belong to given prefetch. This method is used at the time of Fil...
virtual XrdOucCacheIO * Attach(XrdOucCacheIO *, int Options=0)
static const Cache & TheOne()
char * RequestRAM(long long size)
virtual int Prepare(const char *url, int oflags, mode_t mode)
bool DecideIfConsideredCached(long long file_size, long long bytes_on_disk)
static Cache & CreateInstance(XrdSysLogger *logger, XrdOucEnv *env)
Singleton creation.
bool is_prefetch_enabled() const
Base class for selecting which files should be cached.
virtual bool Decide(const std::string &, XrdOss &) const =0
bool FinalizeSyncBeforeExit()
Returns true if any of blocks need sync. Called from Cache::dec_ref_cnt on zero ref cnt.
const char * lPath() const
Log path.
void WriteBlockToDisk(Block *b)
std::string GetRemoteLocations() const
size_t GetAccessCnt() const
int Fstat(struct stat &sbuff)
static File * FileOpen(const std::string &path, long long offset, long long fileSize, XrdOucCacheIO *inputIO)
Static constructor that also does Open. Returns null ptr if Open fails.
long long GetPrefetchedBytes() const
int GetNDownloadedBlocks() const
const Info::AStat * GetLastAccessStats() const
void BlocksRemovedFromWriteQ(std::list< Block * > &)
Handle removal of a set of blocks from Cache's write queue.
const Stats & RefStats() const
void Sync()
Sync file cache inf o and output data with disk.
long long initiate_emergency_shutdown()
long long GetFileSize() const
const std::string & GetLocalPath() const
bool is_in_emergency_shutdown()
Downloads original file into multiple files, chunked into blocks. Only blocks that are asked for are ...
Downloads original file into a single file on local disk. Handles read requests as they come along.
bool HasFile() const
Check if File was opened successfully.
Base cache-io class that implements some XrdOucCacheIO abstract methods.
XrdOucCacheIO * GetInput()
Status of cached file. Can be read from and written into a binary file.
static const char * s_infoExtension
void WriteIOStatSingle(long long bytes_disk)
Write single open/close time for given bytes read from disk.
bool Write(XrdOssDF *fp, const char *dname, const char *fname=0)
bool IsComplete() const
Get complete status.
long long GetFileSize() const
Get file size.
bool Read(XrdOssDF *fp, const char *dname, const char *fname=0)
Read content of cinfo file into this object.
void main_thread_function()
int m_NCksumErrors
number of checksum errors while getting data from remote
long long m_BytesWritten
number of bytes written to disk
void Say(const char *text1, const char *text2=0, const char *txt3=0, const char *text4=0, const char *text5=0, const char *txt6=0)
static int Run(pthread_t *, void *(*proc)(void *), void *arg, int opts=0, const char *desc=0)
static void Wait(int milliseconds)
Contains parameters configurable from the xrootd config file.
long long BytesHit
read from cache
long long BytesBypassed
read from remote and dropped
time_t DetachTime
close time
long long BytesMissed
read from remote and cached
time_t AttachTime
open time