1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package com.allanbank.mongodb.gridfs;
22
23 import static com.allanbank.mongodb.builder.QueryBuilder.where;
24 import static com.allanbank.mongodb.builder.Sort.asc;
25
26 import java.io.FileNotFoundException;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.InterruptedIOException;
30 import java.io.OutputStream;
31 import java.security.MessageDigest;
32 import java.security.NoSuchAlgorithmException;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.HashMap;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.concurrent.ExecutionException;
39 import java.util.concurrent.Future;
40
41 import com.allanbank.mongodb.Durability;
42 import com.allanbank.mongodb.MongoCollection;
43 import com.allanbank.mongodb.MongoDatabase;
44 import com.allanbank.mongodb.MongoDbException;
45 import com.allanbank.mongodb.MongoDbUri;
46 import com.allanbank.mongodb.MongoFactory;
47 import com.allanbank.mongodb.MongoIterator;
48 import com.allanbank.mongodb.bson.Document;
49 import com.allanbank.mongodb.bson.Element;
50 import com.allanbank.mongodb.bson.NumericElement;
51 import com.allanbank.mongodb.bson.builder.BuilderFactory;
52 import com.allanbank.mongodb.bson.builder.DocumentBuilder;
53 import com.allanbank.mongodb.bson.element.BinaryElement;
54 import com.allanbank.mongodb.bson.element.ObjectId;
55 import com.allanbank.mongodb.bson.element.StringElement;
56 import com.allanbank.mongodb.builder.Find;
57 import com.allanbank.mongodb.builder.Index;
58 import com.allanbank.mongodb.util.IOUtils;
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76 public class GridFs {
77
78
79
80
81
82 public static final String CHUNK_NUMBER_FIELD = "n";
83
84
85 public static final int CHUNK_OVERHEAD = 62;
86
87
88
89
90
91 public static final String CHUNK_SIZE_FIELD = "chunkSize";
92
93
94 public static final String CHUNKS_SUFFIX = ".chunks";
95
96
97
98
99
100 public static final String DATA_FIELD = "data";
101
102
103
104
105
106 public static final int DEFAULT_CHUNK_SIZE;
107
108
109 public static final String DEFAULT_ROOT = "fs";
110
111
112
113
114
115 public static final String FILENAME_FIELD = "filename";
116
117
118
119
120
121 public static final String FILES_ID_FIELD = "files_id";
122
123
124 public static final String FILES_SUFFIX = ".files";
125
126
127 public static final String ID_FIELD = "_id";
128
129
130
131
132
133 public static final String LENGTH_FIELD = "length";
134
135
136
137
138
139 public static final String MD5_FIELD = "md5";
140
141
142
143
144
145 public static final String UPLOAD_DATE_FIELD = "uploadDate";
146
147 static {
148 DEFAULT_CHUNK_SIZE = (256 * 1024) - CHUNK_OVERHEAD;
149 }
150
151
152 private final MongoCollection myChunksCollection;
153
154
155 private int myChunkSize = DEFAULT_CHUNK_SIZE;
156
157
158 private final MongoDatabase myDatabase;
159
160
161 private final MongoCollection myFilesCollection;
162
163
164 private final String myRootName;
165
166
167
168
169
170
171
172
173
174
175 public GridFs(final MongoDatabase database) {
176 this(database, DEFAULT_ROOT);
177 }
178
179
180
181
182
183
184
185
186
187
188
189
190 public GridFs(final MongoDatabase database, final String rootName) {
191 myRootName = rootName;
192 myDatabase = database;
193 myFilesCollection = database.getCollection(rootName + FILES_SUFFIX);
194 myChunksCollection = database.getCollection(rootName + CHUNKS_SUFFIX);
195 }
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210 public GridFs(final String mongoDbUri) {
211 this(mongoDbUri, DEFAULT_ROOT);
212 }
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231 public GridFs(final String mongoDbUri, final String rootName) {
232 final MongoDbUri uri = new MongoDbUri(mongoDbUri);
233
234 final MongoDatabase database = MongoFactory.createClient(uri)
235 .getDatabase(uri.getDatabase());
236
237 myRootName = rootName;
238 myDatabase = database;
239 myFilesCollection = database.getCollection(rootName + FILES_SUFFIX);
240 myChunksCollection = database.getCollection(rootName + CHUNKS_SUFFIX);
241 }
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261 public void createIndexes() {
262 try {
263 myFilesCollection.createIndex(true, Index.asc(FILENAME_FIELD),
264 Index.asc(UPLOAD_DATE_FIELD));
265 }
266 catch (final MongoDbException error) {
267
268 myFilesCollection.createIndex(false, Index.asc(FILENAME_FIELD),
269 Index.asc(UPLOAD_DATE_FIELD));
270 }
271
272 try {
273 myChunksCollection.createIndex(true, Index.asc(FILES_ID_FIELD),
274 Index.asc(CHUNK_NUMBER_FIELD));
275 }
276 catch (final MongoDbException error) {
277
278 myChunksCollection.createIndex(false, Index.asc(FILES_ID_FIELD),
279 Index.asc(CHUNK_NUMBER_FIELD));
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 public Map<Object, List<String>> fsck(final boolean repair)
337 throws IOException {
338
339 final Map<Object, List<String>> faults = new HashMap<Object, List<String>>();
340
341 createIndexes();
342
343
344 final MongoIterator<Document> iter = myFilesCollection.find(Find.ALL);
345 try {
346 for (final Document fileDoc : iter) {
347 final Element id = fileDoc.get(ID_FIELD);
348
349 final DocumentBuilder commandDoc = BuilderFactory.start();
350 commandDoc.add(id.withName("filemd5"));
351 commandDoc.add("root", myRootName);
352
353 final Document commandResult = myDatabase.runCommand(commandDoc
354 .build());
355 if (!doVerifyFileMd5(faults, fileDoc, commandResult) && repair) {
356 doTryAndRepair(fileDoc, faults);
357 }
358 }
359 }
360 finally {
361 iter.close();
362 }
363 return faults;
364 }
365
366
367
368
369
370
371 public int getChunkSize() {
372 return myChunkSize;
373 }
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388 public void read(final ObjectId id, final OutputStream sink)
389 throws IOException {
390
391 final Document fileDoc = myFilesCollection.findOne(where(ID_FIELD)
392 .equals(id));
393 if (fileDoc == null) {
394 throw new FileNotFoundException(id.toString());
395 }
396
397 doRead(fileDoc, sink);
398 }
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413 public void read(final String name, final OutputStream sink)
414 throws IOException {
415
416
417 final Document fileDoc = myFilesCollection
418 .findOne(where(FILENAME_FIELD).equals(name));
419 if (fileDoc == null) {
420 throw new FileNotFoundException(name);
421 }
422
423 doRead(fileDoc, sink);
424 }
425
426
427
428
429
430
431
432 public void setChunkSize(final int chunkSize) {
433 myChunkSize = chunkSize;
434 }
435
436
437
438
439
440
441
442
443
444
445 public boolean unlink(final ObjectId id) throws IOException {
446
447
448 final Document fileDoc = myFilesCollection.findOne(where(ID_FIELD)
449 .equals(id));
450 if (fileDoc == null) {
451 return false;
452 }
453
454 return doUnlink(fileDoc);
455 }
456
457
458
459
460
461
462
463
464
465
466 public boolean unlink(final String name) throws IOException {
467
468
469 final Document fileDoc = myFilesCollection
470 .findOne(where(FILENAME_FIELD).equals(name));
471 if (fileDoc == null) {
472 return false;
473 }
474
475 return doUnlink(fileDoc);
476 }
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498 public boolean validate(final ObjectId id) throws IOException {
499
500
501 final Document fileDoc = myFilesCollection.findOne(where(ID_FIELD)
502 .equals(id));
503 if (fileDoc == null) {
504 throw new FileNotFoundException(id.toString());
505 }
506
507 return doValidate(fileDoc);
508 }
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530 public boolean validate(final String name) throws IOException {
531
532
533 final Document fileDoc = myFilesCollection
534 .findOne(where(FILENAME_FIELD).equals(name));
535 if (fileDoc == null) {
536 throw new FileNotFoundException(name);
537 }
538
539 return doValidate(fileDoc);
540 }
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558 public ObjectId write(final String name, final InputStream source)
559 throws IOException {
560 final ObjectId id = new ObjectId();
561 boolean failed = false;
562 try {
563 final byte[] buffer = new byte[myChunkSize];
564 final MessageDigest md5Digest = MessageDigest.getInstance("MD5");
565
566 final List<Future<Integer>> results = new ArrayList<Future<Integer>>();
567 final DocumentBuilder doc = BuilderFactory.start();
568 int n = 0;
569 long length = 0;
570 int read = readFully(source, buffer);
571 while (read > 0) {
572
573 final ObjectId chunkId = new ObjectId();
574
575 doc.reset();
576 doc.addObjectId(ID_FIELD, chunkId);
577 doc.addObjectId(FILES_ID_FIELD, id);
578 doc.addInteger(CHUNK_NUMBER_FIELD, n);
579
580 final byte[] data = (read == buffer.length) ? buffer : Arrays
581 .copyOf(buffer, read);
582 md5Digest.update(data);
583 doc.addBinary(DATA_FIELD, data);
584
585 results.add(myChunksCollection.insertAsync(doc.build()));
586
587 length += data.length;
588 read = readFully(source, buffer);
589 n += 1;
590 }
591
592 doc.reset();
593 doc.addObjectId(ID_FIELD, id);
594 doc.addString(FILENAME_FIELD, name);
595 doc.addTimestamp(UPLOAD_DATE_FIELD, System.currentTimeMillis());
596 doc.addInteger(CHUNK_SIZE_FIELD, buffer.length);
597 doc.addLong(LENGTH_FIELD, length);
598 doc.addString(MD5_FIELD, IOUtils.toHex(md5Digest.digest()));
599
600 results.add(myFilesCollection.insertAsync(doc.build()));
601
602
603 for (final Future<Integer> f : results) {
604 f.get();
605 }
606 }
607 catch (final NoSuchAlgorithmException e) {
608 failed = true;
609 throw new IOException(e);
610 }
611 catch (final InterruptedException e) {
612 failed = true;
613 final InterruptedIOException error = new InterruptedIOException(
614 e.getMessage());
615 error.initCause(e);
616 throw error;
617 }
618 catch (final ExecutionException e) {
619 failed = true;
620 throw new IOException(e.getCause());
621 }
622 finally {
623 if (failed) {
624 myFilesCollection.delete(where(ID_FIELD).equals(id));
625 myChunksCollection.delete(where(FILES_ID_FIELD).equals(id));
626 }
627 }
628
629 return id;
630 }
631
632
633
634
635
636
637
638
639
640
641
642 protected void doAddFault(final Map<Object, List<String>> faults,
643 final Element idObj, final String message) {
644 List<String> docFaults = faults.get(idObj.getValueAsObject());
645 if (docFaults == null) {
646 docFaults = new ArrayList<String>();
647 faults.put(idObj.getValueAsObject(), docFaults);
648 }
649 docFaults.add(message);
650 }
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665 protected void doRead(final Document fileDoc, final OutputStream sink)
666 throws IOException {
667
668 final Element id = fileDoc.get(ID_FIELD);
669
670 long length = -1;
671 final NumericElement lengthElement = fileDoc.get(NumericElement.class,
672 LENGTH_FIELD);
673 if (lengthElement != null) {
674 length = lengthElement.getLongValue();
675 }
676
677 long chunkSize = -1;
678 final NumericElement chunkSizeElement = fileDoc.get(
679 NumericElement.class, CHUNK_SIZE_FIELD);
680 if (chunkSizeElement != null) {
681 chunkSize = chunkSizeElement.getLongValue();
682 }
683
684 long numberChunks = -1;
685 if ((0 <= length) && (0 < chunkSize)) {
686 numberChunks = (long) Math.ceil((double) length
687 / (double) chunkSize);
688 }
689
690 final Element queryElement = id.withName(FILES_ID_FIELD);
691 final DocumentBuilder queryDoc = BuilderFactory.start();
692 queryDoc.add(queryElement);
693
694 final Find.Builder findBuilder = new Find.Builder(queryDoc.build());
695 findBuilder.setSort(asc(CHUNK_NUMBER_FIELD));
696
697
698 findBuilder.setBatchSize(2);
699
700 long expectedChunk = 0;
701 long totalSize = 0;
702 final MongoIterator<Document> iter = myChunksCollection
703 .find(findBuilder.build());
704 try {
705 for (final Document chunk : iter) {
706
707 final NumericElement n = chunk.get(NumericElement.class,
708 CHUNK_NUMBER_FIELD);
709 final BinaryElement bytes = chunk.get(BinaryElement.class,
710 DATA_FIELD);
711
712 if (n == null) {
713 throw new IOException("Missing chunk number '"
714 + (expectedChunk + 1) + "' of '" + numberChunks
715 + "'.");
716 }
717 else if (n.getLongValue() != expectedChunk) {
718 throw new IOException("Skipped chunk '"
719 + (expectedChunk + 1) + "', retreived '"
720 + n.getLongValue() + "' of '" + numberChunks + "'.");
721 }
722 else if (bytes == null) {
723 throw new IOException("Missing bytes in chunk '"
724 + (expectedChunk + 1) + "' of '" + numberChunks
725 + "'.");
726 }
727 else {
728
729 final byte[] buffer = bytes.getValue();
730
731 sink.write(buffer);
732 expectedChunk += 1;
733 totalSize += buffer.length;
734 }
735 }
736 }
737 finally {
738 iter.close();
739 sink.flush();
740 }
741
742 if ((0 <= numberChunks) && (expectedChunk < numberChunks)) {
743 throw new IOException("Missing chunks after '" + expectedChunk
744 + "' of '" + numberChunks + "'.");
745 }
746 if ((0 <= length) && (totalSize != length)) {
747 throw new IOException("File size mismatch. Expected '" + length
748 + "' but only read '" + totalSize + "' bytes.");
749 }
750 }
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765 protected void doTryAndRepair(final Document fileDoc,
766 final Map<Object, List<String>> faults) {
767
768
769 final List<Element> chunkIds = new ArrayList<Element>();
770
771 final Element id = fileDoc.get(ID_FIELD);
772 final Element md5 = fileDoc.get(MD5_FIELD);
773 final Element queryElement = id.withName(FILES_ID_FIELD);
774 final DocumentBuilder queryDoc = BuilderFactory.start().add(
775 queryElement);
776
777 final Find.Builder findBuilder = new Find.Builder(queryDoc.build());
778 findBuilder.setSort(asc(ID_FIELD));
779
780
781 findBuilder.setBatchSize(2);
782
783 MongoIterator<Document> iter = null;
784 try {
785 final MessageDigest md5Digest = MessageDigest.getInstance("MD5");
786 iter = myChunksCollection.find(findBuilder);
787 for (final Document chunkDoc : iter) {
788
789 chunkIds.add(chunkDoc.get(ID_FIELD));
790
791 final BinaryElement chunk = chunkDoc.get(BinaryElement.class,
792 DATA_FIELD);
793 if (chunk != null) {
794 md5Digest.update(chunk.getValue());
795 }
796 }
797
798 final String digest = IOUtils.toHex(md5Digest.digest());
799 final StringElement computed = new StringElement(MD5_FIELD, digest);
800 if (computed.equals(md5)) {
801
802
803 int n = 0;
804 for (final Element idElement : chunkIds) {
805 final DocumentBuilder query = BuilderFactory.start();
806 query.add(idElement);
807 query.add(queryElement);
808
809 final DocumentBuilder update = BuilderFactory.start();
810 update.push("$set").add(CHUNK_NUMBER_FIELD, n);
811
812
813
814 myChunksCollection.update(query.build(), update.build(),
815 true , false, Durability.ACK);
816
817 n += 1;
818 }
819
820 if (doValidate(fileDoc)) {
821 doAddFault(faults, id, "File repaired.");
822
823 }
824 else {
825 doAddFault(faults, id,
826 "Repair failed: Chunks reordered but sill not validating.");
827 }
828 }
829 else {
830 doAddFault(faults, id,
831 "Repair failed: Could not determine correct chunk order.");
832 }
833 }
834 catch (final NoSuchAlgorithmException e) {
835 doAddFault(faults, id,
836 "Repair failed: Could not compute the MD5 for the file: "
837 + e.getMessage());
838 }
839 catch (final RuntimeException e) {
840 doAddFault(faults, id, "Potential Repair Failure: Runtime error: "
841 + e.getMessage());
842 }
843 finally {
844 IOUtils.close(iter);
845 }
846 }
847
848
849
850
851
852
853
854
855
856
857 protected boolean doUnlink(final Document fileDoc) throws IOException {
858 final Element id = fileDoc.get(ID_FIELD);
859
860 final DocumentBuilder queryDoc = BuilderFactory.start();
861 queryDoc.add(id.withName(FILES_ID_FIELD));
862 final Future<Long> cFuture = myChunksCollection.deleteAsync(queryDoc);
863
864 queryDoc.reset();
865 queryDoc.add(id);
866 final Future<Long> fFuture = myFilesCollection.deleteAsync(queryDoc);
867
868 try {
869 return (cFuture.get().longValue() >= 0)
870 && (fFuture.get().longValue() > 0);
871 }
872 catch (final InterruptedException e) {
873 return false;
874 }
875 catch (final ExecutionException e) {
876 return false;
877 }
878 }
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898 protected boolean doValidate(final Document fileDoc) {
899 final Element id = fileDoc.get(ID_FIELD);
900 final Element md5 = fileDoc.get(MD5_FIELD);
901
902 final DocumentBuilder commandDoc = BuilderFactory.start();
903 commandDoc.add(id.withName("filemd5"));
904 commandDoc.add("root", myRootName);
905 final Document result = myDatabase.runCommand(commandDoc.build());
906
907 return (md5 != null) && md5.equals(result.findFirst(MD5_FIELD));
908 }
909
910
911
912
913
914
915
916
917
918
919
920
921 protected boolean doVerifyFileMd5(final Map<Object, List<String>> faults,
922 final Document fileDoc, final Document cmdResult) {
923 boolean ok = false;
924 final Element idElement = fileDoc.get(ID_FIELD);
925
926 final Element md5 = fileDoc.get(MD5_FIELD);
927 final Element commandMd5 = cmdResult.findFirst(MD5_FIELD);
928
929 ok = (md5 != null) && md5.equals(commandMd5);
930 if (!ok) {
931 doAddFault(faults, idElement,
932 "MD5 sums do not match. File document contains '" + md5
933 + "' and the filemd5 command produced '"
934 + commandMd5 + "'.");
935 }
936
937 return ok;
938 }
939
940
941
942
943
944
945
946
947
948
949
950
951
952 private int readFully(final InputStream source, final byte[] buffer)
953 throws IOException {
954
955 int offset = 0;
956
957 while (true) {
958 final int read = source
959 .read(buffer, offset, buffer.length - offset);
960 if (read < 0) {
961 return offset;
962 }
963
964 offset += read;
965
966 if (offset == buffer.length) {
967 return offset;
968 }
969 }
970 }
971 }