MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
mxl::lib::fabrics::ofi::RCTarget Class Reference

Reliable Connected (RC) Target implementation. More...

#include <RCTarget.hpp>

Inheritance diagram for mxl::lib::fabrics::ofi::RCTarget:
Collaboration diagram for mxl::lib::fabrics::ofi::RCTarget:

Classes

struct  Closed
 The closed state. More...
struct  Connected
 The connected state. More...
struct  Draining
 The draining state. More...
struct  WaitForConnection
 The wait for connection state. More...
struct  WaitForConnectionRequest
 The wait for connection request state. More...

Public Member Functions

virtual std::optional< Target::ReadResult > read ()
 Determine if new data can be consumed.
virtual std::optional< Target::ReadResult > readBlocking (std::chrono::steady_clock::duration timeout) final
 Determine if new data can be consumed.
virtual void shutdown () final
 Shut down the target gracefully. Initiates a graceful shutdown of the target and blocks until the shutdown is complete. Can throw an exception if the shutdown is not successful. If this function throws the target can now longer be used.
Public Member Functions inherited from mxl::lib::fabrics::ofi::Target
virtual ~Target ()=default

Static Public Member Functions

static std::pair< std::unique_ptr< RCTarget >, std::unique_ptr< TargetInfo > > setup (mxlFabricsTargetConfig const &config, FabricInfoView info, TargetSetupOptions const &options={})
 Set up a fresh RCTarget and its associated TargetInfo based on the given configuration.

Private Types

using State = std::variant<WaitForConnectionRequest, WaitForConnection, Connected, Draining, Closed>
 The internal state of the RCTarget.

Private Member Functions

State drain (Draining state, std::optional< Target::ReadResult > &result)
 Read the completions that are left after the Initiator closed the connection.
 RCTarget (PassiveEndpoint pep, std::unique_ptr< IngressProtocol > proto, std::shared_ptr< Domain > domain, TargetSetupOptions options)
 Construct a new RCTarget associated with the given domain and passive endpoint.
template<QueueReadMode>
std::optional< Target::ReadResult > readNext (std::chrono::steady_clock::duration timeout)
 Internal method to drive progress based on the current state.
void rejectPendingConnectionRequests ()
 Reject all connection requests that are queued on the passive endpoint.

Static Private Member Functions

static PassiveEndpoint makeListener (std::shared_ptr< Fabric > const &fabric)

Private Attributes

std::shared_ptr< Domain > _domain
PassiveEndpoint _pep
std::unique_ptr< IngressProtocol > _proto
TargetSetupOptions _setupOptions
State _state

Static Private Attributes

static constexpr auto ShutdownTimeout = std::chrono::seconds(2)
 Upper bound for waiting on the local shutdown event in shutdown().

Additional Inherited Members

Public Types inherited from mxl::lib::fabrics::ofi::Target
using ReadResult = std::variant<GrainReadResult, SampleReadResult, Interrupted>

Detailed Description

Reliable Connected (RC) Target implementation.

An RC Target uses connection-oriented endpoint type. It listens for incoming connection requests from an Initiator to establish connection. Once connected, it polls its completion queues to see if new data can be consumed. be read from the connected endpoint.

Definition at line 23 of file RCTarget.hpp.

Member Typedef Documentation

◆ State

The internal state of the RCTarget.

Definition at line 90 of file RCTarget.hpp.

Constructor & Destructor Documentation

◆ RCTarget()

mxl::lib::fabrics::ofi::RCTarget::RCTarget ( PassiveEndpoint pep,
std::unique_ptr< IngressProtocol > proto,
std::shared_ptr< Domain > domain,
TargetSetupOptions options )
private

Construct a new RCTarget associated with the given domain and passive endpoint.

Parameters
domainThe domain to create the RCTarget on.
pepThe passive endpoint to use for listening for incoming connection requests.
optionsThe setup options applied when the completion queue is created for the accepted connection.

Definition at line 59 of file RCTarget.cpp.

60 : _pep(std::move(pep))
61 , _proto(std::move(proto))
62 , _domain(std::move(domain))
63 , _setupOptions(options)
65 {}
std::shared_ptr< Domain > _domain
Definition RCTarget.hpp:138
std::unique_ptr< IngressProtocol > _proto
Definition RCTarget.hpp:137
TargetSetupOptions _setupOptions
Definition RCTarget.hpp:139
The wait for connection request state.
Definition RCTarget.hpp:51

Member Function Documentation

◆ drain()

RCTarget::State mxl::lib::fabrics::ofi::RCTarget::drain ( Draining state,
std::optional< Target::ReadResult > & result )
nodiscardprivate

Read the completions that are left after the Initiator closed the connection.

Parameters
stateThe draining state.
resultReceives the result of the first completion that produces one.
Returns
The draining state if a result was found, otherwise a new WaitForConnectionRequest state.

Definition at line 229 of file RCTarget.cpp.

230 {
231 // The connection is closed, so no new completions are expected. Read the queue without blocking until it returns a result or is
232 // empty. Completions of receive buffers that were cancelled by the shutdown produce no result.
233 while (auto completion = state.ep.completionQueue()->read())
234 {
235 try
236 {
237 result = _proto->read(state.ep, *completion);
238 }
239 catch (FabricException const& ex)
240 {
241 // The protocol posts a new receive buffer before it decodes the completion. Some providers refuse new receive buffers on a
242 // closed connection.
243 MXL_WARN("Failed to read a completion after the connection was shut down: {}", ex.what());
244 }
245
246 if (result)
247 {
248 return state;
249 }
250 }
251
252 MXL_INFO("Transitioning to listening to new connection.");
255 }
#define MXL_WARN(...)
Definition Logging.hpp:56
#define MXL_INFO(...)
Definition Logging.hpp:45
void rejectPendingConnectionRequests()
Reject all connection requests that are queued on the passive endpoint.
Definition RCTarget.cpp:257

◆ makeListener()

PassiveEndpoint mxl::lib::fabrics::ofi::RCTarget::makeListener ( std::shared_ptr< Fabric > const & fabric)
staticnodiscardprivate

Definition at line 270 of file RCTarget.cpp.

271 {
272 // Create a passive endpoint. A passive endpoint can be viewed like a bound TCP socket listening for
273 // incoming connections.
274 auto pep = PassiveEndpoint::create(fabric);
275
276 // Create an event queue for the passive endpoint. Incoming connections generate an entry in the event queue
277 // and be picked up when the Target tries to make progress.
279
280 // Transition the PassiveEndpoint into a listening state. Connections will be accepted from now on.
281 pep.listen();
282
283 return pep;
284 }
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.
static PassiveEndpoint create(std::shared_ptr< Fabric > fabric)
Allocate a new PassiveEndpoint associated with the given Fabric.
static Attributes defaults()
Creates a configuration with all values set to reasonable defaults.

◆ read()

std::optional< Target::ReadResult > mxl::lib::fabrics::ofi::RCTarget::read ( )
virtual

Determine if new data can be consumed.

A non-blocking operation that also drives the connection forward. Continuous invocation of this function is necessary for connection establishment and ongoing progress.

Implements mxl::lib::fabrics::ofi::Target.

Definition at line 67 of file RCTarget.cpp.

68 {
69 return readNext<QueueReadMode::NonBlocking>(std::chrono::steady_clock::duration::zero());
70 }
std::optional< Target::ReadResult > readNext(std::chrono::steady_clock::duration timeout)
Internal method to drive progress based on the current state.
Definition RCTarget.cpp:107

◆ readBlocking()

std::optional< Target::ReadResult > mxl::lib::fabrics::ofi::RCTarget::readBlocking ( std::chrono::steady_clock::duration timeout)
finalvirtual

Determine if new data can be consumed.

A blocking version of readGrain. see readGrain().

Implements mxl::lib::fabrics::ofi::Target.

Definition at line 72 of file RCTarget.cpp.

73 {
75 }

◆ readNext()

template<QueueReadMode queueReadMode>
std::optional< Target::ReadResult > mxl::lib::fabrics::ofi::RCTarget::readNext ( std::chrono::steady_clock::duration timeout)
private

Internal method to drive progress based on the current state.

Parameters
timeoutThe maximum duration to block waiting for progress.
Returns
The result of the read operation.

Definition at line 107 of file RCTarget.cpp.

108 {
109 auto result = std::optional<Target::ReadResult>{std::nullopt};
110
111 _state = std::visit(
112 overloaded{
113 [](std::monostate) -> State { throw Exception::invalidState("Target is in an invalid state and can no longer make progress"); },
114 [&](WaitForConnectionRequest state) -> State
115 {
116 try
117 {
118 auto event = readEventQueue<queueReadMode>(*_pep.eventQueue(), timeout);
119
120 // Check if the entry is available and is a connection request
121 if (event && event->isConnReq())
122 {
123 auto remoteAddr = FabricAddress::fromDestination(event->connReq().info());
124 MXL_INFO("Accept connection from: {}", remoteAddr.toString());
125
127 cqAttr.size = _setupOptions.cqDepth.value_or(CompletionQueue::Attributes::DEFAULT_SIZE);
128 auto cq = CompletionQueue::open(_domain, cqAttr);
129 auto endpoint = Endpoint::create(_domain, _pep.id(), event->connReq().info());
130 endpoint.bind(cq, FI_RECV);
131
133 endpoint.bind(eq);
134
135 // we are now ready to accept the connection
136 endpoint.accept();
137 MXL_DEBUG("Accepted the connection waiting for connected event notification.");
138
139 // Return the new state as the variant type
140 return RCTarget::WaitForConnection{std::move(endpoint)};
141 }
142
143 return state;
144 }
145 catch (FabricException const& ex)
146 {
147 if (ex.isInterrupted())
148 {
149 result = std::make_optional<Target::Interrupted>();
150 return state;
151 }
152
153 throw;
154 }
155 },
156 [&](WaitForConnection state) -> State
157 {
158 try
159 {
160 auto event = readEventQueue<queueReadMode>(*state.ep.eventQueue(), timeout);
161
162 if (event && event->isConnected())
163 {
164 MXL_INFO("Received connected event notification, now connected.");
165
166 // We have a connected event, so we can transition to the connected state
167 auto connected = Connected{.ep = std::move(state.ep)};
168
169 // The endpoint is now ready, initialize the protocol.
170 _proto->start(connected.ep);
171
172 return connected;
173 }
174
175 return WaitForConnection{std::move(state.ep)};
176 }
177 catch (FabricException const& ex)
178 {
179 if (ex.isInterrupted())
180 {
181 result = std::make_optional<Target::Interrupted>();
182 return WaitForConnection{.ep = std::move(state.ep)};
183 }
184
185 throw;
186 }
187 },
188 [&](RCTarget::Connected state) -> State
189 {
190 try
191 {
192 auto [completion, event] = readEndpointQueues<queueReadMode>(state.ep, timeout);
193
194 // A completion that was read together with the shutdown event belongs to data that has already arrived.
195 if (completion)
196 {
197 result = _proto->read(state.ep, *completion);
198 }
199
200 if (event && event.value().isShutdown())
201 {
202 MXL_INFO("Remote endpoint has shutdown the connection.");
203 catchAndLogFabricError([&]() { state.ep.shutdown(); },
204 "Failed to shut down the endpoint after the remote endpoint closed it");
205 return Draining{.ep = std::move(state.ep)};
206 }
207
208 return Connected{.ep = std::move(state.ep)};
209 }
210 catch (FabricException const& ex)
211 {
212 if (ex.isInterrupted())
213 {
214 result = std::make_optional<Target::Interrupted>();
215 return Connected{.ep = std::move(state.ep)};
216 }
217
218 throw;
219 }
220 },
221 [&](RCTarget::Draining state) -> State { return drain(std::move(state), result); },
222 [](RCTarget::Closed) -> State { throw Exception::invalidState("Target has been shut down and can no longer be used."); },
223 },
224 std::move(_state));
225
226 return result;
227 }
#define MXL_DEBUG(...)
Definition Logging.hpp:34
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.
static Endpoint create(std::shared_ptr< Domain > domain, FabricInfoView info)
Allocates (active) new endpoint.
Definition Endpoint.cpp:56
static Exception invalidState(fmt::format_string< T... > fmt, T &&... args)
Make an MXL_ERR_INVALID_STATE exception.
Definition Exception.hpp:59
static FabricAddress fromDestination(FabricInfoView info) noexcept
Build a FabricAddress from the destination address of info.
State drain(Draining state, std::optional< Target::ReadResult > &result)
Read the completions that are left after the Initiator closed the connection.
Definition RCTarget.cpp:229
std::variant< WaitForConnectionRequest, WaitForConnection, Connected, Draining, Closed > State
The internal state of the RCTarget.
Definition RCTarget.hpp:90
std::optional< Event > readEventQueue(EventQueue &eq, std::chrono::steady_clock::duration timeout)
Helper to read an event queue with blocking or non-blocking behaviour.
std::pair< std::optional< Completion >, std::optional< Event > > readEndpointQueues(Endpoint &ep, std::chrono::steady_clock::duration timeout)
Helper to read both completion and event queues of an endpoint with blocking or non-blocking behaviou...
void catchAndLogFabricError(F &&fun, std::string_view msg)
static constexpr std::size_t DEFAULT_SIZE
The completion-queue depth used when no explicit depth is requested.
static Attributes defaults()
Returns the a CompletionQueueAttr with all of its attributes set to reasonable defaults.

◆ rejectPendingConnectionRequests()

void mxl::lib::fabrics::ofi::RCTarget::rejectPendingConnectionRequests ( )
private

Reject all connection requests that are queued on the passive endpoint.

The passive endpoint keeps listening while a connection is established. Requests that arrive in that time are rejected when the target goes back to waiting for a connection request.

Definition at line 257 of file RCTarget.cpp.

258 {
259 while (auto event = _pep.eventQueue()->read())
260 {
261 if (event->isConnReq())
262 {
263 MXL_INFO("Reject connection request from {} that arrived while connected.",
264 FabricAddress::fromDestination(event->connReq().info()).toString());
265 _pep.reject(*event);
266 }
267 }
268 }
std::string toString() const
Format the address exactly as libfabric's internal ofi_straddr.

◆ setup()

std::pair< std::unique_ptr< RCTarget >, std::unique_ptr< TargetInfo > > mxl::lib::fabrics::ofi::RCTarget::setup ( mxlFabricsTargetConfig const & config,
FabricInfoView info,
TargetSetupOptions const & options = {} )
staticnodiscard

Set up a fresh RCTarget and its associated TargetInfo based on the given configuration.

Parameters
configThe configuration to use for setting up the target.
optionsOptional tuning parameters (e.g. completion queue depth).
Returns
A pair consisting of the newly setup RCTarget and its associated TargetInfo.

Definition at line 22 of file RCTarget.cpp.

24 {
25 requireCapability(info, FI_REMOTE_WRITE, "Interface is missing required remote write capability");
26 auto provider = providerFromString(info->fabric_attr->prov_name);
27 if (!provider)
28 {
29 throw Exception::invalidArgument("invalid provider: {}", info->fabric_attr->prov_name);
30 }
31
32 MXL_INFO("Setting up RC target with source address: {}", FabricAddress::fromSource(info).toString());
33
34 // Open fabric and domain. These represent the context of the local network fabric adapter that will be used
35 // to receive data.
36 // See fi_domain(3) and fi_fabric(3) for more complete information about these concepts.
37 auto fabric = Fabric::open(info);
38 auto domain = Domain::open(fabric);
39
40 auto pep = makeListener(fabric);
41
42 auto const mxlRegions = MxlRegions::forWriter(config.writer);
43 auto proto = selectIngressProtocol(mxlRegions.dataLayout(), mxlRegions.regions(), mxlRegions.maxSyncBatchSize());
44 auto targetInfo = std::make_unique<TargetInfo>(
45 pep.id(), pep.localAddress(), *provider, proto->registerMemory(domain), proto->bounceBufferInfo());
46
47 // Helper struct to enable the std::make_unique function to access the private constructor of this class.
48 struct MakeUniqueEnabler : RCTarget
49 {
50 MakeUniqueEnabler(PassiveEndpoint pep, std::unique_ptr<IngressProtocol> proto, std::shared_ptr<Domain> domain, TargetSetupOptions options)
51 : RCTarget(std::move(pep), std::move(proto), std::move(domain), options)
52 {}
53 };
54
55 // Return the constructed RCTarget and associated TargetInfo for remote peers to connect.
56 return {std::make_unique<MakeUniqueEnabler>(std::move(pep), std::move(proto), std::move(domain), options), std::move(targetInfo)};
57 }
static std::shared_ptr< Domain > open(std::shared_ptr< Fabric > fabric)
Open a new domain associated with the specified fabric.
Definition Domain.cpp:30
static Exception invalidArgument(fmt::format_string< T... > fmt, T &&... args)
Make an MXL_ERR_INVALID_ARG exception.
Definition Exception.hpp:43
static FabricAddress fromSource(FabricInfoView info) noexcept
Build a FabricAddress from the source address of info.
static std::shared_ptr< Fabric > open(FabricInfoView info)
Open a fabric object based on the provided FabricInfoView.
Definition Fabric.cpp:15
static MxlRegions forWriter(mxlFlowWriter)
Definition Region.cpp:110
RCTarget(PassiveEndpoint pep, std::unique_ptr< IngressProtocol > proto, std::shared_ptr< Domain > domain, TargetSetupOptions options)
Construct a new RCTarget associated with the given domain and passive endpoint.
Definition RCTarget.cpp:59
static PassiveEndpoint makeListener(std::shared_ptr< Fabric > const &fabric)
Definition RCTarget.cpp:270
std::optional< Provider > providerFromString(std::string const &s) noexcept
Parse a provider name string, and return the enum value.
Definition Provider.cpp:49
std::unique_ptr< IngressProtocol > selectIngressProtocol(DataLayout const &layout, std::vector< Region > regions, std::uint32_t maxSyncBatchSize)
Select an appropriate ingress protocol based on the data layout.
Definition Protocol.cpp:13
void requireCapability(FabricInfoView info, std::uint64_t cap, std::string_view message)

◆ shutdown()

void mxl::lib::fabrics::ofi::RCTarget::shutdown ( )
finalvirtual

Shut down the target gracefully. Initiates a graceful shutdown of the target and blocks until the shutdown is complete. Can throw an exception if the shutdown is not successful. If this function throws the target can now longer be used.

Closes the connection if there is one and waits for the local shutdown event. The target can no longer be used afterwards.

Implements mxl::lib::fabrics::ofi::Target.

Definition at line 77 of file RCTarget.cpp.

78 {
79 if (auto state = std::get_if<Connected>(&_state); state != nullptr)
80 {
81 MXL_INFO("Shutting down the connection.");
82 state->ep.shutdown();
83
84 auto const deadline = std::chrono::steady_clock::now() + ShutdownTimeout;
85 for (;;)
86 {
87 auto const remaining = deadline - std::chrono::steady_clock::now();
88 if (remaining <= std::chrono::steady_clock::duration::zero())
89 {
90 MXL_WARN("Did not receive a shutdown event within {} ms.",
91 std::chrono::duration_cast<std::chrono::milliseconds>(ShutdownTimeout).count());
92 break;
93 }
94
95 auto const event = state->ep.eventQueue()->readBlocking(remaining);
96 if (event && (event->isShutdown() || event->isError()))
97 {
98 break;
99 }
100 }
101 }
102
103 _state = Closed{};
104 }
static constexpr auto ShutdownTimeout
Upper bound for waiting on the local shutdown event in shutdown().
Definition RCTarget.hpp:94
std::size_t count(uuids::uuid id) const noexcept
Returns the number of writers registered for flow id 'id'.

Member Data Documentation

◆ _domain

std::shared_ptr<Domain> mxl::lib::fabrics::ofi::RCTarget::_domain
private

Definition at line 138 of file RCTarget.hpp.

◆ _pep

PassiveEndpoint mxl::lib::fabrics::ofi::RCTarget::_pep
private

The passive endpoint lives as long as the target. Its address and id are published in the TargetInfo, so it is not re-created after a disconnect. A new passive endpoint can bind to a different port.

Definition at line 136 of file RCTarget.hpp.

◆ _proto

std::unique_ptr<IngressProtocol> mxl::lib::fabrics::ofi::RCTarget::_proto
private

Definition at line 137 of file RCTarget.hpp.

◆ _setupOptions

TargetSetupOptions mxl::lib::fabrics::ofi::RCTarget::_setupOptions
private

Setup options applied when accepting connections.

Definition at line 139 of file RCTarget.hpp.

◆ _state

State mxl::lib::fabrics::ofi::RCTarget::_state
private

The current state of the RCTarget.

Definition at line 140 of file RCTarget.hpp.

◆ ShutdownTimeout

auto mxl::lib::fabrics::ofi::RCTarget::ShutdownTimeout = std::chrono::seconds(2)
staticconstexprprivate

Upper bound for waiting on the local shutdown event in shutdown().

Definition at line 94 of file RCTarget.hpp.


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