Skip to content

Commit

Permalink
Merge pull request #2495 from DataDog/glopes/appsec-log-fsync
Browse files Browse the repository at this point in the history
Ensure logs are committed to disk upon shutdown
  • Loading branch information
cataphract authored Jan 30, 2024
2 parents 8beff3e + 7dad066 commit 2d896c8
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 11 deletions.
38 changes: 28 additions & 10 deletions appsec/src/extension/logging.c
Original file line number Diff line number Diff line change
Expand Up @@ -377,9 +377,12 @@ static void _mlog_file(dd_log_level_t level, const char *format, va_list args,
_dd_log_level_to_str(level), message_data, file, line, function);

efree(message_data);
TSRM_MUTEX_LOCK(_mutex);
ssize_t written = write(_mlog_fd, data, data_len);
TSRM_MUTEX_UNLOCK(_mutex);
ssize_t written;
do {
TSRM_MUTEX_LOCK(_mutex);
written = write(_mlog_fd, data, data_len);
TSRM_MUTEX_UNLOCK(_mutex);
} while (written == -1 && errno == EINTR);
efree(data);

if (written == -1) {
Expand Down Expand Up @@ -451,13 +454,23 @@ void dd_log_shutdown()
{
mlog(dd_log_debug, "Shutting down the file logging");

#ifdef ZTS
tsrm_mutex_free(_mutex);
_mutex = NULL;
#endif
if (_log_strategy == log_use_file && _mlog_fd != -1 &&
_mlog_fd > fileno(stderr)) {
int ret = close(_mlog_fd);
if (_log_strategy == log_use_file &&
atomic_load_explicit(&_initialized, memory_order_acquire) &&
_mlog_fd != -1 && _mlog_fd > fileno(stderr)) {
// no need for the mutex at this point
// all the zts workers should have been done
// we're guaranteed visibility of the write to _mlog_fd by _initialized
int ret;
ret = fsync(_mlog_fd);
if (ret == -1) {
_mlog_php_varargs(dd_log_warning,
"Error fsyncing the log file (errno %d: %s)", errno,
_strerror(errno));
}
do {
ret = close(_mlog_fd);
} while (ret == -1 && errno == EINTR);

if (ret == -1) {
_mlog_php_varargs(dd_log_warning,
"Error closing the log file (errno %d: %s)", errno,
Expand All @@ -467,6 +480,11 @@ void dd_log_shutdown()
closelog();
}

#ifdef ZTS
tsrm_mutex_free(_mutex);
_mutex = NULL;
#endif

_mlog_fd = -1;
_log_strategy = log_use_nothing;
atomic_store(&_initialized, false);
Expand Down
2 changes: 1 addition & 1 deletion appsec/src/extension/request_abort.c
Original file line number Diff line number Diff line change
Expand Up @@ -409,8 +409,8 @@ static bool _abort_prelude()
mlog_g(dd_log_warning, "Failed clearing current headers");
}

mlog_g(dd_log_debug, "Discarding output buffers");
php_output_discard_all();
mlog_g(dd_log_debug, "Output buffers have been discarded");
return true;
}

Expand Down

0 comments on commit 2d896c8

Please sign in to comment.