LoggerImplementation.cpp 13.9 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
 *
 * 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
 *****************************************************************************/

25
#include "castor/log/LoggerImplementation.hpp"
26
27
28
29
#include "h/Castor_limits.h"
#include "h/getconfent.h"

#include <errno.h>
30
#include <sstream>
31
32
33
34
35
36
37
38
39
40
41
42
#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
  m_maxMsgLen(determineMaxMsgLen()),
  m_logFile(-1),
  m_connected(false),
  m_priorityToText(generatePriorityToTextMap()) {
  initMutex();
}

//------------------------------------------------------------------------------
// determineMaxMsgLen
//------------------------------------------------------------------------------
57
size_t castor::log::LoggerImplementation::determineMaxMsgLen() const throw() {
58
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
  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>
101
  castor::log::LoggerImplementation::generatePriorityToTextMap() const 
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
  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;
}

//------------------------------------------------------------------------------
// initMutex
//------------------------------------------------------------------------------
127
void castor::log::LoggerImplementation::initMutex()
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
  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
//------------------------------------------------------------------------------
163
castor::log::LoggerImplementation::~LoggerImplementation() throw() {
164
165
166
167
168
}

//------------------------------------------------------------------------------
// openLog
//------------------------------------------------------------------------------
169
void castor::log::LoggerImplementation::openLog() throw() {
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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
  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
//------------------------------------------------------------------------------
213
void castor::log::LoggerImplementation::closeLog() throw() {
214
215
216
217
218
219
220
221
222
  if(!m_connected) {
    return;
  }
  close(m_logFile);
  m_logFile = -1;
  m_connected = false;
}

//-----------------------------------------------------------------------------
223
// logMsg
224
//-----------------------------------------------------------------------------
225
void castor::log::LoggerImplementation::logMsg(
226
227
228
  const int priority,
  const std::string &msg,
  const int numParams,
229
  const log::Param params[],
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
  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;

251
  std::ostringstream logMsg;
252
253
254

  // Start message with priority, time, program and PID (syslog standard
  // format)
255
  logMsg << buildSyslogHeader(priority | LOG_LOCAL3, timeStamp, getpid());
256

257
  // Determine the thread id
258
#ifdef __APPLE__
259
  const int tid = mach_thread_self();
260
#else
261
  const int tid = syscall(__NR_gettid);
262
263
#endif

264
265
266
  // Append the log level, the thread id and the message text
  logMsg << "LVL=" << priorityText << " TID=" << tid << " MSG=\"" << msg << "\" ";

267
268
269
270
271
272
273
274
275
  // 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);

276
277
    // Process the parameter value
    const std::string value = cleanString(param.getValue(), false);
278

279
    // Write the name and value to the buffer
280
    logMsg << name << "=\"" << value << "\" ";
281
282
283
  }

  // Terminate the string
284
285
286
287
288
289
290
291
292
293
294
  logMsg << "\n";

  // If the message is too long for syslog then truncate it before calling
  // reducedSyslog
  if(logMsg.str().length() > m_maxMsgLen) {
    std::ostringstream truncatedLogMsg;
    truncatedLogMsg << logMsg.str().substr(0, m_maxMsgLen - 1);
    truncatedLogMsg << "\n";
    reducedSyslog(truncatedLogMsg.str());
  } else {
    reducedSyslog(logMsg.str());
295
296
297
298
299
300
  }
}

//-----------------------------------------------------------------------------
// buildSyslogHeader
//-----------------------------------------------------------------------------
301
std::string castor::log::LoggerImplementation::buildSyslogHeader(
302
303
304
  const int priority,
  const struct timeval &timeStamp,
  const int pid) const throw() {
305
306
307
308
309
310
311
312
313
314
315
  char buf[80];
  int bufLen = sizeof(buf);
  int len = 0;
  std::ostringstream oss;

  oss << "<" << priority << ">";

  struct tm localTime;
  localtime_r(&(timeStamp.tv_sec), &localTime);
  len += strftime(buf, bufLen, "%Y-%m-%dT%T", &localTime);
  len += snprintf(buf + len, bufLen - len, ".%06ld",
316
    (unsigned long)timeStamp.tv_usec);
317
  len += strftime(buf + len, bufLen - len, "%z: ", &localTime);
318
  // dirty trick to have the proper timezone format (':' between hh and mm)
319
320
321
322
323
324
  buf[len-2] = buf[len-3];
  buf[len-3] = buf[len-4];
  buf[len-4] = ':';
  buf[sizeof(buf) - 1] = '\0';
  oss << buf << m_programName.c_str() << "[" << pid << "]: ";
  return oss.str();
325
326
327
328
329
}

//-----------------------------------------------------------------------------
// cleanString
//-----------------------------------------------------------------------------
330
std::string castor::log::LoggerImplementation::cleanString(const std::string &s,
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
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
  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
//-----------------------------------------------------------------------------
379
380
void castor::log::LoggerImplementation::reducedSyslog(const std::string &msg)
  throw() {
381
382
383
384
385
386
387
388
389
  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);

390
391
  // Try to connect if not already connected
  if(!m_connected) {
392
393
394
    openLog();
  }

395
396
397
398
399
  // If connected
  if(m_connected) {
    // If sending the log message fails then try to reopen the syslog
    // connection and try again
    if(0 > send(m_logFile, msg.c_str(), msg.length(), send_flags)) {
400
401
      closeLog();
      openLog();
402
403
404
405
406
407
408
      if (m_connected) {
        // If the second attempt to send the log message fails then give up and
        // attempt re-open next time
        if(0 > send(m_logFile, msg.c_str(), msg.length(), send_flags)) {
          closeLog();
        }
      }
409
410
411
412
413
414
415
416
    }
  }

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

//-----------------------------------------------------------------------------
417
// logMsg
418
//-----------------------------------------------------------------------------
419
void castor::log::LoggerImplementation::logMsg(
420
  const int priority,
421
422
  const std::string &msg,
  const int numParams,
423
  const log::Param params[]) throw() {
424
425
426
427

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

428
  logMsg(priority, msg, numParams, params, timeStamp);
429
430
431
}

//-----------------------------------------------------------------------------
432
// logMsg
433
//-----------------------------------------------------------------------------
434
void castor::log::LoggerImplementation::logMsg(
435
436
437
  const int priority,
  const std::string &msg) throw() {
  Param *emptyParams = NULL;
438
  logMsg(priority, msg, 0, emptyParams);
439
}