1 from types import StringTypes
2 from datetime import datetime
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
12 from sfa.util.sfalogging import logger
13 from sfa.util.xml import XML
15 from sfa.trust.gid import GID
17 ##############################
18 Base=declarative_base()
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
28 # here are a few utilities for this
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
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:
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
45 # (*) finally for converting a dictionary into an sqlalchemy object, we provide
46 # obj.load_from_dict(dict)
50 self._i = iter(object_mapper(self).columns)
53 n = self._i.next().name
54 return n, getattr(self, n)
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():
62 if isinstance(v, StringTypes) and v.lower() in ['true']: v=True
63 if isinstance(v, StringTypes) and v.lower() in ['false']: v=False
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):
71 if isinstance(fields,dict): fields=fields.keys()
73 def load_from_xml (self, 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():
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()
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)
92 gid.dump(8, dump_parents)
93 elif getattr(self,key,None):
94 print " %s: %s" % (key, getattr(self,key))
96 # # only intended for debugging
97 # def inspect (self, logger, message=""):
98 # logger.info("%s -- Inspecting AlchemyObj -- attrs"%message)
100 # if not k.startswith('_'):
101 # logger.info (" %s: %s"%(k,getattr(self,k)))
102 # logger.info("%s -- Inspecting AlchemyObj -- __dict__"%message)
104 # for (k,v) in d.iteritems():
105 # logger.info("[%s]=%s"%(k,v))
108 ##############################
109 # various kinds of records are implemented as an inheritance hierarchy
110 # RegRecord is the base class for all actual variants
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 }
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
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)
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"
151 def validate_gid (self, key, gid):
152 if isinstance(gid, StringTypes): return gid
153 else: return gid.save_to_string(save_parents=True)
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)
160 def just_created (self):
162 self.date_created=now
163 self.last_updated=now
165 def just_updated (self):
167 self.last_updated=now
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)
177 # append stuff at the end of the record __repr__
179 result = RegRecord.__repr__(self).replace("Record","User")
180 result.replace ("]"," email=%s"%self.email)
184 def validate_email(self, key, address):
185 assert '@' in address
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)
193 # no proper data yet, just hack the typename
195 return RegRecord.__repr__(self).replace("Record","Authority")
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)
203 return RegRecord.__repr__(self).replace("Record","Slice")
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)
211 return RegRecord.__repr__(self).replace("Record","Node")
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)
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)
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)
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)
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)
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)
256 result=RegUser (dict=record_dict)
258 result=RegSlice (dict=record_dict)
260 result=RegNode (dict=record_dict)
262 result=RegRecord (dict=record_dict)
263 logger.info ("converting dict into Reg* with type=%s"%type)
264 logger.info ("returning=%s"%result)
266 # register non-db attributes in an extensions field