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