14#include <rdma/fabric.h>
30 ,
_state(
Idle{.ep = std::move(ep), .idleSince = std::chrono::steady_clock::time_point{}})
40 return std::holds_alternative<Idle>(
_state);
45 return std::holds_alternative<Done>(
_state);
52 [](std::monostate) {
return false; },
53 [](
Idle const&) {
return false; },
57 [](
Flushing const&) {
return true; },
59 [](
Done const&) {
return false; },
70 MXL_INFO(
"Shutdown requested while waiting to activate, aborting.");
75 MXL_INFO(
"Shutdown requested while trying to connect, aborting.");
81 auto pending =
_proto->reset();
88 MXL_INFO(
"Shutdown requested while the endpoint is already flushing.");
93 [](
Done state) ->
State {
return state; },
100 auto const state = std::get_if<Flushing>(&
_state);
101 if (state ==
nullptr)
106 auto const nextName = [next = state->next]()
116 if (state->shutdownReceived && (state->pending == 0))
118 MXL_INFO(
"Flushing complete, transitioning to {} state.", nextName);
120 else if (std::chrono::steady_clock::now() >= state->deadline)
122 MXL_WARN(
"Flushing timed out with {} outstanding operations, shutdown event received: {}. Transitioning to {} state.",
124 state->shutdownReceived,
142 return Flushing{.ep = std::move(ep),
144 .shutdownReceived = shutdownReceived,
146 .deadline = std::chrono::steady_clock::now() +
FlushTimeout};
156 auto idleDuration = std::chrono::steady_clock::now() - state.idleSince;
157 if (idleDuration < std::chrono::seconds(5))
162 MXL_INFO(
"Endpoint has been idle for {}ms, activating",
163 std::chrono::duration_cast<std::chrono::milliseconds>(idleDuration).
count());
167 state.ep.bind(cq, FI_TRANSMIT);
170 auto const faddr =
_info.fabricAddress.decode();
171 MXL_INFO(
"Connecting to {}", faddr.toString());
172 state.ep.connect(
_info.fabricAddress);
179 [](
Done state) ->
State {
return state; },
188 [](
Idle state) ->
State {
return state; },
200 MXL_INFO(
"Endpoint is now connected");
201 return Connected{.ep = std::move(state.ep)};
205 MXL_WARN(
"Received a shutdown event while connecting, going idle");
211 MXL_WARN(
"Received an unexpected event while establishing a connection");
218 MXL_WARN(
"Received an error event in connected state, going idle after flushing. Error: {}", ev.
error().
toString());
219 catchAndLogFabricError([&]() { state.ep.shutdown(); },
"Failed to shut down the endpoint after an error event");
226 MXL_INFO(
"Remote endpoint has closed the connection.");
228 "Failed to shut down the endpoint after the remote endpoint closed it");
238 MXL_INFO(
"Received a shutdown event while flushing the completion queue");
239 state.shutdownReceived =
true;
245 state.shutdownReceived =
true;
249 MXL_ERROR(
"Received an unexpected event while shutting down");
254 [](
Done state) ->
State {
return state; },
261 auto const error = completion.
tryErr();
265 [](
Idle const&) {
MXL_WARN(
"Received a completion event while idle, ignoring."); },
266 [](
Connecting const&) {
MXL_WARN(
"Received a completion event while connecting, ignoring."); },
272 MXL_ERROR(
"Received a completion error: {}", error->toString());
274 _proto->processCompletion(completion);
281 MXL_DEBUG(
"Received a completion error while flushing: {}", error->toString());
283 if (state.pending > 0)
288 [](
Disconnected const&) {
MXL_DEBUG(
"Ignoring completion after the target closed the connection."); },
289 [](
Done const&) {
MXL_DEBUG(
"Ignoring completion after shutdown."); },
297 if (
auto const state = std::get_if<Connected>(&
_state); state !=
nullptr)
299 _proto->transferGrain(state->ep, localIndex, remoteIndex, remotePayloadOffset, sliceRange);
305 if (
auto const state = std::get_if<Connected>(&
_state); state !=
nullptr)
307 _proto->transferSamples(state->ep, headIndex,
count);
319 requireCapability(info, FI_WRITE,
"Interface is missing required write capability");
329 cqAttr.size = *options.
cqDepth;
335 proto->registerMemory(domain);
339 MakeUniqueEnabler(std::shared_ptr<Domain> domain, std::shared_ptr<CompletionQueue> cq, std::shared_ptr<EventQueue> eq,
340 std::unique_ptr<EgressProtocolTemplate> proto)
341 :
RCInitiator(std::move(domain), std::move(cq), std::move(eq), std::move(proto))
345 return std::make_unique<MakeUniqueEnabler>(std::move(domain), std::move(cq), std::move(eq), std::move(proto));
349 std::unique_ptr<EgressProtocolTemplate> proto)
353 ,
_proto(std::move(proto))
359 auto id = endpoint.id();
361 proto->registerMemory(
_domain);
368 if (
auto target = std::ranges::find_if(
_targets, [&targetInfo](
auto const& item) {
return item.second.info().id == targetInfo.
id; });
371 target->second.shutdown();
391 std::uint16_t startSlice, std::uint16_t endSlice)
400 it->second.transferGrain(localIndex, remoteIndex, payloadOffset,
SliceRange::make(startSlice, endSlice));
408 target.transferSamples(headIndex,
count);
425 if (target.hasPendingWork())
445 target.activate(
_cq,
_eq);
453 target.finishFlush();
459 std::erase_if(
_targets, [](
auto const& item) {
return item.second.canEvict(); });
466 if (timeout == std::chrono::milliseconds::zero())
477 auto completion =
_cq->readBlocking(timeout);
488 MXL_WARN(
"Received completion for an unknown endpoint");
493 ep->second.consume(*completion);
513 auto completion =
_cq->read();
523 MXL_WARN(
"Received completion for an unknown endpoint");
528 ep->second.consume(*completion);
536 auto event =
_eq->read();
546 MXL_WARN(
"Received event for an unknown endpoint");
551 ep->second.consume(*event);
584 if (std::holds_alternative<Initiator::Ready>(
makeProgress()))
591 auto deadline = std::chrono::steady_clock::now() + timeout;
596 if (std::holds_alternative<Initiator::Ready>(
makeProgress()))
603 auto timeUntilDeadline = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - std::chrono::steady_clock::now());
604 if (timeUntilDeadline <=
decltype(timeUntilDeadline){0})
611 if (std::holds_alternative<Initiator::NotReady>(res))
627 auto const deadline = std::chrono::steady_clock::now() +
ShutdownTimeout;
640 if (std::chrono::steady_clock::now() >= deadline)
Internal shared-memory headers for discrete grains and event slots.
static std::shared_ptr< CompletionQueue > open(std::shared_ptr< Domain > domain, Attributes const &attr=Attributes::defaults())
Create a new completion queue in the specified domain.
Type to represent a completion entry from a CompletionQueue.
std::optional< Error > tryErr() const noexcept
Attempt to access the error variant. Returns std::nullopt if this is a data entry.
static std::shared_ptr< Domain > open(std::shared_ptr< Fabric > fabric)
Open a new domain associated with the specified fabric.
RAII Wrapper around a libfabric endpoint (fi_ep).
static constexpr Id idFromToken(Completion::Token token) noexcept
Convert a completion token value to an endpoint id value. Convert a completion token to an endpoint i...
static Id idFromFID(::fid_t) noexcept
Read the endpoint id from a libfabric object reference.
std::shared_ptr< Domain > domain() const
Get the domain that the endpoint has beed created on.
std::uintptr_t Id
An id type that can be used to reference this endpoint from completions and events.
static Endpoint create(std::shared_ptr< Domain > domain, FabricInfoView info)
Allocates (active) new endpoint.
FabricInfoView info() const noexcept
Get the fabric information passed to Endpoint::create() initially.
Id id() const noexcept
Get the id of this endpoint.
static constexpr Completion::Token tokenFromId(Id id) noexcept
Convert an endpoint id value to a completion token value. Convert an endpoint id to a completion toke...
static std::shared_ptr< EventQueue > open(std::shared_ptr< Fabric >, Attributes const &attr=Attributes::defaults())
Create a new event queue associated with the specified fabric.
std::string toString() const
Convert the error to a human-readable string.
Type to represent an event entry from an EventQueue.
bool isConnected() const noexcept
Returns true if this event is a FI_CONNECTED.
bool isError() const noexcept
Returns true if this event is an error entry.
bool isShutdown() const noexcept
returns true if this event is a FI_SHUTDOWN
Error const & error() const
Get an error representation of the event. Throws if the event is an error. Users should previously ch...
static Exception notFound(fmt::format_string< T... > fmt, T &&... args)
Make an MXL_ERR_NOT_FOUND exception.
An internal exception type that extends.
bool isInterrupted() const noexcept
Non-owning view of a FabricInfo. Returned when iterating over a FabricInfoList.
::fi_info * raw() noexcept
Returns the raw fi_info object associated with this view.
static std::shared_ptr< Fabric > open(FabricInfoView info)
Open a fabric object based on the provided FabricInfoView.
std::variant< Ready, NotReady, Interrupted > MakeProgressResult
static MxlRegions forReader(mxlFlowReader)
A single endpoint connected to a target that will be created when the user adds a target to an initia...
std::variant< Idle, Connecting, Connected, Flushing, Disconnected, Done > State
The various states that the endpoint can be in are stored inside a variant that we move from and then...
void transferGrain(std::uint64_t localIndex, std::uint64_t remoteIndex, std::uint64_t remotePayloadOffset, SliceRange const &sliceRange)
Post a data transfer request to this endpoint.
void shutdown()
Initiate a shutdown process.
RCInitiatorEndpoint(Endpoint, std::unique_ptr< EgressProtocol > proto, TargetInfo info)
Construct a new RCInitiatorEndpoint object.
AfterFlush
The state that the endpoint goes to when a flush is complete.
static constexpr auto FlushTimeout
Upper bound for the flushing state. Some providers do not report a local shutdown event,...
void consume(Event event)
Consume an event that was posted to the associated event queue.
static Flushing startFlush(Endpoint ep, std::size_t pending, bool shutdownReceived, AfterFlush next)
Create a flushing state that waits for the given number of outstanding operations.
Idle restart(Endpoint const &endpoint)
Restarts the endpoint. Produces a new Idle state from any previous state.
void transferSamples(std::uint64_t headIndex, std::size_t count)
Post a data transfer request to this endpoint.
TargetInfo const & info() const noexcept
Get the target info of the remote endpoint.
void finishFlush()
Move the endpoint out of the flushing state when the flush is complete.
bool isIdle() const noexcept
Returns true if the endpoint is idle and could be actived.
void activate(std::shared_ptr< CompletionQueue > const &cq, std::shared_ptr< EventQueue > const &eq)
Try to activate the endpoint.
std::unique_ptr< EgressProtocol > _proto
bool canEvict() const noexcept
Returns true if the endpoint was shut down and can be evicted from the initiator.
bool hasPendingWork() const noexcept
Returns true if there is any pending events that the endpoint is waiting for, and for which the queue...
std::shared_ptr< EventQueue > _eq
void activateIfIdle(RCInitiatorEndpoint &target)
Try to activate the endpoint if it is idle. Called before a transfer is posted to the endpoint.
void evictDeadEndpoints()
Evict any dead endpoints that are no longer used.
std::unique_ptr< EgressProtocolTemplate > _proto
virtual void transferSamples(std::uint64_t headIndex, std::size_t count) final
Transfer samples to all targets.
RCInitiator(std::shared_ptr< Domain > domain, std::shared_ptr< CompletionQueue > cq, std::shared_ptr< EventQueue > eq, std::unique_ptr< EgressProtocolTemplate > proto)
Initiator::MakeProgressResult afterProgressResult() const noexcept
Returns true if any of the endpoints contained in this initiator have pending work.
virtual void addTarget(TargetInfo const &targetInfo) final
Add a target to the initiator.
virtual Initiator::MakeProgressResult makeProgressBlocking(std::chrono::steady_clock::duration) final
Attempts to progress execution, including connection management and data operations.
Initiator::MakeProgressResult blockOnCQ(std::chrono::steady_clock::duration timeout)
Block on the completion queue with a timeout.
static constexpr auto EQPollInterval
When making progress and using blocking queue reads, this is the minimum interval at which the event ...
static constexpr auto ShutdownPollInterval
Sleep time between two queue reads in shutdown().
virtual void shutdown() final
Shut down the initiator gracefully.
void activateIdleEndpoints()
Try to activate any idle endpoints.
virtual Initiator::MakeProgressResult makeProgress() final
Attempts to progress execution, including connection management and data operations.
void finishFlushingEndpoints()
Move endpoints that have finished flushing to the done state.
std::shared_ptr< CompletionQueue > _cq
virtual void transferGrain(std::uint64_t grainIndex, std::uint16_t startSlice, std::uint16_t endSlice) final
Transfer a grain to all targets.
std::map< Completion::Token, RCInitiatorEndpoint > _targets
void pollEQ()
Poll the event queue and process the returned events until the queue is empty.
std::shared_ptr< Domain > _domain
bool hasTarget() const noexcept
Returns true if the initiator has at least 1 target added no matter what the state is.
static std::unique_ptr< RCInitiator > setup(mxlFabricsInitiatorConfig const &config, FabricInfoView info, InitiatorSetupOptions const &options={})
Set up a fresh initiator without any targets assigned to it.
virtual void transferGrainToTarget(Endpoint::Id targetId, std::uint64_t localIndex, std::uint64_t remoteIndex, std::uint64_t payloadOffset, std::uint16_t startSlice, std::uint16_t endSlice) final
Transfer a grain to a specific target.
static constexpr auto ShutdownTimeout
Upper bound for shutdown(). It is longer than RCInitiatorEndpoint::FlushTimeout, so that each flush e...
virtual void removeTarget(TargetInfo const &targetInfo) final
Remove a target from the initiator.
void pollCQ()
Poll the completion queue and process the events until the queue is empty.
A SliceRange represents a range of slices within a grain.
static SliceRange make(std::uint16_t start, std::uint16_t end)
Create a SliceRange representing the range [start, end).
struct mxlFabricsInitiatorConfig_t mxlFabricsInitiatorConfig
void catchAndLogFabricError(F &&fun, std::string_view msg)
std::unique_ptr< EgressProtocolTemplate > selectEgressProtocol(DataLayout const &layout, std::vector< Region > regions)
Select an appropriate egress protocol based on the data layout.
void requireCapability(FabricInfoView info, std::uint64_t cap, std::string_view message)
constexpr auto const MXL_GRAIN_PAYLOAD_OFFSET
std::size_t count(uuids::uuid id) const noexcept
Returns the number of writers registered for flow id 'id'.
static Attributes defaults()
Returns the a CompletionQueueAttr with all of its attributes set to reasonable defaults.
Provider-independent tuning options for initiator setup.
std::optional< std::size_t > cqDepth
Desired completion-queue depth.
The endpoint is done and can be evicted from the initiator.
TargetInfo contains all the information required by an initiator to operate transfers to the given ta...