22 #include <sys/statvfs.h>
48 Cache *Cache::m_instance =
nullptr;
75 const char *config_filename,
76 const char *parameters,
80 err.
Say(
"++++++ Proxy file cache initialization started.");
91 if (! instance.
Config(config_filename, parameters))
93 err.
Say(
"Config Proxy file cache initialization failed.");
96 err.
Say(
"++++++ Proxy file cache initialization completed.");
103 for (
int wti = 0; wti < instance.
RefConfiguration().m_wqueue_threads; ++wti)
115 env->
PutPtr(
"XrdFSCtl_PC*", pfcFSctl);
125 assert (m_instance == 0);
126 m_instance =
new Cache(logger, env);
137 if (! m_decisionpoints.empty())
140 std::string filename = url.
GetPath();
141 std::vector<Decision*>::const_iterator it;
142 for (it = m_decisionpoints.begin(); it != m_decisionpoints.end(); ++it)
146 if (! d->
Decide(filename, *m_oss))
159 m_log(logger,
"XrdPfc_"),
165 m_prefetch_condVar(0),
166 m_prefetch_enabled(false),
168 m_RAM_write_queue(0),
179 const char* tpfx =
"Attach() ";
200 TRACE(
Error, tpfx <<
"Failed opening local file, falling back to remote access " << io->
Path());
208 ((loc && loc[0] != 0) ? loc :
"<deferred open>"));
228 m_writeQ.condVar.Lock();
230 m_writeQ.queue.push_back(b);
232 m_writeQ.queue.push_front(b);
234 m_writeQ.condVar.Signal();
235 m_writeQ.condVar.UnLock();
240 std::list<Block*> removed_blocks;
241 long long sum_size = 0;
243 m_writeQ.condVar.Lock();
244 std::list<Block*>::iterator i = m_writeQ.queue.begin();
245 while (i != m_writeQ.queue.end())
247 if ((*i)->m_file == file)
249 TRACE(Dump,
"Remove entries for " << (
void*)(*i) <<
" path " << file->
lPath());
250 std::list<Block*>::iterator j = i++;
251 removed_blocks.push_back(*j);
252 sum_size += (*j)->get_size();
253 m_writeQ.queue.erase(j);
261 m_writeQ.condVar.UnLock();
265 m_RAM_write_queue -= sum_size;
277 m_writeQ.condVar.Lock();
278 while (m_writeQ.size == 0)
280 m_writeQ.condVar.Wait();
286 int n_pushed = std::min(m_writeQ.size, m_configuration.
m_wqueue_blocks);
287 long long sum_size = 0;
289 for (
int bi = 0; bi < n_pushed; ++bi)
291 Block* block = m_writeQ.queue.front();
292 m_writeQ.queue.pop_front();
293 m_writeQ.writes_between_purges += block->
get_size();
296 blks_to_write[bi] = block;
298 TRACE(Dump,
"ProcessWriteTasks for block " << (
void*)(block) <<
" path " << block->
m_file->
lPath());
300 m_writeQ.size -= n_pushed;
302 m_writeQ.condVar.UnLock();
306 m_RAM_write_queue -= sum_size;
309 for (
int bi = 0; bi < n_pushed; ++bi)
311 Block* block = blks_to_write[bi];
322 long long ret = m_writeQ.writes_between_purges;
323 m_writeQ.writes_between_purges = 0;
331 static const size_t s_block_align = sysconf(_SC_PAGESIZE);
337 long long total = m_RAM_used + size;
342 if (std_size && m_RAM_std_size > 0)
344 char *buf = m_RAM_std_blocks.back();
345 m_RAM_std_blocks.pop_back();
356 if (posix_memalign((
void**) &buf, s_block_align, (
size_t) size))
379 m_RAM_std_blocks.push_back(buf);
391 TRACE(
Debug,
"GetFile " << path <<
", io " << io);
400 it = m_active.find(path);
404 if (it == m_active.end())
406 it = m_active.insert(std::make_pair(path, (
File*) 0)).first;
412 it->second->AddIO(io);
413 inc_ref_cnt(it->second,
false,
true);
420 m_active_cond.
Wait();
428 int res = io->
Fstat(st);
431 TRACE(
Error,
"GetFile, could not get valid stat");
432 }
else if (res > 0) {
434 TRACE(
Error,
"GetFile, stat returned positive value, this should NOT happen here");
436 filesize = st.st_size;
452 inc_ref_cnt(file,
false,
true);
479 dec_ref_cnt(f,
true);
489 class DiskSyncer :
public XrdJob
496 DiskSyncer(
File *f,
bool high_debug,
const char *desc =
"") :
499 m_high_debug(high_debug)
511 class CommandExecutor :
public XrdJob
514 std::string m_command_url;
517 CommandExecutor(
const std::string& command,
const char *desc =
"") :
519 m_command_url(command)
533 void Cache::schedule_file_sync(
File* f,
bool ref_cnt_already_set,
bool high_debug)
535 DiskSyncer* ds =
new DiskSyncer(f, high_debug);
537 if ( ! ref_cnt_already_set) inc_ref_cnt(f,
true, high_debug);
544 dec_ref_cnt(f, high_debug);
547 void Cache::inc_ref_cnt(
File* f,
bool lock,
bool high_debug)
553 if (lock) m_active_cond.
Lock();
555 if (lock) m_active_cond.
UnLock();
560 void Cache::dec_ref_cnt(
File* f,
bool high_debug)
580 <<
" -- deleting File object without further ado");
603 schedule_file_sync(f,
true,
true);
608 bool finished_p =
false;
613 TRACE_INT(tlvl,
"dec_ref_cnt " << f->
GetLocalPath() <<
", cnt after sync_check and dec_ref_cnt = " << cnt);
631 int len = snprintf(buf, 4096,
"{\"event\":\"file_close\","
632 "\"lfn\":\"%s\",\"size\":%lld,\"blk_size\":%d,\"n_blks\":%d,\"n_blks_done\":%d,"
633 "\"access_cnt\":%lu,\"attach_t\":%lld,\"detach_t\":%lld,\"remotes\":%s,"
634 "\"b_hit\":%lld,\"b_miss\":%lld,\"b_bypass\":%lld,\"b_write\":%lld,\"n_cks_errs\":%d}",
644 suc = m_gstream->
Insert(buf, len + 1);
648 TRACE(
Error,
"Failed g-stream insertion of file_close record, len=" << len);
660 return m_active.find(path) != m_active.end() ||
661 m_purge_delay_set.find(path) != m_purge_delay_set.end();
667 m_purge_delay_set.clear();
678 if ( ! m_prefetch_enabled)
683 m_prefetch_condVar.
Lock();
684 m_prefetchList.push_back(file);
685 m_prefetch_condVar.
Signal();
686 m_prefetch_condVar.
UnLock();
694 if ( ! m_prefetch_enabled)
699 m_prefetch_condVar.
Lock();
700 for (PrefetchList::iterator it = m_prefetchList.begin(); it != m_prefetchList.end(); ++it)
704 m_prefetchList.erase(it);
708 m_prefetch_condVar.
UnLock();
714 m_prefetch_condVar.
Lock();
715 while (m_prefetchList.empty())
717 m_prefetch_condVar.
Wait();
722 size_t l = m_prefetchList.size();
723 int idx = rand() % l;
724 File* f = m_prefetchList[idx];
726 m_prefetch_condVar.
UnLock();
738 bool doPrefetch = (m_RAM_used < limit_RAM);
776 static const mode_t groupReadable = S_IRUSR | S_IWUSR | S_IRGRP;
777 static const mode_t worldReadable = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
778 static const char *lfpReason[] = {
"ForAccess",
"ForInfo",
"ForPath" };
780 TRACE(
Debug,
"LocalFilePath '" << curl <<
"', why=" << lfpReason[why]);
782 if (buff && blen > 0) buff[0] = 0;
785 std::string f_name = url.
GetPath();
790 int ret = m_oss->
Lfn2Pfn(f_name.c_str(), buff, blen);
791 TRACE(
Info,
"LocalFilePath '" << curl <<
"', why=" << lfpReason[why] <<
" -> " << ret);
797 m_purge_delay_set.insert(f_name);
800 struct stat sbuff, sbuff2;
804 if (S_ISDIR(sbuff.st_mode))
806 TRACE(
Info,
"LocalFilePath '" << curl <<
"', why=" << lfpReason[why] <<
" -> EISDIR");
811 bool read_ok =
false;
812 bool is_complete =
false;
824 m_active_cond.
Lock();
826 bool is_active = m_active.find(f_name) != m_active.end();
828 if (is_active) m_active_cond.
UnLock();
832 int res = infoFile->
Open(i_name.c_str(), O_RDWR, 0600, myEnv);
835 Info info(m_trace, 0);
836 if (info.
Read(infoFile, i_name.c_str()))
843 if ( ! is_active && is_complete && why ==
ForAccess)
846 info.
Write(infoFile, i_name.c_str());
853 if ( ! is_active) m_active_cond.
UnLock();
857 if ((is_complete || why ==
ForInfo) && buff != 0)
859 int res2 = m_oss->
Lfn2Pfn(f_name.c_str(), buff, blen);
866 {mode_t mode = (forall ? worldReadable : groupReadable);
867 if (((sbuff.st_mode & worldReadable) != mode)
869 {is_complete =
false;
875 TRACE(
Info,
"LocalFilePath '" << curl <<
"', why=" << lfpReason[why] <<
876 (is_complete ?
" -> FILE_COMPLETE_IN_CACHE" :
" -> EREMOTE"));
878 return is_complete ? 0 : -EREMOTE;
883 TRACE(
Info,
"LocalFilePath '" << curl <<
"', why=" << lfpReason[why] <<
" -> ENOENT");
903 TRACE(
Debug,
"ConsiderFileCached '" << curl <<
"'" );
906 std::string f_name = url.
GetPath();
911 m_purge_delay_set.insert(f_name);
914 struct stat sbuff, sbuff2;
918 if (S_ISDIR(sbuff.st_mode))
920 TRACE(
Info,
"ConsiderCached '" << curl <<
", why=ForInfo" <<
" -> EISDIR");
925 bool read_ok =
false;
926 bool is_cached =
false;
938 m_active_cond.
Lock();
940 bool is_active = m_active.find(f_name) != m_active.end();
947 int res = infoFile->
Open(i_name.c_str(), O_RDWR, 0600, myEnv);
950 Info info(m_trace, 0);
951 if (info.
Read(infoFile, i_name.c_str()))
985 if (!is_active) m_active_cond.
UnLock();
989 TRACE(
Info,
"ConsiderCached '" << curl <<
"', why=ForInfo" << (is_cached ?
" -> FILE_COMPLETE_IN_CACHE" :
" -> EREMOTE"));
990 return is_cached ? 0 : -EREMOTE;
995 TRACE(
Info,
"ConsiderCached '" << curl <<
"', why=ForInfo" <<
" -> ENOENT");
1012 std::string f_name = url.
GetPath();
1016 if (oflags & (O_WRONLY | O_RDWR | O_APPEND | O_CREAT))
1018 TRACE(
Warning,
"Prepare write access requested on file " << f_name <<
". Denying access.");
1027 CommandExecutor *ce =
new CommandExecutor(f_name,
"CommandExecutor");
1037 m_purge_delay_set.insert(f_name);
1041 int res = m_oss->
Stat(i_name.c_str(), &sbuff);
1044 TRACE(Dump,
"Prepare defer open " << f_name);
1064 std::string f_name = url.
GetPath();
1068 m_purge_delay_set.insert(f_name);
1073 if (S_ISDIR(sbuff.st_mode))
1079 bool success =
false;
1084 int res = infoFile->
Open(f_name.c_str(), O_RDONLY, 0600, myEnv);
1087 Info info(m_trace, 0);
1088 if (info.
Read(infoFile, f_name.c_str()))
1096 return success ? 0 : 1;
1113 std::string f_name = url.
GetPath();
1122 static const char* trc_pfx =
"UnlinkFile ";
1128 it = m_active.find(f_name);
1130 if (it != m_active.end())
1134 TRACE(
Info, trc_pfx << f_name <<
", file currently open and force not requested - denying request");
1140 if (it->second == 0)
1142 TRACE(
Info, trc_pfx << f_name <<
", an operation on this file is ongoing - denying request");
1152 it = m_active.insert(std::make_pair(f_name, (
File*) 0)).first;
1165 bool stat_ok = (m_oss->
Stat(f_name.c_str(), &f_stat) ==
XrdOssOK);
1166 int f_ret = m_oss->
Unlink(f_name.c_str());
1167 int i_ret = m_oss->
Unlink(i_name.c_str());
1172 TRACE(
Debug, trc_pfx << f_name <<
", f_ret=" << f_ret <<
", i_ret=" << i_ret);
1180 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 * ResourceMonitorThread(void *)
XrdOucCache * XrdOucGetCache(XrdSysLogger *logger, const char *config_filename, const char *parameters, XrdOucEnv *env)
void * PrefetchThread(void *)
void * ProcessWriteTaskThread(void *)
int stat(const char *path, struct stat *buf)
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 Chmod(const char *path, mode_t mode, XrdOucEnv *envP=0)=0
virtual int Lfn2Pfn(const char *Path, char *buff, int blen)
virtual XrdOssDF * newFile(const char *tident)=0
virtual int Stat(const char *path, struct stat *buff, int opts=0, XrdOucEnv *envP=0)=0
virtual int Unlink(const char *path, int Opts=0, XrdOucEnv *envP=0)=0
virtual const char * Path()=0
virtual int Fstat(struct stat &sbuff)
virtual const char * Location(bool refresh=false)
void * GetPtr(const char *varname)
void PutPtr(const char *varname, void *value)
Attaches/creates and detaches/deletes cache-io objects for disk based cache.
void FileSyncDone(File *, bool high_debug)
File * GetFile(const std::string &, IO *, long long off=0, long long filesize=0)
static const Configuration & Conf()
bool Config(const char *config_filename, const char *parameters)
Parse configuration file.
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.
void DeRegisterPrefetchFile(File *)
void ExecuteCommandUrl(const std::string &command_url)
void RegisterPrefetchFile(File *)
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.
virtual XrdOucCacheIO * Attach(XrdOucCacheIO *ioP, int opts=0)=0
Obtain a new IO object that fronts existing XrdOucCacheIO.
static XrdScheduler * schedP
File * GetNextFileToPrefetch()
ResourceMonitor & RefResMon()
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...
static const Cache & TheOne()
char * RequestRAM(long long size)
virtual int Prepare(const char *url, int oflags, mode_t mode)
static Cache & CreateInstance(XrdSysLogger *logger, XrdOucEnv *env)
Singleton creation.
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)
static File * FileOpen(const std::string &path, long long offset, long long fileSize)
Static constructor that also does Open. Returns null ptr if Open fails.
std::string GetRemoteLocations() const
const Info::AStat * GetLastAccessStats() const
size_t GetAccessCnt() const
int GetNDownloadedBlocks() const
void BlocksRemovedFromWriteQ(std::list< Block * > &)
Handle removal of a set of blocks from Cache's write queue.
void initiate_emergency_shutdown()
void Sync()
Sync file cache inf o and output data with disk.
long long GetFileSize() const
const Stats & RefStats() 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.
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)
long long GetNDownloadedBytes() const
Get number of downloaded bytes.
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 register_file_purge(DirState *target, long long size_in_st_blocks)
void main_thread_function()
Statistics of cache utilisation by a File object.
long long m_BytesMissed
number of bytes served from remote and cached
long long m_BytesBypassed
number of bytes served directly through XrdCl
int m_NCksumErrors
number of checksum errors while getting data from remote
long long m_BytesHit
number of bytes served from disk
long long m_BytesWritten
number of bytes written to disk
void Schedule(XrdJob *jp)
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)
bool Insert(const char *data, int dlen)
Contains parameters configurable from the xrootd config file.
long long m_RamAbsAvailable
available from configuration
bool m_allow_xrdpfc_command
flag for enabling access to /xrdpfc-command/ functionality.
int m_prefetch_max_blocks
maximum number of blocks to prefetch per file
int m_RamKeepStdBlocks
number of standard-sized blocks kept after release
long long m_bufferSize
prefetch buffer size, default 1MB
int m_wqueue_blocks
maximum number of blocks written per write-queue loop
std::string m_username
username passed to oss plugin
double m_onlyIfCachedMinFrac
minimum fraction of downloaded file, used by only-if-cached CGI option
long long m_onlyIfCachedMinSize
minumum size of downloaded file, used by only-if-cached CGI option
time_t DetachTime
close time
time_t AttachTime
open time