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 (Options & XrdOucCache::optRW)
184 {
185 TRACE(Info, tpfx << "passing through write operation" << obfuscateAuth(io->Path()));
186 }
187 else if (Cache::GetInstance().Decide(io))
188 {
189 TRACE(Info, tpfx << obfuscateAuth(io->Path()));
190
191 IO *cio;
192
193 if (Cache::GetInstance().RefConfiguration().m_hdfsmode)
194 {
195 cio = new IOFileBlock(io, *this);
196 }
197 else
198 {
199 IOFile *iof = new IOFile(io, *this);
200
201 if ( ! iof->HasFile())
202 {
203 delete iof;
204 // TODO - redirect instead. But this is kind of an awkward place for it.
205 // errno is set during IOFile construction.
206 TRACE(Error, tpfx << "Failed opening local file, falling back to remote access " << io->Path());
207 return io;
208 }
209
210 cio = iof;
211 }
212
213 TRACE_PC(Debug, const char* loc = io->Location(), tpfx << io->Path() << " location: " <<
214 ((loc && loc[0] != 0) ? loc : "<deferred open>"));
215
216 return cio;
217 }
218 else
219 {
220 TRACE(Info, tpfx << "decision decline " << io->Path());
221 }
222 return io;
223}
224
225void Cache::AddWriteTask(Block* b, bool fromRead)
226{
227 TRACE(Dump, "AddWriteTask() offset=" << b->m_offset << ". file " << b->get_file()->GetLocalPath());
228
229 {
230 XrdSysMutexHelper lock(&m_RAM_mutex);
231 m_RAM_write_queue += b->get_size();
232 }
233
234 m_writeQ.condVar.Lock();
235 if (fromRead)
236 m_writeQ.queue.push_back(b);
237 else
238 m_writeQ.queue.push_front(b);
239 m_writeQ.size++;
240 m_writeQ.condVar.Signal();
241 m_writeQ.condVar.UnLock();
242}
243
245{
246 std::list<Block*> removed_blocks;
247 long long sum_size = 0;
248
249 m_writeQ.condVar.Lock();
250 std::list<Block*>::iterator i = m_writeQ.queue.begin();
251 while (i != m_writeQ.queue.end())
252 {
253 if ((*i)->m_file == file)
254 {
255 TRACE(Dump, "Remove entries for " << (void*)(*i) << " path " << file->lPath());
256 std::list<Block*>::iterator j = i++;
257 removed_blocks.push_back(*j);
258 sum_size += (*j)->get_size();
259 m_writeQ.queue.erase(j);
260 --m_writeQ.size;
261 }
262 else
263 {
264 ++i;
265 }
266 }
267 m_writeQ.condVar.UnLock();
268
269 {
270 XrdSysMutexHelper lock(&m_RAM_mutex);
271 m_RAM_write_queue -= sum_size;
272 }
273
274 file->BlocksRemovedFromWriteQ(removed_blocks);
275}
276
278{
279 std::vector<Block*> blks_to_write(m_configuration.m_wqueue_blocks);
280
281 while (true)
282 {
283 m_writeQ.condVar.Lock();
284 while (m_writeQ.size == 0)
285 {
286 m_writeQ.condVar.Wait();
287 }
288
289 // MT -- optimize to pop several blocks if they are available (or swap the list).
290 // This makes sense especially for smallish block sizes.
291
292 int n_pushed = std::min(m_writeQ.size, m_configuration.m_wqueue_blocks);
293 long long sum_size = 0;
294
295 for (int bi = 0; bi < n_pushed; ++bi)
296 {
297 Block* block = m_writeQ.queue.front();
298 m_writeQ.queue.pop_front();
299 m_writeQ.writes_between_purges += block->get_size();
300 sum_size += block->get_size();
301
302 blks_to_write[bi] = block;
303
304 TRACE(Dump, "ProcessWriteTasks for block " << (void*)(block) << " path " << block->m_file->lPath());
305 }
306 m_writeQ.size -= n_pushed;
307
308 m_writeQ.condVar.UnLock();
309
310 {
311 XrdSysMutexHelper lock(&m_RAM_mutex);
312 m_RAM_write_queue -= sum_size;
313 }
314
315 for (int bi = 0; bi < n_pushed; ++bi)
316 {
317 Block* block = blks_to_write[bi];
318
319 block->m_file->WriteBlockToDisk(block);
320 }
321 }
322}
323
325{
326 // Called from ResourceMonitor for an alternative estimation of disk writes.
327 XrdSysCondVarHelper lock(&m_writeQ.condVar);
328 long long ret = m_writeQ.writes_between_purges;
329 m_writeQ.writes_between_purges = 0;
330 return ret;
331}
332
333//==============================================================================
334
335char* Cache::RequestRAM(long long size)
336{
337 static const size_t s_block_align = sysconf(_SC_PAGESIZE);
338
339 bool std_size = (size == m_configuration.m_bufferSize);
340
341 m_RAM_mutex.Lock();
342
343 long long total = m_RAM_used + size;
344
345 if (total <= m_configuration.m_RamAbsAvailable)
346 {
347 m_RAM_used = total;
348 if (std_size && m_RAM_std_size > 0)
349 {
350 char *buf = m_RAM_std_blocks.back();
351 m_RAM_std_blocks.pop_back();
352 --m_RAM_std_size;
353
354 m_RAM_mutex.UnLock();
355
356 return buf;
357 }
358 else
359 {
360 m_RAM_mutex.UnLock();
361 char *buf;
362 if (posix_memalign((void**) &buf, s_block_align, (size_t) size))
363 {
364 // Report out of mem? Probably should report it at least the first time,
365 // then periodically.
366 return 0;
367 }
368 return buf;
369 }
370 }
371 m_RAM_mutex.UnLock();
372 return 0;
373}
374
375void Cache::ReleaseRAM(char* buf, long long size)
376{
377 bool std_size = (size == m_configuration.m_bufferSize);
378 {
379 XrdSysMutexHelper lock(&m_RAM_mutex);
380
381 m_RAM_used -= size;
382
383 if (std_size && m_RAM_std_size < m_configuration.m_RamKeepStdBlocks)
384 {
385 m_RAM_std_blocks.push_back(buf);
386 ++m_RAM_std_size;
387 return;
388 }
389 }
390 free(buf);
391}
392
393File* Cache::GetFile(const std::string& path, IO* io, long long off, long long filesize)
394{
395 // Called from virtual IOFile constructor.
396
397 TRACE(Debug, "GetFile " << path << ", io " << io);
398
399 ActiveMap_i it;
400
401 {
402 XrdSysCondVarHelper lock(&m_active_cond);
403
404 while (true)
405 {
406 it = m_active.find(path);
407
408 // File is not open or being opened. Mark it as being opened and
409 // proceed to opening it outside of while loop.
410 if (it == m_active.end())
411 {
412 it = m_active.insert(std::make_pair(path, (File*) 0)).first;
413 break;
414 }
415
416 if (it->second != 0)
417 {
418 it->second->AddIO(io);
419 inc_ref_cnt(it->second, false, true);
420
421 return it->second;
422 }
423 else
424 {
425 // Wait for some change in m_active, then recheck.
426 m_active_cond.Wait();
427 }
428 }
429 }
430
431 // This is always true, now that IOFileBlock is unsupported.
432 if (filesize == 0)
433 {
434 struct stat st;
435 int res = io->Fstat(st);
436 if (res < 0) {
437 errno = res;
438 TRACE(Error, "GetFile, could not get valid stat");
439 } else if (res > 0) {
440 errno = ENOTSUP;
441 TRACE(Error, "GetFile, stat returned positive value, this should NOT happen here");
442 } else {
443 filesize = st.st_size;
444 }
445 }
446
447 File *file = 0;
448
449 if (filesize >= 0)
450 {
451 file = File::FileOpen(path, off, filesize);
452 }
453
454 {
455 XrdSysCondVarHelper lock(&m_active_cond);
456
457 if (file)
458 {
459 inc_ref_cnt(file, false, true);
460 it->second = file;
461
462 file->AddIO(io);
463 }
464 else
465 {
466 m_active.erase(it);
467 }
468
469 m_active_cond.Broadcast();
470 }
471
472 return file;
473}
474
476{
477 // Called from virtual IO::DetachFinalize.
478
479 TRACE(Debug, "ReleaseFile " << f->GetLocalPath() << ", io " << io);
480
481 {
482 XrdSysCondVarHelper lock(&m_active_cond);
483
484 f->RemoveIO(io);
485 }
486 dec_ref_cnt(f, true);
487}
488
489
490namespace
491{
492
493class DiskSyncer : public XrdJob
494{
495private:
496 File *m_file;
497 bool m_high_debug;
498
499public:
500 DiskSyncer(File *f, bool high_debug, const char *desc = "") :
501 XrdJob(desc),
502 m_file(f),
503 m_high_debug(high_debug)
504 {}
505
506 void DoIt()
507 {
508 m_file->Sync();
509 Cache::GetInstance().FileSyncDone(m_file, m_high_debug);
510 delete this;
511 }
512};
513
514
515class CommandExecutor : public XrdJob
516{
517private:
518 std::string m_command_url;
519
520public:
521 CommandExecutor(const std::string& command, const char *desc = "") :
522 XrdJob(desc),
523 m_command_url(command)
524 {}
525
526 void DoIt()
527 {
528 Cache::GetInstance().ExecuteCommandUrl(m_command_url);
529 delete this;
530 }
531};
532
533}
534
535//==============================================================================
536
537void Cache::schedule_file_sync(File* f, bool ref_cnt_already_set, bool high_debug)
538{
539 DiskSyncer* ds = new DiskSyncer(f, high_debug);
540
541 if ( ! ref_cnt_already_set) inc_ref_cnt(f, true, high_debug);
542
543 schedP->Schedule(ds);
544}
545
546void Cache::FileSyncDone(File* f, bool high_debug)
547{
548 dec_ref_cnt(f, high_debug);
549}
550
551void Cache::inc_ref_cnt(File* f, bool lock, bool high_debug)
552{
553 // called from GetFile() or SheduleFileSync();
554
555 int tlvl = high_debug ? TRACE_Debug : TRACE_Dump;
556
557 if (lock) m_active_cond.Lock();
558 int rc = f->inc_ref_cnt();
559 if (lock) m_active_cond.UnLock();
560
561 TRACE_INT(tlvl, "inc_ref_cnt " << f->GetLocalPath() << ", cnt at exit = " << rc);
562}
563
564void Cache::dec_ref_cnt(File* f, bool high_debug)
565{
566 // NOT under active lock.
567 // Called from ReleaseFile(), DiskSync callback and stat-like functions.
568
569 int tlvl = high_debug ? TRACE_Debug : TRACE_Dump;
570 int cnt;
571
572 bool emergency_close = false;
573 {
574 XrdSysCondVarHelper lock(&m_active_cond);
575
576 cnt = f->get_ref_cnt();
577 TRACE_INT(tlvl, "dec_ref_cnt " << f->GetLocalPath() << ", cnt at entry = " << cnt);
578
580 {
581 // In this case file has been already removed from m_active map and
582 // does not need to be synced.
583
584 if (cnt == 1)
585 {
586 TRACE_INT(tlvl, "dec_ref_cnt " << f->GetLocalPath() << " is in shutdown, ref_cnt = " << cnt
587 << " -- closing and deleting File object without further ado");
588 emergency_close = true;
589 }
590 else
591 {
592 TRACE_INT(tlvl, "dec_ref_cnt " << f->GetLocalPath() << " is in shutdown, ref_cnt = " << cnt
593 << " -- waiting");
594 f->dec_ref_cnt();
595 return;
596 }
597 }
598 if (cnt > 1)
599 {
600 f->dec_ref_cnt();
601 return;
602 }
603 }
604 if (emergency_close)
605 {
606 f->Close();
607 delete f;
608 return;
609 }
610
611 if (cnt == 1)
612 {
613 if (f->FinalizeSyncBeforeExit())
614 {
615 // Note, here we "reuse" the existing reference count for the
616 // final sync.
617
618 TRACE(Debug, "dec_ref_cnt " << f->GetLocalPath() << ", scheduling final sync");
619 schedule_file_sync(f, true, true);
620 return;
621 }
622 }
623
624 bool finished_p = false;
625 ActiveMap_i act_it;
626 {
627 XrdSysCondVarHelper lock(&m_active_cond);
628
629 cnt = f->dec_ref_cnt();
630 TRACE_INT(tlvl, "dec_ref_cnt " << f->GetLocalPath() << ", cnt after sync_check and dec_ref_cnt = " << cnt);
631 if (cnt == 0)
632 {
633 act_it = m_active.find(f->GetLocalPath());
634 act_it->second = 0;
635
636 finished_p = true;
637 }
638 }
639 if (finished_p)
640 {
641 f->Close();
642 {
643 XrdSysCondVarHelper lock(&m_active_cond);
644 m_active.erase(act_it);
645 }
646
647 if (m_gstream)
648 {
649 const Stats &st = f->RefStats();
650 const Info::AStat *as = f->GetLastAccessStats();
651
652 char buf[4096];
653 int len = snprintf(buf, 4096, "{\"event\":\"file_close\","
654 "\"lfn\":\"%s\",\"size\":%lld,\"blk_size\":%d,\"n_blks\":%d,\"n_blks_done\":%d,"
655 "\"access_cnt\":%lu,\"attach_t\":%lld,\"detach_t\":%lld,\"remotes\":%s,"
656 "\"b_hit\":%lld,\"b_miss\":%lld,\"b_bypass\":%lld,"
657 "\"b_todisk\":%lld,\"b_prefetch\":%lld,\"n_cks_errs\":%d}",
658 f->GetLocalPath().c_str(), f->GetFileSize(), f->GetBlockSize(),
660 (unsigned long) f->GetAccessCnt(), (long long) as->AttachTime, (long long) as->DetachTime,
661 f->GetRemoteLocations().c_str(),
662 as->BytesHit, as->BytesMissed, as->BytesBypassed,
664 );
665 bool suc = false;
666 if (len < 4096)
667 {
668 suc = m_gstream->Insert(buf, len + 1);
669 }
670 if ( ! suc)
671 {
672 TRACE(Error, "Failed g-stream insertion of file_close record, len=" << len);
673 }
674 }
675
676 delete f;
677 }
678}
679
680bool Cache::IsFileActiveOrPurgeProtected(const std::string& path) const
681{
682 XrdSysCondVarHelper lock(&m_active_cond);
683
684 return m_active.find(path) != m_active.end() ||
685 m_purge_delay_set.find(path) != m_purge_delay_set.end();
686}
687
689{
690 XrdSysCondVarHelper lock(&m_active_cond);
691 m_purge_delay_set.clear();
692}
693
694//==============================================================================
695//=== PREFETCH
696//==============================================================================
697
699{
700 // Can be called with other locks held.
701
702 if ( ! m_prefetch_enabled)
703 {
704 return;
705 }
706
707 m_prefetch_condVar.Lock();
708 m_prefetchList.push_back(file);
709 m_prefetch_condVar.Signal();
710 m_prefetch_condVar.UnLock();
711}
712
713
715{
716 // Can be called with other locks held.
717
718 if ( ! m_prefetch_enabled)
719 {
720 return;
721 }
722
723 m_prefetch_condVar.Lock();
724 for (PrefetchList::iterator it = m_prefetchList.begin(); it != m_prefetchList.end(); ++it)
725 {
726 if (*it == file)
727 {
728 m_prefetchList.erase(it);
729 break;
730 }
731 }
732 m_prefetch_condVar.UnLock();
733}
734
735
737{
738 m_prefetch_condVar.Lock();
739 while (m_prefetchList.empty())
740 {
741 m_prefetch_condVar.Wait();
742 }
743
744 // std::sort(m_prefetchList.begin(), m_prefetchList.end(), myobject);
745
746 size_t l = m_prefetchList.size();
747 int idx = rand() % l;
748 File* f = m_prefetchList[idx];
749
750 m_prefetch_condVar.UnLock();
751 return f;
752}
753
754
756{
757 const long long limit_RAM = m_configuration.m_RamAbsAvailable * 7 / 10;
758
759 while (true)
760 {
761 m_RAM_mutex.Lock();
762 bool doPrefetch = (m_RAM_used < limit_RAM);
763 m_RAM_mutex.UnLock();
764
765 if (doPrefetch)
766 {
768 f->Prefetch();
769 }
770 else
771 {
773 }
774 }
775}
776
777
778//==============================================================================
779//=== Virtuals from XrdOucCache
780//==============================================================================
781
782//------------------------------------------------------------------------------
796
797int Cache::LocalFilePath(const char *curl, char *buff, int blen,
798 LFP_Reason why, bool forall)
799{
800 static const mode_t groupReadable = S_IRUSR | S_IWUSR | S_IRGRP;
801 static const mode_t worldReadable = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
802 static const char *lfpReason[] = { "ForAccess", "ForInfo", "ForPath" };
803
804 TRACE(Debug, "LocalFilePath '" << curl << "', why=" << lfpReason[why]);
805
806 if (buff && blen > 0) buff[0] = 0;
807
808 XrdCl::URL url(curl);
809 std::string f_name = url.GetPath();
810 std::string i_name = f_name + Info::s_infoExtension;
811
812 if (why == ForPath)
813 {
814 int ret = m_oss->Lfn2Pfn(f_name.c_str(), buff, blen);
815 TRACE(Info, "LocalFilePath '" << curl << "', why=" << lfpReason[why] << " -> " << ret);
816 return ret;
817 }
818
819 {
820 XrdSysCondVarHelper lock(&m_active_cond);
821 m_purge_delay_set.insert(f_name);
822 }
823
824 struct stat sbuff, sbuff2;
825 if (m_oss->Stat(f_name.c_str(), &sbuff) == XrdOssOK &&
826 m_oss->Stat(i_name.c_str(), &sbuff2) == XrdOssOK)
827 {
828 if (S_ISDIR(sbuff.st_mode))
829 {
830 TRACE(Info, "LocalFilePath '" << curl << "', why=" << lfpReason[why] << " -> EISDIR");
831 return -EISDIR;
832 }
833 else
834 {
835 bool read_ok = false;
836 bool is_complete = false;
837
838 // Lock and check if the file is active. If NOT, keep the lock
839 // and add dummy access after successful reading of info file.
840 // If it IS active, just release the lock, this ongoing access will
841 // assure the file continues to exist.
842
843 // XXXX How can I just loop over the cinfo file when active?
844 // Can I not get is_complete from the existing file?
845 // Do I still want to inject access record?
846 // Oh, it writes only if not active .... still let's try to use existing File.
847
848 m_active_cond.Lock();
849
850 bool is_active = m_active.find(f_name) != m_active.end();
851
852 if (is_active) m_active_cond.UnLock();
853
854 XrdOssDF* infoFile = m_oss->newFile(m_configuration.m_username.c_str());
855 XrdOucEnv myEnv;
856 int res = infoFile->Open(i_name.c_str(), O_RDWR, 0600, myEnv);
857 if (res >= 0)
858 {
859 Info info(m_trace, 0);
860 if (info.Read(infoFile, i_name.c_str()))
861 {
862 read_ok = true;
863
864 is_complete = info.IsComplete();
865
866 // Add full-size access if reason is for access.
867 if ( ! is_active && is_complete && why == ForAccess)
868 {
869 info.WriteIOStatSingle(info.GetFileSize());
870 info.Write(infoFile, i_name.c_str());
871 }
872 }
873 infoFile->Close();
874 }
875 delete infoFile;
876
877 if ( ! is_active) m_active_cond.UnLock();
878
879 if (read_ok)
880 {
881 if ((is_complete || why == ForInfo) && buff != 0)
882 {
883 int res2 = m_oss->Lfn2Pfn(f_name.c_str(), buff, blen);
884 if (res2 < 0)
885 return res2;
886
887 // Normally, files are owned by us but when direct cache access
888 // is wanted and possible, make sure the file is world readable.
889 if (why == ForAccess)
890 {mode_t mode = (forall ? worldReadable : groupReadable);
891 if (((sbuff.st_mode & worldReadable) != mode)
892 && (m_oss->Chmod(f_name.c_str(), mode) != XrdOssOK))
893 {is_complete = false;
894 *buff = 0;
895 }
896 }
897 }
898
899 TRACE(Info, "LocalFilePath '" << curl << "', why=" << lfpReason[why] <<
900 (is_complete ? " -> FILE_COMPLETE_IN_CACHE" : " -> EREMOTE"));
901
902 return is_complete ? 0 : -EREMOTE;
903 }
904 }
905 }
906
907 TRACE(Info, "LocalFilePath '" << curl << "', why=" << lfpReason[why] << " -> ENOENT");
908 return -ENOENT;
909}
910
911//______________________________________________________________________________
912// If supported, write file_size as xattr to cinfo file.
913//------------------------------------------------------------------------------
914void Cache::WriteFileSizeXAttr(int cinfo_fd, long long file_size)
915{
916 if (m_metaXattr) {
917 int res = XrdSysXAttrActive->Set("pfc.fsize", &file_size, sizeof(long long), 0, cinfo_fd, 0);
918 if (res != 0) {
919 TRACE(Debug, "WriteFileSizeXAttr error setting xattr " << res);
920 }
921 }
922}
923
924//______________________________________________________________________________
925// Determine full size of the data file from the corresponding cinfo-file name.
926// Attempts to read xattr first and falls back to reading of the cinfo file.
927// Returns -error on failure.
928//------------------------------------------------------------------------------
929long long Cache::DetermineFullFileSize(const std::string &cinfo_fname)
930{
931 if (m_metaXattr) {
932 char pfn[4096];
933 m_oss->Lfn2Pfn(cinfo_fname.c_str(), pfn, 4096);
934 long long fsize = -1ll;
935 int res = XrdSysXAttrActive->Get("pfc.fsize", &fsize, sizeof(long long), pfn);
936 if (res == sizeof(long long))
937 {
938 return fsize;
939 }
940 else
941 {
942 TRACE(Debug, "DetermineFullFileSize error getting xattr " << res);
943 }
944 }
945
946 XrdOssDF *infoFile = m_oss->newFile(m_configuration.m_username.c_str());
947 XrdOucEnv env;
948 long long ret;
949 int res = infoFile->Open(cinfo_fname.c_str(), O_RDONLY, 0600, env);
950 if (res < 0) {
951 ret = res;
952 } else {
953 Info info(m_trace, 0);
954 if ( ! info.Read(infoFile, cinfo_fname.c_str())) {
955 ret = -EBADF;
956 } else {
957 ret = info.GetFileSize();
958 }
959 infoFile->Close();
960 }
961 delete infoFile;
962 return ret;
963}
964
965//______________________________________________________________________________
966// Calculate if the file is to be considered cached for the purposes of
967// only-if-cached and setting of atime of the Stat() calls.
968// Returns true if the file is to be conidered cached.
969//------------------------------------------------------------------------------
970bool Cache::DecideIfConsideredCached(long long file_size, long long bytes_on_disk)
971{
972 if (file_size == 0 || bytes_on_disk >= file_size)
973 return true;
974
975 double frac_on_disk = (double) bytes_on_disk / file_size;
976
977 if (file_size <= m_configuration.m_onlyIfCachedMinSize)
978 {
979 if (frac_on_disk >= m_configuration.m_onlyIfCachedMinFrac)
980 return true;
981 }
982 else
983 {
984 if (bytes_on_disk >= m_configuration.m_onlyIfCachedMinSize &&
985 frac_on_disk >= m_configuration.m_onlyIfCachedMinFrac)
986 return true;
987 }
988 return false;
989}
990
991//______________________________________________________________________________
992// Check if the file is cached including m_onlyIfCachedMinSize and m_onlyIfCachedMinFrac
993// pfc configuration parameters. The logic of accessing the Info file is the same
994// as in Cache::LocalFilePath.
1002//------------------------------------------------------------------------------
1003int Cache::ConsiderCached(const char *curl)
1004{
1005 static const char* tpfx = "ConsiderCached ";
1006
1007 TRACE(Debug, tpfx << curl);
1008
1009 XrdCl::URL url(curl);
1010 std::string f_name = url.GetPath();
1011
1012 File *file = nullptr;
1013 {
1014 XrdSysCondVarHelper lock(&m_active_cond);
1015 auto it = m_active.find(f_name);
1016 if (it != m_active.end()) {
1017 file = it->second;
1018 // If the file-open is in progress, `file` is a nullptr
1019 // so we cannot increase the reference count. For now,
1020 // simply treat it as if the file open doesn't exist instead
1021 // of trying to wait and see if it succeeds.
1022 if (file) {
1023 inc_ref_cnt(file, false, false);
1024 }
1025 }
1026 }
1027 if (file) {
1028 struct stat sbuff;
1029 int res = file->Fstat(sbuff);
1030 dec_ref_cnt(file, false);
1031 if (res)
1032 return res;
1033 // DecideIfConsideredCached() already called in File::Fstat().
1034 return sbuff.st_atime > 0 ? 0 : -EREMOTE;
1035 }
1036
1037 struct stat sbuff;
1038 int res = m_oss->Stat(f_name.c_str(), &sbuff);
1039 if (res != XrdOssOK) {
1040 TRACE(Debug, tpfx << curl << " -> " << res);
1041 return res;
1042 }
1043 if (S_ISDIR(sbuff.st_mode))
1044 {
1045 TRACE(Debug, tpfx << curl << " -> EISDIR");
1046 return -EISDIR;
1047 }
1048
1049 long long file_size = DetermineFullFileSize(f_name + Info::s_infoExtension);
1050 if (file_size < 0) {
1051 TRACE(Debug, tpfx << curl << " -> " << file_size);
1052 return (int) file_size;
1053 }
1054 bool is_cached = DecideIfConsideredCached(file_size, sbuff.st_blocks * 512ll);
1055
1056 return is_cached ? 0 : -EREMOTE;
1057}
1058
1059//______________________________________________________________________________
1067//------------------------------------------------------------------------------
1068
1069int Cache::Prepare(const char *curl, int oflags, mode_t mode)
1070{
1071 XrdCl::URL url(curl);
1072 std::string f_name = url.GetPath();
1073 std::string i_name = f_name + Info::s_infoExtension;
1074
1075 // Do not allow write access.
1076 if ((oflags & O_ACCMODE) != O_RDONLY)
1077 {
1078 if (Cache::GetInstance().RefConfiguration().m_write_through)
1079 {
1080 return 0;
1081 }
1082 TRACE(Warning, "Prepare write access requested on file " << f_name << ". Denying access.");
1083 return -EROFS;
1084 }
1085
1086 // Intercept xrdpfc_command requests.
1087 if (m_configuration.m_allow_xrdpfc_command && strncmp("/xrdpfc_command/", f_name.c_str(), 16) == 0)
1088 {
1089 // Schedule a job to process command request.
1090 {
1091 CommandExecutor *ce = new CommandExecutor(f_name, "CommandExecutor");
1092
1093 schedP->Schedule(ce);
1094 }
1095
1096 return -EAGAIN;
1097 }
1098
1099 {
1100 XrdSysCondVarHelper lock(&m_active_cond);
1101 m_purge_delay_set.insert(f_name);
1102 }
1103
1104 struct stat sbuff;
1105 if (m_oss->Stat(i_name.c_str(), &sbuff) == XrdOssOK)
1106 {
1107 TRACE(Dump, "Prepare defer open " << f_name);
1108 return 1;
1109 }
1110 else
1111 {
1112 return 0;
1113 }
1114}
1115
1116//______________________________________________________________________________
1117// virtual method of XrdOucCache.
1122//------------------------------------------------------------------------------
1123
1124int Cache::Stat(const char *curl, struct stat &sbuff)
1125{
1126 const char *tpfx = "Stat ";
1127
1128 XrdCl::URL url(curl);
1129 std::string f_name = url.GetPath();
1130
1131 File *file = nullptr;
1132 {
1133 XrdSysCondVarHelper lock(&m_active_cond);
1134 auto it = m_active.find(f_name);
1135 if (it != m_active.end()) {
1136 file = it->second;
1137 // If `file` is nullptr, the file-open is in progress; instead
1138 // of waiting for the file-open to finish, simply treat it as if
1139 // the file-open doesn't exist.
1140 if (file) {
1141 inc_ref_cnt(file, false, false);
1142 }
1143 }
1144 }
1145 if (file) {
1146 int res = file->Fstat(sbuff);
1147 dec_ref_cnt(file, false);
1148 TRACE(Debug, tpfx << "from active file " << curl << " -> " << res);
1149 return res;
1150 }
1151
1152 int res = m_oss->Stat(f_name.c_str(), &sbuff);
1153 if (res != XrdOssOK) {
1154 TRACE(Debug, tpfx << curl << " -> " << res);
1155 return 1; // res; -- for only-if-cached
1156 }
1157 if (S_ISDIR(sbuff.st_mode))
1158 {
1159 TRACE(Debug, tpfx << curl << " -> EISDIR");
1160 return -EISDIR;
1161 }
1162
1163 long long file_size = DetermineFullFileSize(f_name + Info::s_infoExtension);
1164 if (file_size < 0) {
1165 TRACE(Debug, tpfx << curl << " -> " << file_size);
1166 return 1; // (int) file_size; -- for only-if-cached
1167 }
1168 sbuff.st_size = file_size;
1169 bool is_cached = DecideIfConsideredCached(file_size, sbuff.st_blocks * 512ll);
1170 if ( ! is_cached)
1171 sbuff.st_atime = 0;
1172
1173 TRACE(Debug, tpfx << "from disk " << curl << " -> " << res);
1174
1175 return 0;
1176}
1177
1178//______________________________________________________________________________
1179// virtual method of XrdOucCache.
1183//------------------------------------------------------------------------------
1184
1185int Cache::Unlink(const char *curl)
1186{
1187 XrdCl::URL url(curl);
1188 std::string f_name = url.GetPath();
1189
1190 // printf("Unlink url=%s\n\t fname=%s\n", curl, f_name.c_str());
1191
1192 return UnlinkFile(f_name, false);
1193}
1194
1195int Cache::UnlinkFile(const std::string& f_name, bool fail_if_open)
1196{
1197 static const char* trc_pfx = "UnlinkFile ";
1198 ActiveMap_i it;
1199 File *file = 0;
1200 long long st_blocks_to_purge = 0;
1201 {
1202 XrdSysCondVarHelper lock(&m_active_cond);
1203
1204 it = m_active.find(f_name);
1205
1206 if (it != m_active.end())
1207 {
1208 if (fail_if_open)
1209 {
1210 TRACE(Info, trc_pfx << f_name << ", file currently open and force not requested - denying request");
1211 return -EBUSY;
1212 }
1213
1214 // Null File* in m_active map means an operation is ongoing, probably
1215 // Attach() with possible File::Open(). Ask for retry.
1216 if (it->second == 0)
1217 {
1218 TRACE(Info, trc_pfx << f_name << ", an operation on this file is ongoing - denying request");
1219 return -EAGAIN;
1220 }
1221
1222 file = it->second;
1223 st_blocks_to_purge = file->initiate_emergency_shutdown();
1224 it->second = 0;
1225 }
1226 else
1227 {
1228 it = m_active.insert(std::make_pair(f_name, (File*) 0)).first;
1229 }
1230 }
1231
1232 if (file) {
1234 } else {
1235 struct stat f_stat;
1236 if (m_oss->Stat(f_name.c_str(), &f_stat) == XrdOssOK)
1237 st_blocks_to_purge = f_stat.st_blocks;
1238 }
1239
1240 std::string i_name = f_name + Info::s_infoExtension;
1241
1242 // Unlink file & cinfo
1243 int f_ret = m_oss->Unlink(f_name.c_str());
1244 int i_ret = m_oss->Unlink(i_name.c_str());
1245
1246 if (st_blocks_to_purge)
1247 m_res_mon->register_file_purge(f_name, st_blocks_to_purge);
1248
1249 TRACE(Debug, trc_pfx << f_name << ", f_ret=" << f_ret << ", i_ret=" << i_ret);
1250
1251 {
1252 XrdSysCondVarHelper lock(&m_active_cond);
1253
1254 m_active.erase(it);
1255 }
1256
1257 return std::min(f_ret, i_ret);
1258}
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)
static const int optRW
File is read/write (o/w read/only)
XrdOucCache(const char *ctype)
void * GetPtr(const char *varname)
Definition XrdOucEnv.cc:281
void PutPtr(const char *varname, void *value)
Definition XrdOucEnv.cc:316
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:154
long long DetermineFullFileSize(const std::string &cinfo_fname)
Definition XrdPfc.cc:929
void FileSyncDone(File *, bool high_debug)
Definition XrdPfc.cc:546
File * GetFile(const std::string &, IO *, long long off=0, long long filesize=0)
Definition XrdPfc.cc:393
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:797
virtual int Stat(const char *url, struct stat &sbuff)
Definition XrdPfc.cc:1124
const Configuration & RefConfiguration() const
Reference XrdPfc configuration.
Definition XrdPfc.hh:206
static ResourceMonitor & ResMon()
Definition XrdPfc.cc:135
bool IsFileActiveOrPurgeProtected(const std::string &) const
Definition XrdPfc.cc:680
void ClearPurgeProtectedSet()
Definition XrdPfc.cc:688
void ReleaseRAM(char *buf, long long size)
Definition XrdPfc.cc:375
virtual int ConsiderCached(const char *url)
Definition XrdPfc.cc:1003
static Cache & GetInstance()
Singleton access.
Definition XrdPfc.cc:132
void DeRegisterPrefetchFile(File *)
Definition XrdPfc.cc:714
void ExecuteCommandUrl(const std::string &command_url)
void RegisterPrefetchFile(File *)
Definition XrdPfc.cc:698
void WriteFileSizeXAttr(int cinfo_fd, long long file_size)
Definition XrdPfc.cc:914
void Prefetch()
Definition XrdPfc.cc:755
void ReleaseFile(File *, IO *)
Definition XrdPfc.cc:475
void AddWriteTask(Block *b, bool from_read)
Add downloaded block in write queue.
Definition XrdPfc.cc:225
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:1195
static XrdScheduler * schedP
Definition XrdPfc.hh:292
File * GetNextFileToPrefetch()
Definition XrdPfc.cc:736
long long WritesSinceLastCall()
Definition XrdPfc.cc:324
void ProcessWriteTasks()
Separate task which writes blocks from ram to disk.
Definition XrdPfc.cc:277
virtual int Unlink(const char *url)
Definition XrdPfc.cc:1185
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:244
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:335
virtual int Prepare(const char *url, int oflags, mode_t mode)
Definition XrdPfc.cc:1069
bool DecideIfConsideredCached(long long file_size, long long bytes_on_disk)
Definition XrdPfc.cc:970
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:114
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