1 from datetime import datetime
3 from sqlalchemy import or_, and_
4 from sqlalchemy import Column, Integer, String, DateTime
5 from sqlalchemy import Table, Column, MetaData, join, ForeignKey
6 from sqlalchemy.orm import relationship, backref
7 from sqlalchemy.orm import column_property
8 from sqlalchemy.orm import object_mapper
9 from sqlalchemy.orm import validates
10 from sqlalchemy.ext.declarative import declarative_base
12 from sfa.storage.record import Record
13 from sfa.util.sfalogging import logger
14 from sfa.util.sfatime import utcparse, datetime_to_string
15 from sfa.util.xml import XML
17 from sfa.trust.gid import GID
19 ##############################
20 Base = declarative_base()
25 # historically the front end to the db dealt with dicts, so the code was only dealing with dicts
26 # sqlalchemy however offers an object interface, meaning that you write obj.id instead of obj['id']
27 # which is admittedly much nicer
28 # however we still need to deal with dictionaries if only for the xmlrpc layer
30 # here are a few utilities for this
32 # (*) first off, when an old pieve of code needs to be used as-is, if only temporarily, the simplest trick
33 # is to use obj.__dict__
34 # this behaves exactly like required, i.e. obj.__dict__['field']='new value' does change obj.field
35 # however this depends on sqlalchemy's implementation so it should be avoided
37 # (*) second, when an object needs to be exposed to the xmlrpc layer, we need to convert it into a dict
38 # remember though that writing the resulting dictionary won't change the object
39 # essentially obj.__dict__ would be fine too, except that we want to discard alchemy private keys starting with '_'
40 # 2 ways are provided for that:
43 # the former dict(obj) relies on __iter__() and next() below, and does not rely on the fields names
44 # although it seems to work fine, I've found cases where it issues a weird python error that I could not get right
45 # so the latter obj.todict() seems more reliable but more hacky as is relies on the form of fields, so this can probably be improved
47 # (*) finally for converting a dictionary into an sqlalchemy object, we provide
48 # obj.load_from_dict(dict)
51 class AlchemyObj(Record):
54 self._i = iter(object_mapper(self).columns)
58 n = self._i.next().name
59 return n, getattr(self, n)
61 # # only intended for debugging
62 # def inspect (self, logger, message=""):
63 # logger.info("%s -- Inspecting AlchemyObj -- attrs"%message)
65 # if not k.startswith('_'):
66 # logger.info (" %s: %s"%(k,getattr(self,k)))
67 # logger.info("%s -- Inspecting AlchemyObj -- __dict__"%message)
69 # for (k,v) in d.iteritems():
70 # logger.info("[%s]=%s"%(k,v))
73 ##############################
74 # various kinds of records are implemented as an inheritance hierarchy
75 # RegRecord is the base class for all actual variants
76 # a first draft was using 'type' as the discriminator for the inheritance
77 # but we had to define another more internal column (classtype) so we
78 # accomodate variants in types like authority+am and the like
80 class RegRecord(Base, AlchemyObj):
81 __tablename__ = 'records'
82 record_id = Column(Integer, primary_key=True)
83 # this is the discriminator that tells which class to use
84 classtype = Column(String)
85 # in a first version type was the discriminator
86 # but that could not accomodate for 'authority+sa' and the like
90 authority = Column(String)
91 peer_authority = Column(String)
92 pointer = Column(Integer, default=-1)
93 date_created = Column(DateTime)
94 last_updated = Column(DateTime)
95 # use the 'type' column to decide which subclass the object is of
96 __mapper_args__ = {'polymorphic_on': classtype}
98 fields = ['type', 'hrn', 'gid', 'authority', 'peer_authority']
100 def __init__(self, type=None, hrn=None, gid=None, authority=None, peer_authority=None,
101 pointer=None, dict=None):
107 if isinstance(gid, str):
110 self.gid = gid.save_to_string(save_parents=True)
112 self.authority = authority
114 self.peer_authority = peer_authority
116 self.pointer = pointer
118 self.load_from_dict(dict)
121 result = "<Record id=%s, type=%s, hrn=%s, authority=%s" % \
122 (self.record_id, self.type, self.hrn, self.authority)
123 # for extra in ('pointer', 'email', 'name'):
124 # for extra in ('email', 'name'):
125 # displaying names at this point it too dangerous, because of unicode
126 for extra in ('email'):
127 if hasattr(self, extra):
128 result += " {}={},".format(extra, getattr(self, extra))
129 # skip the uniform '--- BEGIN CERTIFICATE --' stuff
131 result += " gid=%s..." % self.gid[28:36]
137 # shortcut - former implem. was record-based
138 def get(self, field, default):
139 return getattr(self, field, default)
142 def validate_gid(self, key, gid):
145 elif isinstance(gid, str):
148 return gid.save_to_string(save_parents=True)
150 def validate_datetime(self, key, incoming):
151 if isinstance(incoming, datetime):
153 elif isinstance(incoming, (int, float)):
154 return datetime.fromtimestamp(incoming)
156 logger.info("Cannot validate datetime for key %s with input %s" %
159 @validates('date_created')
160 def validate_date_created(self, key, incoming):
161 return self.validate_datetime(key, incoming)
163 @validates('last_updated')
164 def validate_last_updated(self, key, incoming):
165 return self.validate_datetime(key, incoming)
167 # xxx - there might be smarter ways to handle get/set'ing gid using
169 def get_gid_object(self):
173 return GID(string=self.gid)
175 def just_created(self):
176 now = datetime.utcnow()
177 self.date_created = now
178 self.last_updated = now
180 def just_updated(self):
181 now = datetime.utcnow()
182 self.last_updated = now
184 # cross-relations tables
185 # authority x user (pis) association
186 authority_pi_table = \
187 Table('authority_pi', Base.metadata,
188 Column('authority_id', Integer, ForeignKey(
189 'records.record_id'), primary_key=True),
190 Column('pi_id', Integer, ForeignKey(
191 'records.record_id'), primary_key=True),
193 # slice x user (researchers) association
194 slice_researcher_table = \
195 Table('slice_researcher', Base.metadata,
196 Column('slice_id', Integer, ForeignKey(
197 'records.record_id'), primary_key=True),
198 Column('researcher_id', Integer, ForeignKey(
199 'records.record_id'), primary_key=True),
202 ##############################
203 # all subclasses define a convenience constructor with a default value for type,
204 # and when applicable a way to define local fields in a kwd=value argument
208 class RegAuthority(RegRecord):
209 __tablename__ = 'authorities'
210 __mapper_args__ = {'polymorphic_identity': 'authority'}
211 record_id = Column(Integer, ForeignKey(
212 "records.record_id"), primary_key=True)
213 # extensions come here
214 name = Column('name', String)
215 # extensions come here
216 reg_pis = relationship \
218 secondary=authority_pi_table,
219 primaryjoin=RegRecord.record_id == authority_pi_table.c.authority_id,
220 secondaryjoin=RegRecord.record_id == authority_pi_table.c.pi_id,
221 backref='reg_authorities_as_pi',
224 def __init__(self, **kwds):
225 # handle local settings
227 self.name = kwds.pop('name')
228 # fill in type if not previously set
229 if 'type' not in kwds:
230 kwds['type'] = 'authority'
231 # base class constructor
232 RegRecord.__init__(self, **kwds)
234 # no proper data yet, just hack the typename
236 result = RegRecord.__repr__(self).replace("Record", "Authority")
237 # here again trying to display names that can be utf8 is too dangerous
238 # result.replace(">", " name={}>".format(self.name))
241 def update_pis(self, pi_hrns, dbsession):
242 # strip that in case we have <researcher> words </researcher>
243 pi_hrns = [x.strip() for x in pi_hrns]
244 request = dbsession.query(RegUser).filter(RegUser.hrn.in_(pi_hrns))
245 logger.info("RegAuthority.update_pis: %d incoming pis, %d matches found"
246 % (len(pi_hrns), request.count()))
247 pis = dbsession.query(RegUser).filter(RegUser.hrn.in_(pi_hrns)).all()
253 class RegSlice(RegRecord):
254 __tablename__ = 'slices'
255 __mapper_args__ = {'polymorphic_identity': 'slice'}
256 record_id = Column(Integer, ForeignKey(
257 "records.record_id"), primary_key=True)
258 # extensions come here
259 reg_researchers = relationship \
261 secondary=slice_researcher_table,
262 primaryjoin=RegRecord.record_id == slice_researcher_table.c.slice_id,
263 secondaryjoin=RegRecord.record_id == slice_researcher_table.c.researcher_id,
264 backref='reg_slices_as_researcher',
267 def __init__(self, **kwds):
268 if 'type' not in kwds:
269 kwds['type'] = 'slice'
270 RegRecord.__init__(self, **kwds)
273 return RegRecord.__repr__(self).replace("Record", "Slice")
275 def update_researchers(self, researcher_hrns, dbsession):
276 # strip that in case we have <researcher> words </researcher>
277 researcher_hrns = [x.strip() for x in researcher_hrns]
278 request = dbsession.query(RegUser).filter(
279 RegUser.hrn.in_(researcher_hrns))
280 logger.info("RegSlice.update_researchers: %d incoming researchers, %d matches found"
281 % (len(researcher_hrns), request.count()))
282 researchers = dbsession.query(RegUser).filter(
283 RegUser.hrn.in_(researcher_hrns)).all()
284 self.reg_researchers = researchers
286 # when dealing with credentials, we need to retrieve the PIs attached to a slice
287 # WARNING: with the move to passing dbsessions around, we face a glitch here because this
288 # helper function is called from the trust/ area that
290 from sqlalchemy.orm import sessionmaker
291 Session = sessionmaker()
292 dbsession = Session.object_session(self)
293 from sfa.util.xrn import get_authority
294 authority_hrn = get_authority(self.hrn)
295 auth_record = dbsession.query(
296 RegAuthority).filter_by(hrn=authority_hrn).first()
297 return auth_record.reg_pis
299 @validates('expires')
300 def validate_expires(self, key, incoming):
301 return self.validate_datetime(key, incoming)
306 class RegNode(RegRecord):
307 __tablename__ = 'nodes'
308 __mapper_args__ = {'polymorphic_identity': 'node'}
309 record_id = Column(Integer, ForeignKey(
310 "records.record_id"), primary_key=True)
312 def __init__(self, **kwds):
313 if 'type' not in kwds:
314 kwds['type'] = 'node'
315 RegRecord.__init__(self, **kwds)
318 return RegRecord.__repr__(self).replace("Record", "Node")
323 class RegUser(RegRecord):
324 __tablename__ = 'users'
325 # these objects will have type='user' in the records table
326 __mapper_args__ = {'polymorphic_identity': 'user'}
327 record_id = Column(Integer, ForeignKey(
328 "records.record_id"), primary_key=True)
329 # extensions come here
330 email = Column('email', String)
331 # can't use name 'keys' here because when loading from xml we're getting
332 # a 'keys' tag, and assigning a list of strings in a reference column like
334 reg_keys = relationship \
335 ('RegKey', backref='reg_user',
336 cascade="all, delete, delete-orphan",
339 # so we can use RegUser (email=.., hrn=..) and the like
340 def __init__(self, **kwds):
341 # handle local settings
343 self.email = kwds.pop('email')
344 if 'type' not in kwds:
345 kwds['type'] = 'user'
346 RegRecord.__init__(self, **kwds)
348 # append stuff at the end of the record __repr__
350 result = RegRecord.__repr__(self).replace("Record", "User")
351 result.replace(">", " email={}>".format(self.email))
355 def validate_email(self, key, address):
356 assert '@' in address
360 # xxx tocheck : not sure about eager loading of this one
361 # meaning, when querying the whole records, we expect there should
362 # be a single query to fetch all the keys
363 # or, is it enough that we issue a single query to retrieve all the keys
367 __tablename__ = 'keys'
368 key_id = Column(Integer, primary_key=True)
369 record_id = Column(Integer, ForeignKey("records.record_id"))
371 pointer = Column(Integer, default=-1)
373 def __init__(self, key, pointer=None):
376 self.pointer = pointer
379 result = "<key id=%s key=%s..." % (self.key_id, self.key[8:16],)
381 result += " user=%s" % self.reg_user.record_id
388 class SliverAllocation(Base, AlchemyObj):
389 __tablename__ = 'sliver_allocation'
390 sliver_id = Column(String, primary_key=True)
391 client_id = Column(String)
392 component_id = Column(String)
393 slice_urn = Column(String)
394 allocation_state = Column(String)
396 def __init__(self, **kwds):
397 if 'sliver_id' in kwds:
398 self.sliver_id = kwds['sliver_id']
399 if 'client_id' in kwds:
400 self.client_id = kwds['client_id']
401 if 'component_id' in kwds:
402 self.component_id = kwds['component_id']
403 if 'slice_urn' in kwds:
404 self.slice_urn = kwds['slice_urn']
405 if 'allocation_state' in kwds:
406 self.allocation_state = kwds['allocation_state']
409 result = "<sliver_allocation sliver_id=%s allocation_state=%s"\
410 % (self.sliver_id, self.allocation_state)
413 @validates('allocation_state')
414 def validate_allocation_state(self, key, state):
415 allocation_states = ['geni_unallocated',
416 'geni_allocated', 'geni_provisioned']
417 assert state in allocation_states
421 def set_allocations(sliver_ids, state, dbsession):
422 if not isinstance(sliver_ids, list):
423 sliver_ids = [sliver_ids]
424 sliver_state_updated = {}
425 constraint = SliverAllocation.sliver_id.in_(sliver_ids)
426 sliver_allocations = dbsession.query(
427 SliverAllocation).filter(constraint)
428 sliver_ids_found = []
429 for sliver_allocation in sliver_allocations:
430 sliver_allocation.allocation_state = state
431 sliver_ids_found.append(sliver_allocation.sliver_id)
433 # Some states may not have been updated becuase no sliver allocation state record
434 # exists for the sliver. Insert new allocation records for these slivers and set
435 # it to geni_allocated.
436 sliver_ids_not_found = set(sliver_ids).difference(sliver_ids_found)
437 for sliver_id in sliver_ids_not_found:
438 record = SliverAllocation(
439 sliver_id=sliver_id, allocation_state=state)
440 dbsession.add(record)
444 def delete_allocations(sliver_ids, dbsession):
445 if not isinstance(sliver_ids, list):
446 sliver_ids = [sliver_ids]
447 constraint = SliverAllocation.sliver_id.in_(sliver_ids)
448 sliver_allocations = dbsession.query(
449 SliverAllocation).filter(constraint)
450 for sliver_allocation in sliver_allocations:
451 dbsession.delete(sliver_allocation)
454 def sync(self, dbsession):
455 constraints = [SliverAllocation.sliver_id == self.sliver_id]
456 results = dbsession.query(SliverAllocation).filter(and_(*constraints))
458 for result in results:
459 records.append(result)
465 record.sliver_id = self.sliver_id
466 record.client_id = self.client_id
467 record.component_id = self.component_id
468 record.slice_urn = self.slice_urn
469 record.allocation_state = self.allocation_state
473 ##############################
474 # although the db needs of course to be reachable for the following functions
475 # the schema management functions are here and not in alchemy
476 # because the actual details of the classes need to be known
477 # migrations: this code has no notion of the previous versions
478 # of the data model nor of migrations
479 # sfa.storage.migrations.db_init uses this when starting from
481 def init_tables(engine):
482 logger.info("Initializing db schema from current/latest model")
483 Base.metadata.create_all(engine)
486 def drop_tables(engine):
487 logger.info("Dropping tables from current/latest model")
488 Base.metadata.drop_all(engine)
490 ##############################
491 # create a record of the right type from either a dict or an xml string
494 def make_record(dict=None, xml=""):
498 return make_record_dict(dict)
500 return make_record_xml(xml)
502 raise Exception("make_record has no input")
504 # convert an incoming record - typically from xmlrpc - into an object
507 def make_record_dict(record_dict):
508 assert ('type' in record_dict)
509 type = record_dict['type'].split('+')[0]
510 if type == 'authority':
511 result = RegAuthority(dict=record_dict)
513 result = RegUser(dict=record_dict)
514 elif type == 'slice':
515 result = RegSlice(dict=record_dict)
517 result = RegNode(dict=record_dict)
519 logger.debug("Untyped RegRecord instance")
520 result = RegRecord(dict=record_dict)
521 logger.info("converting dict into Reg* with type=%s" % type)
522 logger.info("returning=%s" % result)
524 # register non-db attributes in an extensions field
528 def make_record_xml(xml_str):
530 xml_dict = xml.todict()
531 logger.info("load from xml, keys=%s" % list(xml_dict.keys()))
532 return make_record_dict(xml_dict)
535 # augment local records with data from builtin relationships
536 # expose related objects as a list of hrns
537 # we pick names that clearly won't conflict with the ones used in the old approach,
538 # were the relationships data came from the testbed side
539 # for each type, a dict of the form {<field-name-exposed-in-record>:<alchemy_accessor_name>}
540 # so after that, an 'authority' record will e.g. have a 'reg-pis' field
541 # with the hrns of its pi-users
542 augment_map = {'authority': {'reg-pis': 'reg_pis', },
543 'slice': {'reg-researchers': 'reg_researchers', },
544 'user': {'reg-pi-authorities': 'reg_authorities_as_pi',
545 'reg-slices': 'reg_slices_as_researcher', },
550 # the way we use sqlalchemy might be a little wrong
551 # in any case what has been observed is that (Reg)Records as returned by an sqlalchemy
552 # query not always have their __dict__ properly adjusted
553 # typically a RegAuthority object would have its object.name set properly, but
554 # object.__dict__ has no 'name' key
555 # which is an issue because we rely on __dict__ for many things, in particular this
556 # is what gets exposed to the drivers (this is historical and dates back before sqlalchemy)
557 # so it is recommended to always run this function that will make sure
558 # that such built-in fields are properly set in __dict__ too
560 def augment_with_sfa_builtins(local_record):
561 # don't ruin the import of that file in a client world
562 from sfa.util.xrn import Xrn
564 setattr(local_record, 'reg-urn',
565 Xrn(xrn=local_record.hrn, type=local_record.type).urn)
566 # users have keys and this is needed to synthesize 'users' sent over to
569 if local_record.type == 'user':
570 user_keys = [key.key for key in local_record.reg_keys]
571 setattr(local_record, 'reg-keys', user_keys)
572 fields_to_check = ['email']
573 elif local_record.type == 'authority':
574 fields_to_check = ['name']
575 for field in fields_to_check:
576 if not field in local_record.__dict__:
577 logger.debug("augment_with_sfa_builtins: hotfixing missing '{}' in {}"
578 .format(field, local_record.hrn))
579 local_record.__dict__[field] = getattr(local_record, field)
580 # search in map according to record type
581 type_map = augment_map.get(local_record.type, {})
582 # use type-dep. map to do the job
583 for (field_name, attribute) in list(type_map.items()):
584 # get related objects
585 related_records = getattr(local_record, attribute, [])
586 hrns = [r.hrn for r in related_records]
587 setattr(local_record, field_name, hrns)