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