-
Notifications
You must be signed in to change notification settings - Fork 0
/
catalog.py
284 lines (263 loc) · 9.19 KB
/
catalog.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
import argparse
from datetime import datetime
from disk_catalogue import (
Filename,
Inode,
dealer,
Volume,
)
from fix_unicode import fix_bad_unicode
import re
import sys
import os
from sqlalchemy.orm.exc import NoResultFound
import sqlalchemy.sql.functions as func
class MountInfo(object):
device = None
uuid = None
path = None
volume = None
class CatalogueFS(object):
def __init__(self):
self.mount_point = []
self.parse_fail = 0
self.read_mounts()
self.sesh = dealer()
def ready(self):
if len(self.mount_point) == 0:
return False
else:
return True
def catalogue(self):
print "Catalogueing: {mp}".format(
mp=" ".join(self.mount_point),
)
for x in self.mount_point:
self.catalogue_one(x)
def read_mounts(self):
mounts = os.popen("mount", "r")
self.mi = {}
for mount in mounts:
# works with linux & macos x
m = re.match(
r"^(\S.*?) on (/.*?) (?:type (\S+) )?\((?:(\S+),)?",
mount
)
if m:
device, mount_point = m.group(1), m.group(2)
fstype = m.group(3) or m.group(4)
try:
device_num = os.stat(mount_point).st_dev
except OSError, e:
print "Warning: failed to stat {mp}: {e}".format(
mp=mount_point,
e=e,
)
next
if device_num not in self.mi:
mi = self.mi[device_num] = MountInfo()
mi.device = device
mi.path = mount_point
mi.fstype = fstype
else:
print(
"Warning: device {dev} mounted at {path} and "
"{path2}, hopefully that's OK".format(
dev=device,
path=mount_point,
path2=mi.path
)
)
else:
self.parse_fail += 1
def get_uuid(self, device, fstype):
needs_root = True
if re.match(r"ext\d+$", fstype):
cmd = ["dumpe2fs", device]
pattern = r"Filesystem UUID:\s+([a-f0-9\-]+)"
else:
raise Exception(
"Don't know how to collect UUID from {fstype} ({dev})"
.format(
fstype=fstype,
dev=device
)
)
if needs_root:
if os.getuid() == 0:
pass
elif os.geteuid() == 0:
os.setuid(0)
else:
cmd = ["sudo"] + cmd
pipe = os.popen(" ".join(cmd), "r") # FIXME - use subprocess
for l in pipe:
m = re.search(pattern, l)
if m:
return m.group(1)
raise Exception(
"Failed to get UUID of {dev} using {cmd}".format(
dev=device,
cmd=" ".join(cmd),
)
)
def mount_info(self, mount):
devnum = os.stat(mount).st_dev
mi = self.mi.get(devnum, None)
if mi is None or not mount.startswith(mi.path):
import pdb; pdb.set_trace()
raise Exception(
"my clever mount/device code failed, or you're expecting "
"too much of me. sorry."
)
if not hasattr(mi, "vfss"):
# note: this can take a _long_ time on big FAT filesystems
print "Checking size of {mount} ({dev}): ".format(
mount=mi.path,
dev=mi.device,
),
vfss = mi.vfss = os.statvfs(mount)
print "{files} files, {mb} MiB".format(
files=str("(?)" if vfss.f_files is None else vfss.f_files),
mb=str((vfss.f_bsize * (vfss.f_blocks - vfss.f_bfree)) >> 20),
)
# FIXME - call this earlier, to avoid sudo timeout
mi.uuid = self.get_uuid(mi.device, mi.fstype)
mi.volume = self.get_volume(mi)
return mi
def get_volume(self, mi):
try:
volume = self.sesh.query(Volume).filter(Volume.id == mi.uuid).one()
volume.last_mount = mi.path
except NoResultFound, e:
volume = Volume(id=mi.uuid, last_mount=mi.path)
self.sesh.add(volume)
self.sesh.commit()
return volume
def get_file(self, mi, stat):
inc = 0
try:
fobj = self.sesh.query(Inode).filter(
Inode.volume_id == mi.uuid,
Inode.inode_num == stat.st_ino,
).one()
# TODO: update fields & invalidate checksums if critica
# fields change
except NoResultFound, e:
fobj = Inode(
volume_id=mi.uuid,
inode_num=stat.st_ino,
size=stat.st_size,
unix_mode=stat.st_mode,
mtime=datetime.utcfromtimestamp(stat.st_mtime),
atime=datetime.utcfromtimestamp(stat.st_atime),
ctime=datetime.utcfromtimestamp(stat.st_ctime),
alloc=(stat.st_blocks * mi.vfss.f_bsize / 8),
rdev=stat.st_rdev,
uid=stat.st_uid,
gid=stat.st_gid,
nlink=stat.st_nlink,
)
self.sesh.add(fobj)
inc += 1
return fobj, inc
def get_filename(self, fobj, relname):
"""Returns a Filename object, given the Inode object and the filesystem
relative name."""
try:
relname_utf8 = relname.decode("utf8")
except UnicodeDecodeError:
latin1 = relname.decode("latin1")
relname_utf8 = fix_bad_unicode(latin1)
print u"Tidied {rn} to '{new}'".format(
rn=repr(relname),
new=relname_utf8,
)
relname_bin = None
if relname_utf8.encode("utf8") != relname:
relname_bin = relname
try:
fnobj = self.sesh.query(Filename).filter(
Filename.volume_id == fobj.volume_id,
Filename.inode_num == fobj.inode_num,
Filename.filename == relname_utf8,
).one()
#TODO: check other names & remove if necc.
#FIXME: multiple links to same file differing only by unicode!
except NoResultFound:
fnobj = Filename(
volume_id=fobj.volume_id,
inode_num=fobj.inode_num,
filename=relname_utf8,
filename_raw=relname_bin,
)
self.sesh.add(fnobj)
return fnobj
def catalogue_one(self, mount):
mi = self.mount_info(mount)
volume = self.get_volume(mi)
print "Checking database: ",
have_files = self.sesh.query(Inode).filter(
Inode.volume_id == volume.id
).count()
print "{0} file(s),".format(have_files),
try:
have_size = self.sesh.query(
func.sum(Inode.alloc),
).filter(
Inode.volume_id == volume.id
).group_by(Inode.volume_id).one()[0]
except NoResultFound:
have_size = 0
print "{0} MiB".format(int(have_size / (2 ** 20)))
scanned = new = 0
def show_progress():
print "found {x}/{tot} file(s), ~{m}/{totm} MiB".format(
x=(have_files + new),
tot=(mi.vfss.f_files - mi.vfss.f_ffree),
m=int(have_size / (2 ** 20)),
totm=int((
(mi.vfss.f_bsize * (mi.vfss.f_blocks - mi.vfss.f_bfree))
) / (2 ** 20)),
)
for dirpath, dirnames, filenames in os.walk(mount):
reldir = os.path.relpath(dirpath, mi.path)
for filename in filenames:
try:
stat = os.lstat(os.path.join(dirpath, filename))
except OSError, e:
print "Failed to stat {fn}: {e}".format(
fn=filename,
e=e,
)
next
fobj, inc = self.get_file(mi, stat)
relfile = (
os.path.join(reldir, filename) if reldir != "." else
filename
)
fnobj = self.get_filename(fobj, relfile)
scanned += 1
new += inc
if inc > 0:
have_size += mi.vfss.f_bsize * stat.st_blocks
if scanned % 1000 == 0:
show_progress()
self.sesh.commit()
show_progress()
self.sesh.commit()
parser = argparse.ArgumentParser(description="catalog a filesystem")
parser.add_argument(
'mount_point', metavar="PATH", type=str, nargs="+",
help="the mounted root of the filesystem to scan"
)
def main(argv):
cat = CatalogueFS()
parser.parse_args(argv[1:], cat)
if not cat.ready():
parser.print_help()
else:
cat.catalogue()
if __name__ == "__main__":
import sys
main(sys.argv)