-
Notifications
You must be signed in to change notification settings - Fork 131
/
FsSqlDriver.java
2227 lines (2023 loc) · 80.9 KB
/
FsSqlDriver.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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program (see the file COPYING.LIB for more
* details); if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.dcache.chimera;
import static java.util.stream.Collectors.toList;
import static org.dcache.chimera.FileSystemProvider.SetXattrMode;
import static org.dcache.chimera.FileSystemProvider.StatCacheOption.STAT;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import diskCacheV111.util.AccessLatency;
import diskCacheV111.util.RetentionPolicy;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import javax.sql.DataSource;
import org.dcache.acl.ACE;
import org.dcache.acl.enums.AceFlags;
import org.dcache.acl.enums.AceType;
import org.dcache.acl.enums.RsType;
import org.dcache.acl.enums.Who;
import org.dcache.chimera.FileSystemProvider.StatCacheOption;
import org.dcache.chimera.posix.Stat;
import org.dcache.chimera.spi.DBDriverProvider;
import org.dcache.chimera.store.InodeStorageInformation;
import org.dcache.util.Checksum;
import org.dcache.util.ChecksumType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.JdbcUpdateAffectedIncorrectNumberOfRowsException;
import org.springframework.jdbc.LobRetrievalFailureException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ParameterizedPreparedStatementSetter;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator;
/**
* SQL driver
*/
public class FsSqlDriver {
/**
* Simple class to hold a tag assignment's directory inumber and its value.
*/
private class LocatedPrimaryTag {
private final long inumber;
private final byte[] value;
LocatedPrimaryTag(long inumber, byte[] value) {
this.inumber = inumber;
this.value = value;
}
public long getInumber() {
return inumber;
}
public byte[] getValue() {
return value;
}
}
/**
* logger
*/
private static final Logger LOGGER = LoggerFactory.getLogger(FsSqlDriver.class);
private static final ServiceLoader<DBDriverProvider> ALL_PROVIDERS
= ServiceLoader.load(DBDriverProvider.class);
final JdbcTemplate _jdbc;
private final long _root;
/**
* this is a utility class which is issues SQL queries on database
*/
protected FsSqlDriver(DataSource dataSource) throws ChimeraFsException {
_jdbc = new JdbcTemplate(dataSource);
_jdbc.setExceptionTranslator(new SQLErrorCodeSQLExceptionTranslator(dataSource) {
@Override
protected DataAccessException customTranslate(String task, String sql,
SQLException sqlEx) {
if (isForeignKeyError(sqlEx)) {
return new ForeignKeyViolationException(buildMessage(task, sql, sqlEx), sqlEx);
}
return super.customTranslate(task, sql, sqlEx);
}
});
Long root = getInumber("000000000000000000000000000000000000");
if (root == null) {
throw FileNotFoundChimeraFsException.ofPnfsId("000000000000000000000000000000000000");
}
_root = root;
}
long getRootInumber() {
return _root;
}
/**
* Update file system cache table.
*/
void updateFsStat() {
try {
_jdbc.update("UPDATE t_fstat SET " +
"iusedFiles = (SELECT count(*) AS usedFiles FROM t_inodes WHERE itype=32768), " +
"iusedSpace = (SELECT SUM(isize) AS usedSpace FROM t_inodes WHERE itype=32768)");
} catch (DataAccessException e) {
Throwable cause = Throwables.getRootCause(e);
if (cause instanceof SocketException) {
LOGGER.warn("FS statistics update interrupted {}.", e.getMessage());
}
}
}
/**
* Get FsStat for a given filesystem.
*
* @return fsStat
*/
FsStat getFsStat() {
return _jdbc.queryForObject(
"SELECT iusedfiles AS usedFiles, iusedspace AS usedSpace from t_fstat",
(rs, rowNum) -> {
long usedFiles = rs.getBigDecimal("usedFiles")
.min(BigDecimal.valueOf(Long.MAX_VALUE))
.longValue();
BigDecimal usedSpaceB = rs.getBigDecimal("usedSpace");
long usedSpace = usedSpaceB == null ? 0L
: usedSpaceB.min(BigDecimal.valueOf(Long.MAX_VALUE)).longValue();
return new FsStat(JdbcFs.AVAILABLE_SPACE, JdbcFs.TOTAL_FILES, usedSpace,
usedFiles);
});
}
/**
* creates a new inode and an entry name in parent directory. Parent reference count and
* modification time is updated.
*
* @param parent
* @param name
* @param owner
* @param group
* @param mode
* @param type
* @return
*/
FsInode createFile(FsInode parent, String name, int owner, int group, int mode, int type) {
return createFileWithId(parent, FsInode.generateNewID(), name, owner, group, mode, type);
}
/**
* Creates a new entry with given inode is in parent directory. Parent reference count and
* modification time is updated.
*
* @param parent
* @param id
* @param name
* @param owner
* @param group
* @param mode
* @param type
* @return
*/
FsInode createFileWithId(FsInode parent, String id, String name, int owner, int group, int mode,
int type) {
return createInodeInParent(parent, name, id, owner, group, mode, type, 1, 0);
}
Long getInumber(String id) {
return _jdbc.query(
"SELECT inumber FROM t_inodes WHERE ipnfsid = ?",
ps -> ps.setString(1, id),
rs -> rs.next() ? rs.getLong("inumber") : null);
}
String getId(FsInode inode) {
return _jdbc.query(
"SELECT ipnfsid FROM t_inodes WHERE inumber=?",
ps -> ps.setLong(1, inode.ino()),
rs -> rs.next() ? rs.getString("ipnfsid") : null);
}
/**
* Returns {@link DirectoryStreamB} of ChimeraDirectoryEntry in the directory.
*
* @param dir
* @return stream of directory entries
*/
DirectoryStreamB<ChimeraDirectoryEntry> newDirectoryStream(FsInode dir) {
return new DirectoryStreamB<ChimeraDirectoryEntry>() {
final DirectoryStreamImpl stream = new DirectoryStreamImpl(dir, _jdbc);
@Override
public Iterator<ChimeraDirectoryEntry> iterator() {
return new Iterator<ChimeraDirectoryEntry>() {
private ChimeraDirectoryEntry current = innerNext();
@Override
public boolean hasNext() {
return current != null;
}
@Override
public ChimeraDirectoryEntry next() {
if (current == null) {
throw new NoSuchElementException("No more entries");
}
ChimeraDirectoryEntry entry = current;
current = innerNext();
return entry;
}
protected ChimeraDirectoryEntry innerNext() {
try {
ResultSet rs = stream.next();
if (rs == null) {
return null;
}
Stat stat = toStat(rs);
FsInode inode = new FsInode(dir.getFs(), rs.getLong("inumber"),
FsInodeType.INODE, 0, stat);
inode.setParent(dir);
return new ChimeraDirectoryEntry(rs.getString("iname"), inode, stat);
} catch (SQLException e) {
LOGGER.error("failed to fetch next entry: {}", e.getMessage());
return null;
}
}
};
}
@Override
public void close() throws IOException {
stream.close();
}
};
}
/**
* Removes the hard link {@code name} in {@code parent} to {@code inode}. If the last link is
* removed the object is deleted.
*
* @return true if removed, false if the link did not exist.
*/
boolean remove(FsInode parent, String name, FsInode inode) throws ChimeraFsException {
if (inode.type() != FsInodeType.INODE) {
throw new InvalidArgumentChimeraException("Not a file.");
}
if (name.equals("..") || name.equals(".")) {
throw new InvalidNameChimeraException("bad name: '" + name + '\'');
}
return inode.isDirectory() ? removeDir(parent, inode, name)
: removeFile(parent, inode, name);
}
private boolean removeDir(FsInode parent, FsInode inode, String name)
throws ChimeraFsException {
if (!removeEntryInParent(parent, name, inode)) {
return false;
}
// A directory contains two pseudo entries for '.' and '..'
decNlink(inode, 2);
// ensure that t_inodes and t_tags_inodes updated in the same order as
// in mkdir
decNlink(parent);
removeTag(inode);
if (!removeInodeIfUnlinked(inode)) {
throw new DirNotEmptyChimeraFsException("directory is not empty");
}
return true;
}
private boolean removeFile(FsInode parent, FsInode inode, String name)
throws ChimeraFsException {
if (!removeEntryInParent(parent, name, inode)) {
return false;
}
decNlink(inode);
removeInodeIfUnlinked(inode);
/* During bulk deletion of files in the same directory,
* updating the parent inode is often a contention point. The
* link count on the parent is updated last to reduce the time
* in which the directory inode is locked by the database.
*/
decNlink(parent);
return true;
}
void remove(FsInode inode) {
if (inode.isDirectory()) {
removeTag(inode);
}
/* Updating the inode effectively blocks anybody else from changing it and thus also from
* adding more links.
*/
_jdbc.update("UPDATE t_inodes SET inlink=0 WHERE inumber=?", inode.ino());
/* Remove all hard-links. */
List<Long> parents =
_jdbc.queryForList(
"SELECT iparent FROM t_dirs WHERE ichild=?",
Long.class, inode.ino());
for (Long parent : parents) {
decNlink(new FsInode(inode.getFs(), parent));
}
int n = _jdbc.update("DELETE FROM t_dirs WHERE ichild=?", inode.ino());
if (n != parents.size()) {
throw new JdbcUpdateAffectedIncorrectNumberOfRowsException(
"DELETE FROM t_dirs WHERE ichild=?", parents.size(), n);
}
removeInodeIfUnlinked(inode);
}
public Stat stat(String id) {
return _jdbc.query(
"SELECT * FROM t_inodes WHERE ipnfsid=?",
ps -> ps.setString(1, id),
rs -> rs.next() ? toStat(rs) : null);
}
public Stat stat(FsInode inode) {
return stat(inode, 0);
}
public Stat stat(FsInode inode, int level) {
if (level == 0) {
return _jdbc.query(
"SELECT * FROM t_inodes WHERE inumber=?",
ps -> ps.setLong(1, inode.ino()),
rs -> rs.next() ? toStat(rs) : null);
} else {
return _jdbc.query(
"SELECT * FROM t_level_" + level + " WHERE inumber=?",
ps -> ps.setLong(1, inode.ino()),
rs -> rs.next() ? toStatLevel(rs) : null);
}
}
private Stat toStat(ResultSet rs) throws SQLException {
Stat stat = new Stat();
stat.setIno(rs.getLong("inumber"));
stat.setId(rs.getString("ipnfsid"));
stat.setCrTime(rs.getTimestamp("icrtime").getTime());
stat.setGeneration(rs.getLong("igeneration"));
int rp = rs.getInt("iretention_policy");
if (!rs.wasNull()) {
stat.setRetentionPolicy(RetentionPolicy.getRetentionPolicy(rp));
}
int al = rs.getInt("iaccess_latency");
if (!rs.wasNull()) {
stat.setAccessLatency(AccessLatency.getAccessLatency(al));
}
stat.setSize(rs.getLong("isize"));
stat.setATime(rs.getTimestamp("iatime").getTime());
stat.setCTime(rs.getTimestamp("ictime").getTime());
stat.setMTime(rs.getTimestamp("imtime").getTime());
stat.setUid(rs.getInt("iuid"));
stat.setGid(rs.getInt("igid"));
stat.setMode(rs.getInt("imode") | rs.getInt("itype"));
stat.setNlink(rs.getInt("inlink"));
stat.setDev(17);
stat.setRdev(13);
stat.setState(FileState.valueOf(rs.getInt("iio")));
return stat;
}
private Stat toStatLevel(ResultSet rs) throws SQLException {
Stat stat = new Stat();
stat.setIno(rs.getLong("inumber"));
stat.setCrTime(rs.getTimestamp("imtime").getTime());
stat.setGeneration(0);
stat.setSize(rs.getLong("isize"));
stat.setATime(rs.getTimestamp("iatime").getTime());
stat.setCTime(rs.getTimestamp("ictime").getTime());
stat.setMTime(rs.getTimestamp("imtime").getTime());
stat.setUid(rs.getInt("iuid"));
stat.setGid(rs.getInt("igid"));
stat.setMode(rs.getInt("imode") | UnixPermission.S_IFREG);
stat.setNlink(rs.getInt("inlink"));
stat.setDev(17);
stat.setRdev(13);
stat.setState(FileState.STORED);
return stat;
}
/**
* create a new directory in parent with name. The reference count if parent directory as well
* modification time and reference count of newly created directory are updated.
*
* @param parent
* @param name
* @param owner
* @param group
* @param mode
* @return
* @throws ChimeraFsException
*/
FsInode mkdir(FsInode parent, String name, int owner, int group, int mode) {
return createInodeInParent(parent, name, FsInode.generateNewID(), owner, group, mode,
UnixPermission.S_IFDIR, 2, 512);
}
/**
* Move/rename inode from source in srcDir to dest in destDir. The reference counts of srcDir
* and destDir are updated.
*
* @param srcDir
* @param source
* @param destDir
* @param dest
* @param inode
* @return true if moved, false if source did not exist
*/
boolean rename(FsInode inode, FsInode srcDir, String source, FsInode destDir, String dest) {
String moveLink = "UPDATE t_dirs SET iparent=?, iname=? WHERE iparent=? AND iname=? AND ichild=?";
int n = _jdbc.update(moveLink,
ps -> {
ps.setLong(1, destDir.ino());
ps.setString(2, dest);
ps.setLong(3, srcDir.ino());
ps.setString(4, source);
ps.setLong(5, inode.ino());
});
if (n == 0) {
return false;
}
if (n > 1) {
throw new JdbcUpdateAffectedIncorrectNumberOfRowsException(moveLink, 1, n);
}
if (!srcDir.equals(destDir)) {
incNlink(destDir);
decNlink(srcDir);
} else {
incNlink(srcDir, 0);
}
return true;
}
/**
* return the inode of path in directory. In case of pnfs magic commands ( '.(' ) command
* specific inode is returned.
*
* @param parent
* @param name
* @return null if path is not found
*/
FsInode inodeOf(FsInode parent, String name, StatCacheOption stat) {
switch (name) {
case ".":
return parent.isDirectory() ? parent : null;
case "..":
if (!parent.isDirectory()) {
return null;
}
FsInode dir = parent.getParent();
return (dir == null) ? parent : dir;
default:
if (stat == STAT) {
return _jdbc.query(
"SELECT c.* FROM t_dirs d JOIN t_inodes c ON d.ichild = c.inumber " +
"WHERE d.iparent = ? AND d.iname = ?",
ps -> {
ps.setLong(1, parent.ino());
ps.setString(2, name);
},
rs -> rs.next() ? new FsInode(parent.getFs(), rs.getLong("inumber"),
FsInodeType.INODE, 0, toStat(rs)) : null);
} else {
return _jdbc.query("SELECT ichild FROM t_dirs WHERE iparent=? AND iname=?",
ps -> {
ps.setLong(1, parent.ino());
ps.setString(2, name);
},
rs -> rs.next() ? new FsInode(parent.getFs(), rs.getLong("ichild"))
: null);
}
}
}
/**
* return the path associated with inode, starting from root of the tree. in case of hard link,
* one of the possible paths is returned
*
* @param inode
* @param startFrom defined the "root"
* @return
*/
String inode2path(FsInode inode, FsInode startFrom) {
return inode2path(inode.ino(), startFrom.ino());
}
protected String inode2path(long elementId, long root) {
if (elementId == root) {
return "/";
}
try {
List<String> pList = new ArrayList<>();
do {
Map<String, Object> map = _jdbc.queryForMap(
"SELECT iparent, iname FROM t_dirs WHERE ichild=?", elementId);
pList.add((String) map.get("iname"));
elementId = (long) map.get("iparent");
} while (elementId != root);
return Lists.reverse(pList).stream().collect(Collectors.joining("/", "/", ""));
} catch (IncorrectResultSizeDataAccessException e) {
return "";
}
}
FsInode createInodeInParent(FsInode parent, String name, String id, int owner, int group,
int mode,
int type, int nlink, long size) {
Stat stat = createInode(id, type, owner, group, mode, nlink, size);
FsInode inode = new FsInode(parent.getFs(), stat.getIno(), FsInodeType.INODE, 0, stat);
createEntryInParent(parent, name, inode);
incNlink(parent);
return inode;
}
/**
* creates an entry in t_inodes table with initial values. for optimization, initial value of
* reference count may be defined. for newly created files , file size is zero. For directories
* 512.
*
* @param id
* @param uid
* @param gid
* @param mode
* @param nlink
*/
Stat createInode(String id, int type, int uid, int gid, int mode, int nlink, long size) {
Timestamp now = new Timestamp(System.currentTimeMillis());
KeyHolder keyHolder = new GeneratedKeyHolder();
_jdbc.update(
con -> {
PreparedStatement ps = con.prepareStatement(
"INSERT INTO t_inodes (ipnfsid,itype,imode,inlink,iuid,igid,isize,iio," +
"ictime,iatime,imtime,icrtime,igeneration) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",
Statement.RETURN_GENERATED_KEYS);
ps.setString(1, id);
ps.setInt(2, type);
ps.setInt(3, mode & UnixPermission.S_PERMS);
ps.setInt(4, nlink);
ps.setInt(5, uid);
ps.setInt(6, gid);
ps.setLong(7, size);
ps.setInt(8, FileState.CREATED.getValue());
ps.setTimestamp(9, now);
ps.setTimestamp(10, now);
ps.setTimestamp(11, now);
ps.setTimestamp(12, now);
ps.setLong(13, 0);
return ps;
}, keyHolder);
Stat stat = new Stat();
stat.setIno((Long) keyHolder.getKeys().get("inumber"));
stat.setId(id);
stat.setCrTime(now.getTime());
stat.setGeneration(0);
stat.setSize(size);
stat.setATime(now.getTime());
stat.setCTime(now.getTime());
stat.setMTime(now.getTime());
stat.setUid(uid);
stat.setGid(gid);
stat.setMode(mode & UnixPermission.S_PERMS | type);
stat.setNlink(nlink);
stat.setDev(17);
stat.setRdev(13);
stat.setState(FileState.CREATED);
return stat;
}
/**
* creates an entry in t_level_x table
*
* @param inode
* @param uid
* @param gid
* @param mode
* @param level
* @return
*/
FsInode createLevel(FsInode inode, int uid, int gid, int mode, int level) {
Timestamp now = new Timestamp(System.currentTimeMillis());
_jdbc.update("INSERT INTO t_level_" + level
+ "(inumber,imode,inlink,iuid,igid,isize,ictime,iatime,imtime,ifiledata) VALUES(?,?,1,?,?,0,?,?,?, NULL)",
ps -> {
ps.setLong(1, inode.ino());
ps.setInt(2, mode);
ps.setInt(3, uid);
ps.setInt(4, gid);
ps.setTimestamp(5, now);
ps.setTimestamp(6, now);
ps.setTimestamp(7, now);
});
Stat stat = new Stat();
stat.setCrTime(now.getTime());
stat.setGeneration(0);
stat.setSize(0);
stat.setATime(now.getTime());
stat.setCTime(now.getTime());
stat.setMTime(now.getTime());
stat.setUid(uid);
stat.setGid(gid);
stat.setMode(mode | UnixPermission.S_IFREG);
stat.setNlink(1);
stat.setIno(inode.ino());
stat.setDev(17);
stat.setRdev(13);
return new FsInode(inode.getFs(), inode.ino(), FsInodeType.INODE, level, stat);
}
boolean removeInodeIfUnlinked(FsInode inode) {
List<String> ids
= _jdbc.queryForList(
"SELECT ipnfsid FROM t_inodes WHERE inumber=? AND inlink=0 FOR UPDATE",
String.class, inode.ino());
if (ids.isEmpty()) {
return false;
}
if (ids.size() > 1) {
throw new IncorrectResultSizeDataAccessException(1, ids.size());
}
Timestamp now = new Timestamp(System.currentTimeMillis());
String id = ids.get(0);
_jdbc.update(
"INSERT INTO t_locationinfo_trash (ipnfsid,itype,ilocation,ipriority,ictime,iatime,istate) "
+
"(SELECT ?,l.itype,l.ilocation,l.ipriority,?,l.iatime,l.istate " +
"FROM t_locationinfo l WHERE l.inumber=?)",
ps -> {
ps.setString(1, id);
ps.setTimestamp(2, now);
ps.setLong(3, inode.ino());
});
_jdbc.update(
"INSERT INTO t_locationinfo_trash (ipnfsid,itype,ilocation,ipriority,ictime,iatime,istate) VALUES (?,2,'',0,?,?,1)",
ps -> {
ps.setString(1, id);
ps.setTimestamp(2, now);
ps.setTimestamp(3, now);
});
_jdbc.update("DELETE FROM t_inodes WHERE inumber=?", inode.ino());
return true;
}
boolean removeInodeLevel(FsInode inode, int level) {
return _jdbc.update("DELETE FROM t_level_" + level + " WHERE inumber=?", inode.ino()) > 0;
}
/**
* increase inode reference count by 1; the same as incNlink(dbConnection, inode, 1)
*
* @param inode
*/
void incNlink(FsInode inode) {
incNlink(inode, 1);
}
/**
* increases the reference count of the inode by delta
*
* @param inode
* @param delta
*/
void incNlink(FsInode inode, int delta) {
Timestamp now = new Timestamp(System.currentTimeMillis());
_jdbc.update(
"UPDATE t_inodes SET inlink=inlink +?,imtime=?,ictime=?,igeneration=igeneration+1 WHERE inumber=?",
ps -> {
ps.setInt(1, delta);
ps.setTimestamp(2, now);
ps.setTimestamp(3, now);
ps.setLong(4, inode.ino());
});
}
/**
* decreases inode reverence count by 1. the same as decNlink(dbConnection, inode, 1)
*
* @param inode
*/
void decNlink(FsInode inode) {
decNlink(inode, 1);
}
/**
* decreases inode reference count by delta
*
* @param inode
* @param delta
*/
void decNlink(FsInode inode, int delta) {
Timestamp now = new Timestamp(System.currentTimeMillis());
_jdbc.update(
"UPDATE t_inodes SET inlink=inlink -?,imtime=?,ictime=?,igeneration=igeneration+1 WHERE inumber=?",
ps -> {
ps.setInt(1, delta);
ps.setTimestamp(2, now);
ps.setTimestamp(3, now);
ps.setLong(4, inode.ino());
});
}
/**
* creates an entry name for the inode in the directory parent. parent's reference count is not
* increased
*
* @param parent
* @param name
* @param inode
*/
void createEntryInParent(FsInode parent, String name, FsInode inode) {
_jdbc.update("INSERT INTO t_dirs (iparent,ichild,iname) VALUES(?,?,?)",
ps -> {
ps.setLong(1, parent.ino());
ps.setLong(2, inode.ino());
ps.setString(3, name);
});
}
private boolean removeEntryInParent(FsInode parent, String name, FsInode child) {
return _jdbc.update("DELETE FROM t_dirs WHERE iname=? AND iparent=? AND ichild=?",
name, parent.ino(), child.ino()) > 0;
}
/**
* Find locations of inode within the namespace. For directories, a single value is returned,
* for files, multiple entries may be returned if the file has hard-links.
*
* @param inode
* @return
*/
Collection<Link> find(FsInode inode) {
FileSystemProvider provider = inode.getFs();
return _jdbc.query(
"SELECT iparent,iname FROM t_dirs WHERE ichild=?",
ps -> ps.setLong(1, inode.ino()),
(rs, n) -> new Link(new FsInode(provider, rs.getLong("iparent")),
rs.getString("iname")));
}
boolean setInodeAttributes(FsInode inode, int level, Stat stat) {
return _jdbc.update(con -> generateAttributeUpdateStatement(con, inode, stat, level)) > 0;
}
/**
* checks for IO flag of the inode. if IO enabled, regular read and write operations are
* allowed
*
* @param inode
* @return
*/
boolean isIoEnabled(FsInode inode) throws FileNotFoundChimeraFsException {
/* Since we access t_inodes anyway and the cost of transferring the entire row
* is negligible, we fill the stat cache as a side effect.
*/
Boolean enabled = _jdbc.query("SELECT * FROM t_inodes WHERE inumber=?",
ps -> ps.setLong(1, inode.ino()),
rs -> {
if (rs.next()) {
inode.setStatCache(toStat(rs));
return rs.getInt("iio") == 1;
} else {
return false;
}
});
if (enabled == null) {
throw FileNotFoundChimeraFsException.of(inode);
}
return enabled;
}
void setInodeIo(FsInode inode, boolean enable) {
_jdbc.update("UPDATE t_inodes SET iio=? WHERE inumber=?",
ps -> {
ps.setInt(1, enable ? 1 : 0);
ps.setLong(2, inode.ino());
});
}
int write(FsInode inode, int level, long beginIndex, byte[] data, int offset, int len) {
if (level == 0) {
Integer n = _jdbc.queryForObject("SELECT count(*) FROM t_inodes_data WHERE inumber=?",
Integer.class, inode.ino());
if (n != null && n > 0) {
// entry exist, update only
_jdbc.update("UPDATE t_inodes_data SET ifiledata=? WHERE inumber=?",
ps -> {
ps.setBinaryStream(1, new ByteArrayInputStream(data, offset, len), len);
ps.setLong(2, inode.ino());
});
} else {
// new entry
_jdbc.update("INSERT INTO t_inodes_data (inumber,ifiledata) VALUES (?,?)",
ps -> {
ps.setLong(1, inode.ino());
ps.setBinaryStream(2, new ByteArrayInputStream(data, offset, len), len);
});
}
// correct file size
_jdbc.update("UPDATE t_inodes SET isize=? WHERE inumber=?",
ps -> {
ps.setLong(1, len);
ps.setLong(2, inode.ino());
});
} else {
Integer n = _jdbc.queryForObject(
"SELECT count(*) FROM t_level_" + level + " WHERE inumber=?", Integer.class,
inode.ino());
if (n != null && n == 0) {
// if level does not exist, create it
Timestamp now = new Timestamp(System.currentTimeMillis());
_jdbc.update("INSERT INTO t_level_" + level
+ "(inumber,imode,inlink,iuid,igid,isize,ictime,iatime,imtime,ifiledata) VALUES(?,?,1,?,?,?,?,?,?,?)",
ps -> {
ps.setLong(1, inode.ino());
ps.setInt(2, 644);
ps.setInt(3, 0);
ps.setInt(4, 0);
ps.setLong(5, len);
ps.setTimestamp(6, now);
ps.setTimestamp(7, now);
ps.setTimestamp(8, now);
ps.setBinaryStream(9, new ByteArrayInputStream(data, offset, len), len);
});
} else {
_jdbc.update("UPDATE t_level_" + level + " SET ifiledata=?,isize=? WHERE inumber=?",
ps -> {
ps.setBinaryStream(1, new ByteArrayInputStream(data, offset, len), len);
ps.setLong(2, len);
ps.setLong(3, inode.ino());
});
}
}
return len;
}
int read(FsInode inode, int level, long beginIndex, byte[] data, int offset, int len)
throws FileNotFoundChimeraFsException {
ResultSetExtractor<Integer> extractor = rs -> {
try {
int count = 0;
if (rs.next()) {
InputStream in = rs.getBinaryStream(1);
if (in != null) {
in.skip(beginIndex);
int c;
while (((c = in.read()) != -1) && (count < len)) {
data[offset + count] = (byte) c;
++count;
}
}
}
return count;
} catch (IOException e) {
throw new LobRetrievalFailureException(e.getMessage(), e);
}
};
Integer ifiledata;
if (level == 0) {
ifiledata = _jdbc.query("SELECT ifiledata FROM t_inodes_data WHERE inumber=?",
extractor,
inode.ino());
} else {
ifiledata = _jdbc.query("SELECT ifiledata FROM t_level_" + level + " WHERE inumber=?",
extractor, inode.ino());
}
if (ifiledata == null) {
throw FileNotFoundChimeraFsException.ofLevel(inode, level);
}
return ifiledata;
}
/**
* returns a list of locations of defined type for the inode. only 'online' locations is
* returned
*
* @param inode
* @param type
* @return
*/
List<StorageLocatable> getInodeLocations(FsInode inode, int type) {
return _jdbc.query("SELECT ilocation,ipriority,ictime,iatime FROM t_locationinfo " +
"WHERE itype=? AND inumber=? AND istate=1 ORDER BY ipriority DESC",
ps -> {
ps.setInt(1, type);
ps.setLong(2, inode.ino());
},
(rs, rowNum) -> {
long ctime = rs.getTimestamp("ictime").getTime();
long atime = rs.getTimestamp("iatime").getTime();
int priority = rs.getInt("ipriority");
String location = rs.getString("ilocation");
return new StorageGenericLocation(type, priority, location, ctime, atime, true);
});
}
/**
* returns a list of locations for the inode. only 'online' locations is returned
*
* @param inode
* @return
*/
List<StorageLocatable> getInodeLocations(FsInode inode) {
return _jdbc.query("SELECT itype,ilocation,ipriority,ictime,iatime FROM t_locationinfo " +
"WHERE inumber=? AND istate=1 ORDER BY ipriority DESC",
ps -> {
ps.setLong(1, inode.ino());
},
(rs, rowNum) -> {
int type = rs.getInt("itype");
long ctime = rs.getTimestamp("ictime").getTime();
long atime = rs.getTimestamp("iatime").getTime();
int priority = rs.getInt("ipriority");
String location = rs.getString("ilocation");
return new StorageGenericLocation(type, priority, location, ctime, atime, true);
});
}
/**
* adds a new location for the inode
*
* @param inode
* @param type
* @param location
*/
void addInodeLocation(FsInode inode, int type, String location) {
Timestamp now = new Timestamp(System.currentTimeMillis());
_jdbc.update(
"INSERT INTO t_locationinfo (inumber,itype,ilocation,ipriority,ictime,iatime,istate) "
+
"(SELECT * FROM (VALUES (?,?,?,?,?,?,?)) v WHERE NOT EXISTS " +
"(SELECT 1 FROM t_locationinfo WHERE inumber=? AND itype=? AND ilocation=?))",
ps -> {