-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathgmailfs.py
More file actions
executable file
·2455 lines (2202 loc) · 75.1 KB
/
gmailfs.py
File metadata and controls
executable file
·2455 lines (2202 loc) · 75.1 KB
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
#!/usr/bin/python
#@+leo-ver=4
#@+node:@file gmailfs.py
#@@first
#
# Copyright (C) 2004 Richard Jones <richard followed by funny at sign then jones then a dot then name>
# Copyright (C) 2010 Dave Hansen <dave@sr71.net>
#
# GmailFS - Gmail Filesystem Version 0.8.6
# This program can be distributed under the terms of the GNU GPL.
# See the file COPYING.
#
# TODO:
# Problem: a simple write ends up costing at least 3 server writes:
# 1. create directory entry
# 2. create inode
# 3. create first data block
# It would be greate if files below a certain size (say 64k or something)
# could be inlined and just stuck as an attachment inside the inode.
# It should not be too big or else it will end up making things like
# stat() or getattr() much more expensive
#
# It would also be nice to be able to defer actual inode creation for
# a time. dirents are going to be harder because we look them up more,
# but inodes should be easier to keep consistent
#
# Wrap all of the imap access functions up better so that we
# can catch the places to invalidate the caches better.
#
# Are there any other options for storing messages than in base64-encoded
# attachments? I'm worried about the waste of space and bandwidth. It
# appears to be about a 30% penalty.
#
# Be more selective about clearing the rsp cache. It is a bit heavy-handed
# right now. Do we really even need the rsp cache that much? We do our own
# caching for blocks and inodes. I guess it helps for constructing readdir
# responses.
#
# CATENATE
# See if anybody supports this: http://www.faqs.org/rfcs/rfc4469.html
# It would be wonderful when only writing parts of small files, or even
# when updating inodes.
#
# MUTIAPPEND
# With this: http://www.faqs.org/rfcs/rfc3502.html
# we could keep track of modified inodes and submit them in batches back
# to the server
#
# Could support "mount -o ro" or "mount -o remount,ro" with a read-only
# selection of the target mailbox
#
# There some tangling up here of inodes only having a single path
#
"""
GmailFS provides a filesystem using a Google Gmail account as its storage medium
"""
#@+others
#@+node:imports
import pprint
try:
import fuse
except ImportError, e:
print e
print "Are you sure you sure fuse is built into the kernel or loaded as a module?"
print "In a linux shell type \"lsmod | grep fuse\" to find out."
import imaplib
import email
import random
from email import encoders
from email.mime.multipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.mime.base import MIMEBase
import Queue
from fuse import Fuse
import os
from threading import Thread
import threading
import thread
from errno import * # NOTE: wildcard star imports considered evil, namespace pollution
from stat import *
from os.path import abspath, expanduser, isfile
fuse.fuse_python_api = (0, 2)
import thread
import quopri
import sys,traceback,re,string,time,tempfile,array,logging,logging.handlers
#@-node:imports
# Globals
DefaultUsername = 'defaultUser'
DefaultPassword = 'defaultPassword'
DefaultFsname = 'gmailfs'
References={}
IMAPBlockSize = 1024
# this isn't used yet
InlineInodeMax = 32 * 1024
# I tried 64MB for this, but the base64-encoded
# blocks end up about 90MB per message, which is
# a bit too much, and gmail rejects them.
DefaultBlockSize = 512 * 1024
# How many blocks can we cache at once
BlockCacheSize = 100
SystemConfigFile = "/etc/gmailfs/gmailfs.conf"
UserConfigFile = abspath(expanduser("~/.gmailfs.conf"))
GMAILFS_VERSION = '5'
PathStartDelim = '__a__'
PathEndDelim = '__b__'
FileStartDelim = '__c__'
FileEndDelim = '__d__'
LinkStartDelim = '__e__'
LinkEndDelim = '__f__'
MagicStartDelim = '__g__'
MagicEndDelim = '__h__'
InodeSubjectPrefix = 'inode_msg'
DirentSubjectPrefix = 'dirent_msg'
InodeTag ='i'
DevTag = 'd'
NumberLinksTag = 'k'
FsNameTag = 'q'
ModeTag = 'e'
UidTag = 'u'
GidTag = 'g'
SizeTag = 's'
AtimeTag = 'a'
MtimeTag = 'm'
CtimeTag = 'c'
BSizeTag = 'z'
VersionTag = 'v'
SymlinkTag = 'l'
RefInodeTag = 'r'
FileNameTag = 'n'
PathNameTag = 'p'
NumberQueryRetries = 1
regexObjectTrailingMB = re.compile(r'\s?MB$')
rsp_cache_hits = 0
rsp_cache_misses = 0
rsp_cache = {}
debug = 1
if debug >= 3:
imaplib.Debug = 3
#imaplib.Debug = 4
writeout_threads = {}
def abort():
global do_writeout
do_writeout = 0
#for t in writeout_threads:
# print "abort joining thread..."
# t.join()
# print "done joining thread"
exit(0)
sem_msg = {}
def semget(sem):
tries = 0
while not sem.acquire(0):
tries = tries + 1
time.sleep(1)
if tries % 60 == 0:
print("[%d] hung on lock for %d seconds (holder: %s)" % (thread.get_ident(), tries, sem_msg[sem]))
traceback.print_stack()
if tries >= 60:
print("[%d] unhung on lock after %d seconds (last holder: %s)" % (thread.get_ident(), tries, sem_msg[sem]))
sem_msg[sem] = "acquired semget"
return "OK"
def log_error(str):
log.debug(str)
log.error(str)
sys.stdout.write(str+"\n")
sys.stderr.write(str+"\n")
return
def log_debug(str):
log_debug3(str)
#str += "\n"
#sys.stderr.write(str)
return
def log_entry(str):
#print str
log_debug1(str)
def am_lead_thread():
if writeout_threads.has_key(thread.get_ident()):
return 0
return 1
def log_debug1(str):
log_info(str)
#str += "\n"
#sys.stderr.write(str)
return
def log_debug2(str):
if debug >= 2:
log_info(str)
return
def log_debug3(str):
if debug >= 3:
log_info(str)
return
def log_debug4(str):
if debug >= 4:
log_info(str)
return
def log_imap(str):
log_debug2("IMAP: " + str)
def log_imap2(str):
log_debug3("IMAP: " + str)
def log_info(s):
if not am_lead_thread():
return
log.info("[%.2f] %s" % (time.time(), s))
#print str
#str += "\n"
#sys.stderr.write(str)
return
def log_warning(str):
log.warning(str)
#str += "\n"
#sys.stderr.write(str)
return
def parse_path(path):
# should we check that there's always a / in the path??
ind = string.rindex(path, '/')
parent_dir = path[:ind]
filename = path[ind+1:]
if len(parent_dir) == 0:
parent_dir = "/"
return parent_dir, filename
def msg_add_payload(msg, payload, filename=None):
attach_part = MIMEBase('file', 'attach')
attach_part.set_payload(payload)
if filename != None:
attach_part.add_header('Content-Disposition', 'attachment; filename="%s"' % filename)
encoders.encode_base64(attach_part)
msg.attach(attach_part)
# This probably doesn't need to be handed the fsNameVar
# and the username
def mkmsg(subject, preamble, attach = ""):
global username
global fsNameVar
msg = MIMEMultipart()
log_debug2("mkmsg('%s', '%s', '%s', '%s',...)" % (username, fsNameVar, subject, preamble))
msg['Subject'] = subject
msg['To'] = username
msg['From'] = username
msg.preamble = preamble
if len(attach):
log_debug("attaching %d byte file contents" % len(attach))
msg_add_payload(msg, attach)
log_debug3("mkmsg() after subject: '%s'" % (msg['Subject']))
msg.uid = -1
return msg
imap_times = {}
imap_times_last_print = 0
def log_imap_time(cmd, start_time):
global imap_times
global imap_times_last_print
if not imap_times.has_key(cmd):
imap_times[cmd] = 0.0
now = time.time()
end_time = now
duration = end_time - start_time
imap_times[cmd] += duration
imap_times_print()
def imap_times_print(force=0):
global imap_times
global imap_times_last_print
now = time.time()
if force or (now - imap_times_last_print > 10):
for key, total in imap_times.items():
log_info("imap_times[%s]: %d" % (key, total))
imap_times_last_print = now
# this is intended to be a drop-in for imap.uid(), while
# also allowing the imap object to reconnect in the event
# of failures
#
# This hopefully just means that one of the connections
# died. This will try to reestablish it.
def imap_uid(imap, cmd, arg1, arg2 = None, arg3 = None, arg4 = None):
tries = 3
ret = None
while ret == None:
tries = tries - 1
try:
ret = imap.uid(cmd, arg1, arg2, arg3)
except Exception, e:
log_error("imap.uid() error: %s (tries left: %d)" % (str(e), tries))
imap.fs.kick_imap(imap)
if tries <= 0:
raise
except:
log_error("imap.uid() unknown error: (tries left: %d)" % (tries))
imap.fs.kick_imap(imap)
if tries <= 0:
raise
return ret
def __imap_append(imap, fsNameVar, flags, now, msg):
tries = 3
rsp = None
data = None
while rsp == None:
tries = tries - 1
try:
rsp, data = imap.append(fsNameVar, flags, now, msg)
log_debug2("__imap_append() try: %d rsp: '%s'" % (tries, rsp))
if rsp == "NO":
time.sleep(1)
rsp = None
continue
except RuntimeError, e:
log_error("imap.append() error: %s" % (str(e)))
imap.fs.kick_imap(imap)
if tries <= 0:
raise
return rsp, data
def imap_getquotaroot(imap, fsNameVar):
tries = 2
ret = None
while ret == None:
try:
ret = imap.getquotaroot(fsNameVar)
except RuntimeError, e:
log_error("imap.getquotaroot() error: %s" % (str(e)))
imap.fs.kick_imap(imap)
if tries <= 0:
raise
tries = tries - 1
return ret
# The IMAP uid commands can take multiple uids and return
# multiple results
#
# uid here is intended to be an array of uids, and this
# returns a dictionary of results indexed by uid
#
# does python have a ... operator like c preprocessor?
def uid_cmd(imap, cmd, uids, arg1, arg2 = None, arg3 = None):
semget(imap.lock)
ret = __uid_cmd(imap, cmd, uids, arg1, arg2, arg3)
imap.lock.release()
return ret
def __uid_cmd(imap, cmd, uids, arg1, arg2 = None, arg3 = None):
uids_str = string.join(uids, ",")
start = time.time()
log_info("__uid_cmd(%s,...) %d uids" % (cmd, len(uids)))
rsp, rsp_data = imap_uid(imap, cmd, uids_str, arg1, arg2, arg3)
log_imap_time(cmd, start);
log_info("__uid_cmd(%s, [%s]) ret: '%s'" % (cmd, uids_str, rsp))
if rsp != "OK":
log_error("IMAP uid cmd (%s, [%s]) error: %s" % (cmd, uids_str, rsp))
return None
ret = {}
uid_index = 0
for one_rsp_data in rsp_data:
log_debug3("rsp_data[%d]: ->%s<-" % (uid_index, one_rsp_data))
uid_index += 1
uid_index = 0
for rsp_nr in range(len(rsp_data)):
data = rsp_data[rsp_nr]
# I don't know if this is expected or
# not, but every other response is just
# a plain ')' char. Skip them
log_debug3("about to lookup uids[%d] data class: '%s'" % (uid_index, data.__class__.__name__))
if isinstance(data, tuple):
log_debug4("is tuple")
for tval in data:
log_debug4("tval: ->%s<- class: '%s'" % (str(tval), tval.__class__.__name__))
if isinstance(data, str):
continue
uid = uids[uid_index]
uid_index += 1
if data == None:
log_info("uid_cmd(%s) got strange result %s/%s" %
(cmd, rsp_nr, range(len(rsp_data))))
continue
desc = data[0]
result = data[1]
ret[uid] = result
return ret
def clear_rsp_cache():
global rsp_cache
log_debug2("clearing rsp cache with %d entries" % (len(rsp_cache)))
rsp_cache = {}
def imap_trash_uids(imap, raw_uids):
clear_rsp_cache()
checked_uids = []
# there have been a few cases where a -1
# creeps in here because we're trying to
# delete a message that has not yet been
# uploaded to the server. Filter those
# out.
for uid in raw_uids:
if int(uid) <= 0:
continue
checked_uids.append(uid)
if len(checked_uids) == 0:
return
log_imap("imap_trash_uids(%s)" % (string.join(checked_uids,",")))
ret = uid_cmd(imap, "STORE", checked_uids, '+FLAGS', '\\Deleted')
global msg_cache
for uid in checked_uids:
try:
del msg_cache[uid]
except:
foo = 1
# this is OK because the msg may neve have
# been cached
return ret
def imap_trash_msg(imap, msg):
if msg.uid <= 0:
return
imap_trash_uids(imap, [str(msg.uid)])
def imap_append(info, imap, msg):
#gmsg = libgmail.GmailComposedMessage(username, subject, body)
log_imap("imap_append(%s)" % (info))
log_debug2("append Subject: ->%s<-" % (msg['Subject']))
log_debug3("entire message: ->%s<-" % str(msg))
now = imaplib.Time2Internaldate(time.time())
clear_rsp_cache()
start = time.time()
semget(imap.lock)
rsp, data = __imap_append(imap, fsNameVar, "", now, str(msg))
imap.lock.release()
log_imap_time("APPEND", start);
log_imap2("append for '%s': rsp,data: '%s' '%s'" % (info, rsp, data))
if rsp != "OK":
return -1
# data looks like this: '['[APPENDUID 631933985 286] (Success)']'
msgid = int((data[0].split()[2]).replace("]",""))
msg.uid = msgid
log_debug("imap msgid: '%d'" % msgid)
return msgid
def _addLoggingHandlerHelper(handler):
""" Sets our default formatter on the log handler before adding it to
the log object. """
handler.setFormatter(defaultLogFormatter)
log.addHandler(handler)
def GmailConfig(fname):
import ConfigParser
cp = ConfigParser.ConfigParser()
global References
global DefaultUsername, DefaultPassword, DefaultFsname
global NumberQueryRetries
if cp.read(fname) == []:
log_warning("Unable to read configuration file: " + str(fname))
return
sections = cp.sections()
if "account" in sections:
options = cp.options("account")
if "username" in options:
DefaultUsername = cp.get("account", "username")
if "password" in options:
DefaultPassword = cp.get("account", "password")
else:
log.error("Unable to find GMail account configuration")
if "filesystem" in sections:
options = cp.options("filesystem")
if "fsname" in options:
DefaultFsname = cp.get("filesystem", "fsname")
else:
log_warning("Using default file system (Dangerous!)")
if "logs" in sections:
options = cp.options("logs")
if "level" in options:
level = cp.get("logs", "level")
log.setLevel(logging._levelNames[level])
if "logfile" in options:
logfile = abspath(expanduser(cp.get("logs", "logfile")))
log.removeHandler(defaultLoggingHandler)
_addLoggingHandlerHelper(logging.handlers.RotatingFileHandler(logfile, "a", 5242880, 3))
if "references" in sections:
options = cp.options("references")
for option in options:
record = cp.get("references",option)
fields = record.split(':')
if len(fields)<1 or len(fields)>3:
log_warning("Invalid reference '%s' in configuration." % (record))
continue
reference = reference_class(*fields)
References[option] = reference
do_writeout = 1
#@+node:mythread
class testthread(Thread):
def __init__ (self, fs, nr):
Thread.__init__(self)
self.fs = fs
self.nr = nr
def write_out_object(self):
try:
# block, and timeout after 1 second
object = self.fs.dirty_objects.get(1, 1)
except:
# effectively success if we timeout
return 0
# we do not want to sit here sleeping on objects
# so if we can not get the lock, move on to another
# object
got_lock = object.writeout_lock.acquire(0)
if not got_lock:
self.fs.dirty_objects.put(object)
return -1
sem_msg[object.writeout_lock] = "acquired write_out_object()"
reason = Dirtyable.dirty_reason(object)
start = time.time()
ret = write_out_nolock(object, "bdflushd")
end = time.time()
object.writeout_lock.release()
sem_msg[object.writeout_lock] += " released write_out_object()"
size = self.fs.dirty_objects.qsize()
# 0 means it got written out
# 1 means it was not dirty
took = end - start
msg = "[%d] (%2d sec), %%s %s because '%s' %d left" % (self.nr, took, object.to_str(), reason, size)
if ret == 0:
print(msg % ("wrote out"));
else:
print(msg % ("did not write"));
return 1
def run_writeout(self):
tries = 5
for try_nr in range(tries):
writeout_threads[thread.get_ident()] = "running"
ret = self.write_out_object()
#rint("writeout ret: '%s'" % (ret))
if ret == 0:
writeout_threads[thread.get_ident()] = "idle"
msg = "["
for t in range(self.fs.nr_imap_threads):
if t >= 1:
msg += " "
if writeout_threads[thread.get_ident()] == "idle":
msg += str(t)
else:
msg += " "
msg += "] idle\r"
sys.stderr.write(msg)
sys.stderr.flush()
if ret >= 0:
break
# this will happen when there are
# objects in the queue for which
# we can not get the lock. Do
# not spin, sleep instead
if try_nr < tries-1:
continue
time.sleep(1)
def run(self):
global do_writeout
writeout_threads[thread.get_ident()] = 1
log_debug1("mythread: started pid: %d" % (os.getpid()))
print "connected[%d]" % (self.nr)
log_debug1("connected[%d]" % (self.nr))
while do_writeout:
self.run_writeout()
print "thread[%d] done" % (self.nr)
#@-node:mythread
class reference_class:
def __init__(self,fsname,username=None,password=None):
self.fsname = fsname
if username is None or username == '':
self.username = DefaultUsername
else:
self.username = username
if password is None or password == '':
self.password = DefaultPassword
else:
self.password = password
# This ensures backwards compatability where
# old filesystems were stored with 7bit encodings
# but new ones are all quoted printable
def fixQuotedPrintable(body):
# first remove headers
newline = body.find("\r\n\r\n")
if newline >= 0:
body = body[newline:]
fixed = body
if re.search("Content-Transfer-Encoding: quoted",body):
fixed = quopri.decodestring(body)
# Map unicode
return fixed.replace('\u003d','=')
def psub(s):
if len(s) == 0:
return "";
return "SUBJECT \""+s+"\""
def _getMsguidsByQuery(about, imap, queries, or_query = 0):
or_str = ""
if or_query:
or_str = " OR"
fsq = (str(FsNameTag + "=" + MagicStartDelim + fsNameVar + MagicEndDelim))
# this is *REALLY* sensitive, at least on gmail
# Don't put any extra space in it anywhere, or you
# will be sorry
# 53:12.12 > MGLK6 SEARCH (SUBJECT "foo=bar" SUBJECT "bar=__fo__o__")
queryString = '(SUBJECT "%s"' % (fsq)
last_q = queries.pop()
for q in queries:
queryString += or_str + ' SUBJECT "%s"' % (q)
queryString += ' SUBJECT "%s")' % last_q
global rsp_cache
global rsp_cache_hits
global rsp_cache_misses
if rsp_cache_hits+rsp_cache_misses % 10 == 0:
log_info("rsp_cache (size: %d hits: %d misses: %d)" % (len(rsp_cache), rsp_cache_hits, rsp_cache_misses))
if rsp_cache.has_key(queryString):
rsp_cache_hits += 1
return rsp_cache[queryString]
else:
rsp_cache_misses += 1
# make sure mailbox is selected
log_imap("SEARCH query: '"+queryString+"'")
start = time.time()
semget(imap.lock)
try:
resp, msgids_list = imap_uid(imap, "SEARCH", None, queryString)
except:
log_error("IMAP error on SEARCH")
log_error("queryString: ->%s<-" % (queryString))
print "\nIMAP exception ", sys.exc_info()[0]
exit(-1)
finally:
imap.lock.release()
log_imap_time("SEARCH", start);
msgids = msgids_list[0].split(" ")
log_imap2("search resp: %s msgids len: %d" % (resp, len(msgids)))
ret = []
for msgid in msgids:
log_debug2("IMAP search result msg_uid: '%s'" % str(msgid))
if len(str(msgid)) > 0:
ret = msgids
break
if len(rsp_cache) > 1000:
clear_rsp_cache()
rsp_cache[queryString] = ret
return ret
def getSingleMsguidByQuery(imap, q):
msgids = _getMsguidsByQuery("fillme1", imap, q)
nr = len(msgids)
if nr != 1:
qstr = string.join(q, " ")
# this is debug because it's normal to have non-existent files
log_debug2("could not find messages for query: '%s' (found %d)" % (qstr, nr))
return -1;
log_debug2("getSingleMsguidByQuery('%s') ret: '%s' nr: %d" % (string.join(q," "), msgids[0], nr))
return int(msgids[0])
def __fetch_full_messages(imap, msgids):
if msgids == None or len(msgids) == 0:
return None
data = __uid_cmd(imap, "FETCH", msgids, '(RFC822)')
if data == None:
return None
log_imap("fetch(msgids=%s): got %d messages" % (string.join(msgids, ","), len(data)))
#log_debug2("fetch msgid: '%s' resp: '%s' data: %d bytes" % (str(msgid), resp, len(data)))
ret = {}
for uid, raw_str in data.items():
msg = email.message_from_string(raw_str)
msg.uid = uid
ret[str(uid)] = msg
return ret
msg_cache = {}
def fetch_full_messages(imap, msgids):
global msg_cache
ret = {}
fetch_msgids = []
# if we do not hold the lock over this entire
# sequence, we can race and fetch messages
# twice. It doesn't hurt, but it is inefficient
hits = 0
misses = 0
semget(imap.lock)
for msgid in msgids:
if msgid in msg_cache:
ret[msgid] = msg_cache[msgid]
hits += 1
else:
fetch_msgids.append(msgid)
misses += 1
log_debug3("fetch_full_messages() trying to fetch %d msgs" % (len(fetch_msgids)))
fetched = None
if len(fetch_msgids):
fetched = __fetch_full_messages(imap, fetch_msgids)
if fetched != None:
ret.update(fetched)
for uid, msg in fetched.items():
if msg_cache.has_key(uid):
print "uh oh, double-fetched uid: '%s'" % (uid)
log_debug2("filled msg_cache[%s]" % (str(uid)))
msg_cache[uid] = msg
if len(msg_cache) > 1000:
log_info("flushed message cache")
msg_cache = {}
imap.lock.release()
log_debug3("fetch_full_messages() hits: %d misses: %d" % (hits, misses))
return ret
def fetch_full_message(imap, msgid):
resp = fetch_full_messages(imap, [str(msgid)])
if resp == None:
return None
return resp[str(msgid)]
def getSingleMessageByQuery(desc, imap, q):
log_debug2("getSingleMessageByQuery(%s)" % (desc))
msgid = getSingleMsguidByQuery(imap, q)
if msgid == -1:
log_debug2("getSingleMessageByQuery() msgid: %s" % (str(msgid)))
return None
return fetch_full_message(imap, msgid)
def _pathSeparatorEncode(path):
s1 = re.sub("/","__fs__",path)
s2 = re.sub("-","__mi__",s1)
return re.sub("\+","__pl__",s2)
def _pathSeparatorDecode(path):
s1 = re.sub("__fs__","/",path)
s2 = re.sub("__mi__","-",s1)
return re.sub("__pl__","+",s2)
def _logException(msg):
traceback.print_exc(file=sys.stderr)
log.exception(msg)
log.info(msg)
# Maybe I'm retarded, but I couldn't get this to work
# with python inheritance. Oh, well.
def write_out_nolock(o, desc):
dirty_token = o.dirty()
if not dirty_token:
log_debug1("object is not dirty (%s), not writing out" % (str(dirty_token)))
print("object is not dirty (token: %s), not writing out" % (str(dirty_token)))
return 1
#clear_msg = "none"
clear_msg = o.clear_dirty(dirty_token)
if isinstance(o, GmailInode):
ret = o.i_write_out(desc)
elif isinstance(o, GmailDirent):
ret = o.d_write_out(desc)
elif isinstance(o, GmailBlock):
ret = o.b_write_out(desc)
else:
print("unknown dirty object:"+o.to_str())
if ret != 0:
o.mark_dirty("failed writeout");
log_debug1("write_out() finished '%s' (cleared '%s')" % (desc, clear_msg))
return ret
def write_out(o, desc):
# I was seeing situations where a network error (SSL in this case)
# was raised. It wasn't handled and the thread died while holding
# this lock. This should at least make it release the lock before
# dying.
try:
semget(o.writeout_lock)
sem_msg[o.writeout_lock] = "acquired write_out()"
ret = write_out_nolock(o, desc)
finally:
o.writeout_lock.release()
sem_msg[o.writeout_lock] += " released write_out() in exception"
return ret
class Dirtyable(object):
def __init__(self):
log_debug3("Dirtyable.__init__() '%s'" % (self))
self.dirty_reasons = Queue.Queue(1<<20)
self.dirty_mark = Queue.Queue(1)
self.writeout_lock = thread.allocate_lock()
sem_msg[self.writeout_lock] = "brand spankin new"
def dirty(self):
return self.dirty_reasons.qsize()
def dirty_reason(self):
return "%s (%d more reasons hidden)" % (self.__dirty, self.dirty())
def clear_dirty(self, nr):
msgs = []
log_info("clearing %d dirty reasons" % (nr))
for msg_nr in range(nr):
d_msg = self.dirty_reasons.get_nowait()
log_info("dirty reason[%d]: %s" % (msg_nr, d_msg))
msgs.append(d_msg)
msg = "(%s)" % string.join(msgs, ", ")
# there's a race to do this twice
orig_reason = self.dirty_mark.get_nowait();
log_info("cleared original dirty reason: '%s'" % (orig_reason))
return msg
def mark_dirty(self, desc):
self.__dirty = desc
self.dirty_reasons.put(desc)
try:
self.dirty_mark.put_nowait(desc);
self.fs.dirty_objects.put(self)
except:
log_debug("mark_dirty('%s') skipped global list, already dirty" % (self.to_str()))
log_debug1("mark_dirty('%s') because '%s' (%d reasons)" %
(self.to_str(), desc, self.dirty_reasons.qsize()))
def to_str(self):
return "Dirtyable.to_str()"
# end class Dirtyable
#@+node:class GmailDirent
class GmailDirent(Dirtyable):
def __init__(self, dirent_msg, inode, fs):
Dirtyable.__init__(self)
self.dirent_msg = dirent_msg
self.inode = inode
self.fs = fs
def to_str(self):
return "dirent('%s' ino=%s)" % (self.path(), str(self.inode.ino))
def path(self):
d = self.fs.parse_dirent_msg(self.dirent_msg)
file = _pathSeparatorDecode(d[FileNameTag])
path = _pathSeparatorDecode(d[PathNameTag])
log_debug3("decoded path: '%s' file: '%s'" % (path, file))
log_debug3("subject was: ->%s<-" % (self.dirent_msg['Subject']))
# path doesn't have a trailing slash, but the root
# does have one. Need to add one when we're dealing
# with the non-root dir
if path != "/":
path += "/"
return ("%s%s" % (path, file))
def d_write_out(self, desc):
log_info("writing out dirent '%s' for '%s' (dirty reason: '%s')"
% (self.path(), desc, Dirtyable.dirty_reason(self)))
imap = self.fs.get_imap()
msgid = imap_append("dirent writeout", imap, self.dirent_msg)
self.fs.put_imap(imap)
if msgid <= 0:
e = OSError("Could not send mesg in write_out() for: '%s'" % (path))
e.errno = ENOSPC
raise e
return 0
def unlink(self):
# FIXME, don't allow directory unlinking when children
log_debug1("unlink path:"+self.path()+" with nlinks:"+str(self.inode.i_nlink))
if self.inode.mode & S_IFDIR:
log_debug("unlinking dir")
# guaranteed not to return any messages to
# trash since there are two links for dirs
self.inode.dec_nlink()
else:
log_debug("unlinking file")
to_trash = self.inode.dec_nlink()
to_trash.append(str(self.dirent_msg.uid))
if len(to_trash):
imap_trash_uids(self.fs.imap, to_trash)
deleted = self.fs.dirent_cache.pop(self.path())
if deleted != None and deleted != self:
log_error("removed wrong dirent from cache")
#@-node:class GmailDirent
last_ino = -1
# using time for ino is a bad idea FIXME
#
# This helps, but there's still a theoretical
# problem if we mount(), write(), unmount()
# and mount again all within a second.
#
# Should we store this persistently in the
# root inode perhaps?
#
def get_ino():
global last_ino
ret = int(time.time()) << 16
if ret <= last_ino:
ret = last_ino + 1
return int(ret)
#@+node:class GmailInode
class GmailInode(Dirtyable):
"""
Class used to store gmailfs inode details
"""
#@+node:__init__
def __init__(self, inode_msg, fs):
Dirtyable.__init__(self)
# We can either make this inode from scratch, or
# use the inode_msg to fill in all these fields
self.fs = fs
self.xattr = {}
self.i_blocks = {}
self.inode_cache_lock = thread.allocate_lock()
# protected by fs.inode_cache_lock
self.pinned = 0
if inode_msg != None:
self.inode_msg = inode_msg
self.fill_from_inode_msg()
else:
self.version = 2
self.ino = get_ino()
self.mode = 0
self.dev = 0
self.i_nlink = 0
self.uid = 0
self.gid = 0
self.size = 0
self.atime = 0
self.mtime = 0
self.ctime = 0
self.symlink_tgt = ""
self.block_size = DefaultBlockSize
# there are a couple of spots that depend
# on having one of these around
self.inode_msg = self.mk_inode_msg()
#@-node:__init__
def to_str(self):
return "inode(%s)" % (str(self.ino))
def mark_dirty(self, desc):
log_debug2("inode mark_dirty(%s) size: '%s'" % (desc, str(self.size)))
self.mtime = int(time.time())
Dirtyable.mark_dirty(self, desc)
def i_write_out(self, desc):
log_debug2("i_write_out() self: '%s'" % (self))