1 from types import StringTypes
2 from collections import defaultdict
4 from sfa.util.xrn import get_leaf, get_authority, urn_to_hrn
5 from sfa.util.plxrn import hrn_to_pl_slicename
6 from sfa.util.policy import Policy
7 from sfa.rspecs.rspec import RSpec
8 from sfa.plc.vlink import VLink
9 from sfa.util.xrn import Xrn
15 rspec_to_slice_tag = {'max_rate':'net_max_rate'}
17 def __init__(self, api, ttl = .5, origin_hrn=None):
19 #filepath = path + os.sep + filename
20 self.policy = Policy(self.api)
21 self.origin_hrn = origin_hrn
22 self.registry = api.registries[api.hrn]
23 self.credential = api.getCredential()
27 def get_slivers(self, xrn, node=None):
28 hrn, type = urn_to_hrn(xrn)
30 slice_name = hrn_to_pl_slicename(hrn)
31 # XX Should we just call PLCAPI.GetSliceTicket(slice_name) instead
32 # of doing all of this?
33 #return self.api.GetSliceTicket(self.auth, slice_name)
35 # from PLCAPI.GetSlivers.get_slivers()
36 slice_fields = ['slice_id', 'name', 'instantiation', 'expires', 'person_ids', 'slice_tag_ids']
37 slices = self.api.plshell.GetSlices(self.api.plauth, slice_name, slice_fields)
38 # Build up list of users and slice attributes
40 all_slice_tag_ids = set()
42 person_ids.update(slice['person_ids'])
43 all_slice_tag_ids.update(slice['slice_tag_ids'])
44 person_ids = list(person_ids)
45 all_slice_tag_ids = list(all_slice_tag_ids)
46 # Get user information
47 all_persons_list = self.api.plshell.GetPersons(self.api.plauth, {'person_id':person_ids,'enabled':True}, ['person_id', 'enabled', 'key_ids'])
49 for person in all_persons_list:
50 all_persons[person['person_id']] = person
52 # Build up list of keys
54 for person in all_persons.values():
55 key_ids.update(person['key_ids'])
56 key_ids = list(key_ids)
57 # Get user account keys
58 all_keys_list = self.api.plshell.GetKeys(self.api.plauth, key_ids, ['key_id', 'key', 'key_type'])
60 for key in all_keys_list:
61 all_keys[key['key_id']] = key
62 # Get slice attributes
63 all_slice_tags_list = self.api.plshell.GetSliceTags(self.api.plauth, all_slice_tag_ids)
65 for slice_tag in all_slice_tags_list:
66 all_slice_tags[slice_tag['slice_tag_id']] = slice_tag
71 for person_id in slice['person_ids']:
72 if person_id in all_persons:
73 person = all_persons[person_id]
74 if not person['enabled']:
76 for key_id in person['key_ids']:
77 if key_id in all_keys:
78 key = all_keys[key_id]
79 keys += [{'key_type': key['key_type'],
82 # All (per-node and global) attributes for this slice
84 for slice_tag_id in slice['slice_tag_ids']:
85 if slice_tag_id in all_slice_tags:
86 slice_tags.append(all_slice_tags[slice_tag_id])
87 # Per-node sliver attributes take precedence over global
88 # slice attributes, so set them first.
89 # Then comes nodegroup slice attributes
90 # Followed by global slice attributes
91 sliver_attributes = []
94 for sliver_attribute in filter(lambda a: a['node_id'] == node['node_id'], slice_tags):
95 sliver_attributes.append(sliver_attribute['tagname'])
96 attributes.append({'tagname': sliver_attribute['tagname'],
97 'value': sliver_attribute['value']})
99 # set nodegroup slice attributes
100 for slice_tag in filter(lambda a: a['nodegroup_id'] in node['nodegroup_ids'], slice_tags):
101 # Do not set any nodegroup slice attributes for
102 # which there is at least one sliver attribute
104 if slice_tag not in slice_tags:
105 attributes.append({'tagname': slice_tag['tagname'],
106 'value': slice_tag['value']})
108 for slice_tag in filter(lambda a: a['node_id'] is None, slice_tags):
109 # Do not set any global slice attributes for
110 # which there is at least one sliver attribute
112 if slice_tag['tagname'] not in sliver_attributes:
113 attributes.append({'tagname': slice_tag['tagname'],
114 'value': slice_tag['value']})
116 # XXX Sanity check; though technically this should be a system invariant
117 # checked with an assertion
118 if slice['expires'] > MAXINT: slice['expires']= MAXINT
122 'name': slice['name'],
123 'slice_id': slice['slice_id'],
124 'instantiation': slice['instantiation'],
125 'expires': slice['expires'],
127 'attributes': attributes
132 def get_peer(self, xrn):
133 hrn, type = urn_to_hrn(xrn)
134 # Becaues of myplc federation, we first need to determine if this
135 # slice belongs to out local plc or a myplc peer. We will assume it
136 # is a local site, unless we find out otherwise
139 # get this slice's authority (site)
140 slice_authority = get_authority(hrn)
142 # get this site's authority (sfa root authority or sub authority)
143 site_authority = get_authority(slice_authority).lower()
145 # check if we are already peered with this site_authority, if so
146 peers = self.api.plshell.GetPeers(self.api.plauth, {}, ['peer_id', 'peername', 'shortname', 'hrn_root'])
147 for peer_record in peers:
148 names = [name.lower() for name in peer_record.values() if isinstance(name, StringTypes)]
149 if site_authority in names:
154 def get_sfa_peer(self, xrn):
155 hrn, type = urn_to_hrn(xrn)
157 # return the authority for this hrn or None if we are the authority
159 slice_authority = get_authority(hrn)
160 site_authority = get_authority(slice_authority)
162 if site_authority != self.api.hrn:
163 sfa_peer = site_authority
167 def verify_slice_nodes(self, slice, requested_slivers, peer):
169 nodes = self.api.plshell.GetNodes(self.api.plauth, slice['node_ids'], ['hostname'])
170 current_slivers = [node['hostname'] for node in nodes]
172 # remove nodes not in rspec
173 deleted_nodes = list(set(current_slivers).difference(requested_slivers))
175 # add nodes from rspec
176 added_nodes = list(set(requested_slivers).difference(current_slivers))
180 self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'slice', slice['slice_id'], peer['shortname'])
181 self.api.plshell.AddSliceToNodes(self.api.plauth, slice['name'], added_nodes)
182 self.api.plshell.DeleteSliceFromNodes(self.api.plauth, slice['name'], deleted_nodes)
185 self.api.logger.log_exc('Failed to add/remove slice from nodes')
187 def verify_slice_links(self, slice, links, aggregate):
188 # nodes is undefined here
193 # get the ip address of the first node in the link
194 ifname1 = Xrn(link['interface1']['component_id']).get_leaf()
195 (node, device) = ifname1.split(':')
196 node_id = int(node.replace('node', ''))
197 node = aggregate.nodes[node_id]
198 if1 = aggregate.interfaces[node['interface_ids'][0]]
200 topo_rspec = VLink.get_topo_rspec(link, ipaddr)
201 self.api.plshell.AddSliceTag(self.api.plauth, slice['name'], 'topo_rspec', str([topo_rspec]), node_id)
205 def handle_peer(self, site, slice, persons, peer):
210 self.api.plshell.BindObjectToPeer(self.api.plauth, 'site', \
211 site['site_id'], peer['shortname'], slice['site_id'])
213 self.api.plshell.DeleteSite(self.api.plauth, site['site_id'])
219 self.api.plshell.BindObjectToPeer(self.api.plauth, 'slice', \
220 slice['slice_id'], peer['shortname'], slice['slice_id'])
222 self.api.plshell.DeleteSlice(self.api.plauth, slice['slice_id'])
226 for person in persons:
228 self.api.plshell.BindObjectToPeer(self.api.plauth, 'person', \
229 person['person_id'], peer['shortname'], person['peer_person_id'])
231 for (key, remote_key_id) in zip(person['keys'], person['key_ids']):
233 self.api.plshell.BindObjectToPeer(self.api.plauth, 'key',\
234 key['key_id'], peer['shortname'], remote_key_id)
236 self.api.plshell.DeleteKey(self.api.plauth, key['key_id'])
237 self.api.logger("failed to bind key: %s to peer: %s " % (key['key_id'], peer['shortname']))
239 self.api.plshell.DeletePerson(self.api.plauth, person['person_id'])
244 def verify_site(self, slice_xrn, slice_record={}, peer=None, sfa_peer=None):
245 (slice_hrn, type) = urn_to_hrn(slice_xrn)
246 site_hrn = get_authority(slice_hrn)
247 # login base can't be longer than 20 characters
248 slicename = hrn_to_pl_slicename(slice_hrn)
249 authority_name = slicename.split('_')[0]
250 login_base = authority_name[:20]
251 sites = self.api.plshell.GetSites(self.api.plauth, login_base)
253 # create new site record
254 site = {'name': 'geni.%s' % authority_name,
255 'abbreviated_name': authority_name,
256 'login_base': login_base,
260 'peer_site_id': None}
262 site['peer_site_id'] = slice_record.get('site_id', None)
263 site['site_id'] = self.api.plshell.AddSite(self.api.plauth, site)
264 # exempt federated sites from monitor policies
265 self.api.plshell.AddSiteTag(self.api.plauth, site['site_id'], 'exempt_site_until', "20200101")
267 # is this still necessary?
268 # add record to the local registry
269 if sfa_peer and slice_record:
270 peer_dict = {'type': 'authority', 'hrn': site_hrn, \
271 'peer_authority': sfa_peer, 'pointer': site['site_id']}
272 self.registry.register_peer_object(self.credential, peer_dict)
276 # unbind from peer so we can modify if necessary. Will bind back later
277 self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'site', site['site_id'], peer['shortname'])
281 def verify_slice(self, slice_hrn, slice_record, peer, sfa_peer):
282 slicename = hrn_to_pl_slicename(slice_hrn)
283 parts = slicename.split("_")
284 login_base = parts[0]
285 slices = self.api.plshell.GetSlices(self.api.plauth, [slicename])
287 slice = {'name': slicename,
288 'url': slice_record.get('url', slice_hrn),
289 'description': slice_record.get('description', slice_hrn)}
291 slice['slice_id'] = self.api.plshell.AddSlice(self.api.plauth, slice)
292 slice['node_ids'] = []
293 slice['person_ids'] = []
295 slice['peer_slice_id'] = slice_record.get('slice_id', None)
296 # mark this slice as an sfa peer record
298 peer_dict = {'type': 'slice', 'hrn': slice_hrn,
299 'peer_authority': sfa_peer, 'pointer': slice['slice_id']}
300 self.registry.register_peer_object(self.credential, peer_dict)
304 slice['peer_slice_id'] = slice_record.get('slice_id', None)
305 # unbind from peer so we can modify if necessary. Will bind back later
306 self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'slice',\
307 slice['slice_id'], peer['shortname'])
308 #Update existing record (e.g. expires field) it with the latest info.
309 if slice_record and slice['expires'] != slice_record['expires']:
310 self.api.plshell.UpdateSlice(self.api.plauth, slice['slice_id'],\
311 {'expires' : slice_record['expires']})
315 #def get_existing_persons(self, users):
316 def verify_persons(self, slice_hrn, slice_record, users, peer, sfa_peer, append=True):
318 users_by_site = defaultdict(list)
322 if 'append' in user and user['append'] == False:
325 users_by_email[user['email']] = user
326 users_dict[user['email']] = user
328 hrn, type = urn_to_hrn(user['urn'])
329 username = get_leaf(hrn)
330 login_base = get_leaf(get_authority(user['urn']))
331 user['username'] = username
332 users_by_site[login_base].append(user)
334 existing_user_ids = []
336 # get existing users by email
337 existing_users = self.api.plshell.GetPersons(self.api.plauth, \
338 {'email': users_by_email.keys()}, ['person_id', 'key_ids', 'email'])
339 existing_user_ids.extend([user['email'] for user in existing_users])
342 # get a list of user sites (based on requeste user urns
343 site_list = self.api.plshell.GetSites(self.api.plauth, users_by_site.keys(), \
344 ['site_id', 'login_base', 'person_ids'])
348 # get all existing users at these sites
349 for site in site_list:
350 sites[site['site_id']] = site
351 site_user_ids.extend(site['person_ids'])
353 existing_site_persons_list = self.api.plshell.GetPersons(self.api.plauth, \
354 site_user_ids, ['person_id', 'key_ids', 'email', 'site_ids'])
356 # all requested users are either existing users or new (added) users
357 for login_base in users_by_site:
358 requested_site_users = users_by_site[login_base]
359 for requested_user in requested_site_users:
361 for existing_user in existing_site_persons_list:
362 for site_id in existing_user['site_ids']:
363 site = sites[site_id]
364 if login_base == site['login_base'] and \
365 existing_user['email'].startswith(requested_user['username']):
366 existing_user_ids.append(existing_user['email'])
367 users_dict[existing_user['email']] = requested_user
373 if user_found == False:
374 fake_email = requested_user['username'] + '@geni.net'
375 users_dict[fake_email] = requested_user
378 # requested slice users
379 requested_user_ids = users_dict.keys()
380 # existing slice users
381 existing_slice_users_filter = {'person_id': slice_record.get('person_ids', [])}
382 existing_slice_users = self.api.plshell.GetPersons(self.api.plauth, \
383 existing_slice_users_filter, ['person_id', 'key_ids', 'email'])
384 existing_slice_user_ids = [user['email'] for user in existing_slice_users]
386 # users to be added, removed or updated
387 added_user_ids = set(requested_user_ids).difference(existing_user_ids)
388 added_slice_user_ids = set(requested_user_ids).difference(existing_slice_user_ids)
389 removed_user_ids = set(existing_slice_user_ids).difference(requested_user_ids)
390 updated_user_ids = set(existing_slice_user_ids).intersection(requested_user_ids)
392 # Remove stale users (only if we are not appending).
394 for removed_user_id in removed_user_ids:
395 self.api.plshell.DeletePersonFromSlice(self.api.plauth, removed_user_id, slice_record['name'])
396 # update_existing users
397 updated_users_list = [user for user in existing_slice_users if user['email'] in \
399 self.verify_keys(existing_slice_users, updated_users_list, peer, append)
403 for added_user_id in added_user_ids:
404 added_user = users_dict[added_user_id]
405 hrn, type = urn_to_hrn(added_user['urn'])
407 'first_name': added_user.get('first_name', hrn),
408 'last_name': added_user.get('last_name', hrn),
409 'email': added_user_id,
410 'peer_person_id': None,
412 'key_ids': added_user.get('key_ids', []),
414 person['person_id'] = self.api.plshell.AddPerson(self.api.plauth, person)
416 person['peer_person_id'] = added_user['person_id']
417 added_persons.append(person)
420 self.api.plshell.UpdatePerson(self.api.plauth, person['person_id'], {'enabled': True})
423 self.api.plshell.AddPersonToSite(self.api.plauth, added_user_id, login_base)
425 for key_string in added_user.get('keys', []):
426 key = {'key':key_string, 'key_type':'ssh'}
427 key['key_id'] = self.api.plshell.AddPersonKey(self.api.plauth, person['person_id'], key)
428 person['keys'].append(key)
430 # add the registry record
432 peer_dict = {'type': 'user', 'hrn': hrn, 'peer_authority': sfa_peer, \
433 'pointer': person['person_id']}
434 self.registry.register_peer_object(self.credential, peer_dict)
436 for added_slice_user_id in added_slice_user_ids.union(added_user_ids):
437 # add person to the slice
438 self.api.plshell.AddPersonToSlice(self.api.plauth, added_slice_user_id, slice_record['name'])
439 # if this is a peer record then it should already be bound to a peer.
440 # no need to return worry about it getting bound later
445 def verify_keys(self, persons, users, peer, append=True):
448 for person in persons:
449 key_ids.extend(person['key_ids'])
450 keylist = self.api.plshell.GetKeys(self.api.plauth, key_ids, ['key_id', 'key'])
453 keydict[key['key']] = key['key_id']
454 existing_keys = keydict.keys()
456 for person in persons:
457 persondict[person['email']] = person
463 user_keys = user.get('keys', [])
464 updated_persons.append(user)
465 for key_string in user_keys:
466 requested_keys.append(key_string)
467 if key_string not in existing_keys:
468 key = {'key': key_string, 'key_type': 'ssh'}
471 person = persondict[user['email']]
472 self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'person', person['person_id'], peer['shortname'])
473 key['key_id'] = self.api.plshell.AddPersonKey(self.api.plauth, user['email'], key)
475 key_index = user_keys.index(key['key'])
476 remote_key_id = user['key_ids'][key_index]
477 self.api.plshell.BindObjectToPeer(self.api.plauth, 'key', key['key_id'], peer['shortname'], remote_key_id)
481 self.api.plshell.BindObjectToPeer(self.api.plauth, 'person', person['person_id'], peer['shortname'], user['person_id'])
483 # remove old keys (only if we are not appending)
485 removed_keys = set(existing_keys).difference(requested_keys)
486 for existing_key_id in keydict:
487 if keydict[existing_key_id] in removed_keys:
490 self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'key', existing_key_id, peer['shortname'])
491 self.api.plshell.DeleteKey(self.api.plauth, existing_key_id)
495 def verify_slice_attributes(self, slice, requested_slice_attributes):
496 # get list of attributes users ar able to manage
497 slice_attributes = self.api.plshell.GetTagTypes(self.api.plauth, {'category': '*slice*', '|roles': ['user']})
498 valid_slice_attribute_names = [attribute['tagname'] for attribute in slice_attributes]
500 # get sliver attributes
501 added_slice_attributes = []
502 removed_slice_attributes = []
503 ignored_slice_attribute_names = []
504 existing_slice_attributes = self.api.plshell.GetSliceTags(self.api.plauth, {'slice_id': slice['slice_id']})
506 # get attributes that should be removed
507 for slice_tag in existing_slice_attributes:
508 if slice_tag['tagname'] in ignored_slice_attribute_names:
509 # If a slice already has a admin only role it was probably given to them by an
510 # admin, so we should ignore it.
511 ignored_slice_attribute_names.append(slice_tag['tagname'])
513 # If an existing slice attribute was not found in the request it should
515 attribute_found=False
516 for requested_attribute in requested_slice_attributes:
517 if requested_attribute['name'] == slice_tag['tagname'] and \
518 requested_attribute['value'] == slice_tag['value']:
522 if not attribute_found:
523 removed_slice_attributes.append(slice_tag)
525 # get attributes that should be added:
526 for requested_attribute in requested_slice_attributes:
527 # if the requested attribute wasn't found we should add it
528 if requested_attribute['name'] in valid_slice_attribute_names:
529 attribute_found = False
530 for existing_attribute in existing_slice_attributes:
531 if requested_attribute['name'] == existing_attribute['tagname'] and \
532 requested_attribute['value'] == existing_attribute['value']:
535 if not attribute_found:
536 added_slice_attributes.append(requested_attribute)
539 # remove stale attributes
540 for attribute in removed_slice_attributes:
542 self.api.plshell.DeleteSliceTag(self.api.plauth, attribute['slice_tag_id'])
544 self.api.logger.warn('Failed to remove sliver attribute. name: %s, value: %s, node_id: %s\nCause:%s'\
545 % (name, value, node_id, str(e)))
547 # add requested_attributes
548 for attribute in added_slice_attributes:
550 self.api.plshell.AddSliceTag(self.api.plauth, slice['name'], attribute['name'], attribute['value'], attribute.get('node_id', None))
552 self.api.logger.warn('Failed to add sliver attribute. name: %s, value: %s, node_id: %s\nCause:%s'\
553 % (name, value, node_id, str(e)))
555 def create_slice_aggregate(self, xrn, rspec):
556 hrn, type = urn_to_hrn(xrn)
557 # Determine if this is a peer slice
558 peer = self.get_peer(hrn)
559 sfa_peer = self.get_sfa_peer(hrn)
562 # Get the slice record from sfa
563 slicename = hrn_to_pl_slicename(hrn)
566 registry = self.api.registries[self.api.hrn]
567 credential = self.api.getCredential()
569 site_id, remote_site_id = self.verify_site(registry, credential, hrn, peer, sfa_peer)
570 slice = self.verify_slice(registry, credential, hrn, site_id, remote_site_id, peer, sfa_peer)
572 # find out where this slice is currently running
573 nodelist = self.api.plshell.GetNodes(self.api.plauth, slice['node_ids'], ['hostname'])
574 hostnames = [node['hostname'] for node in nodelist]
576 # get netspec details
577 nodespecs = spec.getDictsByTagName('NodeSpec')
579 # dict in which to store slice attributes to set for the nodes
581 for nodespec in nodespecs:
582 if isinstance(nodespec['name'], list):
583 for nodename in nodespec['name']:
585 for k in nodespec.keys():
586 rspec_attribute_value = nodespec[k]
587 if (self.rspec_to_slice_tag.has_key(k)):
588 slice_tag_name = self.rspec_to_slice_tag[k]
589 nodes[nodename][slice_tag_name] = rspec_attribute_value
590 elif isinstance(nodespec['name'], StringTypes):
591 nodename = nodespec['name']
593 for k in nodespec.keys():
594 rspec_attribute_value = nodespec[k]
595 if (self.rspec_to_slice_tag.has_key(k)):
596 slice_tag_name = self.rspec_to_slice_tag[k]
597 nodes[nodename][slice_tag_name] = rspec_attribute_value
599 for k in nodespec.keys():
600 rspec_attribute_value = nodespec[k]
601 if (self.rspec_to_slice_tag.has_key(k)):
602 slice_tag_name = self.rspec_to_slice_tag[k]
603 nodes[nodename][slice_tag_name] = rspec_attribute_value
605 node_names = nodes.keys()
606 # remove nodes not in rspec
607 deleted_nodes = list(set(hostnames).difference(node_names))
608 # add nodes from rspec
609 added_nodes = list(set(node_names).difference(hostnames))
613 self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'slice', slice['slice_id'], peer)
615 self.api.plshell.AddSliceToNodes(self.api.plauth, slicename, added_nodes)
617 # Add recognized slice tags
618 for node_name in node_names:
619 node = nodes[node_name]
620 for slice_tag in node.keys():
621 value = node[slice_tag]
622 if (isinstance(value, list)):
625 self.api.plshell.AddSliceTag(self.api.plauth, slicename, slice_tag, value, node_name)
627 self.api.plshell.DeleteSliceFromNodes(self.api.plauth, slicename, deleted_nodes)
630 self.api.plshell.BindObjectToPeer(self.api.plauth, 'slice', slice['slice_id'], peer, slice['peer_slice_id'])