-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlind_fs_calls.py
1800 lines (1240 loc) · 51.4 KB
/
lind_fs_calls.py
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
"""
Author: Justin Cappos
Edited by : Khagay Nagdimov, CS-3224(Introduction to Operating Systems), Professor Katz
Below is an edited version of the file system developed by Justin Cappos. An important distinction between the two is that the implementation and use of metadata has been abandoned. However, because there are other files part of this file system, there will be a lind.metadata file that will exist in the file system. It however, as the file system is used, that file will not be used. The rest of the commentary belongs to Justin Cappos.
Module: File system calls for Lind. This is essentially POSIX written in
Repy V2.
Start Date: December 17th, 2011
My goal is to write a simple and relatively accurate implementation of POSIX
in Repy V2. This module contains most of the file system calls. A lind
client can execute those calls and they will be mapped into my Repy V2
code where I will more or less faithfully execute them. Since Repy V2
does not support permissions, directories, etc., I will fake these. To
do this I will create a metadata file / dictionary which contains
metadata of this sort. I will persist this metadata and re-read it upon
initialization.
Rather than do all of the struct packing, etc. here, I will do it in another
routine. The reason is that I want to be able to test this in Python / Repy
without unpacking / repacking.
"""
# At a conceptual level, the system works like this:
# 1) Files are written and managed by my program. The actual name on disk
# will not correspond in any way with the filename. The name on disk
# is chosen by my code and the filename only appears in the metadata.
# 2) A dictionary exists which stores file data. Since there may be
# multiple hard links to a file, the dictionary is keyed by "inode"
# instead of filename. The value of each entry is a dictionary that
# contains the file mode data, size, link count, owner, group, and other
# information.
# 3) "Inodes" are simply unique ids per file and have no other meaning.
# They are generated sequentially.
# 4) Every open file has an entry in the filedescriptortable. This
# is a dictionary that is keyed by fd, with the values consisting of
# a dictionary with the position, flags, a lock, and inode keys.
# The inode values are used to update / check the file size after writeat
# calls and for calls like fstat.
# 5) A file's data is mapped the filename FILEDATAPREFIX+str(inode)
# 6) Open file objects are kept in a separate table, the fileobjecttable that
# is keyed by inode. This makes it easier to support multiple open file
# descriptors that point to the same file.
#
# BUG: I created a table which allows one to look up an "inode"
# given a filename. It will break certain things in certain weird corner
# cases with dir symlinks, permissions, etc. However, it will make the
# code simpler and faster
# I called it: fastinodelookuptable = {}
#
# As with Linux, etc. there is a 'current directory' that calls which take a
# filename use as the first part of their path. All other filenames that
# do not begin with '/' start from here.
#
# Here is how some example calls work at a high level:
# unlink: removes filename -> inode map / decrements the link count. If
# the link count is zero, deletes the file.
# link: increments the link count and adds a new filename -> inode map.
# rename: updates the directory's filename -> inode map.
# getdents: returns data from the directory's filename -> inode map.
# mkdir / rmdir: creates a directory / removes a directory
# chdir: sets the current directory for other calls
# stat / access: provides metadata about a file / directory / etc.
# open: makes an entry in the file descriptor table for a file
# read / write: use the file descriptor to perform the action
# lseek: update the file descriptor table entry for position.
# I'm not overly concerned about efficiency right now. I'm more worried
# about correctness. As a result, I'm not going to optimize anything yet.
#
#
# A file's inode looks like this:
#
# {'size':1033, 'uid':1000, 'gid':1000, 'mode':33261, 'linkcount':2,
# 'atime':1323630836, 'ctime':1323630836, 'mtime':1323630836}
# See the stat command for more information about what these mean...
#
#
# A directory's inode looks very similar:
# {'size':1033, 'uid':1000, 'gid':1000, 'mode':16877,
# 'atime':1323630836, 'ctime':1323630836, 'mtime':1323630836,
# 'linkcount':4, # the number of dir entries...
# 'filename_to_inode_dict': {'foo':1234, '.':102, '..':10, 'bar':2245}
# See the stat command for more information about what these mean...
#
#
# Symbolic links, devices, etc. will be done later (if needed)
#
#
# These are all entries in the inode table. It is keyed by inode and maps
# to these entries. The root directory is always at position
# rootDirectoryInode
#
# Store all of the information about the file system in a dict...
# This should not be 0 because this is considered to be deleted
rootDirectoryInode = 26
FILEDATAPREFIX = 'linddata.'
filesystemmetadata = {}
SUPERBLOCKFILENAME = 'linddata.0'
SUPERBLOCK= {}
FREEBLOCKLISTAGGREGATE = []
# A lock that prevents inconsistencies in metadata
filesystemmetadatalock = createlock()
# fast lookup table... (Should I deprecate this?)
fastinodelookuptable = {}
# contains open file descriptor information... (keyed by fd)
filedescriptortable = {}
# contains file objects... (keyed by inode)
fileobjecttable = {}
# I use this so that I can assign to a global string (currentworkingdirectory)
# without using global, which is blocked by RepyV2
fs_calls_context = {}
# Where we currently are at...
fs_calls_context['currentworkingdirectory'] = '/'
SILENT=True
def warning(*msg):
if not SILENT:
for part in msg:
print part,
print
# This is raised to return an error...
class SyscallError(Exception):
"""A system call had an error"""
# This is raised if part of a call is not implemented
class UnimplementedError(Exception):
"""A call was called with arguments that are not fully implemented"""
def _load_lower_handle_stubs():
"""The lower file hadles need stubs in the descriptor talbe."""
filedescriptortable[0] = {'position':0, 'inode':0, 'lock':createlock(), 'flags':O_RDWRFLAGS, 'note':'this is a stub1'}
filedescriptortable[1] = {'position':0, 'inode':1, 'lock':createlock(), 'flags':O_RDWRFLAGS, 'note':'this is a stub2'}
filedescriptortable[2] = {'position':0, 'inode':2, 'lock':createlock(), 'flags':O_RDWRFLAGS, 'note':'this is a stub3'}
def load_fs(name=SUPERBLOCKFILENAME):
""" Help to correcly load a filesystem, if one exists, otherwise
make a new empty one. To do this, check if metadata exists.
If it doesnt, call _blank_fs_init, if it DOES exist call restore_metadata
This is the best entry point for programs loading the file subsystem.
"""
try:
# lets see if the metadata file is already here?
f = openfile(name, False)
except FileNotFoundError, e:
warning("Note: No filesystem found, building a fresh one.")
_blank_fs_init()
else:
f.close()
try:
#restore_metadata(name)
load_superblock()
except (IndexError, KeyError), e:
print "Error: Cannot reload filesystem. Run lind_fsck for details."
exitall(1)
_load_lower_handle_stubs()
# To have a simple, blank file system, simply run this block of code.
#
def _blank_fs_init():
# kill all left over data files...
# metadata will be killed on pe6rsist.
for filename in listfiles():
if filename.startswith(FILEDATAPREFIX):
removefile(filename)
# Now setup blank data structures
SUPERBLOCK = {
'dev_id' : 20,
'creationTime': 1376483073,
'mounted': 50,
'free_start': 1,
'free_end': 25,
'root': 26,
'max_blocks': 10000
}
# it makes no sense this wasn't done before...
persist_data(SUPERBLOCKFILENAME, SUPERBLOCK)
freetable = []
#initialize the free table, set the first 26 blocks to being used which is represented by 1. Set the rest of the blocks to being empty, which is represented by 0. Along the way, initialize the FREEBLOCKLISTAGGREGATE as well.
for i in range(0,27):
freetable.append(1)
FREEBLOCKLISTAGGREGATE.append(1)
for i in range(27,10000):
freetable.append(0)
FREEBLOCKLISTAGGREGATE.append(0)
persist_data(FILEDATAPREFIX + "1", freetable[27:400])
for i in range(2,26):
begin = (i-1) * 400
end = begin + 400
persist_data( "%s%d" % (FILEDATAPREFIX, i), freetable[begin:end])
root = {
'size': 0,
'uid':DEFAULT_UID,
'gid':DEFAULT_GID,
'mode':S_IFDIR | S_IRWXA,
'atime':1323630836,
'ctime':1323630836,
'mtime':1323630836,
'linkcount':2,
'filename_to_inode_dict':
{ 'd.': rootDirectoryInode, 'd..': rootDirectoryInode } }
persist_data("%s%d" % (FILEDATAPREFIX, 26), root)
# initialize the aggregate of the
# These are used to initialize and stop the system
def persist_data(filename, data):
datastring = serializedata(data)
# open the file (clobber) and write out the information...
try:
removefile(filename)
except FileNotFoundError:
pass
datafo = openfile(filename,True)
datafo.writeat(datastring,0)
datafo.close()
# These are used to initialize and stop the system
def persist_metadata(metadatafilename):
metadatastring = serializedata(filesystemmetadata)
# open the file (clobber) and write out the information...
try:
removefile(metadatafilename)
except FileNotFoundError:
pass
metadatafo = openfile(metadatafilename,True)
metadatafo.writeat(metadatastring,0)
metadatafo.close()
def load_superblock():
pass
def restore_metadata(metadatafilename):
# should only be called with a fresh system...
assert(filesystemmetadata == {})
# open the file and write out the information...
metadatafo = openfile(metadatafilename,True)
metadatastring = metadatafo.readat(None, 0)
metadatafo.close()
# get the dict we want
desiredmetadata = deserializedata(metadatastring)
# I need to put things in the dict, but it's not a global... so instead
# add them one at a time. It should be empty to start with
for item in desiredmetadata:
filesystemmetadata[item] = desiredmetadata[item]
# I need to rebuild the fastinodelookuptable. let's do this!
_rebuild_fastinodelookuptable()
# I'm already added.
def _recursive_rebuild_fastinodelookuptable_helper(path, inode):
# for each entry in my table...
for entryname,entryinode in filesystemmetadata['inodetable'][inode]['filename_to_inode_dict'].iteritems():
# if it's . or .. skip it.
if entryname == '.' or entryname == '..':
continue
# always add it...
entrypurepathname = _get_absolute_path(path+'/'+entryname)
fastinodelookuptable[entrypurepathname] = entryinode
# and recurse if a directory...
if 'filename_to_inode_dict' in filesystemmetadata['inodetable'][entryinode]:
_recursive_rebuild_fastinodelookuptable_helper(entrypurepathname,entryinode)
def _rebuild_fastinodelookuptable():
# first, empty it...
for item in fastinodelookuptable:
del fastinodelookuptable[item]
# now let's go through and add items...
# I need to add the root.
fastinodelookuptable['/'] = ROOTDIRECTORYINODE
# let's recursively do the rest...
_recursive_rebuild_fastinodelookuptable_helper('/', ROOTDIRECTORYINODE)
###################### Generic Helper functions #########################
# private helper function that converts a relative path or a path with things
# like foo/../bar to a normal path.
def _get_absolute_path(path):
# should raise an ENOENT error...
if path == '':
return path
# If it's a relative path, prepend the CWD...
if path[0] != '/':
path = fs_calls_context['currentworkingdirectory'] + '/' + path
# now I'll split on '/'. This gives a list like: ['','foo','bar'] for
# '/foo/bar'
pathlist = path.split('/')
# let's remove the leading ''
assert(pathlist[0] == '')
pathlist = pathlist[1:]
# Now, let's remove any '.' entries...
while True:
try:
pathlist.remove('.')
except ValueError:
break
# Also remove any '' entries...
while True:
try:
pathlist.remove('')
except ValueError:
break
# NOTE: This makes '/foo/bar/' -> '/foo/bar'. I think this is okay.
# for a '..' entry, remove the previous entry (if one exists). This will
# only work if we go left to right.
position = 0
while position < len(pathlist):
if pathlist[position] == '..':
# if there is a parent, remove it and this entry.
if position > 0:
del pathlist[position]
del pathlist[position-1]
# go back one position and continue...
position = position -1
continue
else:
# I'm at the beginning. Remove this, but no need to adjust position
del pathlist[position]
continue
else:
# it's a normal entry... move along...
position = position + 1
# now let's join the pathlist!
return '/'+'/'.join(pathlist)
# private helper function
def _get_absolute_parent_path(path):
return _get_absolute_path(path+'/..')
#################### The actual system calls... #############################
##### FSTATFS #####
# return statfs data for fstatfs and statfs
def _istatfs_helper(inode):
"""
http://linux.die.net/man/2/stat
"""
# I need to compute the amount of disk available / used
limits, usage, stoptimes = getresources()
# I'm going to fake large parts of this.
myfsdata = {}
myfsdata['f_type'] = 0xBEEFC0DE # unassigned. New to us...
myfsdata['f_bsize'] = 4096 # Match the repy V2 block size and as delineated in the homework
myfsdata['f_blocks'] = int(limits['diskused']) / 4096
myfsdata['f_bfree'] = (int(limits['diskused']-usage['diskused'])) / 4096
# same as above...
myfsdata['f_bavail'] = (int(limits['diskused']-usage['diskused'])) / 4096
# file nodes... I think this is infinite...
myfsdata['f_files'] = 1024*1024*1024
# free file nodes... I think this is also infinite...
myfsdata['f_files'] = 1024*1024*512
myfsdata['f_fsid'] = SUPERBLOCK['dev_id']
# we don't really have a limit, but let's say 254
myfsdata['f_namelen'] = 254
# same as blocksize...
myfsdata['f_frsize'] = 4096
# it's supposed to be 5 bytes... Let's try null characters...
#CM: should be 8 bytes by my calc
myfsdata['f_spare'] = '\x00'*8
return myfsdata
def fstatfs_syscall(fd):
"""
http://linux.die.net/man/2/fstatfs
"""
# is the file descriptor valid?
if fd not in filedescriptortable:
raise SyscallError("fstatfs_syscall","EBADF","The file descriptor is invalid.")
# if so, return the information...
return _istatfs_helper(filedescriptortable[fd]['inode'])
##### STATFS #####
def statfs_syscall(path):
"""
http://linux.die.net/man/2/statfs
"""
# ... but always release it...
truepath = _get_absolute_path(path)
# is the path there?
if truepath not in fastinodelookuptable:
raise SyscallError("statfs_syscall","ENOENT","The path does not exist.")
thisinode = fastinodelookuptable[truepath]
return _istatfs_helper(thisinode)
##### ACCESS #####
def access_syscall(path, amode):
"""
See: http://linux.die.net/man/2/access
"""
# ... but always release the lock
try:
# get the current path
truepath = _get_absolute_path(path)
# to find which directory the new directory will be placed in, split the path
parentDirec = truepath.split('/')[:-1]
# get the directory's name
dirname = truepath.split('/')[-1]
current_inode = rootDirectoryInode
current_data = restore_data("%s%d" % (FILEDATAPREFIX, current_inode) )
#find the inode(block) number of the directory where the new directory will be stored in
for component in parentDirec:
if component != "":
# This is the name of the directory in the file list
dir_entry = "d%s" % component
# Set the current inode to the component's inode
current_inode = current_data['filename_to_inode_dict'][dir_entry]
current_data = restore_data("%s%d" % (FILEDATAPREFIX, current_inode) )
# BUG: This should take the UID / GID of the requestor in mind
# if all of the bits for this file are set as requested, then indicate
# success (return 0)
if current_data['mode'] & amode == amode:
return 0
raise SyscallError("access_syscall","EACESS","The requested access is denied.")
finally:
pass
##### CHDIR #####
def chdir_syscall(path):
"""
http://linux.die.net/man/2/chdir
"""
# Note: I don't think I need locking here. I don't modify any state and
# only check the fs state once...
# get the actual name. Remove things like '../foo'
truepath = _get_absolute_path(path)
# If it doesn't exist...
if truepath not in fastinodelookuptable:
raise SyscallError("chdir_syscall","ENOENT","A directory in the path does not exist.")
# let's update and return success (0)
fs_calls_context['currentworkingdirectory'] = truepath
return 0
def restore_data(fileName):
filesData = open(fileName,"r")
filesDataString = filesData.read()
restoreData = deserializedata(filesDataString)
filesData.close()
return restoreData
#
##### MKDIR #####
def mkdir_syscall(path, mode):
# get the current path
truepath = _get_absolute_path(path)
# to find which directory the new directory will be placed in, split the path
parentDirec = truepath.split('/')[:-1]
# get the directory's name
dirname = truepath.split('/')[-1]
current_inode = rootDirectoryInode
current_data = restore_data("%s%d" % (FILEDATAPREFIX, current_inode) )
#find the inode(block) number of the directory where the new directory will be stored in
for component in parentDirec:
if component != "":
# This is the name of the directory in the file list
dir_entry = "d%s" % component
# Set the current inode to the component's inode
current_inode = current_data['filename_to_inode_dict'][dir_entry]
current_data = restore_data("%s%d" % (FILEDATAPREFIX, current_inode) )
for i in range(len(FREEBLOCKLISTAGGREGATE)):
if (FREEBLOCKLISTAGGREGATE[i] == 0):
theFreeBlock = i
break
newDirectory = {
'size' : 1033,
'uid' : 1000,
'gid' : 1000,
'mode' : 16877,
'atime' : 1323630836,
'ctime' : 1323630836,
'mtime' : 1323630836,
'linkcount' : 2,
'filename_to_inode_dict' : {'d.' : theFreeBlock, 'd..': current_inode, }
}
current_data['filename_to_inode_dict'][dirname] = theFreeBlock
persist_data("%s%d" % (FILEDATAPREFIX, theFreeBlock), newDirectory)
FREEBLOCKLISTAGGREGATE[theFreeBlock] = 1
persist_data("%s%d" % (FILEDATAPREFIX, current_inode), current_data)
return 0
##### RMDIR #####
def rmdir_syscall(path):
"""
http://linux.die.net/man/2/rmdir
"""
try:
truepath = _get_absolute_path(path)
# Is it the root?
if truepath == '/':
raise SyscallError("rmdir_syscall","EINVAL","Cannot remove the root directory.")
# is the path there?
if truepath not in fastinodelookuptable:
raise SyscallError("rmdir_syscall","EEXIST","The path does not exist.")
thisinode = fastinodelookuptable[truepath]
# okay, is it a directory?
checkFile = open("%s%d" % ('linddata.',thisinode))
checkFileSerialized = checkFile.read()
checkFileUnserialized = serialize_deserializedata(checkFileSerialized)
checkFile.close()
if not IS_DIR(filesystemmetadata['inodetable'][thisinode]['mode']):
raise SyscallError("rmdir_syscall","ENOTDIR","Path is not a directory.")
# Is it empty?
if filesystemmetadata['inodetable'][thisinode]['linkcount'] > 2:
raise SyscallError("rmdir_syscall","ENOTEMPTY","Path is not empty.")
# TODO: I should check permissions...
trueparentpath = _get_absolute_parent_path(path)
parentinode = fastinodelookuptable[trueparentpath]
# remove the entry from the inode table...
del filesystemmetadata['inodetable'][thisinode]
# We're ready to go! Let's clean up the file entry
dirname = truepath.split('/')[-1]
# remove the entry from the parent...
del filesystemmetadata['inodetable'][parentinode]['filename_to_inode_dict'][dirname]
# decrement the link count on the dir...
filesystemmetadata['inodetable'][parentinode]['linkcount'] -= 1
# finally, clean up the fastinodelookuptable and return success!!!
del fastinodelookuptable[truepath]
return 0
finally:
pass
##### LINK #####
def link_syscall(oldpath, newpath):
"""
http://linux.die.net/man/2/link
"""
try:
trueoldpath = _get_absolute_path(oldpath)
# is the old path there?
if trueoldpath not in fastinodelookuptable:
raise SyscallError("link_syscall","ENOENT","Old path does not exist.")
oldinode = fastinodelookuptable[trueoldpath]
# is oldpath a directory?
if IS_DIR(filesystemmetadata['inodetable'][oldinode]['mode']):
raise SyscallError("link_syscall","EPERM","Old path is a directory.")
# TODO: I should check permissions...
# okay, the old path info seems fine...
if newpath == '':
raise SyscallError("link_syscall","ENOENT","New path does not exist.")
truenewpath = _get_absolute_path(newpath)
# does the newpath exist? It shouldn't
if truenewpath in fastinodelookuptable:
raise SyscallError("link_syscall","EEXIST","newpath already exists.")
# okay, it doesn't exist (great!). Does it's parent exist and is it a
# dir?
truenewparentpath = _get_absolute_parent_path(newpath)
if truenewparentpath not in fastinodelookuptable:
raise SyscallError("link_syscall","ENOENT","New path does not exist.")
newparentinode = fastinodelookuptable[truenewparentpath]
if not IS_DIR(filesystemmetadata['inodetable'][newparentinode]['mode']):
raise SyscallError("link_syscall","ENOTDIR","New path's parent is not a directory.")
# TODO: I should check permissions...
# okay, great!!! We're ready to go! Let's make the file...
newfilename = truenewpath.split('/')[-1]
# first, make the directory entry...
filesystemmetadata['inodetable'][newparentinode]['filename_to_inode_dict'][newfilename] = oldinode
# increment the link count on the dir...
filesystemmetadata['inodetable'][newparentinode]['linkcount'] += 1
# ... and the file itself
filesystemmetadata['inodetable'][oldinode]['linkcount'] += 1
# finally, update the fastinodelookuptable and return success!!!
fastinodelookuptable[truenewpath] = oldinode
return 0
finally:
pass
##### UNLINK #####
def unlink_syscall(path):
"""
http://linux.die.net/man/2/unlink
"""
try:
truepath = _get_absolute_path(path)
# is the path there?
if truepath not in fastinodelookuptable:
raise SyscallError("unlink_syscall","ENOENT","The path does not exist.")
thisinode = fastinodelookuptable[truepath]
# okay, is it a directory?
if IS_DIR(filesystemmetadata['inodetable'][thisinode]['mode']):
raise SyscallError("unlink_syscall","EISDIR","Path is a directory.")
# TODO: I should check permissions...
trueparentpath = _get_absolute_parent_path(path)
parentinode = fastinodelookuptable[trueparentpath]
# We're ready to go! Let's clean up the file entry
dirname = truepath.split('/')[-1]
# remove the entry from the parent...
del filesystemmetadata['inodetable'][parentinode]['filename_to_inode_dict'][dirname]
# decrement the link count on the dir...
filesystemmetadata['inodetable'][parentinode]['linkcount'] -= 1
# clean up the fastinodelookuptable
del fastinodelookuptable[truepath]
# decrement the link count...
filesystemmetadata['inodetable'][thisinode]['linkcount'] -= 1
# If zero, remove the entry from the inode table
if filesystemmetadata['inodetable'][thisinode]['linkcount'] == 0:
del filesystemmetadata['inodetable'][thisinode]
# TODO: I also would remove the file. However, I need to do special
# things if it's open, like wait until it is closed to remove it.
return 0
finally:
pass
##### STAT #####
def stat_syscall(path):
"""
http://linux.die.net/man/2/stat
"""
try:
truepath = _get_absolute_path(path)
# is the path there?
if truepath not in fastinodelookuptable:
raise SyscallError("stat_syscall","ENOENT","The path does not exist.")
thisinode = fastinodelookuptable[truepath]
# If its a character file, call the helper function.
if IS_CHR(filesystemmetadata['inodetable'][thisinode]['mode']):
return _istat_helper_chr_file(thisinode)
return _istat_helper(thisinode)
finally:
pass
##### FSTAT #####
def fstat_syscall(fd):
"""
http://linux.die.net/man/2/fstat
"""
# TODO: I don't handle socket objects. I should return something like:
# st_mode=49590, st_ino=0, st_dev=0L, st_nlink=0, st_uid=501, st_gid=20,
# st_size=0, st_atime=0, st_mtime=0, st_ctime=0
# is the file descriptor valid?
if fd not in filedescriptortable:
raise SyscallError("fstat_syscall","EBADF","The file descriptor is invalid.")
# if so, return the information...
inode = filedescriptortable[fd]['inode']
if fd in [0,1,2] or \
(filedescriptortable[fd] is filedescriptortable[0] or \
filedescriptortable[fd] is filedescriptortable[1] or \
filedescriptortable[fd] is filedescriptortable[2] \
):
filesData = open("%s%d" % ('linddata.',inode),'r')
filesDataSerialized = filesData.read()
filesDataUnserialized = serialize_deserializedata(filesDataSerialized)
filesData.close()
return (filesDataUnserialized['dev_id'], # st_dev
inode, # inode
49590, #mode
1, # links
DEFAULT_UID, # uid
DEFAULT_GID, #gid
0, # st_rdev ignored(?)
0, # size
0, # st_blksize ignored(?)
0, # st_blocks ignored(?)
0,
0, # atime ns
0,
0, # mtime ns
0,
0, # ctime ns
)
if IS_CHR(filesystemmetadata['inodetable'][inode]['mode']):
return _istat_helper_chr_file(inode)
return _istat_helper(inode)
# private helper routine that returns stat data given an inode
def _istat_helper(inode):
ret = (filesystemmetadata['dev_id'], # st_dev
inode, # inode
filesystemmetadata['inodetable'][inode]['mode'],
filesystemmetadata['inodetable'][inode]['linkcount'],
filesystemmetadata['inodetable'][inode]['uid'],
filesystemmetadata['inodetable'][inode]['gid'],
0, # st_rdev ignored(?)
filesystemmetadata['inodetable'][inode]['size'],
0, # st_blksize ignored(?)
0, # st_blocks ignored(?)
filesystemmetadata['inodetable'][inode]['atime'],
0, # atime ns
filesystemmetadata['inodetable'][inode]['mtime'],
0, # mtime ns
filesystemmetadata['inodetable'][inode]['ctime'],
0, # ctime ns
)
return ret
##### OPEN #####
# get the next free file descriptor
def get_next_fd():
# let's get the next available fd number. The standard says we need to
# return the lowest open fd number.
for fd in range(STARTINGFD, MAX_FD):
if not fd in filedescriptortable:
return fd
raise SyscallError("open_syscall","EMFILE","The maximum number of files are open.")
def open_syscall(path,flags,mode):
"""
http://linux.die.net/man/2/open
"""
if path == '':
raise SyscallError("open_syscall","ENOENT","The file does not exist.")
truepath = _get_absolute_path(path)
# to find which directory the new directory will be placed in, split the path
parentDirec = truepath.split('/')[:-1]
# get the directory's name
filename = truepath.split('/')[-1]
current_inode = rootDirectoryInode
current_data = restore_data("%s%d" % (FILEDATAPREFIX, current_inode) )
#find the inode(block) number of the directory where the new directory will be stored in
for component in parentDirec:
if component != "":
# This is the name of the directory in the file list
dir_entry = "d%s" % component
# Set the current inode to the component's inode
current_inode = current_data['filename_to_inode_dict'][dir_entry]
current_data = restore_data("%s%d" % (FILEDATAPREFIX, current_inode))
check = 0
# is the file missing?
for i in current_data['filename_to_inode_dict']: # test to see if this file already exists
if(i == filename):
check += 1
if (check == 0): # execute only if the file does not exist
# did they use O_CREAT?
#if not O_CREAT & flags:
#raise SyscallError("open_syscall","ENOENT","The file does not exist.")
if not IS_DIR(current_data['mode']): #is the parent's directory REALLY a directory?
raise SyscallError("open_syscall","ENOTDIR","Path's parent is not a directory.")
inodeNumber = 0
for i in FREEBLOCKLISTAGGREGATE: #find a free inode
if(i ==0):
inodeNumber = i
break
#if inodeNumber == 0: #check that the free block list is not full
# raise SysCallError("open_syscall","ENOSPC","There is no space left on the disk.")