Open Model Railroad Network (OpenMRN)
Loading...
Searching...
No Matches
SocketClient Class Reference
Inheritance diagram for SocketClient:
StateFlowBase Atomic Executable Notifiable QMember Destructable

Classes

struct  AddrInfoDeleter
 Helper structure for creating a unique_ptr for struct addrinfo pointers. More...
 

Public Types

enum class  Attempt : uint8_t {
  RECONNECT , INITIATE_MDNS , CONNECT_MDNS , CONNECT_STATIC ,
  WAIT_RETRY , FAILED_EXIT
}
 This enum represents individual states of this state flow that we can branch to. More...
 
typedef std::unique_ptr< struct addrinfo, AddrInfoDeleterAddrinfoPtr
 Custom unique pointer that knows how to delete a struct addrinfo.
 

Public Member Functions

 SocketClient (Service *service, ExecutorBase *connect_executor, ExecutorBase *mdns_executor, std::unique_ptr< SocketClientParams > params, std::function< void(int, Notifiable *)> connect_callback)
 Constructor.
 
 ~SocketClient ()
 Destructor.
 
void reset_params (std::unique_ptr< SocketClientParams > params)
 Updates the parameter structure for this socket client.
 
void shutdown ()
 Shutdown the client so that it can be deleted.
 
bool is_connected ()
 
bool is_shutdown ()
 
void start_shutdown ()
 Request that this client shutdown and exit the other thread.
 
- Public Member Functions inherited from StateFlowBase
void run () override
 Callback from the executor.
 
void notify () override
 Wakeup call arrived.
 
Serviceservice ()
 Return a pointer to the service I am bound to.
 
- Public Member Functions inherited from Executable
void test_deletion ()
 
- Public Member Functions inherited from QMember
void init ()
 Initiailize a QMember, in place of a public placement construction.
 

Static Public Member Functions

static int connect (const char *host, int port)
 Connects a tcp socket to the specified remote host:port.
 
static int connect (const char *host, const char *port_str)
 Connects a tcp socket to the specified remote host:port.
 
static int connect (struct addrinfo *addr)
 Connects a tcp socket to the specified remote address.
 
static bool address_to_string (struct addrinfo *addr, string *host, int *port)
 Converts a struct addrinfo to a dotted-decimal notation IP address.
 
static AddrinfoPtr string_to_address (const char *host, int port)
 Converts a hostname string and port number to a struct addrinfo.
 
static AddrinfoPtr string_to_address (const char *host, const char *port_str)
 Converts a hostname string (or null) and port number (or service name) to a struct addrinfo.
 
- Static Public Member Functions inherited from StateFlowBase
template<class T , typename... Args>
static void invoke_subflow_and_ignore_result (FlowInterface< Buffer< T > > *target_flow, Args &&... args)
 Calls a helper flow to perform some actions.
 

Private Member Functions

void prepare_strategy ()
 Parses the params_ configuration and fills in strategyConfig_.
 
Action start_connection ()
 Main entry point of the connection process.
 
Action next_step ()
 Execute the next step of the strategy.
 
Action try_schedule_connect (SocketClientParams::LogMessage log, string host, int port)
 Helper function to schedule asynchronous connect on a separate executor.
 
void connect_blocking (const string &host, int port)
 Called on the connect executor.
 
Action connect_complete ()
 State that gets invoked once the reconnect attempt is complete.
 
Action connected ()
 State that gets called when we have a completed connection in fd_.
 
string to_string (const char *p)
 Turns a parameter to a string.
 
Action start_mdns ()
 State that initiates the mdns lookup asynchronously.
 
void mdns_lookup (string mdns_hostname, string mdns_service)
 Synchronous function that runs on the mdns executor.
 
Action wait_and_connect_mdns ()
 Blocks the flow until mdns lookup is complete, then connects to the resulting address.
 
Action connect_mdns ()
 Takes the address from the mdns lookup and connects to it if it is valid.
 
Action failed_oneshot ()
 Last state in the connection sequence, when everything failed, but the caller wanted one shot only.
 
Action wait_retry ()
 Last state in the connection sequence, when everything failed: sleeps until the timeout specified in the params, then goes back to the start_connection.
 
Action sleep_done ()
 
 DISALLOW_COPY_AND_ASSIGN (SocketClient)
 
- Private Member Functions inherited from Atomic
void lock ()
 
void unlock ()
 

Static Private Member Functions

static bool local_test (struct addrinfo *addr)
 Test if a given address is local.
 

Private Attributes

long long startTime_
 When the last connection attempt was started.
 
StateFlowTimer timer_ {this}
 Helper for sleeping.
 
std::unique_ptr< SocketClientParamsparams_
 Stores the parameter structure.
 
std::function< void(int, Notifiable *)> callback_ = nullptr
 callback to call on connection success
 
ExecutorBaseconnectExecutor_ = nullptr
 Executor for synchronous (blocking) connect calls. Externally owned.
 
ExecutorBasemdnsExecutor_ = nullptr
 Executor for synchronous (blocking) mDNS lookup calls.
 
std::array< Attempt, 5 > strategyConfig_
 Stores the sequence of operations we need to try.
 
uint8_t strategyOffset_: 3
 What is the next step in the strategy.
 
uint8_t mdnsPending_: 1
 true if there is a pending mdns lookup operation.
 
uint8_t mdnsJoin_: 1
 true if the main flow is waiting for the mdns lookup to complete.
 
uint8_t sleeping_: 1
 true while we are waiting for the timer.
 
uint8_t requestShutdown_: 1
 true if an external agent requested the flow to exit.
 
uint8_t isConnected_: 1
 true if we are connected and waiting for a client notification to restart.
 
AddrinfoPtr mdnsAddr_
 Holds the results of the mdns lookup. null if failed (or never ran).
 
BarrierNotifiable n_
 
int fd_
 socket descriptor
 

Additional Inherited Members

- Protected Types inherited from StateFlowBase
typedef Action(StateFlowBase::* Callback) ()
 State Flow callback prototype.
 
- Protected Member Functions inherited from StateFlowBase
 StateFlowBase (Service *service)
 Constructor.
 
 ~StateFlowBase ()
 Destructor.
 
void reset_flow (Callback c)
 Resets the flow to the specified state.
 
bool is_state (Callback c)
 
bool is_terminated ()
 
void start_flow (Callback c)
 Resets the flow to the specified state and starts it.
 
Action again ()
 Call the current state again via call_immediately.
 
Action exit ()
 Terminate current StateFlow activity.
 
Action delete_this ()
 Terminates the flow and deletes *this.
 
Action set_terminated ()
 Sets the flow to terminated state.
 
Action call_immediately (Callback c)
 Imediately call the next state upon return.
 
Action wait ()
 Wait for an asynchronous call.
 
Action wait_and_call (Callback c)
 Wait for resource to become available before proceeding to next state.
 
template<class T >
Action allocate_and_call (FlowInterface< Buffer< T > > *target_flow, Callback c, Pool *pool=nullptr)
 Allocates a buffer from a pool and proceed to the next state when allocation is successful.
 
Action allocate_and_call (Callback c, QAsync *queue)
 Allocates an entry from an asynchronous queue, and transitions to a state once the allocation is complete.
 
template<class T >
Buffer< T > * full_allocation_result (FlowInterface< Buffer< T > > *target_flow)
 Takes the result of the asynchronous allocation without resetting the object.
 
template<class T >
T * full_allocation_result (TypedQAsync< T > *queue)
 Takes the result of the asynchronous allocation without resetting the object.
 
template<class T >
void cast_allocation_result (T **member)
 Takes the result of the asynchronous allocation without resetting the object.
 
template<class T >
Buffer< T > * get_allocation_result (FlowInterface< Buffer< T > > *target_flow)
 Takes the result of the asynchronous allocation.
 
Action yield_and_call (Callback c)
 Place the current flow to the back of the executor, and transition to a new state after we get the CPU again.
 
Action yield ()
 Place the current flow to the back of the executor, and re-try the current state after we get the CPU again.
 
Action sleep_and_call (::Timer *timer, long long timeout_nsec, Callback c)
 Suspends execution of this control flow for a specified time.
 
template<class T , typename... Args>
Action invoke_subflow_and_wait (FlowInterface< Buffer< T > > *target_flow, Callback c, Args &&... args)
 Calls a helper flow to perform some actions.
 
Action read_repeated (StateFlowSelectHelper *helper, int fd, void *buf, size_t size, Callback c, unsigned priority=Selectable::MAX_PRIO)
 Blocks until size bytes are read and then invokes the next state.
 
Action read_single (StateFlowSelectHelper *helper, int fd, void *buf, size_t size, Callback c, unsigned priority=Selectable::MAX_PRIO)
 Attempts to read at most size_t bytes, and blocks the caller until at least one byte is read.
 
Action read_nonblocking (StateFlowSelectHelper *helper, int fd, void *buf, size_t size, Callback c, unsigned priority=Selectable::MAX_PRIO)
 Attempts to read at most size bytes, and then invokes the next state, even if only zero bytes are available right now.
 
Action read_repeated_with_timeout (StateFlowTimedSelectHelper *helper, long long timeout_nsec, int fd, void *buf, size_t size, Callback c, unsigned priority=Selectable::MAX_PRIO)
 Blocks until size bytes are read, or a timeout expires.
 
Action internal_try_read ()
 Implementation state that gets repeatedly called upon every wakeup and tries to make progress on reading.
 
Action write_repeated (StateFlowSelectHelper *helper, int fd, const void *buf, size_t size, Callback c, unsigned priority=Selectable::MAX_PRIO)
 Writes some data into a file descriptor, repeating the operation as necessary until all bytes are written.
 
Action internal_try_write ()
 Implementation state that gets repeatedly called upon every wakeup and tries to make progress on writing.
 
- Protected Member Functions inherited from QMember
 QMember ()
 Constructor.
 
 ~QMember ()
 Destructor.
 
- Protected Attributes inherited from QMember
QMembernext
 pointer to the next member in the queue
 

Detailed Description

Definition at line 56 of file SocketClient.hxx.

Member Typedef Documentation

◆ AddrinfoPtr

typedef std::unique_ptr<struct addrinfo, AddrInfoDeleter> SocketClient::AddrinfoPtr

Custom unique pointer that knows how to delete a struct addrinfo.

Definition at line 119 of file SocketClient.hxx.

Member Enumeration Documentation

◆ Attempt

enum class SocketClient::Attempt : uint8_t
strong

This enum represents individual states of this state flow that we can branch to.

The configuration of connection strategy is a sequence of these enum values.

Enumerator
RECONNECT 

Connect to the reconnect slot.

INITIATE_MDNS 

Start mDNS lookup.

CONNECT_MDNS 

Connect to mDNS lookup result.

CONNECT_STATIC 

Connect to static target.

WAIT_RETRY 

Attempt complete. Start again.

FAILED_EXIT 

Failed and do not start again (for one-shot mode).

Definition at line 124 of file SocketClient.hxx.

Constructor & Destructor Documentation

◆ SocketClient()

SocketClient::SocketClient ( Service service,
ExecutorBase connect_executor,
ExecutorBase mdns_executor,
std::unique_ptr< SocketClientParams params,
std::function< void(int, Notifiable *)>  connect_callback 
)
inline

Constructor.

Parameters
serviceservice that the StateFlowBase will be bound to. This service will never be blocked. Externally owned.
connect_executoris a thread on which DNS lookups and blocking connect calls will be attempted. Externally owned. May be shared between different SocketClients.
mdns_executoris a thread on which mdns lookups will be attempted. May be null if mdns is never used (by the parameters) or may be the same executor as connect_executor if connect and mdns attempts ought to be serialized. Externally owned. May be shared between different SocketClients.
paramsdefines all the different parameters on whom to connect to. Takes ownership.
connect_callbackcallback method to invoke when a client connection is made successfully. It is unspecified which thread this callback will be invoked upon.
  • First param is the file descriptor of the resulting socket
  • Second param is a notifiable (ownership is not transferred). The callee must invoke this notifiable when the socket has been torn down in order to restart the search with the same parameters.

Definition at line 80 of file SocketClient.hxx.

◆ ~SocketClient()

SocketClient::~SocketClient ( )
inline

Destructor.

Definition at line 101 of file SocketClient.hxx.

Member Function Documentation

◆ address_to_string()

static bool SocketClient::address_to_string ( struct addrinfo addr,
string *  host,
int *  port 
)
static

Converts a struct addrinfo to a dotted-decimal notation IP address.

Parameters
addris an addrinfo returned by getaddrinfo or gethostbyname.
hostwill be filled with dotted-decimal IP address.
portwill be filled with the port number.
Returns
true on success.

◆ connect() [1/3]

static int SocketClient::connect ( const char *  host,
const char *  port_str 
)
static

Connects a tcp socket to the specified remote host:port.

Returns -1 if unsuccessful; returns the fd if successful.

Parameters
hosthostname to connect to. Shall be null for mDNS target.
port_strTCP port number or mDNS hostname to connect to.
Returns
fd of the connected socket.

◆ connect() [2/3]

static int SocketClient::connect ( const char *  host,
int  port 
)
inlinestatic

Connects a tcp socket to the specified remote host:port.

Returns -1 if unsuccessful; returns the fd if successful.

Parameters
hosthostname to connect to
portTCP port number to connect to
Returns
fd of the connected socket.

Definition at line 227 of file SocketClient.hxx.

◆ connect() [3/3]

static int SocketClient::connect ( struct addrinfo addr)
static

Connects a tcp socket to the specified remote address.

Returns -1 if unsuccessful; returns the fd if successful.

Parameters
addrIP(v4/v6) addrinfo structure describing the remote host. May be null. Ownership is not transferred. Will not be used after the funciton returns.
Returns
fd of the connected socket.

◆ connect_blocking()

void SocketClient::connect_blocking ( const string &  host,
int  port 
)
inlineprivate

Called on the connect executor.

Parameters
hosthostname (or IP address in text form) to connect to
portport number to connect to.

Definition at line 417 of file SocketClient.hxx.

◆ connect_complete()

Action SocketClient::connect_complete ( )
inlineprivate

State that gets invoked once the reconnect attempt is complete.

Definition at line 434 of file SocketClient.hxx.

◆ connect_mdns()

Action SocketClient::connect_mdns ( )
inlineprivate

Takes the address from the mdns lookup and connects to it if it is valid.

Returns
next step or pending connection step.

Definition at line 556 of file SocketClient.hxx.

◆ connected()

Action SocketClient::connected ( )
inlineprivate

State that gets called when we have a completed connection in fd_.

Definition at line 449 of file SocketClient.hxx.

◆ failed_oneshot()

Action SocketClient::failed_oneshot ( )
inlineprivate

Last state in the connection sequence, when everything failed, but the caller wanted one shot only.

Definition at line 572 of file SocketClient.hxx.

◆ is_connected()

bool SocketClient::is_connected ( )
inline
Returns
true if we have a working connection.

Definition at line 175 of file SocketClient.hxx.

◆ is_shutdown()

bool SocketClient::is_shutdown ( )
inline
Returns
true if the shutdown has completed.

Definition at line 182 of file SocketClient.hxx.

◆ local_test()

static bool SocketClient::local_test ( struct addrinfo addr)
staticprivate

Test if a given address is local.

Parameters
addraddress info to test
Returns
true if local, else false if not local

◆ mdns_lookup()

void SocketClient::mdns_lookup ( string  mdns_hostname,
string  mdns_service 
)
inlineprivate

Synchronous function that runs on the mdns executor.

Performs the lookup.

Parameters
mdns_serviceis the service name to look up.
mdns_hostnameis ignored for now.

Definition at line 501 of file SocketClient.hxx.

◆ next_step()

Action SocketClient::next_step ( )
inlineprivate

Execute the next step of the strategy.

Definition at line 353 of file SocketClient.hxx.

◆ prepare_strategy()

void SocketClient::prepare_strategy ( )
inlineprivate

Parses the params_ configuration and fills in strategyConfig_.

Definition at line 280 of file SocketClient.hxx.

◆ reset_params()

void SocketClient::reset_params ( std::unique_ptr< SocketClientParams params)
inline

Updates the parameter structure for this socket client.

Parameters
paramsis the parameter structure; ownership will be transferred.
Todo:
(balazs.racz): do we need to somehow wake up the flow and make it attempt to reconnect?

Definition at line 143 of file SocketClient.hxx.

◆ shutdown()

void SocketClient::shutdown ( )
inline

Shutdown the client so that it can be deleted.

Definition at line 152 of file SocketClient.hxx.

◆ sleep_done()

Action SocketClient::sleep_done ( )
inlineprivate

Definition at line 595 of file SocketClient.hxx.

◆ start_connection()

Action SocketClient::start_connection ( )
inlineprivate

Main entry point of the connection process.

Definition at line 337 of file SocketClient.hxx.

◆ start_mdns()

Action SocketClient::start_mdns ( )
inlineprivate

State that initiates the mdns lookup asynchronously.

Returns
next step state.

Definition at line 479 of file SocketClient.hxx.

◆ start_shutdown()

void SocketClient::start_shutdown ( )
inline

Request that this client shutdown and exit the other thread.

Definition at line 189 of file SocketClient.hxx.

◆ string_to_address() [1/2]

static AddrinfoPtr SocketClient::string_to_address ( const char *  host,
const char *  port_str 
)
static

Converts a hostname string (or null) and port number (or service name) to a struct addrinfo.

Parameters
hosthostname to connect to.
portport name or service name to connect to.
Returns
a struct addrinfo; ownership is transferred to the caller.

◆ string_to_address() [2/2]

static AddrinfoPtr SocketClient::string_to_address ( const char *  host,
int  port 
)
inlinestatic

Converts a hostname string and port number to a struct addrinfo.

Parameters
hosthostname to connect to.
portport number to connect to.
Returns
a struct addrinfo; ownership is transferred.

Definition at line 265 of file SocketClient.hxx.

◆ to_string()

string SocketClient::to_string ( const char *  p)
inlineprivate

Turns a parameter to a string.

Parameters
pis a parameter; may be nullptr or empty.
Returns
empty string if p is null or empty, otherwise p (copied).

Definition at line 468 of file SocketClient.hxx.

◆ try_schedule_connect()

Action SocketClient::try_schedule_connect ( SocketClientParams::LogMessage  log,
string  host,
int  port 
)
inlineprivate

Helper function to schedule asynchronous connect on a separate executor.

Never blocks. Will deliver exactly one notify to the barrier notifiable n_.

Parameters
logwill be emitted to the params_ structure if connection is attempted.
hosthostname (or IP address in text form) to connect to. May be empty in which case no connection will be attempted.
portport number to connect to.
Returns
the connection wait action or next_state depending on whether connection was attempted.

Definition at line 396 of file SocketClient.hxx.

◆ wait_and_connect_mdns()

Action SocketClient::wait_and_connect_mdns ( )
inlineprivate

Blocks the flow until mdns lookup is complete, then connects to the resulting address.

Returns
mdns connect step

Definition at line 540 of file SocketClient.hxx.

◆ wait_retry()

Action SocketClient::wait_retry ( )
inlineprivate

Last state in the connection sequence, when everything failed: sleeps until the timeout specified in the params, then goes back to the start_connection.

Definition at line 580 of file SocketClient.hxx.

Member Data Documentation

◆ callback_

std::function<void(int, Notifiable *)> SocketClient::callback_ = nullptr
private

callback to call on connection success

Definition at line 619 of file SocketClient.hxx.

◆ connectExecutor_

ExecutorBase* SocketClient::connectExecutor_ = nullptr
private

Executor for synchronous (blocking) connect calls. Externally owned.

Definition at line 622 of file SocketClient.hxx.

◆ fd_

int SocketClient::fd_
private

socket descriptor

Definition at line 659 of file SocketClient.hxx.

◆ isConnected_

uint8_t SocketClient::isConnected_
private

true if we are connected and waiting for a client notification to restart.

Definition at line 651 of file SocketClient.hxx.

◆ mdnsAddr_

AddrinfoPtr SocketClient::mdnsAddr_
private

Holds the results of the mdns lookup. null if failed (or never ran).

Definition at line 654 of file SocketClient.hxx.

◆ mdnsExecutor_

ExecutorBase* SocketClient::mdnsExecutor_ = nullptr
private

Executor for synchronous (blocking) mDNS lookup calls.

Externally owned, may be null.

Definition at line 625 of file SocketClient.hxx.

◆ mdnsJoin_

uint8_t SocketClient::mdnsJoin_
private

true if the main flow is waiting for the mdns lookup to complete.

Guarded by Atomic *this.

Definition at line 641 of file SocketClient.hxx.

◆ mdnsPending_

uint8_t SocketClient::mdnsPending_
private

true if there is a pending mdns lookup operation.

Guarded by Atomic *this.

Definition at line 637 of file SocketClient.hxx.

◆ n_

BarrierNotifiable SocketClient::n_
private

Definition at line 656 of file SocketClient.hxx.

◆ params_

std::unique_ptr<SocketClientParams> SocketClient::params_
private

Stores the parameter structure.

Definition at line 616 of file SocketClient.hxx.

◆ requestShutdown_

uint8_t SocketClient::requestShutdown_
private

true if an external agent requested the flow to exit.

Definition at line 647 of file SocketClient.hxx.

◆ sleeping_

uint8_t SocketClient::sleeping_
private

true while we are waiting for the timer.

Definition at line 644 of file SocketClient.hxx.

◆ startTime_

long long SocketClient::startTime_
private

When the last connection attempt was started.

Definition at line 611 of file SocketClient.hxx.

◆ strategyConfig_

std::array<Attempt, 5> SocketClient::strategyConfig_
private
Initial value:
{{
}}
@ WAIT_RETRY
Attempt complete. Start again.

Stores the sequence of operations we need to try.

Definition at line 628 of file SocketClient.hxx.

◆ strategyOffset_

uint8_t SocketClient::strategyOffset_
private

What is the next step in the strategy.

Index into the strategyConfig_ array. Guarded by Atomic *this.

Definition at line 633 of file SocketClient.hxx.

◆ timer_

StateFlowTimer SocketClient::timer_ {this}
private

Helper for sleeping.

Definition at line 613 of file SocketClient.hxx.


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