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, env))
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.is_prefetch_enabled())
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, io->GetInput());
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 m_active_cond.Broadcast();
642 }
643
644 if (m_gstream)
645 {
646 const Stats &st = f->RefStats();
647 const Info::AStat *as = f->GetLastAccessStats();
648
649 char buf[4096];
650 int len = snprintf(buf, 4096, "{\"event\":\"file_close\","
651 "\"lfn\":\"%s\",\"size\":%lld,\"blk_size\":%d,\"n_blks\":%d,\"n_blks_done\":%d,"
652 "\"access_cnt\":%lu,\"attach_t\":%lld,\"detach_t\":%lld,\"remotes\":%s,"
653 "\"b_hit\":%lld,\"b_miss\":%lld,\"b_bypass\":%lld,"
654 "\"b_todisk\":%lld,\"b_prefetch\":%lld,\"n_cks_errs\":%d}",
655 f->GetLocalPath().c_str(), f->GetFileSize(), f->GetBlockSize(),
657 (unsigned long) f->GetAccessCnt(), (long long) as->AttachTime, (long long) as->DetachTime,
658 f->GetRemoteLocations().c_str(),
659 as->BytesHit, as->BytesMissed, as->BytesBypassed,
661 );
662 bool suc = false;
663 if (len < 4096)
664 {
665 suc = m_gstream->Insert(buf, len + 1);
666 }
667 if ( ! suc)
668 {
669 TRACE(Error, "Failed g-stream insertion of file_close record, len=" << len);
670 }
671 }
672
673 delete f;
674 }
675}
676
677bool Cache::IsFileActiveOrPurgeProtected(const std::string& path) const
678{
679 XrdSysCondVarHelper lock(&m_active_cond);
680
681 return m_active.find(path) != m_active.end() ||
682 m_purge_delay_set.find(path) != m_purge_delay_set.end();
683}
684
686{
687 XrdSysCondVarHelper lock(&m_active_cond);
688 m_purge_delay_set.clear();
689}
690
691//==============================================================================
692//=== PREFETCH
693//==============================================================================
694
696{
697 // Can be called with other locks held.
698
699 if ( ! m_prefetch_enabled)
700 {
701 return;
702 }
703
704 m_prefetch_condVar.Lock();
705 m_prefetchList.push_back(file);
706 m_prefetch_condVar.Signal();
707 m_prefetch_condVar.UnLock();
708}
709
710
712{
713 // Can be called with other locks held.
714
715 if ( ! m_prefetch_enabled)
716 {
717 return;
718 }
719
720 m_prefetch_condVar.Lock();
721 for (PrefetchList::iterator it = m_prefetchList.begin(); it != m_prefetchList.end(); ++it)
722 {
723 if (*it == file)
724 {
725 m_prefetchList.erase(it);
726 break;
727 }
728 }
729 m_prefetch_condVar.UnLock();
730}
731
732
734{
735 m_prefetch_condVar.Lock();
736 while (m_prefetchList.empty())
737 {
738 m_prefetch_condVar.Wait();
739 }
740
741 // std::sort(m_prefetchList.begin(), m_prefetchList.end(), myobject);
742
743 size_t l = m_prefetchList.size();
744 int idx = rand() % l;
745 File* f = m_prefetchList[idx];
746
747 m_prefetch_condVar.UnLock();
748 return f;
749}
750
751
753{
754 const long long limit_RAM = m_configuration.m_RamAbsAvailable * 7 / 10;
755
756 while (true)
757 {
758 m_RAM_mutex.Lock();
759 bool doPrefetch = (m_RAM_used < limit_RAM);
760 m_RAM_mutex.UnLock();
761
762 if (doPrefetch)
763 {
765 f->Prefetch();
766 }
767 else
768 {
770 }
771 }
772}
773
774
775//==============================================================================
776//=== Virtuals from XrdOucCache
777//==============================================================================
778
779//------------------------------------------------------------------------------
793
794int Cache::LocalFilePath(const char *curl, char *buff, int blen,
795 LFP_Reason why, bool forall)
796{
797 static const mode_t groupReadable = S_IRUSR | S_IWUSR | S_IRGRP;
798 static const mode_t worldReadable = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
799 static const char *lfpReason[] = { "ForAccess", "ForInfo", "ForPath" };
800
801 TRACE(Debug, "LocalFilePath '" << curl << "', why=" << lfpReason[why]);
802
803 if (buff && blen > 0) buff[0] = 0;
804
805 XrdCl::URL url(curl);
806 std::string f_name = url.GetPath();
807 std::string i_name = f_name + Info::s_infoExtension;
808
809 if (why == ForPath)
810 {
811 int ret = m_oss->Lfn2Pfn(f_name.c_str(), buff, blen);
812 TRACE(Info, "LocalFilePath '" << curl << "', why=" << lfpReason[why] << " -> " << ret);
813 return ret;
814 }
815
816 {
817 XrdSysCondVarHelper lock(&m_active_cond);
818 m_purge_delay_set.insert(f_name);
819 }
820
821 struct stat sbuff, sbuff2;
822 if (m_oss->Stat(f_name.c_str(), &sbuff) == XrdOssOK &&
823 m_oss->Stat(i_name.c_str(), &sbuff2) == XrdOssOK)
824 {
825 if (S_ISDIR(sbuff.st_mode))
826 {
827 TRACE(Info, "LocalFilePath '" << curl << "', why=" << lfpReason[why] << " -> EISDIR");
828 return -EISDIR;
829 }
830 else
831 {
832 bool read_ok = false;
833 bool is_complete = false;
834
835 // Lock and check if the file is active. If NOT, keep the lock
836 // and add dummy access after successful reading of info file.
837 // If it IS active, just release the lock, this ongoing access will
838 // assure the file continues to exist.
839
840 // XXXX How can I just loop over the cinfo file when active?
841 // Can I not get is_complete from the existing file?
842 // Do I still want to inject access record?
843 // Oh, it writes only if not active .... still let's try to use existing File.
844
845 m_active_cond.Lock();
846
847 bool is_active = m_active.find(f_name) != m_active.end();
848
849 if (is_active) m_active_cond.UnLock();
850
851 XrdOssDF* infoFile = m_oss->newFile(m_configuration.m_username.c_str());
852 XrdOucEnv myEnv;
853 int res = infoFile->Open(i_name.c_str(), O_RDWR, 0600, myEnv);
854 if (res >= 0)
855 {
856 Info info(m_trace, 0);
857 if (info.Read(infoFile, i_name.c_str()))
858 {
859 read_ok = true;
860
861 is_complete = info.IsComplete();
862
863 // Add full-size access if reason is for access.
864 if ( ! is_active && is_complete && why == ForAccess)
865 {
866 info.WriteIOStatSingle(info.GetFileSize());
867 info.Write(infoFile, i_name.c_str());
868 }
869 }
870 infoFile->Close();
871 }
872 delete infoFile;
873
874 if ( ! is_active) m_active_cond.UnLock();
875
876 if (read_ok)
877 {
878 if ((is_complete || why == ForInfo) && buff != 0)
879 {
880 int res2 = m_oss->Lfn2Pfn(f_name.c_str(), buff, blen);
881 if (res2 < 0)
882 return res2;
883
884 // Normally, files are owned by us but when direct cache access
885 // is wanted and possible, make sure the file is world readable.
886 if (why == ForAccess)
887 {mode_t mode = (forall ? worldReadable : groupReadable);
888 if (((sbuff.st_mode & worldReadable) != mode)
889 && (m_oss->Chmod(f_name.c_str(), mode) != XrdOssOK))
890 {is_complete = false;
891 *buff = 0;
892 }
893 }
894 }
895
896 TRACE(Info, "LocalFilePath '" << curl << "', why=" << lfpReason[why] <<
897 (is_complete ? " -> FILE_COMPLETE_IN_CACHE" : " -> EREMOTE"));
898
899 return is_complete ? 0 : -EREMOTE;
900 }
901 }
902 }
903
904 TRACE(Info, "LocalFilePath '" << curl << "', why=" << lfpReason[why] << " -> ENOENT");
905 return -ENOENT;
906}
907
908//______________________________________________________________________________
909// If supported, write file_size as xattr to cinfo file.
910//------------------------------------------------------------------------------
911void Cache::WriteFileSizeXAttr(int cinfo_fd, long long file_size)
912{
913 if (m_metaXattr) {
914 int res = XrdSysXAttrActive->Set("pfc.fsize", &file_size, sizeof(long long), 0, cinfo_fd, 0);
915 if (res != 0) {
916 TRACE(Debug, "WriteFileSizeXAttr error setting xattr " << res);
917 }
918 }
919}
920
921//______________________________________________________________________________
922// Determine full size of the data file from the corresponding cinfo-file name.
923// Attempts to read xattr first and falls back to reading of the cinfo file.
924// Returns -error on failure.
925//------------------------------------------------------------------------------
926long long Cache::DetermineFullFileSize(const std::string &cinfo_fname)
927{
928 if (m_metaXattr) {
929 char pfn[4096];
930 m_oss->Lfn2Pfn(cinfo_fname.c_str(), pfn, 4096);
931 long long fsize = -1ll;
932 int res = XrdSysXAttrActive->Get("pfc.fsize", &fsize, sizeof(long long), pfn);
933 if (res == sizeof(long long))
934 {
935 return fsize;
936 }
937 else
938 {
939 TRACE(Debug, "DetermineFullFileSize error getting xattr " << res);
940 }
941 }
942
943 XrdOssDF *infoFile = m_oss->newFile(m_configuration.m_username.c_str());
944 XrdOucEnv env;
945 long long ret;
946 int res = infoFile->Open(cinfo_fname.c_str(), O_RDONLY, 0600, env);
947 if (res < 0) {
948 ret = res;
949 } else {
950 Info info(m_trace, 0);
951 if ( ! info.Read(infoFile, cinfo_fname.c_str())) {
952 ret = -EBADF;
953 } else {
954 ret = info.GetFileSize();
955 }
956 infoFile->Close();
957 }
958 delete infoFile;
959 return ret;
960}
961
962//______________________________________________________________________________
963// Calculate if the file is to be considered cached for the purposes of
964// only-if-cached and setting of atime of the Stat() calls.
965// Returns true if the file is to be conidered cached.
966//------------------------------------------------------------------------------
967bool Cache::DecideIfConsideredCached(long long file_size, long long bytes_on_disk)
968{
969 if (file_size == 0 || bytes_on_disk >= file_size)
970 return true;
971
972 double frac_on_disk = (double) bytes_on_disk / file_size;
973
974 if (file_size <= m_configuration.m_onlyIfCachedMinSize)
975 {
976 if (frac_on_disk >= m_configuration.m_onlyIfCachedMinFrac)
977 return true;
978 }
979 else
980 {
981 if (bytes_on_disk >= m_configuration.m_onlyIfCachedMinSize &&
982 frac_on_disk >= m_configuration.m_onlyIfCachedMinFrac)
983 return true;
984 }
985 return false;
986}
987
988//______________________________________________________________________________
989// Check if the file is cached including m_onlyIfCachedMinSize and m_onlyIfCachedMinFrac
990// pfc configuration parameters. The logic of accessing the Info file is the same
991// as in Cache::LocalFilePath.
999//------------------------------------------------------------------------------
1000int Cache::ConsiderCached(const char *curl)
1001{
1002 static const char* tpfx = "ConsiderCached ";
1003
1004 TRACE(Debug, tpfx << curl);
1005
1006 XrdCl::URL url(curl);
1007 std::string f_name = url.GetPath();
1008
1009 File *file = nullptr;
1010 {
1011 XrdSysCondVarHelper lock(&m_active_cond);
1012 auto it = m_active.find(f_name);
1013 if (it != m_active.end()) {
1014 file = it->second;
1015 // If the file-open is in progress, `file` is a nullptr
1016 // so we cannot increase the reference count. For now,
1017 // simply treat it as if the file open doesn't exist instead
1018 // of trying to wait and see if it succeeds.
1019 if (file) {
1020 inc_ref_cnt(file, false, false);
1021 }
1022 }
1023 }
1024 if (file) {
1025 struct stat sbuff;
1026 int res = file->Fstat(sbuff);
1027 dec_ref_cnt(file, false);
1028 if (res)
1029 return res;
1030 // DecideIfConsideredCached() already called in File::Fstat().
1031 return sbuff.st_atime > 0 ? 0 : -EREMOTE;
1032 }
1033
1034 struct stat sbuff;
1035 int res = m_oss->Stat(f_name.c_str(), &sbuff);
1036 if (res != XrdOssOK) {
1037 TRACE(Debug, tpfx << curl << " -> " << res);
1038 return res;
1039 }
1040 if (S_ISDIR(sbuff.st_mode))
1041 {
1042 TRACE(Debug, tpfx << curl << " -> EISDIR");
1043 return -EISDIR;
1044 }
1045
1046 long long file_size = DetermineFullFileSize(f_name + Info::s_infoExtension);
1047 if (file_size < 0) {
1048 TRACE(Debug, tpfx << curl << " -> " << file_size);
1049 return (int) file_size;
1050 }
1051 bool is_cached = DecideIfConsideredCached(file_size, sbuff.st_blocks * 512ll);
1052
1053 return is_cached ? 0 : -EREMOTE;
1054}
1055
1056//______________________________________________________________________________
1064//------------------------------------------------------------------------------
1065
1066int Cache::Prepare(const char *curl, int oflags, mode_t mode)
1067{
1068 XrdCl::URL url(curl);
1069 std::string f_name = url.GetPath();
1070 std::string i_name = f_name + Info::s_infoExtension;
1071
1072 // Do not allow write access.
1073 if ((oflags & O_ACCMODE) != O_RDONLY)
1074 {
1075 TRACE(Warning, "Prepare write access requested on file " << f_name << ". Denying access.");
1076 return -EROFS;
1077 }
1078
1079 // Intercept xrdpfc_command requests.
1080 if (m_configuration.m_allow_xrdpfc_command && strncmp("/xrdpfc_command/", f_name.c_str(), 16) == 0)
1081 {
1082 // Schedule a job to process command request.
1083 {
1084 CommandExecutor *ce = new CommandExecutor(f_name, "CommandExecutor");
1085
1086 schedP->Schedule(ce);
1087 }
1088
1089 return -EAGAIN;
1090 }
1091
1092 {
1093 XrdSysCondVarHelper lock(&m_active_cond);
1094 m_purge_delay_set.insert(f_name);
1095 }
1096
1097 struct stat sbuff;
1098 if (m_oss->Stat(i_name.c_str(), &sbuff) == XrdOssOK)
1099 {
1100 TRACE(Dump, "Prepare defer open " << f_name);
1101 return 1;
1102 }
1103 else
1104 {
1105 return 0;
1106 }
1107}
1108
1109//______________________________________________________________________________
1110// virtual method of XrdOucCache.
1115//------------------------------------------------------------------------------
1116
1117int Cache::Stat(const char *curl, struct stat &sbuff)
1118{
1119 const char *tpfx = "Stat ";
1120
1121 XrdCl::URL url(curl);
1122 std::string f_name = url.GetPath();
1123
1124 File *file = nullptr;
1125 {
1126 XrdSysCondVarHelper lock(&m_active_cond);
1127 auto it = m_active.find(f_name);
1128 if (it != m_active.end()) {
1129 file = it->second;
1130 // If `file` is nullptr, the file-open is in progress; instead
1131 // of waiting for the file-open to finish, simply treat it as if
1132 // the file-open doesn't exist.
1133 if (file) {
1134 inc_ref_cnt(file, false, false);
1135 }
1136 }
1137 }
1138 if (file) {
1139 int res = file->Fstat(sbuff);
1140 dec_ref_cnt(file, false);
1141 TRACE(Debug, tpfx << "from active file " << curl << " -> " << res);
1142 return res;
1143 }
1144
1145 int res = m_oss->Stat(f_name.c_str(), &sbuff);
1146 if (res != XrdOssOK) {
1147 TRACE(Debug, tpfx << curl << " -> " << res);
1148 return 1; // res; -- for only-if-cached
1149 }
1150 if (S_ISDIR(sbuff.st_mode))
1151 {
1152 TRACE(Debug, tpfx << curl << " -> EISDIR");
1153 return -EISDIR;
1154 }
1155
1156 long long file_size = DetermineFullFileSize(f_name + Info::s_infoExtension);
1157 if (file_size < 0) {
1158 TRACE(Debug, tpfx << curl << " -> " << file_size);
1159 return 1; // (int) file_size; -- for only-if-cached
1160 }
1161 sbuff.st_size = file_size;
1162 bool is_cached = DecideIfConsideredCached(file_size, sbuff.st_blocks * 512ll);
1163 if ( ! is_cached)
1164 sbuff.st_atime = 0;
1165
1166 TRACE(Debug, tpfx << "from disk " << curl << " -> " << res);
1167
1168 return 0;
1169}
1170
1171//______________________________________________________________________________
1172// virtual method of XrdOucCache.
1176//------------------------------------------------------------------------------
1177
1178int Cache::Unlink(const char *curl)
1179{
1180 XrdCl::URL url(curl);
1181 std::string f_name = url.GetPath();
1182
1183 // printf("Unlink url=%s\n\t fname=%s\n", curl, f_name.c_str());
1184
1185 return UnlinkFile(f_name, false);
1186}
1187
1188int Cache::UnlinkFile(const std::string& f_name, bool fail_if_open)
1189{
1190 static const char* trc_pfx = "UnlinkFile ";
1191 ActiveMap_i it;
1192 File *file = 0;
1193 long long st_blocks_to_purge = 0;
1194 {
1195 XrdSysCondVarHelper lock(&m_active_cond);
1196
1197 it = m_active.find(f_name);
1198
1199 if (it != m_active.end())
1200 {
1201 if (fail_if_open)
1202 {
1203 TRACE(Info, trc_pfx << f_name << ", file currently open and force not requested - denying request");
1204 return -EBUSY;
1205 }
1206
1207 // Null File* in m_active map means an operation is ongoing, probably
1208 // Attach() with possible File::Open(). Ask for retry.
1209 if (it->second == 0)
1210 {
1211 TRACE(Info, trc_pfx << f_name << ", an operation on this file is ongoing - denying request");
1212 return -EAGAIN;
1213 }
1214
1215 file = it->second;
1216 st_blocks_to_purge = file->initiate_emergency_shutdown();
1217 it->second = 0;
1218 }
1219 else
1220 {
1221 it = m_active.insert(std::make_pair(f_name, (File*) 0)).first;
1222 }
1223 }
1224
1225 if (file) {
1227 } else {
1228 struct stat f_stat;
1229 if (m_oss->Stat(f_name.c_str(), &f_stat) == XrdOssOK)
1230 st_blocks_to_purge = f_stat.st_blocks;
1231 }
1232
1233 std::string i_name = f_name + Info::s_infoExtension;
1234
1235 // Unlink file & cinfo
1236 int f_ret = m_oss->Unlink(f_name.c_str());
1237 int i_ret = m_oss->Unlink(i_name.c_str());
1238
1239 if (st_blocks_to_purge)
1240 m_res_mon->register_file_purge(f_name, st_blocks_to_purge);
1241
1242 TRACE(Debug, trc_pfx << f_name << ", f_ret=" << f_ret << ", i_ret=" << i_ret);
1243
1244 {
1245 XrdSysCondVarHelper lock(&m_active_cond);
1246 m_active.erase(it);
1247 m_active_cond.Broadcast();
1248 }
1249
1250 return std::min(f_ret, i_ret);
1251}
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:163
long long DetermineFullFileSize(const std::string &cinfo_fname)
Definition XrdPfc.cc:926
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
virtual int LocalFilePath(const char *url, char *buff=0, int blen=0, LFP_Reason why=ForAccess, bool forall=false)
Definition XrdPfc.cc:794
virtual int Stat(const char *url, struct stat &sbuff)
Definition XrdPfc.cc:1117
const Configuration & RefConfiguration() const
Reference XrdPfc configuration.
Definition XrdPfc.hh:215
static ResourceMonitor & ResMon()
Definition XrdPfc.cc:135
bool IsFileActiveOrPurgeProtected(const std::string &) const
Definition XrdPfc.cc:677
void ClearPurgeProtectedSet()
Definition XrdPfc.cc:685
void ReleaseRAM(char *buf, long long size)
Definition XrdPfc.cc:371
virtual int ConsiderCached(const char *url)
Definition XrdPfc.cc:1000
static Cache & GetInstance()
Singleton access.
Definition XrdPfc.cc:132
bool Config(const char *config_filename, const char *parameters, XrdOucEnv *env)
Parse configuration file.
void DeRegisterPrefetchFile(File *)
Definition XrdPfc.cc:711
void ExecuteCommandUrl(const std::string &command_url)
void RegisterPrefetchFile(File *)
Definition XrdPfc.cc:695
void WriteFileSizeXAttr(int cinfo_fd, long long file_size)
Definition XrdPfc.cc:911
void Prefetch()
Definition XrdPfc.cc:752
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:1188
static XrdScheduler * schedP
Definition XrdPfc.hh:302
File * GetNextFileToPrefetch()
Definition XrdPfc.cc:733
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:1178
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:1066
bool DecideIfConsideredCached(long long file_size, long long bytes_on_disk)
Definition XrdPfc.cc:967
static Cache & CreateInstance(XrdSysLogger *logger, XrdOucEnv *env)
Singleton creation.
Definition XrdPfc.cc:125
bool is_prefetch_enabled() const
Definition XrdPfc.hh:307
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)
int GetNBlocks() const
std::string GetRemoteLocations() const
size_t GetAccessCnt() const
int Fstat(struct stat &sbuff)
void AddIO(IO *io)
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 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
XrdOucCacheIO * GetInput()
Definition XrdPfcIO.cc:31
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
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