-
Notifications
You must be signed in to change notification settings - Fork 866
/
ODatabaseExport.java
executable file
·584 lines (471 loc) · 22 KB
/
ODatabaseExport.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
/*
*
* * Copyright 2010-2016 OrientDB LTD (http://orientdb.com)
* *
* * 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.
* *
* * For more information: http://orientdb.com
*
*/
package com.orientechnologies.orient.core.db.tool;
import com.orientechnologies.common.io.OIOException;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.serialization.types.OBinarySerializer;
import com.orientechnologies.orient.core.OConstants;
import com.orientechnologies.orient.core.command.OCommandOutputListener;
import com.orientechnologies.orient.core.config.OStorageConfiguration;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.index.*;
import com.orientechnologies.orient.core.iterator.ORecordIteratorCluster;
import com.orientechnologies.orient.core.metadata.OMetadataInternal;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.schema.OSchemaShared;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.OJSONWriter;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import java.io.*;
import java.util.*;
import java.util.zip.Deflater;
import java.util.zip.GZIPOutputStream;
/**
* Export data from a database to a file.
*
* @author Luca Garulli (l.garulli--(at)--orientdb.com)
*/
public class ODatabaseExport extends ODatabaseImpExpAbstract {
public static final int VERSION = 11;
protected OJSONWriter writer;
protected long recordExported;
protected int compressionLevel = Deflater.BEST_SPEED;
protected int compressionBuffer = 16384; // 16Kb
public ODatabaseExport(final ODatabaseDocumentInternal iDatabase, final String iFileName, final OCommandOutputListener iListener)
throws IOException {
super(iDatabase, iFileName, iListener);
if (fileName == null)
throw new IllegalArgumentException("file name missing");
if (!fileName.endsWith(".gz")) {
fileName += ".gz";
}
final File f = new File(fileName);
if (f.getParentFile() != null)
f.getParentFile().mkdirs();
if (f.exists())
f.delete();
final GZIPOutputStream gzipOS = new GZIPOutputStream(new FileOutputStream(fileName), compressionBuffer) {
{
def.setLevel(compressionLevel);
}
};
writer = new OJSONWriter(new OutputStreamWriter(gzipOS));
writer.beginObject();
}
public ODatabaseExport(final ODatabaseDocumentInternal iDatabase, final OutputStream iOutputStream,
final OCommandOutputListener iListener) throws IOException {
super(iDatabase, "streaming", iListener);
writer = new OJSONWriter(new OutputStreamWriter(iOutputStream));
writer.beginObject();
}
@Override
public void run() {
exportDatabase();
}
@Override
public ODatabaseExport setOptions(final String s) {
super.setOptions(s);
return this;
}
public ODatabaseExport exportDatabase() {
try {
listener.onMessage("\nStarted export of database '" + database.getName() + "' to " + fileName + "...");
long time = System.currentTimeMillis();
if (includeInfo)
exportInfo();
if (includeClusterDefinitions)
exportClusters();
if (includeSchema)
exportSchema();
if (includeRecords)
exportRecords();
if (includeIndexDefinitions)
exportIndexDefinitions();
if (includeManualIndexes)
exportManualIndexes();
listener.onMessage("\n\nDatabase export completed in " + (System.currentTimeMillis() - time) + "ms");
writer.flush();
} catch (Exception e) {
OLogManager.instance().error(this, "Error on exporting database '%s' to: %s", e, database.getName(), fileName);
throw new ODatabaseExportException("Error on exporting database '" + database.getName() + "' to: " + fileName, e);
} finally {
close();
}
return this;
}
public long exportRecords() throws IOException {
long totalFoundRecords = 0;
long totalExportedRecords = 0;
int level = 1;
listener.onMessage("\nExporting records...");
writer.beginCollection(level, true, "records");
int exportedClusters = 0;
int maxClusterId = getMaxClusterId();
for (int i = 0; exportedClusters <= maxClusterId; ++i) {
String clusterName = database.getClusterNameById(i);
exportedClusters++;
long clusterExportedRecordsTot = 0;
if (clusterName != null) {
// CHECK IF THE CLUSTER IS INCLUDED
if (includeClusters != null) {
if (!includeClusters.contains(clusterName.toUpperCase(Locale.ENGLISH)))
continue;
} else if (excludeClusters != null) {
if (excludeClusters.contains(clusterName.toUpperCase(Locale.ENGLISH)))
continue;
}
if (excludeClusters != null && excludeClusters.contains(clusterName.toUpperCase(Locale.ENGLISH)))
continue;
clusterExportedRecordsTot = database.countClusterElements(clusterName);
} else if (includeClusters != null && !includeClusters.isEmpty())
continue;
listener.onMessage("\n- Cluster " + (clusterName != null ? "'" + clusterName + "'" : "NULL") + " (id=" + i + ")...");
long clusterExportedRecordsCurrent = 0;
if (clusterName != null) {
ORecord rec = null;
try {
for (ORecordIteratorCluster<ORecord> it = database.browseCluster(clusterName); it.hasNext();) {
rec = it.next();
if (rec instanceof ODocument) {
// CHECK IF THE CLASS OF THE DOCUMENT IS INCLUDED
ODocument doc = (ODocument) rec;
final String className = doc.getClassName() != null ? doc.getClassName().toUpperCase(Locale.ENGLISH) : null;
if (includeClasses != null) {
if (!includeClasses.contains(className))
continue;
} else if (excludeClasses != null) {
if (excludeClasses.contains(className))
continue;
}
} else if (includeClasses != null && !includeClasses.isEmpty())
continue;
if (exportRecord(clusterExportedRecordsTot, clusterExportedRecordsCurrent, rec))
clusterExportedRecordsCurrent++;
}
} catch (IOException e) {
OLogManager.instance().error(this, "\nError on exporting record %s because of I/O problems", e, rec.getIdentity());
// RE-THROW THE EXCEPTION UP
throw e;
} catch (OIOException e) {
OLogManager.instance().error(this, "\nError on exporting record %s because of I/O problems", e,
rec == null ? null : rec.getIdentity());
// RE-THROW THE EXCEPTION UP
throw e;
} catch (Throwable t) {
if (rec != null) {
final byte[] buffer = rec.toStream();
OLogManager.instance().error(this,
"\nError on exporting record %s. It seems corrupted; size: %d bytes, raw content (as string):\n==========\n%s\n==========",
t, rec.getIdentity(), buffer.length, new String(buffer));
}
}
}
listener.onMessage("OK (records=" + clusterExportedRecordsCurrent + "/" + clusterExportedRecordsTot + ")");
totalExportedRecords += clusterExportedRecordsCurrent;
totalFoundRecords += clusterExportedRecordsTot;
}
writer.endCollection(level, true);
listener.onMessage("\n\nDone. Exported " + totalExportedRecords + " of total " + totalFoundRecords + " records\n");
return totalExportedRecords;
}
public void close() {
database.declareIntent(null);
if (writer == null)
return;
try {
writer.endObject();
writer.close();
writer = null;
} catch (IOException e) {
}
}
protected int getMaxClusterId() {
int totalCluster = -1;
for (String clusterName : database.getClusterNames()) {
if (database.getClusterIdByName(clusterName) > totalCluster)
totalCluster = database.getClusterIdByName(clusterName);
}
return totalCluster;
}
@Override
protected void parseSetting(final String option, final List<String> items) {
if (option.equalsIgnoreCase("-compressionLevel"))
compressionLevel = Integer.parseInt(items.get(0));
else if (option.equalsIgnoreCase("-compressionBuffer"))
compressionBuffer = Integer.parseInt(items.get(0));
else
super.parseSetting(option, items);
}
private void exportClusters() throws IOException {
listener.onMessage("\nExporting clusters...");
writer.beginCollection(1, true, "clusters");
int exportedClusters = 0;
int maxClusterId = getMaxClusterId();
for (int clusterId = 0; clusterId <= maxClusterId; ++clusterId) {
final String clusterName = database.getClusterNameById(clusterId);
// exclude removed clusters
if (clusterName == null)
continue;
// CHECK IF THE CLUSTER IS INCLUDED
if (includeClusters != null) {
if (!includeClusters.contains(clusterName.toUpperCase(Locale.ENGLISH)))
continue;
} else if (excludeClusters != null) {
if (excludeClusters.contains(clusterName.toUpperCase(Locale.ENGLISH)))
continue;
}
writer.beginObject(2, true, null);
writer.writeAttribute(0, false, "name", clusterName);
writer.writeAttribute(0, false, "id", clusterId);
exportedClusters++;
writer.endObject(2, false);
}
listener.onMessage("OK (" + exportedClusters + " clusters)");
writer.endCollection(1, true);
}
private void exportInfo() throws IOException {
listener.onMessage("\nExporting database info...");
writer.beginObject(1, true, "info");
writer.writeAttribute(2, true, "name", database.getName().replace('\\', '/'));
writer.writeAttribute(2, true, "default-cluster-id", database.getDefaultClusterId());
writer.writeAttribute(2, true, "exporter-version", VERSION);
writer.writeAttribute(2, true, "engine-version", OConstants.ORIENT_VERSION);
final String engineBuild = OConstants.getBuildNumber();
if (engineBuild != null)
writer.writeAttribute(2, true, "engine-build", engineBuild);
writer.writeAttribute(2, true, "storage-config-version", OStorageConfiguration.CURRENT_VERSION);
writer.writeAttribute(2, true, "schema-version", OSchemaShared.CURRENT_VERSION_NUMBER);
writer.writeAttribute(2, true, "schemaRecordId", database.getStorage().getConfiguration().schemaRecordId);
writer.writeAttribute(2, true, "indexMgrRecordId", database.getStorage().getConfiguration().indexMgrRecordId);
writer.endObject(1, true);
listener.onMessage("OK");
}
private void exportIndexDefinitions() throws IOException {
listener.onMessage("\nExporting index info...");
writer.beginCollection(1, true, "indexes");
final OIndexManager indexManager = database.getMetadata().getIndexManager();
indexManager.reload();
final Collection<? extends OIndex<?>> indexes = indexManager.getIndexes();
for (OIndex<?> index : indexes) {
if (index.getName().equals(ODatabaseImport.EXPORT_IMPORT_MAP_NAME))
continue;
final String clsName = index.getDefinition() != null ? index.getDefinition().getClassName() : null;
// CHECK TO FILTER CLASS
if (includeClasses != null) {
if (!includeClasses.contains(clsName))
continue;
} else if (excludeClasses != null) {
if (excludeClasses.contains(clsName))
continue;
}
listener.onMessage("\n- Index " + index.getName() + "...");
writer.beginObject(2, true, null);
writer.writeAttribute(3, true, "name", index.getName());
writer.writeAttribute(3, true, "type", index.getType());
if (index.getAlgorithm() != null)
writer.writeAttribute(3, true, "algorithm", index.getAlgorithm());
if (!index.getClusters().isEmpty())
writer.writeAttribute(3, true, "clustersToIndex", index.getClusters());
if (index.getDefinition() != null) {
writer.beginObject(4, true, "definition");
writer.writeAttribute(5, true, "defClass", index.getDefinition().getClass().getName());
writer.writeAttribute(5, true, "stream", index.getDefinition().toStream());
writer.endObject(4, true);
}
final ODocument metadata = index.getMetadata();
if (metadata != null)
writer.writeAttribute(4, true, "metadata", metadata);
final ODocument configuration = index.getConfiguration();
if (configuration.field("blueprintsIndexClass") != null)
writer.writeAttribute(4, true, "blueprintsIndexClass", configuration.field("blueprintsIndexClass"));
writer.endObject(2, true);
listener.onMessage("OK");
}
writer.endCollection(1, true);
listener.onMessage("\nOK (" + indexes.size() + " indexes)");
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void exportManualIndexes() throws IOException {
listener.onMessage("\nExporting manual indexes content...");
final OIndexManager indexManager = database.getMetadata().getIndexManager();
indexManager.reload();
final Collection<? extends OIndex<?>> indexes = indexManager.getIndexes();
ODocument exportEntry = new ODocument();
int manualIndexes = 0;
writer.beginCollection(1, true, "manualIndexes");
for (OIndex<?> index : indexes) {
if (index.getName().equals(ODatabaseImport.EXPORT_IMPORT_MAP_NAME))
continue;
if (!index.isAutomatic()) {
listener.onMessage("\n- Exporting index " + index.getName() + " ...");
writer.beginObject(2, true, null);
writer.writeAttribute(3, true, "name", index.getName());
List<ODocument> indexContent = database.query(new OSQLSynchQuery<ODocument>("select from index:" + index.getName()));
writer.beginCollection(3, true, "content");
int i = 0;
for (ODocument indexEntry : indexContent) {
if (i > 0)
writer.append(",");
indexEntry.setLazyLoad(false);
final OIndexDefinition indexDefinition = index.getDefinition();
exportEntry.reset();
exportEntry.setLazyLoad(false);
if (indexDefinition instanceof ORuntimeKeyIndexDefinition
&& ((ORuntimeKeyIndexDefinition) indexDefinition).getSerializer() != null) {
final OBinarySerializer binarySerializer = ((ORuntimeKeyIndexDefinition) indexDefinition).getSerializer();
final int dataSize = binarySerializer.getObjectSize(indexEntry.field("key"));
final byte[] binaryContent = new byte[dataSize];
binarySerializer.serialize(indexEntry.field("key"), binaryContent, 0);
exportEntry.field("binary", true);
exportEntry.field("key", binaryContent);
} else {
exportEntry.field("binary", false);
exportEntry.field("key", indexEntry.<Object>field("key"));
}
exportEntry.field("rid", indexEntry.<Object>field("rid"));
i++;
writer.append(exportEntry.toJSON());
final long percent = indexContent.size() / 10;
if (percent > 0 && (i % percent) == 0)
listener.onMessage(".");
}
writer.endCollection(3, true);
writer.endObject(2, true);
listener.onMessage("OK (entries=" + index.getSize() + ")");
manualIndexes++;
}
}
writer.endCollection(1, true);
listener.onMessage("\nOK (" + manualIndexes + " manual indexes)");
}
private void exportSchema() throws IOException {
listener.onMessage("\nExporting schema...");
writer.beginObject(1, true, "schema");
OSchema s = ((OMetadataInternal) database.getMetadata()).getImmutableSchemaSnapshot();
writer.writeAttribute(2, true, "version", s.getVersion());
writer.writeAttribute(2, false, "blob-clusters", database.getBlobClusterIds());
if (!s.getClasses().isEmpty()) {
writer.beginCollection(2, true, "classes");
final List<OClass> classes = new ArrayList<OClass>(s.getClasses());
Collections.sort(classes);
for (OClass cls : classes) {
// CHECK TO FILTER CLASS
if (includeClasses != null) {
if (!includeClasses.contains(cls.getName().toUpperCase(Locale.ENGLISH)))
continue;
} else if (excludeClasses != null) {
if (excludeClasses.contains(cls.getName().toUpperCase(Locale.ENGLISH)))
continue;
}
writer.beginObject(3, true, null);
writer.writeAttribute(0, false, "name", cls.getName());
writer.writeAttribute(0, false, "default-cluster-id", cls.getDefaultClusterId());
writer.writeAttribute(0, false, "cluster-ids", cls.getClusterIds());
if (cls.getOverSize() > 1)
writer.writeAttribute(0, false, "oversize", cls.getClassOverSize());
if (cls.isStrictMode())
writer.writeAttribute(0, false, "strictMode", cls.isStrictMode());
if (!cls.getSuperClasses().isEmpty())
writer.writeAttribute(0, false, "super-classes", cls.getSuperClassesNames());
if (cls.getShortName() != null)
writer.writeAttribute(0, false, "short-name", cls.getShortName());
if (cls.isAbstract())
writer.writeAttribute(0, false, "abstract", cls.isAbstract());
writer.writeAttribute(0, false, "cluster-selection", cls.getClusterSelection().getName()); // @SINCE 1.7
if (!cls.properties().isEmpty()) {
writer.beginCollection(4, true, "properties");
final List<OProperty> properties = new ArrayList<OProperty>(cls.declaredProperties());
Collections.sort(properties);
for (OProperty p : properties) {
writer.beginObject(5, true, null);
writer.writeAttribute(0, false, "name", p.getName());
writer.writeAttribute(0, false, "type", p.getType().toString());
if (p.isMandatory())
writer.writeAttribute(0, false, "mandatory", p.isMandatory());
if (p.isReadonly())
writer.writeAttribute(0, false, "readonly", p.isReadonly());
if (p.isNotNull())
writer.writeAttribute(0, false, "not-null", p.isNotNull());
if (p.getLinkedClass() != null)
writer.writeAttribute(0, false, "linked-class", p.getLinkedClass().getName());
if (p.getLinkedType() != null)
writer.writeAttribute(0, false, "linked-type", p.getLinkedType().toString());
if (p.getMin() != null)
writer.writeAttribute(0, false, "min", p.getMin());
if (p.getMax() != null)
writer.writeAttribute(0, false, "max", p.getMax());
if (p.getCollate() != null)
writer.writeAttribute(0, false, "collate", p.getCollate().getName());
if (p.getDefaultValue() != null)
writer.writeAttribute(0, false, "default-value", p.getDefaultValue());
if (p.getRegexp() != null)
writer.writeAttribute(0, false, "regexp", p.getRegexp());
final Set<String> customKeys = p.getCustomKeys();
final Map<String, String> custom = new HashMap<String, String>();
for (String key : customKeys)
custom.put(key, p.getCustom(key));
if (!custom.isEmpty())
writer.writeAttribute(0, false, "customFields", custom);
writer.endObject(0, false);
}
writer.endCollection(4, true);
}
final Set<String> customKeys = cls.getCustomKeys();
final Map<String, String> custom = new HashMap<String, String>();
for (String key : customKeys)
custom.put(key, cls.getCustom(key));
if (!custom.isEmpty())
writer.writeAttribute(0, false, "customFields", custom);
writer.endObject(3, true);
}
writer.endCollection(2, true);
}
writer.endObject(1, true);
listener.onMessage("OK (" + s.getClasses().size() + " classes)");
}
private boolean exportRecord(long recordTot, long recordNum, ORecord rec) throws IOException {
if (rec != null)
try {
if (rec.getIdentity().isValid())
rec.reload();
if (useLineFeedForRecords)
writer.append("\n");
if (recordExported > 0)
writer.append(",");
writer.append(rec.toJSON("rid,type,version,class,attribSameRow,keepTypes,alwaysFetchEmbedded,dateAsLong"));
recordExported++;
recordNum++;
if (recordTot > 10 && (recordNum + 1) % (recordTot / 10) == 0)
listener.onMessage(".");
return true;
} catch (Throwable t) {
if (rec != null) {
final byte[] buffer = rec.toStream();
OLogManager.instance().error(this,
"\nError on exporting record %s. It seems corrupted; size: %d bytes, raw content (as string):\n==========\n%s\n==========",
t, rec.getIdentity(), buffer.length, new String(buffer));
}
}
return false;
}
}