Additional checks then creating a v2 journal file (#20018)
Simplify memory_file_open
Stelios Fragkakis committed
Apr 1, 2025 at 12:58 UTC
543aa597829f6e82dd6a805746722ec819a1efe4
1 file changed
+16
-15
src/libnetdata/memory/nd-mmap.c
+16
-15
@@ -20,23 +20,24 @@ int enable_ksm = 0;
20
#endif
21
22
static int memory_file_open(const char *filename, size_t size) {
23
- // netdata_log_info("memory_file_open('%s', %zu", filename, size);
24
-
23
int fd = open(filename, O_RDWR | O_CREAT | O_NOATIME | O_CLOEXEC, 0664);
26
- if (fd != -1) {
27
- if (lseek(fd, size, SEEK_SET) == (off_t) size) {
28
- if (write(fd, "", 1) == 1) {
29
- if (ftruncate(fd, size))
30
- netdata_log_error("Cannot truncate file '%s' to size %zu. Will use the larger file.", filename, size);
31
- }
32
- else
33
- netdata_log_error("Cannot write to file '%s' at position %zu.", filename, size);
34
- }
35
- else
36
- netdata_log_error("Cannot seek file '%s' to size %zu.", filename, size);
37
- }
38
- else
24
+ if (fd == -1) {
25
netdata_log_error("Cannot create/open file '%s'.", filename);
26
+ return -1;
27
+ }
28
+
29
+ if (ftruncate(fd, size) != 0) {
30
+ netdata_log_error("Cannot truncate file '%s' to size %zu.", filename, size);
31
+ close(fd);
32
+ return -1;
33
+ }
34
+
35
+ struct stat st;
36
+ if (fstat(fd, &st) != 0 || (size_t)st.st_size < size) {
37
+ netdata_log_error("File '%s' is only %lld bytes, expected %zu!", filename, (long long)st.st_size, size);
38
+ close(fd);
39
+ return -1;
40
+ }
41
42
return fd;
43
}