Skip to content

Commit 3d20304

Browse files
Cloaked9000Felipe Zimmerle
authored and
Felipe Zimmerle
committed
Replaced log locking using mutex with fcntl lock
When reloading Nginx, there is a race condition which is visible under high load. As the logging mutex is shared between multiple workers, when a worker is sent a stop signal during a reload, and the log mutex is held, write() will never return, which means that the mutex will never unlock. As other workers share this mutex, they will deadlock. fcntl does not suffer from this issue.
1 parent 5a4ada3 commit 3d20304

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

src/utils/shared_files.cc

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,6 @@ std::pair<msc_file_handler *, FILE *> SharedFiles::add_new_handler(
104104

105105
if (toBeCreated) {
106106
memset(new_debug_log, '\0', sizeof(msc_file_handler_t));
107-
pthread_mutex_init(&new_debug_log->lock, NULL);
108107
new_debug_log->shm_id_structure = shm_id;
109108
memcpy(new_debug_log->file_name, fileName.c_str(), fileName.size());
110109
new_debug_log->file_name[fileName.size()] = '\0';
@@ -222,6 +221,7 @@ bool SharedFiles::write(const std::string& fileName,
222221
std::pair<msc_file_handler *, FILE *> a;
223222
std::string lmsg = msg;
224223
size_t wrote;
224+
struct flock lock{};
225225
bool ret = true;
226226

227227
a = find_handler(fileName);
@@ -230,15 +230,21 @@ bool SharedFiles::write(const std::string& fileName,
230230
return false;
231231
}
232232

233-
pthread_mutex_lock(&a.first->lock);
234-
wrote = fwrite(reinterpret_cast<const char *>(lmsg.c_str()), 1,
235-
lmsg.size(), a.second);
233+
//Exclusively lock whole file
234+
lock.l_start = lock.l_len = lock.l_whence = 0;
235+
lock.l_type = F_WRLCK;
236+
fcntl(fileno(a.second), F_SETLKW, &lock);
237+
238+
wrote = fwrite(lmsg.c_str(), 1, lmsg.size(), a.second);
236239
if (wrote < msg.size()) {
237240
error->assign("failed to write: " + fileName);
238241
ret = false;
239242
}
240243
fflush(a.second);
241-
pthread_mutex_unlock(&a.first->lock);
244+
245+
//Remove exclusive lock
246+
lock.l_type = F_UNLCK;
247+
fcntl(fileno(a.second), F_SETLKW, &lock);
242248

243249
return ret;
244250
}

src/utils/shared_files.h

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,6 @@ namespace utils {
5050

5151
typedef struct msc_file_handler {
5252
int shm_id_structure;
53-
pthread_mutex_t lock;
5453
char file_name[];
5554
} msc_file_handler_t;
5655

0 commit comments

Comments
 (0)