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