ListResources uses sfa.plc.aggregate instead of sfa.plc.network
[sfa.git] / sfa / managers / aggregate_manager_pl.py
1 import datetime
2 import time
3 import traceback
4 import sys
5 import re
6 from types import StringTypes
7
8 from sfa.util.faults import *
9 from sfa.util.xrn import get_authority, hrn_to_urn, urn_to_hrn, Xrn
10 from sfa.util.plxrn import slicename_to_hrn, hrn_to_pl_slicename, hostname_to_urn
11 from sfa.util.rspec import *
12 from sfa.util.specdict import *
13 from sfa.util.record import SfaRecord
14 from sfa.util.policy import Policy
15 from sfa.util.record import *
16 from sfa.util.sfaticket import SfaTicket
17 from sfa.plc.slices import Slices
18 from sfa.trust.credential import Credential
19 import sfa.plc.peers as peers
20 from sfa.plc.network import *
21 from sfa.plc.api import SfaAPI
22 from sfa.plc.aggregate import Aggregate
23 from sfa.plc.slices import *
24 from sfa.util.version import version_core
25 from sfa.util.sfatime import utcparse
26 from sfa.util.callids import Callids
27
28 def GetVersion(api):
29     xrn=Xrn(api.hrn)
30     return version_core({'interface':'aggregate',
31                          'testbed':'myplc',
32                          'hrn':xrn.get_hrn(),
33                          'input_rspec' : ['PG 2', 'SFA 1'],
34                          'output_rspec' : ["SFA 1"],
35                          'ad_rspec' : ["PG 2", "SFA 1"],
36                          })
37
38 def __get_registry_objects(slice_xrn, creds, users):
39     """
40
41     """
42     hrn, type = urn_to_hrn(slice_xrn)
43
44     hrn_auth = get_authority(hrn)
45
46     # Build up objects that an SFA registry would return if SFA
47     # could contact the slice's registry directly
48     reg_objects = None
49
50     if users:
51         # dont allow special characters in the site login base
52         #only_alphanumeric = re.compile('[^a-zA-Z0-9]+')
53         #login_base = only_alphanumeric.sub('', hrn_auth[:20]).lower()
54         slicename = hrn_to_pl_slicename(hrn)
55         login_base = slicename.split('_')[0]
56         reg_objects = {}
57         site = {}
58         site['site_id'] = 0
59         site['name'] = 'geni.%s' % login_base 
60         site['enabled'] = True
61         site['max_slices'] = 100
62
63         # Note:
64         # Is it okay if this login base is the same as one already at this myplc site?
65         # Do we need uniqueness?  Should use hrn_auth instead of just the leaf perhaps?
66         site['login_base'] = login_base
67         site['abbreviated_name'] = login_base
68         site['max_slivers'] = 1000
69         reg_objects['site'] = site
70
71         slice = {}
72         
73         extime = Credential(string=creds[0]).get_expiration()
74         # If the expiration time is > 60 days from now, set the expiration time to 60 days from now
75         if extime > datetime.datetime.utcnow() + datetime.timedelta(days=60):
76             extime = datetime.datetime.utcnow() + datetime.timedelta(days=60)
77         slice['expires'] = int(time.mktime(extime.timetuple()))
78         slice['hrn'] = hrn
79         slice['name'] = hrn_to_pl_slicename(hrn)
80         slice['url'] = hrn
81         slice['description'] = hrn
82         slice['pointer'] = 0
83         reg_objects['slice_record'] = slice
84
85         reg_objects['users'] = {}
86         for user in users:
87             user['key_ids'] = []
88             hrn, _ = urn_to_hrn(user['urn'])
89             user['email'] = hrn_to_pl_slicename(hrn) + "@geni.net"
90             user['first_name'] = hrn
91             user['last_name'] = hrn
92             reg_objects['users'][user['email']] = user
93
94         return reg_objects
95
96 def __get_hostnames(nodes):
97     hostnames = []
98     for node in nodes:
99         hostnames.append(node.hostname)
100     return hostnames
101
102 def SliverStatus(api, slice_xrn, creds, call_id):
103     if Callids().already_handled(call_id): return {}
104
105     (hrn, type) = urn_to_hrn(slice_xrn)
106     # find out where this slice is currently running
107     api.logger.info(hrn)
108     slicename = hrn_to_pl_slicename(hrn)
109     
110     slices = api.plshell.GetSlices(api.plauth, [slicename], ['node_ids','person_ids','name','expires'])
111     if len(slices) == 0:        
112         raise Exception("Slice %s not found (used %s as slicename internally)" % slice_xrn, slicename)
113     slice = slices[0]
114     
115     # report about the local nodes only
116     nodes = api.plshell.GetNodes(api.plauth, {'node_id':slice['node_ids'],'peer_id':None},
117                                  ['hostname', 'site_id', 'boot_state', 'last_contact'])
118     site_ids = [node['site_id'] for node in nodes]
119     sites = api.plshell.GetSites(api.plauth, site_ids, ['site_id', 'login_base'])
120     sites_dict = dict ( [ (site['site_id'],site['login_base'] ) for site in sites ] )
121
122     result = {}
123     top_level_status = 'unknown'
124     if nodes:
125         top_level_status = 'ready'
126     result['geni_urn'] = Xrn(slice_xrn, 'slice').get_urn()
127     result['pl_login'] = slice['name']
128     result['pl_expires'] = datetime.datetime.fromtimestamp(slice['expires']).ctime()
129     
130     resources = []
131     for node in nodes:
132         res = {}
133         res['pl_hostname'] = node['hostname']
134         res['pl_boot_state'] = node['boot_state']
135         res['pl_last_contact'] = node['last_contact']
136         if node['last_contact'] is not None:
137             res['pl_last_contact'] = datetime.datetime.fromtimestamp(node['last_contact']).ctime()
138         res['geni_urn'] = hostname_to_urn(api.hrn, sites_dict[node['site_id']], node['hostname'])
139         if node['boot_state'] == 'boot':
140             res['geni_status'] = 'ready'
141         else:
142             res['geni_status'] = 'failed'
143             top_level_staus = 'failed' 
144             
145         res['geni_error'] = ''
146
147         resources.append(res)
148         
149     result['geni_status'] = top_level_status
150     result['geni_resources'] = resources
151     # XX remove me
152     #api.logger.info(result)
153     # XX remove me
154     return result
155
156 def CreateSliver(api, slice_xrn, creds, rspec, users, call_id):
157     """
158     Create the sliver[s] (slice) at this aggregate.    
159     Verify HRN and initialize the slice record in PLC if necessary.
160     """
161     if Callids().already_handled(call_id): return ""
162
163     reg_objects = __get_registry_objects(slice_xrn, creds, users)
164
165     (hrn, type) = urn_to_hrn(slice_xrn)
166     peer = None
167     slices = Slices(api)
168     peer = slices.get_peer(hrn)
169     sfa_peer = slices.get_sfa_peer(hrn)
170     registry = api.registries[api.hrn]
171     credential = api.getCredential()
172     (site_id, remote_site_id) = slices.verify_site(registry, credential, hrn, 
173                                                    peer, sfa_peer, reg_objects)
174
175     slice_record = slices.verify_slice(registry, credential, hrn, site_id, 
176                                        remote_site_id, peer, sfa_peer, reg_objects)
177      
178     network = Network(api)
179
180     slice = network.get_slice(api, hrn)
181     slice.peer_id = slice_record['peer_slice_id']
182     current = __get_hostnames(slice.get_nodes())
183     
184     network.addRSpec(rspec, api.config.SFA_AGGREGATE_RSPEC_SCHEMA)
185     request = __get_hostnames(network.nodesWithSlivers())
186     
187     # remove nodes not in rspec
188     deleted_nodes = list(set(current).difference(request))
189
190     # add nodes from rspec
191     added_nodes = list(set(request).difference(current))
192
193     try:
194         if peer:
195             api.plshell.UnBindObjectFromPeer(api.plauth, 'slice', slice.id, peer)
196
197         api.plshell.AddSliceToNodes(api.plauth, slice.name, added_nodes) 
198         api.plshell.DeleteSliceFromNodes(api.plauth, slice.name, deleted_nodes)
199
200         network.updateSliceTags()
201
202     finally:
203         if peer:
204             api.plshell.BindObjectToPeer(api.plauth, 'slice', slice.id, peer, 
205                                          slice.peer_id)
206
207     # xxx - check this holds enough data for the client to understand what's happened
208     return network.toxml()
209
210
211 def RenewSliver(api, xrn, creds, expiration_time, call_id):
212     if Callids().already_handled(call_id): return True
213     (hrn, type) = urn_to_hrn(xrn)
214     slicename = hrn_to_pl_slicename(hrn)
215     slices = api.plshell.GetSlices(api.plauth, {'name': slicename}, ['slice_id'])
216     if not slices:
217         raise RecordNotFound(hrn)
218     slice = slices[0]
219     requested_time = utcparse(expiration_time)
220     record = {'expires': int(time.mktime(requested_time.timetuple()))}
221     try:
222         api.plshell.UpdateSlice(api.plauth, slice['slice_id'], record)
223         return True
224     except:
225         return False
226
227 def start_slice(api, xrn, creds):
228     hrn, type = urn_to_hrn(xrn)
229     slicename = hrn_to_pl_slicename(hrn)
230     slices = api.plshell.GetSlices(api.plauth, {'name': slicename}, ['slice_id'])
231     if not slices:
232         raise RecordNotFound(hrn)
233     slice_id = slices[0]['slice_id']
234     slice_tags = api.plshell.GetSliceTags(api.plauth, {'slice_id': slice_id, 'tagname': 'enabled'}, ['slice_tag_id'])
235     # just remove the tag if it exists
236     if slice_tags:
237         api.plshell.DeleteSliceTag(api.plauth, slice_tags[0]['slice_tag_id'])
238
239     return 1
240  
241 def stop_slice(api, xrn, creds):
242     hrn, type = urn_to_hrn(xrn)
243     slicename = hrn_to_pl_slicename(hrn)
244     slices = api.plshell.GetSlices(api.plauth, {'name': slicename}, ['slice_id'])
245     if not slices:
246         raise RecordNotFound(hrn)
247     slice_id = slices[0]['slice_id']
248     slice_tags = api.plshell.GetSliceTags(api.plauth, {'slice_id': slice_id, 'tagname': 'enabled'})
249     if not slice_tags:
250         api.plshell.AddSliceTag(api.plauth, slice_id, 'enabled', '0')
251     elif slice_tags[0]['value'] != "0":
252         tag_id = attributes[0]['slice_tag_id']
253         api.plshell.UpdateSliceTag(api.plauth, tag_id, '0')
254     return 1
255
256 def reset_slice(api, xrn):
257     # XX not implemented at this interface
258     return 1
259
260 def DeleteSliver(api, xrn, creds, call_id):
261     if Callids().already_handled(call_id): return ""
262     (hrn, type) = urn_to_hrn(xrn)
263     slicename = hrn_to_pl_slicename(hrn)
264     slices = api.plshell.GetSlices(api.plauth, {'name': slicename})
265     if not slices:
266         return 1
267     slice = slices[0]
268
269     # determine if this is a peer slice
270     peer = peers.get_peer(api, hrn)
271     try:
272         if peer:
273             api.plshell.UnBindObjectFromPeer(api.plauth, 'slice', slice['slice_id'], peer)
274         api.plshell.DeleteSliceFromNodes(api.plauth, slicename, slice['node_ids'])
275     finally:
276         if peer:
277             api.plshell.BindObjectToPeer(api.plauth, 'slice', slice['slice_id'], peer, slice['peer_slice_id'])
278     return 1
279
280 # xxx Thierry : caching at the aggregate level sounds wrong...
281 caching=True
282 #caching=False
283 def ListSlices(api, creds, call_id):
284     if Callids().already_handled(call_id): return []
285     # look in cache first
286     if caching and api.cache:
287         slices = api.cache.get('slices')
288         if slices:
289             return slices
290
291     # get data from db 
292     slices = api.plshell.GetSlices(api.plauth, {'peer_id': None}, ['name'])
293     slice_hrns = [slicename_to_hrn(api.hrn, slice['name']) for slice in slices]
294     slice_urns = [hrn_to_urn(slice_hrn, 'slice') for slice_hrn in slice_hrns]
295
296     # cache the result
297     if caching and api.cache:
298         api.cache.add('slices', slice_urns) 
299
300     return slice_urns
301     
302 def ListResources(api, creds, options,call_id):
303     if Callids().already_handled(call_id): return ""
304     # get slice's hrn from options
305     xrn = options.get('geni_slice_urn', '')
306     (hrn, type) = urn_to_hrn(xrn)
307
308     # get the rspec's return format from options
309     try:
310         format_raw = options.get('rspec_version', 'SFA 1')
311         format_split = format_raw.split(' ')
312         format, version = format_split[0].lower(), format_split[1]
313     except:
314         # invalid format. Just continue
315         format, version = 'sfa', '1'
316     format_template = "rsepc_%s_%s"
317
318     # look in cache first
319     if caching and api.cache and not xrn:
320         rspec = api.cache.get(format_template % (format, version))
321         if rspec:
322             api.logger.info("aggregate.ListResources: returning cached value for hrn %s"%hrn)
323             return rspec 
324
325     aggregate = Aggregate(api)
326
327     if xrn:
328         # get this rspec for the specified slice 
329         rspec =  aggregate.get_rspec(slice_xrn=hrn, format=format)
330     else:
331         # generate rspec in both pg and sfa formats
332         rspec = aggregate.get_rspec(format=format)
333     # cache the result
334     if caching and api.cache:
335         api.cache.add(format_template % (format, version), rspec)
336
337     return rspec
338
339
340 def get_ticket(api, xrn, creds, rspec, users):
341
342     reg_objects = __get_registry_objects(xrn, creds, users)
343
344     slice_hrn, type = urn_to_hrn(xrn)
345     slices = Slices(api)
346     peer = slices.get_peer(slice_hrn)
347     sfa_peer = slices.get_sfa_peer(slice_hrn)
348
349     # get the slice record
350     registry = api.registries[api.hrn]
351     credential = api.getCredential()
352     records = registry.Resolve(xrn, credential)
353
354     # similar to CreateSliver, we must verify that the required records exist
355     # at this aggregate before we can issue a ticket
356     site_id, remote_site_id = slices.verify_site(registry, credential, slice_hrn,
357                                                  peer, sfa_peer, reg_objects)
358     slice = slices.verify_slice(registry, credential, slice_hrn, site_id,
359                                 remote_site_id, peer, sfa_peer, reg_objects)
360
361     # make sure we get a local slice record
362     record = None
363     for tmp_record in records:
364         if tmp_record['type'] == 'slice' and \
365            not tmp_record['peer_authority']:
366             record = SliceRecord(dict=tmp_record)
367     if not record:
368         raise RecordNotFound(slice_hrn)
369
370     # get sliver info
371     slivers = Slices(api).get_slivers(slice_hrn)
372     if not slivers:
373         raise SliverDoesNotExist(slice_hrn)
374
375     # get initscripts
376     initscripts = []
377     data = {
378         'timestamp': int(time.time()),
379         'initscripts': initscripts,
380         'slivers': slivers
381     }
382
383     # create the ticket
384     object_gid = record.get_gid_object()
385     new_ticket = SfaTicket(subject = object_gid.get_subject())
386     new_ticket.set_gid_caller(api.auth.client_gid)
387     new_ticket.set_gid_object(object_gid)
388     new_ticket.set_issuer(key=api.key, subject=api.hrn)
389     new_ticket.set_pubkey(object_gid.get_pubkey())
390     new_ticket.set_attributes(data)
391     new_ticket.set_rspec(rspec)
392     #new_ticket.set_parent(api.auth.hierarchy.get_auth_ticket(auth_hrn))
393     new_ticket.encode()
394     new_ticket.sign()
395
396     return new_ticket.save_to_string(save_parents=True)
397
398
399
400 def main():
401     api = SfaAPI()
402     """
403     rspec = ListResources(api, "plc.princeton.sapan", None, 'pl_test_sapan')
404     #rspec = ListResources(api, "plc.princeton.coblitz", None, 'pl_test_coblitz')
405     #rspec = ListResources(api, "plc.pl.sirius", None, 'pl_test_sirius')
406     print rspec
407     """
408     f = open(sys.argv[1])
409     xml = f.read()
410     f.close()
411     CreateSliver(api, "plc.princeton.sapan", xml, 'CreateSliver_sapan')
412
413 if __name__ == "__main__":
414     main()