no change = prettyfied wrt spaces, commas and the like
[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:
114             result+=" gid=%s..."%self.gid[28:36]
115         else:
116             result+=" nogid"
117         result += ">"
118         return result
119
120     # shortcut - former implem. was record-based
121     def get (self, field, default):
122         return getattr(self,field,default)
123
124     @validates ('gid')
125     def validate_gid (self, key, gid):
126         if gid is None:                     return
127         elif isinstance(gid, StringTypes):  return gid
128         else:                               return gid.save_to_string(save_parents=True)
129
130     def validate_datetime (self, key, incoming):
131         if isinstance (incoming, datetime):
132             return incoming
133         elif isinstance (incoming, (int, float)):
134             return datetime.fromtimestamp (incoming)
135         else:
136             logger.info("Cannot validate datetime for key %s with input %s"%\
137                         (key,incoming))
138
139     @validates ('date_created')
140     def validate_date_created (self, key, incoming):
141         return self.validate_datetime (key, incoming)
142
143     @validates ('last_updated')
144     def validate_last_updated (self, key, incoming):
145         return self.validate_datetime (key, incoming)
146
147     # xxx - there might be smarter ways to handle get/set'ing gid using validation hooks 
148     def get_gid_object (self):
149         if not self.gid:        return None
150         else:                   return GID(string=self.gid)
151
152     def just_created (self):
153         now = datetime.utcnow()
154         self.date_created = now
155         self.last_updated = now
156
157     def just_updated (self):
158         now = datetime.utcnow()
159         self.last_updated = now
160
161 #################### cross-relations tables
162 # authority x user (pis) association
163 authority_pi_table = \
164     Table ( 'authority_pi', Base.metadata,
165             Column ('authority_id', Integer, ForeignKey ('records.record_id'), primary_key=True),
166             Column ('pi_id', Integer, ForeignKey ('records.record_id'), primary_key=True),
167             )
168 # slice x user (researchers) association
169 slice_researcher_table = \
170     Table ( 'slice_researcher', Base.metadata,
171             Column ('slice_id', Integer, ForeignKey ('records.record_id'), primary_key=True),
172             Column ('researcher_id', Integer, ForeignKey ('records.record_id'), primary_key=True),
173             )
174
175 ##############################
176 # all subclasses define a convenience constructor with a default value for type, 
177 # and when applicable a way to define local fields in a kwd=value argument
178 ####################
179 class RegAuthority (RegRecord):
180     __tablename__       = 'authorities'
181     __mapper_args__     = { 'polymorphic_identity' : 'authority' }
182     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
183     #### extensions come here
184     name                = Column ('name', String)
185     #### extensions come here
186     reg_pis             = relationship \
187         ('RegUser',
188          secondary = authority_pi_table,
189          primaryjoin = RegRecord.record_id==authority_pi_table.c.authority_id,
190          secondaryjoin = RegRecord.record_id==authority_pi_table.c.pi_id,
191          backref = 'reg_authorities_as_pi',
192         )
193     
194     def __init__ (self, **kwds):
195         # handle local settings
196         if 'name' in kwds:
197             self.name = kwds.pop('name')
198         # fill in type if not previously set
199         if 'type' not in kwds:
200             kwds['type']='authority'
201         # base class constructor
202         RegRecord.__init__(self, **kwds)
203
204     # no proper data yet, just hack the typename
205     def __repr__ (self):
206         result = RegRecord.__repr__(self).replace("Record", "Authority")
207         result.replace(">", " name={}>".format(self.name))
208         return result
209
210     def update_pis (self, pi_hrns, dbsession):
211         # strip that in case we have <researcher> words </researcher>
212         pi_hrns = [ x.strip() for x in pi_hrns ]
213         request = dbsession.query (RegUser).filter(RegUser.hrn.in_(pi_hrns))
214         logger.info("RegAuthority.update_pis: %d incoming pis, %d matches found"\
215                     % (len(pi_hrns), request.count()))
216         pis = dbsession.query(RegUser).filter(RegUser.hrn.in_(pi_hrns)).all()
217         self.reg_pis = pis
218
219 ####################
220 class RegSlice (RegRecord):
221     __tablename__       = 'slices'
222     __mapper_args__     = { 'polymorphic_identity' : 'slice' }
223     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
224     #### extensions come here
225     reg_researchers     = relationship \
226         ('RegUser', 
227          secondary=slice_researcher_table,
228          primaryjoin=RegRecord.record_id==slice_researcher_table.c.slice_id,
229          secondaryjoin=RegRecord.record_id==slice_researcher_table.c.researcher_id,
230          backref='reg_slices_as_researcher',
231         )
232
233     def __init__ (self, **kwds):
234         if 'type' not in kwds:
235             kwds['type']='slice'
236         RegRecord.__init__(self, **kwds)
237
238     def __repr__ (self):
239         return RegRecord.__repr__(self).replace("Record", "Slice")
240
241     def update_researchers (self, researcher_hrns, dbsession):
242         # strip that in case we have <researcher> words </researcher>
243         researcher_hrns = [ x.strip() for x in researcher_hrns ]
244         request = dbsession.query (RegUser).filter(RegUser.hrn.in_(researcher_hrns))
245         logger.info ("RegSlice.update_researchers: %d incoming researchers, %d matches found"\
246                      % (len(researcher_hrns), request.count()))
247         researchers = dbsession.query (RegUser).filter(RegUser.hrn.in_(researcher_hrns)).all()
248         self.reg_researchers = researchers
249
250     # when dealing with credentials, we need to retrieve the PIs attached to a slice
251     # WARNING: with the move to passing dbsessions around, we face a glitch here because this
252     # helper function is called from the trust/ area that
253     def get_pis (self):
254         from sqlalchemy.orm import sessionmaker
255         Session = sessionmaker()
256         dbsession = Session.object_session(self)
257         from sfa.util.xrn import get_authority
258         authority_hrn = get_authority(self.hrn)
259         auth_record = dbsession.query(RegAuthority).filter_by(hrn=authority_hrn).first()
260         return auth_record.reg_pis
261         
262     @validates ('expires')
263     def validate_expires (self, key, incoming):
264         return self.validate_datetime (key, incoming)
265
266 ####################
267 class RegNode (RegRecord):
268     __tablename__       = 'nodes'
269     __mapper_args__     = { 'polymorphic_identity' : 'node' }
270     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
271     
272     def __init__(self, **kwds):
273         if 'type' not in kwds:
274             kwds['type']='node'
275         RegRecord.__init__(self, **kwds)
276
277     def __repr__ (self):
278         return RegRecord.__repr__(self).replace("Record", "Node")
279
280 ####################
281 class RegUser (RegRecord):
282     __tablename__       = 'users'
283     # these objects will have type='user' in the records table
284     __mapper_args__     = { 'polymorphic_identity' : 'user' }
285     record_id           = Column (Integer, ForeignKey ("records.record_id"), primary_key=True)
286     #### extensions come here
287     email               = Column ('email', String)
288     # can't use name 'keys' here because when loading from xml we're getting
289     # a 'keys' tag, and assigning a list of strings in a reference column like this crashes
290     reg_keys            = relationship \
291         ('RegKey', backref='reg_user',
292          cascade = "all, delete, delete-orphan",
293         )
294     
295     # so we can use RegUser (email=.., hrn=..) and the like
296     def __init__ (self, **kwds):
297         # handle local settings
298         if 'email' in kwds:
299             self.email = kwds.pop('email')
300         if 'type' not in kwds:
301             kwds['type'] = 'user'
302         RegRecord.__init__(self, **kwds)
303
304     # append stuff at the end of the record __repr__
305     def __repr__ (self): 
306         result = RegRecord.__repr__(self).replace("Record", "User")
307         result.replace(">", " email={}>".format(self.email))
308         return result
309
310     @validates('email') 
311     def validate_email(self, key, address):
312         assert '@' in address
313         return address
314
315 ####################
316 # xxx tocheck : not sure about eager loading of this one
317 # meaning, when querying the whole records, we expect there should
318 # be a single query to fetch all the keys 
319 # or, is it enough that we issue a single query to retrieve all the keys 
320 class RegKey (Base):
321     __tablename__       = 'keys'
322     key_id              = Column (Integer, primary_key=True)
323     record_id           = Column (Integer, ForeignKey ("records.record_id"))
324     key                 = Column (String)
325     pointer             = Column (Integer, default = -1)
326     
327     def __init__ (self, key, pointer=None):
328         self.key = key
329         if pointer:
330             self.pointer = pointer
331
332     def __repr__ (self):
333         result = "<key id=%s key=%s..." % (self.key_id, self.key[8:16],)
334         try:    result += " user=%s" % self.reg_user.record_id
335         except: result += " no-user"
336         result += ">"
337         return result
338
339 class SliverAllocation(Base,AlchemyObj):
340     __tablename__       = 'sliver_allocation'
341     sliver_id           = Column(String, primary_key=True)
342     client_id           = Column(String)
343     component_id        = Column(String)
344     slice_urn           = Column(String)
345     allocation_state    = Column(String)
346
347     def __init__(self, **kwds):
348         if 'sliver_id' in kwds:
349             self.sliver_id = kwds['sliver_id']
350         if 'client_id' in kwds:
351             self.client_id = kwds['client_id']
352         if 'component_id' in kwds:
353             self.component_id = kwds['component_id']
354         if 'slice_urn' in kwds:
355             self.slice_urn = kwds['slice_urn']
356         if 'allocation_state' in kwds:
357             self.allocation_state = kwds['allocation_state']
358
359     def __repr__(self):
360         result = "<sliver_allocation sliver_id=%s allocation_state=%s"\
361                  % (self.sliver_id, self.allocation_state)
362         return result
363
364     @validates('allocation_state')
365     def validate_allocation_state(self, key, state):
366         allocation_states = ['geni_unallocated', 'geni_allocated', 'geni_provisioned']
367         assert state in allocation_states
368         return state
369
370     @staticmethod    
371     def set_allocations(sliver_ids, state, dbsession):
372         if not isinstance(sliver_ids, list):
373             sliver_ids = [sliver_ids]
374         sliver_state_updated = {}
375         constraint = SliverAllocation.sliver_id.in_(sliver_ids)
376         sliver_allocations = dbsession.query (SliverAllocation).filter(constraint)
377         sliver_ids_found = []
378         for sliver_allocation in sliver_allocations:
379             sliver_allocation.allocation_state = state
380             sliver_ids_found.append(sliver_allocation.sliver_id)
381
382         # Some states may not have been updated becuase no sliver allocation state record
383         # exists for the sliver. Insert new allocation records for these slivers and set
384         # it to geni_allocated.
385         sliver_ids_not_found = set(sliver_ids).difference(sliver_ids_found)
386         for sliver_id in sliver_ids_not_found:
387             record = SliverAllocation(sliver_id=sliver_id, allocation_state=state)
388             dbsession.add(record)
389         dbsession.commit()
390
391     @staticmethod
392     def delete_allocations(sliver_ids, dbsession):
393         if not isinstance(sliver_ids, list):
394             sliver_ids = [sliver_ids]
395         constraint = SliverAllocation.sliver_id.in_(sliver_ids)
396         sliver_allocations = dbsession.query(SliverAllocation).filter(constraint)
397         for sliver_allocation in sliver_allocations:
398             dbsession.delete(sliver_allocation)
399         dbsession.commit()
400     
401     def sync(self, dbsession):
402         constraints = [SliverAllocation.sliver_id == self.sliver_id]
403         results = dbsession.query(SliverAllocation).filter(and_(*constraints))
404         records = []
405         for result in results:
406             records.append(result) 
407         
408         if not records:
409             dbsession.add(self)
410         else:
411             record = records[0]
412             record.sliver_id = self.sliver_id
413             record.client_id  = self.client_id
414             record.component_id  = self.component_id
415             record.slice_urn  = self.slice_urn
416             record.allocation_state = self.allocation_state
417         dbsession.commit()    
418         
419
420 ##############################
421 # although the db needs of course to be reachable for the following functions
422 # the schema management functions are here and not in alchemy
423 # because the actual details of the classes need to be known
424 # migrations: this code has no notion of the previous versions
425 # of the data model nor of migrations
426 # sfa.storage.migrations.db_init uses this when starting from
427 # a fresh db only
428 def init_tables(engine):
429     logger.info("Initializing db schema from current/latest model")
430     Base.metadata.create_all(engine)
431
432 def drop_tables(engine):
433     logger.info("Dropping tables from current/latest model")
434     Base.metadata.drop_all(engine)
435
436 ##############################
437 # create a record of the right type from either a dict or an xml string
438 def make_record (dict=None, xml=""):
439     if dict is None: dict={}
440     if dict:    return make_record_dict (dict)
441     elif xml:   return make_record_xml (xml)
442     else:       raise Exception("make_record has no input")
443
444 # convert an incoming record - typically from xmlrpc - into an object
445 def make_record_dict (record_dict):
446     assert ('type' in record_dict)
447     type = record_dict['type'].split('+')[0]
448     if type == 'authority':
449         result = RegAuthority (dict=record_dict)
450     elif type == 'user':
451         result = RegUser (dict=record_dict)
452     elif type == 'slice':
453         result = RegSlice (dict=record_dict)
454     elif type == 'node':
455         result = RegNode (dict=record_dict)
456     else:
457         logger.debug("Untyped RegRecord instance")
458         result = RegRecord (dict=record_dict)
459     logger.info("converting dict into Reg* with type=%s"%type)
460     logger.info("returning=%s"%result)
461     # xxx todo
462     # register non-db attributes in an extensions field
463     return result
464         
465 def make_record_xml (xml):
466     xml_record = XML(xml)
467     xml_dict = xml_record.todict()
468     logger.info("load from xml, keys=%s"%xml_dict.keys())
469     return make_record_dict (xml_dict)
470
471 ####################
472 # augment local records with data from builtin relationships
473 # expose related objects as a list of hrns
474 # we pick names that clearly won't conflict with the ones used in the old approach,
475 # were the relationships data came from the testbed side
476 # for each type, a dict of the form {<field-name-exposed-in-record>:<alchemy_accessor_name>}
477 # so after that, an 'authority' record will e.g. have a 'reg-pis' field with the hrns of its pi-users
478 augment_map={'authority': {'reg-pis' : 'reg_pis',},
479              'slice': {'reg-researchers' : 'reg_researchers',},
480              'user': {'reg-pi-authorities' : 'reg_authorities_as_pi',
481                       'reg-slices' : 'reg_slices_as_researcher',},
482              }
483
484 def augment_with_sfa_builtins(local_record):
485     # don't ruin the import of that file in a client world
486     from sfa.util.xrn import Xrn
487     # add a 'urn' field
488     setattr(local_record,'reg-urn',Xrn(xrn=local_record.hrn, type=local_record.type).urn)
489     # users have keys and this is needed to synthesize 'users' sent over to CreateSliver
490     if local_record.type == 'user':
491         user_keys = [ key.key for key in local_record.reg_keys ]
492         setattr(local_record, 'reg-keys', user_keys)
493     # search in map according to record type
494     type_map=augment_map.get(local_record.type, {})
495     # use type-dep. map to do the job
496     for (field_name, attribute) in type_map.items():
497         # get related objects
498         related_records = getattr(local_record, attribute, [])
499         hrns = [ r.hrn for r in related_records ]
500         setattr (local_record, field_name, hrns)
501     
502