|
| 1 | +/** |
| 2 | + * ContainerProxy |
| 3 | + * |
| 4 | + * Copyright (C) 2016-2024 Open Analytics |
| 5 | + * |
| 6 | + * =========================================================================== |
| 7 | + * |
| 8 | + * This program is free software: you can redistribute it and/or modify |
| 9 | + * it under the terms of the Apache License as published by |
| 10 | + * The Apache Software Foundation, either version 2 of the License, or |
| 11 | + * (at your option) any later version. |
| 12 | + * |
| 13 | + * This program is distributed in the hope that it will be useful, |
| 14 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 16 | + * Apache License for more details. |
| 17 | + * |
| 18 | + * You should have received a copy of the Apache License |
| 19 | + * along with this program. If not, see <http://www.apache.org/licenses/> |
| 20 | + */ |
| 21 | +package eu.openanalytics.containerproxy.stat.impl; |
| 22 | + |
| 23 | +import com.fasterxml.jackson.databind.MappingIterator; |
| 24 | +import com.fasterxml.jackson.databind.SequenceWriter; |
| 25 | +import com.fasterxml.jackson.dataformat.csv.CsvGenerator; |
| 26 | +import com.fasterxml.jackson.dataformat.csv.CsvMapper; |
| 27 | +import com.fasterxml.jackson.dataformat.csv.CsvSchema; |
| 28 | +import eu.openanalytics.containerproxy.stat.StatCollectorFactory; |
| 29 | +import org.slf4j.Logger; |
| 30 | +import org.slf4j.LoggerFactory; |
| 31 | +import org.springframework.context.ApplicationEvent; |
| 32 | +import org.springframework.security.core.Authentication; |
| 33 | + |
| 34 | +import javax.annotation.PostConstruct; |
| 35 | +import java.io.FileWriter; |
| 36 | +import java.io.IOException; |
| 37 | +import java.nio.file.Files; |
| 38 | +import java.nio.file.Path; |
| 39 | +import java.util.HashMap; |
| 40 | +import java.util.List; |
| 41 | +import java.util.Map; |
| 42 | +import java.util.Objects; |
| 43 | +import java.util.UUID; |
| 44 | + |
| 45 | +public class CSVCollector extends AbstractDbCollector implements AutoCloseable { |
| 46 | + |
| 47 | + private final Path url; |
| 48 | + private final List<StatCollectorFactory.UsageStatsAttribute> usageStatsAttributes; |
| 49 | + private final Logger logger = LoggerFactory.getLogger(getClass()); |
| 50 | + private FileWriter fileWriter; |
| 51 | + private SequenceWriter writer; |
| 52 | + private CsvSchema schema; |
| 53 | + |
| 54 | + public CSVCollector(String url, List<StatCollectorFactory.UsageStatsAttribute> usageStatsAttributes) { |
| 55 | + this.url = Path.of(url); |
| 56 | + this.usageStatsAttributes = usageStatsAttributes; |
| 57 | + } |
| 58 | + |
| 59 | + @PostConstruct |
| 60 | + public void init() throws IOException { |
| 61 | + CsvMapper csvMapper = new CsvMapper(); |
| 62 | + csvMapper.enable(CsvGenerator.Feature.ALWAYS_QUOTE_STRINGS); |
| 63 | + csvMapper.enable(CsvGenerator.Feature.ALWAYS_QUOTE_EMPTY_STRINGS); |
| 64 | + CsvSchema.Builder schemaBuilder = CsvSchema.builder(); |
| 65 | + if (Files.exists(url) && Files.size(url) > 0) { |
| 66 | + CsvSchema csvSchema = csvMapper.typedSchemaFor(Map.class).withHeader(); |
| 67 | + try { |
| 68 | + try (MappingIterator<Map<String, String>> it = csvMapper.readerFor(Map.class) |
| 69 | + .with(csvSchema.withColumnSeparator(',')) |
| 70 | + .readValues(url.toFile())) { |
| 71 | + for (String existingColumn : it.next().keySet()) { |
| 72 | + schemaBuilder.addColumn(existingColumn); |
| 73 | + } |
| 74 | + } |
| 75 | + fileWriter = new FileWriter(url.toFile(), true); |
| 76 | + } catch (Exception e) { |
| 77 | + String newUrl = url.toString().replace(".csv", "-" + UUID.randomUUID() + ".csv"); |
| 78 | + logger.warn("Not re-using existing csv file for usage stats (not in expected format), writing to {}", newUrl, e); |
| 79 | + fileWriter = new FileWriter(newUrl); |
| 80 | + schemaBuilder.setUseHeader(true); |
| 81 | + } |
| 82 | + } else { |
| 83 | + fileWriter = new FileWriter(url.toFile()); |
| 84 | + schemaBuilder.setUseHeader(true); |
| 85 | + } |
| 86 | + if (!schemaBuilder.hasColumn("event_time")) { |
| 87 | + schemaBuilder.addColumn("event_time"); |
| 88 | + } |
| 89 | + if (!schemaBuilder.hasColumn("username")) { |
| 90 | + schemaBuilder.addColumn("username"); |
| 91 | + } |
| 92 | + if (!schemaBuilder.hasColumn("type")) { |
| 93 | + schemaBuilder.addColumn("type"); |
| 94 | + } |
| 95 | + if (!schemaBuilder.hasColumn("data")) { |
| 96 | + schemaBuilder.addColumn("data"); |
| 97 | + } |
| 98 | + |
| 99 | + if (usageStatsAttributes != null) { |
| 100 | + for (StatCollectorFactory.UsageStatsAttribute attribute : usageStatsAttributes) { |
| 101 | + if (!schemaBuilder.hasColumn(attribute.getName())) { |
| 102 | + schemaBuilder.addColumn(attribute.getName()); |
| 103 | + } |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + schema = schemaBuilder.build(); |
| 108 | + writer = csvMapper.writer(schema).writeValues(fileWriter); |
| 109 | + } |
| 110 | + |
| 111 | + @Override |
| 112 | + protected void writeToDb(ApplicationEvent event, long timestamp, String userId, String type, String data, Authentication authentication) throws IOException { |
| 113 | + Map<String, String> row = new HashMap<>(); |
| 114 | + for (String column : schema.getColumnNames()) { |
| 115 | + row.put(column, ""); |
| 116 | + } |
| 117 | + row.put("event_time", Long.toString(timestamp)); |
| 118 | + row.put("username", Objects.requireNonNullElse(userId, "")); |
| 119 | + row.put("type", Objects.requireNonNullElse(type, "")); |
| 120 | + row.put("data", Objects.requireNonNullElse(data, "")); |
| 121 | + row.putAll(resolveAttributes(authentication, event, usageStatsAttributes)); |
| 122 | + writer.write(row); |
| 123 | + } |
| 124 | + |
| 125 | + @Override |
| 126 | + public void close() throws Exception { |
| 127 | + writer.close(); |
| 128 | + fileWriter.close(); |
| 129 | + } |
| 130 | +} |
0 commit comments