99b390ae4a5a9af92288747d0adc3be12fdf8955
[sfa.git] / sfa / rspecs / aggregates / rspec_manager_max.py
1 #!/usr/bin/python
2
3 from sfa.util.rspec import RSpec
4 import sys
5 import pdb
6 from sfa.util.namespace import get_authority, hrn_to_pl_slicename, 
7 from sfa.util.rspec import *
8 from sfa.util.specdict import *
9 from sfa.util.faults import *
10 from sfa.util.storage import *
11 from sfa.util.policy import Policy
12 from sfa.server.aggregate import Aggregates
13 from sfa.server.registry import Registries
14 from sfa.util.faults import *
15
16 import xml.dom.minidom
17
18 SFA_MAX_CONF_FILE = '/etc/sfa/max_allocations'
19 SFA_MAX_DEFAULT_RSPEC = '/etc/sfa/max_physical.xml'
20 SFA_MAX_CANNED_RSPEC = '/etc/sfa/max_physical_canned.xml'
21
22 topology = {}
23
24 class SfaOutOfResource(SfaFault):
25     def __init__(self, interface):
26         faultString = "Interface " + interface + " not available"
27         SfaFault.__init__(self, 100, faultString, '')
28
29 class SfaNoPairRSpec(SfaFault):
30     def __init__(self, interface, interface2):
31         faultString = "Interface " + interface + " should be paired with " + interface2
32         SfaFault.__init__(self, 100, faultString, '')
33
34 # Returns a mapping from interfaces to the nodes they lie on and their peer interfaces
35 # i -> node,i_peer
36
37 def get_interface_map():
38     r = RSpec()
39     r.parseFile(SFA_MAX_DEFAULT_RSPEC)
40     rspec = r.toDict()
41     capacity = rspec['rspec']['capacity']
42     netspec = capacity[0]['netspec'][0]
43     linkdefs = {}
44     for n in netspec['nodespec']:
45         ifspecs = n['ifspec']
46         nodename = n['node']
47         for i in ifspecs:
48             ifname = i['name']
49             linkid = i['linkid']
50
51             if (linkdefs.has_key(linkid)):
52                 linkdefs[linkid].extend([(nodename,ifname)])
53             else:
54                 linkdefs[linkid]=[(nodename,ifname)]
55     
56     # topology maps interface x interface -> link,node1,node2
57     topology={}
58
59     for k in linkdefs.keys():
60         (n1,i1) = linkdefs[k][0]
61         (n2,i2) = linkdefs[k][1]
62
63         topology[i1] = (n1, i2)
64         topology[i2] = (n2, i1)
65         
66
67     return topology    
68
69     
70 def allocations_to_rspec(allocations):
71     rspec = xml.dom.minidom.parse(SFA_MAX_DEFAULT_RSPEC)
72     req = rspec.firstChild.appendChild(rspec.createElement("request"))
73     for (iname,ip) in allocations:
74         ifspec = req.appendChild(rspec.createElement("ifspec"))
75         ifspec.setAttribute("name","tns:"+iname)
76         ifspec.setAttribute("ip",ip)
77
78     return rspec.toxml()
79         
80     
81 def if_endpoints(ifs):
82     nodes=[]
83     for l in ifs:
84         nodes.extend(topology[l][0])
85     return nodes
86
87 def lock_state_file():
88     # Noop for demo
89     return True
90
91 def unlock_state_file():
92     return True
93     # Noop for demo
94
95 def read_alloc_dict():
96     alloc_dict={}
97     rows = open(SFA_MAX_CONF_FILE).read().split('\n')
98     for r in rows:
99         columns = r.split(' ')
100         if (len(columns)==2):
101             hrn = columns[0]
102             allocs = columns[1].split(',')
103             ipallocs = map(lambda alloc:alloc.split('/'), allocs)
104             alloc_dict[hrn]=ipallocs
105     return alloc_dict
106
107 def commit_alloc_dict(d):
108     f = open(SFA_MAX_CONF_FILE, 'w')
109     for hrn in d.keys():
110         columns = d[hrn]
111         ipcolumns = map(lambda x:"/".join(x), columns)
112         row = hrn+' '+','.join(ipcolumns)+'\n'
113         f.write(row)
114     f.close()
115
116 def collapse_alloc_dict(d):
117     ret = []
118     for k in d.keys():
119         ret.extend(d[k])
120     return ret
121
122
123 def alloc_links(api, hrn, links_to_add, links_to_drop):
124     slicename=hrn_to_pl_slicename(hrn)
125     for (iface,ip) in links_to_add:
126         node = topology[iface][0][0]
127         try:
128             api.plshell.AddSliceTag(api.plauth, slicename, "ip_addresses", ip, node)
129             api.plshell.AddSliceTag(api.plauth, slicename, "vsys", "getvlan", node)
130         except Exception: 
131             # Probably a duplicate tag. XXX July 21
132             pass
133     return True
134
135 def alloc_nodes(api,hrn, requested_ifs):
136     requested_nodes = if_endpoints(requested_ifs)
137     create_slice_max_aggregate(api, hrn, requested_nodes)
138
139 # Taken from slices.py
140
141 def create_slice_max_aggregate(api, hrn, nodes):
142     # Get the slice record from SFA
143     global topology
144     topology = get_interface_map()
145     slice = {}
146     registries = Registries(api)
147     registry = registries[api.hrn]
148     credential = api.getCredential()
149     records = registry.resolve(credential, hrn)
150     for record in records:
151         if record.get_type() in ['slice']:
152             slice = record.as_dict()
153     if not slice:
154         raise RecordNotFound(hrn)   
155
156     # Make sure slice exists at plc, if it doesnt add it
157     slicename = hrn_to_pl_slicename(hrn)
158     slices = api.plshell.GetSlices(api.plauth, [slicename], ['node_ids'])
159     if not slices:
160         parts = slicename.split("_")
161         login_base = parts[0]
162         # if site doesnt exist add it
163         sites = api.plshell.GetSites(api.plauth, [login_base])
164         if not sites:
165             authority = get_authority(hrn)
166             site_records = registry.resolve(credential, authority)
167             site_record = {}
168             if not site_records:
169                 raise RecordNotFound(authority)
170             site_record = site_records[0]
171             site = site_record.as_dict()
172                 
173             # add the site
174             site.pop('site_id')
175             site_id = api.plshell.AddSite(api.plauth, site)
176         else:
177             site = sites[0]
178             
179         slice_fields = {}
180         slice_keys = ['name', 'url', 'description']
181         for key in slice_keys:
182             if key in slice and slice[key]:
183                 slice_fields[key] = slice[key]  
184         api.plshell.AddSlice(api.plauth, slice_fields)
185         slice = slice_fields
186         slice['node_ids'] = 0
187     else:
188         slice = slices[0]    
189
190     # get the list of valid slice users from the registry and make 
191     # they are added to the slice 
192     researchers = record.get('researcher', [])
193     for researcher in researchers:
194         person_record = {}
195         person_records = registry.resolve(credential, researcher)
196         for record in person_records:
197             if record.get_type() in ['user']:
198                 person_record = record
199         if not person_record:
200             pass
201         person_dict = person_record.as_dict()
202         persons = api.plshell.GetPersons(api.plauth, [person_dict['email']],
203                                          ['person_id', 'key_ids'])
204
205         # Create the person record 
206         if not persons:
207             person_id=api.plshell.AddPerson(api.plauth, person_dict)
208
209             # The line below enables the user account on the remote aggregate
210             # soon after it is created.
211             # without this the user key is not transfered to the slice
212             # (as GetSlivers returns key of only enabled users),
213             # which prevents the user from login to the slice.
214             # We may do additional checks before enabling the user.
215
216             api.plshell.UpdatePerson(api.plauth, person_id, {'enabled' : True})
217             key_ids = []
218         else:
219             key_ids = persons[0]['key_ids']
220
221         api.plshell.AddPersonToSlice(api.plauth, person_dict['email'],
222                                      slicename)        
223
224         # Get this users local keys
225         keylist = api.plshell.GetKeys(api.plauth, key_ids, ['key'])
226         keys = [key['key'] for key in keylist]
227
228         # add keys that arent already there 
229         for personkey in person_dict['keys']:
230             if personkey not in keys:
231                 key = {'key_type': 'ssh', 'key': personkey}
232                 api.plshell.AddPersonKey(api.plauth, person_dict['email'], key)
233
234     # find out where this slice is currently running
235     nodelist = api.plshell.GetNodes(api.plauth, slice['node_ids'],
236                                     ['hostname'])
237     hostnames = [node['hostname'] for node in nodelist]
238
239     # remove nodes not in rspec
240     deleted_nodes = list(set(hostnames).difference(nodes))
241     # add nodes from rspec
242     added_nodes = list(set(nodes).difference(hostnames))
243
244     api.plshell.AddSliceToNodes(api.plauth, slicename, added_nodes) 
245     api.plshell.DeleteSliceFromNodes(api.plauth, slicename, deleted_nodes)
246
247     return 1
248
249
250 def get_rspec(api, hrn):
251     # Eg. config line:
252     # plc.princeton.sapan vlan23,vlan45
253
254     allocations = read_alloc_dict()
255     if (hrn and allocations.has_key(hrn)):
256             ret_rspec = allocations_to_rspec(allocations[hrn])
257     else:
258         ret_rspec = open(SFA_MAX_CANNED_RSPEC).read()
259
260     return (ret_rspec)
261
262
263 def create_slice(api, hrn, rspec_xml):
264     global topology
265     topology = get_interface_map()
266
267     # Check if everything in rspec is either allocated by hrn
268     # or not allocated at all.
269     r = RSpec()
270     r.parseString(rspec_xml)
271     rspec = r.toDict()
272
273     lock_state_file()
274
275     allocations = read_alloc_dict()
276     requested_allocations = rspec_to_allocations (rspec)
277     current_allocations = collapse_alloc_dict(allocations)
278     try:
279         current_hrn_allocations=allocations[hrn]
280     except KeyError:
281         current_hrn_allocations=[]
282
283     # Check request against current allocations
284     requested_interfaces = map(lambda(elt):elt[0], requested_allocations)
285     current_interfaces = map(lambda(elt):elt[0], current_allocations)
286     current_hrn_interfaces = map(lambda(elt):elt[0], current_hrn_allocations)
287
288     for a in requested_interfaces:
289         if (a not in current_hrn_interfaces and a in current_interfaces):
290             raise SfaOutOfResource(a)
291         if (topology[a][1] not in requested_interfaces):
292             raise SfaNoPairRSpec(a,topology[a][1])
293     # Request OK
294
295     # Allocations to delete
296     allocations_to_delete = []
297     for a in current_hrn_allocations:
298         if (a not in requested_allocations):
299             allocations_to_delete.extend([a])
300
301     # Ok, let's do our thing
302     alloc_nodes(api, hrn, requested_interfaces)
303     alloc_links(api, hrn, requested_allocations, allocations_to_delete)
304     allocations[hrn] = requested_allocations
305     commit_alloc_dict(allocations)
306
307     unlock_state_file()
308
309     return True
310
311 def rspec_to_allocations(rspec):
312     ifs = []
313     try:
314         ifspecs = rspec['rspec']['request'][0]['ifspec']
315         for l in ifspecs:
316             ifs.extend([(l['name'].replace('tns:',''),l['ip'])])
317     except KeyError:
318         # Bad RSpec
319         pass
320     return ifs
321
322 def main():
323     t = get_interface_map()
324     r = RSpec()
325     rspec_xml = open(sys.argv[1]).read()
326     #get_rspec(None,'foo')
327     create_slice(None, "plc.princeton.sap0", rspec_xml)
328     
329 if __name__ == "__main__":
330     main()