-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTsFileWriter.java
286 lines (254 loc) · 10.5 KB
/
TsFileWriter.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
package cn.edu.tsinghua.tsfile.write;
import cn.edu.tsinghua.tsfile.common.conf.TSFileConfig;
import cn.edu.tsinghua.tsfile.common.conf.TSFileDescriptor;
import cn.edu.tsinghua.tsfile.file.footer.ChunkGroupFooter;
import cn.edu.tsinghua.tsfile.write.schema.MeasurementSchema;
import cn.edu.tsinghua.tsfile.exception.write.NoMeasurementException;
import cn.edu.tsinghua.tsfile.exception.write.WriteProcessException;
import cn.edu.tsinghua.tsfile.write.writer.TsFileIOWriter;
import cn.edu.tsinghua.tsfile.write.record.TSRecord;
import cn.edu.tsinghua.tsfile.write.record.datapoint.DataPoint;
import cn.edu.tsinghua.tsfile.write.schema.FileSchema;
import cn.edu.tsinghua.tsfile.write.schema.JsonConverter;
import cn.edu.tsinghua.tsfile.write.chunk.IChunkGroupWriter;
import cn.edu.tsinghua.tsfile.write.chunk.ChunkGroupWriterImpl;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* TsFileWriter is the entrance for writing processing. It receives a record and send it to
* responding chunk group write. It checks memory size for all writing processing along its strategy
* and flush data stored in memory to OutputStream. At the end of writing, user should call
* {@code close()} method to flush the last data outside and close the normal outputStream and error
* outputStream.
*
* @author kangrong
*/
public class TsFileWriter {
private static final Logger LOG = LoggerFactory.getLogger(TsFileWriter.class);
/**
* IO writer of this TsFile
**/
private final TsFileIOWriter fileWriter;
/**
* schema of this TsFile
**/
protected final FileSchema schema;
private final int pageSize;
private long recordCount = 0;
/**
* all IChunkGroupWriters
**/
private Map<String, IChunkGroupWriter> groupWriters = new HashMap<String, IChunkGroupWriter>();
/**
* min value of threshold of data points num check
**/
private long recordCountForNextMemCheck = 100;
private long chunkGroupSizeThreshold;
/**
* init this TsFileWriter
*
* @param file the File to be written by this TsFileWriter
* @throws IOException
*/
public TsFileWriter(File file) throws IOException {
this(new TsFileIOWriter(file), new FileSchema(), TSFileDescriptor.getInstance().getConfig());
}
/**
* init this TsFileWriter
*
* @param file the File to be written by this TsFileWriter
* @param schema the schema of this TsFile
* @throws IOException
*/
public TsFileWriter(File file, FileSchema schema) throws IOException {
this(new TsFileIOWriter(file), schema, TSFileDescriptor.getInstance().getConfig());
}
/**
* init this TsFileWriter
*
* @param file the File to be written by this TsFileWriter
* @param conf the configuration of this TsFile
* @throws IOException
*/
public TsFileWriter(File file, TSFileConfig conf) throws IOException {
this(new TsFileIOWriter(file), new FileSchema(), conf);
}
/**
* init this TsFileWriter
*
* @param file the File to be written by this TsFileWriter
* @param schema the schema of this TsFile
* @param conf the configuration of this TsFile
* @throws IOException
*/
public TsFileWriter(File file, FileSchema schema, TSFileConfig conf)
throws IOException {
this(new TsFileIOWriter(file), schema, conf);
}
/**
* init this TsFileWriter
*
* @param fileWriter the io writer of this TsFile
* @param schema the schema of this TsFile
* @param conf the configuration of this TsFile
*/
protected TsFileWriter(TsFileIOWriter fileWriter, FileSchema schema, TSFileConfig conf) {
this.fileWriter = fileWriter;
this.schema = schema;
this.pageSize = conf.pageSizeInByte;
this.chunkGroupSizeThreshold = conf.groupSizeInByte;
}
/**
* add a measurementSchema to this TsFile
*/
public void addMeasurement(MeasurementSchema measurementSchema)
throws WriteProcessException {
if (schema.hasMeasurement(measurementSchema.getMeasurementId()))
throw new WriteProcessException(
"given measurement has exists! " + measurementSchema.getMeasurementId());
schema.registerMeasurement(measurementSchema);
}
/**
* add a new measurement according to json string.
*
* @param measurement example:
* {
* "measurement_id": "sensor_cpu_50",
* "data_type": "INT32",
* "encoding": "RLE"
* "compressor": "SNAPPY"
* }
* @throws WriteProcessException if the json is illegal or the measurement exists
*/
void addMeasurementByJson(JSONObject measurement) throws WriteProcessException {
addMeasurement(JsonConverter.convertJsonToMeasurementSchema(measurement));
}
/**
* Confirm whether the record is legal. If legal, add it into this RecordWriter.
*
* @param record - a record responding a line
* @return - whether the record has been added into RecordWriter legally
* @throws WriteProcessException exception
*/
private boolean checkIsTimeSeriesExist(TSRecord record) throws WriteProcessException {
IChunkGroupWriter groupWriter;
if (!groupWriters.containsKey(record.deviceId)) {
groupWriter = new ChunkGroupWriterImpl(record.deviceId);
groupWriters.put(record.deviceId, groupWriter);
} else {
groupWriter = groupWriters.get(record.deviceId);
}
// add all SeriesWriter of measurements in this TSRecord to this ChunkGroupWriter
Map<String, MeasurementSchema> schemaDescriptorMap = schema.getAllMeasurementSchema();
for (DataPoint dp : record.dataPointList) {
String measurementId = dp.getMeasurementId();
if (schemaDescriptorMap.containsKey(measurementId))
groupWriter.addSeriesWriter(schemaDescriptorMap.get(measurementId), pageSize);
else
throw new NoMeasurementException("input measurement is invalid: " + measurementId);
}
return true;
}
/**
* write a record in type of T.
*
* @param record - record responding a data line
* @return true -size of tsfile or metadata reaches the threshold.
* false - otherwise
* @throws IOException exception in IO
* @throws WriteProcessException exception in write process
*/
public boolean write(TSRecord record) throws IOException, WriteProcessException {
// make sure the ChunkGroupWriter for this TSRecord exist
if (checkIsTimeSeriesExist(record)) {
// get corresponding ChunkGroupWriter and write this TSRecord
groupWriters.get(record.deviceId).write(record.time, record.dataPointList);
++recordCount;
return checkMemorySizeAndMayFlushGroup();
}
return false;
}
/**
* calculate total memory size occupied by all ChunkGroupWriter instances currently.
*
* @return total memory size used
*/
private long calculateMemSizeForAllGroup() {
int memTotalSize = 0;
for (IChunkGroupWriter group : groupWriters.values()) {
memTotalSize += group.updateMaxGroupMemSize();
}
return memTotalSize;
}
/**
* check occupied memory size, if it exceeds the chunkGroupSize threshold, flush them to given
* OutputStream.
*
* @return true - size of tsfile or metadata reaches the threshold.
* false - otherwise
* @throws IOException exception in IO
*/
private boolean checkMemorySizeAndMayFlushGroup() throws IOException {
if (recordCount >= recordCountForNextMemCheck) {
long memSize = calculateMemSizeForAllGroup();
if (memSize > chunkGroupSizeThreshold) {
LOG.info("start_flush_row_group, memory space occupy:" + memSize);
recordCountForNextMemCheck = recordCount * chunkGroupSizeThreshold / memSize;
LOG.debug("current threshold:{}, next check:{}", recordCount, recordCountForNextMemCheck);
return flushAllChunkGroups();
} else {
recordCountForNextMemCheck = recordCount * chunkGroupSizeThreshold / memSize;
LOG.debug("current threshold:{}, next check:{}", recordCount, recordCountForNextMemCheck);
return false;
}
}
return false;
}
/**
* flush the data in all series writers of all rowgroup writers and their page writers to outputStream.
*
* @return true - size of tsfile or metadata reaches the threshold.
* false - otherwise. But this function just return false, the Override of IoTDB may return true.
* @throws IOException exception in IO
*/
private boolean flushAllChunkGroups() throws IOException {
if (recordCount > 0) {
long totalMemStart = fileWriter.getPos();
for (String deviceId : groupWriters.keySet()) {
long pos = fileWriter.getPos();
IChunkGroupWriter groupWriter = groupWriters.get(deviceId);
fileWriter.startFlushChunkGroup(deviceId);
ChunkGroupFooter chunkGroupFooter = groupWriter.flushToFileWriter(fileWriter);
if (fileWriter.getPos() - pos != chunkGroupFooter.getDataSize())
throw new IOException(String.format("Flushed data size is inconsistent with computation! Estimated: %d, Actuall: %d",
chunkGroupFooter.getDataSize(), fileWriter.getPos() - pos));
fileWriter.endChunkGroup(chunkGroupFooter);
}
long actualTotalChunkGroupSize = fileWriter.getPos() - totalMemStart;
LOG.info("total chunk group size:{}", actualTotalChunkGroupSize);
LOG.info("write chunk group end");
recordCount = 0;
reset();
}
return false;
}
private void reset() {
groupWriters.clear();
}
/**
* calling this method to write the last data remaining in memory and close the normal and error
* OutputStream.
*
* @throws IOException exception in IO
*/
public void close() throws IOException {
LOG.info("start close file");
flushAllChunkGroups();
fileWriter.endFile(this.schema);
}
}