-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathParquetUtil.java
381 lines (349 loc) · 14.3 KB
/
ParquetUtil.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/*
* Copyright 2020-2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.fhir.analytics;
import ca.uhn.fhir.context.FhirVersionEnum;
import com.cerner.bunsen.exception.ProfileException;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.fhir.analytics.view.ViewApplicationException;
import com.google.fhir.analytics.view.ViewApplicator;
import com.google.fhir.analytics.view.ViewApplicator.RowList;
import com.google.fhir.analytics.view.ViewDefinition;
import com.google.fhir.analytics.view.ViewDefinitionException;
import com.google.fhir.analytics.view.ViewManager;
import com.google.fhir.analytics.view.ViewSchema;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import javax.annotation.Nullable;
import org.apache.avro.generic.GenericRecord;
import org.apache.beam.sdk.io.fs.ResolveOptions.StandardResolveOptions;
import org.apache.beam.sdk.io.fs.ResourceId;
import org.apache.beam.sdk.util.MimeTypes;
import org.apache.parquet.avro.AvroParquetWriter;
import org.apache.parquet.hadoop.ParquetWriter;
import org.hl7.fhir.r4.model.Bundle;
import org.hl7.fhir.r4.model.Bundle.BundleEntryComponent;
import org.hl7.fhir.r4.model.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// Implementing AutoCloseable does not help much in the usage pattern we have with DoFns. This is
// because we cannot wrap single resource writes into a "try-with-resources" block, otherwise each
// Parquet row-group will include only one record.
public class ParquetUtil {
private static final Logger log = LoggerFactory.getLogger(ParquetUtil.class);
public static String PARQUET_EXTENSION = ".parquet";
private final AvroConversionUtil conversionUtil;
private final Map<String, WriterWithCache> viewWriterMap;
private final Map<String, WriterWithCache> writerMap;
private final int rowGroupSize;
private final boolean cacheBundle;
private final DwhFiles dwhFiles;
private final Timer timer;
private final Random random;
private final String namePrefix;
private boolean flushedInCurrentPeriod;
private ViewManager viewManager;
private final boolean createParquetViews;
private synchronized void setFlushedInCurrentPeriod(boolean value) {
flushedInCurrentPeriod = value;
}
public String getParquetPath() {
return dwhFiles.getRoot();
}
// TODO remove this constructor and only expose a similar one in `DwhFiles` (for testing).
/**
* @param fhirVersionEnum This should match the resources intended to be converted.
* @param structureDefinitionsPath Directory path containing the structure definitions for custom
* fhir profiles; if it starts with `classpath:` then classpath will be searched instead.
* @param parquetFilePath The directory under which the Parquet files are written.
* @param secondsToFlush The interval after which the content of Parquet writers is flushed to
* disk.
* @param rowGroupSize The approximate size of row-groups in the Parquet files (0 means use
* default).
* @param namePrefix The prefix directory at which the Parquet files are written
* @param recursiveDepth The maximum recursive depth for FHIR resources when converting to Avro.
* @param cacheBundle Whether to cache output records or directly send them to the Parquet writer.
* If this is enabled, then it is the responsibility of the user code to call emptyCache. This
* is used when we want to make sure a DoFn is idempotent.
* @throws ProfileException if any errors are encountered during initialisation of FhirContext
*/
@VisibleForTesting
ParquetUtil(
FhirVersionEnum fhirVersionEnum,
String structureDefinitionsPath,
String parquetFilePath,
String viewDefinitionsDir,
boolean createParquetViews,
int secondsToFlush,
int rowGroupSize,
String namePrefix,
int recursiveDepth,
boolean cacheBundle)
throws ProfileException {
if (fhirVersionEnum == FhirVersionEnum.DSTU3 || fhirVersionEnum == FhirVersionEnum.R4) {
this.conversionUtil =
AvroConversionUtil.getInstance(fhirVersionEnum, structureDefinitionsPath, recursiveDepth);
} else {
throw new IllegalArgumentException("Only versions 3 and 4 of FHIR are supported!");
}
this.dwhFiles = new DwhFiles(parquetFilePath, conversionUtil.getFhirContext());
this.writerMap = new HashMap<>();
this.rowGroupSize = rowGroupSize;
this.cacheBundle = cacheBundle;
this.namePrefix = namePrefix;
this.createParquetViews = createParquetViews;
this.viewWriterMap = new HashMap<>();
this.viewManager = null;
setFlushedInCurrentPeriod(false);
if (createParquetViews) {
try {
this.viewManager = ViewManager.createForDir(viewDefinitionsDir);
} catch (IOException | ViewDefinitionException e) {
String errorMsg = String.format("Error while reading views from %s", viewDefinitionsDir);
log.error(errorMsg, e);
throw new IllegalArgumentException(errorMsg);
}
}
if (secondsToFlush > 0) {
TimerTask task =
new TimerTask() {
@Override
public void run() {
try {
// If a flush has happened recently, e.g., through a `FinishBundle` call, we don't
// need to do that again; the timer here is just to make sure the data is flushed
// into Parquet files _at least_ once in every `secondsToFlush`.
if (!flushedInCurrentPeriod) {
log.info("Flush timed out for thread " + Thread.currentThread().getId());
flushAll();
}
setFlushedInCurrentPeriod(false);
} catch (IOException | ProfileException e) {
log.error("Could not flush Parquet files: " + e);
}
}
};
this.timer = new Timer();
timer.scheduleAtFixedRate(task, secondsToFlush * 1000, secondsToFlush * 1000);
} else {
timer = null;
}
this.random = new Random(System.currentTimeMillis());
}
@VisibleForTesting
synchronized ResourceId getUniqueOutputFilePath(String resourceType) throws IOException {
ResourceId resourceId = dwhFiles.getResourcePath(resourceType);
String uniqueFileName =
String.format(
"%s%s_output-parquet-th-%d-ts-%d-r-%d%s",
namePrefix,
resourceType,
Thread.currentThread().getId(),
System.currentTimeMillis(),
random.nextInt(1000000),
PARQUET_EXTENSION);
return resourceId.resolve(uniqueFileName, StandardResolveOptions.RESOLVE_FILE);
}
@VisibleForTesting
synchronized ResourceId getUniqueOutputFilePathView(String viewName) throws IOException {
ResourceId resourceId = dwhFiles.getResourcePath(viewName.toLowerCase(Locale.ENGLISH));
String uniqueFileName =
String.format(
"%s%s_output-parquet-th-%d-ts-%d-r-%d%s",
namePrefix,
viewName,
Thread.currentThread().getId(),
System.currentTimeMillis(),
random.nextInt(1000000),
PARQUET_EXTENSION);
return resourceId.resolve(uniqueFileName, StandardResolveOptions.RESOLVE_FILE);
}
private synchronized void createWriter(String resourceType, @Nullable ViewDefinition vDef)
throws IOException, ProfileException {
boolean noView = vDef == null;
ResourceId resourceId =
noView
? getUniqueOutputFilePath(resourceType)
: getUniqueOutputFilePathView(vDef.getName());
WritableByteChannel writableByteChannel =
org.apache.beam.sdk.io.FileSystems.create(resourceId, MimeTypes.BINARY);
OutputStream outputStream = Channels.newOutputStream(writableByteChannel);
FhirOutputFile fhirOutputFile = new FhirOutputFile(outputStream);
AvroParquetWriter.Builder<GenericRecord> builder = AvroParquetWriter.builder(fhirOutputFile);
// TODO: Adjust other parquet file parameters for our needs or make them configurable.
if (rowGroupSize > 0) {
builder.withRowGroupSize(rowGroupSize);
}
ParquetWriter<GenericRecord> writer;
if (noView) {
writer = builder.withSchema(conversionUtil.getResourceSchema(resourceType)).build();
writerMap.put(resourceType, new WriterWithCache(writer, this.cacheBundle));
} else {
writer = builder.withSchema(ViewSchema.getAvroSchema(vDef)).build();
viewWriterMap.put(vDef.getName(), new WriterWithCache(writer, this.cacheBundle));
}
}
/**
* This is to write a FHIR resource to a Parquet file. Automatically handles file creation in a
* directory named after the resource type (e.g., `Patient`) with names following the
* "output-parquet-th-T-ts-TS-r-R.parquet" pattern where T is the thread identifier, TS is a
* timestamp and R is a random number
*/
public synchronized void write(Resource resource)
throws IOException, ProfileException, ViewApplicationException {
Preconditions.checkNotNull(resource.fhirType());
String resourceType = resource.fhirType();
if (!writerMap.containsKey(resourceType)) {
createWriter(resourceType, null);
}
final WriterWithCache writer = writerMap.get(resourceType);
GenericRecord record = conversionUtil.convertToAvro(resource);
if (record != null) {
writer.write(record);
}
if (createParquetViews) {
ImmutableList<ViewDefinition> views = viewManager.getViewsForType(resource.fhirType());
if (views != null) {
for (ViewDefinition vDef : views) {
write(resource, vDef);
}
}
}
}
public synchronized void emptyCache() throws IOException {
for (WriterWithCache writer : writerMap.values()) {
writer.flushCache();
}
for (WriterWithCache writer : viewWriterMap.values()) {
writer.flushCache();
}
}
/**
* This is to write a materialized View Definition to a Parquet file.
*
* @see #write(Resource)
*/
private synchronized void write(Resource resource, ViewDefinition vDef)
throws IOException, ProfileException, ViewApplicationException {
Preconditions.checkNotNull(resource.fhirType());
if (!viewWriterMap.containsKey(vDef.getName())) {
createWriter("", vDef);
}
final WriterWithCache parquetWriter = viewWriterMap.get(vDef.getName());
ViewApplicator applicator = new ViewApplicator(vDef);
RowList rows = applicator.apply(resource);
List<GenericRecord> result = ViewSchema.setValueInRecord(rows, vDef);
for (GenericRecord record : result) {
parquetWriter.write(record);
}
}
private synchronized void flush(String resourceType) throws IOException, ProfileException {
WriterWithCache writer = writerMap.get(resourceType);
if (writer != null && writer.getDataSize() > 0) {
writer.close();
createWriter(resourceType, null);
}
}
private synchronized void flushViewWriter(String viewName) throws IOException, ProfileException {
WriterWithCache writer = viewWriterMap.get(viewName);
if (writer != null && writer.getDataSize() > 0) {
writer.close();
// TODO: We need to investigate why we need to create the writer here. If we change this logic
// to remove the writer at this line, E2E Streaming Tests fail in CloudBuild.
createWriter(viewName, this.viewManager.getViewDefinition(viewName));
}
}
synchronized void flushAll() throws IOException, ProfileException {
log.info("Flushing all Parquet writers for thread " + Thread.currentThread().getId());
for (String viewName : viewWriterMap.keySet()) {
flushViewWriter(viewName);
}
for (String resourceType : writerMap.keySet()) {
flush(resourceType);
}
setFlushedInCurrentPeriod(true);
}
public synchronized void closeAllWriters() throws IOException {
if (timer != null) {
timer.cancel();
}
for (Map.Entry<String, WriterWithCache> entry : viewWriterMap.entrySet()) {
entry.getValue().close();
viewWriterMap.put(entry.getKey(), null);
}
for (Map.Entry<String, WriterWithCache> entry : writerMap.entrySet()) {
entry.getValue().close();
writerMap.put(entry.getKey(), null);
}
}
public void writeRecords(Bundle bundle, Set<String> resourceTypes)
throws IOException, ProfileException, ViewApplicationException {
if (bundle.getEntry() == null) {
return;
}
for (BundleEntryComponent entry : bundle.getEntry()) {
Resource resource = entry.getResource();
if (resourceTypes == null || resourceTypes.contains(resource.getResourceType().name())) {
write(resource);
}
}
}
private static class WriterWithCache {
private final ParquetWriter<GenericRecord> writer;
private final List<GenericRecord> cache;
private final boolean useCache;
WriterWithCache(ParquetWriter<GenericRecord> writer, boolean useCache) {
this.writer = writer;
this.cache = new ArrayList<>();
this.useCache = useCache;
}
void flushCache() throws IOException {
if (useCache && !cache.isEmpty()) {
log.info("Parquet cache size= {}", cache.size());
for (GenericRecord record : cache) {
writer.write(record);
}
cache.clear();
}
}
void write(GenericRecord record) throws IOException {
if (useCache) {
cache.add(record);
} else {
writer.write(record);
}
}
void close() throws IOException {
flushCache();
writer.close();
}
long getDataSize() {
return writer.getDataSize();
}
}
}