Merge branch 'master' of ssh://git.onelab.eu/git/sfa
[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
26 def GetVersion(api):
27     xrn=Xrn(api.hrn)
28     return version_core({'interface':'aggregate',
29                          'testbed':'myplc',
30                          'hrn':xrn.get_hrn(),
31                          })
32
33 def __get_registry_objects(slice_xrn, creds, users):
34     """
35
36     """
37     hrn, type = urn_to_hrn(slice_xrn)
38
39     hrn_auth = get_authority(hrn)
40
41     # Build up objects that an SFA registry would return if SFA
42     # could contact the slice's registry directly
43     reg_objects = None
44
45     if users:
46         # dont allow special characters in the site login base
47         #only_alphanumeric = re.compile('[^a-zA-Z0-9]+')
48         #login_base = only_alphanumeric.sub('', hrn_auth[:20]).lower()
49         slicename = hrn_to_pl_slicename(hrn)
50         login_base = slicename.split('_')[0]
51         reg_objects = {}
52         site = {}
53         site['site_id'] = 0
54         site['name'] = 'geni.%s' % login_base 
55         site['enabled'] = True
56         site['max_slices'] = 100
57
58         # Note:
59         # Is it okay if this login base is the same as one already at this myplc site?
60         # Do we need uniqueness?  Should use hrn_auth instead of just the leaf perhaps?
61         site['login_base'] = login_base
62         site['abbreviated_name'] = login_base
63         site['max_slivers'] = 1000
64         reg_objects['site'] = site
65
66         slice = {}
67         
68         extime = Credential(string=creds[0]).get_expiration()
69         # If the expiration time is > 60 days from now, set the expiration time to 60 days from now
70         if extime > datetime.datetime.utcnow() + datetime.timedelta(days=60):
71             extime = datetime.datetime.utcnow() + datetime.timedelta(days=60)
72         slice['expires'] = int(time.mktime(extime.timetuple()))
73         slice['hrn'] = hrn
74         slice['name'] = hrn_to_pl_slicename(hrn)
75         slice['url'] = hrn
76         slice['description'] = hrn
77         slice['pointer'] = 0
78         reg_objects['slice_record'] = slice
79
80         reg_objects['users'] = {}
81         for user in users:
82             user['key_ids'] = []
83             hrn, _ = urn_to_hrn(user['urn'])
84             user['email'] = hrn_to_pl_slicename(hrn) + "@geni.net"
85             user['first_name'] = hrn
86             user['last_name'] = hrn
87             reg_objects['users'][user['email']] = user
88
89         return reg_objects
90
91 def __get_hostnames(nodes):
92     hostnames = []
93     for node in nodes:
94         hostnames.append(node.hostname)
95     return hostnames
96
97 def slice_status(api, slice_xrn, creds):
98     hrn, type = urn_to_hrn(slice_xrn)
99     # find out where this slice is currently running
100     api.logger.info(hrn)
101     slicename = hrn_to_pl_slicename(hrn)
102     
103     slices = api.plshell.GetSlices(api.plauth, [slicename], ['node_ids','person_ids','name','expires'])
104     if len(slices) == 0:        
105         raise Exception("Slice %s not found (used %s as slicename internally)" % slice_xrn, slicename)
106     slice = slices[0]
107     
108     nodes = api.plshell.GetNodes(api.plauth, slice['node_ids'],
109                                     ['hostname', 'site_id', 'boot_state', 'last_contact'])
110     site_ids = [node['site_id'] for node in nodes]
111     sites = api.plshell.GetSites(api.plauth, site_ids, ['site_id', 'login_base'])
112     sites_dict = {}
113     for site in sites:
114         sites_dict[site['site_id']] = site['login_base']
115
116     # XX remove me
117     #api.logger.info(slice_xrn)
118     #api.logger.info(slice)
119     #api.logger.info(nodes)
120     # XX remove me
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 not node['last_contact'] is 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 create_slice(api, slice_xrn, creds, rspec, users):
157     """
158     Create the sliver[s] (slice) at this aggregate.    
159     Verify HRN and initialize the slice record in PLC if necessary.
160     """
161
162     reg_objects = __get_registry_objects(slice_xrn, creds, users)
163
164     hrn, type = urn_to_hrn(slice_xrn)
165     peer = None
166     slices = Slices(api)
167     peer = slices.get_peer(hrn)
168     sfa_peer = slices.get_sfa_peer(hrn)
169     registry = api.registries[api.hrn]
170     credential = api.getCredential()
171     site_id, remote_site_id = slices.verify_site(registry, credential, hrn, 
172                                                  peer, sfa_peer, reg_objects)
173
174     slice_record = slices.verify_slice(registry, credential, hrn, site_id, 
175                                 remote_site_id, peer, sfa_peer, reg_objects)
176      
177     network = Network(api)
178
179     slice = network.get_slice(api, hrn)
180     slice.peer_id = slice_record['peer_slice_id']
181     current = __get_hostnames(slice.get_nodes())
182     
183     network.addRSpec(rspec, api.config.SFA_AGGREGATE_RSPEC_SCHEMA)
184     request = __get_hostnames(network.nodesWithSlivers())
185     
186     # remove nodes not in rspec
187     deleted_nodes = list(set(current).difference(request))
188
189     # add nodes from rspec
190     added_nodes = list(set(request).difference(current))
191
192     try:
193         if peer:
194             api.plshell.UnBindObjectFromPeer(api.plauth, '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         network.updateSliceTags()
200
201     finally:
202         if peer:
203             api.plshell.BindObjectToPeer(api.plauth, 'slice', slice.id, peer, 
204                                          slice.peer_id)
205
206     # print network.toxml()
207
208     return True
209
210
211 def renew_slice(api, xrn, creds, expiration_time):
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     api.plshell.UpdateSlice(api.plauth, slice['slice_id'], record)
221     return 1         
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 delete_slice(api, xrn, creds):
257     hrn, type = urn_to_hrn(xrn)
258     slicename = hrn_to_pl_slicename(hrn)
259     slices = api.plshell.GetSlices(api.plauth, {'name': slicename})
260     if not slices:
261         return 1
262     slice = slices[0]
263
264     # determine if this is a peer slice
265     peer = peers.get_peer(api, hrn)
266     try:
267         if peer:
268             api.plshell.UnBindObjectFromPeer(api.plauth, 'slice', slice['slice_id'], peer)
269         api.plshell.DeleteSliceFromNodes(api.plauth, slicename, slice['node_ids'])
270     finally:
271         if peer:
272             api.plshell.BindObjectToPeer(api.plauth, 'slice', slice['slice_id'], peer, slice['peer_slice_id'])
273     return 1
274
275 def get_slices(api, creds):
276     # look in cache first
277     if api.cache:
278         slices = api.cache.get('slices')
279         if slices:
280             return slices
281
282     # get data from db 
283     slices = api.plshell.GetSlices(api.plauth, {'peer_id': None}, ['name'])
284     slice_hrns = [slicename_to_hrn(api.hrn, slice['name']) for slice in slices]
285     slice_urns = [hrn_to_urn(slice_hrn, 'slice') for slice_hrn in slice_hrns]
286
287     # cache the result
288     if api.cache:
289         api.cache.add('slices', slice_urns) 
290
291     return slice_urns
292     
293 def get_rspec(api, creds, options):
294     # get slice's hrn from options
295     xrn = options.get('geni_slice_urn', '')
296     hrn, type = urn_to_hrn(xrn)
297
298     # look in cache first
299     if api.cache and not xrn:
300         rspec = api.cache.get('nodes')
301         if rspec:
302             return rspec 
303
304     network = Network(api)
305     if (hrn):
306         if network.get_slice(api, hrn):
307             network.addSlice()
308
309     rspec = network.toxml()
310
311     # cache the result
312     if api.cache and not xrn:
313         api.cache.add('nodes', rspec)
314
315     return rspec
316
317
318 def get_ticket(api, xrn, creds, rspec, users):
319
320     reg_objects = __get_registry_objects(xrn, creds, users)
321
322     slice_hrn, type = urn_to_hrn(xrn)
323     slices = Slices(api)
324     peer = slices.get_peer(slice_hrn)
325     sfa_peer = slices.get_sfa_peer(slice_hrn)
326
327     # get the slice record
328     registry = api.registries[api.hrn]
329     credential = api.getCredential()
330     records = registry.Resolve(xrn, credential)
331
332     # similar to create_slice, we must verify that the required records exist
333     # at this aggregate before we can issue a ticket
334     site_id, remote_site_id = slices.verify_site(registry, credential, slice_hrn,
335                                                  peer, sfa_peer, reg_objects)
336     slice = slices.verify_slice(registry, credential, slice_hrn, site_id,
337                                 remote_site_id, peer, sfa_peer, reg_objects)
338
339     # make sure we get a local slice record
340     record = None
341     for tmp_record in records:
342         if tmp_record['type'] == 'slice' and \
343            not tmp_record['peer_authority']:
344             record = SliceRecord(dict=tmp_record)
345     if not record:
346         raise RecordNotFound(slice_hrn)
347
348     # get sliver info
349     slivers = Slices(api).get_slivers(slice_hrn)
350     if not slivers:
351         raise SliverDoesNotExist(slice_hrn)
352
353     # get initscripts
354     initscripts = []
355     data = {
356         'timestamp': int(time.time()),
357         'initscripts': initscripts,
358         'slivers': slivers
359     }
360
361     # create the ticket
362     object_gid = record.get_gid_object()
363     new_ticket = SfaTicket(subject = object_gid.get_subject())
364     new_ticket.set_gid_caller(api.auth.client_gid)
365     new_ticket.set_gid_object(object_gid)
366     new_ticket.set_issuer(key=api.key, subject=api.hrn)
367     new_ticket.set_pubkey(object_gid.get_pubkey())
368     new_ticket.set_attributes(data)
369     new_ticket.set_rspec(rspec)
370     #new_ticket.set_parent(api.auth.hierarchy.get_auth_ticket(auth_hrn))
371     new_ticket.encode()
372     new_ticket.sign()
373
374     return new_ticket.save_to_string(save_parents=True)
375
376
377
378 def main():
379     api = SfaAPI()
380     """
381     rspec = get_rspec(api, "plc.princeton.sapan", None)
382     #rspec = get_rspec(api, "plc.princeton.coblitz", None)
383     #rspec = get_rspec(api, "plc.pl.sirius", None)
384     print rspec
385     """
386     f = open(sys.argv[1])
387     xml = f.read()
388     f.close()
389     create_slice(api, "plc.princeton.sapan", xml)
390
391 if __name__ == "__main__":
392     main()