authorities can also have a 'name' for standalone deployments
[sfa.git] / sfa / storage / model.py
1 from types import StringTypes
2 from datetime import datetime
3
4 from sqlalchemy import or_, and_ 
5 from sqlalchemy import Column, Integer, String, DateTime
6 from sqlalchemy import Table, Column, MetaData, join, ForeignKey
7 from sqlalchemy.orm import relationship, backref
8 from sqlalchemy.orm import column_property
9 from sqlalchemy.orm import object_mapper
10 from sqlalchemy.orm import validates
11 from sqlalchemy.ext.declarative import declarative_base
12
13 from sfa.storage.record import Record
14 from sfa.util.sfalogging import logger
15 from sfa.util.sfatime import utcparse, datetime_to_string
16 from sfa.util.xml import XML 
17
18 from sfa.trust.gid import GID
19
20 ##############################
21 Base=declarative_base()
22
23 ####################
24 # dicts vs objects
25 ####################
26 # historically the front end to the db dealt with dicts, so the code was only dealing with dicts
27 # sqlalchemy however offers an object interface, meaning that you write obj.id instead of obj['id']
28 # which is admittedly much nicer
29 # however we still need to deal with dictionaries if only for the xmlrpc layer
30
31 # here are a few utilities for this 
32
33 # (*) first off, when an old pieve of code needs to be used as-is, if only temporarily, the simplest trick
34 # is to use obj.__dict__
35 # this behaves exactly like required, i.e. obj.__dict__['field']='new value' does change obj.field
36 # however this depends on sqlalchemy's implementation so it should be avoided 
37 #
38 # (*) second, when an object needs to be exposed to the xmlrpc layer, we need to convert it into a dict
39 # remember though that writing the resulting dictionary won't change the object
40 # essentially obj.__dict__ would be fine too, except that we want to discard alchemy private keys starting with '_'
41 # 2 ways are provided for that:
42 # . dict(obj)
43 # . obj.todict()
44 # the former dict(obj) relies on __iter__() and next() below, and does not rely on the fields names
45 # although it seems to work fine, I've found cases where it issues a weird python error that I could not get right
46 # 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
47 #
48 # (*) finally for converting a dictionary into an sqlalchemy object, we provide
49 # obj.load_from_dict(dict)
50
51 class AlchemyObj(Record):
52     def __iter__(self): 
53         self._i = iter(object_mapper(self).columns)
54         return self 
55     def next(self): 
56         n = self._i.next().name
57         return n, getattr(self, n)
58
59 #    # only intended for debugging 
60 #    def inspect (self, logger, message=""):
61 #        logger.info("%s -- Inspecting AlchemyObj -- attrs"%message)
62 #        for k in dir(self):
63 #            if not k.startswith('_'):
64 #                logger.info ("  %s: %s"%(k,getattr(self,k)))
65 #        logger.info("%s -- Inspecting AlchemyObj -- __dict__"%message)
66 #        d=self.__dict__
67 #        for (k,v) in d.iteritems():
68 #            logger.info("[%s]=%s"%(k,v))
69
70
71 ##############################
72 # various kinds of records are implemented as an inheritance hierarchy
73 # RegRecord is the base class for all actual variants
74 # a first draft was using 'type' as the discriminator for the inheritance
75 # but we had to define another more internal column (classtype) so we 
76 # accomodate variants in types like authority+am and the like
77
78 class RegRecord (Base,AlchemyObj):
79     __tablename__       = 'records'
80     record_id           = Column (Integer, primary_key=True)
81     # this is the discriminator that tells which class to use
82     classtype           = Column (String)
83     # in a first version type was the discriminator
84     # but that could not accomodate for 'authority+sa' and the like
85     type                = Column (String)
86     hrn                 = Column (String)
87     gid                 = Column (String)
88     authority           = Column (String)
89     peer_authority      = Column (String)
90     pointer             = Column (Integer, default=-1)
91     date_created        = Column (DateTime)
92     last_updated        = Column (DateTime)
93     # use the 'type' column to decide which subclass the object is of
94     __mapper_args__     = { 'polymorphic_on' : classtype }
95
96     fields = [ 'type', 'hrn', 'gid', 'authority', 'peer_authority' ]
97     def __init__ (self, type=None, hrn=None, gid=None, authority=None, peer_authority=None, 
98                   pointer=None, dict=None):
99         if type:                                self.type=type
100         if hrn:                                 self.hrn=hrn
101         if gid: 
102             if isinstance(gid, StringTypes):    self.gid=gid
103             else:                               self.gid=gid.save_to_string(save_parents=True)
104         if authority:                           self.authority=authority
105         if peer_authority:                      self.peer_authority=peer_authority
106         if pointer:                             self.pointer=pointer
107         if dict:                                self.load_from_dict (dict)
108
109     def __repr__(self):
110         result="<Record id=%s, type=%s, hrn=%s, authority=%s, pointer=%s" % \
111                 (self.record_id, self.type, self.hrn, self.authority, self.pointer)
112         # skip the uniform '--- BEGIN CERTIFICATE --' stuff
113         if self.gid: result+=" gid=%s..."%self.gid[28:36]
114         else: result+=" nogid"
115         result += ">"
116         return result
117
118     # shortcut - former implem. was record-based
119     def get (self, field, default):
120         return getattr(self,field,default)
121
122     @validates ('gid')
123     def validate_gid (self, key, gid):
124         if gid is None:                     return
125         elif isinstance(gid, StringTypes):  return gid
126         else:                               return gid.save_to_string(save_parents=True)
127
128     def validate_datetime (self, key, incoming):
129         if isinstance (incoming, datetime):     return incoming
130         elif isinstance (incoming, (int,float)):return datetime.fromtimestamp (incoming)
131         else: logger.info("Cannot validate datetime for key %s with input %s"%\
132                               (key,incoming))
133
134     @validates ('date_created')
135     def validate_date_created (self, key, incoming): return self.validate_datetime (key, incoming)
136
137     @validates ('last_updated')
138     def validate_last_updated (self, key, incoming): return self.validate_datetime (key, incoming)
139
140     # xxx - there might be smarter ways to handle get/set'ing gid using validation hooks 
141     def get_gid_object (self):
142         if not self.gid: return None
143         else: return GID(string=self.gid)
144
145     def just_created (self):
146         now=datetime.utcnow()
147         self.date_created=now
148         self.last_updated=now
149
150     def just_updated (self):
151         now=datetime.utcnow()
152         self.last_updated=now
153
154 #################### cross-relations tables
155 # authority x user (pis) association
156 authority_pi_table = \
157     Table ( 'authority_pi', Base.metadata,
158             Column ('authority_id', Integer, ForeignKey ('records.record_id'), primary_key=True),
159             Column ('pi_id', Integer, ForeignKey ('records.record_id'), primary_key=True),
160             )
161 # slice x user (researchers) association
162 slice_researcher_table = \
163     Table ( 'slice_researcher', Base.metadata,
164             Column ('slice_id', Integer, ForeignKey ('records.record_id'), primary_key=True),
165             Column ('researcher_id', Integer, ForeignKey ('records.record_id'), primary_key=True),
166             )
167
168 ##############################
169 # all subclasses define a convenience constructor with a default value for type, 
170 # and when applicable a way to define local fields in a kwd=value argument
171 ####################
172 class RegAuthority (RegRecord):
173     __tablename__       = 'authorities'
174     __mapper_args__     = { 'polymorphic_identity' : 'authority' }
175     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
176     #### extensions come here
177     name                = Column ('name', String)
178     #### extensions come here
179     reg_pis             = relationship \
180         ('RegUser',
181          secondary=authority_pi_table,
182          primaryjoin=RegRecord.record_id==authority_pi_table.c.authority_id,
183          secondaryjoin=RegRecord.record_id==authority_pi_table.c.pi_id,
184          backref='reg_authorities_as_pi')
185     
186     def __init__ (self, **kwds):
187         # handle local settings
188         if 'name' in kwds:
189             self.name = kwds.pop('name')
190         # fill in type if not previously set
191         if 'type' not in kwds: kwds['type']='authority'
192         # base class constructor
193         RegRecord.__init__(self, **kwds)
194
195     # no proper data yet, just hack the typename
196     def __repr__ (self):
197         result = RegRecord.__repr__(self).replace("Record", "Authority")
198         result.replace(">", " name={}>".format(self.name))
199         return result
200
201     def update_pis (self, pi_hrns, dbsession):
202         # strip that in case we have <researcher> words </researcher>
203         pi_hrns = [ x.strip() for x in pi_hrns ]
204         request = dbsession.query (RegUser).filter(RegUser.hrn.in_(pi_hrns))
205         logger.info ("RegAuthority.update_pis: %d incoming pis, %d matches found"%(len(pi_hrns),request.count()))
206         pis = dbsession.query (RegUser).filter(RegUser.hrn.in_(pi_hrns)).all()
207         self.reg_pis = pis
208
209 ####################
210 class RegSlice (RegRecord):
211     __tablename__       = 'slices'
212     __mapper_args__     = { 'polymorphic_identity' : 'slice' }
213     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
214     #### extensions come here
215     reg_researchers     = relationship \
216         ('RegUser', 
217          secondary=slice_researcher_table,
218          primaryjoin=RegRecord.record_id==slice_researcher_table.c.slice_id,
219          secondaryjoin=RegRecord.record_id==slice_researcher_table.c.researcher_id,
220          backref='reg_slices_as_researcher')
221
222     def __init__ (self, **kwds):
223         if 'type' not in kwds: kwds['type']='slice'
224         RegRecord.__init__(self, **kwds)
225
226     def __repr__ (self):
227         return RegRecord.__repr__(self).replace("Record","Slice")
228
229     def update_researchers (self, researcher_hrns, dbsession):
230         # strip that in case we have <researcher> words </researcher>
231         researcher_hrns = [ x.strip() for x in researcher_hrns ]
232         request = dbsession.query (RegUser).filter(RegUser.hrn.in_(researcher_hrns))
233         logger.info ("RegSlice.update_researchers: %d incoming researchers, %d matches found"%(len(researcher_hrns),request.count()))
234         researchers = dbsession.query (RegUser).filter(RegUser.hrn.in_(researcher_hrns)).all()
235         self.reg_researchers = researchers
236
237     # when dealing with credentials, we need to retrieve the PIs attached to a slice
238     # WARNING: with the move to passing dbsessions around, we face a glitch here because this
239     # helper function is called from the trust/ area that
240     def get_pis (self):
241         from sqlalchemy.orm import sessionmaker
242         Session=sessionmaker()
243         dbsession=Session.object_session(self)
244         from sfa.util.xrn import get_authority
245         authority_hrn = get_authority(self.hrn)
246         auth_record = dbsession.query(RegAuthority).filter_by(hrn=authority_hrn).first()
247         return auth_record.reg_pis
248         
249     @validates ('expires')
250     def validate_expires (self, key, incoming): return self.validate_datetime (key, incoming)
251
252 ####################
253 class RegNode (RegRecord):
254     __tablename__       = 'nodes'
255     __mapper_args__     = { 'polymorphic_identity' : 'node' }
256     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
257     
258     def __init__ (self, **kwds):
259         if 'type' not in kwds: kwds['type']='node'
260         RegRecord.__init__(self, **kwds)
261
262     def __repr__ (self):
263         return RegRecord.__repr__(self).replace("Record","Node")
264
265 ####################
266 class RegUser (RegRecord):
267     __tablename__       = 'users'
268     # these objects will have type='user' in the records table
269     __mapper_args__     = { 'polymorphic_identity' : 'user' }
270     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
271     #### extensions come here
272     email               = Column ('email', String)
273     # can't use name 'keys' here because when loading from xml we're getting
274     # a 'keys' tag, and assigning a list of strings in a reference column like this crashes
275     reg_keys            = relationship \
276         ('RegKey', backref='reg_user',
277          cascade="all, delete, delete-orphan")
278     
279     # so we can use RegUser (email=.., hrn=..) and the like
280     def __init__ (self, **kwds):
281         # handle local settings
282         if 'email' in kwds: self.email=kwds.pop('email')
283         if 'type' not in kwds: kwds['type']='user'
284         RegRecord.__init__(self, **kwds)
285
286     # append stuff at the end of the record __repr__
287     def __repr__ (self): 
288         result = RegRecord.__repr__(self).replace("Record","User")
289         result.replace (">"," email=%s"%self.email)
290         result += ">"
291         return result
292
293     @validates('email') 
294     def validate_email(self, key, address):
295         assert '@' in address
296         return address
297
298 ####################
299 # xxx tocheck : not sure about eager loading of this one
300 # meaning, when querying the whole records, we expect there should
301 # be a single query to fetch all the keys 
302 # or, is it enough that we issue a single query to retrieve all the keys 
303 class RegKey (Base):
304     __tablename__       = 'keys'
305     key_id              = Column (Integer, primary_key=True)
306     record_id             = Column (Integer, ForeignKey ("records.record_id"))
307     key                 = Column (String)
308     pointer             = Column (Integer, default = -1)
309     
310     def __init__ (self, key, pointer=None):
311         self.key=key
312         if pointer: self.pointer=pointer
313
314     def __repr__ (self):
315         result="<key id=%s key=%s..."%(self.key_id,self.key[8:16],)
316         try:    result += " user=%s"%self.reg_user.record_id
317         except: result += " no-user"
318         result += ">"
319         return result
320
321 class SliverAllocation(Base,AlchemyObj):
322     __tablename__       = 'sliver_allocation'
323     sliver_id           = Column(String, primary_key=True)
324     client_id           = Column(String)
325     component_id        = Column(String)
326     slice_urn           = Column(String)
327     allocation_state    = Column(String)
328
329     def __init__(self, **kwds):
330         if 'sliver_id' in kwds:
331             self.sliver_id = kwds['sliver_id']
332         if 'client_id' in kwds:
333             self.client_id = kwds['client_id']
334         if 'component_id' in kwds:
335             self.component_id = kwds['component_id']
336         if 'slice_urn' in kwds:
337             self.slice_urn = kwds['slice_urn']
338         if 'allocation_state' in kwds:
339             self.allocation_state = kwds['allocation_state']
340
341     def __repr__(self):
342         result = "<sliver_allocation sliver_id=%s allocation_state=%s" % \
343                   (self.sliver_id, self.allocation_state)
344         return result
345
346     @validates('allocation_state')
347     def validate_allocation_state(self, key, state):
348         allocation_states = ['geni_unallocated', 'geni_allocated', 'geni_provisioned']
349         assert state in allocation_states
350         return state
351
352     @staticmethod    
353     def set_allocations(sliver_ids, state, dbsession):
354         if not isinstance(sliver_ids, list):
355             sliver_ids = [sliver_ids]
356         sliver_state_updated = {}
357         constraint = SliverAllocation.sliver_id.in_(sliver_ids)
358         sliver_allocations = dbsession.query (SliverAllocation).filter(constraint)
359         sliver_ids_found = []
360         for sliver_allocation in sliver_allocations:
361             sliver_allocation.allocation_state = state
362             sliver_ids_found.append(sliver_allocation.sliver_id)
363
364         # Some states may not have been updated becuase no sliver allocation state record
365         # exists for the sliver. Insert new allocation records for these slivers and set
366         # it to geni_allocated.
367         sliver_ids_not_found = set(sliver_ids).difference(sliver_ids_found)
368         for sliver_id in sliver_ids_not_found:
369             record = SliverAllocation(sliver_id=sliver_id, allocation_state=state)
370             dbsession.add(record)
371         dbsession.commit()
372
373     @staticmethod
374     def delete_allocations(sliver_ids, dbsession):
375         if not isinstance(sliver_ids, list):
376             sliver_ids = [sliver_ids]
377         constraint = SliverAllocation.sliver_id.in_(sliver_ids)
378         sliver_allocations = dbsession.query(SliverAllocation).filter(constraint)
379         for sliver_allocation in sliver_allocations:
380             dbsession.delete(sliver_allocation)
381         dbsession.commit()
382     
383     def sync(self, dbsession):
384         constraints = [SliverAllocation.sliver_id==self.sliver_id]
385         results = dbsession.query(SliverAllocation).filter(and_(*constraints))
386         records = []
387         for result in results:
388             records.append(result) 
389         
390         if not records:
391             dbsession.add(self)
392         else:
393             record = records[0]
394             record.sliver_id = self.sliver_id
395             record.client_id  = self.client_id
396             record.component_id  = self.component_id
397             record.slice_urn  = self.slice_urn
398             record.allocation_state = self.allocation_state
399         dbsession.commit()    
400         
401
402 ##############################
403 # although the db needs of course to be reachable for the following functions
404 # the schema management functions are here and not in alchemy
405 # because the actual details of the classes need to be known
406 # migrations: this code has no notion of the previous versions
407 # of the data model nor of migrations
408 # sfa.storage.migrations.db_init uses this when starting from
409 # a fresh db only
410 def init_tables(engine):
411     logger.info("Initializing db schema from current/latest model")
412     Base.metadata.create_all(engine)
413
414 def drop_tables(engine):
415     logger.info("Dropping tables from current/latest model")
416     Base.metadata.drop_all(engine)
417
418 ##############################
419 # create a record of the right type from either a dict or an xml string
420 def make_record (dict=None, xml=""):
421     if dict is None: dict={}
422     if dict:    return make_record_dict (dict)
423     elif xml:   return make_record_xml (xml)
424     else:       raise Exception("make_record has no input")
425
426 # convert an incoming record - typically from xmlrpc - into an object
427 def make_record_dict (record_dict):
428     assert ('type' in record_dict)
429     type=record_dict['type'].split('+')[0]
430     if type=='authority':
431         result=RegAuthority (dict=record_dict)
432     elif type=='user':
433         result=RegUser (dict=record_dict)
434     elif type=='slice':
435         result=RegSlice (dict=record_dict)
436     elif type=='node':
437         result=RegNode (dict=record_dict)
438     else:
439         logger.debug("Untyped RegRecord instance")
440         result=RegRecord (dict=record_dict)
441     logger.info ("converting dict into Reg* with type=%s"%type)
442     logger.info ("returning=%s"%result)
443     # xxx todo
444     # register non-db attributes in an extensions field
445     return result
446         
447 def make_record_xml (xml):
448     xml_record = XML(xml)
449     xml_dict = xml_record.todict()
450     logger.info("load from xml, keys=%s"%xml_dict.keys())
451     return make_record_dict (xml_dict)
452
453 ####################
454 # augment local records with data from builtin relationships
455 # expose related objects as a list of hrns
456 # we pick names that clearly won't conflict with the ones used in the old approach,
457 # were the relationships data came from the testbed side
458 # for each type, a dict of the form {<field-name-exposed-in-record>:<alchemy_accessor_name>}
459 # so after that, an 'authority' record will e.g. have a 'reg-pis' field with the hrns of its pi-users
460 augment_map={'authority': {'reg-pis':'reg_pis',},
461              'slice': {'reg-researchers':'reg_researchers',},
462              'user': {'reg-pi-authorities':'reg_authorities_as_pi',
463                       'reg-slices':'reg_slices_as_researcher',},
464              }
465
466 def augment_with_sfa_builtins (local_record):
467     # don't ruin the import of that file in a client world
468     from sfa.util.xrn import Xrn
469     # add a 'urn' field
470     setattr(local_record,'reg-urn',Xrn(xrn=local_record.hrn,type=local_record.type).urn)
471     # users have keys and this is needed to synthesize 'users' sent over to CreateSliver
472     if local_record.type=='user':
473         user_keys = [ key.key for key in local_record.reg_keys ]
474         setattr(local_record, 'reg-keys', user_keys)
475     # search in map according to record type
476     type_map=augment_map.get(local_record.type,{})
477     # use type-dep. map to do the job
478     for (field_name,attribute) in type_map.items():
479         # get related objects
480         related_records = getattr(local_record,attribute,[])
481         hrns = [ r.hrn for r in related_records ]
482         setattr (local_record, field_name, hrns)
483     
484