-
Notifications
You must be signed in to change notification settings - Fork 5
/
InfluxDbSink.java
286 lines (266 loc) · 11.1 KB
/
InfluxDbSink.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/*
* © 2021. TU Dortmund University,
* Institute of Energy Systems, Energy Efficiency and Energy Economics,
* Research group Distribution grid planning and operation
*/
package edu.ie3.datamodel.io.sink;
import edu.ie3.datamodel.exceptions.ProcessorProviderException;
import edu.ie3.datamodel.exceptions.SinkException;
import edu.ie3.datamodel.io.connectors.InfluxDbConnector;
import edu.ie3.datamodel.io.naming.EntityPersistenceNamingStrategy;
import edu.ie3.datamodel.io.processor.ProcessorProvider;
import edu.ie3.datamodel.models.UniqueEntity;
import edu.ie3.datamodel.models.result.ResultEntity;
import edu.ie3.datamodel.models.timeseries.TimeSeries;
import edu.ie3.datamodel.models.timeseries.TimeSeriesEntry;
import edu.ie3.datamodel.models.value.Value;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** InfluxDB Sink for result and time series data */
public class InfluxDbSink implements OutputDataSink {
public static final Logger log = LoggerFactory.getLogger(InfluxDbSink.class);
/** Field name for time */
private static final String FIELD_NAME_TIME = "time";
/** Field name for input model uuid field in result entities */
private static final String FIELD_NAME_INPUT = "inputModel";
private final InfluxDbConnector connector;
private final EntityPersistenceNamingStrategy entityPersistenceNamingStrategy;
private final ProcessorProvider processorProvider;
/**
* Initializes a new InfluxDbWeatherSource
*
* @param connector needed for database connection
* @param entityPersistenceNamingStrategy needed to create measurement names for entities
*/
public InfluxDbSink(
InfluxDbConnector connector,
EntityPersistenceNamingStrategy entityPersistenceNamingStrategy) {
this.connector = connector;
this.entityPersistenceNamingStrategy = entityPersistenceNamingStrategy;
this.processorProvider =
new ProcessorProvider(
ProcessorProvider.allResultEntityProcessors(),
ProcessorProvider.allTimeSeriesProcessors());
}
/**
* Initializes a new InfluxDbWeatherSource with a default EntityPersistenceNamingStrategy
*
* @param connector needed for database connection
*/
public InfluxDbSink(InfluxDbConnector connector) {
this(connector, new EntityPersistenceNamingStrategy());
}
@Override
public void shutdown() {
connector.shutdown();
}
@Override
public <C extends UniqueEntity> void persist(C entity) throws ProcessorProviderException {
Set<Point> points = extractPoints(entity);
// writes only the exact one point instead of unnecessarily wrapping it in BatchPoints
if (points.size() == 1) write(points.iterator().next());
else writeAll(points);
}
@Override
public <C extends UniqueEntity> void persistAll(Collection<C> entities)
throws ProcessorProviderException {
Set<Point> points = new HashSet<>();
for (C entity : entities) {
points.addAll(extractPoints(entity));
}
writeAll(points);
}
@Override
public <E extends TimeSeriesEntry<V>, V extends Value> void persistTimeSeries(
TimeSeries<E, V> timeSeries) throws ProcessorProviderException {
Set<Point> points = transformToPoints(timeSeries);
writeAll(points);
}
/**
* If batch writing is enabled, this call writes everything inside the batch to the database. This
* will block until all pending points are written.
*/
public void flush() {
if (connector.getSession().isBatchEnabled()) connector.getSession().flush();
}
/**
* Transforms a ResultEntity to an influxDB data point. <br>
* As the equivalent to a relational table, the influxDB measurement point will be named using the
* given EntityPersistenceNamingStrategy if possible, or the class name otherwise. All special
* characters in the measurement name will be replaced by underscores.
*
* @param entity the entity to transform
*/
private Optional<Point> transformToPoint(ResultEntity entity) {
Optional<String> measurementName =
entityPersistenceNamingStrategy.getResultEntityName(entity.getClass());
if (measurementName.isEmpty())
log.warn(
"I could not get a measurement name for class {}. I am using its simple name instead.",
entity.getClass().getSimpleName());
return transformToPoint(entity, measurementName.orElse(entity.getClass().getSimpleName()));
}
/**
* Transforms a ResultEntity to an influxDB data point. <br>
* All special characters in the measurement name will be replaced by underscores.
*
* @param entity the entity to transform
* @param measurementName equivalent to the name of a relational table
*/
private Optional<Point> transformToPoint(ResultEntity entity, String measurementName) {
LinkedHashMap<String, String> entityFieldData;
try {
entityFieldData = processorProvider.handleEntity(entity);
entityFieldData.remove(FIELD_NAME_TIME);
return Optional.of(
Point.measurement(transformToMeasurementName(measurementName))
.time(entity.getTime().toInstant().toEpochMilli(), TimeUnit.MILLISECONDS)
.tag("input_model", entityFieldData.remove(FIELD_NAME_INPUT))
.tag("scenario", connector.getScenarioName())
.fields(Collections.unmodifiableMap(entityFieldData))
.build());
} catch (ProcessorProviderException e) {
log.error(
"Cannot persist provided entity '{}'. Exception: {}",
entity.getClass().getSimpleName(),
new SinkException(
"Cannot persist entity of type '"
+ entity.getClass().getSimpleName()
+ "'. This sink can only process the following entities: ["
+ processorProvider.getRegisteredClasses().stream()
.map(Class::getSimpleName)
.collect(Collectors.joining(","))
+ "]"));
}
return Optional.empty();
}
/**
* Transforms a timeSeries to influxDB data points, one point for each value. <br>
* As the equivalent to a relational table, the influxDB measurement point will be named using the
* given EntityPersistenceNamingStrategy if possible, or the class name otherwise. All special
* characters in the measurement name will be replaced by underscores.
*
* @param timeSeries the time series to transform
*/
private <E extends TimeSeriesEntry<V>, V extends Value> Set<Point> transformToPoints(
TimeSeries<E, V> timeSeries) throws ProcessorProviderException {
if (timeSeries.getEntries().isEmpty()) return Collections.emptySet();
try {
Optional<String> measurementName = entityPersistenceNamingStrategy.getEntityName(timeSeries);
if (measurementName.isEmpty()) {
String valueClassName =
timeSeries.getEntries().iterator().next().getValue().getClass().getSimpleName();
log.warn(
"I could not get a measurement name for TimeSeries value class {}. I am using it's value's simple name instead.",
valueClassName);
return transformToPoints(timeSeries, valueClassName);
}
return transformToPoints(timeSeries, measurementName.get());
} catch (ProcessorProviderException e) {
log.error(
"Cannot persist provided time series '{}'. Exception: {}",
timeSeries.getClass().getSimpleName(),
e);
throw e;
}
}
/**
* Transforms a timeSeries to influxDB data points, one point for each value. <br>
* All special characters in the measurement name will be replaced by underscores.
*
* @param timeSeries the time series to transform
* @param measurementName equivalent to the name of a relational table
*/
private <E extends TimeSeriesEntry<V>, V extends Value> Set<Point> transformToPoints(
TimeSeries<E, V> timeSeries, String measurementName) throws ProcessorProviderException {
Set<Point> points = new HashSet<>();
try {
Set<LinkedHashMap<String, String>> entityFieldData =
processorProvider.handleTimeSeries(timeSeries);
for (LinkedHashMap<String, String> dataMapping : entityFieldData) {
String timeString = dataMapping.remove(FIELD_NAME_TIME);
long timeMillis = ZonedDateTime.parse(timeString).toInstant().toEpochMilli();
Point point =
Point.measurement(transformToMeasurementName(measurementName))
.time(timeMillis, TimeUnit.MILLISECONDS)
.tag("scenario", connector.getScenarioName())
.fields(Collections.unmodifiableMap(dataMapping))
.build();
points.add(point);
}
} catch (ProcessorProviderException e) {
log.error(
"Cannot persist provided entity '{}'. Exception: {}",
timeSeries.getClass().getSimpleName(),
e);
throw e;
}
return points;
}
/**
* Transforms an entity to an influxDB data point. <br>
* The measurement point will be named by the given EntityPersistenceNamingStrategy if possible,
* or the class name otherwise. All special characters in the measurement name will be replaced by
* underscores.
*
* @param entity the entity of which influxDB points will be extracted
* @param <C> bounded to be all unique entities, but logs an error and returns an empty Set if it
* does not extend {@link ResultEntity} or {@link TimeSeries}
*/
private <C extends UniqueEntity> Set<Point> extractPoints(C entity)
throws ProcessorProviderException {
Set<Point> points = new HashSet<>();
/* Distinguish between result models and time series */
if (entity instanceof ResultEntity resultEntity) {
try {
points.add(
transformToPoint(resultEntity)
.orElseThrow(() -> new SinkException("Could not transform entity")));
} catch (SinkException e) {
log.error(
"Cannot persist provided entity '{}'. Exception: {}",
entity.getClass().getSimpleName(),
e);
}
} else if (entity instanceof TimeSeries<?, ?> timeSeries) {
points.addAll(transformToPoints(timeSeries));
} else {
log.error(
"I don't know how to handle an entity of class {}", entity.getClass().getSimpleName());
}
return points;
}
/**
* Writes the point to the database
*
* @param point point to write
*/
private void write(Point point) {
if (point == null) return;
connector.getSession().write(point);
}
/**
* Writes all points as a batch to the database
*
* @param points points to write
*/
private void writeAll(Collection<Point> points) {
if (points.isEmpty()) return;
BatchPoints batchPoints = BatchPoints.builder().points(points).build();
connector.getSession().write(batchPoints);
}
/**
* Remove leading and trailing whitespace and replace all special characters with underscores
*
* @param filename the file name to transform
*/
private static String transformToMeasurementName(String filename) {
return filename.trim().replaceAll("\\W", "_");
}
}