22#include <sys/statvfs.h>
48Cache * Cache::m_instance = 0;
82 const char *config_filename,
83 const char *parameters,
87 err.
Say(
"++++++ Proxy file cache initialization started.");
98 if (! instance.
Config(config_filename, parameters))
100 err.
Say(
"Config Proxy file cache initialization failed.");
103 err.
Say(
"------ Proxy file cache initialization completed.");
108 for (
int wti = 0; wti < instance.
RefConfiguration().m_wqueue_threads; ++wti)
124 env->
PutPtr(
"XrdFSCtl_PC*", pfcFSctl);
133 double &frac_du,
double &frac_fu)
147 frac_du = std::min( std::max( frac_du, 0.0), 1.0 );
148 frac_fu = std::min( std::max( frac_fu, 0.0), 1.0 );
155 assert (m_instance == 0);
156 m_instance =
new Cache(logger, env);
166 if (! m_decisionpoints.empty())
169 std::string filename = url.
GetPath();
170 std::vector<Decision*>::const_iterator it;
171 for (it = m_decisionpoints.begin(); it != m_decisionpoints.end(); ++it)
175 if (! d->
Decide(filename, *m_oss))
188 m_log(logger,
"XrdPfc_"),
193 m_prefetch_condVar(0),
194 m_prefetch_enabled(false),
196 m_RAM_write_queue(0),
201 m_stats_n_purge_cond(0),
203 m_last_scan_duration(0),
204 m_last_purge_duration(0),
205 m_spt_state(SPTS_Idle)
213 const char* tpfx =
"Attach() ";
234 TRACE(
Error, tpfx <<
"Failed opening local file, falling back to remote access " << io->
Path());
242 ((loc && loc[0] != 0) ? loc :
"<deferred open>"));
262 m_writeQ.condVar.Lock();
264 m_writeQ.queue.push_back(b);
266 m_writeQ.queue.push_front(b);
268 m_writeQ.condVar.Signal();
269 m_writeQ.condVar.UnLock();
274 std::list<Block*> removed_blocks;
275 long long sum_size = 0;
277 m_writeQ.condVar.Lock();
278 std::list<Block*>::iterator i = m_writeQ.queue.begin();
279 while (i != m_writeQ.queue.end())
281 if ((*i)->m_file == file)
283 TRACE(Dump,
"Remove entries for " << (
void*)(*i) <<
" path " << file->
lPath());
284 std::list<Block*>::iterator j = i++;
285 removed_blocks.push_back(*j);
286 sum_size += (*j)->get_size();
287 m_writeQ.queue.erase(j);
295 m_writeQ.condVar.UnLock();
299 m_RAM_write_queue -= sum_size;
311 m_writeQ.condVar.Lock();
312 while (m_writeQ.size == 0)
314 m_writeQ.condVar.Wait();
320 int n_pushed = std::min(m_writeQ.size, m_configuration.
m_wqueue_blocks);
321 long long sum_size = 0;
323 for (
int bi = 0; bi < n_pushed; ++bi)
325 Block* block = m_writeQ.queue.front();
326 m_writeQ.queue.pop_front();
327 m_writeQ.writes_between_purges += block->
get_size();
330 blks_to_write[bi] = block;
332 TRACE(Dump,
"ProcessWriteTasks for block " << (
void*)(block) <<
" path " << block->
m_file->
lPath());
334 m_writeQ.size -= n_pushed;
336 m_writeQ.condVar.UnLock();
340 m_RAM_write_queue -= sum_size;
343 for (
int bi = 0; bi < n_pushed; ++bi)
345 Block* block = blks_to_write[bi];
356 static const size_t s_block_align = sysconf(_SC_PAGESIZE);
362 long long total = m_RAM_used + size;
367 if (std_size && m_RAM_std_size > 0)
369 char *buf = m_RAM_std_blocks.back();
370 m_RAM_std_blocks.pop_back();
381 if (posix_memalign((
void**) &buf, s_block_align, (
size_t) size))
404 m_RAM_std_blocks.push_back(buf);
416 TRACE(
Debug,
"GetFile " << path <<
", io " << io);
425 it = m_active.find(path);
429 if (it == m_active.end())
431 it = m_active.insert(std::make_pair(path, (
File*) 0)).first;
437 it->second->AddIO(io);
438 inc_ref_cnt(it->second,
false,
true);
445 m_active_cond.
Wait();
453 int res = io->
Fstat(st);
456 TRACE(
Error,
"GetFile, could not get valid stat");
457 }
else if (res > 0) {
459 TRACE(
Error,
"GetFile, stat returned positive value, this should NOT happen here");
461 filesize = st.st_size;
477 inc_ref_cnt(file,
false,
true);
504 dec_ref_cnt(f,
true);
511class DiskSyncer :
public XrdJob
518 DiskSyncer(
File *f,
bool high_debug,
const char *desc =
"") :
521 m_high_debug(high_debug)
533class CommandExecutor :
public XrdJob
536 std::string m_command_url;
539 CommandExecutor(
const std::string& command,
const char *desc =
"") :
541 m_command_url(command)
555void Cache::schedule_file_sync(
File* f,
bool ref_cnt_already_set,
bool high_debug)
557 DiskSyncer* ds =
new DiskSyncer(f, high_debug);
559 if ( ! ref_cnt_already_set) inc_ref_cnt(f,
true, high_debug);
566 dec_ref_cnt(f, high_debug);
569void Cache::inc_ref_cnt(
File* f,
bool lock,
bool high_debug)
575 if (lock) m_active_cond.
Lock();
577 if (lock) m_active_cond.
UnLock();
582void Cache::dec_ref_cnt(
File* f,
bool high_debug)
602 <<
" -- deleting File object without further ado");
625 schedule_file_sync(f,
true,
true);
634 TRACE_INT(tlvl,
"dec_ref_cnt " << f->
GetLocalPath() <<
", cnt after sync_check and dec_ref_cnt = " << cnt);
648 int len = snprintf(buf, 4096,
"{\"event\":\"file_close\","
649 "\"lfn\":\"%s\",\"size\":%lld,\"blk_size\":%d,\"n_blks\":%d,\"n_blks_done\":%d,"
650 "\"access_cnt\":%lu,\"attach_t\":%lld,\"detach_t\":%lld,\"remotes\":%s,"
651 "\"b_hit\":%lld,\"b_miss\":%lld,\"b_bypass\":%lld,\"n_cks_errs\":%d}",
661 suc = m_gstream->
Insert(buf, len + 1);
665 TRACE(
Error,
"Failed g-stream insertion of file_close record, len=" << len);
678 return m_active.find(path) != m_active.end() ||
679 m_purge_delay_set.find(path) != m_purge_delay_set.end();
691 if ( ! m_prefetch_enabled)
696 m_prefetch_condVar.
Lock();
697 m_prefetchList.push_back(file);
698 m_prefetch_condVar.
Signal();
699 m_prefetch_condVar.
UnLock();
707 if ( ! m_prefetch_enabled)
712 m_prefetch_condVar.
Lock();
713 for (PrefetchList::iterator it = m_prefetchList.begin(); it != m_prefetchList.end(); ++it)
717 m_prefetchList.erase(it);
721 m_prefetch_condVar.
UnLock();
727 m_prefetch_condVar.
Lock();
728 while (m_prefetchList.empty())
730 m_prefetch_condVar.
Wait();
735 size_t l = m_prefetchList.size();
736 int idx = rand() % l;
737 File* f = m_prefetchList[idx];
739 m_prefetch_condVar.
UnLock();
751 bool doPrefetch = (m_RAM_used < limit_RAM);
789 static const mode_t groupReadable = S_IRUSR | S_IWUSR | S_IRGRP;
790 static const mode_t worldReadable = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
791 static const char *lfpReason[] = {
"ForAccess",
"ForInfo",
"ForPath" };
793 TRACE(
Debug,
"LocalFilePath '" << curl <<
"', why=" << lfpReason[why]);
795 if (buff && blen > 0) buff[0] = 0;
798 std::string f_name = url.
GetPath();
803 int ret = m_oss->
Lfn2Pfn(f_name.c_str(), buff, blen);
804 TRACE(
Info,
"LocalFilePath '" << curl <<
"', why=" << lfpReason[why] <<
" -> " << ret);
810 m_purge_delay_set.insert(f_name);
813 struct stat sbuff, sbuff2;
817 if (S_ISDIR(sbuff.st_mode))
819 TRACE(
Info,
"LocalFilePath '" << curl <<
"', why=" << lfpReason[why] <<
" -> EISDIR");
824 bool read_ok =
false;
825 bool is_complete =
false;
837 m_active_cond.
Lock();
839 bool is_active = m_active.find(f_name) != m_active.end();
841 if (is_active) m_active_cond.
UnLock();
845 int res = infoFile->
Open(i_name.c_str(), O_RDWR, 0600, myEnv);
848 Info info(m_trace, 0);
849 if (info.
Read(infoFile, i_name.c_str()))
856 if ( ! is_active && is_complete && why ==
ForAccess)
859 info.
Write(infoFile, i_name.c_str());
866 if ( ! is_active) m_active_cond.
UnLock();
870 if ((is_complete || why ==
ForInfo) && buff != 0)
872 int res2 = m_oss->
Lfn2Pfn(f_name.c_str(), buff, blen);
879 {mode_t mode = (forall ? worldReadable : groupReadable);
880 if (((sbuff.st_mode & worldReadable) != mode)
882 {is_complete =
false;
888 TRACE(
Info,
"LocalFilePath '" << curl <<
"', why=" << lfpReason[why] <<
889 (is_complete ?
" -> FILE_COMPLETE_IN_CACHE" :
" -> EREMOTE"));
891 return is_complete ? 0 : -EREMOTE;
896 TRACE(
Info,
"LocalFilePath '" << curl <<
"', why=" << lfpReason[why] <<
" -> ENOENT");
916 TRACE(
Debug,
"ConsiderFileCached '" << curl <<
"'" );
919 std::string f_name = url.
GetPath();
924 m_purge_delay_set.insert(f_name);
927 struct stat sbuff, sbuff2;
931 if (S_ISDIR(sbuff.st_mode))
933 TRACE(
Info,
"ConsiderCached '" << curl <<
", why=ForInfo" <<
" -> EISDIR");
938 bool read_ok =
false;
939 bool is_cached =
false;
951 m_active_cond.
Lock();
953 bool is_active = m_active.find(f_name) != m_active.end();
960 int res = infoFile->
Open(i_name.c_str(), O_RDWR, 0600, myEnv);
963 Info info(m_trace, 0);
964 if (info.
Read(infoFile, i_name.c_str()))
998 if (!is_active) m_active_cond.
UnLock();
1002 TRACE(
Info,
"ConsiderCached '" << curl <<
"', why=ForInfo" << (is_cached ?
" -> FILE_COMPLETE_IN_CACHE" :
" -> EREMOTE"));
1003 return is_cached ? 0 : -EREMOTE;
1008 TRACE(
Info,
"ConsiderCached '" << curl <<
"', why=ForInfo" <<
" -> ENOENT");
1025 std::string f_name = url.
GetPath();
1029 if (oflags & (O_WRONLY | O_RDWR | O_APPEND | O_CREAT))
1031 TRACE(Warning,
"Prepare write access requested on file " << f_name <<
". Denying access.");
1040 CommandExecutor *ce =
new CommandExecutor(f_name,
"CommandExecutor");
1050 m_purge_delay_set.insert(f_name);
1054 int res = m_oss->
Stat(i_name.c_str(), &sbuff);
1057 TRACE(Dump,
"Prepare defer open " << f_name);
1077 std::string f_name = url.
GetPath();
1081 m_purge_delay_set.insert(f_name);
1086 if (S_ISDIR(sbuff.st_mode))
1092 bool success =
false;
1097 int res = infoFile->
Open(f_name.c_str(), O_RDONLY, 0600, myEnv);
1100 Info info(m_trace, 0);
1101 if (info.
Read(infoFile, f_name.c_str()))
1109 return success ? 0 : 1;
1126 std::string f_name = url.
GetPath();
1140 it = m_active.find(f_name);
1142 if (it != m_active.end())
1146 TRACE(
Info,
"UnlinkCommon " << f_name <<
", file currently open and force not requested - denying request");
1152 if (it->second == 0)
1154 TRACE(
Info,
"UnlinkCommon " << f_name <<
", an operation on this file is ongoing - denying request");
1164 it = m_active.insert(std::make_pair(f_name, (
File*) 0)).first;
1176 int f_ret = m_oss->
Unlink(f_name.c_str());
1177 int i_ret = m_oss->
Unlink(i_name.c_str());
1179 TRACE(
Debug,
"UnlinkCommon " << f_name <<
", f_ret=" << f_ret <<
", i_ret=" << i_ret);
1187 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 *)
void * ResourceMonitorHeartBeatThread(void *)
void * PrefetchThread(void *)
XrdOucCache * XrdOucGetCache(XrdSysLogger *logger, const char *config_filename, const char *parameters, XrdOucEnv *env)
void * PurgeThread(void *)
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 XrdOssDF * newFile(const char *tident)=0
virtual int Chmod(const char *path, mode_t mode, XrdOucEnv *envP=0)=0
virtual int Lfn2Pfn(const char *Path, char *buff, int blen)
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 int Fstat(struct stat &sbuff)
virtual const char * Path()=0
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.
void Purge()
Thread function invoked to scan and purge files from disk when needed.
void ReleaseRAM(char *buf, long long size)
virtual int ConsiderCached(const char *url)
static Cache & GetInstance()
Singleton access.
void ResourceMonitorHeartBeat()
Thread function checking resource usage periodically.
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.
static XrdScheduler * schedP
bool IsFileActiveOrPurgeProtected(const std::string &)
File * GetNextFileToPrefetch()
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)
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)
std::string & GetLocalPath()
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
size_t GetAccessCnt() 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.
void initiate_emergency_shutdown()
const Stats & RefStats() const
void Sync()
Sync file cache inf o and output data with disk.
Stats DeltaStatsFromLastCall()
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.
Statistics of cache utilisation by a File object.
int m_NCksumErrors
number of checksum errors while getting data from remote
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
long long m_fileUsageMax
cache purge - files usage maximum
long long m_fileUsageBaseline
cache purge - files usage baseline
bool m_allow_xrdpfc_command
flag for enabling access to /xrdpfc-command/ functionality.
long long m_diskUsageHWM
cache purge - disk usage high water mark
int m_prefetch_max_blocks
maximum number of blocks to prefetch per file
void calculate_fractional_usages(long long du, long long fu, double &frac_du, double &frac_fu)
long long m_diskUsageLWM
cache purge - disk usage low water mark
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
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