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