-
Notifications
You must be signed in to change notification settings - Fork 5
/
metadata_db.go
1699 lines (1536 loc) · 45.3 KB
/
metadata_db.go
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
package dxfuse
import (
"context"
"database/sql"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"math"
"os"
"path/filepath"
"strings"
"time"
"github.com/dnanexus/dxda"
)
const (
nsDirType = 1
nsDataObjType = 2
)
type MetadataDb struct {
// an open handle to the database
db *sql.DB
dbFullPath string
// configuration information for accessing dnanexus servers
dxEnv dxda.DXEnvironment
// mapping from mounted directory to project ID
baseDir2ProjectId map[string]string
inodeCnt int64
options Options
// API to dx
ops *DxOps
}
func NewMetadataDb(
dbFullPath string,
dxEnv dxda.DXEnvironment,
options Options) (*MetadataDb, error) {
// create a connection to the database, that will be kept open
db, err := sql.Open("sqlite3", dbFullPath+"?mode=rwc")
if err != nil {
return nil, fmt.Errorf("Could not open the database %s", dbFullPath)
}
return &MetadataDb{
db: db,
dbFullPath: dbFullPath,
dxEnv: dxEnv,
baseDir2ProjectId: make(map[string]string),
inodeCnt: InodeRoot + 1,
options: options,
ops: NewDxOps(dxEnv, options),
}, nil
}
// write a log message, and add a header
func (mdb *MetadataDb) log(a string, args ...interface{}) {
LogMsg("metadata_db", a, args...)
}
func (mdb *MetadataDb) BeginTxn() (*sql.Tx, error) {
return mdb.db.Begin()
}
func (mdb *MetadataDb) opOpen() *OpHandle {
txn, err := mdb.db.Begin()
if err != nil {
log.Panic("Could not open transaction")
}
return &OpHandle{
httpClient: nil,
txn: txn,
err: nil,
}
}
func (mdb *MetadataDb) opClose(oph *OpHandle) {
if oph.err == nil {
err := oph.txn.Commit()
if err != nil {
log.Panic("could not commit transaction")
}
} else {
err := oph.txn.Rollback()
if err != nil {
log.Panic("could not rollback transaction")
}
}
}
// Construct a local sql database that holds metadata for
// a large number of dx:files. This metadata_db will be consulted
// when performing dxfuse operations. For example, a read-dir is
// translated into a query for all the files inside a directory.
// Split a path into a parent and child. For example:
//
// /A/B/C -> "/A/B", "C"
// / -> "", "/"
func splitPath(fullPath string) (parentDir string, basename string) {
if fullPath == "/" {
// The anomalous case.
// Dir/Base returns: "/", "/"
// but what we want is "", "/"
return "", "/"
} else {
return filepath.Dir(fullPath), filepath.Base(fullPath)
}
}
// Marshal a DNAx object tags to/from a string that
// is stored in a database table.
//
// We use base64 encoding to avoid problematic characters (`) when
// putting this string into SQL statements
type MTags struct {
Elements []string `json:"elements"`
}
func tagsMarshal(tags []string) string {
if tags == nil || len(tags) == 0 {
return ""
}
payload, err := json.Marshal(MTags{
Elements: tags,
})
if err != nil {
log.Panicf("failed to marshal tags (%v), %s", tags, err.Error())
return ""
}
return base64.StdEncoding.EncodeToString(payload)
}
func tagsUnmarshal(buf string) []string {
if buf == "" {
return nil
}
originalBytes, err := base64.StdEncoding.DecodeString(buf)
if err != nil {
log.Panicf("failed to base64 decode tags (%s), %s", buf, err.Error())
return nil
}
var coded MTags
err = json.Unmarshal(originalBytes, &coded)
if err != nil {
log.Panicf("failed to unmarshal tags (%s), %s", buf, err.Error())
return nil
}
return coded.Elements
}
// Marshal a DNAx object properties to/from a string that
// is stored in a database table. We use base64 encoding for the
// same reason as tags (see above).
type MProperties struct {
Elements map[string]string `json:"elements"`
}
func propertiesMarshal(props map[string]string) string {
if props == nil || len(props) == 0 {
return ""
}
payload, err := json.Marshal(MProperties{
Elements: props,
})
if err != nil {
log.Panicf("failed to marshal properties (%v), %s", props, err.Error())
return ""
}
return base64.StdEncoding.EncodeToString(payload)
}
func propertiesUnmarshal(buf string) map[string]string {
if buf == "" {
return make(map[string]string)
}
originalBytes, err := base64.StdEncoding.DecodeString(buf)
if err != nil {
log.Panicf("failed to base64 decode properties (%s), %s", buf, err.Error())
return nil
}
var coded MProperties
err = json.Unmarshal(originalBytes, &coded)
if err != nil {
log.Panicf("failed to unmarshal properties (%s), %s", string(originalBytes), err.Error())
return nil
}
return coded.Elements
}
func (mdb *MetadataDb) init2(txn *sql.Tx) error {
// Create table for files.
//
// mtime and ctime are measured in seconds since 1st of January 1970
// (Unix time).
sqlStmt := `
CREATE TABLE data_objects (
kind int,
id text,
proj_id text,
state text,
archival_state text,
inode bigint,
size bigint,
ctime bigint,
mtime bigint,
mode int,
tags text,
properties text,
dirty_data int,
dirty_metadata int,
PRIMARY KEY (inode)
);
`
if _, err := txn.Exec(sqlStmt); err != nil {
mdb.log(err.Error())
return fmt.Errorf("Could not create table data_objects")
}
sqlStmt = `
CREATE INDEX idx_dirty_data
ON data_objects (dirty_data);
`
if _, err := txn.Exec(sqlStmt); err != nil {
mdb.log(err.Error())
return fmt.Errorf("Could not create index on dirty_data column in table data_objects")
}
sqlStmt = `
CREATE INDEX idx_dirty_metadata
ON data_objects (dirty_metadata);
`
if _, err := txn.Exec(sqlStmt); err != nil {
mdb.log(err.Error())
return fmt.Errorf("Could not create index on dirty_metdata column in table data_objects")
}
// Create a table for the namespace relationships. All members of a directory
// are listed here under their parent. Linking all the tables are the inode numbers.
//
// For example, directory /A/B/C will be represented with record:
// dname="C"
// folder="/A/B"
//
sqlStmt = `
CREATE TABLE namespace (
parent text,
name text,
obj_type int,
inode bigint,
PRIMARY KEY (parent,name)
);
`
if _, err := txn.Exec(sqlStmt); err != nil {
mdb.log(err.Error())
return fmt.Errorf("Could not create table namespace")
}
sqlStmt = `
CREATE INDEX parent_index
ON namespace (parent);
`
if _, err := txn.Exec(sqlStmt); err != nil {
mdb.log(err.Error())
return fmt.Errorf("Could not create index parent_index on table namespace")
}
// we need to be able to get from the files/tables, back to the namespace
// with an inode ID. Due to hardlinks, a single inode can have multiple namespace entries.
sqlStmt = `
CREATE INDEX inode_rev_index
ON namespace (inode);
`
if _, err := txn.Exec(sqlStmt); err != nil {
mdb.log(err.Error())
return fmt.Errorf("Could not create index inode_rev_index on table namespace")
}
// A separate table for directories.
//
// If the inode is -1, then, the directory does not exist on the platform.
// If poplated is zero, we haven't described the directory yet.
sqlStmt = `
CREATE TABLE directories (
inode bigint,
proj_id text,
proj_folder text,
populated int,
ctime bigint,
mtime bigint,
mode int,
PRIMARY KEY (inode)
);
`
if _, err := txn.Exec(sqlStmt); err != nil {
mdb.log(err.Error())
return fmt.Errorf("Could not create table directories")
}
// Adding a root directory. The root directory does
// not belong to any one project. This allows mounting
// several projects from the same root. This is denoted
// by marking the project as the empty string.
nowSeconds := time.Now().Unix()
sqlStmt = fmt.Sprintf(`
INSERT INTO directories
VALUES ('%d', '%s', '%s', '%d', '%d', '%d', '%d');`,
InodeRoot, "", "", boolToInt(false),
nowSeconds, nowSeconds, dirReadOnlyMode)
if _, err := txn.Exec(sqlStmt); err != nil {
mdb.log(err.Error())
return fmt.Errorf("Could not create root directory")
}
// We want the root path to match the results of splitPath("/")
rParent, rBase := splitPath("/")
sqlStmt = fmt.Sprintf(`
INSERT INTO namespace
VALUES ('%s', '%s', '%d', '%d');`,
rParent, rBase, nsDirType, InodeRoot)
if _, err := txn.Exec(sqlStmt); err != nil {
mdb.log(err.Error())
return fmt.Errorf("Could not create root inode (%d)", InodeRoot)
}
return nil
}
// construct an initial empty database, representing an entire project.
func (mdb *MetadataDb) Init() error {
if mdb.options.Verbose {
mdb.log("Initializing metadata database\n")
}
txn, err := mdb.db.Begin()
if err != nil {
mdb.log(err.Error())
return fmt.Errorf("Could not open transaction")
}
if err := mdb.init2(txn); err != nil {
txn.Rollback()
mdb.log(err.Error())
return fmt.Errorf("Could not initialize database")
}
if err := txn.Commit(); err != nil {
txn.Rollback()
mdb.log(err.Error())
return fmt.Errorf("Error during commit")
}
if mdb.options.Verbose {
mdb.log("Completed creating files and directories tables\n")
}
return nil
}
func (mdb *MetadataDb) Shutdown() {
if err := mdb.db.Close(); err != nil {
mdb.log(err.Error())
mdb.log("Error closing the sqlite database %s", mdb.dbFullPath)
}
}
// Allocate an inode number. These must remain stable during the
// lifetime of the mount.
//
// Note: this call should perform while holding the mutex
func (mdb *MetadataDb) allocInodeNum() int64 {
mdb.inodeCnt += 1
return mdb.inodeCnt
}
// search for a file with a particular inode
//
// This is important for a file with multiple hard links. The
// parent directory determines which project the file belongs to.
// This is why we set the project-id instead of reading it from the file
func (mdb *MetadataDb) lookupDataObjectByInode(oph *OpHandle, oname string, inode int64) (File, bool, error) {
// point lookup in the files table
sqlStmt := fmt.Sprintf(`
SELECT kind,id,proj_id,state,archival_state,size,ctime,mtime,mode,tags,properties, dirty_data, dirty_metadata
FROM data_objects
WHERE inode = '%d';`,
inode)
rows, err := oph.txn.Query(sqlStmt)
if err != nil {
mdb.log("lookupDataObjectByInode %s inode=%d err=%s", oname, inode, err.Error())
return File{}, false, oph.RecordError(err)
}
var f File
f.Name = oname
f.Inode = inode
f.Uid = mdb.options.Uid
f.Gid = mdb.options.Gid
numRows := 0
for rows.Next() {
var ctime int64
var mtime int64
var props string
var tags string
var dirtyData int
var dirtyMetadata int
rows.Scan(&f.Kind, &f.Id, &f.ProjId, &f.State, &f.ArchivalState, &f.Size, &ctime, &mtime, &f.Mode,
&tags, &props, &dirtyData, &dirtyMetadata)
f.Ctime = SecondsToTime(ctime)
f.Mtime = SecondsToTime(mtime)
f.Tags = tagsUnmarshal(tags)
f.Properties = propertiesUnmarshal(props)
f.dirtyData = intToBool(dirtyData)
f.dirtyMetadata = intToBool(dirtyMetadata)
numRows++
}
rows.Close()
switch numRows {
case 0:
// no file found
return File{}, false, nil
case 1:
// found exactly one file
return f, true, nil
default:
log.Panicf("Found %d data-objects with inode=%d (name %s)", numRows, inode, oname)
return File{}, false, nil
}
}
func (mdb *MetadataDb) lookupDirByInode(oph *OpHandle, parent string, dname string, inode int64) (Dir, bool, error) {
var d Dir
d.Parent = parent
d.Dname = dname
d.FullPath = filepath.Clean(filepath.Join(parent, dname))
d.Inode = inode
d.Uid = mdb.options.Uid
d.Gid = mdb.options.Gid
// Extract information from the directories table
sqlStmt := fmt.Sprintf(`
SELECT proj_id, proj_folder, populated, ctime, mtime, mode
FROM directories
WHERE inode = '%d';`,
inode)
rows, err := oph.txn.Query(sqlStmt)
if err != nil {
mdb.log("lookupDirByInode inode=%d err=%s", inode, err.Error())
return Dir{}, false, oph.RecordError(err)
}
numRows := 0
for rows.Next() {
var populated int
var ctime int64
var mtime int64
var mode int
rows.Scan(&d.ProjId, &d.ProjFolder, &populated, &ctime, &mtime, &mode)
d.Ctime = SecondsToTime(ctime)
d.Mtime = SecondsToTime(mtime)
d.Mode = os.FileMode(mode)
d.Populated = intToBool(populated)
numRows++
}
rows.Close()
switch numRows {
case 0:
return Dir{}, false, nil
case 1:
// correct, just one version
default:
log.Panicf("found %d directory with inode=%d in the directories table",
numRows, inode)
}
// is this a faux directory? These don't exist on the platform,
// but are used for files with multiple versions.
if d.ProjFolder == "" {
d.faux = true
} else {
d.faux = false
}
return d, true, nil
}
// search for a file with a particular inode.
func (mdb *MetadataDb) LookupByInode(ctx context.Context, oph *OpHandle, inode int64) (Node, bool, error) {
// point lookup in the namespace table
sqlStmt := fmt.Sprintf(`
SELECT parent,name,obj_type
FROM namespace
WHERE inode = '%d';`,
inode)
rows, err := oph.txn.Query(sqlStmt)
if err != nil {
mdb.log("LookupByInode: error in query err=%s", err.Error())
return nil, false, oph.RecordError(err)
}
var parent string
var name string
var obj_type int
numRows := 0
for rows.Next() {
rows.Scan(&parent, &name, &obj_type)
numRows++
}
rows.Close()
if numRows == 0 {
return nil, false, nil
}
if numRows > 1 {
log.Panicf("More than one node with inode=%d", inode)
return nil, false, nil
}
switch obj_type {
case nsDirType:
return mdb.lookupDirByInode(oph, parent, name, inode)
case nsDataObjType:
// This is important for a file with multiple hard links. The
// parent directory determines which project the file belongs to.
return mdb.lookupDataObjectByInode(oph, name, inode)
default:
log.Panicf("Invalid type %d in namespace table", obj_type)
return nil, false, nil
}
}
func (mdb *MetadataDb) LookupDirByInode(ctx context.Context, oph *OpHandle, inode int64) (Dir, bool, error) {
node, ok, err := mdb.LookupByInode(ctx, oph, inode)
if !ok {
return Dir{}, false, err
}
if err != nil {
return Dir{}, false, err
}
dir := node.(Dir)
return dir, true, nil
}
// Find information on a directory by searching on its full name.
func (mdb *MetadataDb) lookupDirByName(oph *OpHandle, dirname string) (string, string, error) {
parentDir, basename := splitPath(dirname)
if mdb.options.Verbose {
mdb.log("lookupDirByName (%s)", dirname)
}
// Extract information for all the subdirectories
sqlStmt := fmt.Sprintf(`
SELECT dirs.proj_id, dirs.proj_folder, nm.obj_type
FROM directories as dirs
JOIN namespace as nm
ON dirs.inode = nm.inode
WHERE nm.parent = '%s' AND nm.name = '%s' ;`,
parentDir, basename)
rows, err := oph.txn.Query(sqlStmt)
if err != nil {
return "", "", err
}
numRows := 0
var projId string
var projFolder string
var objType int
for rows.Next() {
numRows++
rows.Scan(&projId, &projFolder, &objType)
if objType != nsDirType {
log.Panicf("looking for a directory, but found a file")
}
}
rows.Close()
if numRows != 1 {
log.Panicf("looking for directory %s, and found %d of them",
dirname, numRows)
}
return projId, projFolder, nil
}
// We wrote a new version of this file, creating a new file-id.
func (mdb *MetadataDb) UpdateInodeFileId(inode int64, fileId string) error {
oph := mdb.opOpen()
defer mdb.opClose(oph)
sqlStmt := fmt.Sprintf(`
UPDATE data_objects
SET id = '%s'
WHERE inode = '%d';`,
fileId, inode)
if _, err := oph.txn.Exec(sqlStmt); err != nil {
mdb.log("UpdateInodeFileId Error updating data_object table, %s",
err.Error())
return err
}
return nil
}
// The directory is in the database, read it in its entirety.
func (mdb *MetadataDb) directoryReadAllEntries(
oph *OpHandle,
dirFullName string) (map[string]File, map[string]Dir, error) {
if mdb.options.Verbose {
mdb.log("directoryReadAllEntries %s", dirFullName)
}
// Extract information for all the subdirectories
sqlStmt := `SELECT directories.inode, directories.proj_id, namespace.name, directories.ctime, directories.mtime, directories.mode
FROM directories
JOIN namespace
ON directories.inode = namespace.inode
WHERE namespace.parent = $1 AND namespace.obj_type = $2`
rows, err := oph.txn.Query(sqlStmt, dirFullName, nsDirType)
if err != nil {
mdb.log("Error in directories query, err=%s", err.Error())
return nil, nil, oph.RecordError(err)
}
subdirs := make(map[string]Dir)
for rows.Next() {
var inode int64
var dname string
var projId string
var ctime int64
var mtime int64
var mode int
rows.Scan(&inode, &projId, &dname, &ctime, &mtime, &mode)
subdirs[dname] = Dir{
Parent: dirFullName,
Dname: dname,
FullPath: filepath.Clean(filepath.Join(dirFullName, dname)),
Inode: inode,
Ctime: SecondsToTime(ctime),
Mtime: SecondsToTime(mtime),
Mode: os.FileMode(mode),
}
}
rows.Close()
// Extract information for all the files
sqlStmt = `SELECT dos.kind, dos.id, dos.proj_id, dos.state, dos.archival_state, dos.inode, dos.size, dos.ctime, dos.mtime, dos.mode, dos.tags, dos.properties, dos.dirty_data, dos.dirty_metadata, namespace.name
FROM data_objects as dos
JOIN namespace
ON dos.inode = namespace.inode
WHERE namespace.parent = $1 AND namespace.obj_type = $2`
rows, err = oph.txn.Query(sqlStmt, dirFullName, nsDataObjType)
if err != nil {
mdb.log("Error in data object query, err=%s", err.Error())
return nil, nil, oph.RecordError(err)
}
// Find the files in the directory
files := make(map[string]File)
for rows.Next() {
var f File
var ctime int64
var mtime int64
var tags string
var props string
var mode int
var dirtyData int
var dirtyMetadata int
rows.Scan(&f.Kind, &f.Id, &f.ProjId, &f.State, &f.ArchivalState, &f.Inode,
&f.Size, &ctime, &mtime, &mode,
&tags, &props, &dirtyData, &dirtyMetadata, &f.Name)
f.Ctime = SecondsToTime(ctime)
f.Mtime = SecondsToTime(mtime)
f.Tags = tagsUnmarshal(tags)
f.Properties = propertiesUnmarshal(props)
f.Mode = os.FileMode(mode)
f.dirtyData = intToBool(dirtyData)
f.dirtyMetadata = intToBool(dirtyMetadata)
files[f.Name] = f
}
//mdb.log(" #files=%d", len(files))
//mdb.log("]")
return files, subdirs, nil
}
// Create an entry representing one remote file. This has
// several use cases:
// 1. Create a singleton file from the manifest
// 2. Create a new file, and upload it later to the platform
// (the file-id will be the empty string "")
// 3. Discover a file in a directory, which may actually be a link to another file.
func (mdb *MetadataDb) createDataObject(
oph *OpHandle,
kind int,
dirtyData bool,
dirtyMetadata bool,
projId string,
state string,
archivalState string,
objId string,
size int64,
ctime int64,
mtime int64,
tags []string,
properties map[string]string,
mode os.FileMode,
parentDir string,
fname string) (int64, error) {
if mdb.options.VerboseLevel > 1 {
mdb.log("createDataObject %s:%s %s", projId, objId,
filepath.Clean(parentDir+"/"+fname))
}
// File doesn't exist, we need to choose a new inode number.
// Note: it is on stable storage, and will not change.
inode := mdb.allocInodeNum()
// marshal tags and properties
mTags := tagsMarshal(tags)
mProps := propertiesMarshal(properties)
// Create an entry for the file
sqlStmt := fmt.Sprintf(`
INSERT INTO data_objects
VALUES ('%d', '%s', '%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d', '%s', '%s', '%d', '%d');`,
kind, objId, projId, state, archivalState, inode, size, ctime, mtime, int(mode),
mTags, mProps,
boolToInt(dirtyData), boolToInt(dirtyMetadata))
if _, err := oph.txn.Exec(sqlStmt); err != nil {
mdb.log(err.Error())
mdb.log("Error inserting into data objects table")
mdb.log("sqlStmt = (%s)", sqlStmt)
return 0, oph.RecordError(err)
}
sqlStatementPrep, _ := oph.txn.Prepare(`INSERT INTO namespace
VALUES ($1, $2, $3, $4);`)
defer sqlStatementPrep.Close()
if _, err := sqlStatementPrep.Exec(parentDir, fname, nsDataObjType, inode); err != nil {
mdb.log("Error inserting %s/%s into the namespace table err=%s", parentDir, fname, err.Error())
return 0, oph.RecordError(err)
}
return inode, nil
}
// Create an empty directory, and return the inode
//
// Assumption: the directory does not already exist in the database.
func (mdb *MetadataDb) createEmptyDir(
oph *OpHandle,
projId string,
projFolder string,
ctime int64,
mtime int64,
mode os.FileMode,
dirPath string,
populated bool) (int64, error) {
if dirPath[0] != '/' {
log.Panicf("directory must start with a slash")
}
// choose unused inode number. It is on stable stoage, and will not change.
inode := mdb.allocInodeNum()
parentDir, basename := splitPath(dirPath)
if mdb.options.VerboseLevel > 1 {
mdb.log("createEmptyDir %s:%s %s populated=%t",
projId, projFolder, dirPath, populated)
}
sqlStmt := "INSERT INTO namespace VALUES ($1, $2, $3, $4)"
if _, err := oph.txn.Exec(sqlStmt, parentDir, basename, nsDirType, inode); err != nil {
mdb.log("createEmptyDir: error inserting into namespace table %s/%s, err=%s",
parentDir, basename, err.Error())
return 0, oph.RecordError(err)
}
// Create an entry for the subdirectory
mode = mode | os.ModeDir
sqlStmt = "INSERT INTO directories VALUES ($1, $2, $3, $4, $5, $6, $7)"
if _, err := oph.txn.Exec(sqlStmt, inode, projId, projFolder, boolToInt(populated), ctime, mtime, int(mode)); err != nil {
mdb.log(err.Error())
mdb.log("createEmptyDir: error inserting into directories table %d", inode)
return 0, oph.RecordError(err)
}
return inode, nil
}
// Assumption: the directory does not already exist in the database.
func (mdb *MetadataDb) CreateDir(
oph *OpHandle,
projId string,
projFolder string,
ctime int64,
mtime int64,
mode os.FileMode,
dirPath string) (int64, error) {
dnode, err := mdb.createEmptyDir(oph, projId, projFolder, ctime, mtime, mode, dirPath, false)
if err != nil {
mdb.log("error in create dir")
return 0, oph.RecordError(err)
}
return dnode, nil
}
// Remove a directory from the database
func (mdb *MetadataDb) RemoveEmptyDir(oph *OpHandle, inode int64) error {
sqlStmt := fmt.Sprintf(`
DELETE FROM directories
WHERE inode='%d';`,
inode)
if _, err := oph.txn.Exec(sqlStmt); err != nil {
mdb.log("RemoveEmptyDir(%d): error in directories table removal", inode)
return oph.RecordError(err)
}
sqlStmt = fmt.Sprintf(`
DELETE FROM namespace
WHERE inode='%d';`,
inode)
if _, err := oph.txn.Exec(sqlStmt); err != nil {
mdb.log("RemoveEmptyDir(%d): error in namespace table removal", inode)
return oph.RecordError(err)
}
return nil
}
// Update the directory populated flag to TRUE
func (mdb *MetadataDb) setDirectoryToPopulated(oph *OpHandle, dinode int64) error {
sqlStmt := fmt.Sprintf(`
UPDATE directories
SET populated = '1'
WHERE inode = '%d'`,
dinode)
if _, err := oph.txn.Exec(sqlStmt); err != nil {
mdb.log("Error set directory %d to populated", dinode)
return oph.RecordError(err)
}
return nil
}
func (mdb *MetadataDb) kindOfFile(o DxDescribeDataObject) int {
kind := 0
if strings.HasPrefix(o.Id, "file-") {
kind = FK_Regular
} else if strings.HasPrefix(o.Id, "applet-") {
kind = FK_Applet
} else if strings.HasPrefix(o.Id, "workflow-") {
kind = FK_Workflow
} else if strings.HasPrefix(o.Id, "record-") {
kind = FK_Record
} else if strings.HasPrefix(o.Id, "database-") {
kind = FK_Database
}
if kind == 0 {
mdb.log("A data object has an unknown prefix (%s)", o.Id)
kind = FK_Other
}
return kind
}
// Create a directory with: an i-node, files, and empty unpopulated subdirectories.
func (mdb *MetadataDb) populateDir(
oph *OpHandle,
dinode int64,
projId string,
projFolder string,
ctime int64,
mtime int64,
dirPath string,
dxObjs []DxDescribeDataObject,
subdirs []string) error {
if mdb.options.VerboseLevel > 1 {
var objNames []string
for _, oDesc := range dxObjs {
objNames = append(objNames, oDesc.Name)
}
mdb.log("populateDir(%s) data-objects=%v subdirs=%v", dirPath, objNames, subdirs)
}
// Create a database entry for each file
if mdb.options.VerboseLevel > 1 {
mdb.log("inserting files")
}
for _, o := range dxObjs {
kind := mdb.kindOfFile(o)
_, err := mdb.createDataObject(
oph,
kind,
false,
false,
o.ProjId,
o.State,
o.ArchivalState,
o.Id,
o.Size,
o.CtimeSeconds,
o.MtimeSeconds,
o.Tags,
o.Properties,
fileReadOnlyMode,
dirPath,
o.Name)
if err != nil {
return oph.RecordError(err)
}
}
// Create a database entry for each sub-directory
if mdb.options.VerboseLevel > 1 {
mdb.log("inserting subdirs")
}
for _, subDirName := range subdirs {
// Create an entry for the subdirectory.
// We haven't described it yet from DNAx, so the populate flag
// is false.
_, err := mdb.createEmptyDir(
oph,
projId, filepath.Clean(projFolder+"/"+subDirName),
ctime, mtime,
dirReadWriteMode,
filepath.Clean(dirPath+"/"+subDirName),
false)
if err != nil {
mdb.log("Error creating empty directory %s while populating directory %s",
filepath.Clean(projFolder+"/"+subDirName), dirPath)
return err
}
}
if mdb.options.VerboseLevel > 1 {
mdb.log("setting populated for directory %s", dirPath)
}
// Update the directory populated flag to TRUE
mdb.setDirectoryToPopulated(oph, dinode)
return nil
}
// Query DNAx about a folder, and encode all the information in the database.
//
// assumptions:
// 1. An empty directory has been created on the database.
// 1. The directory has not been queried yet.
// 2. The global lock is held
func (mdb *MetadataDb) directoryReadFromDNAx(
ctx context.Context,
oph *OpHandle,
dinode int64,
projId string,
projFolder string,
ctime int64,
mtime int64,
dirFullName string) error {
if mdb.options.Verbose {
mdb.log("directoryReadFromDNAx: describe folder %s:%s", projId, projFolder)
}
// describe all (closed) files
dxDir, err := DxDescribeFolder(ctx, oph.httpClient, &mdb.dxEnv, projId, projFolder)
if err != nil {
fmt.Printf(err.Error())
fmt.Printf("reading directory frmo DNAx error")
return err
}
if mdb.options.Verbose {
mdb.log("read dir from DNAx #data_objects=%d #subdirs=%d",
len(dxDir.dataObjects),
len(dxDir.subdirs))
}
// Approximate the ctime/mtime using the file timestamps.
// - The directory creation time is the minimum of all file creates.
// - The directory modification time is the maximum across all file modifications.
ctimeApprox := ctime
mtimeApprox := mtime
for _, f := range dxDir.dataObjects {
ctimeApprox = MinInt64(ctimeApprox, f.CtimeSeconds)
mtimeApprox = MaxInt64(mtimeApprox, f.MtimeSeconds)
}
// The DNAx storage system does not adhere to POSIX. Try
// to fix the elements in the directory, so they would comply. This