6 from types import StringTypes
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.aggregate import Aggregate
23 from sfa.plc.slices import *
24 from sfa.util.version import version_core
25 from sfa.rspecs.rspec_version import RSpecVersion
26 from sfa.rspecs.rspec_parser import parse_rspec
27 from sfa.util.sfatime import utcparse
28 from sfa.util.callids import Callids
32 return version_core({'interface':'aggregate',
35 'input_rspec' : ['PG 2', 'SFA 1'],
36 'output_rspec' : ["SFA 1"],
37 'ad_rspec' : ["PG 2", "SFA 1"],
40 def __get_registry_objects(slice_xrn, creds, users):
44 hrn, type = urn_to_hrn(slice_xrn)
46 hrn_auth = get_authority(hrn)
48 # Build up objects that an SFA registry would return if SFA
49 # could contact the slice's registry directly
53 # dont allow special characters in the site login base
54 #only_alphanumeric = re.compile('[^a-zA-Z0-9]+')
55 #login_base = only_alphanumeric.sub('', hrn_auth[:20]).lower()
56 slicename = hrn_to_pl_slicename(hrn)
57 login_base = slicename.split('_')[0]
61 site['name'] = 'geni.%s' % login_base
62 site['enabled'] = True
63 site['max_slices'] = 100
66 # Is it okay if this login base is the same as one already at this myplc site?
67 # Do we need uniqueness? Should use hrn_auth instead of just the leaf perhaps?
68 site['login_base'] = login_base
69 site['abbreviated_name'] = login_base
70 site['max_slivers'] = 1000
71 reg_objects['site'] = site
75 extime = Credential(string=creds[0]).get_expiration()
76 # If the expiration time is > 60 days from now, set the expiration time to 60 days from now
77 if extime > datetime.datetime.utcnow() + datetime.timedelta(days=60):
78 extime = datetime.datetime.utcnow() + datetime.timedelta(days=60)
79 slice['expires'] = int(time.mktime(extime.timetuple()))
81 slice['name'] = hrn_to_pl_slicename(hrn)
83 slice['description'] = hrn
85 reg_objects['slice_record'] = slice
87 reg_objects['users'] = {}
90 hrn, _ = urn_to_hrn(user['urn'])
91 user['email'] = hrn_to_pl_slicename(hrn) + "@geni.net"
92 user['first_name'] = hrn
93 user['last_name'] = hrn
94 reg_objects['users'][user['email']] = user
98 def __get_hostnames(nodes):
101 hostnames.append(node.hostname)
104 def SliverStatus(api, slice_xrn, creds, call_id):
105 if Callids().already_handled(call_id): return {}
107 (hrn, type) = urn_to_hrn(slice_xrn)
108 # find out where this slice is currently running
110 slicename = hrn_to_pl_slicename(hrn)
112 slices = api.plshell.GetSlices(api.plauth, [slicename], ['node_ids','person_ids','name','expires'])
114 raise Exception("Slice %s not found (used %s as slicename internally)" % slice_xrn, slicename)
117 # report about the local nodes only
118 nodes = api.plshell.GetNodes(api.plauth, {'node_id':slice['node_ids'],'peer_id':None},
119 ['hostname', 'site_id', 'boot_state', 'last_contact'])
120 site_ids = [node['site_id'] for node in nodes]
121 sites = api.plshell.GetSites(api.plauth, site_ids, ['site_id', 'login_base'])
122 sites_dict = dict ( [ (site['site_id'],site['login_base'] ) for site in sites ] )
125 top_level_status = 'unknown'
127 top_level_status = 'ready'
128 result['geni_urn'] = Xrn(slice_xrn, 'slice').get_urn()
129 result['pl_login'] = slice['name']
130 result['pl_expires'] = datetime.datetime.fromtimestamp(slice['expires']).ctime()
135 res['pl_hostname'] = node['hostname']
136 res['pl_boot_state'] = node['boot_state']
137 res['pl_last_contact'] = node['last_contact']
138 if node['last_contact'] is not None:
139 res['pl_last_contact'] = datetime.datetime.fromtimestamp(node['last_contact']).ctime()
140 res['geni_urn'] = hostname_to_urn(api.hrn, sites_dict[node['site_id']], node['hostname'])
141 if node['boot_state'] == 'boot':
142 res['geni_status'] = 'ready'
144 res['geni_status'] = 'failed'
145 top_level_staus = 'failed'
147 res['geni_error'] = ''
149 resources.append(res)
151 result['geni_status'] = top_level_status
152 result['geni_resources'] = resources
154 #api.logger.info(result)
158 def CreateSliver(api, slice_xrn, creds, rspec_string, users, call_id):
160 Create the sliver[s] (slice) at this aggregate.
161 Verify HRN and initialize the slice record in PLC if necessary.
163 if Callids().already_handled(call_id): return ""
165 reg_objects = __get_registry_objects(slice_xrn, creds, users)
167 (hrn, type) = urn_to_hrn(slice_xrn)
169 aggregate = Aggregate(api)
171 peer = slices.get_peer(hrn)
172 sfa_peer = slices.get_sfa_peer(hrn)
173 registry = api.registries[api.hrn]
174 credential = api.getCredential()
175 (site_id, remote_site_id) = slices.verify_site(registry, credential, hrn,
176 peer, sfa_peer, reg_objects)
178 slice = slices.verify_slice(registry, credential, hrn, site_id,
179 remote_site_id, peer, sfa_peer, reg_objects)
181 nodes = api.plshell.GetNodes(api.plauth, slice['node_ids'], ['hostname'])
182 current_slivers = [node['hostname'] for node in nodes]
183 rspec = parse_rspec(rspec_string)
184 requested_slivers = [str(host) for host in rspec.get_nodes_with_slivers()]
185 # remove nodes not in rspec
186 deleted_nodes = list(set(current_slivers).difference(requested_slivers))
188 # add nodes from rspec
189 added_nodes = list(set(requested_slivers).difference(current_slivers))
193 api.plshell.UnBindObjectFromPeer(api.plauth, 'slice', slice['slice_id'], peer)
195 api.plshell.AddSliceToNodes(api.plauth, slice['name'], added_nodes)
196 api.plshell.DeleteSliceFromNodes(api.plauth, slice['name'], deleted_nodes)
198 # TODO: update slice tags
199 #network.updateSliceTags()
203 api.plshell.BindObjectToPeer(api.plauth, 'slice', slice.id, peer,
206 return aggregate.get_rspec(slice_xrn=slice_xrn, version=RSpecVersion("pg"))
209 def RenewSliver(api, xrn, creds, expiration_time, call_id):
210 if Callids().already_handled(call_id): return True
211 (hrn, type) = urn_to_hrn(xrn)
212 slicename = hrn_to_pl_slicename(hrn)
213 slices = api.plshell.GetSlices(api.plauth, {'name': slicename}, ['slice_id'])
215 raise RecordNotFound(hrn)
217 requested_time = utcparse(expiration_time)
218 record = {'expires': int(time.mktime(requested_time.timetuple()))}
220 api.plshell.UpdateSlice(api.plauth, slice['slice_id'], record)
225 def start_slice(api, xrn, creds):
226 hrn, type = urn_to_hrn(xrn)
227 slicename = hrn_to_pl_slicename(hrn)
228 slices = api.plshell.GetSlices(api.plauth, {'name': slicename}, ['slice_id'])
230 raise RecordNotFound(hrn)
231 slice_id = slices[0]['slice_id']
232 slice_tags = api.plshell.GetSliceTags(api.plauth, {'slice_id': slice_id, 'tagname': 'enabled'}, ['slice_tag_id'])
233 # just remove the tag if it exists
235 api.plshell.DeleteSliceTag(api.plauth, slice_tags[0]['slice_tag_id'])
239 def stop_slice(api, xrn, creds):
240 hrn, type = urn_to_hrn(xrn)
241 slicename = hrn_to_pl_slicename(hrn)
242 slices = api.plshell.GetSlices(api.plauth, {'name': slicename}, ['slice_id'])
244 raise RecordNotFound(hrn)
245 slice_id = slices[0]['slice_id']
246 slice_tags = api.plshell.GetSliceTags(api.plauth, {'slice_id': slice_id, 'tagname': 'enabled'})
248 api.plshell.AddSliceTag(api.plauth, slice_id, 'enabled', '0')
249 elif slice_tags[0]['value'] != "0":
250 tag_id = attributes[0]['slice_tag_id']
251 api.plshell.UpdateSliceTag(api.plauth, tag_id, '0')
254 def reset_slice(api, xrn):
255 # XX not implemented at this interface
258 def DeleteSliver(api, xrn, creds, call_id):
259 if Callids().already_handled(call_id): return ""
260 (hrn, type) = urn_to_hrn(xrn)
261 slicename = hrn_to_pl_slicename(hrn)
262 slices = api.plshell.GetSlices(api.plauth, {'name': slicename})
267 # determine if this is a peer slice
268 peer = peers.get_peer(api, hrn)
271 api.plshell.UnBindObjectFromPeer(api.plauth, 'slice', slice['slice_id'], peer)
272 api.plshell.DeleteSliceFromNodes(api.plauth, slicename, slice['node_ids'])
275 api.plshell.BindObjectToPeer(api.plauth, 'slice', slice['slice_id'], peer, slice['peer_slice_id'])
278 # xxx Thierry : caching at the aggregate level sounds wrong...
281 def ListSlices(api, creds, call_id):
282 if Callids().already_handled(call_id): return []
283 # look in cache first
284 if caching and api.cache:
285 slices = api.cache.get('slices')
290 slices = api.plshell.GetSlices(api.plauth, {'peer_id': None}, ['name'])
291 slice_hrns = [slicename_to_hrn(api.hrn, slice['name']) for slice in slices]
292 slice_urns = [hrn_to_urn(slice_hrn, 'slice') for slice_hrn in slice_hrns]
295 if caching and api.cache:
296 api.cache.add('slices', slice_urns)
300 def ListResources(api, creds, options,call_id):
301 if Callids().already_handled(call_id): return ""
302 # get slice's hrn from options
303 xrn = options.get('geni_slice_urn', '')
304 (hrn, type) = urn_to_hrn(xrn)
306 # get the rspec's return format from options
307 rspec_version = RSpecVersion(options.get('rspec_version', 'SFA 1'))
308 version_string = "rspec_%s_%s" % (rspec_version.format, rspec_version.version)
310 # look in cache first
311 if caching and api.cache and not xrn:
312 rspec = api.cache.get(version_string)
314 api.logger.info("aggregate.ListResources: returning cached value for hrn %s"%hrn)
317 aggregate = Aggregate(api)
320 # get this rspec for the specified slice
321 rspec = aggregate.get_rspec(slice_xrn=hrn, version=rspec_version)
323 # generate rspec in both pg and sfa formats
324 rspec = aggregate.get_rspec(version=rspec_version)
327 if caching and api.cache and not xrn:
328 api.cache.add(version_string, rspec)
333 def get_ticket(api, xrn, creds, rspec, users):
335 reg_objects = __get_registry_objects(xrn, creds, users)
337 slice_hrn, type = urn_to_hrn(xrn)
339 peer = slices.get_peer(slice_hrn)
340 sfa_peer = slices.get_sfa_peer(slice_hrn)
342 # get the slice record
343 registry = api.registries[api.hrn]
344 credential = api.getCredential()
345 records = registry.Resolve(xrn, credential)
347 # similar to CreateSliver, we must verify that the required records exist
348 # at this aggregate before we can issue a ticket
349 site_id, remote_site_id = slices.verify_site(registry, credential, slice_hrn,
350 peer, sfa_peer, reg_objects)
351 slice = slices.verify_slice(registry, credential, slice_hrn, site_id,
352 remote_site_id, peer, sfa_peer, reg_objects)
354 # make sure we get a local slice record
356 for tmp_record in records:
357 if tmp_record['type'] == 'slice' and \
358 not tmp_record['peer_authority']:
359 record = SliceRecord(dict=tmp_record)
361 raise RecordNotFound(slice_hrn)
364 slivers = Slices(api).get_slivers(slice_hrn)
366 raise SliverDoesNotExist(slice_hrn)
371 'timestamp': int(time.time()),
372 'initscripts': initscripts,
377 object_gid = record.get_gid_object()
378 new_ticket = SfaTicket(subject = object_gid.get_subject())
379 new_ticket.set_gid_caller(api.auth.client_gid)
380 new_ticket.set_gid_object(object_gid)
381 new_ticket.set_issuer(key=api.key, subject=api.hrn)
382 new_ticket.set_pubkey(object_gid.get_pubkey())
383 new_ticket.set_attributes(data)
384 new_ticket.set_rspec(rspec)
385 #new_ticket.set_parent(api.auth.hierarchy.get_auth_ticket(auth_hrn))
389 return new_ticket.save_to_string(save_parents=True)
396 rspec = ListResources(api, "plc.princeton.sapan", None, 'pl_test_sapan')
397 #rspec = ListResources(api, "plc.princeton.coblitz", None, 'pl_test_coblitz')
398 #rspec = ListResources(api, "plc.pl.sirius", None, 'pl_test_sirius')
401 f = open(sys.argv[1])
404 CreateSliver(api, "plc.princeton.sapan", xml, 'CreateSliver_sapan')
406 if __name__ == "__main__":