MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
mxl::lib::Instance Class Reference

#include <Instance.hpp>

Collaboration diagram for mxl::lib::Instance:

Classes

class  RefCounted

Public Member Functions

FlowSynchronizationGroup * createFlowSynchronizationGroup ()
std::tuple< mxlFlowConfigInfo, FlowWriter *, bool > createFlowWriter (std::string const &flowDef, std::optional< std::string > options={})
std::size_t garbageCollect () const
std::string getDomain () const
std::string getFlowDef (uuids::uuid const &flowId) const
FlowReader * getFlowReader (std::string const &flowId)
std::uint64_t getHistoryDurationNs () const
 Instance (Instance &&)=delete
 Instance (Instance const &)=delete
 Instance (std::filesystem::path const &mxlDomain, std::string const &options, std::unique_ptr< FlowIoFactory > &&flowIoFactory, DomainWatcher::ptr watcher)
Instance & operator= (Instance &&)=delete
Instance & operator= (Instance const &)=delete
void releaseFlowSynchronizationGroup (FlowSynchronizationGroup const *group)
void releaseReader (FlowReader *reader)
void releaseWriter (FlowWriter *writer)
 ~Instance ()
 Dtor. Release all readers and writers.

Private Member Functions

std::pair< std::unique_ptr< FlowData >, bool > createOrOpenContinuousFlowData (std::string const &flowDef, FlowParser const &, FlowOptionsParser const &)
std::pair< std::unique_ptr< FlowData >, bool > createOrOpenDiscreteFlowData (std::string const &flowDef, FlowParser const &, FlowOptionsParser const &)
void parseOptions (std::string const &options)

Private Attributes

std::unique_ptr< FlowIoFactory > _flowIoFactory
 The I/O factor used to delegate the creation of readers and writers.
FlowManager _flowManager
 Performs flow CRUD operations.
std::uint64_t _historyDuration
 Ring buffer history duration in nanoseconds.
std::mutex _mutex
 Protects the maps.
std::string _options
 For future use.
std::map< uuids::uuid, RefCounted< FlowReader > > _readers
 Maps flow uuids to flow readers.
std::atomic_bool _stopping
std::forward_list< FlowSynchronizationGroup > _syncGroups
 The set of active flow synchronization groups.
DomainWatcher::ptr _watcher
std::map< uuids::uuid, RefCounted< FlowWriter > > _writers
 Maps flow uuids to flow writers.

Detailed Description

Manages mxl resources allocated by the SDK user. Represents a single mxfInstance.

Definition at line 31 of file Instance.hpp.

Constructor & Destructor Documentation

◆ Instance() [1/3]

mxl::lib::Instance::Instance ( std::filesystem::path const & mxlDomain,
std::string const & options,
std::unique_ptr< FlowIoFactory > && flowIoFactory,
DomainWatcher::ptr watcher )

Creates an instance

Parameters
[in]mxlDomainThe directory where the shared memory files will be created
[in]optionsAdditional options.
Todo
Not implemented yet.
Parameters
[in]flowIoFactoryA factory used to create flow readers for flows of different types.
[in]watcherA DomainWatcher that is shared with the flowIoFactory

Definition at line 125 of file Instance.cpp.

127 : _flowManager{mxlDomain}
128 , _flowIoFactory{std::move(flowIoFactory)}
129 , _readers{}
130 , _writers{}
131 , _mutex{}
132 , _syncGroups{}
133 , _options{options}
134 , _historyDuration{200'000'000ULL}
135 , _watcher{std::move(watcher)}
136 , _stopping{false}
137 {
138 std::call_once(loggingFlag, [&]() { initializeLogging(); });
139 parseOptions(options);
140 MXL_DEBUG("Instance created. MXL Domain: {}", mxlDomain.string());
141 }
#define MXL_DEBUG(...)
Definition Logging.hpp:34
FlowManager _flowManager
Performs flow CRUD operations.
Definition Instance.hpp:167
std::map< uuids::uuid, RefCounted< FlowReader > > _readers
Maps flow uuids to flow readers.
Definition Instance.hpp:173
std::string _options
For future use.
Definition Instance.hpp:184
std::forward_list< FlowSynchronizationGroup > _syncGroups
The set of active flow synchronization groups.
Definition Instance.hpp:181
std::unique_ptr< FlowIoFactory > _flowIoFactory
The I/O factor used to delegate the creation of readers and writers.
Definition Instance.hpp:170
std::atomic_bool _stopping
Definition Instance.hpp:191
std::uint64_t _historyDuration
Ring buffer history duration in nanoseconds.
Definition Instance.hpp:187
std::map< uuids::uuid, RefCounted< FlowWriter > > _writers
Maps flow uuids to flow writers.
Definition Instance.hpp:175
std::mutex _mutex
Protects the maps.
Definition Instance.hpp:178
DomainWatcher::ptr _watcher
Definition Instance.hpp:189
void parseOptions(std::string const &options)
Definition Instance.cpp:422

◆ ~Instance()

mxl::lib::Instance::~Instance ( )

Dtor. Release all readers and writers.

Definition at line 143 of file Instance.cpp.

144 {
145 _stopping = true;
146 _watcher->stop();
147 MXL_DEBUG("Instance destroyed.");
148
149 for (auto& [id, writer] : _writers)
150 {
151 try
152 {
153 if (writer.get()->isExclusive() || writer.get()->makeExclusive())
154 {
155 MXL_WARN("Cleaning up flow '{}' of leaked flow writer.", uuids::to_string(id));
156
157 _flowManager.deleteFlow(id);
158 }
159 }
160 catch (std::exception const& ex)
161 {
162 MXL_ERROR("Failed to clean up leaked flow writer: {}", ex.what());
163 }
164 }
165
166 spdlog::default_logger()->flush();
167 }
#define MXL_ERROR(...)
Definition Logging.hpp:67
#define MXL_WARN(...)
Definition Logging.hpp:56
mxlFlowWriter writer

◆ Instance() [2/3]

mxl::lib::Instance::Instance ( Instance && )
delete

◆ Instance() [3/3]

mxl::lib::Instance::Instance ( Instance const & )
delete

Member Function Documentation

◆ createFlowSynchronizationGroup()

FlowSynchronizationGroup * mxl::lib::Instance::createFlowSynchronizationGroup ( )

Create a flow synchronization group.

Returns
A pointer to the created flow synchronization group.
Note
Please note that each successful call to this method must be paired with a corresponding call to releaseFlowSynchronizationGroup().

Definition at line 443 of file Instance.cpp.

444 {
445 return &_syncGroups.emplace_front();
446 }

◆ createFlowWriter()

std::tuple< mxlFlowConfigInfo, FlowWriter *, bool > mxl::lib::Instance::createFlowWriter ( std::string const & flowDef,
std::optional< std::string > options = {} )
Parameters
[in]flowDefThe json flow definition according to the NMOS Flow Resource json schema
[in]optionsAdditional options for flow creation

Definition at line 239 of file Instance.cpp.

240 {
241 auto const lock = std::scoped_lock{_mutex};
242 auto const parser = FlowParser{flowDef};
243 auto const optionsParser = (options) ? FlowOptionsParser{*options} : FlowOptionsParser{};
244 auto created = false;
245 auto flowData = std::unique_ptr<FlowData>{};
246
247 if (auto const format = parser.getFormat(); mxlIsDiscreteDataFormat(format))
248 {
249 auto [rFlowData, rCreated] = createOrOpenDiscreteFlowData(flowDef, parser, optionsParser);
250 flowData = std::move(rFlowData);
251 created = rCreated;
252 }
253 else if (format == MXL_DATA_FORMAT_EVENT)
254 {
255 auto const grainRate = parser.getGrainRate();
256 auto const eventCount = _historyDuration * __int128_t{grainRate.numerator} / (1'000'000'000 * __int128_t{grainRate.denominator});
257 if ((eventCount < 2) || (eventCount > 65536))
258 {
259 throw std::invalid_argument("Invalid event count.");
260 }
261 auto [wasCreated, data] = _flowManager.createOrOpenEventFlow(
262 parser.getId(), flowDef, static_cast<std::size_t>(eventCount), grainRate, parser.getPayloadSize());
263 flowData = std::move(data);
264 created = wasCreated;
265 }
266 else if (mxlIsContinuousDataFormat(format))
267 {
268 auto [rFlowData, rWasCreated] = createOrOpenContinuousFlowData(flowDef, parser, optionsParser);
269 flowData = std::move(rFlowData);
270 created = rWasCreated;
271 }
272 else
273 {
274 throw std::runtime_error("Invalid flow format.");
275 }
276
277 auto id = uuids::uuid{flowData->flowInfo()->config.common.id};
278 auto flowConfigInfo = flowData->flowInfo()->config;
279
280 if (auto const pos = _writers.find(id); pos != _writers.end())
281 {
282 auto& v = (*pos).second;
283 v.addReference();
284 return {flowConfigInfo, v.get(), created};
285 }
286 else
287 {
288 auto writer = _flowIoFactory->createFlowWriter(_flowManager, id, std::move(flowData));
289
290 return {flowConfigInfo, (*_writers.try_emplace(pos, id, std::move(writer))).second.get(), created};
291 }
292 }
std::pair< std::unique_ptr< FlowData >, bool > createOrOpenDiscreteFlowData(std::string const &flowDef, FlowParser const &, FlowOptionsParser const &)
Definition Instance.cpp:294
std::pair< std::unique_ptr< FlowData >, bool > createOrOpenContinuousFlowData(std::string const &flowDef, FlowParser const &, FlowOptionsParser const &)
Definition Instance.cpp:318
int mxlIsContinuousDataFormat(int format)
Definition dataformat.h:106
int mxlIsDiscreteDataFormat(int format)
Definition dataformat.h:75
@ MXL_DATA_FORMAT_EVENT
Asynchronous queue of complete events or event fragments.
Definition dataformat.h:30
auto flowDef

◆ createOrOpenContinuousFlowData()

std::pair< std::unique_ptr< FlowData >, bool > mxl::lib::Instance::createOrOpenContinuousFlowData ( std::string const & flowDef,
FlowParser const & parser,
FlowOptionsParser const & optionsParser )
private

Definition at line 318 of file Instance.cpp.

320 {
321 // Read the mandatory grain_rate field
322 auto const sampleRate = parser.getGrainRate();
323 // Compute the buffer length based on our configured history duration.
324 // The length is divided by 500M instead of 1B to effectively make it twice the
325 // history duration, which is necessary, because only half of the buffer is
326 // accessible for reading at any one point in time.
327 auto const bufferLength = _historyDuration * sampleRate.numerator / (500'000'000ULL * sampleRate.denominator);
328
329 auto const sampleWordSize = parser.getPayloadSize();
330 // FIXME: The page size is just an educated guess to round to for good measure
331 auto const lengthPerPage = 4096U / sampleWordSize;
332
333 auto const pageAlignedLength = ((bufferLength + lengthPerPage - 1U) / lengthPerPage) * lengthPerPage;
334
335 // Default to 10ms worth of samples
336 auto batchSizeDefault = parser.getGrainRate().numerator / (100U * parser.getGrainRate().denominator);
337
338 auto [created, flowData] = _flowManager.createOrOpenContinuousFlow(parser.getId(),
339 flowDef,
340 parser.getFormat(),
341 sampleRate,
342 parser.getChannelCount(),
343 sampleWordSize,
344 pageAlignedLength,
345 optionsParser.getMaxSyncBatchSizeHint().value_or(batchSizeDefault),
346 optionsParser.getMaxCommitBatchSizeHint().value_or(batchSizeDefault));
347
348 return {std::move(flowData), created};
349 }

◆ createOrOpenDiscreteFlowData()

std::pair< std::unique_ptr< FlowData >, bool > mxl::lib::Instance::createOrOpenDiscreteFlowData ( std::string const & flowDef,
FlowParser const & parser,
FlowOptionsParser const & optionsParser )
private

Definition at line 294 of file Instance.cpp.

296 {
297 // Read the mandatory grain_rate field
298 auto const grainRate = parser.getGrainRate();
299 // Compute the grain count based on our configured history duration
300 auto const grainCount = _historyDuration * grainRate.numerator / (1'000'000'000ULL * grainRate.denominator);
301
302 auto const batchSizeDefault = parser.getTotalPayloadSlices();
303
304 auto [created, flowData] = _flowManager.createOrOpenDiscreteFlow(parser.getId(),
305 flowDef,
306 parser.getFormat(),
307 grainCount,
308 grainRate,
309 parser.getPayloadSize(),
310 parser.getTotalPayloadSlices(),
311 parser.getPayloadSliceLengths(),
312 optionsParser.getMaxSyncBatchSizeHint().value_or(batchSizeDefault),
313 optionsParser.getMaxCommitBatchSizeHint().value_or(batchSizeDefault));
314
315 return {std::move(flowData), created};
316 }

◆ garbageCollect()

std::size_t mxl::lib::Instance::garbageCollect ( ) const

Garbage collect the inactive flows. This will remove any flows that are not being used by any readers or writers.

Returns
The number of flows that were removed.

Definition at line 364 of file Instance.cpp.

365 {
366 auto count = std::size_t{};
367 try
368 {
369 auto const base = std::filesystem::path{_flowManager.getDomain()};
370 if (!is_directory(base))
371 {
372 MXL_DEBUG("MXL domain {} does not exist or is not a directory", base.string());
373 return count;
374 }
375 for (auto const& entry : std::filesystem::directory_iterator{base})
376 {
377 if (!is_directory(entry) || (entry.path().extension() != mxl::lib::FLOW_DIRECTORY_NAME_SUFFIX))
378 {
379 continue;
380 }
381 auto const flowDataFile = mxl::lib::makeFlowDataFilePath(_flowManager.getDomain(), entry.path().stem().string());
382 if (!std::filesystem::exists(flowDataFile))
383 {
384 MXL_DEBUG("Flow data file {} does not exist", flowDataFile.string());
385 continue;
386 }
387
388#ifdef __APPLE__
389 constexpr auto flags = O_RDONLY | O_CLOEXEC;
390#else
391 constexpr auto flags = O_RDONLY | O_CLOEXEC | O_NOATIME;
392#endif
393 auto const fd = ::open(flowDataFile.c_str(), flags);
394 // An exclusive lock indicates that no producer is using the flow.
395 auto const active = ::flock(fd, LOCK_EX | LOCK_NB) < 0;
396 ::close(fd);
397 if (active)
398 {
399 continue;
400 }
401 auto ec = std::error_code{};
402 std::filesystem::remove_all(entry.path(), ec);
403 if (ec)
404 {
405 MXL_DEBUG("Failed to remove '{}': {} (error code {})", entry.path().string(), ec.message(), ec.value());
406 continue;
407 }
408 ++count;
409 }
410 }
411 catch (std::exception const& e)
412 {
413 MXL_DEBUG("Failed to perform garbage collection: {}", e.what());
414 }
415 catch (...)
416 {
417 MXL_DEBUG("Failed to perform garbage collection");
418 }
419 return count;
420 }
std::filesystem::path makeFlowDataFilePath(std::filesystem::path const &flowDirectory)
Definition PathUtils.cpp:17
constexpr auto const FLOW_DIRECTORY_NAME_SUFFIX
Definition PathUtils.hpp:14
std::size_t count(uuids::uuid id) const noexcept
Returns the number of writers registered for flow id 'id'.
bool active
gInfo flags
Mark the grain as invalid.

◆ getDomain()

std::string mxl::lib::Instance::getDomain ( ) const

Accessor for the domain path

Returns
The path to the MXL domain of this instance

Definition at line 351 of file Instance.cpp.

352 {
353 return _flowManager.getDomain();
354 }

◆ getFlowDef()

std::string mxl::lib::Instance::getFlowDef ( uuids::uuid const & flowId) const

See details in FlowManager::getFlowDef.

Definition at line 356 of file Instance.cpp.

357 {
358 return _flowManager.getFlowDef(flowId);
359 }
auto const flowId

◆ getFlowReader()

FlowReader * mxl::lib::Instance::getFlowReader ( std::string const & flowId)

Create a FlowReader or obtain an additional reference to a previously created FlowReader.

Parameters
[in]flowIdThe id of the flow to obtain a reader for
Returns
A pointer to the created flow reader.
Note
Please note that each successful call to this method must be paired with a corresponding call to releaseReader().
Exceptions
std::invalid_argumentif flowId is not a valid UUID.

Definition at line 169 of file Instance.cpp.

170 {
171 auto const id = uuids::uuid::from_string(flowId);
172 if (!id.has_value())
173 {
174 throw std::invalid_argument{"Invalid flow id: '" + flowId + "'."};
175 }
176
177 auto const lock = std::scoped_lock{_mutex};
178 if (auto const pos = _readers.find(*id); pos != _readers.end())
179 {
180 auto& v = (*pos).second;
181 v.addReference();
182 return v.get();
183 }
184 else
185 {
186 auto flowData = _flowManager.openFlow(*id, AccessMode::READ_ONLY);
187 auto reader = _flowIoFactory->createFlowReader(_flowManager, *id, std::move(flowData));
188
189 return (*_readers.try_emplace(pos, *id, std::move(reader))).second.get();
190 }
191 }
mxlFlowReader reader

◆ getHistoryDurationNs()

std::uint64_t mxl::lib::Instance::getHistoryDurationNs ( ) const

Accessor for the history duration value

Returns
The history duration in nanoseconds

Definition at line 438 of file Instance.cpp.

439 {
440 return _historyDuration;
441 }

◆ operator=() [1/2]

Instance & mxl::lib::Instance::operator= ( Instance && )
delete

◆ operator=() [2/2]

Instance & mxl::lib::Instance::operator= ( Instance const & )
delete

◆ parseOptions()

void mxl::lib::Instance::parseOptions ( std::string const & options)
private

Parses the options json string (if non empty) and merges it with the optional domain-wide options (if defined in the domain). Values defined at the instance level will override the domain-wide value.

Parameters
optionsThe options json string

Definition at line 422 of file Instance.cpp.

423 {
424 _historyDuration = readDomainHistoryDuration(makeDomainOptionsFilePath(_flowManager.getDomain()), _historyDuration);
425
426 // Instance options are validated but do not override domain history duration.
427 if (!options.empty())
428 {
429 auto config = picojson::object{};
430 if (!parseOptionsJson(options, config))
431 {
432 MXL_ERROR("Failed to parse instance specific options: {}", options);
433 }
434 }
435 MXL_DEBUG("History duration set to {} ns", _historyDuration);
436 }
std::filesystem::path makeDomainOptionsFilePath(std::filesystem::path const &domain)
Definition PathUtils.cpp:59

◆ releaseFlowSynchronizationGroup()

void mxl::lib::Instance::releaseFlowSynchronizationGroup ( FlowSynchronizationGroup const * group)

Release a reference to a flow synchronization group in order to free all resources associated with it.

Parameters
[in]groupa pointer to a flow synchronization group previously obtained by a call to createFlowSynchronizationGroup().

Definition at line 448 of file Instance.cpp.

449 {
450 auto prev = _syncGroups.before_begin();
451 for (auto current = std::next(prev); current != _syncGroups.end(); ++current)
452 {
453 if (&(*current) == group)
454 {
455 _syncGroups.erase_after(prev);
456 return;
457 }
458 prev = current;
459 }
460 }

◆ releaseReader()

void mxl::lib::Instance::releaseReader ( FlowReader * reader)

Release a reference to a FlowReader in order to ultimately free all resources associated with it, once the last reference is dropped.

Parameters
[in]readera pointer to a reader previously obtained by a call to getFlowReader.

Definition at line 193 of file Instance.cpp.

194 {
195 if (reader)
196 {
197 auto const& id = reader->getId();
198
199 auto const lock = std::scoped_lock{_mutex};
200 if (auto const pos = _readers.find(id); pos != _readers.end())
201 {
202 if ((*pos).second.releaseReference())
203 {
204 // Remove from the synchronization groups
205 for (auto& group : _syncGroups)
206 {
207 group.removeReader(*reader);
208 }
209 _readers.erase(pos);
210 }
211 }
212 }
213 }

◆ releaseWriter()

void mxl::lib::Instance::releaseWriter ( FlowWriter * writer)

Release a reference to a FlowWriter in order to ultimately free all resources associated with it, once the last reference is dropped.

Parameters
[in]writera pointer to a writer previously obtained by a call to getFlowWriter.

Definition at line 215 of file Instance.cpp.

216 {
217 if (writer)
218 {
219 auto const id = writer->getId();
220 {
221 auto const lock = std::scoped_lock{_mutex};
222 if (auto const pos = _writers.find(id); pos != _writers.end())
223 {
224 if ((*pos).second.releaseReference())
225 {
226 // Delete the flow if we are the last writer.
227 if (writer->isExclusive() || writer->makeExclusive())
228 {
229 _flowManager.deleteFlow(id);
230 }
231
232 _writers.erase(pos);
233 }
234 }
235 }
236 }
237 }

Member Data Documentation

◆ _flowIoFactory

std::unique_ptr<FlowIoFactory> mxl::lib::Instance::_flowIoFactory
private

The I/O factor used to delegate the creation of readers and writers.

Definition at line 170 of file Instance.hpp.

◆ _flowManager

FlowManager mxl::lib::Instance::_flowManager
private

Performs flow CRUD operations.

Definition at line 167 of file Instance.hpp.

◆ _historyDuration

std::uint64_t mxl::lib::Instance::_historyDuration
private

Ring buffer history duration in nanoseconds.

Definition at line 187 of file Instance.hpp.

◆ _mutex

std::mutex mxl::lib::Instance::_mutex
private

Protects the maps.

Definition at line 178 of file Instance.hpp.

◆ _options

std::string mxl::lib::Instance::_options
private

For future use.

Definition at line 184 of file Instance.hpp.

◆ _readers

std::map<uuids::uuid, RefCounted<FlowReader> > mxl::lib::Instance::_readers
private

Maps flow uuids to flow readers.

Definition at line 173 of file Instance.hpp.

◆ _stopping

std::atomic_bool mxl::lib::Instance::_stopping
private

Definition at line 191 of file Instance.hpp.

◆ _syncGroups

std::forward_list<FlowSynchronizationGroup> mxl::lib::Instance::_syncGroups
private

The set of active flow synchronization groups.

Definition at line 181 of file Instance.hpp.

◆ _watcher

DomainWatcher::ptr mxl::lib::Instance::_watcher
private

Definition at line 189 of file Instance.hpp.

◆ _writers

std::map<uuids::uuid, RefCounted<FlowWriter> > mxl::lib::Instance::_writers
private

Maps flow uuids to flow writers.

Definition at line 175 of file Instance.hpp.


The documentation for this class was generated from the following files: