Path: blob/master/src/hotspot/share/logging/logFileOutput.cpp
40930 views
/*1* Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/23#include "precompiled.hpp"24#include "jvm.h"25#include "logging/log.hpp"26#include "logging/logAsyncWriter.hpp"27#include "logging/logConfiguration.hpp"28#include "logging/logFileOutput.hpp"29#include "memory/allocation.inline.hpp"30#include "runtime/arguments.hpp"31#include "runtime/os.hpp"32#include "utilities/globalDefinitions.hpp"33#include "utilities/defaultStream.hpp"3435const char* const LogFileOutput::Prefix = "file=";36const char* const LogFileOutput::FileOpenMode = "a";37const char* const LogFileOutput::PidFilenamePlaceholder = "%p";38const char* const LogFileOutput::TimestampFilenamePlaceholder = "%t";39const char* const LogFileOutput::TimestampFormat = "%Y-%m-%d_%H-%M-%S";40const char* const LogFileOutput::FileSizeOptionKey = "filesize";41const char* const LogFileOutput::FileCountOptionKey = "filecount";42char LogFileOutput::_pid_str[PidBufferSize];43char LogFileOutput::_vm_start_time_str[StartTimeBufferSize];4445LogFileOutput::LogFileOutput(const char* name)46: LogFileStreamOutput(NULL), _name(os::strdup_check_oom(name, mtLogging)),47_file_name(NULL), _archive_name(NULL), _current_file(0),48_file_count(DefaultFileCount), _is_default_file_count(true), _archive_name_len(0),49_rotate_size(DefaultFileSize), _current_size(0), _rotation_semaphore(1) {50assert(strstr(name, Prefix) == name, "invalid output name '%s': missing prefix: %s", name, Prefix);51_file_name = make_file_name(name + strlen(Prefix), _pid_str, _vm_start_time_str);52}5354const char* LogFileOutput::cur_log_file_name() {55if (strlen(_archive_name) == 0) {56return _file_name;57} else {58return _archive_name;59}60}6162void LogFileOutput::set_file_name_parameters(jlong vm_start_time) {63int res = jio_snprintf(_pid_str, sizeof(_pid_str), "%d", os::current_process_id());64assert(res > 0, "PID buffer too small");6566struct tm local_time;67time_t utc_time = vm_start_time / 1000;68os::localtime_pd(&utc_time, &local_time);69res = (int)strftime(_vm_start_time_str, sizeof(_vm_start_time_str), TimestampFormat, &local_time);70assert(res > 0, "VM start time buffer too small.");71}7273LogFileOutput::~LogFileOutput() {74if (_stream != NULL) {75if (fclose(_stream) != 0) {76jio_fprintf(defaultStream::error_stream(), "Could not close log file '%s' (%s).\n",77_file_name, os::strerror(errno));78}79}80os::free(_archive_name);81os::free(_file_name);82os::free(const_cast<char*>(_name));83}8485static size_t parse_value(const char* value_str) {86char* end;87unsigned long long value = strtoull(value_str, &end, 10);88if (!isdigit(*value_str) || end != value_str + strlen(value_str) || value >= SIZE_MAX) {89return SIZE_MAX;90}91return value;92}9394static bool file_exists(const char* filename) {95struct stat dummy_stat;96return os::stat(filename, &dummy_stat) == 0;97}9899static uint number_of_digits(uint number) {100return number < 10 ? 1 : (number < 100 ? 2 : 3);101}102103static bool is_regular_file(const char* filename) {104struct stat st;105int ret = os::stat(filename, &st);106if (ret != 0) {107return false;108}109return (st.st_mode & S_IFMT) == S_IFREG;110}111112static bool is_fifo_file(const char* filename) {113struct stat st;114int ret = os::stat(filename, &st);115if (ret != 0) {116return false;117}118return S_ISFIFO(st.st_mode);119}120121// Try to find the next number that should be used for file rotation.122// Return UINT_MAX on error.123static uint next_file_number(const char* filename,124uint number_of_digits,125uint filecount,126outputStream* errstream) {127bool found = false;128uint next_num = 0;129130// len is filename + dot + digits + null char131size_t len = strlen(filename) + number_of_digits + 2;132char* archive_name = NEW_C_HEAP_ARRAY(char, len, mtLogging);133char* oldest_name = NEW_C_HEAP_ARRAY(char, len, mtLogging);134135for (uint i = 0; i < filecount; i++) {136int ret = jio_snprintf(archive_name, len, "%s.%0*u",137filename, number_of_digits, i);138assert(ret > 0 && static_cast<size_t>(ret) == len - 1,139"incorrect buffer length calculation");140141if (file_exists(archive_name) && !is_regular_file(archive_name)) {142// We've encountered something that's not a regular file among the143// possible file rotation targets. Fail immediately to prevent144// problems later.145errstream->print_cr("Possible rotation target file '%s' already exists "146"but is not a regular file.", archive_name);147next_num = UINT_MAX;148break;149}150151// Stop looking if we find an unused file name152if (!file_exists(archive_name)) {153next_num = i;154found = true;155break;156}157158// Keep track of oldest existing log file159if (!found160|| os::compare_file_modified_times(oldest_name, archive_name) > 0) {161strcpy(oldest_name, archive_name);162next_num = i;163found = true;164}165}166167FREE_C_HEAP_ARRAY(char, oldest_name);168FREE_C_HEAP_ARRAY(char, archive_name);169return next_num;170}171172bool LogFileOutput::parse_options(const char* options, outputStream* errstream) {173if (options == NULL || strlen(options) == 0) {174return true;175}176bool success = true;177char* opts = os::strdup_check_oom(options, mtLogging);178179char* comma_pos;180char* pos = opts;181do {182comma_pos = strchr(pos, ',');183if (comma_pos != NULL) {184*comma_pos = '\0';185}186187char* equals_pos = strchr(pos, '=');188if (equals_pos == NULL) {189errstream->print_cr("Invalid option '%s' for log file output.", pos);190success = false;191break;192}193char* key = pos;194char* value_str = equals_pos + 1;195*equals_pos = '\0';196197if (strcmp(FileCountOptionKey, key) == 0) {198size_t value = parse_value(value_str);199if (value > MaxRotationFileCount) {200errstream->print_cr("Invalid option: %s must be in range [0, %u]",201FileCountOptionKey,202MaxRotationFileCount);203success = false;204break;205}206_file_count = static_cast<uint>(value);207_is_default_file_count = false;208} else if (strcmp(FileSizeOptionKey, key) == 0) {209julong value;210success = Arguments::atojulong(value_str, &value);211if (!success || (value > SIZE_MAX)) {212errstream->print_cr("Invalid option: %s must be in range [0, "213SIZE_FORMAT "]", FileSizeOptionKey, (size_t)SIZE_MAX);214success = false;215break;216}217_rotate_size = static_cast<size_t>(value);218} else {219errstream->print_cr("Invalid option '%s' for log file output.", key);220success = false;221break;222}223pos = comma_pos + 1;224} while (comma_pos != NULL);225226os::free(opts);227return success;228}229230bool LogFileOutput::initialize(const char* options, outputStream* errstream) {231if (!parse_options(options, errstream)) {232return false;233}234235bool file_exist = file_exists(_file_name);236if (file_exist && _is_default_file_count && is_fifo_file(_file_name)) {237_file_count = 0; // Prevent file rotation for fifo's such as named pipes.238}239240if (_file_count > 0) {241// compute digits with filecount - 1 since numbers will start from 0242_file_count_max_digits = number_of_digits(_file_count - 1);243_archive_name_len = 2 + strlen(_file_name) + _file_count_max_digits;244_archive_name = NEW_C_HEAP_ARRAY(char, _archive_name_len, mtLogging);245_archive_name[0] = 0;246}247248log_trace(logging)("Initializing logging to file '%s' (filecount: %u"249", filesize: " SIZE_FORMAT " KiB).",250_file_name, _file_count, _rotate_size / K);251252if (_file_count > 0 && file_exist) {253if (!is_regular_file(_file_name)) {254errstream->print_cr("Unable to log to file %s with log file rotation: "255"%s is not a regular file",256_file_name, _file_name);257return false;258}259_current_file = next_file_number(_file_name,260_file_count_max_digits,261_file_count,262errstream);263if (_current_file == UINT_MAX) {264return false;265}266log_trace(logging)("Existing log file found, saving it as '%s.%0*u'",267_file_name, _file_count_max_digits, _current_file);268archive();269increment_file_count();270}271272_stream = os::fopen(_file_name, FileOpenMode);273if (_stream == NULL) {274errstream->print_cr("Error opening log file '%s': %s",275_file_name, os::strerror(errno));276return false;277}278279if (_file_count == 0 && is_regular_file(_file_name)) {280log_trace(logging)("Truncating log file");281os::ftruncate(os::get_fileno(_stream), 0);282}283284return true;285}286287int LogFileOutput::write_blocking(const LogDecorations& decorations, const char* msg) {288_rotation_semaphore.wait();289int written = LogFileStreamOutput::write(decorations, msg);290if (written > 0) {291_current_size += written;292293if (should_rotate()) {294rotate();295}296}297_rotation_semaphore.signal();298299return written;300}301302int LogFileOutput::write(const LogDecorations& decorations, const char* msg) {303if (_stream == NULL) {304// An error has occurred with this output, avoid writing to it.305return 0;306}307308AsyncLogWriter* aio_writer = AsyncLogWriter::instance();309if (aio_writer != nullptr) {310aio_writer->enqueue(*this, decorations, msg);311return 0;312}313314return write_blocking(decorations, msg);315}316317int LogFileOutput::write(LogMessageBuffer::Iterator msg_iterator) {318if (_stream == NULL) {319// An error has occurred with this output, avoid writing to it.320return 0;321}322323AsyncLogWriter* aio_writer = AsyncLogWriter::instance();324if (aio_writer != nullptr) {325aio_writer->enqueue(*this, msg_iterator);326return 0;327}328329_rotation_semaphore.wait();330int written = LogFileStreamOutput::write(msg_iterator);331if (written > 0) {332_current_size += written;333334if (should_rotate()) {335rotate();336}337}338_rotation_semaphore.signal();339340return written;341}342343void LogFileOutput::archive() {344assert(_archive_name != NULL && _archive_name_len > 0, "Rotation must be configured before using this function.");345int ret = jio_snprintf(_archive_name, _archive_name_len, "%s.%0*u",346_file_name, _file_count_max_digits, _current_file);347assert(ret >= 0, "Buffer should always be large enough");348349// Attempt to remove possibly existing archived log file before we rename.350// Don't care if it fails, we really only care about the rename that follows.351remove(_archive_name);352353// Rename the file from ex hotspot.log to hotspot.log.2354if (rename(_file_name, _archive_name) == -1) {355jio_fprintf(defaultStream::error_stream(), "Could not rename log file '%s' to '%s' (%s).\n",356_file_name, _archive_name, os::strerror(errno));357}358}359360void LogFileOutput::force_rotate() {361if (_file_count == 0) {362// Rotation not possible363return;364}365_rotation_semaphore.wait();366rotate();367_rotation_semaphore.signal();368}369370void LogFileOutput::rotate() {371372if (fclose(_stream)) {373jio_fprintf(defaultStream::error_stream(), "Error closing file '%s' during log rotation (%s).\n",374_file_name, os::strerror(errno));375}376377// Archive the current log file378archive();379380// Open the active log file using the same stream as before381_stream = os::fopen(_file_name, FileOpenMode);382if (_stream == NULL) {383jio_fprintf(defaultStream::error_stream(), "Could not reopen file '%s' during log rotation (%s).\n",384_file_name, os::strerror(errno));385return;386}387388// Reset accumulated size, increase current file counter, and check for file count wrap-around.389_current_size = 0;390increment_file_count();391}392393char* LogFileOutput::make_file_name(const char* file_name,394const char* pid_string,395const char* timestamp_string) {396char* result = NULL;397398// Lets start finding out if we have any %d and/or %t in the name.399// We will only replace the first occurrence of any placeholder400const char* pid = strstr(file_name, PidFilenamePlaceholder);401const char* timestamp = strstr(file_name, TimestampFilenamePlaceholder);402403if (pid == NULL && timestamp == NULL) {404// We found no place-holders, return the simple filename405return os::strdup_check_oom(file_name, mtLogging);406}407408// At least one of the place-holders were found in the file_name409const char* first = "";410size_t first_pos = SIZE_MAX;411size_t first_replace_len = 0;412413const char* second = "";414size_t second_pos = SIZE_MAX;415size_t second_replace_len = 0;416417// If we found a %p, then setup our variables accordingly418if (pid != NULL) {419if (timestamp == NULL || pid < timestamp) {420first = pid_string;421first_pos = pid - file_name;422first_replace_len = strlen(PidFilenamePlaceholder);423} else {424second = pid_string;425second_pos = pid - file_name;426second_replace_len = strlen(PidFilenamePlaceholder);427}428}429430if (timestamp != NULL) {431if (pid == NULL || timestamp < pid) {432first = timestamp_string;433first_pos = timestamp - file_name;434first_replace_len = strlen(TimestampFilenamePlaceholder);435} else {436second = timestamp_string;437second_pos = timestamp - file_name;438second_replace_len = strlen(TimestampFilenamePlaceholder);439}440}441442size_t first_len = strlen(first);443size_t second_len = strlen(second);444445// Allocate the new buffer, size it to hold all we want to put in there +1.446size_t result_len = strlen(file_name) + first_len - first_replace_len + second_len - second_replace_len;447result = NEW_C_HEAP_ARRAY(char, result_len + 1, mtLogging);448449// Assemble the strings450size_t file_name_pos = 0;451size_t i = 0;452while (i < result_len) {453if (file_name_pos == first_pos) {454// We are in the range of the first placeholder455strcpy(result + i, first);456// Bump output buffer position with length of replacing string457i += first_len;458// Bump source buffer position to skip placeholder459file_name_pos += first_replace_len;460} else if (file_name_pos == second_pos) {461// We are in the range of the second placeholder462strcpy(result + i, second);463i += second_len;464file_name_pos += second_replace_len;465} else {466// Else, copy char by char of the original file467result[i] = file_name[file_name_pos++];468i++;469}470}471// Add terminating char472result[result_len] = '\0';473return result;474}475476void LogFileOutput::describe(outputStream *out) {477LogOutput::describe(out);478out->print(" ");479480out->print("filecount=%u,filesize=" SIZE_FORMAT "%s,async=%s", _file_count,481byte_size_in_proper_unit(_rotate_size),482proper_unit_for_byte_size(_rotate_size),483LogConfiguration::is_async_mode() ? "true" : "false");484}485486487