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