LoggerImplementation.cpp 14.6 KB
Newer Older
1
/******************************************************************************
2
 *                      castor/log/LoggerImplementation.cpp
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 *
 * This file is part of the Castor project.
 * See http://castor.web.cern.ch/castor
 *
 * Copyright (C) 2003  CERN
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * Interface to the CASTOR logging system
 *
 * @author Steven.Murray@cern.ch
 *****************************************************************************/

#include "castor/log/Constants.hpp"
26
#include "castor/log/LoggerImplementation.hpp"
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include "h/Castor_limits.h"
#include "h/getconfent.h"

#include <errno.h>
#include <string.h>
#include <sys/un.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

//------------------------------------------------------------------------------
// constructor
//------------------------------------------------------------------------------
43
castor::log::LoggerImplementation::LoggerImplementation(
44
45
  const std::string &programName)
  throw(castor::exception::Internal, castor::exception::InvalidArgument):
46
  Logger(programName),
47
48
49
50
51
52
53
54
55
56
57
  m_maxMsgLen(determineMaxMsgLen()),
  m_logFile(-1),
  m_connected(false),
  m_priorityToText(generatePriorityToTextMap()) {
  checkProgramNameLen(programName);
  initMutex();
}

//------------------------------------------------------------------------------
// determineMaxMsgLen
//------------------------------------------------------------------------------
58
size_t castor::log::LoggerImplementation::determineMaxMsgLen() const throw() {
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
  const char *p = NULL;
  size_t msgSize = 0;

  if((p = getconfent("LOG", "MaxMessageSize", 0)) != NULL) {
    msgSize = atoi(p);
  } else {
    // Determine the size automatically, this is not guaranteed to work!
    FILE *const fp = fopen("/etc/rsyslog.conf", "r");
    if(fp) {
      char buffer[1024];

      // The /etc/rsyslog.conf file exists so we assume the default message
      // size of 2K.
      msgSize = DEFAULT_RSYSLOG_MSGLEN;

      // In rsyslog versions >= 3.21.4, the maximum size of a message became
      // configurable through the $MaxMessageSize global config directive.
      // Here we attempt to find out if the user has increased the size!
      while(fgets(buffer, sizeof(buffer), fp) != NULL) {
        if(strncasecmp(buffer, "$MaxMessageSize", 15)) {
          continue; // Option not of interest
        }
        msgSize = atol(&buffer[15]);
      }
      fclose(fp);
    }
    // If the /etc/rsyslog.conf file is missing which implies that we are
    // running on a stock syslogd system, therefore the message size is
    // governed by the syslog RFC: http://www.faqs.org/rfcs/rfc3164.html
  }

  // Check that the size of messages falls within acceptable limits
  if((msgSize >= DEFAULT_SYSLOG_MSGLEN) && (msgSize <= LOG_MAX_LINELEN)) {
    return msgSize;
  } else {
    return DEFAULT_SYSLOG_MSGLEN;
  }
}

//------------------------------------------------------------------------------
// generatePriorityToTextMap
//------------------------------------------------------------------------------
std::map<int, std::string>
102
  castor::log::LoggerImplementation::generatePriorityToTextMap() const 
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
  throw(castor::exception::Internal) {
  std::map<int, std::string> m;

  try {
    m[LOG_EMERG]   = "Emerg";
    m[LOG_ALERT]   = "Alert";
    m[LOG_CRIT]    = "Crit";
    m[LOG_ERR]     = "Error";
    m[LOG_WARNING] = "Warn";
    m[LOG_NOTICE]  = "Notice";
    m[LOG_INFO]    = "Info";
    m[LOG_DEBUG]   = "Debug";
  } catch(std::exception &se) {
    castor::exception::Internal ex;
    ex.getMessage() << "Failed to generate priority to text mapping: " <<
      se.what();
    throw ex;
  }

  return m;
}

//------------------------------------------------------------------------------
// checkProgramNameLen
//------------------------------------------------------------------------------
128
void castor::log::LoggerImplementation::checkProgramNameLen(
129
130
131
132
133
134
135
136
137
138
139
140
  const std::string &programName) throw(castor::exception::InvalidArgument) {
  if(programName.length() > LOG_MAX_PROGNAMELEN) {
    castor::exception::InvalidArgument ex;
    ex.getMessage() << "Invalid argument: programName is too log: max=" <<
      LOG_MAX_PROGNAMELEN << " actual=" << programName.length();
    throw ex;
  }
}

//------------------------------------------------------------------------------
// initMutex
//------------------------------------------------------------------------------
141
void castor::log::LoggerImplementation::initMutex()
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
  throw(castor::exception::Internal) {
  pthread_mutexattr_t attr;
  int rc = pthread_mutexattr_init(&attr);
  if(0 != rc) {
    castor::exception::Internal ex;
    ex.getMessage() << "Failed to initialize mutex attribute for m_mutex: " <<
      sstrerror(rc);
    throw ex;
  }
  rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
  if(0 != rc) {
    castor::exception::Internal ex;
    ex.getMessage() << "Failed to set mutex type of m_mutex: " <<
      sstrerror(rc);
    throw ex;
  }
  rc = pthread_mutex_init(&m_mutex, NULL);
   if(0 != rc) {
     castor::exception::Internal ex;
     ex.getMessage() << "Failed to initialize m_mutex: " << sstrerror(rc);
     throw ex;
   }
  rc = pthread_mutexattr_destroy(&attr);
  if(0 != rc) {
    pthread_mutex_destroy(&m_mutex);
    castor::exception::Internal ex;
    ex.getMessage() << "Failed to destroy mutex attribute of m_mutex: " <<
      sstrerror(rc);
    throw ex;
  }
}

//------------------------------------------------------------------------------
// destructor
//------------------------------------------------------------------------------
177
castor::log::LoggerImplementation::~LoggerImplementation() throw() {
178
179
180
181
182
}

//------------------------------------------------------------------------------
// openLog
//------------------------------------------------------------------------------
183
void castor::log::LoggerImplementation::openLog() throw() {
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
  if(-1 == m_logFile) {
    struct sockaddr_un syslogAddr;
    syslogAddr.sun_family = AF_UNIX;
    strncpy(syslogAddr.sun_path, _PATH_LOG, sizeof(syslogAddr.sun_path));
    m_logFile = socket(AF_UNIX, SOCK_DGRAM, 0);
    if(-1 == m_logFile) {
      return;
    }

    if(-1 == fcntl(m_logFile, F_SETFD, FD_CLOEXEC)) {
      close(m_logFile);
      m_logFile = -1;
      return;
    }
  }
  if(!m_connected) {
    struct sockaddr_un syslogAddr;
    syslogAddr.sun_family = AF_UNIX;
    strncpy(syslogAddr.sun_path, _PATH_LOG, sizeof(syslogAddr.sun_path));
    if(-1 == connect(m_logFile, (struct sockaddr *)&syslogAddr,
      sizeof(syslogAddr))) {
      close(m_logFile);
      m_logFile = -1;
    } else {
#ifdef __APPLE__
      // MAC has has no MSG_NOSIGNAL
      // but >= 10.2 comes with SO_NOSIGPIPE
      int set = 1;
      if(0 != setsockopt(s_logFile, SOL_SOCKET, SO_NOSIGPIPE, &set,
        sizeof(int))) {
        close(m_logFile);
        m_logFile = -1;
        return;
      }
#endif
      m_connected = true;
    }
  }
}

//------------------------------------------------------------------------------
// closeLog
//------------------------------------------------------------------------------
227
void castor::log::LoggerImplementation::closeLog() throw() {
228
229
230
231
232
233
234
235
236
  if(!m_connected) {
    return;
  }
  close(m_logFile);
  m_logFile = -1;
  m_connected = false;
}

//-----------------------------------------------------------------------------
237
// logMsg
238
//-----------------------------------------------------------------------------
239
void castor::log::LoggerImplementation::logMsg(
240
241
242
  const int priority,
  const std::string &msg,
  const int numParams,
243
  const log::Param params[],
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
  const struct timeval &timeStamp) throw() {
  //---------------------------------------------------------------------------
  // Note that we do here part of the work of the real syslog call, by building
  // the message ourselves. We then only call a reduced version of syslog
  // (namely reducedSyslog). The reason behind it is to be able to set the
  // message timestamp ourselves, in case we log messages asynchronously, as
  // we do when retrieving logs from the DB
  //----------------------------------------------------------------------------

  // Try to find the textual representation of the syslog priority
  std::map<int, std::string>::const_iterator priorityTextPair =
    m_priorityToText.find(priority);

  // Do nothing if the log priority is not valid
  if(m_priorityToText.end() == priorityTextPair) {
    return;
  }

  // Safe to get a reference to the textual representation of the priority
  const std::string &priorityText = priorityTextPair->second;

  // Initialize buffer
  char buffer[LOG_MAX_LINELEN * 2];
  memset(buffer,  '\0', sizeof(buffer));

  // Start message with priority, time, program and PID (syslog standard
  // format)
  size_t len = buildSyslogHeader(buffer, m_maxMsgLen, priority | LOG_LOCAL3,
    timeStamp, getpid());

  // Append the log level, the thread id and the message text
#ifdef __APPLE__
  len += snprintf(buffer + len, m_maxMsgLen - len, "LVL=%s TID=%d MSG=\"%s\" ",
    priorityText.c_str(),(int)mach_thread_self(), msg.c_str());
#else
  len += snprintf(buffer + len, m_maxMsgLen - len, "LVL=%s TID=%d MSG=\"%s\" ",
    priorityText.c_str(),(int)syscall(__NR_gettid), msg.c_str());
#endif

  // Process parameters
  for(int i = 0; i < numParams; i++) {
    const Param &param = params[i];

    // Check the parameter name, if it's an empty string set the value to
    // "Undefined".
    const std::string name = param.getName() == "" ? "Undefined" :
      cleanString(param.getName(), true);

292
293
    // Process the parameter value
    const std::string value = cleanString(param.getValue(), false);
294

295
296
297
298
    // Write the name and value to the buffer
    len += snprintf(buffer + len, m_maxMsgLen - len, "%.*s=\"%.*s\" ",
      (int)LOG_MAX_PARAMNAMELEN, name.c_str(),
      (int)LOG_MAX_PARAMSTRLEN, value.c_str());
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317

    // Check if there is enough space in the buffer
    if(len >= m_maxMsgLen) {
      buffer[m_maxMsgLen - 1] = '\n';
      break;
    }
  }

  // Terminate the string
  if(len < m_maxMsgLen) {
    len += snprintf(buffer + (len - 1), m_maxMsgLen - len, "\n");
  }

  reducedSyslog(buffer, len);
}

//-----------------------------------------------------------------------------
// buildSyslogHeader
//-----------------------------------------------------------------------------
318
int castor::log::LoggerImplementation::buildSyslogHeader(
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
  char *const buffer,
  const int buflen,
  const int priority,
  const struct timeval &timeStamp,
  const int pid) const throw() {
  struct tm tmp;
  int len = snprintf(buffer, buflen, "<%d>", priority);
  localtime_r(&(timeStamp.tv_sec), &tmp);
  len += strftime(buffer + len, buflen - len, "%Y-%m-%dT%T", &tmp);
  len += snprintf(buffer + len, buflen - len, ".%06ld",
    (unsigned long)timeStamp.tv_usec);
  len += strftime(buffer + len, buflen - len, "%z: ", &tmp);
  // dirty trick to have the proper timezone format (':' between hh and mm)
  buffer[len-2] = buffer[len-3];
  buffer[len-3] = buffer[len-4];
  buffer[len-4] = ':';
  // if no source given, you by default the name of the process in which we run
  // print source and pid
  len += snprintf(buffer + len, buflen - len, "%s[%d]: ",
    m_programName.c_str(), pid);
  return len;
}

//-----------------------------------------------------------------------------
// cleanString
//-----------------------------------------------------------------------------
345
std::string castor::log::LoggerImplementation::cleanString(const std::string &s,
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
  const bool replaceSpaces) throw() {
  char *str = strdup(s.c_str());

  // Return an empty string if the strdup() failed
  if(NULL == str) {
    return "";
  }

  // Variables
  char *end = NULL;
  char *ptr = NULL;

  // Replace newline and tab with a space
  while (((ptr = strchr(str, '\n')) != NULL) ||
         ((ptr = strchr(str, '\t')) != NULL)) {
    *ptr = ' ';
  }

  // Remove leading whitespace
  while (isspace(*str)) str++;

  // Remove trailing whitespace
  end = str + strlen(str) - 1;
  while (end > str && isspace(*end)) end--;

  // Write new null terminator
  *(end + 1) = '\0';

  // Replace double quotes with single quotes
  while ((ptr = strchr(str, '"')) != NULL) {
    *ptr = '\'';
  }

  // Check for replacement of spaces with underscores
  if (replaceSpaces) {
    while ((ptr = strchr(str, ' ')) != NULL) {
      *ptr = '_';
    }
  }

  std::string result(str);
  free(str);
  return result;
}

//-----------------------------------------------------------------------------
// reducedSyslog
//-----------------------------------------------------------------------------
394
void castor::log::LoggerImplementation::reducedSyslog(const char *const msg,
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
  const int msgLen) throw() {
  int send_flags = 0;
#ifndef __APPLE__
  // MAC has has no MSG_NOSIGNAL
  // but >= 10.2 comes with SO_NOSIGPIPE
  send_flags = MSG_NOSIGNAL;
#endif
  // enter critical section
  pthread_mutex_lock(&m_mutex);

  // Get connected, output the message to the local logger.
  if (!m_connected) {
    openLog();
  }

  if (!m_connected ||
    send(m_logFile, msg, msgLen, send_flags) < 0) {
    if (m_connected) {
      // Try to reopen the syslog connection.  Maybe it went down.
      closeLog();
      openLog();
    }
    if (!m_connected ||
      send(m_logFile, msg, msgLen, send_flags) < 0) {
      closeLog();  // attempt re-open next time
    }
  }

  // Leave critical section.
  pthread_mutex_unlock(&m_mutex);
}

//-----------------------------------------------------------------------------
428
// logMsg
429
//-----------------------------------------------------------------------------
430
void castor::log::LoggerImplementation::logMsg(
431
  const int priority,
432
433
  const std::string &msg,
  const int numParams,
434
  const log::Param params[]) throw() {
435
436
437
438

  struct timeval timeStamp;
  gettimeofday(&timeStamp, NULL);

439
  logMsg(priority, msg, numParams, params, timeStamp);
440
441
442
}

//-----------------------------------------------------------------------------
443
// logMsg
444
//-----------------------------------------------------------------------------
445
void castor::log::LoggerImplementation::logMsg(
446
447
448
  const int priority,
  const std::string &msg) throw() {
  Param *emptyParams = NULL;
449
  logMsg(priority, msg, 0, emptyParams);
450
}