80 lines
2.6 KiB
Java
80 lines
2.6 KiB
Java
package dev.dinauer.monitoring.volume;
|
|
|
|
import java.io.IOException;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.nio.file.Files;
|
|
import java.nio.file.Path;
|
|
import java.nio.file.StandardOpenOption;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
import java.util.stream.Stream;
|
|
|
|
import jakarta.annotation.PostConstruct;
|
|
import jakarta.enterprise.context.ApplicationScoped;
|
|
import jakarta.inject.Inject;
|
|
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
|
|
|
import dev.dinauer.WorkdirProvider;
|
|
|
|
@ApplicationScoped
|
|
public class VolumeUsageRepo
|
|
{
|
|
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().registerModule(new JavaTimeModule());
|
|
|
|
@Inject
|
|
WorkdirProvider workdirProvider;
|
|
|
|
private Path directory;
|
|
|
|
@PostConstruct
|
|
void init() throws IOException
|
|
{
|
|
Path directory = workdirProvider.getWorkdirPath(Path.of("monitorings", "volumes", "jobs"));
|
|
Files.createDirectories(directory);
|
|
this.directory = directory;
|
|
}
|
|
|
|
public void persist(VolumeUsage usage) throws IOException
|
|
{
|
|
Path file = getMonitoringPath(usage.monitoringId()).resolve(usage.podId());
|
|
Files.write(file, (OBJECT_MAPPER.writeValueAsString(usage) + "\n").getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
|
|
}
|
|
|
|
public List<VolumeUsage> findByMonitoringIdAndPodId(String monitoringId, String podId) throws IOException
|
|
{
|
|
Path file = getMonitoringPath(monitoringId).resolve(podId);
|
|
if (Files.exists(file))
|
|
{
|
|
List<VolumeUsage> result = new ArrayList<>();
|
|
for (String line : Files.readAllLines(file, StandardCharsets.UTF_8))
|
|
{
|
|
result.add(OBJECT_MAPPER.readValue(line, VolumeUsage.class));
|
|
}
|
|
return result;
|
|
}
|
|
return new ArrayList<>();
|
|
}
|
|
|
|
public List<VolumeUsage> findAll(String monitoringId) throws IOException
|
|
{
|
|
List<VolumeUsage> result = new ArrayList<>();
|
|
try (Stream<Path> files = Files.list(getMonitoringPath(monitoringId)))
|
|
{
|
|
for (Path file : files.toList())
|
|
{
|
|
result.add(OBJECT_MAPPER.readValue(Files.readString(file), VolumeUsage.class));
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
private Path getMonitoringPath(String monitoringId) throws IOException
|
|
{
|
|
Path monitoringDirectory = workdirProvider.getWorkdirPath(directory.resolve(monitoringId));
|
|
Files.createDirectories(monitoringDirectory);
|
|
return monitoringDirectory;
|
|
}
|
|
}
|