cascade delete so that unreferenced keys get deleted
[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.xml import XML 
14
15 from sfa.trust.gid import GID
16
17 ##############################
18 Base=declarative_base()
19
20 ####################
21 # dicts vs objects
22 ####################
23 # historically the front end to the db dealt with dicts, so the code was only dealing with dicts
24 # sqlalchemy however offers an object interface, meaning that you write obj.id instead of obj['id']
25 # which is admittedly much nicer
26 # however we still need to deal with dictionaries if only for the xmlrpc layer
27
28 # here are a few utilities for this 
29
30 # (*) first off, when an old pieve of code needs to be used as-is, if only temporarily, the simplest trick
31 # is to use obj.__dict__
32 # this behaves exactly like required, i.e. obj.__dict__['field']='new value' does change obj.field
33 # however this depends on sqlalchemy's implementation so it should be avoided 
34 #
35 # (*) second, when an object needs to be exposed to the xmlrpc layer, we need to convert it into a dict
36 # remember though that writing the resulting dictionary won't change the object
37 # essentially obj.__dict__ would be fine too, except that we want to discard alchemy private keys starting with '_'
38 # 2 ways are provided for that:
39 # . dict(obj)
40 # . obj.todict()
41 # the former dict(obj) relies on __iter__() and next() below, and does not rely on the fields names
42 # although it seems to work fine, I've found cases where it issues a weird python error that I could not get right
43 # 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
44 #
45 # (*) finally for converting a dictionary into an sqlalchemy object, we provide
46 # obj.load_from_dict(dict)
47
48 class AlchemyObj:
49     def __iter__(self): 
50         self._i = iter(object_mapper(self).columns)
51         return self 
52     def next(self): 
53         n = self._i.next().name
54         return n, getattr(self, n)
55     def todict (self):
56         d=self.__dict__
57         keys=[k for k in d.keys() if not k.startswith('_')]
58         return dict ( [ (k,d[k]) for k in keys ] )
59     def load_from_dict (self, d):
60         for (k,v) in d.iteritems():
61             # experimental
62             if isinstance(v, StringTypes) and v.lower() in ['true']: v=True
63             if isinstance(v, StringTypes) and v.lower() in ['false']: v=False
64             setattr(self,k,v)
65     
66     # in addition we provide convenience for converting to and from xml records
67     # for this purpose only, we need the subclasses to define 'fields' as either 
68     # a list or a dictionary
69     def xml_fields (self):
70         fields=self.fields
71         if isinstance(fields,dict): fields=fields.keys()
72         return fields
73
74     def save_as_xml (self):
75         # xxx not sure about the scope here
76         input_dict = dict( [ (key, getattr(self.key), ) for key in self.xml_fields() if getattr(self,key,None) ] )
77         xml_record=XML("<record />")
78         xml_record.parse_dict (input_dict)
79         return xml_record.toxml()
80
81     def dump(self, dump_parents=False):
82         for key in self.fields:
83             if key == 'gid' and self.gid:
84                 gid = GID(string=self.gid)
85                 print "    %s:" % key
86                 gid.dump(8, dump_parents)
87             elif getattr(self,key,None):    
88                 print "    %s: %s" % (key, getattr(self,key))
89     
90 #    # only intended for debugging 
91 #    def inspect (self, logger, message=""):
92 #        logger.info("%s -- Inspecting AlchemyObj -- attrs"%message)
93 #        for k in dir(self):
94 #            if not k.startswith('_'):
95 #                logger.info ("  %s: %s"%(k,getattr(self,k)))
96 #        logger.info("%s -- Inspecting AlchemyObj -- __dict__"%message)
97 #        d=self.__dict__
98 #        for (k,v) in d.iteritems():
99 #            logger.info("[%s]=%s"%(k,v))
100
101
102 ##############################
103 # various kinds of records are implemented as an inheritance hierarchy
104 # RegRecord is the base class for all actual variants
105 # a first draft was using 'type' as the discriminator for the inheritance
106 # but we had to define another more internal column (classtype) so we 
107 # accomodate variants in types like authority+am and the like
108
109 class RegRecord (Base,AlchemyObj):
110     __tablename__       = 'records'
111     record_id           = Column (Integer, primary_key=True)
112     # this is the discriminator that tells which class to use
113     classtype           = Column (String)
114     # in a first version type was the discriminator
115     # but that could not accomodate for 'authority+sa' and the like
116     type                = Column (String)
117     hrn                 = Column (String)
118     gid                 = Column (String)
119     authority           = Column (String)
120     peer_authority      = Column (String)
121     pointer             = Column (Integer, default=-1)
122     date_created        = Column (DateTime)
123     last_updated        = Column (DateTime)
124     # use the 'type' column to decide which subclass the object is of
125     __mapper_args__     = { 'polymorphic_on' : classtype }
126
127     fields = [ 'type', 'hrn', 'gid', 'authority', 'peer_authority' ]
128     def __init__ (self, type=None, hrn=None, gid=None, authority=None, peer_authority=None, 
129                   pointer=None, dict=None):
130         if type:                                self.type=type
131         if hrn:                                 self.hrn=hrn
132         if gid: 
133             if isinstance(gid, StringTypes):    self.gid=gid
134             else:                               self.gid=gid.save_to_string(save_parents=True)
135         if authority:                           self.authority=authority
136         if peer_authority:                      self.peer_authority=peer_authority
137         if pointer:                             self.pointer=pointer
138         if dict:                                self.load_from_dict (dict)
139
140     def __repr__(self):
141         result="<Record id=%s, type=%s, hrn=%s, authority=%s, pointer=%s" % \
142                 (self.record_id, self.type, self.hrn, self.authority, self.pointer)
143         # skip the uniform '--- BEGIN CERTIFICATE --' stuff
144         if self.gid: result+=" gid=%s..."%self.gid[28:36]
145         else: result+=" nogid"
146         result += ">"
147         return result
148
149     @validates ('gid')
150     def validate_gid (self, key, gid):
151         if gid is None:                     return
152         elif isinstance(gid, StringTypes):  return gid
153         else:                               return gid.save_to_string(save_parents=True)
154
155     # xxx - there might be smarter ways to handle get/set'ing gid using validation hooks 
156     def get_gid_object (self):
157         if not self.gid: return None
158         else: return GID(string=self.gid)
159
160     def just_created (self):
161         now=datetime.now()
162         self.date_created=now
163         self.last_updated=now
164
165     def just_updated (self):
166         now=datetime.now()
167         self.last_updated=now
168
169 ##############################
170 # all subclasses define a convenience constructor with a default value for type, 
171 # and when applicable a way to define local fields in a kwd=value argument
172 ####################
173 class RegAuthority (RegRecord):
174     __tablename__       = 'authorities'
175     __mapper_args__     = { 'polymorphic_identity' : 'authority' }
176     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
177     
178     def __init__ (self, **kwds):
179         # fill in type if not previously set
180         if 'type' not in kwds: kwds['type']='authority'
181         # base class constructor
182         RegRecord.__init__(self, **kwds)
183
184     # no proper data yet, just hack the typename
185     def __repr__ (self):
186         return RegRecord.__repr__(self).replace("Record","Authority")
187
188 ####################
189 class RegSlice (RegRecord):
190     __tablename__       = 'slices'
191     __mapper_args__     = { 'polymorphic_identity' : 'slice' }
192     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
193     
194     def __init__ (self, **kwds):
195         if 'type' not in kwds: kwds['type']='slice'
196         RegRecord.__init__(self, **kwds)
197
198     def __repr__ (self):
199         return RegRecord.__repr__(self).replace("Record","Slice")
200
201 ####################
202 class RegNode (RegRecord):
203     __tablename__       = 'nodes'
204     __mapper_args__     = { 'polymorphic_identity' : 'node' }
205     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
206     
207     def __init__ (self, **kwds):
208         if 'type' not in kwds: kwds['type']='node'
209         RegRecord.__init__(self, **kwds)
210
211     def __repr__ (self):
212         return RegRecord.__repr__(self).replace("Record","Node")
213
214 ####################
215 class RegUser (RegRecord):
216     __tablename__       = 'users'
217     # these objects will have type='user' in the records table
218     __mapper_args__     = { 'polymorphic_identity' : 'user' }
219     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
220     email               = Column ('email', String)
221     # can't use name 'keys' here because when loading from xml we're getting
222     # a 'keys' tag, and assigning a list of strings in a reference column like this crashes
223     reg_keys            = relationship ('RegKey', backref='reg_user',
224                                         cascade="all, delete, delete-orphan")
225     
226     # so we can use RegUser (email=.., hrn=..) and the like
227     def __init__ (self, **kwds):
228         # handle local settings
229         if 'email' in kwds: self.email=kwds.pop('email')
230         if 'type' not in kwds: kwds['type']='user'
231         RegRecord.__init__(self, **kwds)
232
233     # append stuff at the end of the record __repr__
234     def __repr__ (self): 
235         result = RegRecord.__repr__(self).replace("Record","User")
236         result.replace (">"," email=%s"%self.email)
237         result += ">"
238         return result
239
240     @validates('email') 
241     def validate_email(self, key, address):
242         assert '@' in address
243         return address
244
245     # xxx this might be temporary
246     def normalize_xml (self):
247         if hasattr(self,'keys'): self.reg_keys = [ RegKey (key) for key in self.keys ]
248
249 ####################
250 # xxx tocheck : not sure about eager loading of this one
251 # meaning, when querying the whole records, we expect there should
252 # be a single query to fetch all the keys 
253 # or, is it enough that we issue a single query to retrieve all the keys 
254 class RegKey (Base):
255     __tablename__       = 'keys'
256     key_id              = Column (Integer, primary_key=True)
257     record_id             = Column (Integer, ForeignKey ("records.record_id"))
258     key                 = Column (String)
259     pointer             = Column (Integer, default = -1)
260     
261     def __init__ (self, key, pointer=None):
262         self.key=key
263         if pointer: self.pointer=pointer
264
265     def __repr__ (self):
266         result="<key id=%s key=%s..."%(self.key_id,self.key[8:16],)
267         try:    result += " user=%s"%self.reg_user.record_id
268         except: result += " no-user"
269         result += ">"
270         return result
271
272 ##############################
273 # although the db needs of course to be reachable for the following functions
274 # the schema management functions are here and not in alchemy
275 # because the actual details of the classes need to be known
276 # migrations: this code has no notion of the previous versions
277 # of the data model nor of migrations
278 # sfa.storage.migrations.db_init uses this when starting from
279 # a fresh db only
280 def init_tables(engine):
281     logger.info("Initializing db schema from current/latest model")
282     Base.metadata.create_all(engine)
283
284 def drop_tables(engine):
285     logger.info("Dropping tables from current/latest model")
286     Base.metadata.drop_all(engine)
287
288 ##############################
289 # create a record of the right type from either a dict or an xml string
290 def make_record (dict={}, xml=""):
291     if dict:    return make_record_dict (dict)
292     elif xml:   return make_record_xml (xml)
293     else:       raise Exception("make_record has no input")
294
295 # convert an incoming record - typically from xmlrpc - into an object
296 def make_record_dict (record_dict):
297     assert ('type' in record_dict)
298     type=record_dict['type'].split('+')[0]
299     if type=='authority':
300         result=RegAuthority (dict=record_dict)
301     elif type=='user':
302         result=RegUser (dict=record_dict)
303     elif type=='slice':
304         result=RegSlice (dict=record_dict)
305     elif type=='node':
306         result=RegNode (dict=record_dict)
307     else:
308         logger.debug("Untyped RegRecord instance")
309         result=RegRecord (dict=record_dict)
310     logger.info ("converting dict into Reg* with type=%s"%type)
311     logger.info ("returning=%s"%result)
312     # xxx todo
313     # register non-db attributes in an extensions field
314     return result
315         
316 def make_record_xml (xml):
317     xml_record = XML(xml)
318     xml_dict = xml_record.todict()
319     logger.info("load from xml, keys=%s"%xml_dict.keys())
320     return make_record_dict (xml_dict)
321