rename the authority+* types as non temporary
[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     def load_from_xml (self, xml):
74         xml_record = XML(xml)
75         xml_dict = xml_record.todict()
76         logger.info("load from xml, keys=%s"%xml_dict.keys())
77         for (k,v) in xml_dict.iteritems():
78             setattr(self,k,v)
79
80     def save_as_xml (self):
81         # xxx not sure about the scope here
82         input_dict = dict( [ (key, getattr(self.key), ) for key in self.xml_fields() if getattr(self,key,None) ] )
83         xml_record=XML("<record />")
84         xml_record.parse_dict (input_dict)
85         return xml_record.toxml()
86
87     def dump(self, dump_parents=False):
88         for key in self.fields:
89             if key == 'gid' and self.gid:
90                 gid = GID(string=self.gid)
91                 print "    %s:" % key
92                 gid.dump(8, dump_parents)
93             elif getattr(self,key,None):    
94                 print "    %s: %s" % (key, getattr(self,key))
95     
96 #    # only intended for debugging 
97 #    def inspect (self, logger, message=""):
98 #        logger.info("%s -- Inspecting AlchemyObj -- attrs"%message)
99 #        for k in dir(self):
100 #            if not k.startswith('_'):
101 #                logger.info ("  %s: %s"%(k,getattr(self,k)))
102 #        logger.info("%s -- Inspecting AlchemyObj -- __dict__"%message)
103 #        d=self.__dict__
104 #        for (k,v) in d.iteritems():
105 #            logger.info("[%s]=%s"%(k,v))
106
107
108 ##############################
109 # various kinds of records are implemented as an inheritance hierarchy
110 # RegRecord is the base class for all actual variants
111
112 class RegRecord (Base,AlchemyObj):
113     # xxx tmp would be 'records'
114     __tablename__       = 'records'
115     record_id           = Column (Integer, primary_key=True)
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' : type }
126
127     fields = [ 'type', 'hrn', 'gid', 'authority', 'peer_authority' ]
128     def __init__ (self, type='unknown', hrn=None, gid=None, authority=None, peer_authority=None, 
129                   pointer=None, dict=None):
130 # managed by alchemy's polymorphic stuff
131 #        self.type=type
132         if hrn:                                 self.hrn=hrn
133         if gid: 
134             if isinstance(gid, StringTypes):    self.gid=gid
135             else:                               self.gid=gid.save_to_string(save_parents=True)
136         if authority:                           self.authority=authority
137         if peer_authority:                      self.peer_authority=peer_authority
138         if pointer:                             self.pointer=pointer
139         if dict:                                self.load_from_dict (dict)
140
141     def __repr__(self):
142         result="[Record id=%s, type=%s, hrn=%s, authority=%s, pointer=%s" % \
143                 (self.record_id, self.type, self.hrn, self.authority, self.pointer)
144         # skip the uniform '--- BEGIN CERTIFICATE --' stuff
145         if self.gid: result+=" gid=%s..."%self.gid[28:36]
146         else: result+=" nogid"
147         result += "]"
148         return result
149
150     @validates ('gid')
151     def validate_gid (self, key, gid):
152         if 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 class RegUser (RegRecord):
171     __tablename__       = 'users'
172     # these objects will have type='user' in the records table
173     __mapper_args__     = { 'polymorphic_identity' : 'user' }
174     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
175     email               = Column ('email', String)
176     
177     # append stuff at the end of the record __repr__
178     def __repr__ (self): 
179         result = RegRecord.__repr__(self).replace("Record","User")
180         result.replace ("]"," email=%s"%self.email)
181         return result
182     
183     @validates('email') 
184     def validate_email(self, key, address):
185         assert '@' in address
186         return address
187
188 class RegAuthority (RegRecord):
189     __tablename__       = 'authorities'
190     __mapper_args__     = { 'polymorphic_identity' : 'authority' }
191     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
192     
193     # no proper data yet, just hack the typename
194     def __repr__ (self):
195         return RegRecord.__repr__(self).replace("Record","Authority")
196
197 class RegSlice (RegRecord):
198     __tablename__       = 'slices'
199     __mapper_args__     = { 'polymorphic_identity' : 'slice' }
200     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
201     
202     def __repr__ (self):
203         return RegRecord.__repr__(self).replace("Record","Slice")
204
205 class RegNode (RegRecord):
206     __tablename__       = 'nodes'
207     __mapper_args__     = { 'polymorphic_identity' : 'node' }
208     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
209     
210     def __repr__ (self):
211         return RegRecord.__repr__(self).replace("Record","Node")
212
213 # because we use 'type' as the discriminator here, the only way to have type set to
214 # e.g. authority+sa is to define a separate class
215 # this currently is not used at all though, just to check if all this stuff really is useful
216 # if so it would make more sense to store that in the authorities table instead
217 class RegAuthoritySa (RegRecord):
218     __tablename__       = 'authorities_sa'
219     __mapper_args__     = { 'polymorphic_identity' : 'authority+sa' }
220     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
221
222 class RegAuthorityAm (RegRecord):
223     __tablename__       = 'authorities_am'
224     __mapper_args__     = { 'polymorphic_identity' : 'authority+am' }
225     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
226
227 class RegAuthoritySm (RegRecord):
228     __tablename__       = 'authorities_sm'
229     __mapper_args__     = { 'polymorphic_identity' : 'authority+sm' }
230     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
231
232 ##############################
233 def init_tables(dbsession):
234     logger.info("Initializing db schema and builtin types")
235     # the doc states we could retrieve the engine this way
236     # engine=dbsession.get_bind()
237     # however I'm getting this
238     # TypeError: get_bind() takes at least 2 arguments (1 given)
239     # so let's import alchemy - but not from toplevel 
240     from sfa.storage.alchemy import engine
241     Base.metadata.create_all(engine)
242
243 def drop_tables(dbsession):
244     logger.info("Dropping tables")
245     # same as for init_tables
246     from sfa.storage.alchemy import engine
247     Base.metadata.drop_all(engine)
248
249 # convert an incoming record - typically from xmlrpc - into an object
250 def make_record (record_dict):
251     assert ('type' in record_dict)
252     type=record_dict['type']
253     if type=='authority':
254         result=RegAuthority (dict=record_dict)
255     elif type=='user':
256         result=RegUser (dict=record_dict)
257     elif type=='slice':
258         result=RegSlice (dict=record_dict)
259     elif type=='node':
260         result=RegNode (dict=record_dict)
261     else:
262         result=RegRecord (dict=record_dict)
263     logger.info ("converting dict into Reg* with type=%s"%type)
264     logger.info ("returning=%s"%result)
265     # xxx todo
266     # register non-db attributes in an extensions field
267     return result
268         
269