The Gaudi Framework master (9cc87df9)
Loading...
Searching...
No Matches
FileSvc.cpp
Go to the documentation of this file.
1/***********************************************************************************\
2* (c) Copyright 2024-2026 CERN for the benefit of the LHCb and ATLAS collaborations *
3* *
4* This software is distributed under the terms of the Apache version 2 licence, *
5* copied verbatim in the file "LICENSE". *
6* *
7* In applying this licence, CERN does not waive the privileges and immunities *
8* granted to it by virtue of its status as an Intergovernmental Organization *
9* or submit itself to any jurisdiction. *
10\***********************************************************************************/
15#include <GaudiKernel/Service.h>
17#include <TFile.h>
18#include <boost/algorithm/string.hpp>
19#include <memory>
20#include <mutex>
21#include <optional>
22#include <string>
23#include <unordered_map>
24#include <vector>
25
43class FileSvc : public extends<Service, Gaudi::Interfaces::IFileSvc> {
44public:
45 // Constructor
46 FileSvc( const std::string& name, ISvcLocator* svc );
47
48 StatusCode initialize() override;
49
50 StatusCode start() override;
51
52 StatusCode finalize() override;
53
60 std::shared_ptr<TFile> getFile( const std::string& identifier ) override;
61
63 bool hasIdentifier( const std::string& identifier ) const override;
64
65public:
66 // See FileSvc documentation for the syntax supported for paths
68 this, "Config", {}, "Map of keywords to file paths for file access" };
69
70private:
79 std::shared_ptr<TFile> openFile( const std::string& filePath, const std::string& option, int compress );
80
86
87private:
88 // Map holding file identifiers to file indices in the m_files vector
90
91 // Vector to hold all files unique pointers
94};
95
97
98namespace {
105 std::map<std::string, std::string> parseFilePath( const std::string& path ) {
107 boost::split( parts, path, boost::is_any_of( "?" ) );
109 if ( parts.size() > 1 ) {
111 boost::split( params, parts[1], boost::is_any_of( "&" ) );
112 for ( auto& param : params ) {
114 boost::split( kv, param, boost::is_any_of( "=" ) );
115 if ( kv.size() == 2 ) { result[boost::trim_copy( kv[0] )] = boost::trim_copy( kv[1] ); }
116 }
117 }
118 result["mode"] = ( result.find( "mode" ) == result.end() ) ? "CREATE" : result["mode"];
119 result["path"] = boost::trim_copy( parts[0] );
120 return result;
121 }
122
132 StatusCode checkConfig( const std::map<std::string, std::string>& configMap, const FileSvc& svc ) {
134 for ( const auto& [identifier, path] : configMap ) {
135 auto params = parseFilePath( path );
136
137 auto& existingParams = fileParams[params["path"]];
138 if ( !existingParams.empty() ) {
139 if ( existingParams != params ) {
140 svc.error() << "Conflicting configurations for file path: " << params["path"] << endmsg;
141 return StatusCode::FAILURE;
142 }
143 } else {
144 existingParams = std::move( params );
145 }
146 }
147 return StatusCode::SUCCESS;
148 }
149
157 std::optional<size_t> findFileIndex( const std::vector<std::shared_ptr<TFile>>& files, const std::string& filePath ) {
158 auto it = std::find_if( files.begin(), files.end(),
159 [&filePath]( const auto& file ) { return file && file->GetName() == filePath; } );
160 if ( it != files.end() ) { return std::distance( files.begin(), it ); }
161 return std::nullopt;
162 }
163} // namespace
164
165FileSvc::FileSvc( const std::string& name, ISvcLocator* svc ) : base_class( name, svc ) {}
166
168 return Service::initialize().andThen( [this]() {
169 if ( checkConfig( m_config, *this ).isFailure() ) { return StatusCode::FAILURE; }
170
171 for ( const auto& [identifier, path] : m_config ) {
172 auto params = parseFilePath( path );
173
174 // Check if this file is already opened and mapped
175 if ( auto fileIndex = findFileIndex( m_files, params["path"] ) ) {
176 // File already opened, just map the identifier to the existing index
177 m_identifiers[boost::to_lower_copy( identifier )] = *fileIndex;
178 } else {
179 // File not found, open a new one
180 int compress = ( params.find( "compress" ) != params.end() )
181 ? std::stoi( params["compress"] )
182 : ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault;
183 if ( auto file = openFile( path, params["mode"], compress ) ) {
184 m_files.push_back( std::move( file ) );
185 m_identifiers[boost::to_lower_copy( identifier )] = m_files.size() - 1;
186 } else {
187 error() << "Failed to open file: " << params["path"] << endmsg;
188 return StatusCode::FAILURE;
189 }
190 }
191 }
192
193 return StatusCode::SUCCESS;
194 } );
195}
196
198 return Service::start().andThen( [this] {
199 // All services have now initialized and registered their listeners, including
200 // those ordered after FileSvc so that they finalize before its files close.
201 // Announce physical files, not identifiers, and do not repeat on stop/start.
203 if ( auto incidentSvc = service<IIncidentSvc>( "IncidentSvc", false ) ) {
204 for ( auto const& file : m_files ) {
205 incidentSvc->fireIncident( ContextIncident<TFile*>( file->GetName(), "CONNECTED_OUTPUT", file.get() ) );
206 }
207 }
208 } );
209 } );
210}
211
213
214std::shared_ptr<TFile> FileSvc::getFile( const std::string& identifier ) {
215 auto it = m_identifiers.find( boost::to_lower_copy( identifier ) );
216 if ( it != m_identifiers.end() && it->second < m_files.size() ) { return m_files[it->second]; }
217 error() << "No file associated with identifier: " << identifier << endmsg;
218 return nullptr;
219}
220
221bool FileSvc::hasIdentifier( const std::string& identifier ) const {
222 return m_identifiers.find( boost::to_lower_copy( identifier ) ) != m_identifiers.end();
223}
224
225std::shared_ptr<TFile> FileSvc::openFile( const std::string& filePath, const std::string& option, int compress ) {
226 auto file = std::make_shared<TFile>( filePath.c_str(), option.c_str(), "", compress );
227 if ( !file || file->IsZombie() ) { return nullptr; }
228 return file;
229}
230
232 for ( const auto& file : m_files ) {
233 if ( file ) { file->Close(); }
234 }
235 m_files.clear();
237 return StatusCode::SUCCESS;
238}
MsgStream & endmsg(MsgStream &s)
MsgStream Modifier: endmsg. Calls the output method of the MsgStream.
Definition MsgStream.h:198
#define DECLARE_COMPONENT(type)
constexpr _OI move(_II __first, _II __last, _OI __result)
constexpr _InputIterator find_if(_InputIterator __first, _InputIterator __last, _Predicate __pred)
void call_once(once_flag &__once, _Callable &&__f, _Args &&... __args)
constexpr iterator_traits< _InputIterator >::difference_type distance(_InputIterator __first, _InputIterator __last)
const _CharT * c_str() const noexcept
const_iterator end() const noexcept
iterator find(const key_type &__x)
constexpr void push_back(const value_type &__x)
constexpr size_type size() const noexcept
iterator end() noexcept
void clear() noexcept
iterator find(const key_type &__x)
MsgStream & error() const
shortcut for the method msgStream(MSG::ERROR)
Implementation of the IFileSvc interface, allowing algorithms to access ROOT files via a centralized ...
Definition FileSvc.cpp:43
Gaudi::Property< std::map< std::string, std::string > > m_config
Definition FileSvc.cpp:67
StatusCode closeFiles()
Close all files.
Definition FileSvc.cpp:231
StatusCode start() override
Definition FileSvc.cpp:197
std::vector< std::shared_ptr< TFile > > m_files
Definition FileSvc.cpp:92
StatusCode initialize() override
Definition FileSvc.cpp:167
bool hasIdentifier(const std::string &identifier) const override
Check if a given identifier is known to the service.
Definition FileSvc.cpp:221
StatusCode finalize() override
Definition FileSvc.cpp:212
std::once_flag m_announceOutputs
Definition FileSvc.cpp:93
std::unordered_map< std::string, size_t > m_identifiers
Definition FileSvc.cpp:89
FileSvc(const std::string &name, ISvcLocator *svc)
Definition FileSvc.cpp:165
std::shared_ptr< TFile > getFile(const std::string &identifier) override
Get a TFile pointer based on an identifier.
Definition FileSvc.cpp:214
std::shared_ptr< TFile > openFile(const std::string &filePath, const std::string &option, int compress)
Open a file based on a specified path and opening mode.
Definition FileSvc.cpp:225
Implementation of property with value of concrete type.
Definition Property.h:35
The ISvcLocator is the interface implemented by the Service Factory in the Application Manager to loc...
Definition ISvcLocator.h:42
const std::string & name() const override
Retrieve name of the service.
Definition Service.cpp:333
SmartIF< IFace > service(const std::string &name, bool createIf=true) const
Definition Service.h:79
StatusCode start() override
Definition Service.cpp:187
StatusCode initialize() override
Definition Service.cpp:118
This class is used for returning status codes from appropriate routines.
Definition StatusCode.h:64
StatusCode andThen(F &&f, ARGS &&... args) const
Chain code blocks making the execution conditional a success result.
Definition StatusCode.h:151
constexpr static const auto SUCCESS
Definition StatusCode.h:99
constexpr static const auto FAILURE
Definition StatusCode.h:100
Base class used to extend a class implementing other interfaces.
Definition extends.h:19