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
16 from sfa.util.py23 import StringType
18 from sfa.trust.gid import GID
20 ##############################
21 Base = declarative_base()
26 # historically the front end to the db dealt with dicts, so the code was only dealing with dicts
27 # sqlalchemy however offers an object interface, meaning that you write obj.id instead of obj['id']
28 # which is admittedly much nicer
29 # however we still need to deal with dictionaries if only for the xmlrpc layer
31 # here are a few utilities for this
33 # (*) first off, when an old pieve of code needs to be used as-is, if only temporarily, the simplest trick
34 # is to use obj.__dict__
35 # this behaves exactly like required, i.e. obj.__dict__['field']='new value' does change obj.field
36 # however this depends on sqlalchemy's implementation so it should be avoided
38 # (*) second, when an object needs to be exposed to the xmlrpc layer, we need to convert it into a dict
39 # remember though that writing the resulting dictionary won't change the object
40 # essentially obj.__dict__ would be fine too, except that we want to discard alchemy private keys starting with '_'
41 # 2 ways are provided for that:
44 # the former dict(obj) relies on __iter__() and next() below, and does not rely on the fields names
45 # although it seems to work fine, I've found cases where it issues a weird python error that I could not get right
46 # 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
48 # (*) finally for converting a dictionary into an sqlalchemy object, we provide
49 # obj.load_from_dict(dict)
51 class AlchemyObj(Record):
53 self._i = iter(object_mapper(self).columns)
56 n = self._i.next().name
57 return n, getattr(self, n)
59 # # only intended for debugging
60 # def inspect (self, logger, message=""):
61 # logger.info("%s -- Inspecting AlchemyObj -- attrs"%message)
63 # if not k.startswith('_'):
64 # logger.info (" %s: %s"%(k,getattr(self,k)))
65 # logger.info("%s -- Inspecting AlchemyObj -- __dict__"%message)
67 # for (k,v) in d.iteritems():
68 # logger.info("[%s]=%s"%(k,v))
71 ##############################
72 # various kinds of records are implemented as an inheritance hierarchy
73 # RegRecord is the base class for all actual variants
74 # a first draft was using 'type' as the discriminator for the inheritance
75 # but we had to define another more internal column (classtype) so we
76 # accomodate variants in types like authority+am and the like
78 class RegRecord(Base, AlchemyObj):
79 __tablename__ = 'records'
80 record_id = Column (Integer, primary_key=True)
81 # this is the discriminator that tells which class to use
82 classtype = Column (String)
83 # in a first version type was the discriminator
84 # but that could not accomodate for 'authority+sa' and the like
85 type = Column (String)
88 authority = Column (String)
89 peer_authority = Column (String)
90 pointer = Column (Integer, default=-1)
91 date_created = Column (DateTime)
92 last_updated = Column (DateTime)
93 # use the 'type' column to decide which subclass the object is of
94 __mapper_args__ = { 'polymorphic_on' : classtype }
96 fields = [ 'type', 'hrn', 'gid', 'authority', 'peer_authority' ]
97 def __init__ (self, type=None, hrn=None, gid=None, authority=None, peer_authority=None,
98 pointer=None, dict=None):
99 if type: self.type=type
102 if isinstance(gid, StringType): self.gid=gid
103 else: self.gid=gid.save_to_string(save_parents=True)
104 if authority: self.authority=authority
105 if peer_authority: self.peer_authority=peer_authority
106 if pointer: self.pointer=pointer
107 if dict: self.load_from_dict (dict)
110 result="<Record id=%s, type=%s, hrn=%s, authority=%s" % \
111 (self.record_id, self.type, self.hrn, self.authority)
112 # for extra in ('pointer', 'email', 'name'):
113 # for extra in ('email', 'name'):
114 # displaying names at this point it too dangerous, because of unicode
115 for extra in ('email'):
116 if hasattr(self, extra):
117 result += " {}={},".format(extra, getattr(self, extra))
118 # skip the uniform '--- BEGIN CERTIFICATE --' stuff
120 result+=" gid=%s..."%self.gid[28:36]
126 # shortcut - former implem. was record-based
127 def get (self, field, default):
128 return getattr(self,field,default)
131 def validate_gid (self, key, gid):
132 if gid is None: return
133 elif isinstance(gid, StringType): return gid
134 else: return gid.save_to_string(save_parents=True)
136 def validate_datetime (self, key, incoming):
137 if isinstance (incoming, datetime):
139 elif isinstance (incoming, (int, float)):
140 return datetime.fromtimestamp (incoming)
142 logger.info("Cannot validate datetime for key %s with input %s"%\
145 @validates ('date_created')
146 def validate_date_created (self, key, incoming):
147 return self.validate_datetime (key, incoming)
149 @validates ('last_updated')
150 def validate_last_updated (self, key, incoming):
151 return self.validate_datetime (key, incoming)
153 # xxx - there might be smarter ways to handle get/set'ing gid using validation hooks
154 def get_gid_object (self):
155 if not self.gid: return None
156 else: return GID(string=self.gid)
158 def just_created (self):
159 now = datetime.utcnow()
160 self.date_created = now
161 self.last_updated = now
163 def just_updated (self):
164 now = datetime.utcnow()
165 self.last_updated = now
167 #################### cross-relations tables
168 # authority x user (pis) association
169 authority_pi_table = \
170 Table ( 'authority_pi', Base.metadata,
171 Column ('authority_id', Integer, ForeignKey ('records.record_id'), primary_key=True),
172 Column ('pi_id', Integer, ForeignKey ('records.record_id'), primary_key=True),
174 # slice x user (researchers) association
175 slice_researcher_table = \
176 Table ( 'slice_researcher', Base.metadata,
177 Column ('slice_id', Integer, ForeignKey ('records.record_id'), primary_key=True),
178 Column ('researcher_id', Integer, ForeignKey ('records.record_id'), primary_key=True),
181 ##############################
182 # all subclasses define a convenience constructor with a default value for type,
183 # and when applicable a way to define local fields in a kwd=value argument
185 class RegAuthority(RegRecord):
186 __tablename__ = 'authorities'
187 __mapper_args__ = { 'polymorphic_identity' : 'authority' }
188 record_id = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
189 #### extensions come here
190 name = Column ('name', String)
191 #### extensions come here
192 reg_pis = relationship \
194 secondary = authority_pi_table,
195 primaryjoin = RegRecord.record_id==authority_pi_table.c.authority_id,
196 secondaryjoin = RegRecord.record_id==authority_pi_table.c.pi_id,
197 backref = 'reg_authorities_as_pi',
200 def __init__ (self, **kwds):
201 # handle local settings
203 self.name = kwds.pop('name')
204 # fill in type if not previously set
205 if 'type' not in kwds:
206 kwds['type']='authority'
207 # base class constructor
208 RegRecord.__init__(self, **kwds)
210 # no proper data yet, just hack the typename
212 result = RegRecord.__repr__(self).replace("Record", "Authority")
213 # here again trying to display names that can be utf8 is too dangerous
214 # result.replace(">", " name={}>".format(self.name))
217 def update_pis (self, pi_hrns, dbsession):
218 # strip that in case we have <researcher> words </researcher>
219 pi_hrns = [ x.strip() for x in pi_hrns ]
220 request = dbsession.query(RegUser).filter(RegUser.hrn.in_(pi_hrns))
221 logger.info("RegAuthority.update_pis: %d incoming pis, %d matches found"\
222 % (len(pi_hrns), request.count()))
223 pis = dbsession.query(RegUser).filter(RegUser.hrn.in_(pi_hrns)).all()
227 class RegSlice(RegRecord):
228 __tablename__ = 'slices'
229 __mapper_args__ = { 'polymorphic_identity' : 'slice' }
230 record_id = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
231 #### extensions come here
232 reg_researchers = relationship \
234 secondary=slice_researcher_table,
235 primaryjoin=RegRecord.record_id==slice_researcher_table.c.slice_id,
236 secondaryjoin=RegRecord.record_id==slice_researcher_table.c.researcher_id,
237 backref='reg_slices_as_researcher',
240 def __init__ (self, **kwds):
241 if 'type' not in kwds:
243 RegRecord.__init__(self, **kwds)
246 return RegRecord.__repr__(self).replace("Record", "Slice")
248 def update_researchers (self, researcher_hrns, dbsession):
249 # strip that in case we have <researcher> words </researcher>
250 researcher_hrns = [ x.strip() for x in researcher_hrns ]
251 request = dbsession.query (RegUser).filter(RegUser.hrn.in_(researcher_hrns))
252 logger.info ("RegSlice.update_researchers: %d incoming researchers, %d matches found"\
253 % (len(researcher_hrns), request.count()))
254 researchers = dbsession.query (RegUser).filter(RegUser.hrn.in_(researcher_hrns)).all()
255 self.reg_researchers = researchers
257 # when dealing with credentials, we need to retrieve the PIs attached to a slice
258 # WARNING: with the move to passing dbsessions around, we face a glitch here because this
259 # helper function is called from the trust/ area that
261 from sqlalchemy.orm import sessionmaker
262 Session = sessionmaker()
263 dbsession = Session.object_session(self)
264 from sfa.util.xrn import get_authority
265 authority_hrn = get_authority(self.hrn)
266 auth_record = dbsession.query(RegAuthority).filter_by(hrn=authority_hrn).first()
267 return auth_record.reg_pis
269 @validates ('expires')
270 def validate_expires (self, key, incoming):
271 return self.validate_datetime (key, incoming)
274 class RegNode(RegRecord):
275 __tablename__ = 'nodes'
276 __mapper_args__ = { 'polymorphic_identity' : 'node' }
277 record_id = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
279 def __init__(self, **kwds):
280 if 'type' not in kwds:
282 RegRecord.__init__(self, **kwds)
285 return RegRecord.__repr__(self).replace("Record", "Node")
288 class RegUser(RegRecord):
289 __tablename__ = 'users'
290 # these objects will have type='user' in the records table
291 __mapper_args__ = { 'polymorphic_identity' : 'user' }
292 record_id = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
293 #### extensions come here
294 email = Column ('email', String)
295 # can't use name 'keys' here because when loading from xml we're getting
296 # a 'keys' tag, and assigning a list of strings in a reference column like this crashes
297 reg_keys = relationship \
298 ('RegKey', backref='reg_user',
299 cascade = "all, delete, delete-orphan",
302 # so we can use RegUser (email=.., hrn=..) and the like
303 def __init__ (self, **kwds):
304 # handle local settings
306 self.email = kwds.pop('email')
307 if 'type' not in kwds:
308 kwds['type'] = 'user'
309 RegRecord.__init__(self, **kwds)
311 # append stuff at the end of the record __repr__
313 result = RegRecord.__repr__(self).replace("Record", "User")
314 result.replace(">", " email={}>".format(self.email))
318 def validate_email(self, key, address):
319 assert '@' in address
323 # xxx tocheck : not sure about eager loading of this one
324 # meaning, when querying the whole records, we expect there should
325 # be a single query to fetch all the keys
326 # or, is it enough that we issue a single query to retrieve all the keys
328 __tablename__ = 'keys'
329 key_id = Column (Integer, primary_key=True)
330 record_id = Column (Integer, ForeignKey ("records.record_id"))
331 key = Column (String)
332 pointer = Column (Integer, default = -1)
334 def __init__ (self, key, pointer=None):
337 self.pointer = pointer
340 result = "<key id=%s key=%s..." % (self.key_id, self.key[8:16],)
341 try: result += " user=%s" % self.reg_user.record_id
342 except: result += " no-user"
346 class SliverAllocation(Base,AlchemyObj):
347 __tablename__ = 'sliver_allocation'
348 sliver_id = Column(String, primary_key=True)
349 client_id = Column(String)
350 component_id = Column(String)
351 slice_urn = Column(String)
352 allocation_state = Column(String)
354 def __init__(self, **kwds):
355 if 'sliver_id' in kwds:
356 self.sliver_id = kwds['sliver_id']
357 if 'client_id' in kwds:
358 self.client_id = kwds['client_id']
359 if 'component_id' in kwds:
360 self.component_id = kwds['component_id']
361 if 'slice_urn' in kwds:
362 self.slice_urn = kwds['slice_urn']
363 if 'allocation_state' in kwds:
364 self.allocation_state = kwds['allocation_state']
367 result = "<sliver_allocation sliver_id=%s allocation_state=%s"\
368 % (self.sliver_id, self.allocation_state)
371 @validates('allocation_state')
372 def validate_allocation_state(self, key, state):
373 allocation_states = ['geni_unallocated', 'geni_allocated', 'geni_provisioned']
374 assert state in allocation_states
378 def set_allocations(sliver_ids, state, dbsession):
379 if not isinstance(sliver_ids, list):
380 sliver_ids = [sliver_ids]
381 sliver_state_updated = {}
382 constraint = SliverAllocation.sliver_id.in_(sliver_ids)
383 sliver_allocations = dbsession.query (SliverAllocation).filter(constraint)
384 sliver_ids_found = []
385 for sliver_allocation in sliver_allocations:
386 sliver_allocation.allocation_state = state
387 sliver_ids_found.append(sliver_allocation.sliver_id)
389 # Some states may not have been updated becuase no sliver allocation state record
390 # exists for the sliver. Insert new allocation records for these slivers and set
391 # it to geni_allocated.
392 sliver_ids_not_found = set(sliver_ids).difference(sliver_ids_found)
393 for sliver_id in sliver_ids_not_found:
394 record = SliverAllocation(sliver_id=sliver_id, allocation_state=state)
395 dbsession.add(record)
399 def delete_allocations(sliver_ids, dbsession):
400 if not isinstance(sliver_ids, list):
401 sliver_ids = [sliver_ids]
402 constraint = SliverAllocation.sliver_id.in_(sliver_ids)
403 sliver_allocations = dbsession.query(SliverAllocation).filter(constraint)
404 for sliver_allocation in sliver_allocations:
405 dbsession.delete(sliver_allocation)
408 def sync(self, dbsession):
409 constraints = [SliverAllocation.sliver_id == self.sliver_id]
410 results = dbsession.query(SliverAllocation).filter(and_(*constraints))
412 for result in results:
413 records.append(result)
419 record.sliver_id = self.sliver_id
420 record.client_id = self.client_id
421 record.component_id = self.component_id
422 record.slice_urn = self.slice_urn
423 record.allocation_state = self.allocation_state
427 ##############################
428 # although the db needs of course to be reachable for the following functions
429 # the schema management functions are here and not in alchemy
430 # because the actual details of the classes need to be known
431 # migrations: this code has no notion of the previous versions
432 # of the data model nor of migrations
433 # sfa.storage.migrations.db_init uses this when starting from
435 def init_tables(engine):
436 logger.info("Initializing db schema from current/latest model")
437 Base.metadata.create_all(engine)
439 def drop_tables(engine):
440 logger.info("Dropping tables from current/latest model")
441 Base.metadata.drop_all(engine)
443 ##############################
444 # create a record of the right type from either a dict or an xml string
445 def make_record (dict=None, xml=""):
446 if dict is None: dict={}
447 if dict: return make_record_dict (dict)
448 elif xml: return make_record_xml (xml)
449 else: raise Exception("make_record has no input")
451 # convert an incoming record - typically from xmlrpc - into an object
452 def make_record_dict (record_dict):
453 assert ('type' in record_dict)
454 type = record_dict['type'].split('+')[0]
455 if type == 'authority':
456 result = RegAuthority (dict=record_dict)
458 result = RegUser (dict=record_dict)
459 elif type == 'slice':
460 result = RegSlice (dict=record_dict)
462 result = RegNode (dict=record_dict)
464 logger.debug("Untyped RegRecord instance")
465 result = RegRecord (dict=record_dict)
466 logger.info("converting dict into Reg* with type=%s"%type)
467 logger.info("returning=%s"%result)
469 # register non-db attributes in an extensions field
472 def make_record_xml (xml_str):
474 xml_dict = xml.todict()
475 logger.info("load from xml, keys=%s"%xml_dict.keys())
476 return make_record_dict (xml_dict)
479 # augment local records with data from builtin relationships
480 # expose related objects as a list of hrns
481 # we pick names that clearly won't conflict with the ones used in the old approach,
482 # were the relationships data came from the testbed side
483 # for each type, a dict of the form {<field-name-exposed-in-record>:<alchemy_accessor_name>}
484 # so after that, an 'authority' record will e.g. have a 'reg-pis' field with the hrns of its pi-users
485 augment_map = {'authority': {'reg-pis' : 'reg_pis',},
486 'slice': {'reg-researchers' : 'reg_researchers',},
487 'user': {'reg-pi-authorities' : 'reg_authorities_as_pi',
488 'reg-slices' : 'reg_slices_as_researcher',},
493 # the way we use sqlalchemy might be a little wrong
494 # in any case what has been observed is that (Reg)Records as returned by an sqlalchemy
495 # query not always have their __dict__ properly adjusted
496 # typically a RegAuthority object would have its object.name set properly, but
497 # object.__dict__ has no 'name' key
498 # which is an issue because we rely on __dict__ for many things, in particular this
499 # is what gets exposed to the drivers (this is historical and dates back before sqlalchemy)
500 # so it is recommended to always run this function that will make sure
501 # that such built-in fields are properly set in __dict__ too
503 def augment_with_sfa_builtins(local_record):
504 # don't ruin the import of that file in a client world
505 from sfa.util.xrn import Xrn
507 setattr(local_record, 'reg-urn', Xrn(xrn=local_record.hrn, type=local_record.type).urn)
508 # users have keys and this is needed to synthesize 'users' sent over to CreateSliver
510 if local_record.type == 'user':
511 user_keys = [ key.key for key in local_record.reg_keys ]
512 setattr(local_record, 'reg-keys', user_keys)
513 fields_to_check = ['email']
514 elif local_record.type == 'authority':
515 fields_to_check = ['name']
516 for field in fields_to_check:
517 if not field in local_record.__dict__:
518 logger.debug("augment_with_sfa_builtins: hotfixing missing '{}' in {}"
519 .format(field, local_record.hrn))
520 local_record.__dict__[field] = getattr(local_record, field)
521 # search in map according to record type
522 type_map = augment_map.get(local_record.type, {})
523 # use type-dep. map to do the job
524 for (field_name, attribute) in type_map.items():
525 # get related objects
526 related_records = getattr(local_record, attribute, [])
527 hrns = [ r.hrn for r in related_records ]
528 setattr (local_record, field_name, hrns)