use generice email address for each PG slice
[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
10 from sfa.util.plxrn import slicename_to_hrn, hrn_to_pl_slicename
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
83             user['first_name'] = hrn
84             user['last_name'] = hrn
85             reg_objects['users'][user['email']] = user
86
87         return reg_objects
88
89 def __get_hostnames(nodes):
90     hostnames = []
91     for node in nodes:
92         hostnames.append(node.hostname)
93     return hostnames
94
95 def slice_status(api, slice_xrn, creds):
96     hrn, type = urn_to_hrn(slice_xrn)
97     # find out where this slice is currently running
98     api.logger.info(hrn)
99     slicename = hrn_to_pl_slicename(hrn)
100     
101     slices = api.plshell.GetSlices(api.plauth, [slicename], ['node_ids','person_ids','name','expires'])
102     if len(slices) == 0:        
103         raise Exception("Slice %s not found (used %s as slicename internally)" % slice_xrn, slicename)
104     slice = slices[0]
105     
106     nodes = api.plshell.GetNodes(api.plauth, slice['node_ids'],
107                                     ['hostname', 'boot_state', 'last_contact'])
108     api.logger.info(slice)
109     api.logger.info(nodes)
110     
111     result = {}
112     result['geni_urn'] = slice_xrn
113     result['geni_status'] = 'unknown'
114     result['pl_login'] = slice['name']
115     result['pl_expires'] = datetime.datetime.fromtimestamp(slice['expires']).ctime()
116     
117     resources = []
118     
119     for node in nodes:
120         res = {}
121         res['pl_hostname'] = node['hostname']
122         res['pl_boot_state'] = node['boot_state']
123         res['pl_last_contact'] = node['last_contact']
124         if not node['last_contact'] is None:
125             res['pl_last_contact'] = datetime.datetime.fromtimestamp(node['last_contact']).ctime()
126         res['geni_urn'] = ''
127         res['geni_status'] = 'unknown'
128         res['geni_error'] = ''
129
130         resources.append(res)
131         
132     result['geni_resources'] = resources
133     return result
134
135 def create_slice(api, slice_xrn, creds, rspec, users):
136     """
137     Create the sliver[s] (slice) at this aggregate.    
138     Verify HRN and initialize the slice record in PLC if necessary.
139     """
140
141     reg_objects = __get_registry_objects(slice_xrn, creds, users)
142
143     hrn, type = urn_to_hrn(slice_xrn)
144     peer = None
145     slices = Slices(api)
146     peer = slices.get_peer(hrn)
147     sfa_peer = slices.get_sfa_peer(hrn)
148     registry = api.registries[api.hrn]
149     credential = api.getCredential()
150     site_id, remote_site_id = slices.verify_site(registry, credential, hrn, 
151                                                  peer, sfa_peer, reg_objects)
152
153     slice_record = slices.verify_slice(registry, credential, hrn, site_id, 
154                                 remote_site_id, peer, sfa_peer, reg_objects)
155      
156     network = Network(api)
157
158     slice = network.get_slice(api, hrn)
159     slice.peer_id = slice_record['peer_slice_id']
160     current = __get_hostnames(slice.get_nodes())
161     
162     network.addRSpec(rspec, api.config.SFA_AGGREGATE_RSPEC_SCHEMA)
163     request = __get_hostnames(network.nodesWithSlivers())
164     
165     # remove nodes not in rspec
166     deleted_nodes = list(set(current).difference(request))
167
168     # add nodes from rspec
169     added_nodes = list(set(request).difference(current))
170
171     try:
172         if peer:
173             api.plshell.UnBindObjectFromPeer(api.plauth, 'slice', slice.id, peer)
174
175         api.plshell.AddSliceToNodes(api.plauth, slice.name, added_nodes) 
176         api.plshell.DeleteSliceFromNodes(api.plauth, slice.name, deleted_nodes)
177
178         network.updateSliceTags()
179
180     finally:
181         if peer:
182             api.plshell.BindObjectToPeer(api.plauth, 'slice', slice.id, peer, 
183                                          slice.peer_id)
184
185     # print network.toxml()
186
187     return True
188
189
190 def renew_slice(api, xrn, creds, expiration_time):
191     hrn, type = urn_to_hrn(xrn)
192     slicename = hrn_to_pl_slicename(hrn)
193     slices = api.plshell.GetSlices(api.plauth, {'name': slicename}, ['slice_id'])
194     if not slices:
195         raise RecordNotFound(hrn)
196     slice = slices[0]
197     requested_time = utcparse(expiration_time)
198     record = {'expires': int(time.mktime(requested_time.timetuple()))}
199     api.plshell.UpdateSlice(api.plauth, slice['slice_id'], record)
200     return 1         
201
202 def start_slice(api, xrn, creds):
203     hrn, type = urn_to_hrn(xrn)
204     slicename = hrn_to_pl_slicename(hrn)
205     slices = api.plshell.GetSlices(api.plauth, {'name': slicename}, ['slice_id'])
206     if not slices:
207         raise RecordNotFound(hrn)
208     slice_id = slices[0]['slice_id']
209     slice_tags = api.plshell.GetSliceTags(api.plauth, {'slice_id': slice_id, 'tagname': 'enabled'}, ['slice_tag_id'])
210     # just remove the tag if it exists
211     if slice_tags:
212         api.plshell.DeleteSliceTag(api.plauth, slice_tags[0]['slice_tag_id'])
213
214     return 1
215  
216 def stop_slice(api, xrn, creds):
217     hrn, type = urn_to_hrn(xrn)
218     slicename = hrn_to_pl_slicename(hrn)
219     slices = api.plshell.GetSlices(api.plauth, {'name': slicename}, ['slice_id'])
220     if not slices:
221         raise RecordNotFound(hrn)
222     slice_id = slices[0]['slice_id']
223     slice_tags = api.plshell.GetSliceTags(api.plauth, {'slice_id': slice_id, 'tagname': 'enabled'})
224     if not slice_tags:
225         api.plshell.AddSliceTag(api.plauth, slice_id, 'enabled', '0')
226     elif slice_tags[0]['value'] != "0":
227         tag_id = attributes[0]['slice_tag_id']
228         api.plshell.UpdateSliceTag(api.plauth, tag_id, '0')
229     return 1
230
231 def reset_slice(api, xrn):
232     # XX not implemented at this interface
233     return 1
234
235 def delete_slice(api, xrn, creds):
236     hrn, type = urn_to_hrn(xrn)
237     slicename = hrn_to_pl_slicename(hrn)
238     slices = api.plshell.GetSlices(api.plauth, {'name': slicename})
239     if not slices:
240         return 1
241     slice = slices[0]
242
243     # determine if this is a peer slice
244     peer = peers.get_peer(api, hrn)
245     try:
246         if peer:
247             api.plshell.UnBindObjectFromPeer(api.plauth, 'slice', slice['slice_id'], peer)
248         api.plshell.DeleteSliceFromNodes(api.plauth, slicename, slice['node_ids'])
249     finally:
250         if peer:
251             api.plshell.BindObjectToPeer(api.plauth, 'slice', slice['slice_id'], peer, slice['peer_slice_id'])
252     return 1
253
254 def get_slices(api, creds):
255     # look in cache first
256     if api.cache:
257         slices = api.cache.get('slices')
258         if slices:
259             return slices
260
261     # get data from db 
262     slices = api.plshell.GetSlices(api.plauth, {'peer_id': None}, ['name'])
263     slice_hrns = [slicename_to_hrn(api.hrn, slice['name']) for slice in slices]
264     slice_urns = [hrn_to_urn(slice_hrn, 'slice') for slice_hrn in slice_hrns]
265
266     # cache the result
267     if api.cache:
268         api.cache.add('slices', slice_urns) 
269
270     return slice_urns
271     
272 def get_rspec(api, creds, options):
273     # get slice's hrn from options
274     xrn = options.get('geni_slice_urn', '')
275     hrn, type = urn_to_hrn(xrn)
276
277     # look in cache first
278     if api.cache and not xrn:
279         rspec = api.cache.get('nodes')
280         if rspec:
281             return rspec 
282
283     network = Network(api)
284     if (hrn):
285         if network.get_slice(api, hrn):
286             network.addSlice()
287
288     rspec = network.toxml()
289
290     # cache the result
291     if api.cache and not xrn:
292         api.cache.add('nodes', rspec)
293
294     return rspec
295
296
297 def get_ticket(api, xrn, creds, rspec, users):
298
299     reg_objects = __get_registry_objects(xrn, creds, users)
300
301     slice_hrn, type = urn_to_hrn(xrn)
302     slices = Slices(api)
303     peer = slices.get_peer(slice_hrn)
304     sfa_peer = slices.get_sfa_peer(slice_hrn)
305
306     # get the slice record
307     registry = api.registries[api.hrn]
308     credential = api.getCredential()
309     records = registry.Resolve(xrn, credential)
310
311     # similar to create_slice, we must verify that the required records exist
312     # at this aggregate before we can issue a ticket
313     site_id, remote_site_id = slices.verify_site(registry, credential, slice_hrn,
314                                                  peer, sfa_peer, reg_objects)
315     slice = slices.verify_slice(registry, credential, slice_hrn, site_id,
316                                 remote_site_id, peer, sfa_peer, reg_objects)
317
318     # make sure we get a local slice record
319     record = None
320     for tmp_record in records:
321         if tmp_record['type'] == 'slice' and \
322            not tmp_record['peer_authority']:
323             record = SliceRecord(dict=tmp_record)
324     if not record:
325         raise RecordNotFound(slice_hrn)
326
327     # get sliver info
328     slivers = Slices(api).get_slivers(slice_hrn)
329     if not slivers:
330         raise SliverDoesNotExist(slice_hrn)
331
332     # get initscripts
333     initscripts = []
334     data = {
335         'timestamp': int(time.time()),
336         'initscripts': initscripts,
337         'slivers': slivers
338     }
339
340     # create the ticket
341     object_gid = record.get_gid_object()
342     new_ticket = SfaTicket(subject = object_gid.get_subject())
343     new_ticket.set_gid_caller(api.auth.client_gid)
344     new_ticket.set_gid_object(object_gid)
345     new_ticket.set_issuer(key=api.key, subject=api.hrn)
346     new_ticket.set_pubkey(object_gid.get_pubkey())
347     new_ticket.set_attributes(data)
348     new_ticket.set_rspec(rspec)
349     #new_ticket.set_parent(api.auth.hierarchy.get_auth_ticket(auth_hrn))
350     new_ticket.encode()
351     new_ticket.sign()
352
353     return new_ticket.save_to_string(save_parents=True)
354
355
356
357 def main():
358     api = SfaAPI()
359     """
360     rspec = get_rspec(api, "plc.princeton.sapan", None)
361     #rspec = get_rspec(api, "plc.princeton.coblitz", None)
362     #rspec = get_rspec(api, "plc.pl.sirius", None)
363     print rspec
364     """
365     f = open(sys.argv[1])
366     xml = f.read()
367     f.close()
368     create_slice(api, "plc.princeton.sapan", xml)
369
370 if __name__ == "__main__":
371     main()