(no commit message)
[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.misc import *
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.util.debug import log
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 GeniOutOfResource(GeniFault):
26     def __init__(self, interface):
27         faultString = "Interface " + interface + " not available"
28         GeniFault.__init__(self, 100, faultString, '')
29
30 class GeniNoPairRspec(GeniFault):
31     def __init__(self, interface, interface2):
32         faultString = "Interface " + interface + " should be paired with " + interface2
33         GeniFault.__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, links_to_add, links_to_drop, foo):
125     #for l in links_to_add:
126         #(node1,ip1,node2,ip2) = l
127         #api.plshell.AddSliceTag(api.plauth, [slicename], ['node_ids'])
128     return True
129
130 def alloc_nodes(api,hrn, requested_ifs):
131     
132     requested_nodes = if_endpoints(requested_ifs)
133
134     create_slice_max_aggregate(api, hrn, requested_nodes)
135
136 # Taken from slices.py
137
138 def create_slice_max_aggregate(api, hrn, nodes):
139     # Get the slice record from geni
140     global topology
141     topology = get_interface_map()
142     slice = {}
143     registries = Registries(api)
144     registry = registries[api.hrn]
145     credential = api.getCredential()
146     records = registry.resolve(credential, hrn)
147     for record in records:
148         if record.get_type() in ['slice']:
149             slice = record.as_dict()
150     if not slice:
151         raise RecordNotFound(hrn)   
152
153     # Make sure slice exists at plc, if it doesnt add it
154     slicename = hrn_to_pl_slicename(hrn)
155     slices = api.plshell.GetSlices(api.plauth, [slicename], ['node_ids'])
156     if not slices:
157         parts = slicename.split("_")
158         login_base = parts[0]
159         # if site doesnt exist add it
160         sites = api.plshell.GetSites(api.plauth, [login_base])
161         if not sites:
162             authority = get_authority(hrn)
163             site_records = registry.resolve(credential, authority)
164             site_record = {}
165             if not site_records:
166                 raise RecordNotFound(authority)
167             site_record = site_records[0]
168             site = site_record.as_dict()
169                 
170             # add the site
171             site.pop('site_id')
172             site_id = api.plshell.AddSite(api.plauth, site)
173         else:
174             site = sites[0]
175             
176         slice_fields = {}
177         slice_keys = ['name', 'url', 'description']
178         for key in slice_keys:
179             if key in slice and slice[key]:
180                 slice_fields[key] = slice[key]  
181         api.plshell.AddSlice(api.plauth, slice_fields)
182         slice = slice_fields
183         slice['node_ids'] = 0
184     else:
185         slice = slices[0]    
186
187     # get the list of valid slice users from the registry and make 
188     # they are added to the slice 
189     researchers = record.get('researcher', [])
190     for researcher in researchers:
191         person_record = {}
192         person_records = registry.resolve(credential, researcher)
193         for record in person_records:
194             if record.get_type() in ['user']:
195                 person_record = record
196         if not person_record:
197             pass
198         person_dict = person_record.as_dict()
199         persons = api.plshell.GetPersons(api.plauth, [person_dict['email']],
200                                          ['person_id', 'key_ids'])
201
202         # Create the person record 
203         if not persons:
204             person_id=api.plshell.AddPerson(api.plauth, person_dict)
205
206             # The line below enables the user account on the remote aggregate
207             # soon after it is created.
208             # without this the user key is not transfered to the slice
209             # (as GetSlivers returns key of only enabled users),
210             # which prevents the user from login to the slice.
211             # We may do additional checks before enabling the user.
212
213             api.plshell.UpdatePerson(api.plauth, person_id, {'enabled' : True})
214             key_ids = []
215         else:
216             key_ids = persons[0]['key_ids']
217
218         api.plshell.AddPersonToSlice(api.plauth, person_dict['email'],
219                                      slicename)        
220
221         # Get this users local keys
222         keylist = api.plshell.GetKeys(api.plauth, key_ids, ['key'])
223         keys = [key['key'] for key in keylist]
224
225         # add keys that arent already there 
226         for personkey in person_dict['keys']:
227             if personkey not in keys:
228                 key = {'key_type': 'ssh', 'key': personkey}
229                 api.plshell.AddPersonKey(api.plauth, person_dict['email'], key)
230
231     # find out where this slice is currently running
232     nodelist = api.plshell.GetNodes(api.plauth, slice['node_ids'],
233                                     ['hostname'])
234     hostnames = [node['hostname'] for node in nodelist]
235
236     # remove nodes not in rspec
237     deleted_nodes = list(set(hostnames).difference(nodes))
238     # add nodes from rspec
239     added_nodes = list(set(nodes).difference(hostnames))
240
241     api.plshell.AddSliceToNodes(api.plauth, slicename, added_nodes) 
242     api.plshell.DeleteSliceFromNodes(api.plauth, slicename, deleted_nodes)
243
244     return 1
245
246
247 def get_rspec(api, hrn):
248     # Eg. config line:
249     # plc.princeton.sapan vlan23,vlan45
250
251     allocations = read_alloc_dict()
252     if (hrn and allocations.has_key(hrn)):
253             ret_rspec = allocations_to_rspec(allocations[hrn])
254     else:
255         ret_rspec = open(SFA_MAX_CANNED_RSPEC).read()
256
257     return (ret_rspec)
258
259
260 def create_slice(api, hrn, rspec_xml):
261     global topology
262     topology = get_interface_map()
263
264     # Check if everything in rspec is either allocated by hrn
265     # or not allocated at all.
266     r = Rspec()
267     r.parseString(rspec_xml)
268     rspec = r.toDict()
269
270     lock_state_file()
271
272     allocations = read_alloc_dict()
273     requested_allocations = rspec_to_allocations (rspec)
274     current_allocations = collapse_alloc_dict(allocations)
275     try:
276         current_hrn_allocations=allocations[hrn]
277     except KeyError:
278         current_hrn_allocations=[]
279
280     # Check request against current allocations
281     requested_interfaces = map(lambda(elt):elt[0], requested_allocations)
282     current_interfaces = map(lambda(elt):elt[0], current_allocations)
283     current_hrn_interfaces = map(lambda(elt):elt[0], current_hrn_allocations)
284
285     for a in requested_interfaces:
286         if (a not in current_hrn_interfaces and a in current_interfaces):
287             raise GeniOutOfResource(a)
288         if (topology[a][1] not in requested_interfaces):
289             raise GeniNoPairRspec(a,topology[a][1])
290     # Request OK
291
292     # Allocations to delete
293     allocations_to_delete = []
294     for a in current_hrn_allocations:
295         if (a not in requested_allocations):
296             allocations_to_delete.extend([a])
297
298     # Ok, let's do our thing
299     alloc_nodes(api, hrn, requested_interfaces)
300     alloc_links(api, hrn, requested_allocations, allocations_to_delete)
301     allocations[hrn] = requested_allocations
302     commit_alloc_dict(allocations)
303
304     unlock_state_file()
305
306     return True
307
308 def rspec_to_allocations(rspec):
309     ifs = []
310     try:
311         ifspecs = rspec['rspec']['request'][0]['ifspec']
312         for l in ifspecs:
313             ifs.extend([(l['name'].replace('tns:',''),l['ip'])])
314     except KeyError:
315         # Bad Rspec
316         pass
317     return ifs
318
319 def main():
320     t = get_interface_map()
321     r = Rspec()
322     rspec_xml = open(sys.argv[1]).read()
323     #get_rspec(None,'foo')
324     create_slice(None, "foo", rspec_xml)
325     
326 if __name__ == "__main__":
327     main()