- String dateSuffix = Instant.now().atOffset(ZoneOffset.UTC).format(DateTimeFormatter.ISO_LOCAL_DATE);
-
- Path csvPath = basePath.resolve("statistics-" + unitName + "-" + dateSuffix + ".csv");
- boolean writeHeader = !Files.exists(csvPath);
- try (Writer writer = Files.newBufferedWriter(csvPath, StandardCharsets.UTF_8,
- StandardOpenOption.APPEND)) {
- CsvWriter csvWriter = new CsvWriter(writer);
-
- if (writeHeader)// header
- csvWriter.writeLine("CurrentTimeMillis", "CPUUsageNSec", "MemoryCurrent", "IPIngressBytes",
- "IPEgressBytes", "IOReadBytes", "IOWriteBytes", "TasksCurrent");
-
- // TODO better synchronise with stop
- csvWriter.writeLine(System.currentTimeMillis(), service.getCPUUsageNSec(),
- service.getMemoryCurrent(), service.getIPIngressBytes(), service.getIPEgressBytes(),
- service.getIOReadBytes(), service.getIOWriteBytes(), service.getTasksCurrent());
+ synchronized (this) {
+
+ String dateSuffix = Instant.ofEpochMilli(begin).atOffset(ZoneOffset.UTC)
+ .format(DateTimeFormatter.ISO_LOCAL_DATE) + "-" + begin;
+
+ Path statisticsPath = basePath.resolve("statistics-" + unitName + "-" + dateSuffix + ".csv");
+ boolean writeHeader = !Files.exists(statisticsPath);
+ if (!writeHeader && previousStat == null)
+ logger.log(ERROR,
+ "File " + statisticsPath + " exists, but we don't have previous statistics in memory");
+
+ try (Writer writer = Files.newBufferedWriter(statisticsPath, StandardCharsets.UTF_8,
+ StandardOpenOption.APPEND, StandardOpenOption.CREATE)) {
+ CsvWriter csvWriter = new CsvWriter(writer);
+
+ if (writeHeader)// header
+ csvWriter.writeLine("CurrentTimeMillis", "CPUUsageNSec", "MemoryCurrent", "IPIngressBytes",
+ "IPEgressBytes", "IOReadBytes", "IOWriteBytes", "TasksCurrent");
+
+ Statistics s = new Statistics(Instant.now().toEpochMilli(), service.getCPUUsageNSec(),
+ service.getMemoryCurrent(), service.getIPIngressBytes(), service.getIPEgressBytes(),
+ service.getIOReadBytes(), service.getIOWriteBytes(), service.getTasksCurrent());
+
+ if (s.MemoryCurrent().compareTo(maxMemory) > 0)
+ maxMemory = s.MemoryCurrent();
+ if (s.TasksCurrent().compareTo(maxTasks) > 0)
+ maxTasks = s.TasksCurrent();
+
+ Statistics diff = Statistics.diff(s, previousStat);
+ // TODO better synchronise with stop
+ csvWriter.writeLine(diff.CurrentTimeMillis(), diff.CPUUsageNSec(), diff.MemoryCurrent(),
+ diff.IPIngressBytes(), diff.IPEgressBytes(), diff.IOReadBytes(), diff.IOWriteBytes(),
+ diff.TasksCurrent());
+ previousStat = s;
+ }
+ try {
+ this.wait(frequency);
+ } catch (InterruptedException e) {
+ logger.log(Level.TRACE, () -> "Statistics collection interrupted for " + unitName);
+ }