8 from types import StringTypes
10 from sfa.util.faults import *
11 from sfa.util.xrn import get_authority, hrn_to_urn, urn_to_hrn, Xrn, urn_to_sliver_id
12 from sfa.util.plxrn import slicename_to_hrn, hrn_to_pl_slicename, hostname_to_urn
13 from sfa.util.rspec import *
14 from sfa.util.specdict import *
15 from sfa.util.record import SfaRecord
16 from sfa.util.policy import Policy
17 from sfa.util.record import *
18 from sfa.util.sfaticket import SfaTicket
19 from sfa.plc.slices import Slices
20 from sfa.trust.credential import Credential
21 import sfa.plc.peers as peers
22 from sfa.plc.network import *
23 from sfa.plc.api import SfaAPI
24 from sfa.plc.aggregate import Aggregate
25 from sfa.plc.slices import *
26 from sfa.util.version import version_core
27 from sfa.rspecs.rspec_version import RSpecVersion
28 from sfa.rspecs.sfa_rspec import sfa_rspec_version
29 from sfa.rspecs.pg_rspec import pg_rspec_ad_version, pg_rspec_request_version
30 from sfa.rspecs.rspec_parser import parse_rspec
31 from sfa.util.sfatime import utcparse
32 from sfa.util.callids import Callids
36 request_rspec_versions = [dict(pg_rspec_request_version), dict(sfa_rspec_version)]
37 ad_rspec_versions = [dict(pg_rspec_ad_version), dict(sfa_rspec_version)]
38 version_more = {'interface':'aggregate',
41 'request_rspec_versions': request_rspec_versions,
42 'ad_rspec_versions': ad_rspec_versions,
43 'default_ad_rspec': dict(sfa_rspec_version)
45 return version_core(version_more)
47 def __get_registry_objects(slice_xrn, creds, users):
51 hrn, type = urn_to_hrn(slice_xrn)
53 hrn_auth = get_authority(hrn)
55 # Build up objects that an SFA registry would return if SFA
56 # could contact the slice's registry directly
60 # dont allow special characters in the site login base
61 #only_alphanumeric = re.compile('[^a-zA-Z0-9]+')
62 #login_base = only_alphanumeric.sub('', hrn_auth[:20]).lower()
63 slicename = hrn_to_pl_slicename(hrn)
64 login_base = slicename.split('_')[0]
68 site['name'] = 'geni.%s' % login_base
69 site['enabled'] = True
70 site['max_slices'] = 100
73 # Is it okay if this login base is the same as one already at this myplc site?
74 # Do we need uniqueness? Should use hrn_auth instead of just the leaf perhaps?
75 site['login_base'] = login_base
76 site['abbreviated_name'] = login_base
77 site['max_slivers'] = 1000
78 reg_objects['site'] = site
82 # get_expiration always returns a normalized datetime - no need to utcparse
83 extime = Credential(string=creds[0]).get_expiration()
84 # If the expiration time is > 60 days from now, set the expiration time to 60 days from now
85 if extime > datetime.datetime.utcnow() + datetime.timedelta(days=60):
86 extime = datetime.datetime.utcnow() + datetime.timedelta(days=60)
87 slice['expires'] = int(time.mktime(extime.timetuple()))
89 slice['name'] = hrn_to_pl_slicename(hrn)
91 slice['description'] = hrn
93 reg_objects['slice_record'] = slice
95 reg_objects['users'] = {}
98 hrn, _ = urn_to_hrn(user['urn'])
99 user['email'] = hrn_to_pl_slicename(hrn) + "@geni.net"
100 user['first_name'] = hrn
101 user['last_name'] = hrn
102 reg_objects['users'][user['email']] = user
106 def __get_hostnames(nodes):
109 hostnames.append(node.hostname)
112 def SliverStatus(api, slice_xrn, creds, call_id):
113 if Callids().already_handled(call_id): return {}
115 (hrn, type) = urn_to_hrn(slice_xrn)
116 # find out where this slice is currently running
118 slicename = hrn_to_pl_slicename(hrn)
120 slices = api.plshell.GetSlices(api.plauth, [slicename], ['slice_id', 'node_ids','person_ids','name','expires'])
122 raise Exception("Slice %s not found (used %s as slicename internally)" % (slice_xrn, slicename))
125 # report about the local nodes only
126 nodes = api.plshell.GetNodes(api.plauth, {'node_id':slice['node_ids'],'peer_id':None},
127 ['node_id', 'hostname', 'site_id', 'boot_state', 'last_contact'])
128 site_ids = [node['site_id'] for node in nodes]
129 sites = api.plshell.GetSites(api.plauth, site_ids, ['site_id', 'login_base'])
130 sites_dict = dict ( [ (site['site_id'],site['login_base'] ) for site in sites ] )
133 top_level_status = 'unknown'
135 top_level_status = 'ready'
136 slice_urn = Xrn(slice_xrn, 'slice').get_urn()
137 result['geni_urn'] = slice_urn
138 result['pl_login'] = slice['name']
139 result['pl_expires'] = datetime.datetime.fromtimestamp(slice['expires']).ctime()
144 res['pl_hostname'] = node['hostname']
145 res['pl_boot_state'] = node['boot_state']
146 res['pl_last_contact'] = node['last_contact']
147 if node['last_contact'] is not None:
148 res['pl_last_contact'] = datetime.datetime.fromtimestamp(node['last_contact']).ctime()
149 sliver_id = urn_to_sliver_id(slice_urn, slice['slice_id'], node['node_id'])
150 res['geni_urn'] = sliver_id
151 if node['boot_state'] == 'boot':
152 res['geni_status'] = 'ready'
154 res['geni_status'] = 'failed'
155 top_level_staus = 'failed'
157 res['geni_error'] = ''
159 resources.append(res)
161 result['geni_status'] = top_level_status
162 result['geni_resources'] = resources
164 #api.logger.info(result)
168 def CreateSliver(api, slice_xrn, creds, rspec_string, users, call_id):
170 Create the sliver[s] (slice) at this aggregate.
171 Verify HRN and initialize the slice record in PLC if necessary.
173 if Callids().already_handled(call_id): return ""
175 reg_objects = __get_registry_objects(slice_xrn, creds, users)
177 (hrn, type) = urn_to_hrn(slice_xrn)
179 aggregate = Aggregate(api)
181 peer = slices.get_peer(hrn)
182 sfa_peer = slices.get_sfa_peer(hrn)
183 registry = api.registries[api.hrn]
184 credential = api.getCredential()
185 (site_id, remote_site_id) = slices.verify_site(registry, credential, hrn,
186 peer, sfa_peer, reg_objects)
188 slice = slices.verify_slice(registry, credential, hrn, site_id,
189 remote_site_id, peer, sfa_peer, reg_objects)
191 nodes = api.plshell.GetNodes(api.plauth, slice['node_ids'], ['hostname'])
192 current_slivers = [node['hostname'] for node in nodes]
193 rspec = parse_rspec(rspec_string)
194 requested_slivers = [str(host) for host in rspec.get_nodes_with_slivers()]
195 # remove nodes not in rspec
196 deleted_nodes = list(set(current_slivers).difference(requested_slivers))
198 # add nodes from rspec
199 added_nodes = list(set(requested_slivers).difference(current_slivers))
201 # get sliver attributes
202 requested_slice_attributes = rspec.get_slice_attributes()
203 removed_slice_attributes = []
204 existing_slice_attributes = []
205 for slice_tag in api.plshell.GetSliceTags(api.plauth, {'slice_id': slice['slice_id']}):
206 attribute_found=False
207 for requested_attribute in requested_slice_attributes:
208 if requested_attribute['name'] == slice_tag['tagname'] and \
209 requested_attribute['value'] == slice_tag['value']:
212 if not attribute_found:
213 removed_slice_attributes.append(slice_tag)
215 existing_slice_attributes.append(slice_tag)
219 api.plshell.UnBindObjectFromPeer(api.plauth, 'slice', slice['slice_id'], peer)
221 api.plshell.AddSliceToNodes(api.plauth, slice['name'], added_nodes)
222 api.plshell.DeleteSliceFromNodes(api.plauth, slice['name'], deleted_nodes)
223 # remove stale attributes
224 for attribute in removed_slice_attributes:
226 api.plshell.DeleteSliceTag(api.plauth, attribute['slice_tag_id'])
228 api.logger.warn('Failed to remove sliver attribute. name: %s, value: %s, node_id: %s\nCause:%s'\
229 % (name, value, node_id, str(e)))
231 # add requested_attributes
232 for attribute in requested_slice_attributes:
234 name, value, node_id = attribute['name'], attribute['value'], attribute.get('node_id', None)
235 api.plshell.AddSliceTag(api.plauth, slice['name'], name, value, node_id)
237 api.logger.warn('Failed to add sliver attribute. name: %s, value: %s, node_id: %s\nCause:%s'\
238 % (name, value, node_id, str(e)))
242 api.plshell.BindObjectToPeer(api.plauth, 'slice', slice['slice_id'], peer,
245 return aggregate.get_rspec(slice_xrn=slice_xrn, version=rspec.version)
248 def RenewSliver(api, xrn, creds, expiration_time, call_id):
249 if Callids().already_handled(call_id): return True
250 (hrn, type) = urn_to_hrn(xrn)
251 slicename = hrn_to_pl_slicename(hrn)
252 slices = api.plshell.GetSlices(api.plauth, {'name': slicename}, ['slice_id'])
254 raise RecordNotFound(hrn)
256 requested_time = utcparse(expiration_time)
257 record = {'expires': int(time.mktime(requested_time.timetuple()))}
259 api.plshell.UpdateSlice(api.plauth, slice['slice_id'], record)
264 def start_slice(api, xrn, creds):
265 hrn, type = urn_to_hrn(xrn)
266 slicename = hrn_to_pl_slicename(hrn)
267 slices = api.plshell.GetSlices(api.plauth, {'name': slicename}, ['slice_id'])
269 raise RecordNotFound(hrn)
270 slice_id = slices[0]['slice_id']
271 slice_tags = api.plshell.GetSliceTags(api.plauth, {'slice_id': slice_id, 'tagname': 'enabled'}, ['slice_tag_id'])
272 # just remove the tag if it exists
274 api.plshell.DeleteSliceTag(api.plauth, slice_tags[0]['slice_tag_id'])
278 def stop_slice(api, xrn, creds):
279 hrn, type = urn_to_hrn(xrn)
280 slicename = hrn_to_pl_slicename(hrn)
281 slices = api.plshell.GetSlices(api.plauth, {'name': slicename}, ['slice_id'])
283 raise RecordNotFound(hrn)
284 slice_id = slices[0]['slice_id']
285 slice_tags = api.plshell.GetSliceTags(api.plauth, {'slice_id': slice_id, 'tagname': 'enabled'})
287 api.plshell.AddSliceTag(api.plauth, slice_id, 'enabled', '0')
288 elif slice_tags[0]['value'] != "0":
289 tag_id = attributes[0]['slice_tag_id']
290 api.plshell.UpdateSliceTag(api.plauth, tag_id, '0')
293 def reset_slice(api, xrn):
294 # XX not implemented at this interface
297 def DeleteSliver(api, xrn, creds, call_id):
298 if Callids().already_handled(call_id): return ""
299 (hrn, type) = urn_to_hrn(xrn)
300 slicename = hrn_to_pl_slicename(hrn)
301 slices = api.plshell.GetSlices(api.plauth, {'name': slicename})
306 # determine if this is a peer slice
307 peer = peers.get_peer(api, hrn)
310 api.plshell.UnBindObjectFromPeer(api.plauth, 'slice', slice['slice_id'], peer)
311 api.plshell.DeleteSliceFromNodes(api.plauth, slicename, slice['node_ids'])
314 api.plshell.BindObjectToPeer(api.plauth, 'slice', slice['slice_id'], peer, slice['peer_slice_id'])
317 # xxx Thierry : caching at the aggregate level sounds wrong...
320 def ListSlices(api, creds, call_id):
321 if Callids().already_handled(call_id): return []
322 # look in cache first
323 if caching and api.cache:
324 slices = api.cache.get('slices')
329 slices = api.plshell.GetSlices(api.plauth, {'peer_id': None}, ['name'])
330 slice_hrns = [slicename_to_hrn(api.hrn, slice['name']) for slice in slices]
331 slice_urns = [hrn_to_urn(slice_hrn, 'slice') for slice_hrn in slice_hrns]
334 if caching and api.cache:
335 api.cache.add('slices', slice_urns)
339 def ListResources(api, creds, options,call_id):
340 if Callids().already_handled(call_id): return ""
341 # get slice's hrn from options
342 xrn = options.get('geni_slice_urn', '')
343 (hrn, type) = urn_to_hrn(xrn)
345 # get the rspec's return format from options
346 rspec_version = RSpecVersion(options.get('rspec_version'))
347 version_string = "rspec_%s" % (rspec_version.get_version_name())
349 #panos adding the info option to the caching key (can be improved)
350 if options.get('info'):
351 version_string = version_string + "_"+options.get('info', 'default')
353 # look in cache first
354 if caching and api.cache and not xrn:
355 rspec = api.cache.get(version_string)
357 api.logger.info("aggregate.ListResources: returning cached value for hrn %s"%hrn)
360 #aggregate = Aggregate(api)
361 #panos: passing user-defined options
362 #print "manager options = ",options
363 aggregate = Aggregate(api, options)
365 rspec = aggregate.get_rspec(slice_xrn=xrn, version=rspec_version)
368 if caching and api.cache and not xrn:
369 api.cache.add(version_string, rspec)
374 def get_ticket(api, xrn, creds, rspec, users):
376 reg_objects = __get_registry_objects(xrn, creds, users)
378 slice_hrn, type = urn_to_hrn(xrn)
380 peer = slices.get_peer(slice_hrn)
381 sfa_peer = slices.get_sfa_peer(slice_hrn)
383 # get the slice record
384 registry = api.registries[api.hrn]
385 credential = api.getCredential()
386 records = registry.Resolve(xrn, credential)
388 # similar to CreateSliver, we must verify that the required records exist
389 # at this aggregate before we can issue a ticket
390 site_id, remote_site_id = slices.verify_site(registry, credential, slice_hrn,
391 peer, sfa_peer, reg_objects)
392 slice = slices.verify_slice(registry, credential, slice_hrn, site_id,
393 remote_site_id, peer, sfa_peer, reg_objects)
395 # make sure we get a local slice record
397 for tmp_record in records:
398 if tmp_record['type'] == 'slice' and \
399 not tmp_record['peer_authority']:
400 record = SliceRecord(dict=tmp_record)
402 raise RecordNotFound(slice_hrn)
405 slivers = Slices(api).get_slivers(slice_hrn)
407 raise SliverDoesNotExist(slice_hrn)
412 'timestamp': int(time.time()),
413 'initscripts': initscripts,
418 object_gid = record.get_gid_object()
419 new_ticket = SfaTicket(subject = object_gid.get_subject())
420 new_ticket.set_gid_caller(api.auth.client_gid)
421 new_ticket.set_gid_object(object_gid)
422 new_ticket.set_issuer(key=api.key, subject=api.hrn)
423 new_ticket.set_pubkey(object_gid.get_pubkey())
424 new_ticket.set_attributes(data)
425 new_ticket.set_rspec(rspec)
426 #new_ticket.set_parent(api.auth.hierarchy.get_auth_ticket(auth_hrn))
430 return new_ticket.save_to_string(save_parents=True)
437 rspec = ListResources(api, "plc.princeton.sapan", None, 'pl_test_sapan')
438 #rspec = ListResources(api, "plc.princeton.coblitz", None, 'pl_test_coblitz')
439 #rspec = ListResources(api, "plc.pl.sirius", None, 'pl_test_sirius')
442 f = open(sys.argv[1])
445 CreateSliver(api, "plc.princeton.sapan", xml, 'CreateSliver_sapan')
447 if __name__ == "__main__":