Skip to content

Commit

Permalink
[logging] rework locking around logging
Browse files Browse the repository at this point in the history
make sure to check/fill data after locking and complete write
before release the lock.

also use trylock vs lock since most log are called while already
locked and it's cleaner.

Signed-off-by: Fabio M. Di Nitto <fdinitto@redhat.com>
  • Loading branch information
fabbione committed Jun 17, 2016
1 parent d44cbab commit 6e9eed2
Showing 1 changed file with 16 additions and 13 deletions.
29 changes: 16 additions & 13 deletions libknet/logging.c
Expand Up @@ -175,37 +175,33 @@ void log_msg(knet_handle_t knet_h, uint8_t subsystem, uint8_t msglevel,
int len, err;

if ((!knet_h) ||
(knet_h->logfd <= 0) ||
(subsystem > KNET_SUB_LAST) ||
(msglevel > knet_h->log_levels[subsystem]))
return;

memset(&msg, 0, sizeof(struct knet_log_msg));
msg.subsystem = subsystem;
msg.msglevel = msglevel;

/*
* most logging calls will take place with locking in place.
* if we get an EINVAL and locking is initialized, then
* we are getting a real error and we need to stop
*/
err = pthread_rwlock_rdlock(&knet_h->global_rwlock);
if ((err == EINVAL) && (knet_h->lock_init_done))
err = pthread_rwlock_tryrdlock(&knet_h->global_rwlock);
if ((err == EAGAIN) && (knet_h->lock_init_done))
return;

if (knet_h->logfd <= 0)
goto out_unlock;

memset(&msg, 0, sizeof(struct knet_log_msg));
msg.subsystem = subsystem;
msg.msglevel = msglevel;

va_start(ap, fmt);
vsnprintf(msg.msg, sizeof(msg.msg) - 2, fmt, ap);
va_end(ap);

len = strlen(msg.msg);
msg.msg[len+1] = '\n';

/*
* unlock only if we are holding the lock
*/
if (!err)
pthread_rwlock_unlock(&knet_h->global_rwlock);

while (byte_cnt < sizeof(struct knet_log_msg)) {
len = write(knet_h->logfd, &msg, sizeof(struct knet_log_msg) - byte_cnt);
if (len <= 0)
Expand All @@ -214,5 +210,12 @@ void log_msg(knet_handle_t knet_h, uint8_t subsystem, uint8_t msglevel,
byte_cnt += len;
}

out_unlock:
/*
* unlock only if we are holding the lock
*/
if (!err)
pthread_rwlock_unlock(&knet_h->global_rwlock);

return;
}

0 comments on commit 6e9eed2

Please sign in to comment.