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