1 /*
   2  * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 #include "precompiled.hpp"
  25 #include "logging/log.hpp"
  26 #include "logging/logConfiguration.hpp"
  27 #include "logging/logFileOutput.hpp"
  28 #include "memory/allocation.inline.hpp"
  29 #include "runtime/mutexLocker.hpp"
  30 #include "runtime/os.inline.hpp"
  31 #include "utilities/globalDefinitions.hpp"
  32 #include "utilities/defaultStream.hpp"
  33 
  34 const char* LogFileOutput::FileOpenMode = "a";
  35 const char* LogFileOutput::PidFilenamePlaceholder = "%p";
  36 const char* LogFileOutput::TimestampFilenamePlaceholder = "%t";
  37 const char* LogFileOutput::TimestampFormat = "%Y-%m-%d_%H-%M-%S";
  38 const char* LogFileOutput::FileSizeOptionKey = "filesize";
  39 const char* LogFileOutput::FileCountOptionKey = "filecount";
  40 char        LogFileOutput::_pid_str[PidBufferSize];
  41 char        LogFileOutput::_vm_start_time_str[StartTimeBufferSize];
  42 
  43 LogFileOutput::LogFileOutput(const char* name)
  44     : LogFileStreamOutput(NULL), _name(os::strdup_check_oom(name, mtLogging)),
  45       _file_name(NULL), _archive_name(NULL), _archive_name_len(0), _current_size(0),
  46       _rotate_size(0), _current_file(1), _file_count(0),
  47       _rotation_lock(Mutex::leaf, "LogFileOutput rotation lock", true, Mutex::_safepoint_check_sometimes) {
  48   _file_name = make_file_name(name, _pid_str, _vm_start_time_str);
  49 }
  50 
  51 void LogFileOutput::set_file_name_parameters(jlong vm_start_time) {
  52   int res = jio_snprintf(_pid_str, sizeof(_pid_str), "%d", os::current_process_id());
  53   assert(res > 0, "PID buffer too small");
  54 
  55   struct tm local_time;
  56   time_t utc_time = vm_start_time / 1000;
  57   os::localtime_pd(&utc_time, &local_time);
  58   res = (int)strftime(_vm_start_time_str, sizeof(_vm_start_time_str), TimestampFormat, &local_time);
  59   assert(res > 0, "VM start time buffer too small.");
  60 }
  61 
  62 LogFileOutput::~LogFileOutput() {
  63   if (_stream != NULL) {
  64     if (_archive_name != NULL) {
  65       archive();
  66     }
  67     if (fclose(_stream) != 0) {
  68       jio_fprintf(defaultStream::error_stream(), "Could not close log file '%s' (%s).\n",
  69                   _file_name, strerror(errno));
  70     }
  71   }
  72   os::free(_archive_name);
  73   os::free(_file_name);
  74   os::free(const_cast<char*>(_name));
  75 }
  76 
  77 size_t LogFileOutput::parse_value(const char* value_str) {
  78   char* end;
  79   unsigned long long value = strtoull(value_str, &end, 10);
  80   if (!isdigit(*value_str) || end != value_str + strlen(value_str) || value >= SIZE_MAX) {
  81     return SIZE_MAX;
  82   }
  83   return value;
  84 }
  85 
  86 bool LogFileOutput::configure_rotation(const char* options) {
  87   if (options == NULL || strlen(options) == 0) {
  88     return true;
  89   }
  90   bool success = true;
  91   char* opts = os::strdup_check_oom(options, mtLogging);
  92 
  93   char* comma_pos;
  94   char* pos = opts;
  95   do {
  96     comma_pos = strchr(pos, ',');
  97     if (comma_pos != NULL) {
  98       *comma_pos = '\0';
  99     }
 100 
 101     char* equals_pos = strchr(pos, '=');
 102     if (equals_pos == NULL) {
 103       success = false;
 104       break;
 105     }
 106     char* key = pos;
 107     char* value_str = equals_pos + 1;
 108     *equals_pos = '\0';
 109 
 110     if (strcmp(FileCountOptionKey, key) == 0) {
 111       size_t value = parse_value(value_str);
 112       if (value == SIZE_MAX || value >= UINT_MAX) {
 113         success = false;
 114         break;
 115       }
 116       _file_count = static_cast<uint>(value);
 117       _file_count_max_digits = static_cast<uint>(log10(static_cast<double>(_file_count)) + 1);
 118       _archive_name_len = 2 + strlen(_file_name) + _file_count_max_digits;
 119       _archive_name = NEW_C_HEAP_ARRAY(char, _archive_name_len, mtLogging);
 120     } else if (strcmp(FileSizeOptionKey, key) == 0) {
 121       size_t value = parse_value(value_str);
 122       if (value == SIZE_MAX || value > SIZE_MAX / K) {
 123         success = false;
 124         break;
 125       }
 126       _rotate_size = value * K;
 127     } else {
 128       success = false;
 129       break;
 130     }
 131     pos = comma_pos + 1;
 132   } while (comma_pos != NULL);
 133 
 134   os::free(opts);
 135   return success;
 136 }
 137 
 138 bool LogFileOutput::initialize(const char* options) {
 139   if (!configure_rotation(options)) {
 140     return false;
 141   }
 142   _stream = fopen(_file_name, FileOpenMode);
 143   if (_stream == NULL) {
 144     log_error(logging)("Could not open log file '%s' (%s).\n", _file_name, strerror(errno));
 145     return false;
 146   }
 147   return true;
 148 }
 149 
 150 int LogFileOutput::write(const LogDecorations& decorations, const char* msg) {
 151   if (_stream == NULL) {
 152     // An error has occurred with this output, avoid writing to it.
 153     return 0;
 154   }
 155   int written = LogFileStreamOutput::write(decorations, msg);
 156   _current_size += written;
 157 
 158   if (should_rotate()) {
 159     rotate();
 160   }
 161 
 162   return written;
 163 }
 164 
 165 void LogFileOutput::archive() {
 166   assert(_archive_name != NULL && _archive_name_len > 0, "Rotation must be configured before using this function.");
 167   int ret = jio_snprintf(_archive_name, _archive_name_len, "%s.%0*u",
 168                          _file_name, _file_count_max_digits, _current_file);
 169   assert(ret >= 0, "Buffer should always be large enough");
 170 
 171   // Attempt to remove possibly existing archived log file before we rename.
 172   // Don't care if it fails, we really only care about the rename that follows.
 173   remove(_archive_name);
 174 
 175   // Rename the file from ex hotspot.log to hotspot.log.2
 176   if (rename(_file_name, _archive_name) == -1) {
 177     jio_fprintf(defaultStream::error_stream(), "Could not rename log file '%s' to '%s' (%s).\n",
 178                 _file_name, _archive_name, strerror(errno));
 179   }
 180 }
 181 
 182 void LogFileOutput::rotate() {
 183   MutexLockerEx ml(&_rotation_lock, true /* no safepoint check */);
 184 
 185   // Archive the current log file
 186   archive();
 187 
 188   // Open the active log file using the same stream as before
 189   _stream = freopen(_file_name, FileOpenMode, _stream);
 190   if (_stream == NULL) {
 191     jio_fprintf(defaultStream::error_stream(), "Could not reopen file '%s' during log rotation (%s).\n",
 192                 _file_name, strerror(errno));
 193     return;
 194   }
 195 
 196   // Reset accumulated size, increase current file counter, and check for file count wrap-around.
 197   _current_size = 0;
 198   _current_file = (_current_file >= _file_count ? 1 : _current_file + 1);
 199 }
 200 
 201 char* LogFileOutput::make_file_name(const char* file_name,
 202                                     const char* pid_string,
 203                                     const char* timestamp_string) {
 204   char* result = NULL;
 205 
 206   // Lets start finding out if we have any %d and/or %t in the name.
 207   // We will only replace the first occurrence of any placeholder
 208   const char* pid = strstr(file_name, PidFilenamePlaceholder);
 209   const char* timestamp = strstr(file_name, TimestampFilenamePlaceholder);
 210 
 211   if (pid == NULL && timestamp == NULL) {
 212     // We found no place-holders, return the simple filename
 213     return os::strdup_check_oom(file_name, mtLogging);
 214   }
 215 
 216   // At least one of the place-holders were found in the file_name
 217   const char* first = "";
 218   size_t first_pos = SIZE_MAX;
 219   size_t first_replace_len = 0;
 220 
 221   const char* second = "";
 222   size_t second_pos = SIZE_MAX;
 223   size_t second_replace_len = 0;
 224 
 225   // If we found a %p, then setup our variables accordingly
 226   if (pid != NULL) {
 227     if (timestamp == NULL || pid < timestamp) {
 228       first = pid_string;
 229       first_pos = pid - file_name;
 230       first_replace_len = strlen(PidFilenamePlaceholder);
 231     } else {
 232       second = pid_string;
 233       second_pos = pid - file_name;
 234       second_replace_len = strlen(PidFilenamePlaceholder);
 235     }
 236   }
 237 
 238   if (timestamp != NULL) {
 239     if (pid == NULL || timestamp < pid) {
 240       first = timestamp_string;
 241       first_pos = timestamp - file_name;
 242       first_replace_len = strlen(TimestampFilenamePlaceholder);
 243     } else {
 244       second = timestamp_string;
 245       second_pos = timestamp - file_name;
 246       second_replace_len = strlen(TimestampFilenamePlaceholder);
 247     }
 248   }
 249 
 250   size_t first_len = strlen(first);
 251   size_t second_len = strlen(second);
 252 
 253   // Allocate the new buffer, size it to hold all we want to put in there +1.
 254   size_t result_len =  strlen(file_name) + first_len - first_replace_len + second_len - second_replace_len;
 255   result = NEW_C_HEAP_ARRAY(char, result_len + 1, mtLogging);
 256 
 257   // Assemble the strings
 258   size_t file_name_pos = 0;
 259   size_t i = 0;
 260   while (i < result_len) {
 261     if (file_name_pos == first_pos) {
 262       // We are in the range of the first placeholder
 263       strcpy(result + i, first);
 264       // Bump output buffer position with length of replacing string
 265       i += first_len;
 266       // Bump source buffer position to skip placeholder
 267       file_name_pos += first_replace_len;
 268     } else if (file_name_pos == second_pos) {
 269       // We are in the range of the second placeholder
 270       strcpy(result + i, second);
 271       i += second_len;
 272       file_name_pos += second_replace_len;
 273     } else {
 274       // Else, copy char by char of the original file
 275       result[i] = file_name[file_name_pos++];
 276       i++;
 277     }
 278   }
 279   // Add terminating char
 280   result[result_len] = '\0';
 281   return result;
 282 }