cosmetic
[sfa.git] / sfa / storage / persistentobjs.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     # xxx tmp would be 'records'
111     __tablename__       = 'records'
112     record_id           = Column (Integer, primary_key=True)
113     # this is the discriminator that tells which class to use
114     classtype           = Column (String)
115     type                = Column (String)
116     hrn                 = Column (String)
117     gid                 = Column (String)
118     authority           = Column (String)
119     peer_authority      = Column (String)
120     pointer             = Column (Integer, default=-1)
121     date_created        = Column (DateTime)
122     last_updated        = Column (DateTime)
123     # use the 'type' column to decide which subclass the object is of
124     __mapper_args__     = { 'polymorphic_on' : classtype }
125
126     fields = [ 'type', 'hrn', 'gid', 'authority', 'peer_authority' ]
127     def __init__ (self, type=None, hrn=None, gid=None, authority=None, peer_authority=None, 
128                   pointer=None, dict=None):
129         if type:                                self.type=type
130         if hrn:                                 self.hrn=hrn
131         if gid: 
132             if isinstance(gid, StringTypes):    self.gid=gid
133             else:                               self.gid=gid.save_to_string(save_parents=True)
134         if authority:                           self.authority=authority
135         if peer_authority:                      self.peer_authority=peer_authority
136         if pointer:                             self.pointer=pointer
137         if dict:                                self.load_from_dict (dict)
138
139     def __repr__(self):
140         result="[Record id=%s, type=%s, hrn=%s, authority=%s, pointer=%s" % \
141                 (self.record_id, self.type, self.hrn, self.authority, self.pointer)
142         # skip the uniform '--- BEGIN CERTIFICATE --' stuff
143         if self.gid: result+=" gid=%s..."%self.gid[28:36]
144         else: result+=" nogid"
145         result += "]"
146         return result
147
148     @validates ('gid')
149     def validate_gid (self, key, gid):
150         if gid is None:                     return
151         elif isinstance(gid, StringTypes):  return gid
152         else:                               return gid.save_to_string(save_parents=True)
153
154     # xxx - there might be smarter ways to handle get/set'ing gid using validation hooks 
155     def get_gid_object (self):
156         if not self.gid: return None
157         else: return GID(string=self.gid)
158
159     def just_created (self):
160         now=datetime.now()
161         self.date_created=now
162         self.last_updated=now
163
164     def just_updated (self):
165         now=datetime.now()
166         self.last_updated=now
167
168 ##############################
169 class RegUser (RegRecord):
170     __tablename__       = 'users'
171     # these objects will have type='user' in the records table
172     __mapper_args__     = { 'polymorphic_identity' : 'user' }
173     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
174     email               = Column ('email', String)
175     
176     # append stuff at the end of the record __repr__
177     def __repr__ (self): 
178         result = RegRecord.__repr__(self).replace("Record","User")
179         result.replace ("]"," email=%s"%self.email)
180         return result
181     
182     @validates('email') 
183     def validate_email(self, key, address):
184         assert '@' in address
185         return address
186
187 class RegAuthority (RegRecord):
188     __tablename__       = 'authorities'
189     __mapper_args__     = { 'polymorphic_identity' : 'authority' }
190     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
191     
192     # no proper data yet, just hack the typename
193     def __repr__ (self):
194         return RegRecord.__repr__(self).replace("Record","Authority")
195
196 class RegSlice (RegRecord):
197     __tablename__       = 'slices'
198     __mapper_args__     = { 'polymorphic_identity' : 'slice' }
199     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
200     
201     def __repr__ (self):
202         return RegRecord.__repr__(self).replace("Record","Slice")
203
204 class RegNode (RegRecord):
205     __tablename__       = 'nodes'
206     __mapper_args__     = { 'polymorphic_identity' : 'node' }
207     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
208     
209     def __repr__ (self):
210         return RegRecord.__repr__(self).replace("Record","Node")
211
212 ##############################
213 # although the db needs of course to be reachable,
214 # the schema management functions are here and not in alchemy
215 # because the actual details of the classes need to be known
216 def init_tables(dbsession):
217     logger.info("Initializing db schema and builtin types")
218     # the doc states we could retrieve the engine this way
219     # engine=dbsession.get_bind()
220     # however I'm getting this
221     # TypeError: get_bind() takes at least 2 arguments (1 given)
222     # so let's import alchemy - but not from toplevel 
223     from sfa.storage.alchemy import engine
224     Base.metadata.create_all(engine)
225
226 def drop_tables(dbsession):
227     logger.info("Dropping tables")
228     # same as for init_tables
229     from sfa.storage.alchemy import engine
230     Base.metadata.drop_all(engine)
231
232 ##############################
233 # create a record of the right type from either a dict or an xml string
234 def make_record (dict={}, xml=""):
235     if dict:    return make_record_dict (dict)
236     elif xml:   return make_record_xml (xml)
237     else:       raise Exception("make_record has no input")
238
239 # convert an incoming record - typically from xmlrpc - into an object
240 def make_record_dict (record_dict):
241     assert ('type' in record_dict)
242     type=record_dict['type'].split('+')[0]
243     if type=='authority':
244         result=RegAuthority (dict=record_dict)
245     elif type=='user':
246         result=RegUser (dict=record_dict)
247     elif type=='slice':
248         result=RegSlice (dict=record_dict)
249     elif type=='node':
250         result=RegNode (dict=record_dict)
251     else:
252         result=RegRecord (dict=record_dict)
253     logger.info ("converting dict into Reg* with type=%s"%type)
254     logger.info ("returning=%s"%result)
255     # xxx todo
256     # register non-db attributes in an extensions field
257     return result
258         
259 def make_record_xml (xml):
260     xml_record = XML(xml)
261     xml_dict = xml_record.todict()
262     logger.info("load from xml, keys=%s"%xml_dict.keys())
263     return make_record_dict (xml_dict)