1 from types import StringTypes
2 from collections import defaultdict
4 from sfa.util.sfatime import utcparse, datetime_to_epoch
5 from sfa.util.sfalogging import logger
6 from sfa.util.xrn import Xrn, get_leaf, get_authority, urn_to_hrn
7 from sfa.rspecs.rspec import RSpec
8 from sfa.planetlab.vlink import VLink
9 from sfa.planetlab.topology import Topology
10 from sfa.planetlab.plxrn import PlXrn, hrn_to_pl_slicename
11 from sfa.storage.model import SliverAllocation
12 from sfa.storage.alchemy import dbsession
18 rspec_to_slice_tag = {'max_rate':'net_max_rate'}
20 def __init__(self, driver):
23 def get_slivers(self, xrn, node=None):
24 hrn, type = urn_to_hrn(xrn)
26 slice_name = hrn_to_pl_slicename(hrn)
27 # XX Should we just call PLCAPI.GetSliceTicket(slice_name) instead
28 # of doing all of this?
29 #return self.driver.shell.GetSliceTicket(self.auth, slice_name)
31 # from PLCAPI.GetSlivers.get_slivers()
32 slice_fields = ['slice_id', 'name', 'instantiation', 'expires', 'person_ids', 'slice_tag_ids']
33 slices = self.driver.shell.GetSlices(slice_name, slice_fields)
34 # Build up list of users and slice attributes
36 all_slice_tag_ids = set()
38 person_ids.update(slice['person_ids'])
39 all_slice_tag_ids.update(slice['slice_tag_ids'])
40 person_ids = list(person_ids)
41 all_slice_tag_ids = list(all_slice_tag_ids)
42 # Get user information
43 all_persons_list = self.driver.shell.GetPersons({'person_id':person_ids,'enabled':True}, ['person_id', 'enabled', 'key_ids'])
45 for person in all_persons_list:
46 all_persons[person['person_id']] = person
48 # Build up list of keys
50 for person in all_persons.values():
51 key_ids.update(person['key_ids'])
52 key_ids = list(key_ids)
53 # Get user account keys
54 all_keys_list = self.driver.shell.GetKeys(key_ids, ['key_id', 'key', 'key_type'])
56 for key in all_keys_list:
57 all_keys[key['key_id']] = key
58 # Get slice attributes
59 all_slice_tags_list = self.driver.shell.GetSliceTags(all_slice_tag_ids)
61 for slice_tag in all_slice_tags_list:
62 all_slice_tags[slice_tag['slice_tag_id']] = slice_tag
67 for person_id in slice['person_ids']:
68 if person_id in all_persons:
69 person = all_persons[person_id]
70 if not person['enabled']:
72 for key_id in person['key_ids']:
73 if key_id in all_keys:
74 key = all_keys[key_id]
75 keys += [{'key_type': key['key_type'],
78 # All (per-node and global) attributes for this slice
80 for slice_tag_id in slice['slice_tag_ids']:
81 if slice_tag_id in all_slice_tags:
82 slice_tags.append(all_slice_tags[slice_tag_id])
83 # Per-node sliver attributes take precedence over global
84 # slice attributes, so set them first.
85 # Then comes nodegroup slice attributes
86 # Followed by global slice attributes
87 sliver_attributes = []
90 for sliver_attribute in filter(lambda a: a['node_id'] == node['node_id'], slice_tags):
91 sliver_attributes.append(sliver_attribute['tagname'])
92 attributes.append({'tagname': sliver_attribute['tagname'],
93 'value': sliver_attribute['value']})
95 # set nodegroup slice attributes
96 for slice_tag in filter(lambda a: a['nodegroup_id'] in node['nodegroup_ids'], slice_tags):
97 # Do not set any nodegroup slice attributes for
98 # which there is at least one sliver attribute
100 if slice_tag not in slice_tags:
101 attributes.append({'tagname': slice_tag['tagname'],
102 'value': slice_tag['value']})
104 for slice_tag in filter(lambda a: a['node_id'] is None, slice_tags):
105 # Do not set any global slice attributes for
106 # which there is at least one sliver attribute
108 if slice_tag['tagname'] not in sliver_attributes:
109 attributes.append({'tagname': slice_tag['tagname'],
110 'value': slice_tag['value']})
112 # XXX Sanity check; though technically this should be a system invariant
113 # checked with an assertion
114 if slice['expires'] > MAXINT: slice['expires']= MAXINT
118 'name': slice['name'],
119 'slice_id': slice['slice_id'],
120 'instantiation': slice['instantiation'],
121 'expires': slice['expires'],
123 'attributes': attributes
128 def get_peer(self, xrn):
129 hrn, type = urn_to_hrn(xrn)
130 # Becaues of myplc federation, we first need to determine if this
131 # slice belongs to out local plc or a myplc peer. We will assume it
132 # is a local site, unless we find out otherwise
135 # get this slice's authority (site)
136 slice_authority = get_authority(hrn)
138 # get this site's authority (sfa root authority or sub authority)
139 site_authority = get_authority(slice_authority).lower()
141 # check if we are already peered with this site_authority, if so
142 peers = self.driver.shell.GetPeers({}, ['peer_id', 'peername', 'shortname', 'hrn_root'])
143 for peer_record in peers:
144 names = [name.lower() for name in peer_record.values() if isinstance(name, StringTypes)]
145 if site_authority in names:
150 def get_sfa_peer(self, xrn):
151 hrn, type = urn_to_hrn(xrn)
153 # return the authority for this hrn or None if we are the authority
155 slice_authority = get_authority(hrn)
156 site_authority = get_authority(slice_authority)
158 if site_authority != self.driver.hrn:
159 sfa_peer = site_authority
163 def verify_slice_leases(self, slice, requested_leases, kept_leases, peer):
165 leases = self.driver.shell.GetLeases({'name':slice['name']}, ['lease_id'])
166 grain = self.driver.shell.GetLeaseGranularity()
167 current_leases = [lease['lease_id'] for lease in leases]
168 deleted_leases = list(set(current_leases).difference(kept_leases))
172 self.driver.shell.UnBindObjectFromPeer('slice', slice['slice_id'], peer['shortname'])
173 deleted=self.driver.shell.DeleteLeases(deleted_leases)
174 for lease in requested_leases:
175 added=self.driver.shell.AddLeases(lease['hostname'], slice['name'], int(lease['start_time']), int(lease['duration']) * grain + int(lease['start_time']))
178 logger.log_exc('Failed to add/remove slice leases')
183 def verify_slice_nodes(self, slice, rspec_nodes, peer):
186 for node in rspec_nodes:
188 client_id = node.get('client_id')
189 if node.get('component_name'):
190 hostname = node.get('component_name').strip()
191 elif node.get('component_id'):
192 hostname = xrn_to_hostname(node.get('component_id').strip())
194 slivers[hostname] = client_id
196 nodes = self.driver.shell.GetNodes(slice['node_ids'], ['node_id', 'hostname', 'interface_ids'])
197 current_slivers = [node['hostname'] for node in nodes]
199 # remove nodes not in rspec
200 deleted_nodes = list(set(current_slivers).difference(slivers.keys()))
202 # add nodes from rspec
203 added_nodes = list(set(slivers.keys()).difference(current_slivers))
207 self.driver.shell.UnBindObjectFromPeer('slice', slice['slice_id'], peer['shortname'])
208 self.driver.shell.AddSliceToNodes(slice['name'], added_nodes)
209 self.driver.shell.DeleteSliceFromNodes(slice['name'], deleted_nodes)
212 logger.log_exc('Failed to add/remove slice from nodes')
214 slices = self.driver.shell.GetSlices(slice['name'], ['node_ids'])
215 resulting_nodes = self.driver.shell.GetNodes(slices[0]['node_ids'])
217 # update sliver allocations
218 for node in resulting_nodes:
219 client_id = slivers[node['hostname']]
220 logger.info(client_id)
221 sliver_hrn = '%s.%s-%s' % (self.driver.hrn, slice['slice_id'], node['node_id'])
222 sliver_id = Xrn(sliver_hrn, type='sliver').urn
223 record = SliverAllocation(sliver_id=sliver_id, client_id=client_id, allocation_state='geni_allocated')
225 return resulting_nodes
227 def free_egre_key(self):
229 for tag in self.driver.shell.GetSliceTags({'tagname': 'egre_key'}):
230 used.add(int(tag['value']))
232 for i in range(1, 256):
237 raise KeyError("No more EGRE keys available")
241 def verify_slice_links(self, slice, requested_links, nodes):
243 if not requested_links:
246 # exit if links are not supported here
247 topology = Topology()
251 # build dict of nodes
255 nodes_dict[node['node_id']] = node
256 interface_ids.extend(node['interface_ids'])
257 # build dict of interfaces
258 interfaces = self.driver.shell.GetInterfaces(interface_ids)
260 for interface in interfaces:
261 interfaces_dict[interface['interface_id']] = interface
266 slice_tags.append({'name': 'egre_key', 'value': self.free_egre_key()})
269 slice_tags.append({'name': 'netns', 'value': '1'})
272 # need to update the attribute string?
273 slice_tags.append({'name': 'capabilities', 'value': 'CAP_NET_ADMIN'})
275 for link in requested_links:
276 # get the ip address of the first node in the link
277 ifname1 = Xrn(link['interface1']['component_id']).get_leaf()
278 ifname_parts = ifname1.split(':')
279 node_raw = ifname_parts[0]
281 if len(ifname_parts) > 1:
282 device = ifname_parts[1]
283 node_id = int(node_raw.replace('node', ''))
284 node = nodes_dict[node_id]
285 if1 = interfaces_dict[node['interface_ids'][0]]
287 topo_rspec = VLink.get_topo_rspec(link, ipaddr)
289 slice_tags.append({'name': 'topo_rspec', 'value': str([topo_rspec]), 'node_id': node_id})
291 slice_tags.append({'name': 'vini_topo', 'value': 'manual', 'node_id': node_id})
292 #self.driver.shell.AddSliceTag(slice['name'], 'topo_rspec', str([topo_rspec]), node_id)
294 self.verify_slice_attributes(slice, slice_tags, {'append': True}, admin=True)
298 def handle_peer(self, site, slice, persons, peer):
303 self.driver.shell.BindObjectToPeer('site', site['site_id'], peer['shortname'], slice['site_id'])
305 self.driver.shell.DeleteSite(site['site_id'])
311 self.driver.shell.BindObjectToPeer('slice', slice['slice_id'], peer['shortname'], slice['slice_id'])
313 self.driver.shell.DeleteSlice(slice['slice_id'])
317 for person in persons:
319 self.driver.shell.BindObjectToPeer('person',
320 person['person_id'], peer['shortname'], person['peer_person_id'])
322 for (key, remote_key_id) in zip(person['keys'], person['key_ids']):
324 self.driver.shell.BindObjectToPeer( 'key', key['key_id'], peer['shortname'], remote_key_id)
326 self.driver.shell.DeleteKey(key['key_id'])
327 logger("failed to bind key: %s to peer: %s " % (key['key_id'], peer['shortname']))
329 self.driver.shell.DeletePerson(person['person_id'])
334 def verify_site(self, slice_xrn, slice_record={}, peer=None, sfa_peer=None, options={}):
335 (slice_hrn, type) = urn_to_hrn(slice_xrn)
336 site_hrn = get_authority(slice_hrn)
337 # login base can't be longer than 20 characters
338 slicename = hrn_to_pl_slicename(slice_hrn)
339 authority_name = slicename.split('_')[0]
340 login_base = authority_name[:20]
341 sites = self.driver.shell.GetSites(login_base)
343 # create new site record
344 site = {'name': 'geni.%s' % authority_name,
345 'abbreviated_name': authority_name,
346 'login_base': login_base,
350 'peer_site_id': None}
352 site['peer_site_id'] = slice_record.get('site_id', None)
353 site['site_id'] = self.driver.shell.AddSite(site)
354 # exempt federated sites from monitor policies
355 self.driver.shell.AddSiteTag(site['site_id'], 'exempt_site_until', "20200101")
357 # # is this still necessary?
358 # # add record to the local registry
359 # if sfa_peer and slice_record:
360 # peer_dict = {'type': 'authority', 'hrn': site_hrn, \
361 # 'peer_authority': sfa_peer, 'pointer': site['site_id']}
362 # self.registry.register_peer_object(self.credential, peer_dict)
366 # unbind from peer so we can modify if necessary. Will bind back later
367 self.driver.shell.UnBindObjectFromPeer('site', site['site_id'], peer['shortname'])
371 def verify_slice(self, slice_hrn, slice_record, peer, sfa_peer, options={}):
372 slicename = hrn_to_pl_slicename(slice_hrn)
373 parts = slicename.split("_")
374 login_base = parts[0]
375 slices = self.driver.shell.GetSlices([slicename])
377 slice = {'name': slicename,
379 'description': 'No Description'}
381 slice['slice_id'] = self.driver.shell.AddSlice(slice)
382 slice['node_ids'] = []
383 slice['person_ids'] = []
384 if peer and slice_record:
385 slice['peer_slice_id'] = slice_record.get('slice_id', None)
388 if peer and slice_record:
389 slice['peer_slice_id'] = slice_record.get('slice_id', None)
390 # unbind from peer so we can modify if necessary. Will bind back later
391 self.driver.shell.UnBindObjectFromPeer('slice', slice['slice_id'], peer['shortname'])
392 #Update existing record (e.g. expires field) it with the latest info.
393 if slice_record and slice_record.get('expires'):
394 requested_expires = int(datetime_to_epoch(utcparse(slice_record['expires'])))
395 if requested_expires and slice['expires'] != requested_expires:
396 self.driver.shell.UpdateSlice( slice['slice_id'], {'expires' : requested_expires})
400 #def get_existing_persons(self, users):
401 def verify_persons(self, slice_hrn, slice_record, users, peer, sfa_peer, options={}):
403 users_by_site = defaultdict(list)
406 user['urn'] = user['urn'].lower()
407 hrn, type = urn_to_hrn(user['urn'])
408 username = get_leaf(hrn)
409 login_base = PlXrn(xrn=user['urn']).pl_login_base()
410 user['username'] = username
411 user['site'] = login_base
414 user['email'] = user['email'].lower()
415 users_by_email[user['email']] = user
416 users_dict[user['email']] = user
418 users_by_site[user['site']].append(user)
420 # start building a list of existing users
421 existing_user_ids = []
422 existing_user_ids_filter = []
424 existing_user_ids_filter.extend(users_by_email.keys())
426 for login_base in users_by_site:
427 users = users_by_site[login_base]
429 existing_user_ids_filter.append(user['username']+'@geni.net')
430 if existing_user_ids_filter:
431 # get existing users by email
432 existing_users = self.driver.shell.GetPersons({'email': existing_user_ids_filter},
433 ['person_id', 'key_ids', 'email'])
434 existing_user_ids.extend([user['email'] for user in existing_users])
437 # get a list of user sites (based on requeste user urns
438 site_list = self.driver.shell.GetSites(users_by_site.keys(), \
439 ['site_id', 'login_base', 'person_ids'])
440 # get all existing users at these sites
443 for site in site_list:
444 sites[site['site_id']] = site
445 site_user_ids.extend(site['person_ids'])
447 existing_site_persons_list = self.driver.shell.GetPersons(site_user_ids,
448 ['person_id', 'key_ids', 'email', 'site_ids'])
450 # all requested users are either existing users or new (added) users
451 for login_base in users_by_site:
452 requested_site_users = users_by_site[login_base]
453 for requested_user in requested_site_users:
455 for existing_user in existing_site_persons_list:
456 for site_id in existing_user['site_ids']:
458 site = sites[site_id]
459 if login_base == site['login_base'] and \
460 existing_user['email'].startswith(requested_user['username']+'@'):
461 existing_user_ids.append(existing_user['email'])
462 requested_user['email'] = existing_user['email']
463 users_dict[existing_user['email']] = requested_user
469 if user_found == False:
470 fake_email = requested_user['username'] + '@geni.net'
471 requested_user['email'] = fake_email
472 users_dict[fake_email] = requested_user
474 # requested slice users
475 requested_user_ids = users_dict.keys()
476 # existing slice users
477 existing_slice_users_filter = {'person_id': slice_record.get('person_ids', [])}
478 existing_slice_users = self.driver.shell.GetPersons(existing_slice_users_filter,
479 ['person_id', 'key_ids', 'email'])
480 existing_slice_user_ids = [user['email'] for user in existing_slice_users]
482 # users to be added, removed or updated
483 added_user_ids = set(requested_user_ids).difference(existing_user_ids)
484 added_slice_user_ids = set(requested_user_ids).difference(existing_slice_user_ids)
485 removed_user_ids = set(existing_slice_user_ids).difference(requested_user_ids)
486 updated_user_ids = set(existing_slice_user_ids).intersection(requested_user_ids)
488 # Remove stale users (only if we are not appending).
490 append = options.get('append', True)
492 for removed_user_id in removed_user_ids:
493 self.driver.shell.DeletePersonFromSlice(removed_user_id, slice_record['name'])
494 # update_existing users
495 updated_users_list = [user for user in users_dict.values() if user['email'] in \
497 self.verify_keys(existing_slice_users, updated_users_list, peer, options)
501 for added_user_id in added_user_ids:
502 added_user = users_dict[added_user_id]
503 hrn, type = urn_to_hrn(added_user['urn'])
505 'first_name': added_user.get('first_name', hrn),
506 'last_name': added_user.get('last_name', hrn),
507 'email': added_user_id,
508 'peer_person_id': None,
510 'key_ids': added_user.get('key_ids', []),
512 person['person_id'] = self.driver.shell.AddPerson(person)
514 person['peer_person_id'] = added_user['person_id']
515 added_persons.append(person)
518 self.driver.shell.UpdatePerson(person['person_id'], {'enabled': True})
521 self.driver.shell.AddPersonToSite(added_user_id, added_user['site'])
523 for key_string in added_user.get('keys', []):
524 key = {'key':key_string, 'key_type':'ssh'}
525 key['key_id'] = self.driver.shell.AddPersonKey(person['person_id'], key)
526 person['keys'].append(key)
528 # add the registry record
530 # peer_dict = {'type': 'user', 'hrn': hrn, 'peer_authority': sfa_peer, \
531 # 'pointer': person['person_id']}
532 # self.registry.register_peer_object(self.credential, peer_dict)
534 for added_slice_user_id in added_slice_user_ids.union(added_user_ids):
535 # add person to the slice
536 self.driver.shell.AddPersonToSlice(added_slice_user_id, slice_record['name'])
537 # if this is a peer record then it should already be bound to a peer.
538 # no need to return worry about it getting bound later
543 def verify_keys(self, persons, users, peer, options={}):
546 for person in persons:
547 key_ids.extend(person['key_ids'])
548 keylist = self.driver.shell.GetKeys(key_ids, ['key_id', 'key'])
551 keydict[key['key']] = key['key_id']
552 existing_keys = keydict.keys()
554 for person in persons:
555 persondict[person['email']] = person
561 user_keys = user.get('keys', [])
562 updated_persons.append(user)
563 for key_string in user_keys:
564 requested_keys.append(key_string)
565 if key_string not in existing_keys:
566 key = {'key': key_string, 'key_type': 'ssh'}
569 person = persondict[user['email']]
570 self.driver.shell.UnBindObjectFromPeer('person', person['person_id'], peer['shortname'])
571 key['key_id'] = self.driver.shell.AddPersonKey(user['email'], key)
573 key_index = user_keys.index(key['key'])
574 remote_key_id = user['key_ids'][key_index]
575 self.driver.shell.BindObjectToPeer('key', key['key_id'], peer['shortname'], remote_key_id)
579 self.driver.shell.BindObjectToPeer('person', person['person_id'], peer['shortname'], user['person_id'])
581 # remove old keys (only if we are not appending)
582 append = options.get('append', True)
584 removed_keys = set(existing_keys).difference(requested_keys)
585 for existing_key_id in keydict:
586 if keydict[existing_key_id] in removed_keys:
589 self.driver.shell.UnBindObjectFromPeer('key', existing_key_id, peer['shortname'])
590 self.driver.shell.DeleteKey(existing_key_id)
594 def verify_slice_attributes(self, slice, requested_slice_attributes, options={}, admin=False):
595 append = options.get('append', True)
596 # get list of attributes users ar able to manage
597 filter = {'category': '*slice*'}
599 filter['|roles'] = ['user']
600 slice_attributes = self.driver.shell.GetTagTypes(filter)
601 valid_slice_attribute_names = [attribute['tagname'] for attribute in slice_attributes]
603 # get sliver attributes
604 added_slice_attributes = []
605 removed_slice_attributes = []
606 ignored_slice_attribute_names = []
607 existing_slice_attributes = self.driver.shell.GetSliceTags({'slice_id': slice['slice_id']})
609 # get attributes that should be removed
610 for slice_tag in existing_slice_attributes:
611 if slice_tag['tagname'] in ignored_slice_attribute_names:
612 # If a slice already has a admin only role it was probably given to them by an
613 # admin, so we should ignore it.
614 ignored_slice_attribute_names.append(slice_tag['tagname'])
616 # If an existing slice attribute was not found in the request it should
618 attribute_found=False
619 for requested_attribute in requested_slice_attributes:
620 if requested_attribute['name'] == slice_tag['tagname'] and \
621 requested_attribute['value'] == slice_tag['value']:
625 if not attribute_found and not append:
626 removed_slice_attributes.append(slice_tag)
628 # get attributes that should be added:
629 for requested_attribute in requested_slice_attributes:
630 # if the requested attribute wasn't found we should add it
631 if requested_attribute['name'] in valid_slice_attribute_names:
632 attribute_found = False
633 for existing_attribute in existing_slice_attributes:
634 if requested_attribute['name'] == existing_attribute['tagname'] and \
635 requested_attribute['value'] == existing_attribute['value']:
638 if not attribute_found:
639 added_slice_attributes.append(requested_attribute)
642 # remove stale attributes
643 for attribute in removed_slice_attributes:
645 self.driver.shell.DeleteSliceTag(attribute['slice_tag_id'])
647 logger.warn('Failed to remove sliver attribute. name: %s, value: %s, node_id: %s\nCause:%s'\
648 % (slice['name'], attribute['value'], attribute.get('node_id'), str(e)))
650 # add requested_attributes
651 for attribute in added_slice_attributes:
653 self.driver.shell.AddSliceTag(slice['name'], attribute['name'], attribute['value'], attribute.get('node_id', None))
655 logger.warn('Failed to add sliver attribute. name: %s, value: %s, node_id: %s\nCause:%s'\
656 % (slice['name'], attribute['value'], attribute.get('node_id'), str(e)))