Merge branch 'master' into sqlalchemy
[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 self.get_gid_object().dump_string(8, dump_parents)  
114         
115         # print remaining fields
116         for attrib_name in dir(self):
117             attrib = getattr(self, attrib_name)
118             # skip internals
119             if attrib_name.startswith('_'):     continue
120             # skip core fields
121             if attrib_name in core_fields:      continue
122             # skip callables 
123             if callable (attrib):               continue
124             print "     %s: %s" % (attrib_name, attrib)
125     
126     def dump_simple(self):
127         return "%s"%self
128       
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)
136 #        d=self.__dict__
137 #        for (k,v) in d.iteritems():
138 #            logger.info("[%s]=%s"%(k,v))
139
140
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
147
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 }
165
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
170         if hrn:                                 self.hrn=hrn
171         if gid: 
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)
178
179     def __repr__(self):
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"
185         result += ">"
186         return result
187
188     @validates ('gid')
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)
193
194     @validates ('date_created')
195     def validate_date_created (self, key, incoming): return self.validate_datetime (key, incoming)
196
197     @validates ('last_updated')
198     def validate_last_updated (self, key, incoming): return self.validate_datetime (key, incoming)
199
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)
204
205     def just_created (self):
206         now=datetime.now()
207         self.date_created=now
208         self.last_updated=now
209
210     def just_updated (self):
211         now=datetime.now()
212         self.last_updated=now
213
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
217 ####################
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)
222     
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)
228
229     # no proper data yet, just hack the typename
230     def __repr__ (self):
231         return RegRecord.__repr__(self).replace("Record","Authority")
232
233 ####################
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),
239             )
240
241 ####################
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 \
248         ('RegUser', 
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")
253
254     def __init__ (self, **kwds):
255         if 'type' not in kwds: kwds['type']='slice'
256         RegRecord.__init__(self, **kwds)
257
258     def __repr__ (self):
259         return RegRecord.__repr__(self).replace("Record","Slice")
260
261 ####################
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)
266     
267     def __init__ (self, **kwds):
268         if 'type' not in kwds: kwds['type']='node'
269         RegRecord.__init__(self, **kwds)
270
271     def __repr__ (self):
272         return RegRecord.__repr__(self).replace("Record","Node")
273
274 ####################
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")
287     
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)
294
295     # append stuff at the end of the record __repr__
296     def __repr__ (self): 
297         result = RegRecord.__repr__(self).replace("Record","User")
298         result.replace (">"," email=%s"%self.email)
299         result += ">"
300         return result
301
302     @validates('email') 
303     def validate_email(self, key, address):
304         assert '@' in address
305         return address
306
307 ####################
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 
312 class RegKey (Base):
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)
318     
319     def __init__ (self, key, pointer=None):
320         self.key=key
321         if pointer: self.pointer=pointer
322
323     def __repr__ (self):
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"
327         result += ">"
328         return result
329
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
337 # a fresh db only
338 def init_tables(engine):
339     logger.info("Initializing db schema from current/latest model")
340     Base.metadata.create_all(engine)
341
342 def drop_tables(engine):
343     logger.info("Dropping tables from current/latest model")
344     Base.metadata.drop_all(engine)
345
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")
352
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)
359     elif type=='user':
360         result=RegUser (dict=record_dict)
361     elif type=='slice':
362         result=RegSlice (dict=record_dict)
363     elif type=='node':
364         result=RegNode (dict=record_dict)
365     else:
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)
370     # xxx todo
371     # register non-db attributes in an extensions field
372     return result
373         
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)
379