Bredbandskollen CLI  1.2
Asynchronous network task engine
Public Member Functions | Static Public Member Functions | List of all members
EventLoop Class Reference

Manage timers and tasks. More...

#include <eventloop.h>

Inheritance diagram for EventLoop:
Inheritance graph
[legend]
Collaboration diagram for EventLoop:
Collaboration graph
[legend]

Public Member Functions

 EventLoop (std::string log_label="MainLoop")
 
void addTask (Task *task, Task *parent=nullptr)
 
bool run (double timeout_s)
 
void runUntilComplete ()
 Run until all task are done.
 
void waitForThreadsToFinish ()
 Block current thread until all spawned threads have finished.
 
void abortTask (Task *task)
 Remove the given task.
 
void abort ()
 Remove all tasks.
 
void getChildTasks (std::set< Task * > &tset, Task *parent) const
 Get all tasks with the given parent.
 
void abortChildTasks (Task *parent)
 Remove all tasks with the given parent.
 
void wakeUpTask (Task *t)
 Restart idle connections owned by the given task.
 
bool wakeUpConnection (SocketConnection *s)
 Restart an idle connection.
 
void cancelConnection (SocketConnection *s)
 Remove a connection.
 
std::set< Socket * > findConnByTask (const Task *t) const
 Return all connetcions owned by the given task.
 
bool isActive (const Socket *conn) const
 Return true if conn still exists.
 
void resetTimer (Task *task, double s)
 
bool addConnection (SocketConnection *conn)
 
bool addConnected (SocketConnection *conn)
 
bool addServer (ServerSocket *conn)
 
bool tlsSetKey (ServerSocket *conn, const std::string &crt_path, const std::string &key_path, const std::string &password)
 Use SSL certificate for a listening socket.
 
bool setCABundle (const std::string &path)
 Set path to file containing chain of trust for SSL certificate.
 
bool running (Task *task)
 Return true if task is running.
 
void taskDeleted (Task *task)
 Notify EventLoop that a task object it ows has been deleted. More...
 
void spawnThread (Task *task, const std::string &name="ThreadLoop", std::ostream *log_file=nullptr, Task *parent=nullptr)
 Create a new thread and run task in its own loop in that thread.
 
int externalCommand (Task *owner, const char *const argv[])
 
WorkerProcesscreateWorker (Task *parent, std::ostream *log_file, unsigned int channels, unsigned int wno)
 
WorkerProcesscreateWorker (Task *parent, const std::string &log_file_name, unsigned int channels, unsigned int wno)
 
void killChildProcesses (int signum)
 Send signal to all child processes.
 
void notifyTaskFinished (Task *task)
 Mark the given task as finished. More...
 
void notifyTaskMessage (Task *task)
 Notify the EventLoop that the given task has a message to deliver. More...
 
bool aborted () const
 Return true if the EventLoop is about to be terminated.
 
void addSignalHandler (int signum, void(*handler)(int, EventLoop &))
 Add handler for the given OS signal.
 
bool startObserving (Task *from, Task *to)
 
bool isObserving (Task *observer, Task *task) const
 Return true if observer is observing task.
 
- Public Member Functions inherited from Logger
 Logger (std::string label)
 
std::string label () const
 Return the object's log label.
 
void resetLabel (const std::string &new_label)
 Modify the object's log label.
 

Static Public Member Functions

static void runTask (Task *task, const std::string &name="MainLoop", std::ostream *log_file=nullptr, EventLoop *parent=nullptr)
 
static void interrupt ()
 
static void daemonize ()
 Fork into background, detach from shell.
 
static void setLogFilename (const std::string &filename)
 Set path to log file. More...
 
- Static Public Member Functions inherited from Logger
static void setLogFile (std::ostream &stream)
 Set global log destination. More...
 
static void reopenLogFile (const std::string &filename)
 If current log is a file (ofstream), reopen it with new filename:
 
static void setLogLimit (unsigned int loglines=0, unsigned int warnlines=0, unsigned int errlines=0)
 Set max number of lines of info/warn/err log. More...
 
static void sayTime (std::ostream &stream)
 Write current local time to the given stream.
 
static bool inError ()
 Return true if any error has been logged (globally since start)
 
static std::ostream & err_log (const std::string &label)
 Write a line of error log. More...
 
static std::ostream & warn_log (const std::string &label)
 Write a line of warning log. More...
 
static std::ostream & log (const std::string &label)
 Write a line of info log. More...
 
static void flushLogFile ()
 
static void pauseLogging ()
 Disable all log output until next call to Logger::setLogFile.
 
static double secondsSince (const TimePoint &t)
 
static double secondsTo (const TimePoint &t)
 
static int64_t msSince (const TimePoint &t)
 
static int64_t msTo (const TimePoint &t)
 
static bool hasExpired (const TimePoint &t)
 Return true if current time is after the given TimePoint.
 
static TimePoint timeNow ()
 Return current time.
 
static TimePoint timeAfter (double s)
 Return current time plus s seconds.
 
static TimePoint timeMax ()
 Return a very distant time.
 
static std::chrono::microseconds toUs (double t)
 Convert s (seconds) to std::chrono::microseconds.
 
static std::string dateString (time_t t=0)
 Return local time, formatted as 2023-10-14T09:38:47+0200.
 
static std::string dateString2 (time_t t=0)
 Return local time, formatted as Sat, 14 Oct 2023 09:38:47.
 
static std::string createHashKey (unsigned int length=20)
 Return a random string. More...
 

Additional Inherited Members

- Protected Member Functions inherited from Logger
std::ostream & errno_log () const
 Write a line of error log after a failed system call has set the global errno to a non-zero value. More...
 
std::ostream & err_log () const
 Write a line of error log. More...
 
std::ostream & warn_log () const
 Write a line of warning log. More...
 
std::ostream & log () const
 Write a line of info log. More...
 
std::ostream & dbg_log () const
 Write a line of debug log. More...
 

Detailed Description

Manage timers and tasks.

This class manages Task objects and their timers. It also manages all network connections through an Engine object. The Engine is an "inner event loop" used to manage low-level network events.

Your code must create an EventLoop object, add one or more Task objects to it, and then run the event loop, either "forever" using the method EventLoop::runUntilComplete() or by regularly calling the method EventLoop::run(double timeout_s)

Constructor & Destructor Documentation

◆ EventLoop()

EventLoop::EventLoop ( std::string  log_label = "MainLoop")
inline

Create a new EventLoop. Normally, the application should have at most one EventLoop in each thread.

Member Function Documentation

◆ addConnected()

bool EventLoop::addConnected ( SocketConnection conn)

Use this if conn contains a socket that has already been connected. Returns false (and deletes conn) on failure. On success, returns true and calls connAdded on owner task, then calls connected() on conn to get initial state.

◆ addConnection()

bool EventLoop::addConnection ( SocketConnection conn)

Create a new socket connection, and add it to the loop. Returns false (and deletes conn) on failure. On success, returns true and calls connAdded on owner task. A connection to the server will be initiated. When connected, the connected() method will be called on conn to get initial state.

◆ addServer()

bool EventLoop::addServer ( ServerSocket conn)

Returns false (and deletes conn) on failure. On success, returns true and calls serverAdded on owner task.

◆ addTask()

void EventLoop::addTask ( Task task,
Task parent = nullptr 
)

Add a task to be managed by the EventLoop. The value of the task parameter must be an object of a subclass of Task. You must create the object with new; it cannot be an object on the stack. The EventLoop will take ownership of the object and will delete it when the task has finished. Before it is deleted, the parent's taskFinished method will be called unless the parent is nullptr.

◆ createWorker() [1/2]

WorkerProcess * EventLoop::createWorker ( Task parent,
const std::string &  log_file_name,
unsigned int  channels,
unsigned int  wno 
)

Create a child process. Return child's PID. Channels can be used to pass sockets and messages between parent and child.

◆ createWorker() [2/2]

WorkerProcess * EventLoop::createWorker ( Task parent,
std::ostream *  log_file,
unsigned int  channels,
unsigned int  wno 
)

Create a child process. Return child's PID. Channels can be used to pass sockets and messages between parent and child.

◆ externalCommand()

int EventLoop::externalCommand ( Task owner,
const char *const  argv[] 
)

Asynchronously execute an external command. Return false on immediate failure.

◆ interrupt()

static void EventLoop::interrupt ( )
inlinestatic

Call this to make the network engine yield control to me (the task supervisor).

◆ notifyTaskFinished()

void EventLoop::notifyTaskFinished ( Task task)
inline

Mark the given task as finished.

Don't call this method directly. Use Task::setResult instead.

◆ notifyTaskMessage()

void EventLoop::notifyTaskMessage ( Task task)
inline

Notify the EventLoop that the given task has a message to deliver.

Don't call this method directly. Use Task::setMessage instead.

◆ resetTimer()

void EventLoop::resetTimer ( Task task,
double  s 
)

Remove previous timer, run after s seconds instead. If s = 0, run timer immediately. If s < 0, remove timer.

◆ run()

bool EventLoop::run ( double  timeout_s)

Run for at most timeout_s seconds. Returns false if all done, otherwise true:

◆ runTask()

void EventLoop::runTask ( Task task,
const std::string &  name = "MainLoop",
std::ostream *  log_file = nullptr,
EventLoop parent = nullptr 
)
static

Create an EventLoop object that runs the task until it's finished. You cannot use this if you have created your own EventLoop object.

The "parent" parameter is used if the main thread (the parent) should be notified when the thread running the task is finished.

◆ setLogFilename()

static void EventLoop::setLogFilename ( const std::string &  filename)
inlinestatic

Set path to log file.

The new log file will be activated upon receiving the SIGHUP signal.

◆ startObserving()

bool EventLoop::startObserving ( Task from,
Task to 
)

Enable events from task "from" to task "to". I.e. "from" will be able to call executeHandler with "to" as a parameter. If "to" dies before "from", "from" will be notified through a call to taskFinished. Will return false unless both tasks still exist.

◆ taskDeleted()

void EventLoop::taskDeleted ( Task task)

Notify EventLoop that a task object it ows has been deleted.

This is just a safeguard against buggy clients. Only the EventLoop is allowed to delete tasks is owns.


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