XRootD
Loading...
Searching...
No Matches
XrdPfc.cc
Go to the documentation of this file.
1//----------------------------------------------------------------------------------
2// Copyright (c) 2014 by Board of Trustees of the Leland Stanford, Jr., University
3// Author: Alja Mrak-Tadel, Matevz Tadel, Brian Bockelman
4//----------------------------------------------------------------------------------
5// XRootD is free software: you can redistribute it and/or modify
6// it under the terms of the GNU Lesser General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// XRootD is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU Lesser General Public License
16// along with XRootD. If not, see <http://www.gnu.org/licenses/>.
17//----------------------------------------------------------------------------------
18
19#include <fcntl.h>
20#include <sstream>
21#include <algorithm>
22#include <sys/statvfs.h>
23
24#include "XrdCl/XrdClURL.hh"
25
26#include "XrdOuc/XrdOucEnv.hh"
27#include "XrdOuc/XrdOucUtils.hh"
29
30#include "XrdSys/XrdSysTimer.hh"
31#include "XrdSys/XrdSysTrace.hh"
32#include "XrdSys/XrdSysXAttr.hh"
33
35
36#include "XrdOss/XrdOss.hh"
37
38#include "XrdPfc.hh"
39#include "XrdPfcTrace.hh"
40#include "XrdPfcFSctl.hh"
41#include "XrdPfcInfo.hh"
42#include "XrdPfcIOFile.hh"
43#include "XrdPfcIOFileBlock.hh"
45
47
48using namespace XrdPfc;
49
50Cache *Cache::m_instance = nullptr;
52
53
55{
57 return 0;
58}
59
61{
63 return 0;
64}
65
66void *PrefetchThread(void*)
67{
69 return 0;
70}
71
72//==============================================================================
73
74extern "C"
75{
77 const char *config_filename,
78 const char *parameters,
79 XrdOucEnv *env)
80{
81 XrdSysError err(logger, "");
82 err.Say("++++++ Proxy file cache initialization started.");
83
84 if ( ! env ||
85 ! (XrdPfc::Cache::schedP = (XrdScheduler*) env->GetPtr("XrdScheduler*")))
86 {
88 XrdPfc::Cache::schedP->Start();
89 }
90
91 Cache &instance = Cache::CreateInstance(logger, env);
92
93 if (! instance.Config(config_filename, parameters))
94 {
95 err.Say("Config Proxy file cache initialization failed.");
96 return 0;
97 }
98 err.Say("++++++ Proxy file cache initialization completed.");
99
100 {
101 pthread_t tid;
102
103 XrdSysThread::Run(&tid, ResourceMonitorThread, 0, 0, "XrdPfc ResourceMonitor");
104
105 for (int wti = 0; wti < instance.RefConfiguration().m_wqueue_threads; ++wti)
106 {
107 XrdSysThread::Run(&tid, ProcessWriteTaskThread, 0, 0, "XrdPfc WriteTasks ");
108 }
109
110 if (instance.RefConfiguration().m_prefetch_max_blocks > 0)
111 {
112 XrdSysThread::Run(&tid, PrefetchThread, 0, 0, "XrdPfc Prefetch ");
113 }
114 }
115
116 XrdPfcFSctl* pfcFSctl = new XrdPfcFSctl(instance, logger);
117 env->PutPtr("XrdFSCtl_PC*", pfcFSctl);
118
119 return &instance;
120}
121}
122
123//==============================================================================
124
126{
127 assert (m_instance == 0);
128 m_instance = new Cache(logger, env);
129 return *m_instance;
130}
131
132 Cache& Cache::GetInstance() { return *m_instance; }
133const Cache& Cache::TheOne() { return *m_instance; }
134const Configuration& Cache::Conf() { return m_instance->RefConfiguration(); }
135 ResourceMonitor& Cache::ResMon() { return m_instance->RefResMon(); }
136
138{
139 if (! m_decisionpoints.empty())
140 {
141 XrdCl::URL url(io->Path());
142 std::string filename = url.GetPath();
143 std::vector<Decision*>::const_iterator it;
144 for (it = m_decisionpoints.begin(); it != m_decisionpoints.end(); ++it)
145 {
146 XrdPfc::Decision *d = *it;
147 if (! d) continue;
148 if (! d->Decide(filename, *m_oss))
149 {
150 return false;
151 }
152 }
153 }
154
155 return true;
156}
157
159 XrdOucCache("pfc"),
160 m_env(env),
161 m_log(logger, "XrdPfc_"),
162 m_trace(new XrdSysTrace("XrdPfc", logger)),
163 m_traceID("Cache"),
164 m_oss(0),
165 m_gstream(0),
166 m_purge_pin(0),
167 m_prefetch_condVar(0),
168 m_prefetch_enabled(false),
169 m_RAM_used(0),
170 m_RAM_write_queue(0),
171 m_RAM_std_size(0),
172 m_isClient(false),
173 m_active_cond(0)
174{
175 // Default log level is Warning.
176 m_trace->What = 2;
177}
178
180{
181 const char* tpfx = "Attach() ";
182
183 if (Cache::GetInstance().Decide(io))
184 {
185 TRACE(Info, tpfx << obfuscateAuth(io->Path()));
186
187 IO *cio;
188
189 if (Cache::GetInstance().RefConfiguration().m_hdfsmode)
190 {
191 cio = new IOFileBlock(io, *this);
192 }
193 else
194 {
195 IOFile *iof = new IOFile(io, *this);
196
197 if ( ! iof->HasFile())
198 {
199 delete iof;
200 // TODO - redirect instead. But this is kind of an awkward place for it.
201 // errno is set during IOFile construction.
202 TRACE(Error, tpfx << "Failed opening local file, falling back to remote access " << io->Path());
203 return io;
204 }
205
206 cio = iof;
207 }
208
209 TRACE_PC(Debug, const char* loc = io->Location(), tpfx << io->Path() << " location: " <<
210 ((loc && loc[0] != 0) ? loc : "<deferred open>"));
211
212 return cio;
213 }
214 else
215 {
216 TRACE(Info, tpfx << "decision decline " << io->Path());
217 }
218 return io;
219}
220
221void Cache::AddWriteTask(Block* b, bool fromRead)
222{
223 TRACE(Dump, "AddWriteTask() offset=" << b->m_offset << ". file " << b->get_file()->GetLocalPath());
224
225 {
226 XrdSysMutexHelper lock(&m_RAM_mutex);
227 m_RAM_write_queue += b->get_size();
228 }
229
230 m_writeQ.condVar.Lock();
231 if (fromRead)
232 m_writeQ.queue.push_back(b);
233 else
234 m_writeQ.queue.push_front(b);
235 m_writeQ.size++;
236 m_writeQ.condVar.Signal();
237 m_writeQ.condVar.UnLock();
238}
239
241{
242 std::list<Block*> removed_blocks;
243 long long sum_size = 0;
244
245 m_writeQ.condVar.Lock();
246 std::list<Block*>::iterator i = m_writeQ.queue.begin();
247 while (i != m_writeQ.queue.end())
248 {
249 if ((*i)->m_file == file)
250 {
251 TRACE(Dump, "Remove entries for " << (void*)(*i) << " path " << file->lPath());
252 std::list<Block*>::iterator j = i++;
253 removed_blocks.push_back(*j);
254 sum_size += (*j)->get_size();
255 m_writeQ.queue.erase(j);
256 --m_writeQ.size;
257 }
258 else
259 {
260 ++i;
261 }
262 }
263 m_writeQ.condVar.UnLock();
264
265 {
266 XrdSysMutexHelper lock(&m_RAM_mutex);
267 m_RAM_write_queue -= sum_size;
268 }
269
270 file->BlocksRemovedFromWriteQ(removed_blocks);
271}
272
274{
275 std::vector<Block*> blks_to_write(m_configuration.m_wqueue_blocks);
276
277 while (true)
278 {
279 m_writeQ.condVar.Lock();
280 while (m_writeQ.size == 0)
281 {
282 m_writeQ.condVar.Wait();
283 }
284
285 // MT -- optimize to pop several blocks if they are available (or swap the list).
286 // This makes sense especially for smallish block sizes.
287
288 int n_pushed = std::min(m_writeQ.size, m_configuration.m_wqueue_blocks);
289 long long sum_size = 0;
290
291 for (int bi = 0; bi < n_pushed; ++bi)
292 {
293 Block* block = m_writeQ.queue.front();
294 m_writeQ.queue.pop_front();
295 m_writeQ.writes_between_purges += block->get_size();
296 sum_size += block->get_size();
297
298 blks_to_write[bi] = block;
299
300 TRACE(Dump, "ProcessWriteTasks for block " << (void*)(block) << " path " << block->m_file->lPath());
301 }
302 m_writeQ.size -= n_pushed;
303
304 m_writeQ.condVar.UnLock();
305
306 {
307 XrdSysMutexHelper lock(&m_RAM_mutex);
308 m_RAM_write_queue -= sum_size;
309 }
310
311 for (int bi = 0; bi < n_pushed; ++bi)
312 {
313 Block* block = blks_to_write[bi];
314
315 block->m_file->WriteBlockToDisk(block);
316 }
317 }
318}
319
321{
322 // Called from ResourceMonitor for an alternative estimation of disk writes.
323 XrdSysCondVarHelper lock(&m_writeQ.condVar);
324 long long ret = m_writeQ.writes_between_purges;
325 m_writeQ.writes_between_purges = 0;
326 return ret;
327}
328
329//==============================================================================
330
331char* Cache::RequestRAM(long long size)
332{
333 static const size_t s_block_align = sysconf(_SC_PAGESIZE);
334
335 bool std_size = (size == m_configuration.m_bufferSize);
336
337 m_RAM_mutex.Lock();
338
339 long long total = m_RAM_used + size;
340
341 if (total <= m_configuration.m_RamAbsAvailable)
342 {
343 m_RAM_used = total;
344 if (std_size && m_RAM_std_size > 0)
345 {
346 char *buf = m_RAM_std_blocks.back();
347 m_RAM_std_blocks.pop_back();
348 --m_RAM_std_size;
349
350 m_RAM_mutex.UnLock();
351
352 return buf;
353 }
354 else
355 {
356 m_RAM_mutex.UnLock();
357 char *buf;
358 if (posix_memalign((void**) &buf, s_block_align, (size_t) size))
359 {
360 // Report out of mem? Probably should report it at least the first time,
361 // then periodically.
362 return 0;
363 }
364 return buf;
365 }
366 }
367 m_RAM_mutex.UnLock();
368 return 0;
369}
370
371void Cache::ReleaseRAM(char* buf, long long size)
372{
373 bool std_size = (size == m_configuration.m_bufferSize);
374 {
375 XrdSysMutexHelper lock(&m_RAM_mutex);
376
377 m_RAM_used -= size;
378
379 if (std_size && m_RAM_std_size < m_configuration.m_RamKeepStdBlocks)
380 {
381 m_RAM_std_blocks.push_back(buf);
382 ++m_RAM_std_size;
383 return;
384 }
385 }
386 free(buf);
387}
388
389File* Cache::GetFile(const std::string& path, IO* io, long long off, long long filesize)
390{
391 // Called from virtual IOFile constructor.
392
393 TRACE(Debug, "GetFile " << path << ", io " << io);
394
395 ActiveMap_i it;
396
397 {
398 XrdSysCondVarHelper lock(&m_active_cond);
399
400 while (true)
401 {
402 it = m_active.find(path);
403
404 // File is not open or being opened. Mark it as being opened and
405 // proceed to opening it outside of while loop.
406 if (it == m_active.end())
407 {
408 it = m_active.insert(std::make_pair(path, (File*) 0)).first;
409 break;
410 }
411
412 if (it->second != 0)
413 {
414 it->second->AddIO(io);
415 inc_ref_cnt(it->second, false, true);
416
417 return it->second;
418 }
419 else
420 {
421 // Wait for some change in m_active, then recheck.
422 m_active_cond.Wait();
423 }
424 }
425 }
426
427 // This is always true, now that IOFileBlock is unsupported.
428 if (filesize == 0)
429 {
430 struct stat st;
431 int res = io->Fstat(st);
432 if (res < 0) {
433 errno = res;
434 TRACE(Error, "GetFile, could not get valid stat");
435 } else if (res > 0) {
436 errno = ENOTSUP;
437 TRACE(Error, "GetFile, stat returned positive value, this should NOT happen here");
438 } else {
439 filesize = st.st_size;
440 }
441 }
442
443 File *file = 0;
444
445 if (filesize >= 0)
446 {
447 file = File::FileOpen(path, off, filesize);
448 }
449
450 {
451 XrdSysCondVarHelper lock(&m_active_cond);
452
453 if (file)
454 {
455 inc_ref_cnt(file, false, true);
456 it->second = file;
457
458 file->AddIO(io);
459 }
460 else
461 {
462 m_active.erase(it);
463 }
464
465 m_active_cond.Broadcast();
466 }
467
468 return file;
469}
470
472{
473 // Called from virtual IO::DetachFinalize.
474
475 TRACE(Debug, "ReleaseFile " << f->GetLocalPath() << ", io " << io);
476
477 {
478 XrdSysCondVarHelper lock(&m_active_cond);
479
480 f->RemoveIO(io);
481 }
482 dec_ref_cnt(f, true);
483}
484
485
486namespace
487{
488
489class DiskSyncer : public XrdJob
490{
491private:
492 File *m_file;
493 bool m_high_debug;
494
495public:
496 DiskSyncer(File *f, bool high_debug, const char *desc = "") :
497 XrdJob(desc),
498 m_file(f),
499 m_high_debug(high_debug)
500 {}
501
502 void DoIt()
503 {
504 m_file->Sync();
505 Cache::GetInstance().FileSyncDone(m_file, m_high_debug);
506 delete this;
507 }
508};
509
510
511class CommandExecutor : public XrdJob
512{
513private:
514 std::string m_command_url;
515
516public:
517 CommandExecutor(const std::string& command, const char *desc = "") :
518 XrdJob(desc),
519 m_command_url(command)
520 {}
521
522 void DoIt()
523 {
524 Cache::GetInstance().ExecuteCommandUrl(m_command_url);
525 delete this;
526 }
527};
528
529}
530
531//==============================================================================
532
533void Cache::schedule_file_sync(File* f, bool ref_cnt_already_set, bool high_debug)
534{
535 DiskSyncer* ds = new DiskSyncer(f, high_debug);
536
537 if ( ! ref_cnt_already_set) inc_ref_cnt(f, true, high_debug);
538
539 schedP->Schedule(ds);
540}
541
542void Cache::FileSyncDone(File* f, bool high_debug)
543{
544 dec_ref_cnt(f, high_debug);
545}
546
547void Cache::inc_ref_cnt(File* f, bool lock, bool high_debug)
548{
549 // called from GetFile() or SheduleFileSync();
550
551 int tlvl = high_debug ? TRACE_Debug : TRACE_Dump;
552
553 if (lock) m_active_cond.Lock();
554 int rc = f->inc_ref_cnt();
555 if (lock) m_active_cond.UnLock();
556
557 TRACE_INT(tlvl, "inc_ref_cnt " << f->GetLocalPath() << ", cnt at exit = " << rc);
558}
559
560void Cache::dec_ref_cnt(File* f, bool high_debug)
561{
562 // NOT under active lock.
563 // Called from ReleaseFile(), DiskSync callback and stat-like functions.
564
565 int tlvl = high_debug ? TRACE_Debug : TRACE_Dump;
566 int cnt;
567
568 bool emergency_close = false;
569 {
570 XrdSysCondVarHelper lock(&m_active_cond);
571
572 cnt = f->get_ref_cnt();
573 TRACE_INT(tlvl, "dec_ref_cnt " << f->GetLocalPath() << ", cnt at entry = " << cnt);
574
576 {
577 // In this case file has been already removed from m_active map and
578 // does not need to be synced.
579
580 if (cnt == 1)
581 {
582 TRACE_INT(tlvl, "dec_ref_cnt " << f->GetLocalPath() << " is in shutdown, ref_cnt = " << cnt
583 << " -- closing and deleting File object without further ado");
584 emergency_close = true;
585 }
586 else
587 {
588 TRACE_INT(tlvl, "dec_ref_cnt " << f->GetLocalPath() << " is in shutdown, ref_cnt = " << cnt
589 << " -- waiting");
590 f->dec_ref_cnt();
591 return;
592 }
593 }
594 if (cnt > 1)
595 {
596 f->dec_ref_cnt();
597 return;
598 }
599 }
600 if (emergency_close)
601 {
602 f->Close();
603 delete f;
604 return;
605 }
606
607 if (cnt == 1)
608 {
609 if (f->FinalizeSyncBeforeExit())
610 {
611 // Note, here we "reuse" the existing reference count for the
612 // final sync.
613
614 TRACE(Debug, "dec_ref_cnt " << f->GetLocalPath() << ", scheduling final sync");
615 schedule_file_sync(f, true, true);
616 return;
617 }
618 }
619
620 bool finished_p = false;
621 ActiveMap_i act_it;
622 {
623 XrdSysCondVarHelper lock(&m_active_cond);
624
625 cnt = f->dec_ref_cnt();
626 TRACE_INT(tlvl, "dec_ref_cnt " << f->GetLocalPath() << ", cnt after sync_check and dec_ref_cnt = " << cnt);
627 if (cnt == 0)
628 {
629 act_it = m_active.find(f->GetLocalPath());
630 act_it->second = 0;
631
632 finished_p = true;
633 }
634 }
635 if (finished_p)
636 {
637 f->Close();
638 {
639 XrdSysCondVarHelper lock(&m_active_cond);
640 m_active.erase(act_it);
641 }
642
643 if (m_gstream)
644 {
645 const Stats &st = f->RefStats();
646 const Info::AStat *as = f->GetLastAccessStats();
647
648 char buf[4096];
649 int len = snprintf(buf, 4096, "{\"event\":\"file_close\","
650 "\"lfn\":\"%s\",\"size\":%lld,\"blk_size\":%d,\"n_blks\":%d,\"n_blks_done\":%d,"
651 "\"access_cnt\":%lu,\"attach_t\":%lld,\"detach_t\":%lld,\"remotes\":%s,"
652 "\"b_hit\":%lld,\"b_miss\":%lld,\"b_bypass\":%lld,"
653 "\"b_todisk\":%lld,\"b_prefetch\":%lld,\"n_cks_errs\":%d}",
654 f->GetLocalPath().c_str(), f->GetFileSize(), f->GetBlockSize(),
656 (unsigned long) f->GetAccessCnt(), (long long) as->AttachTime, (long long) as->DetachTime,
657 f->GetRemoteLocations().c_str(),
658 as->BytesHit, as->BytesMissed, as->BytesBypassed,
660 );
661 bool suc = false;
662 if (len < 4096)
663 {
664 suc = m_gstream->Insert(buf, len + 1);
665 }
666 if ( ! suc)
667 {
668 TRACE(Error, "Failed g-stream insertion of file_close record, len=" << len);
669 }
670 }
671
672 delete f;
673 }
674}
675
676bool Cache::IsFileActiveOrPurgeProtected(const std::string& path) const
677{
678 XrdSysCondVarHelper lock(&m_active_cond);
679
680 return m_active.find(path) != m_active.end() ||
681 m_purge_delay_set.find(path) != m_purge_delay_set.end();
682}
683
685{
686 XrdSysCondVarHelper lock(&m_active_cond);
687 m_purge_delay_set.clear();
688}
689
690//==============================================================================
691//=== PREFETCH
692//==============================================================================
693
695{
696 // Can be called with other locks held.
697
698 if ( ! m_prefetch_enabled)
699 {
700 return;
701 }
702
703 m_prefetch_condVar.Lock();
704 m_prefetchList.push_back(file);
705 m_prefetch_condVar.Signal();
706 m_prefetch_condVar.UnLock();
707}
708
709
711{
712 // Can be called with other locks held.
713
714 if ( ! m_prefetch_enabled)
715 {
716 return;
717 }
718
719 m_prefetch_condVar.Lock();
720 for (PrefetchList::iterator it = m_prefetchList.begin(); it != m_prefetchList.end(); ++it)
721 {
722 if (*it == file)
723 {
724 m_prefetchList.erase(it);
725 break;
726 }
727 }
728 m_prefetch_condVar.UnLock();
729}
730
731
733{
734 m_prefetch_condVar.Lock();
735 while (m_prefetchList.empty())
736 {
737 m_prefetch_condVar.Wait();
738 }
739
740 // std::sort(m_prefetchList.begin(), m_prefetchList.end(), myobject);
741
742 size_t l = m_prefetchList.size();
743 int idx = rand() % l;
744 File* f = m_prefetchList[idx];
745
746 m_prefetch_condVar.UnLock();
747 return f;
748}
749
750
752{
753 const long long limit_RAM = m_configuration.m_RamAbsAvailable * 7 / 10;
754
755 while (true)
756 {
757 m_RAM_mutex.Lock();
758 bool doPrefetch = (m_RAM_used < limit_RAM);
759 m_RAM_mutex.UnLock();
760
761 if (doPrefetch)
762 {
764 f->Prefetch();
765 }
766 else
767 {
769 }
770 }
771}
772
773
774//==============================================================================
775//=== Virtuals from XrdOucCache
776//==============================================================================
777
778//------------------------------------------------------------------------------
792
793int Cache::LocalFilePath(const char *curl, char *buff, int blen,
794 LFP_Reason why, bool forall)
795{
796 static const mode_t groupReadable = S_IRUSR | S_IWUSR | S_IRGRP;
797 static const mode_t worldReadable = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
798 static const char *lfpReason[] = { "ForAccess", "ForInfo", "ForPath" };
799
800 TRACE(Debug, "LocalFilePath '" << curl << "', why=" << lfpReason[why]);
801
802 if (buff && blen > 0) buff[0] = 0;
803
804 XrdCl::URL url(curl);
805 std::string f_name = url.GetPath();
806 std::string i_name = f_name + Info::s_infoExtension;
807
808 if (why == ForPath)
809 {
810 int ret = m_oss->Lfn2Pfn(f_name.c_str(), buff, blen);
811 TRACE(Info, "LocalFilePath '" << curl << "', why=" << lfpReason[why] << " -> " << ret);
812 return ret;
813 }
814
815 {
816 XrdSysCondVarHelper lock(&m_active_cond);
817 m_purge_delay_set.insert(f_name);
818 }
819
820 struct stat sbuff, sbuff2;
821 if (m_oss->Stat(f_name.c_str(), &sbuff) == XrdOssOK &&
822 m_oss->Stat(i_name.c_str(), &sbuff2) == XrdOssOK)
823 {
824 if (S_ISDIR(sbuff.st_mode))
825 {
826 TRACE(Info, "LocalFilePath '" << curl << "', why=" << lfpReason[why] << " -> EISDIR");
827 return -EISDIR;
828 }
829 else
830 {
831 bool read_ok = false;
832 bool is_complete = false;
833
834 // Lock and check if the file is active. If NOT, keep the lock
835 // and add dummy access after successful reading of info file.
836 // If it IS active, just release the lock, this ongoing access will
837 // assure the file continues to exist.
838
839 // XXXX How can I just loop over the cinfo file when active?
840 // Can I not get is_complete from the existing file?
841 // Do I still want to inject access record?
842 // Oh, it writes only if not active .... still let's try to use existing File.
843
844 m_active_cond.Lock();
845
846 bool is_active = m_active.find(f_name) != m_active.end();
847
848 if (is_active) m_active_cond.UnLock();
849
850 XrdOssDF* infoFile = m_oss->newFile(m_configuration.m_username.c_str());
851 XrdOucEnv myEnv;
852 int res = infoFile->Open(i_name.c_str(), O_RDWR, 0600, myEnv);
853 if (res >= 0)
854 {
855 Info info(m_trace, 0);
856 if (info.Read(infoFile, i_name.c_str()))
857 {
858 read_ok = true;
859
860 is_complete = info.IsComplete();
861
862 // Add full-size access if reason is for access.
863 if ( ! is_active && is_complete && why == ForAccess)
864 {
865 info.WriteIOStatSingle(info.GetFileSize());
866 info.Write(infoFile, i_name.c_str());
867 }
868 }
869 infoFile->Close();
870 }
871 delete infoFile;
872
873 if ( ! is_active) m_active_cond.UnLock();
874
875 if (read_ok)
876 {
877 if ((is_complete || why == ForInfo) && buff != 0)
878 {
879 int res2 = m_oss->Lfn2Pfn(f_name.c_str(), buff, blen);
880 if (res2 < 0)
881 return res2;
882
883 // Normally, files are owned by us but when direct cache access
884 // is wanted and possible, make sure the file is world readable.
885 if (why == ForAccess)
886 {mode_t mode = (forall ? worldReadable : groupReadable);
887 if (((sbuff.st_mode & worldReadable) != mode)
888 && (m_oss->Chmod(f_name.c_str(), mode) != XrdOssOK))
889 {is_complete = false;
890 *buff = 0;
891 }
892 }
893 }
894
895 TRACE(Info, "LocalFilePath '" << curl << "', why=" << lfpReason[why] <<
896 (is_complete ? " -> FILE_COMPLETE_IN_CACHE" : " -> EREMOTE"));
897
898 return is_complete ? 0 : -EREMOTE;
899 }
900 }
901 }
902
903 TRACE(Info, "LocalFilePath '" << curl << "', why=" << lfpReason[why] << " -> ENOENT");
904 return -ENOENT;
905}
906
907//______________________________________________________________________________
908// If supported, write file_size as xattr to cinfo file.
909//------------------------------------------------------------------------------
910void Cache::WriteFileSizeXAttr(int cinfo_fd, long long file_size)
911{
912 if (m_metaXattr) {
913 int res = XrdSysXAttrActive->Set("pfc.fsize", &file_size, sizeof(long long), 0, cinfo_fd, 0);
914 if (res != 0) {
915 TRACE(Debug, "WriteFileSizeXAttr error setting xattr " << res);
916 }
917 }
918}
919
920//______________________________________________________________________________
921// Determine full size of the data file from the corresponding cinfo-file name.
922// Attempts to read xattr first and falls back to reading of the cinfo file.
923// Returns -error on failure.
924//------------------------------------------------------------------------------
925long long Cache::DetermineFullFileSize(const std::string &cinfo_fname)
926{
927 if (m_metaXattr) {
928 char pfn[4096];
929 m_oss->Lfn2Pfn(cinfo_fname.c_str(), pfn, 4096);
930 long long fsize = -1ll;
931 int res = XrdSysXAttrActive->Get("pfc.fsize", &fsize, sizeof(long long), pfn);
932 if (res == sizeof(long long))
933 {
934 return fsize;
935 }
936 else
937 {
938 TRACE(Debug, "DetermineFullFileSize error getting xattr " << res);
939 }
940 }
941
942 XrdOssDF *infoFile = m_oss->newFile(m_configuration.m_username.c_str());
943 XrdOucEnv env;
944 long long ret;
945 int res = infoFile->Open(cinfo_fname.c_str(), O_RDONLY, 0600, env);
946 if (res < 0) {
947 ret = res;
948 } else {
949 Info info(m_trace, 0);
950 if ( ! info.Read(infoFile, cinfo_fname.c_str())) {
951 ret = -EBADF;
952 } else {
953 ret = info.GetFileSize();
954 }
955 infoFile->Close();
956 }
957 delete infoFile;
958 return ret;
959}
960
961//______________________________________________________________________________
962// Calculate if the file is to be considered cached for the purposes of
963// only-if-cached and setting of atime of the Stat() calls.
964// Returns true if the file is to be conidered cached.
965//------------------------------------------------------------------------------
966bool Cache::DecideIfConsideredCached(long long file_size, long long bytes_on_disk)
967{
968 if (file_size == 0 || bytes_on_disk >= file_size)
969 return true;
970
971 double frac_on_disk = (double) bytes_on_disk / file_size;
972
973 if (file_size <= m_configuration.m_onlyIfCachedMinSize)
974 {
975 if (frac_on_disk >= m_configuration.m_onlyIfCachedMinFrac)
976 return true;
977 }
978 else
979 {
980 if (bytes_on_disk >= m_configuration.m_onlyIfCachedMinSize &&
981 frac_on_disk >= m_configuration.m_onlyIfCachedMinFrac)
982 return true;
983 }
984 return false;
985}
986
987//______________________________________________________________________________
988// Check if the file is cached including m_onlyIfCachedMinSize and m_onlyIfCachedMinFrac
989// pfc configuration parameters. The logic of accessing the Info file is the same
990// as in Cache::LocalFilePath.
998//------------------------------------------------------------------------------
999int Cache::ConsiderCached(const char *curl)
1000{
1001 static const char* tpfx = "ConsiderCached ";
1002
1003 TRACE(Debug, tpfx << curl);
1004
1005 XrdCl::URL url(curl);
1006 std::string f_name = url.GetPath();
1007
1008 File *file = nullptr;
1009 {
1010 XrdSysCondVarHelper lock(&m_active_cond);
1011 auto it = m_active.find(f_name);
1012 if (it != m_active.end()) {
1013 file = it->second;
1014 // If the file-open is in progress, `file` is a nullptr
1015 // so we cannot increase the reference count. For now,
1016 // simply treat it as if the file open doesn't exist instead
1017 // of trying to wait and see if it succeeds.
1018 if (file) {
1019 inc_ref_cnt(file, false, false);
1020 }
1021 }
1022 }
1023 if (file) {
1024 struct stat sbuff;
1025 int res = file->Fstat(sbuff);
1026 dec_ref_cnt(file, false);
1027 if (res)
1028 return res;
1029 // DecideIfConsideredCached() already called in File::Fstat().
1030 return sbuff.st_atime > 0 ? 0 : -EREMOTE;
1031 }
1032
1033 struct stat sbuff;
1034 int res = m_oss->Stat(f_name.c_str(), &sbuff);
1035 if (res != XrdOssOK) {
1036 TRACE(Debug, tpfx << curl << " -> " << res);
1037 return res;
1038 }
1039 if (S_ISDIR(sbuff.st_mode))
1040 {
1041 TRACE(Debug, tpfx << curl << " -> EISDIR");
1042 return -EISDIR;
1043 }
1044
1045 long long file_size = DetermineFullFileSize(f_name + Info::s_infoExtension);
1046 if (file_size < 0) {
1047 TRACE(Debug, tpfx << curl << " -> " << file_size);
1048 return (int) file_size;
1049 }
1050 bool is_cached = DecideIfConsideredCached(file_size, sbuff.st_blocks * 512ll);
1051
1052 return is_cached ? 0 : -EREMOTE;
1053}
1054
1055//______________________________________________________________________________
1063//------------------------------------------------------------------------------
1064
1065int Cache::Prepare(const char *curl, int oflags, mode_t mode)
1066{
1067 XrdCl::URL url(curl);
1068 std::string f_name = url.GetPath();
1069 std::string i_name = f_name + Info::s_infoExtension;
1070
1071 // Do not allow write access.
1072 if ((oflags & O_ACCMODE) != O_RDONLY)
1073 {
1074 TRACE(Warning, "Prepare write access requested on file " << f_name << ". Denying access.");
1075 return -EROFS;
1076 }
1077
1078 // Intercept xrdpfc_command requests.
1079 if (m_configuration.m_allow_xrdpfc_command && strncmp("/xrdpfc_command/", f_name.c_str(), 16) == 0)
1080 {
1081 // Schedule a job to process command request.
1082 {
1083 CommandExecutor *ce = new CommandExecutor(f_name, "CommandExecutor");
1084
1085 schedP->Schedule(ce);
1086 }
1087
1088 return -EAGAIN;
1089 }
1090
1091 {
1092 XrdSysCondVarHelper lock(&m_active_cond);
1093 m_purge_delay_set.insert(f_name);
1094 }
1095
1096 struct stat sbuff;
1097 if (m_oss->Stat(i_name.c_str(), &sbuff) == XrdOssOK)
1098 {
1099 TRACE(Dump, "Prepare defer open " << f_name);
1100 return 1;
1101 }
1102 else
1103 {
1104 return 0;
1105 }
1106}
1107
1108//______________________________________________________________________________
1109// virtual method of XrdOucCache.
1114//------------------------------------------------------------------------------
1115
1116int Cache::Stat(const char *curl, struct stat &sbuff)
1117{
1118 const char *tpfx = "Stat ";
1119
1120 XrdCl::URL url(curl);
1121 std::string f_name = url.GetPath();
1122
1123 File *file = nullptr;
1124 {
1125 XrdSysCondVarHelper lock(&m_active_cond);
1126 auto it = m_active.find(f_name);
1127 if (it != m_active.end()) {
1128 file = it->second;
1129 // If `file` is nullptr, the file-open is in progress; instead
1130 // of waiting for the file-open to finish, simply treat it as if
1131 // the file-open doesn't exist.
1132 if (file) {
1133 inc_ref_cnt(file, false, false);
1134 }
1135 }
1136 }
1137 if (file) {
1138 int res = file->Fstat(sbuff);
1139 dec_ref_cnt(file, false);
1140 TRACE(Debug, tpfx << "from active file " << curl << " -> " << res);
1141 return res;
1142 }
1143
1144 int res = m_oss->Stat(f_name.c_str(), &sbuff);
1145 if (res != XrdOssOK) {
1146 TRACE(Debug, tpfx << curl << " -> " << res);
1147 return 1; // res; -- for only-if-cached
1148 }
1149 if (S_ISDIR(sbuff.st_mode))
1150 {
1151 TRACE(Debug, tpfx << curl << " -> EISDIR");
1152 return -EISDIR;
1153 }
1154
1155 long long file_size = DetermineFullFileSize(f_name + Info::s_infoExtension);
1156 if (file_size < 0) {
1157 TRACE(Debug, tpfx << curl << " -> " << file_size);
1158 return 1; // (int) file_size; -- for only-if-cached
1159 }
1160 sbuff.st_size = file_size;
1161 bool is_cached = DecideIfConsideredCached(file_size, sbuff.st_blocks * 512ll);
1162 if ( ! is_cached)
1163 sbuff.st_atime = 0;
1164
1165 TRACE(Debug, tpfx << "from disk " << curl << " -> " << res);
1166
1167 return 0;
1168}
1169
1170//______________________________________________________________________________
1171// virtual method of XrdOucCache.
1175//------------------------------------------------------------------------------
1176
1177int Cache::Unlink(const char *curl)
1178{
1179 XrdCl::URL url(curl);
1180 std::string f_name = url.GetPath();
1181
1182 // printf("Unlink url=%s\n\t fname=%s\n", curl, f_name.c_str());
1183
1184 return UnlinkFile(f_name, false);
1185}
1186
1187int Cache::UnlinkFile(const std::string& f_name, bool fail_if_open)
1188{
1189 static const char* trc_pfx = "UnlinkFile ";
1190 ActiveMap_i it;
1191 File *file = 0;
1192 long long st_blocks_to_purge = 0;
1193 {
1194 XrdSysCondVarHelper lock(&m_active_cond);
1195
1196 it = m_active.find(f_name);
1197
1198 if (it != m_active.end())
1199 {
1200 if (fail_if_open)
1201 {
1202 TRACE(Info, trc_pfx << f_name << ", file currently open and force not requested - denying request");
1203 return -EBUSY;
1204 }
1205
1206 // Null File* in m_active map means an operation is ongoing, probably
1207 // Attach() with possible File::Open(). Ask for retry.
1208 if (it->second == 0)
1209 {
1210 TRACE(Info, trc_pfx << f_name << ", an operation on this file is ongoing - denying request");
1211 return -EAGAIN;
1212 }
1213
1214 file = it->second;
1215 st_blocks_to_purge = file->initiate_emergency_shutdown();
1216 it->second = 0;
1217 }
1218 else
1219 {
1220 it = m_active.insert(std::make_pair(f_name, (File*) 0)).first;
1221 }
1222 }
1223
1224 if (file) {
1226 } else {
1227 struct stat f_stat;
1228 if (m_oss->Stat(f_name.c_str(), &f_stat) == XrdOssOK)
1229 st_blocks_to_purge = f_stat.st_blocks;
1230 }
1231
1232 std::string i_name = f_name + Info::s_infoExtension;
1233
1234 // Unlink file & cinfo
1235 int f_ret = m_oss->Unlink(f_name.c_str());
1236 int i_ret = m_oss->Unlink(i_name.c_str());
1237
1238 if (st_blocks_to_purge)
1239 m_res_mon->register_file_purge(f_name, st_blocks_to_purge);
1240
1241 TRACE(Debug, trc_pfx << f_name << ", f_ret=" << f_ret << ", i_ret=" << i_ret);
1242
1243 {
1244 XrdSysCondVarHelper lock(&m_active_cond);
1245
1246 m_active.erase(it);
1247 }
1248
1249 return std::min(f_ret, i_ret);
1250}
int DoIt(int argpnt, int argc, char **argv, bool singleshot)
#define TRACE_Debug
#define XrdOssOK
Definition XrdOss.hh:50
std::string obfuscateAuth(const std::string &input)
#define TRACE_Dump
#define TRACE_PC(act, pre_code, x)
#define TRACE_INT(act, x)
void * ProcessWriteTaskThread(void *)
Definition XrdPfc.cc:60
XrdSysXAttr * XrdSysXAttrActive
void * ResourceMonitorThread(void *)
Definition XrdPfc.cc:54
void * PrefetchThread(void *)
Definition XrdPfc.cc:66
XrdOucCache * XrdOucGetCache(XrdSysLogger *logger, const char *config_filename, const char *parameters, XrdOucEnv *env)
Definition XrdPfc.cc:76
#define stat(a, b)
Definition XrdPosix.hh:101
bool Debug
#define TRACE(act, x)
Definition XrdTrace.hh:63
URL representation.
Definition XrdClURL.hh:31
const std::string & GetPath() const
Get the path.
Definition XrdClURL.hh:217
virtual int Close(long long *retsz=0)=0
virtual int Open(const char *path, int Oflag, mode_t Mode, XrdOucEnv &env)
Definition XrdOss.hh:200
virtual int Fstat(struct stat &sbuff)
virtual const char * Path()=0
virtual const char * Location(bool refresh=false)
XrdOucCache(const char *ctype)
void * GetPtr(const char *varname)
Definition XrdOucEnv.cc:263
void PutPtr(const char *varname, void *value)
Definition XrdOucEnv.cc:298
int get_size() const
long long m_offset
File * get_file() const
Attaches/creates and detaches/deletes cache-io objects for disk based cache.
Definition XrdPfc.hh:152
long long DetermineFullFileSize(const std::string &cinfo_fname)
Definition XrdPfc.cc:925
void FileSyncDone(File *, bool high_debug)
Definition XrdPfc.cc:542
File * GetFile(const std::string &, IO *, long long off=0, long long filesize=0)
Definition XrdPfc.cc:389
static const Configuration & Conf()
Definition XrdPfc.cc:134
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)
Definition XrdPfc.cc:793
virtual int Stat(const char *url, struct stat &sbuff)
Definition XrdPfc.cc:1116
const Configuration & RefConfiguration() const
Reference XrdPfc configuration.
Definition XrdPfc.hh:204
static ResourceMonitor & ResMon()
Definition XrdPfc.cc:135
bool IsFileActiveOrPurgeProtected(const std::string &) const
Definition XrdPfc.cc:676
void ClearPurgeProtectedSet()
Definition XrdPfc.cc:684
void ReleaseRAM(char *buf, long long size)
Definition XrdPfc.cc:371
virtual int ConsiderCached(const char *url)
Definition XrdPfc.cc:999
static Cache & GetInstance()
Singleton access.
Definition XrdPfc.cc:132
void DeRegisterPrefetchFile(File *)
Definition XrdPfc.cc:710
void ExecuteCommandUrl(const std::string &command_url)
void RegisterPrefetchFile(File *)
Definition XrdPfc.cc:694
void WriteFileSizeXAttr(int cinfo_fd, long long file_size)
Definition XrdPfc.cc:910
void Prefetch()
Definition XrdPfc.cc:751
void ReleaseFile(File *, IO *)
Definition XrdPfc.cc:471
void AddWriteTask(Block *b, bool from_read)
Add downloaded block in write queue.
Definition XrdPfc.cc:221
Cache(XrdSysLogger *logger, XrdOucEnv *env)
Constructor.
Definition XrdPfc.cc:158
bool Decide(XrdOucCacheIO *)
Makes decision if the original XrdOucCacheIO should be cached.
Definition XrdPfc.cc:137
int UnlinkFile(const std::string &f_name, bool fail_if_open)
Remove cinfo and data files from cache.
Definition XrdPfc.cc:1187
static XrdScheduler * schedP
Definition XrdPfc.hh:290
File * GetNextFileToPrefetch()
Definition XrdPfc.cc:732
long long WritesSinceLastCall()
Definition XrdPfc.cc:320
void ProcessWriteTasks()
Separate task which writes blocks from ram to disk.
Definition XrdPfc.cc:273
virtual int Unlink(const char *url)
Definition XrdPfc.cc:1177
void RemoveWriteQEntriesFor(File *f)
Remove blocks from write queue which belong to given prefetch. This method is used at the time of Fil...
Definition XrdPfc.cc:240
virtual XrdOucCacheIO * Attach(XrdOucCacheIO *, int Options=0)
Definition XrdPfc.cc:179
static const Cache & TheOne()
Definition XrdPfc.cc:133
char * RequestRAM(long long size)
Definition XrdPfc.cc:331
virtual int Prepare(const char *url, int oflags, mode_t mode)
Definition XrdPfc.cc:1065
bool DecideIfConsideredCached(long long file_size, long long bytes_on_disk)
Definition XrdPfc.cc:966
static Cache & CreateInstance(XrdSysLogger *logger, XrdOucEnv *env)
Singleton creation.
Definition XrdPfc.cc:125
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.
int GetNBlocks() const
std::string GetRemoteLocations() const
size_t GetAccessCnt() const
int Fstat(struct stat &sbuff)
void AddIO(IO *io)
long long GetPrefetchedBytes() const
int GetBlockSize() 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.
int inc_ref_cnt()
const Stats & RefStats() const
void Sync()
Sync file cache inf o and output data with disk.
int dec_ref_cnt()
int get_ref_cnt()
long long initiate_emergency_shutdown()
long long GetFileSize() const
const std::string & GetLocalPath() const
void RemoveIO(IO *io)
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.
Definition XrdPfcIO.hh:16
Status of cached file. Can be read from and written into a binary file.
Definition XrdPfcInfo.hh:41
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.
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)
XrdPosixStats Stats
Contains parameters configurable from the xrootd config file.
Definition XrdPfc.hh:64
int m_prefetch_max_blocks
maximum number of blocks to prefetch per file
Definition XrdPfc.hh:113
long long BytesHit
read from cache
Definition XrdPfcInfo.hh:64
long long BytesBypassed
read from remote and dropped
Definition XrdPfcInfo.hh:66
time_t DetachTime
close time
Definition XrdPfcInfo.hh:59
long long BytesMissed
read from remote and cached
Definition XrdPfcInfo.hh:65
time_t AttachTime
open time
Definition XrdPfcInfo.hh:58