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