Index: trunk/wmfmailadmin/mbcleanup.py |
— | — | @@ -0,0 +1,67 @@ |
| 2 | +#!/usr/bin/python |
| 3 | +""" |
| 4 | +WMF mailadmin mbcleanup |
| 5 | +Cleans up mailboxes for no longer existing accounts |
| 6 | +Written by Mark Bergsma <mark@wikimedia.org> |
| 7 | +""" |
| 8 | + |
| 9 | +import sys, os, sqlite3, time |
| 10 | + |
| 11 | +def get_accounts(dbname): |
| 12 | + """ |
| 13 | + Retrieves a list of current accounts |
| 14 | + """ |
| 15 | + |
| 16 | + conn = sqlite3.connect(dbname) |
| 17 | + cur = conn.cursor() |
| 18 | + cur.execute("SELECT domain, localpart FROM account") |
| 19 | + |
| 20 | + return set(cur.fetchall()) |
| 21 | + |
| 22 | +def get_mailboxes(mbroot): |
| 23 | + """ |
| 24 | + Retrieves a list of mail boxes |
| 25 | + """ |
| 26 | + |
| 27 | + # 2 levels: domain/localpart |
| 28 | + mailboxes = set() |
| 29 | + for domain in os.listdir(mbroot): |
| 30 | + domaindir = os.path.join(mbroot, domain) |
| 31 | + if os.path.isdir(domaindir): |
| 32 | + for localpart in os.listdir(domaindir): |
| 33 | + if os.path.isdir(os.path.join(domaindir, localpart)): |
| 34 | + mailboxes.add((unicode(domain), unicode(localpart))) |
| 35 | + |
| 36 | + return mailboxes |
| 37 | + |
| 38 | +def move_mailboxes(mbroot, mbbackuproot, mailboxes): |
| 39 | + """ |
| 40 | + Moves a set of mailboxes to a backup location |
| 41 | + """ |
| 42 | + |
| 43 | + for mb in mailboxes: |
| 44 | + date = time.strftime('%Y%m%d%H%M') |
| 45 | + oldpath = os.path.join(mbroot, mb[0], mb[1]) |
| 46 | + newpath = os.path.join(mbbackuproot, mb[0], mb[1]) + '.' + date |
| 47 | + print 'Moving', oldpath, '=>', newpath |
| 48 | + os.makedirs(newpath) |
| 49 | + os.rename(oldpath, newpath) |
| 50 | + |
| 51 | +def main(): |
| 52 | + """ |
| 53 | + Main function |
| 54 | + """ |
| 55 | + |
| 56 | + try: |
| 57 | + dbname, mbroot, mbbackuproot = sys.argv[1:4] |
| 58 | + except ValueError: |
| 59 | + print >> sys.stderr, "Usage:", sys.argv[0], "{user.db file} {mail boxes root path} {backup root path}" |
| 60 | + sys.exit(1) |
| 61 | + |
| 62 | + accounts, mailboxes = get_accounts(dbname), get_mailboxes(mbroot) |
| 63 | + |
| 64 | + # Move mailboxes without a corresponding account |
| 65 | + move_mailboxes(mbroot, mbbackuproot, mailboxes - accounts) |
| 66 | + |
| 67 | +if __name__ == '__main__': |
| 68 | + main() |
\ No newline at end of file |