提交 b983c05e authored 作者: Iñaki Baz Castillo's avatar Iñaki Baz Castillo

Share logs and Channel messages into the same socket.

上级 0421e598
...@@ -4,6 +4,7 @@ const EventEmitter = require('events').EventEmitter; ...@@ -4,6 +4,7 @@ const EventEmitter = require('events').EventEmitter;
const netstring = require('netstring'); const netstring = require('netstring');
const logger = require('./logger')('Channel'); const logger = require('./logger')('Channel');
const workerLogger = require('./logger')('mediasoup-worker');
const utils = require('./utils'); const utils = require('./utils');
const errors = require('./errors'); const errors = require('./errors');
...@@ -53,7 +54,6 @@ class Channel extends EventEmitter ...@@ -53,7 +54,6 @@ class Channel extends EventEmitter
while (true) while (true)
{ {
let nsPayload; let nsPayload;
let json;
try try
{ {
...@@ -79,19 +79,38 @@ class Channel extends EventEmitter ...@@ -79,19 +79,38 @@ class Channel extends EventEmitter
// Check whether it is valid JSON // Check whether it is valid JSON
try try
{ {
// NOTE: cool, JSON.parse() allows a Buffer // We can receive JSON messages (Channel messages) or log strings
json = JSON.parse(nsPayload); switch (nsPayload[0])
{
// 123 = '{' (a Channel JSON messsage)
case 123:
this._processMessage(JSON.parse(nsPayload));
break;
// 68 = 'D' (a debug log)
case 68:
workerLogger.debug(nsPayload.toString(null, 1));
break;
// 87 = 'W' (a warning log)
case 87:
workerLogger.warn(nsPayload.toString(null, 1));
break;
// 69 = 'E' (an error log)
case 69:
workerLogger.error(nsPayload.toString(null, 1));
break;
default:
workerLogger.error('unexpected log: %s', nsPayload.toString());
}
} }
catch (error) catch (error)
{ {
logger.error('received invalid JSON: %s', error.message); logger.error('received invalid JSON: %s', error.message);
return;
} }
// Process JSON
this._processMessage(json);
// Remove the read payload from the recvBuffer // Remove the read payload from the recvBuffer
this._recvBuffer = this._recvBuffer.slice(netstring.nsLength(this._recvBuffer)); this._recvBuffer = this._recvBuffer.slice(netstring.nsLength(this._recvBuffer));
...@@ -121,8 +140,8 @@ class Channel extends EventEmitter ...@@ -121,8 +140,8 @@ class Channel extends EventEmitter
// Close every pending sent // Close every pending sent
this._pendingSent.forEach((sent) => sent.close()); this._pendingSent.forEach((sent) => sent.close());
// Close the UnixStream socket this._socket.removeAllListeners('end');
this._socket.destroy(); this._socket.removeAllListeners('error');
} }
request(method, data) request(method, data)
......
...@@ -12,11 +12,9 @@ const Room = require('./Room'); ...@@ -12,11 +12,9 @@ const Room = require('./Room');
const WORKER_BIN_PATH = path.join(__dirname, '..', 'worker', 'bin', 'mediasoup-worker'); const WORKER_BIN_PATH = path.join(__dirname, '..', 'worker', 'bin', 'mediasoup-worker');
const CHANNEL_FD = 3; const CHANNEL_FD = 3;
const LOGGER_FD = 4;
// Set environtment variables for the worker // Set environtment variables for the worker
process.env.MEDIASOUP_CHANNEL_FD = String(CHANNEL_FD); process.env.MEDIASOUP_CHANNEL_FD = String(CHANNEL_FD);
process.env.MEDIASOUP_LOGGER_FD = String(LOGGER_FD);
class Worker extends EventEmitter class Worker extends EventEmitter
{ {
...@@ -36,9 +34,8 @@ class Worker extends EventEmitter ...@@ -36,9 +34,8 @@ class Worker extends EventEmitter
* that log their own stuff * that log their own stuff
* fd 2 (stderr) : Same as stdout * fd 2 (stderr) : Same as stdout
* fd 3 (channel) : Channel fd * fd 3 (channel) : Channel fd
* fd 4 (logger) : Logger fd
*/ */
stdio : [ 'ignore', 'pipe', 'pipe', 'pipe', 'pipe' ] stdio : [ 'ignore', 'pipe', 'pipe', 'pipe' ]
}; };
// Create the mediasoup-worker child process // Create the mediasoup-worker child process
...@@ -50,46 +47,24 @@ class Worker extends EventEmitter ...@@ -50,46 +47,24 @@ class Worker extends EventEmitter
// Set of Room instances // Set of Room instances
this._rooms = new Set(); this._rooms = new Set();
// Set worker logger // Be ready for 3rd party worker libraries logging to stdout/stderr
this._child.stdio[LOGGER_FD].on('data', (buffer) =>
this._child.stdout.on('data', (buffer) =>
{ {
buffer.toString('utf8').split('\f').forEach((line) => buffer.toString('utf8').split('\f').forEach((line) =>
{ {
switch (line[0]) if (line)
{ logger.debug(`mediasoup-worker's stdout [id:${id}]: ${line}`);
case undefined:
break;
// MS_DEBUG & MS_TRACE
case 'D':
logger.debug(line.slice(1));
break;
// MS_WARN
case 'W':
logger.warn(line.slice(1));
break;
// MS_ERROR
case 'E':
logger.error(line.slice(1));
break;
// Should not happen
default:
logger.warn(`unexpected log: ${line}`);
}
}); });
}); });
// Be also ready for 3rd party worker libraries logging to stdout/stderr
// TODO: This does not work. If mediasoup-worker prints on stdout here
// we do not receive anything
this._child.stdout.on('data', (buffer) =>
{
logger.debug(`worker stdout: ${buffer.toString('utf8')}`);
});
this._child.stderr.on('data', (buffer) => this._child.stderr.on('data', (buffer) =>
{ {
logger.error(`worker stderr: ${buffer.toString('utf8')}`); buffer.toString('utf8').split('\f').forEach((line) =>
{
if (line)
logger.error(`mediasoup-worker's stderr [id:${id}]: ${line}`);
});
}); });
// Set child process events // Set child process events
......
...@@ -25,10 +25,12 @@ namespace Channel ...@@ -25,10 +25,12 @@ namespace Channel
static MS_BYTE writeBuffer[]; static MS_BYTE writeBuffer[];
public: public:
UnixStreamSocket(Listener* listener, int fd); UnixStreamSocket(int fd);
virtual ~UnixStreamSocket(); virtual ~UnixStreamSocket();
void SetListener(Listener* listener);
void Send(Json::Value &json); void Send(Json::Value &json);
void SendLog(char* ns_payload, int ns_payload_len);
/* Pure virtual methods inherited from ::UnixStreamSocket. */ /* Pure virtual methods inherited from ::UnixStreamSocket. */
public: public:
...@@ -42,6 +44,7 @@ namespace Channel ...@@ -42,6 +44,7 @@ namespace Channel
Json::CharReader* jsonReader = nullptr; Json::CharReader* jsonReader = nullptr;
Json::StreamWriter* jsonWriter = nullptr; Json::StreamWriter* jsonWriter = nullptr;
size_t msgStart = 0; // Where the latest message starts. size_t msgStart = 0; // Where the latest message starts.
bool closed = false;
}; };
} }
......
...@@ -3,11 +3,14 @@ ...@@ -3,11 +3,14 @@
#include "common.h" #include "common.h"
#include "Settings.h" #include "Settings.h"
#include "handles/UnixStreamSocket.h"
#include "Channel/UnixStreamSocket.h"
#include <string> #include <string>
#include <cstdio> // dprintf() #include <cstdio> // std::snprintf(), std::fprintf(), stdout, stderr
#include <cstring> #include <cstring>
#include <cstdlib> // std::_Exit(), std::abort(), std::genenv() #include <cstdlib> // std::abort()
#include <uv.h>
#define MS_LOGGER_BUFFER_SIZE 10000
/* /*
* Logger facility. * Logger facility.
...@@ -45,12 +48,13 @@ ...@@ -45,12 +48,13 @@
class Logger class Logger
{ {
public: public:
static void Init(const std::string id); static void Init(const std::string id, Channel::UnixStreamSocket* channel);
static bool HasDebugLevel(); static bool HasDebugLevel();
public: public:
static std::string id; static std::string id;
static int fd; static Channel::UnixStreamSocket* channel;
static char buffer[];
}; };
/* Inline static methods. */ /* Inline static methods. */
...@@ -63,7 +67,7 @@ bool Logger::HasDebugLevel() ...@@ -63,7 +67,7 @@ bool Logger::HasDebugLevel()
// NOTE: Each file including Logger.h MUST define its own MS_CLASS macro. // NOTE: Each file including Logger.h MUST define its own MS_CLASS macro.
#define _MS_LOG_SEPARATOR_CHAR "\f" #define _MS_LOG_SEPARATOR_CHAR_STD "\f"
#ifdef MS_DEVEL #ifdef MS_DEVEL
#define _MS_LOG_STR "[%s] %s:%d | %s::%s()" #define _MS_LOG_STR "[%s] %s:%d | %s::%s()"
...@@ -80,11 +84,20 @@ bool Logger::HasDebugLevel() ...@@ -80,11 +84,20 @@ bool Logger::HasDebugLevel()
#define MS_TRACE() \ #define MS_TRACE() \
do \ do \
{ \ { \
dprintf(Logger::fd, "D(trace) " _MS_LOG_STR _MS_LOG_SEPARATOR_CHAR, _MS_LOG_ARG); \ int ms_logger_written = std::snprintf(Logger::buffer, MS_LOGGER_BUFFER_SIZE, "D(trace) " _MS_LOG_STR, _MS_LOG_ARG); \
Logger::channel->SendLog(Logger::buffer, ms_logger_written); \
} \
while (0)
#define MS_TRACE_STD() \
do \
{ \
std::fprintf(stdout, "(trace) " _MS_LOG_STR _MS_LOG_SEPARATOR_CHAR_STD, _MS_LOG_ARG); \
std::fflush(stdout); \
} \ } \
while (0) while (0)
#else #else
#define MS_TRACE() #define MS_TRACE()
#define MS_TRACE_STD()
#endif #endif
#define MS_DEBUG(desc, ...) \ #define MS_DEBUG(desc, ...) \
...@@ -92,48 +105,55 @@ bool Logger::HasDebugLevel() ...@@ -92,48 +105,55 @@ bool Logger::HasDebugLevel()
{ \ { \
if (MS_LOG_LEVEL_DEBUG == MS_CURRENT_LOG_LEVEL) \ if (MS_LOG_LEVEL_DEBUG == MS_CURRENT_LOG_LEVEL) \
{ \ { \
dprintf(Logger::fd, "D" _MS_LOG_STR_DESC desc _MS_LOG_SEPARATOR_CHAR, _MS_LOG_ARG, ##__VA_ARGS__); \ int ms_logger_written = std::snprintf(Logger::buffer, MS_LOGGER_BUFFER_SIZE, "D" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
Logger::channel->SendLog(Logger::buffer, ms_logger_written); \
} \ } \
} \ } \
while (0) while (0)
#define MS_WARN(desc, ...) \ #define MS_DEBUG_STD(desc, ...) \
do \ do \
{ \ { \
if (MS_LOG_LEVEL_WARN <= MS_CURRENT_LOG_LEVEL) \ if (MS_LOG_LEVEL_DEBUG == MS_CURRENT_LOG_LEVEL) \
{ \ { \
dprintf(Logger::fd, "W" _MS_LOG_STR_DESC desc _MS_LOG_SEPARATOR_CHAR, _MS_LOG_ARG, ##__VA_ARGS__); \ std::fprintf(stdout, _MS_LOG_STR_DESC desc _MS_LOG_SEPARATOR_CHAR_STD, _MS_LOG_ARG, ##__VA_ARGS__); \
std::fflush(stdout); \
} \ } \
} \ } \
while (0) while (0)
#define MS_ERROR(desc, ...) \ #define MS_WARN(desc, ...) \
do \ do \
{ \ { \
dprintf(Logger::fd, "E" _MS_LOG_STR_DESC desc _MS_LOG_SEPARATOR_CHAR, _MS_LOG_ARG, ##__VA_ARGS__); \ if (MS_LOG_LEVEL_WARN <= MS_CURRENT_LOG_LEVEL) \
{ \
int ms_logger_written = std::snprintf(Logger::buffer, MS_LOGGER_BUFFER_SIZE, "W" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
Logger::channel->SendLog(Logger::buffer, ms_logger_written); \
} \
} \ } \
while (0) while (0)
#define MS_EXIT_SUCCESS(desc, ...) \ #define MS_ERROR(desc, ...) \
do \ do \
{ \ { \
MS_DEBUG("SUCCESS EXIT | " desc, ##__VA_ARGS__); \ int ms_logger_written = std::snprintf(Logger::buffer, MS_LOGGER_BUFFER_SIZE, "E" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
std::_Exit(EXIT_SUCCESS); \ Logger::channel->SendLog(Logger::buffer, ms_logger_written); \
} \ } \
while (0) while (0)
#define MS_EXIT_FAILURE(desc, ...) \ #define MS_ERROR_STD(desc, ...) \
do \ do \
{ \ { \
MS_ERROR("FAILURE EXIT | " desc, ##__VA_ARGS__); \ std::fprintf(stderr, _MS_LOG_STR_DESC desc _MS_LOG_SEPARATOR_CHAR_STD, _MS_LOG_ARG, ##__VA_ARGS__); \
std::_Exit(EXIT_FAILURE); \ std::fflush(stderr); \
} \ } \
while (0) while (0)
#define MS_ABORT(desc, ...) \ #define MS_ABORT(desc, ...) \
do \ do \
{ \ { \
MS_ERROR("ABORT | " desc, ##__VA_ARGS__); \ std::fprintf(stderr, "ABORT | " desc, ##__VA_ARGS__); \
std::fflush(stderr); \
std::abort(); \ std::abort(); \
} \ } \
while (0) while (0)
......
...@@ -13,7 +13,7 @@ class Loop : ...@@ -13,7 +13,7 @@ class Loop :
public Channel::UnixStreamSocket::Listener public Channel::UnixStreamSocket::Listener
{ {
public: public:
Loop(); Loop(Channel::UnixStreamSocket* channel);
~Loop(); ~Loop();
private: private:
...@@ -31,9 +31,10 @@ public: ...@@ -31,9 +31,10 @@ public:
virtual void onChannelUnixStreamSocketRemotelyClosed(Channel::UnixStreamSocket* channel) override; virtual void onChannelUnixStreamSocketRemotelyClosed(Channel::UnixStreamSocket* channel) override;
private: private:
// Passed by argument.
Channel::UnixStreamSocket* channel = nullptr;
// Allocated by this. // Allocated by this.
SignalsHandler* signalsHandler = nullptr; SignalsHandler* signalsHandler = nullptr;
Channel::UnixStreamSocket* channel = nullptr;
// Others. // Others.
bool closed = false; bool closed = false;
typedef std::unordered_map<unsigned int, RTC::Room*> Rooms; typedef std::unordered_map<unsigned int, RTC::Room*> Rooms;
......
...@@ -22,8 +22,18 @@ MediaSoupError::MediaSoupError(const char* description) : std::runtime_error(des ...@@ -22,8 +22,18 @@ MediaSoupError::MediaSoupError(const char* description) : std::runtime_error(des
do \ do \
{ \ { \
MS_ERROR("throwing MediaSoupError | " desc, ##__VA_ARGS__); \ MS_ERROR("throwing MediaSoupError | " desc, ##__VA_ARGS__); \
char buffer[1000]; \ static char buffer[2000]; \
std::snprintf(buffer, 1000, desc, ##__VA_ARGS__); \ std::snprintf(buffer, 2000, desc, ##__VA_ARGS__); \
throw MediaSoupError(buffer); \
} \
while (0)
#define MS_THROW_ERROR_STD(desc, ...) \
do \
{ \
MS_ERROR_STD("throwing MediaSoupError | " desc, ##__VA_ARGS__); \
static char buffer[2000]; \
std::snprintf(buffer, 2000, desc, ##__VA_ARGS__); \
throw MediaSoupError(buffer); \ throw MediaSoupError(buffer); \
} \ } \
while (0) while (0)
......
...@@ -21,11 +21,10 @@ namespace Channel ...@@ -21,11 +21,10 @@ namespace Channel
/* Instance methods. */ /* Instance methods. */
UnixStreamSocket::UnixStreamSocket(Listener* listener, int fd) : UnixStreamSocket::UnixStreamSocket(int fd) :
::UnixStreamSocket::UnixStreamSocket(fd, NS_MAX_SIZE), ::UnixStreamSocket::UnixStreamSocket(fd, NS_MAX_SIZE)
listener(listener)
{ {
MS_TRACE(); MS_TRACE_STD();
// Create the JSON reader. // Create the JSON reader.
{ {
...@@ -58,15 +57,25 @@ namespace Channel ...@@ -58,15 +57,25 @@ namespace Channel
UnixStreamSocket::~UnixStreamSocket() UnixStreamSocket::~UnixStreamSocket()
{ {
MS_TRACE(); MS_TRACE_STD();
delete this->jsonReader; delete this->jsonReader;
delete this->jsonWriter; delete this->jsonWriter;
} }
void UnixStreamSocket::SetListener(Listener* listener)
{
MS_TRACE_STD();
this->listener = listener;
}
void UnixStreamSocket::Send(Json::Value &msg) void UnixStreamSocket::Send(Json::Value &msg)
{ {
MS_TRACE(); if (this->closed)
return;
// MS_TRACE_STD();
std::ostringstream stream; std::ostringstream stream;
std::string ns_payload; std::string ns_payload;
...@@ -80,7 +89,7 @@ namespace Channel ...@@ -80,7 +89,7 @@ namespace Channel
if (ns_payload_len > MESSAGE_MAX_SIZE) if (ns_payload_len > MESSAGE_MAX_SIZE)
{ {
MS_ERROR("mesage too big"); MS_ERROR_STD("mesage too big");
return; return;
} }
...@@ -105,9 +114,46 @@ namespace Channel ...@@ -105,9 +114,46 @@ namespace Channel
Write(UnixStreamSocket::writeBuffer, ns_len); Write(UnixStreamSocket::writeBuffer, ns_len);
} }
void UnixStreamSocket::SendLog(char* ns_payload, int ns_payload_len)
{
if (this->closed)
return;
// MS_TRACE_STD();
size_t ns_num_len;
size_t ns_len;
if (ns_payload_len > MESSAGE_MAX_SIZE)
{
MS_ERROR_STD("mesage too big");
return;
}
if (ns_payload_len == 0)
{
ns_num_len = 1;
UnixStreamSocket::writeBuffer[0] = '0';
UnixStreamSocket::writeBuffer[1] = ':';
UnixStreamSocket::writeBuffer[2] = ',';
}
else
{
ns_num_len = (size_t)std::ceil(std::log10((double)ns_payload_len + 1));
std::sprintf((char*)UnixStreamSocket::writeBuffer, "%lu:", (unsigned long)ns_payload_len);
std::memcpy(UnixStreamSocket::writeBuffer + ns_num_len + 1, ns_payload, ns_payload_len);
UnixStreamSocket::writeBuffer[ns_num_len + ns_payload_len + 1] = ',';
}
ns_len = ns_num_len + ns_payload_len + 2;
Write(UnixStreamSocket::writeBuffer, ns_len);
}
void UnixStreamSocket::userOnUnixStreamRead() void UnixStreamSocket::userOnUnixStreamRead()
{ {
MS_TRACE(); MS_TRACE_STD();
// Be ready to parse more than a single message in a single TCP chunk. // Be ready to parse more than a single message in a single TCP chunk.
while (true) while (true)
...@@ -123,7 +169,7 @@ namespace Channel ...@@ -123,7 +169,7 @@ namespace Channel
switch (ns_ret) switch (ns_ret)
{ {
case NETSTRING_ERROR_TOO_SHORT: case NETSTRING_ERROR_TOO_SHORT:
MS_DEBUG("received netstring is too short, need more data"); MS_DEBUG_STD("received netstring is too short, need more data");
// Check if the buffer is full. // Check if the buffer is full.
if (this->bufferDataLen == this->bufferSize) if (this->bufferDataLen == this->bufferSize)
...@@ -132,7 +178,7 @@ namespace Channel ...@@ -132,7 +178,7 @@ namespace Channel
// the buffer, so move the incomplete message to the position 0. // the buffer, so move the incomplete message to the position 0.
if (this->msgStart != 0) if (this->msgStart != 0)
{ {
MS_DEBUG("no more space in the buffer, moving parsed bytes to the beginning of the buffer and waiting for more data"); MS_DEBUG_STD("no more space in the buffer, moving parsed bytes to the beginning of the buffer and waiting for more data");
std::memmove(this->buffer, this->buffer + this->msgStart, read_len); std::memmove(this->buffer, this->buffer + this->msgStart, read_len);
this->msgStart = 0; this->msgStart = 0;
...@@ -142,7 +188,7 @@ namespace Channel ...@@ -142,7 +188,7 @@ namespace Channel
// The message is too big, so discard it. // The message is too big, so discard it.
else else
{ {
MS_ERROR("no more space in the buffer for the unfinished message being parsed, discarding it"); MS_ERROR_STD("no more space in the buffer for the unfinished message being parsed, discarding it");
this->msgStart = 0; this->msgStart = 0;
this->bufferDataLen = 0; this->bufferDataLen = 0;
...@@ -154,19 +200,19 @@ namespace Channel ...@@ -154,19 +200,19 @@ namespace Channel
return; return;
case NETSTRING_ERROR_TOO_LONG: case NETSTRING_ERROR_TOO_LONG:
MS_ERROR("NETSTRING_ERROR_TOO_LONG"); MS_ERROR_STD("NETSTRING_ERROR_TOO_LONG");
break; break;
case NETSTRING_ERROR_NO_COLON: case NETSTRING_ERROR_NO_COLON:
MS_ERROR("NETSTRING_ERROR_NO_COLON"); MS_ERROR_STD("NETSTRING_ERROR_NO_COLON");
break; break;
case NETSTRING_ERROR_NO_COMMA: case NETSTRING_ERROR_NO_COMMA:
MS_ERROR("NETSTRING_ERROR_NO_COMMA"); MS_ERROR_STD("NETSTRING_ERROR_NO_COMMA");
break; break;
case NETSTRING_ERROR_LEADING_ZERO: case NETSTRING_ERROR_LEADING_ZERO:
MS_ERROR("NETSTRING_ERROR_LEADING_ZERO"); MS_ERROR_STD("NETSTRING_ERROR_LEADING_ZERO");
break; break;
case NETSTRING_ERROR_NO_LENGTH: case NETSTRING_ERROR_NO_LENGTH:
...@@ -198,7 +244,7 @@ namespace Channel ...@@ -198,7 +244,7 @@ namespace Channel
} }
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
MS_ERROR("discarding wrong Channel request"); MS_ERROR_STD("discarding wrong Channel request");
} }
if (request) if (request)
...@@ -212,14 +258,14 @@ namespace Channel ...@@ -212,14 +258,14 @@ namespace Channel
} }
else else
{ {
MS_ERROR("JSON parsing error: %s", json_parse_error.c_str()); MS_ERROR_STD("JSON parsing error: %s", json_parse_error.c_str());
} }
// If there is no more space available in the buffer and that is because // If there is no more space available in the buffer and that is because
// the latest parsed message filled it, then empty the full buffer. // the latest parsed message filled it, then empty the full buffer.
if ((this->msgStart + read_len) == this->bufferSize) if ((this->msgStart + read_len) == this->bufferSize)
{ {
MS_DEBUG("no more space in the buffer, emptying the buffer data"); MS_DEBUG_STD("no more space in the buffer, emptying the buffer data");
this->msgStart = 0; this->msgStart = 0;
this->bufferDataLen = 0; this->bufferDataLen = 0;
...@@ -235,7 +281,7 @@ namespace Channel ...@@ -235,7 +281,7 @@ namespace Channel
// then parse again. Otherwise break here and wait for more data. // then parse again. Otherwise break here and wait for more data.
if (this->bufferDataLen > this->msgStart) if (this->bufferDataLen > this->msgStart)
{ {
MS_DEBUG("there is more data after the parsed message, continue parsing"); MS_DEBUG_STD("there is more data after the parsed message, continue parsing");
continue; continue;
} }
else else
...@@ -247,7 +293,9 @@ namespace Channel ...@@ -247,7 +293,9 @@ namespace Channel
void UnixStreamSocket::userOnUnixStreamSocketClosed(bool is_closed_by_peer) void UnixStreamSocket::userOnUnixStreamSocketClosed(bool is_closed_by_peer)
{ {
MS_TRACE(); MS_TRACE_STD();
this->closed = true;
if (is_closed_by_peer) if (is_closed_by_peer)
{ {
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
#include "DepLibUV.h" #include "DepLibUV.h"
#include "Logger.h" #include "Logger.h"
#include <cstdlib> // std::abort()
/* Static variables. */ /* Static variables. */
...@@ -11,17 +12,14 @@ uv_loop_t* DepLibUV::loop = nullptr; ...@@ -11,17 +12,14 @@ uv_loop_t* DepLibUV::loop = nullptr;
void DepLibUV::ClassInit() void DepLibUV::ClassInit()
{ {
MS_TRACE(); // NOTE: Logger depends on this so we cannot log anything here.
int err; int err;
// Print libuv version.
MS_DEBUG("loaded libuv version: %s", uv_version_string());
DepLibUV::loop = new uv_loop_t; DepLibUV::loop = new uv_loop_t;
err = uv_loop_init(DepLibUV::loop); err = uv_loop_init(DepLibUV::loop);
if (err) if (err)
MS_ABORT("uv_loop_init() failed: %s", uv_strerror(err)); std::abort();
} }
void DepLibUV::ClassDestroy() void DepLibUV::ClassDestroy()
......
...@@ -5,14 +5,15 @@ ...@@ -5,14 +5,15 @@
/* Class variables. */ /* Class variables. */
std::string Logger::id; std::string Logger::id;
int Logger::fd; Channel::UnixStreamSocket* Logger::channel = nullptr;
char Logger::buffer[MS_LOGGER_BUFFER_SIZE];
/* Class methods. */ /* Class methods. */
void Logger::Init(const std::string id) void Logger::Init(const std::string id, Channel::UnixStreamSocket* channel)
{ {
Logger::id = id; Logger::id = id;
Logger::fd = std::stoi(std::getenv("MEDIASOUP_LOGGER_FD")); Logger::channel = channel;
MS_TRACE(); MS_TRACE();
} }
...@@ -8,17 +8,19 @@ ...@@ -8,17 +8,19 @@
#include <string> #include <string>
#include <utility> // std::pair() #include <utility> // std::pair()
#include <csignal> // sigfillset, pthread_sigmask() #include <csignal> // sigfillset, pthread_sigmask()
#include <cstdlib> // std::genenv()
#include <cerrno> #include <cerrno>
#include <iostream> // std::cout, std::cerr
#include <json/json.h> #include <json/json.h>
/* Instance methods. */ /* Instance methods. */
Loop::Loop() Loop::Loop(Channel::UnixStreamSocket* channel) :
channel(channel)
{ {
MS_TRACE(); MS_TRACE();
int channelFd = std::stoi(std::getenv("MEDIASOUP_CHANNEL_FD")); // Set us as Channel's listener.
this->channel->SetListener(this);
// Set the signals handler. // Set the signals handler.
this->signalsHandler = new SignalsHandler(this); this->signalsHandler = new SignalsHandler(this);
...@@ -27,9 +29,6 @@ Loop::Loop() ...@@ -27,9 +29,6 @@ Loop::Loop()
this->signalsHandler->AddSignal(SIGINT, "INT"); this->signalsHandler->AddSignal(SIGINT, "INT");
this->signalsHandler->AddSignal(SIGTERM, "TERM"); this->signalsHandler->AddSignal(SIGTERM, "TERM");
// Set the Channel socket.
this->channel = new Channel::UnixStreamSocket(this, channelFd);
MS_DEBUG("starting libuv loop"); MS_DEBUG("starting libuv loop");
DepLibUV::RunLoop(); DepLibUV::RunLoop();
MS_DEBUG("libuv loop ended"); MS_DEBUG("libuv loop ended");
...@@ -89,10 +88,8 @@ void Loop::Close() ...@@ -89,10 +88,8 @@ void Loop::Close()
MS_ERROR("pthread_sigmask() failed: %s", std::strerror(errno)); MS_ERROR("pthread_sigmask() failed: %s", std::strerror(errno));
// Close the SignalsHandler. // Close the SignalsHandler.
this->signalsHandler->Close(); if (this->signalsHandler)
this->signalsHandler->Close();
// Close the Channel socket.
this->channel->Close();
// Close all the Rooms. // Close all the Rooms.
for (auto& kv : this->rooms) for (auto& kv : this->rooms)
...@@ -101,6 +98,10 @@ void Loop::Close() ...@@ -101,6 +98,10 @@ void Loop::Close()
room->Close(); room->Close();
} }
// Close the Channel socket.
if (this->channel)
this->channel->Close();
} }
void Loop::onSignal(SignalsHandler* signalsHandler, int signum) void Loop::onSignal(SignalsHandler* signalsHandler, int signum)
...@@ -127,6 +128,8 @@ void Loop::onSignal(SignalsHandler* signalsHandler, int signum) ...@@ -127,6 +128,8 @@ void Loop::onSignal(SignalsHandler* signalsHandler, int signum)
void Loop::onSignalsHandlerClosed(SignalsHandler* signalsHandler) void Loop::onSignalsHandlerClosed(SignalsHandler* signalsHandler)
{ {
MS_TRACE(); MS_TRACE();
this->signalsHandler = nullptr;
} }
void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request* request) void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request* request)
...@@ -279,14 +282,16 @@ void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request ...@@ -279,14 +282,16 @@ void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request
void Loop::onChannelUnixStreamSocketRemotelyClosed(Channel::UnixStreamSocket* socket) void Loop::onChannelUnixStreamSocketRemotelyClosed(Channel::UnixStreamSocket* socket)
{ {
MS_TRACE(); MS_TRACE_STD();
// When mediasoup Node process ends it sends a SIGTERM to us so we close this // When mediasoup Node process ends it sends a SIGTERM to us so we close this
// pipe and then exit. // pipe and then exit.
// If the pipe is remotely closed it means that mediasoup Node process // If the pipe is remotely closed it means that mediasoup Node process
// abruptly died (SIGKILL?) so we must die. // abruptly died (SIGKILL?) so we must die.
MS_ERROR("Channel remotely closed, killing myself"); MS_ERROR_STD("Channel remotely closed, killing myself");
this->channel = nullptr;
Close(); Close();
} }
...@@ -6,7 +6,6 @@ ...@@ -6,7 +6,6 @@
#include "MediaSoupError.h" #include "MediaSoupError.h"
#include "Logger.h" #include "Logger.h"
#define MS_READ_BUFFER_SIZE 65536 #define MS_READ_BUFFER_SIZE 65536
#define RETURN_IF_CLOSING() \ #define RETURN_IF_CLOSING() \
if (this->isClosing) \ if (this->isClosing) \
......
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
#define RETURN_IF_CLOSING() \ #define RETURN_IF_CLOSING() \
if (this->isClosing) \ if (this->isClosing) \
{ \ { \
MS_DEBUG("in closing state, doing nothing"); \ MS_DEBUG_STD("in closing state, doing nothing"); \
return; \ return; \
} }
...@@ -65,7 +65,7 @@ void on_error_close(uv_handle_t* handle) ...@@ -65,7 +65,7 @@ void on_error_close(uv_handle_t* handle)
UnixStreamSocket::UnixStreamSocket(int fd, size_t bufferSize) : UnixStreamSocket::UnixStreamSocket(int fd, size_t bufferSize) :
bufferSize(bufferSize) bufferSize(bufferSize)
{ {
MS_TRACE(); MS_TRACE_STD();
int err; int err;
...@@ -77,14 +77,14 @@ UnixStreamSocket::UnixStreamSocket(int fd, size_t bufferSize) : ...@@ -77,14 +77,14 @@ UnixStreamSocket::UnixStreamSocket(int fd, size_t bufferSize) :
{ {
delete this->uvHandle; delete this->uvHandle;
this->uvHandle = nullptr; this->uvHandle = nullptr;
MS_THROW_ERROR("uv_pipe_init() failed: %s", uv_strerror(err)); MS_THROW_ERROR_STD("uv_pipe_init() failed: %s", uv_strerror(err));
} }
err = uv_pipe_open(this->uvHandle, fd); err = uv_pipe_open(this->uvHandle, fd);
if (err) if (err)
{ {
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close); uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close);
MS_THROW_ERROR("uv_pipe_open() failed: %s", uv_strerror(err)); MS_THROW_ERROR_STD("uv_pipe_open() failed: %s", uv_strerror(err));
} }
// Start reading. // Start reading.
...@@ -92,7 +92,7 @@ UnixStreamSocket::UnixStreamSocket(int fd, size_t bufferSize) : ...@@ -92,7 +92,7 @@ UnixStreamSocket::UnixStreamSocket(int fd, size_t bufferSize) :
if (err) if (err)
{ {
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close); uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_error_close);
MS_THROW_ERROR("uv_read_start() failed: %s", uv_strerror(err)); MS_THROW_ERROR_STD("uv_read_start() failed: %s", uv_strerror(err));
} }
// NOTE: Don't allocate the buffer here. Instead wait for the first uv_alloc_cb(). // NOTE: Don't allocate the buffer here. Instead wait for the first uv_alloc_cb().
...@@ -100,7 +100,7 @@ UnixStreamSocket::UnixStreamSocket(int fd, size_t bufferSize) : ...@@ -100,7 +100,7 @@ UnixStreamSocket::UnixStreamSocket(int fd, size_t bufferSize) :
UnixStreamSocket::~UnixStreamSocket() UnixStreamSocket::~UnixStreamSocket()
{ {
MS_TRACE(); MS_TRACE_STD();
if (this->uvHandle) if (this->uvHandle)
delete this->uvHandle; delete this->uvHandle;
...@@ -110,13 +110,13 @@ UnixStreamSocket::~UnixStreamSocket() ...@@ -110,13 +110,13 @@ UnixStreamSocket::~UnixStreamSocket()
void UnixStreamSocket::Write(const MS_BYTE* data, size_t len) void UnixStreamSocket::Write(const MS_BYTE* data, size_t len)
{ {
MS_TRACE(); // MS_TRACE_STD();
RETURN_IF_CLOSING(); RETURN_IF_CLOSING();
if (len == 0) if (len == 0)
{ {
MS_DEBUG("ignoring 0 length data"); MS_DEBUG_STD("ignoring 0 length data");
return; return;
} }
...@@ -144,7 +144,7 @@ void UnixStreamSocket::Write(const MS_BYTE* data, size_t len) ...@@ -144,7 +144,7 @@ void UnixStreamSocket::Write(const MS_BYTE* data, size_t len)
// Error. Should not happen. // Error. Should not happen.
else if (written < 0) else if (written < 0)
{ {
MS_WARN("uv_try_write() failed: %s | closing the socket", uv_strerror(written)); MS_ERROR_STD("uv_try_write() failed: %s | closing the socket", uv_strerror(written));
Close(); Close();
return; return;
} }
...@@ -167,7 +167,7 @@ void UnixStreamSocket::Write(const MS_BYTE* data, size_t len) ...@@ -167,7 +167,7 @@ void UnixStreamSocket::Write(const MS_BYTE* data, size_t len)
void UnixStreamSocket::Close() void UnixStreamSocket::Close()
{ {
MS_TRACE(); MS_TRACE_STD();
RETURN_IF_CLOSING(); RETURN_IF_CLOSING();
...@@ -198,13 +198,13 @@ void UnixStreamSocket::Close() ...@@ -198,13 +198,13 @@ void UnixStreamSocket::Close()
void UnixStreamSocket::Dump() void UnixStreamSocket::Dump()
{ {
MS_DEBUG("[status: %s]", (!this->isClosing) ? "open" : "closed"); MS_DEBUG_STD("[status: %s]", (!this->isClosing) ? "open" : "closed");
} }
inline inline
void UnixStreamSocket::onUvReadAlloc(size_t suggested_size, uv_buf_t* buf) void UnixStreamSocket::onUvReadAlloc(size_t suggested_size, uv_buf_t* buf)
{ {
MS_TRACE(); MS_TRACE_STD();
// If this is the first call to onUvReadAlloc() then allocate the receiving buffer now. // If this is the first call to onUvReadAlloc() then allocate the receiving buffer now.
if (!this->buffer) if (!this->buffer)
...@@ -216,19 +216,19 @@ void UnixStreamSocket::onUvReadAlloc(size_t suggested_size, uv_buf_t* buf) ...@@ -216,19 +216,19 @@ void UnixStreamSocket::onUvReadAlloc(size_t suggested_size, uv_buf_t* buf)
if (this->bufferSize > this->bufferDataLen) if (this->bufferSize > this->bufferDataLen)
{ {
buf->len = this->bufferSize - this->bufferDataLen; buf->len = this->bufferSize - this->bufferDataLen;
MS_DEBUG("available space in the buffer: %zu", buf->len); // MS_DEBUG_STD("available space in the buffer: %zu", buf->len);
} }
else else
{ {
buf->len = 0; buf->len = 0;
MS_WARN("no available space in the buffer"); MS_ERROR_STD("no available space in the buffer");
} }
} }
inline inline
void UnixStreamSocket::onUvRead(ssize_t nread, const uv_buf_t* buf) void UnixStreamSocket::onUvRead(ssize_t nread, const uv_buf_t* buf)
{ {
MS_TRACE(); MS_TRACE_STD();
if (nread == 0) if (nread == 0)
return; return;
...@@ -245,7 +245,6 @@ void UnixStreamSocket::onUvRead(ssize_t nread, const uv_buf_t* buf) ...@@ -245,7 +245,6 @@ void UnixStreamSocket::onUvRead(ssize_t nread, const uv_buf_t* buf)
// Peer disconneted. // Peer disconneted.
else if (nread == UV_EOF || nread == UV_ECONNRESET) else if (nread == UV_EOF || nread == UV_ECONNRESET)
{ {
MS_DEBUG("pipe closed by peer | closing local side");
this->isClosedByPeer = true; this->isClosedByPeer = true;
// Close local side of the pipe. // Close local side of the pipe.
...@@ -254,7 +253,7 @@ void UnixStreamSocket::onUvRead(ssize_t nread, const uv_buf_t* buf) ...@@ -254,7 +253,7 @@ void UnixStreamSocket::onUvRead(ssize_t nread, const uv_buf_t* buf)
// Some error. // Some error.
else else
{ {
MS_DEBUG("read error: %s | closing the pipe", uv_strerror(nread)); MS_ERROR_STD("read error: %s | closing the pipe", uv_strerror(nread));
this->hasError = true; this->hasError = true;
// Close the socket. // Close the socket.
...@@ -266,18 +265,18 @@ void UnixStreamSocket::onUvRead(ssize_t nread, const uv_buf_t* buf) ...@@ -266,18 +265,18 @@ void UnixStreamSocket::onUvRead(ssize_t nread, const uv_buf_t* buf)
inline inline
void UnixStreamSocket::onUvWriteError(int error) void UnixStreamSocket::onUvWriteError(int error)
{ {
MS_TRACE(); MS_TRACE_STD();
if (this->isClosing) if (this->isClosing)
return; return;
if (error == UV_EPIPE || error == UV_ENOTCONN) if (error == UV_EPIPE || error == UV_ENOTCONN)
{ {
MS_DEBUG("write error: %s | closing the pipe", uv_strerror(error)); MS_DEBUG_STD("write error: %s | closing the pipe", uv_strerror(error));
} }
else else
{ {
MS_DEBUG("write error: %s | closing the pipe", uv_strerror(error)); MS_DEBUG_STD("write error: %s | closing the pipe", uv_strerror(error));
this->hasError = true; this->hasError = true;
} }
...@@ -287,14 +286,14 @@ void UnixStreamSocket::onUvWriteError(int error) ...@@ -287,14 +286,14 @@ void UnixStreamSocket::onUvWriteError(int error)
inline inline
void UnixStreamSocket::onUvShutdown(uv_shutdown_t* req, int status) void UnixStreamSocket::onUvShutdown(uv_shutdown_t* req, int status)
{ {
MS_TRACE(); MS_TRACE_STD();
delete req; delete req;
if (status == UV_EPIPE || status == UV_ENOTCONN || status == UV_ECANCELED) if (status == UV_EPIPE || status == UV_ENOTCONN || status == UV_ECANCELED)
MS_DEBUG("shutdown error: %s", uv_strerror(status)); MS_DEBUG_STD("shutdown error: %s", uv_strerror(status));
else if (status) else if (status)
MS_DEBUG("shutdown error: %s", uv_strerror(status)); MS_DEBUG_STD("shutdown error: %s", uv_strerror(status));
// Now do close the handle. // Now do close the handle.
uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close); uv_close((uv_handle_t*)this->uvHandle, (uv_close_cb)on_close);
...@@ -303,7 +302,7 @@ void UnixStreamSocket::onUvShutdown(uv_shutdown_t* req, int status) ...@@ -303,7 +302,7 @@ void UnixStreamSocket::onUvShutdown(uv_shutdown_t* req, int status)
inline inline
void UnixStreamSocket::onUvClosed() void UnixStreamSocket::onUvClosed()
{ {
MS_TRACE(); MS_TRACE_STD();
// Notify the subclass. // Notify the subclass.
userOnUnixStreamSocketClosed(this->isClosedByPeer); userOnUnixStreamSocketClosed(this->isClosedByPeer);
......
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
#include "DepLibSRTP.h" #include "DepLibSRTP.h"
#include "DepUsrSCTP.h" #include "DepUsrSCTP.h"
#include "Utils.h" #include "Utils.h"
#include "Channel/UnixStreamSocket.h"
#include "RTC/UDPSocket.h" #include "RTC/UDPSocket.h"
#include "RTC/TCPServer.h" #include "RTC/TCPServer.h"
#include "RTC/DTLSAgent.h" #include "RTC/DTLSAgent.h"
...@@ -16,9 +17,12 @@ ...@@ -16,9 +17,12 @@
#include "Logger.h" #include "Logger.h"
#include <map> #include <map>
#include <string> #include <string>
#include <iostream> // std::cout, std::cerr
#include <cstdlib> // std::_Exit(), std::genenv()
#include <csignal> // sigaction() #include <csignal> // sigaction()
#include <cerrno> #include <cerrno>
#include <unistd.h> // getpid() #include <unistd.h> // getpid()
#include <uv.h>
static void init(); static void init();
static void ignoreSignals(); static void ignoreSignals();
...@@ -26,12 +30,20 @@ static void destroy(); ...@@ -26,12 +30,20 @@ static void destroy();
int main(int argc, char* argv[], char** envp) int main(int argc, char* argv[], char** envp)
{ {
if (argc == 1) // Initialize libuv stuff (we need it for the Channel).
MS_EXIT_FAILURE("process id must be given as first argument"); DepLibUV::ClassInit();
int channelFd = std::stoi(std::getenv("MEDIASOUP_CHANNEL_FD"));
// Set the Channel socket (this will be handled and deleted by the Loop).
Channel::UnixStreamSocket* channel = new Channel::UnixStreamSocket(channelFd);
std::string id = std::string(argv[1]); std::string id = std::string(argv[1]);
Logger::Init(id); Logger::Init(id, channel);
// Print libuv version.
MS_DEBUG("loaded libuv version: %s", uv_version_string());
try try
{ {
...@@ -39,7 +51,8 @@ int main(int argc, char* argv[], char** envp) ...@@ -39,7 +51,8 @@ int main(int argc, char* argv[], char** envp)
} }
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
MS_EXIT_FAILURE("%s", error.what()); std::cerr << "failure exit: " << error.what() << std::endl;
std::_Exit(EXIT_FAILURE);
} }
// Print configuration. // Print configuration.
...@@ -66,16 +79,18 @@ int main(int argc, char* argv[], char** envp) ...@@ -66,16 +79,18 @@ int main(int argc, char* argv[], char** envp)
init(); init();
// Run the Loop. // Run the Loop.
Loop loop; Loop loop(channel);
destroy();
std::cout << "success exit" << std::endl;
std::_Exit(EXIT_SUCCESS);
} }
catch (const MediaSoupError &error) catch (const MediaSoupError &error)
{ {
destroy(); destroy();
MS_EXIT_FAILURE("%s", error.what()); std::cerr << "failure exit: " << error.what() << std::endl;
std::_Exit(EXIT_FAILURE);
} }
destroy();
MS_EXIT_SUCCESS(MS_PROCESS_NAME " ends");
} }
void init() void init()
...@@ -85,7 +100,6 @@ void init() ...@@ -85,7 +100,6 @@ void init()
ignoreSignals(); ignoreSignals();
// Initialize static stuff. // Initialize static stuff.
DepLibUV::ClassInit();
DepOpenSSL::ClassInit(); DepOpenSSL::ClassInit();
DepLibSRTP::ClassInit(); DepLibSRTP::ClassInit();
DepUsrSCTP::ClassInit(); DepUsrSCTP::ClassInit();
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论