Update web code to for SQLAlchemy 0.4
[invirt/packages/invirt-web.git] / code / cache_acls.py
1 #!/usr/bin/python
2 from invirt.database import *
3 from invirt.config import structs as config
4 import sys
5 import getafsgroups
6 import subprocess
7
8 def expandLocker(name):
9     groups = getafsgroups.getLockerAcl(name)
10     cell = getafsgroups.getCell(name)
11     ans = set()
12     for group in groups:
13         if ':' in group:
14             ans.update(getafsgroups.getAfsGroupMembers(group, cell))
15         else:
16             ans.add(group)
17     return ans
18
19 def isUser(name):
20     p = subprocess.Popen(['vos', 'examine', 'user.'+name],
21                          stdout=subprocess.PIPE, stderr=subprocess.PIPE)
22     if p.wait():
23         return False
24     return True
25     
26
27 def expandName(name):
28     if ':' not in name:
29         if isUser(name):
30             return [name]
31         return []
32     try:
33         return getafsgroups.getAfsGroupMembers(name, config.authz[0].cell)
34     except getafsgroups.AfsProcessError:
35         return []
36
37 def accessList(m):
38     people = set()
39     people.update(expandLocker(m.owner))
40     people.update(expandName(m.administrator))
41     return people
42
43 def refreshMachine(m):
44     people = accessList(m)
45     old_people = set(a.user for a in m.acl)
46     for removed in old_people - people:
47         ma = [x for x in m.acl if x.user == removed][0]
48         session.delete(ma)
49     for p in people - old_people:
50         ma = MachineAccess(user=p)
51         m.acl.append(ma)
52         session.save_or_update(ma)
53     
54 def refreshCache():
55     session.begin()
56
57     try:
58         machines = Machine.select()
59         for m in machines:
60             refreshMachine(m)
61         session.flush()
62             
63         # Atomically execute our changes
64         session.commit()
65     except:
66         # Failed! Rollback all the changes.
67         session.rollback()
68         raise
69
70 if __name__ == '__main__':
71     connect()
72     refreshCache()