Use API host when Planetflow host isn't defined.
[nodemanager.git] / vsys.py
1 # $Id$
2 # $URL$
3
4 """vsys configurator.  Maintains ACLs and script pipes inside vservers based on slice attributes."""
5
6 import logger
7 import os
8 import vserver
9 from sets import Set
10
11 VSYSCONF="/etc/vsys.conf"
12 VSYSBKEND="/vsys"
13
14 def start(options, config):
15     pass
16
17
18 def GetSlivers(data):
19     """For each sliver with the vsys attribute, set the script ACL, create the vsys directory in the slice, and restart vsys."""
20     # Touch ACLs and create dict of available
21     # XXX ...Sigh...  fromkeys will use an immutable 
22     #scripts = dict.fromkeys(touchAcls(),[])A
23     scripts = {}
24     for script in touchAcls(): scripts[script] = []
25     # slices that need to be written to the conf
26     slices = []
27     # Parse attributes and update dict of scripts
28     for sliver in data['slivers']:
29         for attribute in sliver['attributes']:
30             if attribute['name'] == 'vsys':
31                 # Check to see if sliver is running.  If not, continue
32                 try:
33                     if vserver.VServer(sliver['name']).is_running():
34                         if sliver['name'] not in slices:
35                             # add to conf
36                             slices.append(sliver['name'])
37                             # As the name implies, when we find an attribute, we
38                             createVsysDir(sliver['name'])
39                         # add it to our list of slivers that need vsys
40                         if attribute['value'] in scripts.keys():
41                             scripts[attribute['value']].append(sliver['name'])
42                 except:
43                     logger.log("vsys:  sliver %s not running yet.  Deferring." \
44                                % sliver['name'])
45                     pass
46  
47     # Write the conf
48     writeConf(slices, parseConf())
49     # Write out the ACLs
50     if writeAcls(scripts, parseAcls()): 
51         logger.log("vsys: restarting vsys service")
52         os.system("/etc/init.d/vsys restart")
53
54
55 def createVsysDir(sliver):
56     '''Create /vsys directory in slice.  Update vsys conf file.'''
57     try: os.makedirs("/vservers/%s/vsys" % sliver)
58     except OSError: pass
59
60
61 def touchAcls():
62     '''Creates empty acl files for scripts.  
63     To be ran in case of new scripts that appear in the backend.
64     Returns list of available scripts.'''
65     acls = []
66     scripts = []
67     for (root, dirs, files) in os.walk(VSYSBKEND):
68         for file in files:
69             if file.endswith(".acl"):
70                 acls.append(file.rstrip(".acl"))
71             else:
72                 scripts.append(file)
73     for new in (Set(scripts) - Set(acls)):
74         logger.log("vsys: Found new script %s.  Writing empty acl." % new)
75         f = open("%s/%s.acl" %(VSYSBKEND, new), "w")
76         f.write("\n")
77         f.close()
78     
79     return scripts
80
81
82 def writeAcls(currentscripts, oldscripts):
83     '''Creates .acl files for script in the script repo.'''
84     # Check each oldscript entry to see if we need to modify
85     _restartvsys = False
86     # for iteritems along dict(oldscripts), if length of values
87     # not the same as length of values of new scripts,
88     # and length of non intersection along new scripts is not 0,
89     # then dicts are different.
90     for (acl, oldslivers) in oldscripts.iteritems():
91         if (len(oldslivers) != len(currentscripts[acl])) or \
92         (len(Set(oldslivers) - Set(currentscripts[acl])) != 0):
93             _restartvsys = True
94             logger.log("vsys: Updating %s.acl w/ slices %s" % (acl, currentscripts[acl]))
95             f = open("%s/%s.acl" % (VSYSBKEND, acl), "w")
96             for slice in currentscripts[acl]: f.write("%s\n" % slice)
97             f.close()
98     # Trigger a restart
99     return _restartvsys
100
101
102 def parseAcls():
103     '''Parse the frontend script acls.  Return {script: [slices]} in conf.'''
104     # make a dict of what slices are in what acls.
105     scriptacls = {}
106     for (root, dirs, files) in os.walk(VSYSBKEND):
107         for file in files:
108             if file.endswith(".acl"):
109                 f = open(root+"/"+file,"r+")
110                 scriptname = file.rstrip(".acl")
111                 scriptacls[scriptname] = []
112                 for slice in f.readlines():  
113                     scriptacls[scriptname].append(slice.rstrip())
114                 f.close()
115     # return what scripts are configured for which slices.
116     return scriptacls
117
118
119 def writeConf(slivers, oldslivers):
120     # Check if this is needed
121     # The assumption here is if lengths are the same,
122     # and the non intersection of both arrays has length 0,
123     # then the arrays are identical.
124     if (len(slivers) != len(oldslivers)) or \
125     (len(Set(oldslivers) - Set(slivers)) != 0):
126         logger.log("vsys:  Updating %s" % VSYSCONF)
127         f = open(VSYSCONF,"w")
128         for sliver in slivers:
129             f.write("/vservers/%(name)s/vsys %(name)s\n" % {"name": sliver})
130         f.truncate()
131         f.close()
132
133
134 def parseConf():
135     '''Parse the vsys conf and return list of slices in conf.'''
136     scriptacls = {}
137     slicesinconf = []
138     try: 
139         f = open(VSYSCONF)
140         for line in f.readlines():
141             (path, slice) = line.split()
142             slicesinconf.append(slice)
143         f.close()
144     except: logger.log_exc()
145     return slicesinconf
146
147