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