~rlane/nova/ldapimprovements

« back to all changes in this revision

Viewing changes to nova/db/sqlalchemy/models.py

  • Committer: Ryan Lane
  • Date: 2010-11-24 15:46:32 UTC
  • mfrom: (382.48.1 trunk)
  • Revision ID: laner@controller-20101124154632-zh7kwjuyyd02a2lh
MergeĀ fromĀ trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16
16
#    License for the specific language governing permissions and limitations
17
17
#    under the License.
18
 
 
19
 
"""
20
 
SQLAlchemy models for nova data
21
 
"""
22
 
 
23
 
import sys
 
18
"""
 
19
SQLAlchemy models for nova data.
 
20
"""
 
21
 
24
22
import datetime
25
23
 
26
 
# TODO(vish): clean up these imports
27
 
from sqlalchemy.orm import relationship, backref, exc, object_mapper
 
24
from sqlalchemy.orm import relationship, backref, object_mapper
28
25
from sqlalchemy import Column, Integer, String, schema
29
26
from sqlalchemy import ForeignKey, DateTime, Boolean, Text
30
27
from sqlalchemy.exc import IntegrityError
37
34
from nova import exception
38
35
from nova import flags
39
36
 
 
37
 
40
38
FLAGS = flags.FLAGS
41
 
 
42
39
BASE = declarative_base()
43
40
 
44
41
 
45
42
class NovaBase(object):
46
 
    """Base class for Nova Models"""
 
43
    """Base class for Nova Models."""
47
44
    __table_args__ = {'mysql_engine': 'InnoDB'}
48
45
    __table_initialized__ = False
49
 
    __prefix__ = 'none'
50
46
    created_at = Column(DateTime, default=datetime.datetime.utcnow)
51
47
    updated_at = Column(DateTime, onupdate=datetime.datetime.utcnow)
52
48
    deleted_at = Column(DateTime)
53
49
    deleted = Column(Boolean, default=False)
54
50
 
55
 
    @property
56
 
    def str_id(self):
57
 
        """Get string id of object (generally prefix + '-' + id)"""
58
 
        return "%s-%s" % (self.__prefix__, self.id)
59
 
 
60
51
    def save(self, session=None):
61
 
        """Save this object"""
 
52
        """Save this object."""
62
53
        if not session:
63
54
            session = get_session()
64
55
        session.add(self)
71
62
                raise
72
63
 
73
64
    def delete(self, session=None):
74
 
        """Delete this object"""
 
65
        """Delete this object."""
75
66
        self.deleted = True
76
67
        self.deleted_at = datetime.datetime.utcnow()
77
68
        self.save(session=session)
82
73
    def __getitem__(self, key):
83
74
        return getattr(self, key)
84
75
 
 
76
    def get(self, key, default=None):
 
77
        return getattr(self, key, default)
 
78
 
85
79
    def __iter__(self):
86
80
        self._i = iter(object_mapper(self).columns)
87
81
        return self
90
84
        n = self._i.next().name
91
85
        return n, getattr(self, n)
92
86
 
 
87
    def update(self, values):
 
88
        """Make the model object behave like a dict"""
 
89
        for k, v in values.iteritems():
 
90
            setattr(self, k, v)
 
91
 
 
92
    def iteritems(self):
 
93
        """Make the model object behave like a dict"""
 
94
        return iter(self)
 
95
 
 
96
 
93
97
# TODO(vish): Store images in the database instead of file system
94
98
#class Image(BASE, NovaBase):
95
99
#    """Represents an image in the datastore"""
96
100
#    __tablename__ = 'images'
97
 
#    __prefix__ = 'ami'
98
101
#    id = Column(Integer, primary_key=True)
99
102
#    ec2_id = Column(String(12), unique=True)
100
103
#    user_id = Column(String(255))
137
140
 
138
141
 
139
142
class Service(BASE, NovaBase):
140
 
    """Represents a running service on a host"""
 
143
    """Represents a running service on a host."""
 
144
 
141
145
    __tablename__ = 'services'
142
146
    id = Column(Integer, primary_key=True)
143
147
    host = Column(String(255))  # , ForeignKey('hosts.id'))
148
152
 
149
153
 
150
154
class Instance(BASE, NovaBase):
151
 
    """Represents a guest vm"""
 
155
    """Represents a guest vm."""
152
156
    __tablename__ = 'instances'
153
 
    __prefix__ = 'i'
154
157
    id = Column(Integer, primary_key=True)
155
158
    internal_id = Column(Integer, unique=True)
156
159
 
225
228
 
226
229
 
227
230
class Volume(BASE, NovaBase):
228
 
    """Represents a block storage device that can be attached to a vm"""
 
231
    """Represents a block storage device that can be attached to a vm."""
229
232
    __tablename__ = 'volumes'
230
 
    __prefix__ = 'vol'
231
233
    id = Column(Integer, primary_key=True)
232
234
    ec2_id = Column(String(12), unique=True)
233
235
 
255
257
    display_name = Column(String(255))
256
258
    display_description = Column(String(255))
257
259
 
 
260
    @property
 
261
    def name(self):
 
262
        return self.ec2_id
 
263
 
258
264
 
259
265
class Quota(BASE, NovaBase):
260
 
    """Represents quota overrides for a project"""
 
266
    """Represents quota overrides for a project."""
261
267
    __tablename__ = 'quotas'
262
268
    id = Column(Integer, primary_key=True)
263
269
 
269
275
    gigabytes = Column(Integer)
270
276
    floating_ips = Column(Integer)
271
277
 
272
 
    @property
273
 
    def str_id(self):
274
 
        return self.project_id
275
 
 
276
278
 
277
279
class ExportDevice(BASE, NovaBase):
278
 
    """Represates a shelf and blade that a volume can be exported on"""
 
280
    """Represates a shelf and blade that a volume can be exported on."""
279
281
    __tablename__ = 'export_devices'
280
282
    __table_args__ = (schema.UniqueConstraint("shelf_id", "blade_id"),
281
283
                      {'mysql_engine': 'InnoDB'})
290
292
                                           'ExportDevice.deleted==False)')
291
293
 
292
294
 
 
295
class IscsiTarget(BASE, NovaBase):
 
296
    """Represates an iscsi target for a given host"""
 
297
    __tablename__ = 'iscsi_targets'
 
298
    __table_args__ = (schema.UniqueConstraint("target_num", "host"),
 
299
                      {'mysql_engine': 'InnoDB'})
 
300
    id = Column(Integer, primary_key=True)
 
301
    target_num = Column(Integer)
 
302
    host = Column(String(255))
 
303
    volume_id = Column(Integer, ForeignKey('volumes.id'), nullable=True)
 
304
    volume = relationship(Volume,
 
305
                          backref=backref('iscsi_target', uselist=False),
 
306
                          foreign_keys=volume_id,
 
307
                          primaryjoin='and_(IscsiTarget.volume_id==Volume.id,'
 
308
                                           'IscsiTarget.deleted==False)')
 
309
 
 
310
 
293
311
class SecurityGroupInstanceAssociation(BASE, NovaBase):
294
312
    __tablename__ = 'security_group_instance_association'
295
313
    id = Column(Integer, primary_key=True)
298
316
 
299
317
 
300
318
class SecurityGroup(BASE, NovaBase):
301
 
    """Represents a security group"""
 
319
    """Represents a security group."""
302
320
    __tablename__ = 'security_groups'
303
321
    id = Column(Integer, primary_key=True)
304
322
 
328
346
 
329
347
 
330
348
class SecurityGroupIngressRule(BASE, NovaBase):
331
 
    """Represents a rule in a security group"""
 
349
    """Represents a rule in a security group."""
332
350
    __tablename__ = 'security_group_rules'
333
351
    id = Column(Integer, primary_key=True)
334
352
 
350
368
 
351
369
 
352
370
class KeyPair(BASE, NovaBase):
353
 
    """Represents a public key pair for ssh"""
 
371
    """Represents a public key pair for ssh."""
354
372
    __tablename__ = 'key_pairs'
355
373
    id = Column(Integer, primary_key=True)
356
374
 
361
379
    fingerprint = Column(String(255))
362
380
    public_key = Column(Text)
363
381
 
364
 
    @property
365
 
    def str_id(self):
366
 
        return '%s.%s' % (self.user_id, self.name)
367
 
 
368
382
 
369
383
class Network(BASE, NovaBase):
370
 
    """Represents a network"""
 
384
    """Represents a network."""
371
385
    __tablename__ = 'networks'
372
386
    __table_args__ = (schema.UniqueConstraint("vpn_public_address",
373
387
                                              "vpn_public_port"),
396
410
 
397
411
 
398
412
class AuthToken(BASE, NovaBase):
399
 
    """Represents an authorization token for all API transactions. Fields
400
 
    are a string representing the actual token and a user id for mapping
401
 
    to the actual user"""
 
413
    """Represents an authorization token for all API transactions.
 
414
 
 
415
    Fields are a string representing the actual token and a user id for
 
416
    mapping to the actual user
 
417
 
 
418
    """
402
419
    __tablename__ = 'auth_tokens'
403
420
    token_hash = Column(String(255), primary_key=True)
404
421
    user_id = Column(Integer)
409
426
 
410
427
# TODO(vish): can these both come from the same baseclass?
411
428
class FixedIp(BASE, NovaBase):
412
 
    """Represents a fixed ip for an instance"""
 
429
    """Represents a fixed ip for an instance."""
413
430
    __tablename__ = 'fixed_ips'
414
431
    id = Column(Integer, primary_key=True)
415
432
    address = Column(String(255))
426
443
    leased = Column(Boolean, default=False)
427
444
    reserved = Column(Boolean, default=False)
428
445
 
429
 
    @property
430
 
    def str_id(self):
431
 
        return self.address
432
 
 
433
446
 
434
447
class User(BASE, NovaBase):
435
 
    """Represents a user"""
 
448
    """Represents a user."""
436
449
    __tablename__ = 'users'
437
450
    id = Column(String(255), primary_key=True)
438
451
 
444
457
 
445
458
 
446
459
class Project(BASE, NovaBase):
447
 
    """Represents a project"""
 
460
    """Represents a project."""
448
461
    __tablename__ = 'projects'
449
462
    id = Column(String(255), primary_key=True)
450
463
    name = Column(String(255))
492
505
 
493
506
 
494
507
class FloatingIp(BASE, NovaBase):
495
 
    """Represents a floating ip that dynamically forwards to a fixed ip"""
 
508
    """Represents a floating ip that dynamically forwards to a fixed ip."""
496
509
    __tablename__ = 'floating_ips'
497
510
    id = Column(Integer, primary_key=True)
498
511
    address = Column(String(255))
508
521
 
509
522
 
510
523
def register_models():
511
 
    """Register Models and create metadata"""
 
524
    """Register Models and create metadata.
 
525
 
 
526
    Called from nova.db.sqlalchemy.__init__ as part of loading the driver,
 
527
    it will never need to be called explicitly elsewhere.
 
528
    """
512
529
    from sqlalchemy import create_engine
513
 
    models = (Service, Instance, Volume, ExportDevice, FixedIp,
 
530
    models = (Service, Instance, Volume, ExportDevice, IscsiTarget, FixedIp,
514
531
              FloatingIp, Network, SecurityGroup,
515
532
              SecurityGroupIngressRule, SecurityGroupInstanceAssociation,
516
533
              AuthToken, User, Project)  # , Image, Host