summaryrefslogtreecommitdiff
path: root/open-vm-tools/lib/glibUtils/fileLogger.c
blob: 14df1c8f5744ceb0d26c80d77ac42d6544215aa8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
101
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
127
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
163
164
165
166
167
168
169
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
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
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/*********************************************************
 * Copyright (C) 2010 VMware, Inc. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA.
 *
 *********************************************************/

/**
 * @file fileLogger.c
 *
 * Logger that uses file streams and provides optional log rotation.
 */

#include "glibUtils.h"
#include <stdio.h>
#include <string.h>
#include <glib/gstdio.h>
#if defined(G_PLATFORM_WIN32)
#  include <process.h>
#  include <windows.h>
#else
#  include <fcntl.h>
#  include <unistd.h>
#endif


typedef struct FileLogger {
   GlibLogger     handler;
   GIOChannel    *file;
   gchar         *path;
   gint           logSize;
   guint64        maxSize;
   guint          maxFiles;
   gboolean       append;
   gboolean       error;
   GStaticMutex   lock;
} FileLogger;


#if !defined(_WIN32)
/*
 *******************************************************************************
 * FileLoggerIsValid --                                                   */ /**
 *
 * Checks that the file descriptor backing this logger is still valid.
 *
 * This is a racy workaround for an issue with glib code; or, rather, two
 * issues. The first issue is that we can't intercept G_LOG_FLAG_RECURSION,
 * and glib just aborts when that happens (see gnome bug 618956). The second
 * is that if a GIOChannel channel write fails, that calls
 * g_io_channel_error_from_errno, which helpfully logs stuff, causing recursion.
 * Don't get me started on why that's, well, at least questionable.
 *
 * This is racy because between the check and the actual GIOChannel operation,
 * the state of the FD may have changed. In reality, since the bug this is
 * fixing happens in very special situations where code outside this file is
 * doing weird things like closing random fds, it should be OK.
 *
 * We may still get other write errors from the GIOChannel than EBADF, but
 * those would be harder to work around. Hopefully this handles the most usual
 * cases.
 *
 * See bug 783999 for some details about what triggers the bug.
 *
 * @param[in] logger The logger instance.
 *
 * @return TRUE if the I/O channel is still valid.
 *
 *******************************************************************************
 */

static gboolean
FileLoggerIsValid(FileLogger *logger)
{
   if (logger->file != NULL) {
      int fd = g_io_channel_unix_get_fd(logger->file);
      return fcntl(fd, F_GETFD) >= 0;
   }

   return FALSE;
}

#else

#define FileLoggerIsValid(logger) TRUE

#endif


/*
 *******************************************************************************
 * FileLoggerGetPath --                                                   */ /**
 *
 * Parses the given template file name and expands embedded variables, and
 * places the log index information at the right position.
 *
 * The following variables are expanded:
 *
 *    - ${USER}:  user's login name.
 *    - ${PID}:   current process's pid.
 *    - ${IDX}:   index of the log file (for rotation).
 *
 * @param[in] data         Log handler data.
 * @param[in] index        Index of the log file.
 *
 * @return The expanded log file path.
 *
 ******************************************************************************
 */

static gchar *
FileLoggerGetPath(FileLogger *data,
                  gint index)
{
   gboolean hasIndex = FALSE;
   gchar indexStr[11];
   gchar *logpath;
   gchar *vars[] = {
      "${USER}",  NULL,
      "${PID}",   NULL,
      "${IDX}",   indexStr,
   };
   gchar *tmp;
   size_t i;

   logpath = g_strdup(data->path);
   vars[1] = (char *) g_get_user_name();
   vars[3] = g_strdup_printf("%u", (unsigned int) getpid());
   g_snprintf(indexStr, sizeof indexStr, "%d", index);

   for (i = 0; i < G_N_ELEMENTS(vars); i += 2) {
      char *last = logpath;
      char *start;
      while ((start = strstr(last, vars[i])) != NULL) {
         gchar *tmp;
         char *end = start + strlen(vars[i]);
         size_t offset = (start - last) + strlen(vars[i+1]);

         *start = '\0';
         tmp = g_strdup_printf("%s%s%s", logpath, vars[i+1], end);
         g_free(logpath);
         logpath = tmp;
         last = logpath + offset;

         /* XXX: ugly, but well... */
         if (i == 4) {
            hasIndex = TRUE;
         }
      }
   }

   g_free(vars[3]);

   /*
    * Always make sure we add the index if it's not 0, since that's used for
    * backing up old log files.
    */
   if (index != 0 && !hasIndex) {
      char *sep = strrchr(logpath, '.');
      char *pathsep = strrchr(logpath, '/');

      if (pathsep == NULL) {
         pathsep = strrchr(logpath, '\\');
      }

      if (sep != NULL && sep > pathsep) {
         *sep = '\0';
         sep++;
         tmp = g_strdup_printf("%s.%d.%s", logpath, index, sep);
      } else {
         tmp = g_strdup_printf("%s.%d", logpath, index);
      }
      g_free(logpath);
      logpath = tmp;
   }

   return logpath;
}


/*
 *******************************************************************************
 * FileLoggerOpen --                                                      */ /**
 *
 * Opens a log file for writing, backing up the existing log file if one is
 * present. Only one old log file is preserved.
 *
 * @note Make sure this function is called with the write lock held.
 *
 * @param[in] data   Log handler data.
 *
 * @return Log file pointer (NULL on error).
 *
 *******************************************************************************
 */

static GIOChannel *
FileLoggerOpen(FileLogger *data)
{
   GIOChannel *logfile = NULL;
   gchar *path;

   g_return_val_if_fail(data != NULL, NULL);
   path = FileLoggerGetPath(data, 0);

   if (g_file_test(path, G_FILE_TEST_EXISTS)) {
      struct stat fstats;
      if (g_stat(path, &fstats) > -1) {
         data->logSize = (gint) fstats.st_size;
      }

      if (!data->append || data->logSize >= data->maxSize) {
         /*
          * Find the last log file and iterate back, changing the indices as we go,
          * so that the oldest log file has the highest index (the new log file
          * will always be index "0"). When not rotating, "maxFiles" is 1, so we
          * always keep one backup.
          */
         gchar *log;
         guint id;
         GPtrArray *logfiles = g_ptr_array_new();

         /*
          * Find the id of the last log file. The pointer array will hold
          * the names of all existing log files + the name of the last log
          * file, which may or may not exist.
          */
         for (id = 0; id < data->maxFiles; id++) {
            log = FileLoggerGetPath(data, id);
            g_ptr_array_add(logfiles, log);
            if (!g_file_test(log, G_FILE_TEST_IS_REGULAR)) {
               break;
            }
         }

         /* Rename the existing log files, increasing their index by 1. */
         for (id = logfiles->len - 1; id > 0; id--) {
            gchar *dest = g_ptr_array_index(logfiles, id);
            gchar *src = g_ptr_array_index(logfiles, id - 1);

            if (!g_file_test(dest, G_FILE_TEST_IS_DIR) &&
                (!g_file_test(dest, G_FILE_TEST_EXISTS) ||
                 g_unlink(dest) == 0)) {
               g_rename(src, dest);
            } else {
               g_unlink(src);
            }
         }

         /* Cleanup. */
         for (id = 0; id < logfiles->len; id++) {
            g_free(g_ptr_array_index(logfiles, id));
         }
         g_ptr_array_free(logfiles, TRUE);
         data->logSize = 0;
         data->append = FALSE;
      }
   }

   logfile = g_io_channel_new_file(path, data->append ? "a" : "w", NULL);
   g_free(path);

   if (logfile != NULL) {
      g_io_channel_set_encoding(logfile, NULL, NULL);
   }

   return logfile;
}


/*
 *******************************************************************************
 * FileLoggerLog --                                                       */ /**
 *
 * Logs a message to the configured destination file. Also opens the file for
 * writing if it hasn't been done yet.
 *
 * @param[in] domain    Log domain.
 * @param[in] level     Log level.
 * @param[in] message   Message to log.
 * @param[in] data      File logger.
 *
 *******************************************************************************
 */

static void
FileLoggerLog(const gchar *domain,
              GLogLevelFlags level,
              const gchar *message,
              gpointer data)
{
   FileLogger *logger = data;
   gsize written;

   g_static_mutex_lock(&logger->lock);

   if (logger->error) {
      goto exit;
   }

   if (logger->file == NULL) {
      if (logger->file == NULL) {
         logger->file = FileLoggerOpen(data);
      }
      if (logger->file == NULL) {
         logger->error = TRUE;
         goto exit;
      }
   }

   if (!FileLoggerIsValid(logger)) {
      logger->error = TRUE;
      goto exit;
   }

   /* Write the log file and do log rotation accounting. */
   if (g_io_channel_write_chars(logger->file, message, -1, &written, NULL) ==
       G_IO_STATUS_NORMAL) {
      if (logger->maxSize > 0) {
         logger->logSize += (gint) written;
         if (logger->logSize >= logger->maxSize) {
            g_io_channel_unref(logger->file);
            logger->append = FALSE;
            logger->file = FileLoggerOpen(logger);
         } else {
            g_io_channel_flush(logger->file, NULL);
         }
      } else {
         g_io_channel_flush(logger->file, NULL);
      }
   }

exit:
   g_static_mutex_unlock(&logger->lock);
}


/*
 ******************************************************************************
 * FileLoggerDestroy --                                               */ /**
 *
 * Cleans up the internal state of a file logger.
 *
 * @param[in] _data     File logger data.
 *
 ******************************************************************************
 */

static void
FileLoggerDestroy(gpointer data)
{
   FileLogger *logger = data;
   if (logger->file != NULL) {
      g_io_channel_unref(logger->file);
   }
   g_static_mutex_free(&logger->lock);
   g_free(logger->path);
   g_free(logger);
}


/*
 *******************************************************************************
 * GlibUtils_CreateFileLogger --                                          */ /**
 *
 * @brief Creates a new file logger based on the given configuration.
 *
 * @param[in] path      Path to log file.
 * @param[in] append    Whether to append to existing log file.
 * @param[in] maxSize   Maximum log file size (in MB, 0 = no limit).
 * @param[in] maxFiles  Maximum number of old files to be kept.
 *
 * @return A new logger, or NULL on error.
 *
 *******************************************************************************
 */

GlibLogger *
GlibUtils_CreateFileLogger(const char *path,
                           gboolean append,
                           guint maxSize,
                           guint maxFiles)
{
   FileLogger *data = NULL;

   g_return_val_if_fail(path != NULL, NULL);

   data = g_new0(FileLogger, 1);
   data->handler.addsTimestamp = FALSE;
   data->handler.shared = FALSE;
   data->handler.logfn = FileLoggerLog;
   data->handler.dtor = FileLoggerDestroy;

   data->path = g_filename_from_utf8(path, -1, NULL, NULL, NULL);
   if (data->path == NULL) {
      g_free(data);
      return NULL;
   }

   data->append = append;
   data->maxSize = maxSize * 1024 * 1024;
   data->maxFiles = maxFiles + 1; /* To account for the active log file. */
   g_static_mutex_init(&data->lock);

   return &data->handler;
}