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
#include <stdlib.h>
32
33
34
35
36
37
38
39
40
41
42
43
#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
//------------------------------------------------------------------------------
44
castor::log::LoggerImplementation::LoggerImplementation(
45
46
  const std::string &programName)
  throw(castor::exception::Internal, castor::exception::InvalidArgument):
47
  Logger(programName),
48
49
50
51
52
53
54
55
56
57
  m_maxMsgLen(determineMaxMsgLen()),
  m_logFile(-1),
  m_connected(false),
  m_priorityToText(generatePriorityToTextMap()) {
  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;
}

//------------------------------------------------------------------------------
// initMutex
//------------------------------------------------------------------------------
128
void castor::log::LoggerImplementation::initMutex()
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
163
  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
//------------------------------------------------------------------------------
164
castor::log::LoggerImplementation::~LoggerImplementation() throw() {
165
166
167
168
169
}

//------------------------------------------------------------------------------
// openLog
//------------------------------------------------------------------------------
170
void castor::log::LoggerImplementation::openLog() throw() {
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
213
  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
//------------------------------------------------------------------------------
214
void castor::log::LoggerImplementation::closeLog() throw() {
215
216
217
218
219
220
221
222
223
  if(!m_connected) {
    return;
  }
  close(m_logFile);
  m_logFile = -1;
  m_connected = false;
}

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

252
  std::ostringstream logMsg;
253
254
255

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

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

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

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

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

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

  // Terminate the string
285
286
287
288
289
290
291
292
293
294
295
  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());
296
297
298
299
300
301
  }
}

//-----------------------------------------------------------------------------
// buildSyslogHeader
//-----------------------------------------------------------------------------
302
std::string castor::log::LoggerImplementation::buildSyslogHeader(
303
304
305
  const int priority,
  const struct timeval &timeStamp,
  const int pid) const throw() {
306
307
308
309
310
311
312
313
314
315
316
  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",
317
    (unsigned long)timeStamp.tv_usec);
318
  len += strftime(buf + len, bufLen - len, "%z: ", &localTime);
319
  // dirty trick to have the proper timezone format (':' between hh and mm)
320
321
322
323
324
325
  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();
326
327
328
329
330
}

//-----------------------------------------------------------------------------
// cleanString
//-----------------------------------------------------------------------------
331
std::string castor::log::LoggerImplementation::cleanString(const std::string &s,
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
379
  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
//-----------------------------------------------------------------------------
380
381
void castor::log::LoggerImplementation::reducedSyslog(const std::string &msg)
  throw() {
382
383
384
385
386
387
388
389
390
  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);

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

396
397
398
399
400
  // 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)) {
401
402
      closeLog();
      openLog();
403
404
405
406
407
408
409
      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();
        }
      }
410
411
412
413
414
415
416
417
    }
  }

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

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

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

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

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