X-Git-Url: https://osm.etsi.org/gitweb/?a=blobdiff_plain;f=osm_mon%2Fcore%2Fdatabase.py;h=61bd18060122f759a22c625064e7a1b98b1db84e;hb=628df021896fa8775f9743af62a4267b617cc35c;hp=2191106fc16edb33a7dc6fb0fe68381c67d4a68a;hpb=6439eb0e6f03b89629bbb8bad3e092133e56a614;p=osm%2FMON.git diff --git a/osm_mon/core/database.py b/osm_mon/core/database.py index 2191106..61bd180 100644 --- a/osm_mon/core/database.py +++ b/osm_mon/core/database.py @@ -23,45 +23,74 @@ ## import logging +import os +from typing import Iterable -from peewee import * -from playhouse.sqlite_ext import SqliteExtDatabase +from peewee import CharField, FloatField, Model, AutoField, Proxy, ForeignKeyField +from peewee_migrate import Router +from playhouse.db_url import connect -from osm_mon.plugins.OpenStack.settings import Config +from osm_mon import migrations +from osm_mon.core.config import Config log = logging.getLogger(__name__) -cfg = Config.instance() -db = SqliteExtDatabase('mon.db') +db = Proxy() class BaseModel(Model): + id = AutoField(primary_key=True) + class Meta: database = db -class VimCredentials(BaseModel): - uuid = CharField() +class Alarm(BaseModel): + uuid = CharField(unique=True) + name = CharField() + severity = CharField() + threshold = FloatField() + operation = CharField() + statistic = CharField() + metric = CharField() + + +class AlarmTag(BaseModel): name = CharField() - type = CharField() - url = CharField() - user = CharField() - password = CharField() - tenant_name = CharField() - config = TextField() + value = CharField() + alarm = ForeignKeyField(Alarm, related_name='tags', on_delete='CASCADE') class DatabaseManager: - def create_tables(self): - try: - db.connect() - db.create_tables([VimCredentials]) - db.close() - except Exception as e: - log.exception("Error creating tables: ") - - def get_credentials(self, vim_uuid): - return VimCredentials.get(VimCredentials.uuid == vim_uuid) - - def save_credentials(self, vim_credentials): - vim_credentials.save() + def __init__(self, config: Config): + db.initialize(connect(config.get('sql', 'database_uri'))) + + def create_tables(self) -> None: + db.connect() + with db.atomic(): + router = Router(db, os.path.dirname(migrations.__file__)) + router.run() + db.close() + + +class AlarmTagRepository: + @staticmethod + def create(**query) -> Alarm: + return AlarmTag.create(**query) + + +class AlarmRepository: + @staticmethod + def create(**query) -> Alarm: + return Alarm.create(**query) + + @staticmethod + def get(*expressions) -> Alarm: + return Alarm.select().where(*expressions).get() + + @staticmethod + def list(*expressions) -> Iterable[Alarm]: + if expressions == (): + return Alarm.select() + else: + return Alarm.select().where(*expressions)