1 from types import StringTypes
2 from datetime import datetime
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.util.sfalogging import logger
13 from sfa.util.sfatime import utcparse, datetime_to_string
14 from sfa.util.xml import XML
16 from sfa.trust.gid import GID
18 ##############################
19 Base=declarative_base()
24 # historically the front end to the db dealt with dicts, so the code was only dealing with dicts
25 # sqlalchemy however offers an object interface, meaning that you write obj.id instead of obj['id']
26 # which is admittedly much nicer
27 # however we still need to deal with dictionaries if only for the xmlrpc layer
29 # here are a few utilities for this
31 # (*) first off, when an old pieve of code needs to be used as-is, if only temporarily, the simplest trick
32 # is to use obj.__dict__
33 # this behaves exactly like required, i.e. obj.__dict__['field']='new value' does change obj.field
34 # however this depends on sqlalchemy's implementation so it should be avoided
36 # (*) second, when an object needs to be exposed to the xmlrpc layer, we need to convert it into a dict
37 # remember though that writing the resulting dictionary won't change the object
38 # essentially obj.__dict__ would be fine too, except that we want to discard alchemy private keys starting with '_'
39 # 2 ways are provided for that:
42 # the former dict(obj) relies on __iter__() and next() below, and does not rely on the fields names
43 # although it seems to work fine, I've found cases where it issues a weird python error that I could not get right
44 # 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
46 # (*) finally for converting a dictionary into an sqlalchemy object, we provide
47 # obj.load_from_dict(dict)
51 self._i = iter(object_mapper(self).columns)
54 n = self._i.next().name
55 return n, getattr(self, n)
58 keys=[k for k in d.keys() if not k.startswith('_')]
59 return dict ( [ (k,d[k]) for k in keys ] )
60 def load_from_dict (self, d):
61 for (k,v) in d.iteritems():
63 if isinstance(v, StringTypes) and v.lower() in ['true']: v=True
64 if isinstance(v, StringTypes) and v.lower() in ['false']: v=False
67 def validate_datetime (self, key, incoming):
68 if isinstance (incoming, datetime): return incoming
69 elif isinstance (incoming, (int,float)):return datetime.fromtimestamp (incoming)
71 # in addition we provide convenience for converting to and from xml records
72 # for this purpose only, we need the subclasses to define 'fields' as either
73 # a list or a dictionary
74 def xml_fields (self):
76 if isinstance(fields,dict): fields=fields.keys()
79 def save_as_xml (self):
80 # xxx not sure about the scope here
81 input_dict = dict( [ (key, getattr(self.key), ) for key in self.xml_fields() if getattr(self,key,None) ] )
82 xml_record=XML("<record />")
83 xml_record.parse_dict (input_dict)
84 return xml_record.toxml()
86 def dump(self, format=None, dump_parents=False):
90 format = format.lower()
92 self.dump_text(dump_parents)
94 print self.save_to_string()
95 elif format == 'simple':
96 print self.dump_simple()
98 raise Exception, "Invalid format %s" % format
100 def dump_text(self, dump_parents=False):
101 # print core fields in this order
102 core_fields = [ 'hrn', 'type', 'authority', 'date_created', 'last_updated', 'gid', ]
103 print "".join(['=' for i in range(40)])
105 print " hrn:", self.hrn
106 print " type:", self.type
107 print " authority:", self.authority
108 date_created = utcparse(datetime_to_string(self.date_created))
109 print " date created:", date_created
110 last_updated = utcparse(datetime_to_string(self.last_updated))
111 print " last updated:", last_updated
113 print self.get_gid_object().dump_string(8, dump_parents)
115 # print remaining fields
116 for attrib_name in dir(self):
117 attrib = getattr(self, attrib_name)
119 if attrib_name.startswith('_'): continue
121 if attrib_name in core_fields: continue
123 if callable (attrib): continue
124 print " %s: %s" % (attrib_name, attrib)
126 def dump_simple(self):
129 # # only intended for debugging
130 # def inspect (self, logger, message=""):
131 # logger.info("%s -- Inspecting AlchemyObj -- attrs"%message)
132 # for k in dir(self):
133 # if not k.startswith('_'):
134 # logger.info (" %s: %s"%(k,getattr(self,k)))
135 # logger.info("%s -- Inspecting AlchemyObj -- __dict__"%message)
137 # for (k,v) in d.iteritems():
138 # logger.info("[%s]=%s"%(k,v))
141 ##############################
142 # various kinds of records are implemented as an inheritance hierarchy
143 # RegRecord is the base class for all actual variants
144 # a first draft was using 'type' as the discriminator for the inheritance
145 # but we had to define another more internal column (classtype) so we
146 # accomodate variants in types like authority+am and the like
148 class RegRecord (Base,AlchemyObj):
149 __tablename__ = 'records'
150 record_id = Column (Integer, primary_key=True)
151 # this is the discriminator that tells which class to use
152 classtype = Column (String)
153 # in a first version type was the discriminator
154 # but that could not accomodate for 'authority+sa' and the like
155 type = Column (String)
156 hrn = Column (String)
157 gid = Column (String)
158 authority = Column (String)
159 peer_authority = Column (String)
160 pointer = Column (Integer, default=-1)
161 date_created = Column (DateTime)
162 last_updated = Column (DateTime)
163 # use the 'type' column to decide which subclass the object is of
164 __mapper_args__ = { 'polymorphic_on' : classtype }
166 fields = [ 'type', 'hrn', 'gid', 'authority', 'peer_authority' ]
167 def __init__ (self, type=None, hrn=None, gid=None, authority=None, peer_authority=None,
168 pointer=None, dict=None):
169 if type: self.type=type
172 if isinstance(gid, StringTypes): self.gid=gid
173 else: self.gid=gid.save_to_string(save_parents=True)
174 if authority: self.authority=authority
175 if peer_authority: self.peer_authority=peer_authority
176 if pointer: self.pointer=pointer
177 if dict: self.load_from_dict (dict)
180 result="<Record id=%s, type=%s, hrn=%s, authority=%s, pointer=%s" % \
181 (self.record_id, self.type, self.hrn, self.authority, self.pointer)
182 # skip the uniform '--- BEGIN CERTIFICATE --' stuff
183 if self.gid: result+=" gid=%s..."%self.gid[28:36]
184 else: result+=" nogid"
189 def validate_gid (self, key, gid):
190 if gid is None: return
191 elif isinstance(gid, StringTypes): return gid
192 else: return gid.save_to_string(save_parents=True)
194 @validates ('date_created')
195 def validate_date_created (self, key, incoming): return self.validate_datetime (key, incoming)
197 @validates ('last_updated')
198 def validate_last_updated (self, key, incoming): return self.validate_datetime (key, incoming)
200 # xxx - there might be smarter ways to handle get/set'ing gid using validation hooks
201 def get_gid_object (self):
202 if not self.gid: return None
203 else: return GID(string=self.gid)
205 def just_created (self):
207 self.date_created=now
208 self.last_updated=now
210 def just_updated (self):
212 self.last_updated=now
214 ##############################
215 # all subclasses define a convenience constructor with a default value for type,
216 # and when applicable a way to define local fields in a kwd=value argument
218 class RegAuthority (RegRecord):
219 __tablename__ = 'authorities'
220 __mapper_args__ = { 'polymorphic_identity' : 'authority' }
221 record_id = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
223 def __init__ (self, **kwds):
224 # fill in type if not previously set
225 if 'type' not in kwds: kwds['type']='authority'
226 # base class constructor
227 RegRecord.__init__(self, **kwds)
229 # no proper data yet, just hack the typename
231 return RegRecord.__repr__(self).replace("Record","Authority")
234 # slice x user (researchers) association
235 slice_researcher_table = \
236 Table ( 'slice_researcher', Base.metadata,
237 Column ('slice_id', Integer, ForeignKey ('records.record_id'), primary_key=True),
238 Column ('researcher_id', Integer, ForeignKey ('records.record_id'), primary_key=True),
242 class RegSlice (RegRecord):
243 __tablename__ = 'slices'
244 __mapper_args__ = { 'polymorphic_identity' : 'slice' }
245 record_id = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
246 #### extensions come here
247 reg_researchers = relationship \
249 secondary=slice_researcher_table,
250 primaryjoin=RegRecord.record_id==slice_researcher_table.c.slice_id,
251 secondaryjoin=RegRecord.record_id==slice_researcher_table.c.researcher_id,
252 backref="reg_slices_as_researcher")
254 def __init__ (self, **kwds):
255 if 'type' not in kwds: kwds['type']='slice'
256 RegRecord.__init__(self, **kwds)
259 return RegRecord.__repr__(self).replace("Record","Slice")
262 class RegNode (RegRecord):
263 __tablename__ = 'nodes'
264 __mapper_args__ = { 'polymorphic_identity' : 'node' }
265 record_id = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
267 def __init__ (self, **kwds):
268 if 'type' not in kwds: kwds['type']='node'
269 RegRecord.__init__(self, **kwds)
272 return RegRecord.__repr__(self).replace("Record","Node")
275 class RegUser (RegRecord):
276 __tablename__ = 'users'
277 # these objects will have type='user' in the records table
278 __mapper_args__ = { 'polymorphic_identity' : 'user' }
279 record_id = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
280 #### extensions come here
281 email = Column ('email', String)
282 # can't use name 'keys' here because when loading from xml we're getting
283 # a 'keys' tag, and assigning a list of strings in a reference column like this crashes
284 reg_keys = relationship \
285 ('RegKey', backref='reg_user',
286 cascade="all, delete, delete-orphan")
288 # so we can use RegUser (email=.., hrn=..) and the like
289 def __init__ (self, **kwds):
290 # handle local settings
291 if 'email' in kwds: self.email=kwds.pop('email')
292 if 'type' not in kwds: kwds['type']='user'
293 RegRecord.__init__(self, **kwds)
295 # append stuff at the end of the record __repr__
297 result = RegRecord.__repr__(self).replace("Record","User")
298 result.replace (">"," email=%s"%self.email)
303 def validate_email(self, key, address):
304 assert '@' in address
308 # xxx tocheck : not sure about eager loading of this one
309 # meaning, when querying the whole records, we expect there should
310 # be a single query to fetch all the keys
311 # or, is it enough that we issue a single query to retrieve all the keys
313 __tablename__ = 'keys'
314 key_id = Column (Integer, primary_key=True)
315 record_id = Column (Integer, ForeignKey ("records.record_id"))
316 key = Column (String)
317 pointer = Column (Integer, default = -1)
319 def __init__ (self, key, pointer=None):
321 if pointer: self.pointer=pointer
324 result="<key id=%s key=%s..."%(self.key_id,self.key[8:16],)
325 try: result += " user=%s"%self.reg_user.record_id
326 except: result += " no-user"
330 ##############################
331 # although the db needs of course to be reachable for the following functions
332 # the schema management functions are here and not in alchemy
333 # because the actual details of the classes need to be known
334 # migrations: this code has no notion of the previous versions
335 # of the data model nor of migrations
336 # sfa.storage.migrations.db_init uses this when starting from
338 def init_tables(engine):
339 logger.info("Initializing db schema from current/latest model")
340 Base.metadata.create_all(engine)
342 def drop_tables(engine):
343 logger.info("Dropping tables from current/latest model")
344 Base.metadata.drop_all(engine)
346 ##############################
347 # create a record of the right type from either a dict or an xml string
348 def make_record (dict={}, xml=""):
349 if dict: return make_record_dict (dict)
350 elif xml: return make_record_xml (xml)
351 else: raise Exception("make_record has no input")
353 # convert an incoming record - typically from xmlrpc - into an object
354 def make_record_dict (record_dict):
355 assert ('type' in record_dict)
356 type=record_dict['type'].split('+')[0]
357 if type=='authority':
358 result=RegAuthority (dict=record_dict)
360 result=RegUser (dict=record_dict)
362 result=RegSlice (dict=record_dict)
364 result=RegNode (dict=record_dict)
366 logger.debug("Untyped RegRecord instance")
367 result=RegRecord (dict=record_dict)
368 logger.info ("converting dict into Reg* with type=%s"%type)
369 logger.info ("returning=%s"%result)
371 # register non-db attributes in an extensions field
374 def make_record_xml (xml):
375 xml_record = XML(xml)
376 xml_dict = xml_record.todict()
377 logger.info("load from xml, keys=%s"%xml_dict.keys())
378 return make_record_dict (xml_dict)