missing import and adds validation hooks for datetime columns
[sfa.git] / sfa / storage / model.py
1 from types import StringTypes
2 from datetime import datetime
3
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
11
12 from sfa.util.sfalogging import logger
13 from sfa.util.sfatime import utcparse, datetime_to_string
14 from sfa.util.xml import XML 
15
16 from sfa.trust.gid import GID
17
18 ##############################
19 Base=declarative_base()
20
21 ####################
22 # dicts vs objects
23 ####################
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
28
29 # here are a few utilities for this 
30
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 
35 #
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:
40 # . dict(obj)
41 # . obj.todict()
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
45 #
46 # (*) finally for converting a dictionary into an sqlalchemy object, we provide
47 # obj.load_from_dict(dict)
48
49 class AlchemyObj:
50     def __iter__(self): 
51         self._i = iter(object_mapper(self).columns)
52         return self 
53     def next(self): 
54         n = self._i.next().name
55         return n, getattr(self, n)
56     def todict (self):
57         d=self.__dict__
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():
62             # experimental
63             if isinstance(v, StringTypes) and v.lower() in ['true']: v=True
64             if isinstance(v, StringTypes) and v.lower() in ['false']: v=False
65             setattr(self,k,v)
66
67     def validate_datetime (self, key, incoming):
68         if isinstance (incoming, datetime):     return incoming
69         elif isinstance (incoming, (int,float)):return datetime.fromtimestamp (incoming)
70
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):
75         fields=self.fields
76         if isinstance(fields,dict): fields=fields.keys()
77         return fields
78
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()
85
86     def dump(self, format=None, dump_parents=False):
87         if not format:
88             format = 'text'
89         else:
90             format = format.lower()
91         if format == 'text':
92             self.dump_text(dump_parents)
93         elif format == 'xml':
94             print self.save_to_string()
95         elif format == 'simple':
96             print self.dump_simple()
97         else:
98             raise Exception, "Invalid format %s" % format
99    
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)])
104         print "RECORD"
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
112         print "    gid:"
113         print "\t\t", self.get_gid_object().dump_string(8, dump_parents)  
114         
115         # print remaining fields
116         for attrib_name in dir(self):
117             # skip core fields
118             if attrib_name in core_fields:
119                 continue
120             # skik callables 
121             attrib = getattr(self, attrib_name)
122             if callable(attrib):
123                 continue
124             print "     %s: %s" % (attrib_name, attrib)
125     
126     def dump_simple(self):
127         return "Record(record_id=%s, hrn=%s, type=%s, authority=%s, pointer=%s)" % \
128                 (self.record_id, self.hrn, self.type, self.authority, self.pointer)
129       
130 #    # only intended for debugging 
131 #    def inspect (self, logger, message=""):
132 #        logger.info("%s -- Inspecting AlchemyObj -- attrs"%message)
133 #        for k in dir(self):
134 #            if not k.startswith('_'):
135 #                logger.info ("  %s: %s"%(k,getattr(self,k)))
136 #        logger.info("%s -- Inspecting AlchemyObj -- __dict__"%message)
137 #        d=self.__dict__
138 #        for (k,v) in d.iteritems():
139 #            logger.info("[%s]=%s"%(k,v))
140
141
142 ##############################
143 # various kinds of records are implemented as an inheritance hierarchy
144 # RegRecord is the base class for all actual variants
145 # a first draft was using 'type' as the discriminator for the inheritance
146 # but we had to define another more internal column (classtype) so we 
147 # accomodate variants in types like authority+am and the like
148
149 class RegRecord (Base,AlchemyObj):
150     __tablename__       = 'records'
151     record_id           = Column (Integer, primary_key=True)
152     # this is the discriminator that tells which class to use
153     classtype           = Column (String)
154     # in a first version type was the discriminator
155     # but that could not accomodate for 'authority+sa' and the like
156     type                = Column (String)
157     hrn                 = Column (String)
158     gid                 = Column (String)
159     authority           = Column (String)
160     peer_authority      = Column (String)
161     pointer             = Column (Integer, default=-1)
162     date_created        = Column (DateTime)
163     last_updated        = Column (DateTime)
164     # use the 'type' column to decide which subclass the object is of
165     __mapper_args__     = { 'polymorphic_on' : classtype }
166
167     fields = [ 'type', 'hrn', 'gid', 'authority', 'peer_authority' ]
168     def __init__ (self, type=None, hrn=None, gid=None, authority=None, peer_authority=None, 
169                   pointer=None, dict=None):
170         if type:                                self.type=type
171         if hrn:                                 self.hrn=hrn
172         if gid: 
173             if isinstance(gid, StringTypes):    self.gid=gid
174             else:                               self.gid=gid.save_to_string(save_parents=True)
175         if authority:                           self.authority=authority
176         if peer_authority:                      self.peer_authority=peer_authority
177         if pointer:                             self.pointer=pointer
178         if dict:                                self.load_from_dict (dict)
179
180     def __repr__(self):
181         result="<Record id=%s, type=%s, hrn=%s, authority=%s, pointer=%s" % \
182                 (self.record_id, self.type, self.hrn, self.authority, self.pointer)
183         # skip the uniform '--- BEGIN CERTIFICATE --' stuff
184         if self.gid: result+=" gid=%s..."%self.gid[28:36]
185         else: result+=" nogid"
186         result += ">"
187         return result
188
189     @validates ('gid')
190     def validate_gid (self, key, gid):
191         if gid is None:                     return
192         elif isinstance(gid, StringTypes):  return gid
193         else:                               return gid.save_to_string(save_parents=True)
194
195     @validates ('date_created')
196     def validate_date_created (self, key, incoming): return self.validate_datetime (key, incoming)
197
198     @validates ('last_updated')
199     def validate_last_updated (self, key, incoming): return self.validate_datetime (key, incoming)
200
201     # xxx - there might be smarter ways to handle get/set'ing gid using validation hooks 
202     def get_gid_object (self):
203         if not self.gid: return None
204         else: return GID(string=self.gid)
205
206     def just_created (self):
207         now=datetime.now()
208         self.date_created=now
209         self.last_updated=now
210
211     def just_updated (self):
212         now=datetime.now()
213         self.last_updated=now
214
215 ##############################
216 # all subclasses define a convenience constructor with a default value for type, 
217 # and when applicable a way to define local fields in a kwd=value argument
218 ####################
219 class RegAuthority (RegRecord):
220     __tablename__       = 'authorities'
221     __mapper_args__     = { 'polymorphic_identity' : 'authority' }
222     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
223     
224     def __init__ (self, **kwds):
225         # fill in type if not previously set
226         if 'type' not in kwds: kwds['type']='authority'
227         # base class constructor
228         RegRecord.__init__(self, **kwds)
229
230     # no proper data yet, just hack the typename
231     def __repr__ (self):
232         return RegRecord.__repr__(self).replace("Record","Authority")
233
234 ####################
235 # slice x user (researchers) association
236 slice_researcher_table = \
237     Table ( 'slice_researcher', Base.metadata,
238             Column ('slice_id', Integer, ForeignKey ('records.record_id'), primary_key=True),
239             Column ('researcher_id', Integer, ForeignKey ('records.record_id'), primary_key=True),
240             )
241
242 ####################
243 class RegSlice (RegRecord):
244     __tablename__       = 'slices'
245     __mapper_args__     = { 'polymorphic_identity' : 'slice' }
246     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
247     #### extensions come here
248     reg_researchers     = relationship \
249         ('RegUser', 
250          secondary=slice_researcher_table,
251          primaryjoin=RegRecord.record_id==slice_researcher_table.c.slice_id,
252          secondaryjoin=RegRecord.record_id==slice_researcher_table.c.researcher_id,
253          backref="reg_slices_as_researcher")
254
255     def __init__ (self, **kwds):
256         if 'type' not in kwds: kwds['type']='slice'
257         RegRecord.__init__(self, **kwds)
258
259     def __repr__ (self):
260         return RegRecord.__repr__(self).replace("Record","Slice")
261
262 ####################
263 class RegNode (RegRecord):
264     __tablename__       = 'nodes'
265     __mapper_args__     = { 'polymorphic_identity' : 'node' }
266     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
267     
268     def __init__ (self, **kwds):
269         if 'type' not in kwds: kwds['type']='node'
270         RegRecord.__init__(self, **kwds)
271
272     def __repr__ (self):
273         return RegRecord.__repr__(self).replace("Record","Node")
274
275 ####################
276 class RegUser (RegRecord):
277     __tablename__       = 'users'
278     # these objects will have type='user' in the records table
279     __mapper_args__     = { 'polymorphic_identity' : 'user' }
280     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
281     #### extensions come here
282     email               = Column ('email', String)
283     # can't use name 'keys' here because when loading from xml we're getting
284     # a 'keys' tag, and assigning a list of strings in a reference column like this crashes
285     reg_keys            = relationship \
286         ('RegKey', backref='reg_user',
287          cascade="all, delete, delete-orphan")
288     
289     # so we can use RegUser (email=.., hrn=..) and the like
290     def __init__ (self, **kwds):
291         # handle local settings
292         if 'email' in kwds: self.email=kwds.pop('email')
293         if 'type' not in kwds: kwds['type']='user'
294         RegRecord.__init__(self, **kwds)
295
296     # append stuff at the end of the record __repr__
297     def __repr__ (self): 
298         result = RegRecord.__repr__(self).replace("Record","User")
299         result.replace (">"," email=%s"%self.email)
300         result += ">"
301         return result
302
303     @validates('email') 
304     def validate_email(self, key, address):
305         assert '@' in address
306         return address
307
308 ####################
309 # xxx tocheck : not sure about eager loading of this one
310 # meaning, when querying the whole records, we expect there should
311 # be a single query to fetch all the keys 
312 # or, is it enough that we issue a single query to retrieve all the keys 
313 class RegKey (Base):
314     __tablename__       = 'keys'
315     key_id              = Column (Integer, primary_key=True)
316     record_id             = Column (Integer, ForeignKey ("records.record_id"))
317     key                 = Column (String)
318     pointer             = Column (Integer, default = -1)
319     
320     def __init__ (self, key, pointer=None):
321         self.key=key
322         if pointer: self.pointer=pointer
323
324     def __repr__ (self):
325         result="<key id=%s key=%s..."%(self.key_id,self.key[8:16],)
326         try:    result += " user=%s"%self.reg_user.record_id
327         except: result += " no-user"
328         result += ">"
329         return result
330
331 ##############################
332 # although the db needs of course to be reachable for the following functions
333 # the schema management functions are here and not in alchemy
334 # because the actual details of the classes need to be known
335 # migrations: this code has no notion of the previous versions
336 # of the data model nor of migrations
337 # sfa.storage.migrations.db_init uses this when starting from
338 # a fresh db only
339 def init_tables(engine):
340     logger.info("Initializing db schema from current/latest model")
341     Base.metadata.create_all(engine)
342
343 def drop_tables(engine):
344     logger.info("Dropping tables from current/latest model")
345     Base.metadata.drop_all(engine)
346
347 ##############################
348 # create a record of the right type from either a dict or an xml string
349 def make_record (dict={}, xml=""):
350     if dict:    return make_record_dict (dict)
351     elif xml:   return make_record_xml (xml)
352     else:       raise Exception("make_record has no input")
353
354 # convert an incoming record - typically from xmlrpc - into an object
355 def make_record_dict (record_dict):
356     assert ('type' in record_dict)
357     type=record_dict['type'].split('+')[0]
358     if type=='authority':
359         result=RegAuthority (dict=record_dict)
360     elif type=='user':
361         result=RegUser (dict=record_dict)
362     elif type=='slice':
363         result=RegSlice (dict=record_dict)
364     elif type=='node':
365         result=RegNode (dict=record_dict)
366     else:
367         logger.debug("Untyped RegRecord instance")
368         result=RegRecord (dict=record_dict)
369     logger.info ("converting dict into Reg* with type=%s"%type)
370     logger.info ("returning=%s"%result)
371     # xxx todo
372     # register non-db attributes in an extensions field
373     return result
374         
375 def make_record_xml (xml):
376     xml_record = XML(xml)
377     xml_dict = xml_record.todict()
378     logger.info("load from xml, keys=%s"%xml_dict.keys())
379     return make_record_dict (xml_dict)
380