Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/jdk17u
Path: blob/master/src/hotspot/share/logging/logFileOutput.cpp
64440 views
1
/*
2
* Copyright (c) 2015, 2021, 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 "jvm.h"
26
#include "logging/log.hpp"
27
#include "logging/logAsyncWriter.hpp"
28
#include "logging/logConfiguration.hpp"
29
#include "logging/logFileOutput.hpp"
30
#include "memory/allocation.inline.hpp"
31
#include "runtime/arguments.hpp"
32
#include "runtime/os.hpp"
33
#include "utilities/globalDefinitions.hpp"
34
#include "utilities/defaultStream.hpp"
35
36
const char* const LogFileOutput::Prefix = "file=";
37
const char* const LogFileOutput::FileOpenMode = "a";
38
const char* const LogFileOutput::PidFilenamePlaceholder = "%p";
39
const char* const LogFileOutput::TimestampFilenamePlaceholder = "%t";
40
const char* const LogFileOutput::TimestampFormat = "%Y-%m-%d_%H-%M-%S";
41
const char* const LogFileOutput::FileSizeOptionKey = "filesize";
42
const char* const LogFileOutput::FileCountOptionKey = "filecount";
43
char LogFileOutput::_pid_str[PidBufferSize];
44
char LogFileOutput::_vm_start_time_str[StartTimeBufferSize];
45
46
LogFileOutput::LogFileOutput(const char* name)
47
: LogFileStreamOutput(NULL), _name(os::strdup_check_oom(name, mtLogging)),
48
_file_name(NULL), _archive_name(NULL), _current_file(0),
49
_file_count(DefaultFileCount), _is_default_file_count(true), _archive_name_len(0),
50
_rotate_size(DefaultFileSize), _current_size(0), _rotation_semaphore(1) {
51
assert(strstr(name, Prefix) == name, "invalid output name '%s': missing prefix: %s", name, Prefix);
52
_file_name = make_file_name(name + strlen(Prefix), _pid_str, _vm_start_time_str);
53
}
54
55
const char* LogFileOutput::cur_log_file_name() {
56
if (strlen(_archive_name) == 0) {
57
return _file_name;
58
} else {
59
return _archive_name;
60
}
61
}
62
63
void LogFileOutput::set_file_name_parameters(jlong vm_start_time) {
64
int res = jio_snprintf(_pid_str, sizeof(_pid_str), "%d", os::current_process_id());
65
assert(res > 0, "PID buffer too small");
66
67
struct tm local_time;
68
time_t utc_time = vm_start_time / 1000;
69
os::localtime_pd(&utc_time, &local_time);
70
res = (int)strftime(_vm_start_time_str, sizeof(_vm_start_time_str), TimestampFormat, &local_time);
71
assert(res > 0, "VM start time buffer too small.");
72
}
73
74
LogFileOutput::~LogFileOutput() {
75
if (_stream != NULL) {
76
if (fclose(_stream) != 0) {
77
jio_fprintf(defaultStream::error_stream(), "Could not close log file '%s' (%s).\n",
78
_file_name, os::strerror(errno));
79
}
80
}
81
os::free(_archive_name);
82
os::free(_file_name);
83
os::free(const_cast<char*>(_name));
84
}
85
86
static size_t parse_value(const char* value_str) {
87
char* end;
88
unsigned long long value = strtoull(value_str, &end, 10);
89
if (!isdigit(*value_str) || end != value_str + strlen(value_str) || value >= SIZE_MAX) {
90
return SIZE_MAX;
91
}
92
return value;
93
}
94
95
static bool file_exists(const char* filename) {
96
struct stat dummy_stat;
97
return os::stat(filename, &dummy_stat) == 0;
98
}
99
100
static uint number_of_digits(uint number) {
101
return number < 10 ? 1 : (number < 100 ? 2 : 3);
102
}
103
104
static bool is_regular_file(const char* filename) {
105
struct stat st;
106
int ret = os::stat(filename, &st);
107
if (ret != 0) {
108
return false;
109
}
110
return (st.st_mode & S_IFMT) == S_IFREG;
111
}
112
113
static bool is_fifo_file(const char* filename) {
114
struct stat st;
115
int ret = os::stat(filename, &st);
116
if (ret != 0) {
117
return false;
118
}
119
return S_ISFIFO(st.st_mode);
120
}
121
122
// Try to find the next number that should be used for file rotation.
123
// Return UINT_MAX on error.
124
static uint next_file_number(const char* filename,
125
uint number_of_digits,
126
uint filecount,
127
outputStream* errstream) {
128
bool found = false;
129
uint next_num = 0;
130
131
// len is filename + dot + digits + null char
132
size_t len = strlen(filename) + number_of_digits + 2;
133
char* archive_name = NEW_C_HEAP_ARRAY(char, len, mtLogging);
134
char* oldest_name = NEW_C_HEAP_ARRAY(char, len, mtLogging);
135
136
for (uint i = 0; i < filecount; i++) {
137
int ret = jio_snprintf(archive_name, len, "%s.%0*u",
138
filename, number_of_digits, i);
139
assert(ret > 0 && static_cast<size_t>(ret) == len - 1,
140
"incorrect buffer length calculation");
141
142
if (file_exists(archive_name) && !is_regular_file(archive_name)) {
143
// We've encountered something that's not a regular file among the
144
// possible file rotation targets. Fail immediately to prevent
145
// problems later.
146
errstream->print_cr("Possible rotation target file '%s' already exists "
147
"but is not a regular file.", archive_name);
148
next_num = UINT_MAX;
149
break;
150
}
151
152
// Stop looking if we find an unused file name
153
if (!file_exists(archive_name)) {
154
next_num = i;
155
found = true;
156
break;
157
}
158
159
// Keep track of oldest existing log file
160
if (!found
161
|| os::compare_file_modified_times(oldest_name, archive_name) > 0) {
162
strcpy(oldest_name, archive_name);
163
next_num = i;
164
found = true;
165
}
166
}
167
168
FREE_C_HEAP_ARRAY(char, oldest_name);
169
FREE_C_HEAP_ARRAY(char, archive_name);
170
return next_num;
171
}
172
173
bool LogFileOutput::parse_options(const char* options, outputStream* errstream) {
174
if (options == NULL || strlen(options) == 0) {
175
return true;
176
}
177
bool success = true;
178
char* opts = os::strdup_check_oom(options, mtLogging);
179
180
char* comma_pos;
181
char* pos = opts;
182
do {
183
comma_pos = strchr(pos, ',');
184
if (comma_pos != NULL) {
185
*comma_pos = '\0';
186
}
187
188
char* equals_pos = strchr(pos, '=');
189
if (equals_pos == NULL) {
190
errstream->print_cr("Invalid option '%s' for log file output.", pos);
191
success = false;
192
break;
193
}
194
char* key = pos;
195
char* value_str = equals_pos + 1;
196
*equals_pos = '\0';
197
198
if (strcmp(FileCountOptionKey, key) == 0) {
199
size_t value = parse_value(value_str);
200
if (value > MaxRotationFileCount) {
201
errstream->print_cr("Invalid option: %s must be in range [0, %u]",
202
FileCountOptionKey,
203
MaxRotationFileCount);
204
success = false;
205
break;
206
}
207
_file_count = static_cast<uint>(value);
208
_is_default_file_count = false;
209
} else if (strcmp(FileSizeOptionKey, key) == 0) {
210
julong value;
211
success = Arguments::atojulong(value_str, &value);
212
if (!success || (value > SIZE_MAX)) {
213
errstream->print_cr("Invalid option: %s must be in range [0, "
214
SIZE_FORMAT "]", FileSizeOptionKey, (size_t)SIZE_MAX);
215
success = false;
216
break;
217
}
218
_rotate_size = static_cast<size_t>(value);
219
} else {
220
errstream->print_cr("Invalid option '%s' for log file output.", key);
221
success = false;
222
break;
223
}
224
pos = comma_pos + 1;
225
} while (comma_pos != NULL);
226
227
os::free(opts);
228
return success;
229
}
230
231
bool LogFileOutput::initialize(const char* options, outputStream* errstream) {
232
if (!parse_options(options, errstream)) {
233
return false;
234
}
235
236
bool file_exist = file_exists(_file_name);
237
if (file_exist && _is_default_file_count && is_fifo_file(_file_name)) {
238
_file_count = 0; // Prevent file rotation for fifo's such as named pipes.
239
}
240
241
if (_file_count > 0) {
242
// compute digits with filecount - 1 since numbers will start from 0
243
_file_count_max_digits = number_of_digits(_file_count - 1);
244
_archive_name_len = 2 + strlen(_file_name) + _file_count_max_digits;
245
_archive_name = NEW_C_HEAP_ARRAY(char, _archive_name_len, mtLogging);
246
_archive_name[0] = 0;
247
}
248
249
log_trace(logging)("Initializing logging to file '%s' (filecount: %u"
250
", filesize: " SIZE_FORMAT " KiB).",
251
_file_name, _file_count, _rotate_size / K);
252
253
if (_file_count > 0 && file_exist) {
254
if (!is_regular_file(_file_name)) {
255
errstream->print_cr("Unable to log to file %s with log file rotation: "
256
"%s is not a regular file",
257
_file_name, _file_name);
258
return false;
259
}
260
_current_file = next_file_number(_file_name,
261
_file_count_max_digits,
262
_file_count,
263
errstream);
264
if (_current_file == UINT_MAX) {
265
return false;
266
}
267
log_trace(logging)("Existing log file found, saving it as '%s.%0*u'",
268
_file_name, _file_count_max_digits, _current_file);
269
archive();
270
increment_file_count();
271
}
272
273
_stream = os::fopen(_file_name, FileOpenMode);
274
if (_stream == NULL) {
275
errstream->print_cr("Error opening log file '%s': %s",
276
_file_name, os::strerror(errno));
277
return false;
278
}
279
280
if (_file_count == 0 && is_regular_file(_file_name)) {
281
log_trace(logging)("Truncating log file");
282
os::ftruncate(os::get_fileno(_stream), 0);
283
}
284
285
return true;
286
}
287
288
class RotationLocker : public StackObj {
289
Semaphore& _sem;
290
291
public:
292
RotationLocker(Semaphore& sem) : _sem(sem) {
293
sem.wait();
294
}
295
296
~RotationLocker() {
297
_sem.signal();
298
}
299
};
300
301
int LogFileOutput::write_blocking(const LogDecorations& decorations, const char* msg) {
302
RotationLocker lock(_rotation_semaphore);
303
if (_stream == NULL) {
304
// An error has occurred with this output, avoid writing to it.
305
return 0;
306
}
307
308
int written = LogFileStreamOutput::write(decorations, msg);
309
if (written > 0) {
310
_current_size += written;
311
312
if (should_rotate()) {
313
rotate();
314
}
315
}
316
317
return written;
318
}
319
320
int LogFileOutput::write(const LogDecorations& decorations, const char* msg) {
321
if (_stream == NULL) {
322
// An error has occurred with this output, avoid writing to it.
323
return 0;
324
}
325
326
AsyncLogWriter* aio_writer = AsyncLogWriter::instance();
327
if (aio_writer != nullptr) {
328
aio_writer->enqueue(*this, decorations, msg);
329
return 0;
330
}
331
332
return write_blocking(decorations, msg);
333
}
334
335
int LogFileOutput::write(LogMessageBuffer::Iterator msg_iterator) {
336
if (_stream == NULL) {
337
// An error has occurred with this output, avoid writing to it.
338
return 0;
339
}
340
341
AsyncLogWriter* aio_writer = AsyncLogWriter::instance();
342
if (aio_writer != nullptr) {
343
aio_writer->enqueue(*this, msg_iterator);
344
return 0;
345
}
346
347
RotationLocker lock(_rotation_semaphore);
348
int written = LogFileStreamOutput::write(msg_iterator);
349
if (written > 0) {
350
_current_size += written;
351
352
if (should_rotate()) {
353
rotate();
354
}
355
}
356
357
return written;
358
}
359
360
void LogFileOutput::archive() {
361
assert(_archive_name != NULL && _archive_name_len > 0, "Rotation must be configured before using this function.");
362
int ret = jio_snprintf(_archive_name, _archive_name_len, "%s.%0*u",
363
_file_name, _file_count_max_digits, _current_file);
364
assert(ret >= 0, "Buffer should always be large enough");
365
366
// Attempt to remove possibly existing archived log file before we rename.
367
// Don't care if it fails, we really only care about the rename that follows.
368
remove(_archive_name);
369
370
// Rename the file from ex hotspot.log to hotspot.log.2
371
if (rename(_file_name, _archive_name) == -1) {
372
jio_fprintf(defaultStream::error_stream(), "Could not rename log file '%s' to '%s' (%s).\n",
373
_file_name, _archive_name, os::strerror(errno));
374
}
375
}
376
377
void LogFileOutput::force_rotate() {
378
if (_file_count == 0) {
379
// Rotation not possible
380
return;
381
}
382
383
RotationLocker lock(_rotation_semaphore);
384
rotate();
385
}
386
387
void LogFileOutput::rotate() {
388
if (fclose(_stream)) {
389
jio_fprintf(defaultStream::error_stream(), "Error closing file '%s' during log rotation (%s).\n",
390
_file_name, os::strerror(errno));
391
}
392
393
// Archive the current log file
394
archive();
395
396
// Open the active log file using the same stream as before
397
_stream = os::fopen(_file_name, FileOpenMode);
398
if (_stream == NULL) {
399
jio_fprintf(defaultStream::error_stream(), "Could not reopen file '%s' during log rotation (%s).\n",
400
_file_name, os::strerror(errno));
401
return;
402
}
403
404
// Reset accumulated size, increase current file counter, and check for file count wrap-around.
405
_current_size = 0;
406
increment_file_count();
407
}
408
409
char* LogFileOutput::make_file_name(const char* file_name,
410
const char* pid_string,
411
const char* timestamp_string) {
412
char* result = NULL;
413
414
// Lets start finding out if we have any %d and/or %t in the name.
415
// We will only replace the first occurrence of any placeholder
416
const char* pid = strstr(file_name, PidFilenamePlaceholder);
417
const char* timestamp = strstr(file_name, TimestampFilenamePlaceholder);
418
419
if (pid == NULL && timestamp == NULL) {
420
// We found no place-holders, return the simple filename
421
return os::strdup_check_oom(file_name, mtLogging);
422
}
423
424
// At least one of the place-holders were found in the file_name
425
const char* first = "";
426
size_t first_pos = SIZE_MAX;
427
size_t first_replace_len = 0;
428
429
const char* second = "";
430
size_t second_pos = SIZE_MAX;
431
size_t second_replace_len = 0;
432
433
// If we found a %p, then setup our variables accordingly
434
if (pid != NULL) {
435
if (timestamp == NULL || pid < timestamp) {
436
first = pid_string;
437
first_pos = pid - file_name;
438
first_replace_len = strlen(PidFilenamePlaceholder);
439
} else {
440
second = pid_string;
441
second_pos = pid - file_name;
442
second_replace_len = strlen(PidFilenamePlaceholder);
443
}
444
}
445
446
if (timestamp != NULL) {
447
if (pid == NULL || timestamp < pid) {
448
first = timestamp_string;
449
first_pos = timestamp - file_name;
450
first_replace_len = strlen(TimestampFilenamePlaceholder);
451
} else {
452
second = timestamp_string;
453
second_pos = timestamp - file_name;
454
second_replace_len = strlen(TimestampFilenamePlaceholder);
455
}
456
}
457
458
size_t first_len = strlen(first);
459
size_t second_len = strlen(second);
460
461
// Allocate the new buffer, size it to hold all we want to put in there +1.
462
size_t result_len = strlen(file_name) + first_len - first_replace_len + second_len - second_replace_len;
463
result = NEW_C_HEAP_ARRAY(char, result_len + 1, mtLogging);
464
465
// Assemble the strings
466
size_t file_name_pos = 0;
467
size_t i = 0;
468
while (i < result_len) {
469
if (file_name_pos == first_pos) {
470
// We are in the range of the first placeholder
471
strcpy(result + i, first);
472
// Bump output buffer position with length of replacing string
473
i += first_len;
474
// Bump source buffer position to skip placeholder
475
file_name_pos += first_replace_len;
476
} else if (file_name_pos == second_pos) {
477
// We are in the range of the second placeholder
478
strcpy(result + i, second);
479
i += second_len;
480
file_name_pos += second_replace_len;
481
} else {
482
// Else, copy char by char of the original file
483
result[i] = file_name[file_name_pos++];
484
i++;
485
}
486
}
487
// Add terminating char
488
result[result_len] = '\0';
489
return result;
490
}
491
492
void LogFileOutput::describe(outputStream *out) {
493
LogOutput::describe(out);
494
out->print(" ");
495
496
out->print("filecount=%u,filesize=" SIZE_FORMAT "%s,async=%s", _file_count,
497
byte_size_in_proper_unit(_rotate_size),
498
proper_unit_for_byte_size(_rotate_size),
499
LogConfiguration::is_async_mode() ? "true" : "false");
500
}
501
502