From ccd8f24adf24b700e3d4ab2ac218c0c91d195e25 Mon Sep 17 00:00:00 2001 From: vanzhiganov Date: Tue, 10 May 2016 02:42:07 +0300 Subject: [PATCH] refactoring --- SWSCloudCore/__init__.py | 102 +----------------- SWSCloudCore/application.py | 100 +++++++++++++++++ SWSCloudCore/config.py | 33 ++++++ SWSCloudCore/controllers/settings/__init__.py | 32 +++++- SWSCloudCore/controllers/settings/manage.py | 2 +- SWSCloudCore/models.py | 12 +-- SWSCloudCore/settings.py | 19 ---- ...wscloud-admin-add.py => cloud-admin-add.py | 2 +- .../swscloud-admin-ls.py => cloud-admin-ls.py | 0 ...admin-passwd.py => cloud-admin-password.py | 0 exec/swscloud-db-init.py => cloud-db-init.py | 22 ++-- exec/swscloud-dc-add.py => cloud-dc-add.py | 0 exec/swscloud-dc-ls.py => cloud-dc-ls.py | 0 exec/swscloud-ip-add.py => cloud-ip-add.py | 0 ...wscloud-runserver.py => cloud-runserver.py | 0 ...cloud-server-add.py => cloud-server-add.py | 0 ...wscloud-server-ls.py => cloud-server-ls.py | 0 ...settings-init.py => cloud-settings-init.py | 0 cloud-settings.py | 45 ++++++++ setup.py | 24 +++-- swscloud-runserver.py | 7 -- 21 files changed, 245 insertions(+), 155 deletions(-) create mode 100644 SWSCloudCore/application.py create mode 100644 SWSCloudCore/config.py delete mode 100644 SWSCloudCore/settings.py rename exec/swscloud-admin-add.py => cloud-admin-add.py (92%) rename exec/swscloud-admin-ls.py => cloud-admin-ls.py (100%) rename exec/swscloud-admin-passwd.py => cloud-admin-password.py (100%) rename exec/swscloud-db-init.py => cloud-db-init.py (71%) rename exec/swscloud-dc-add.py => cloud-dc-add.py (100%) rename exec/swscloud-dc-ls.py => cloud-dc-ls.py (100%) rename exec/swscloud-ip-add.py => cloud-ip-add.py (100%) rename exec/swscloud-runserver.py => cloud-runserver.py (100%) rename exec/swscloud-server-add.py => cloud-server-add.py (100%) rename exec/swscloud-server-ls.py => cloud-server-ls.py (100%) rename exec/swscloud-settings-init.py => cloud-settings-init.py (100%) create mode 100644 cloud-settings.py delete mode 100644 swscloud-runserver.py diff --git a/SWSCloudCore/__init__.py b/SWSCloudCore/__init__.py index b5500d2..61086b2 100644 --- a/SWSCloudCore/__init__.py +++ b/SWSCloudCore/__init__.py @@ -1,100 +1,2 @@ -# coding: utf-8 - -from flask import Flask, g, render_template, request -from flask_babel import Babel -from flaskext.markdown import Markdown - -from SWSCloudCore.views import viewHomepage -from SWSCloudCore.views.account import viewAccount -from SWSCloudCore.views.administrator import viewAdministrator -from SWSCloudCore.views.api import viewAPI -from SWSCloudCore.views.containers import viewContainers -from SWSCloudCore.views.documents import viewDocuments -from SWSCloudCore.views.kb import viewKB -from SWSCloudCore.views.server_api import viewServerAPI -from SWSCloudCore.views.support import viewSupport -from SWSCloudCore.views.tasks import viewTasks -from SWSCloudCore.views.payments import viewPayments - -from SWSCloudCore import models -from SWSCloudCore.models import database -from SWSCloudCore.settings import settings - -app = Flask(__name__, static_folder='static', static_url_path='') -# app.config['SERVER_NAME'] = settings.get('Application', 'SERVER_NAME') -app.config['DEBUG'] = settings.getboolean('Application', 'DEBUG') -app.config['SECRET_KEY'] = settings.get("Application", "SECRET_KEY") -Markdown(app) -babel = Babel(app) - - -# / -app.register_blueprint(viewHomepage) -app.register_blueprint(viewSupport) -app.register_blueprint(viewKB) -app.register_blueprint(viewDocuments) -app.register_blueprint(viewAPI) -# /tasks -app.register_blueprint(viewTasks) -# /containers -app.register_blueprint(viewContainers) -# /id -app.register_blueprint(viewAccount) -# /payments -app.register_blueprint(viewPayments) -# /api -app.register_blueprint(viewServerAPI) -# /administrator -app.register_blueprint(viewAdministrator) - - -@app.errorhandler(404) -def page_not_found(e): - return render_template('errors/404.html'), 404 - - -@app.errorhandler(403) -def page_not_found(e): - return render_template('errors/403.html'), 403 - - -@app.errorhandler(410) -def page_not_found(e): - return render_template('errors/410.html'), 410 - - -@app.errorhandler(500) -def page_not_found(e): - print e - return render_template('errors/500.html'), 500 - - -@app.before_request -def before_request(): - # app.logger.debug("db.connect") - g.errors = {'total': 0, 'items': []} - g.settings = dict() - - try: - database.connect() - except Exception as e: - # TODO: code to email alert - print e - print request.path - # g.endpoint = request.endpoint.replace('.', '/') - return render_template('errors/500.html'), 500 - - # извлекаем настройки и определяем их в глобальную переменную - for setting in models.Settings.select(models.Settings.key, models.Settings.val).execute(): - g.settings[setting.key] = setting.val - - -@app.after_request -def after_request(response): - # app.logger.debug("db.close") - try: - database.close() - except Exception as e: - # TODO: code to email alert - print e - return response +from SWSCloudCore.application import app +from SWSCloudCore.config import config diff --git a/SWSCloudCore/application.py b/SWSCloudCore/application.py new file mode 100644 index 0000000..14b4a23 --- /dev/null +++ b/SWSCloudCore/application.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +from flask import Flask, g, render_template, request +from flask_babel import Babel +from flaskext.markdown import Markdown + +from SWSCloudCore.views import viewHomepage +from SWSCloudCore.views.account import viewAccount +from SWSCloudCore.views.administrator import viewAdministrator +from SWSCloudCore.views.api import viewAPI +from SWSCloudCore.views.containers import viewContainers +from SWSCloudCore.views.documents import viewDocuments +from SWSCloudCore.views.kb import viewKB +from SWSCloudCore.views.server_api import viewServerAPI +from SWSCloudCore.views.support import viewSupport +from SWSCloudCore.views.tasks import viewTasks +from SWSCloudCore.views.payments import viewPayments + +from SWSCloudCore import models +from SWSCloudCore.models import database +from SWSCloudCore.config import config + +app = Flask(__name__, static_folder='static', static_url_path='') +# app.config['SERVER_NAME'] = settings.get('Application', 'SERVER_NAME') +app.config['DEBUG'] = config.getboolean('Application', 'DEBUG') +app.config['SECRET_KEY'] = config.get("Application", "SECRET_KEY") +Markdown(app) +babel = Babel(app) + + +# / +app.register_blueprint(viewHomepage) +app.register_blueprint(viewSupport) +app.register_blueprint(viewKB) +app.register_blueprint(viewDocuments) +app.register_blueprint(viewAPI) +# /tasks +app.register_blueprint(viewTasks) +# /containers +app.register_blueprint(viewContainers) +# /id +app.register_blueprint(viewAccount) +# /payments +app.register_blueprint(viewPayments) +# /api +app.register_blueprint(viewServerAPI) +# /administrator +app.register_blueprint(viewAdministrator) + + +@app.errorhandler(404) +def page_not_found(e): + return render_template('errors/404.html'), 404 + + +@app.errorhandler(403) +def page_not_found(e): + return render_template('errors/403.html'), 403 + + +@app.errorhandler(410) +def page_not_found(e): + return render_template('errors/410.html'), 410 + + +@app.errorhandler(500) +def page_not_found(e): + print e + return render_template('errors/500.html'), 500 + + +@app.before_request +def before_request(): + # app.logger.debug("db.connect") + g.errors = {'total': 0, 'items': []} + g.settings = dict() + + try: + database.connect() + except Exception as e: + # TODO: code to email alert + print e + print request.path + # g.endpoint = request.endpoint.replace('.', '/') + return render_template('errors/500.html'), 500 + + # извлекаем настройки и определяем их в глобальную переменную + for setting in models.Settings.select(models.Settings.key, models.Settings.val).execute(): + g.settings[setting.key] = setting.val + + +@app.after_request +def after_request(response): + # app.logger.debug("db.close") + try: + database.close() + except Exception as e: + # TODO: code to email alert + print e + return response diff --git a/SWSCloudCore/config.py b/SWSCloudCore/config.py new file mode 100644 index 0000000..e3b59b0 --- /dev/null +++ b/SWSCloudCore/config.py @@ -0,0 +1,33 @@ +# coding: utf-8 + +import sys +import os +import ConfigParser + +__config_file__ = os.getenv('CLOUD_CONFIG_FILE', '/etc/sws/cloud/core.ini') + +# setting file read +config = ConfigParser.ConfigParser() +if os.path.exists(__config_file__): + config.read(__config_file__) + + if not config.has_section('Application'): + sys.exit(1) + if not config.has_option('Application', 'DEBUG'): + sys.exit(1) + if not config.has_option('Application', 'SECRET_KEY'): + sys.exit(1) + if not config.has_section('Database'): + sys.exit(1) + if not config.has_option('Database', 'name'): + sys.exit(1) + if not config.has_option('Database', 'host'): + sys.exit(1) + if not config.has_option('Database', 'port'): + sys.exit(1) + if not config.has_option('Database', 'user'): + sys.exit(1) + if not config.has_option('Database', 'password'): + sys.exit(1) +else: + sys.exit('config file not found: %s' % __config_file__) diff --git a/SWSCloudCore/controllers/settings/__init__.py b/SWSCloudCore/controllers/settings/__init__.py index 0b39d46..8af1e23 100644 --- a/SWSCloudCore/controllers/settings/__init__.py +++ b/SWSCloudCore/controllers/settings/__init__.py @@ -1,8 +1,38 @@ # coding: utf-8 -__author__ = 'vanzhiganov' +from SWSCloudCore.models import Settings class ControllerSettings: def __init__(self): pass + + def get(self, key=''): + x = Settings.select().where(Settings.key == key) + return x.get().val + + def set(self, key, val): + if self.exists(key): + # update + return True + # insert + return True + + def create(self, key, val): + x = Settings.create(key=key, val=val) + return x.id + + def update(self, key, val): + x = Settings.update(val=val).where(Settings.key == key) + x.execute() + return True + + def delete(self, key): + x = Settings.delete().where(Settings.key == key) + x.execute() + return True + + def exists(self, key): + if Settings.select().where(Settings.key == key).count() == 0: + return False + return True diff --git a/SWSCloudCore/controllers/settings/manage.py b/SWSCloudCore/controllers/settings/manage.py index a412d5c..f841dd6 100644 --- a/SWSCloudCore/controllers/settings/manage.py +++ b/SWSCloudCore/controllers/settings/manage.py @@ -12,4 +12,4 @@ class ControllerManageSettings: return None def delete(self): - return None \ No newline at end of file + return None diff --git a/SWSCloudCore/models.py b/SWSCloudCore/models.py index 9732127..5a0a642 100644 --- a/SWSCloudCore/models.py +++ b/SWSCloudCore/models.py @@ -6,15 +6,15 @@ from peewee import DateTimeField, TextField, FloatField, BigIntegerField from peewee import Model, UUIDField, CharField, ForeignKeyField, IntegerField from peewee import PostgresqlDatabase -from SWSCloudCore.settings import settings +from SWSCloudCore.config import config # connect to database database = PostgresqlDatabase( - settings.get('Database', 'name'), - host=settings.get('Database', 'host'), - port=settings.getint('Database', 'port'), - user=settings.get('Database', 'user'), - password=settings.get('Database', 'password'), + config.get('Database', 'name'), + host=config.get('Database', 'host'), + port=config.getint('Database', 'port'), + user=config.get('Database', 'user'), + password=config.get('Database', 'password'), threadlocals=True, fields={'uuid': 'uuid'} ) diff --git a/SWSCloudCore/settings.py b/SWSCloudCore/settings.py deleted file mode 100644 index 560e96c..0000000 --- a/SWSCloudCore/settings.py +++ /dev/null @@ -1,19 +0,0 @@ -# coding: utf-8 - -import sys -import os -import ConfigParser - -default_file = '/etc/sws/cloud/settings.ini' -# default_file = '%s/gocloud.ini' % os.getenv('HOME') - -settings_file = os.getenv('CLOUDNS_SETTINGS_FILE', default_file) - -# current_path = os.path.dirname(os.path.abspath(__file__)) - -# setting file read -settings = ConfigParser.ConfigParser() -if os.path.exists(settings_file): - settings.read(settings_file) -else: - sys.exit('settings file not found: %s' % settings_file) diff --git a/exec/swscloud-admin-add.py b/cloud-admin-add.py similarity index 92% rename from exec/swscloud-admin-add.py rename to cloud-admin-add.py index 6f8a88f..7cb02a2 100644 --- a/exec/swscloud-admin-add.py +++ b/cloud-admin-add.py @@ -10,7 +10,7 @@ from SWSCloudCore import models """ Утилита добавления администратора Как использовать: - swscloud-admin-add.py --email admin@cloud.com --password qwerty + cloud-admin-add.py --email admin@cloud.com --password qwerty """ parser = argparse.ArgumentParser(description='') diff --git a/exec/swscloud-admin-ls.py b/cloud-admin-ls.py similarity index 100% rename from exec/swscloud-admin-ls.py rename to cloud-admin-ls.py diff --git a/exec/swscloud-admin-passwd.py b/cloud-admin-password.py similarity index 100% rename from exec/swscloud-admin-passwd.py rename to cloud-admin-password.py diff --git a/exec/swscloud-db-init.py b/cloud-db-init.py similarity index 71% rename from exec/swscloud-db-init.py rename to cloud-db-init.py index 514a606..3cee2d8 100644 --- a/exec/swscloud-db-init.py +++ b/cloud-db-init.py @@ -1,27 +1,31 @@ #!/usr/bin/env python +# coding: utf-8 from SWSCloudCore import models -# TODO: connect to database -models.database.create_tables({ - models.Admins, +tables = [ models.DataCenters, models.Servers, models.ServersSettings, models.Ips, - models.Settings, models.Users, - models.UsersBalance, - models.UsersBalanceTransactions, - models.UsersDetails, models.UsersRecoveryCodes, models.UsersSecrets, + models.UsersDetails, + models.UsersBalance, + models.UsersBalanceTransactions, models.SSHKeys, models.Containers, models.ContainersStatistics, models.ContainersStatisticsState, models.Tasks, -}, safe=True) + models.Settings, + models.Admins, + models.Notifications, + models.NotificationsSecurity, +] -# TODO: close connect with database +models.database.connect() +models.database.create_tables(tables, safe=True) +models.database.close() diff --git a/exec/swscloud-dc-add.py b/cloud-dc-add.py similarity index 100% rename from exec/swscloud-dc-add.py rename to cloud-dc-add.py diff --git a/exec/swscloud-dc-ls.py b/cloud-dc-ls.py similarity index 100% rename from exec/swscloud-dc-ls.py rename to cloud-dc-ls.py diff --git a/exec/swscloud-ip-add.py b/cloud-ip-add.py similarity index 100% rename from exec/swscloud-ip-add.py rename to cloud-ip-add.py diff --git a/exec/swscloud-runserver.py b/cloud-runserver.py similarity index 100% rename from exec/swscloud-runserver.py rename to cloud-runserver.py diff --git a/exec/swscloud-server-add.py b/cloud-server-add.py similarity index 100% rename from exec/swscloud-server-add.py rename to cloud-server-add.py diff --git a/exec/swscloud-server-ls.py b/cloud-server-ls.py similarity index 100% rename from exec/swscloud-server-ls.py rename to cloud-server-ls.py diff --git a/exec/swscloud-settings-init.py b/cloud-settings-init.py similarity index 100% rename from exec/swscloud-settings-init.py rename to cloud-settings-init.py diff --git a/cloud-settings.py b/cloud-settings.py new file mode 100644 index 0000000..a957001 --- /dev/null +++ b/cloud-settings.py @@ -0,0 +1,45 @@ +#!/usr/bin/bash +# coding: utf-8 + +import argparse +from SWSCloudCore.controllers.settings import ControllerSettings + + +class SettingsCli(object): + def __init__(self): + self.parser = argparse.ArgumentParser(description='Process some integers.') + self.parser.add_argument('--key', metavar='k', type=str, default='', help='settings key') + self.parser.add_argument('--value', metavar='v', type=str, default='', help='settings value') + # get, set, delete + self.parser.add_argument('--action', metavar='a', type=str, help='action to invoke (get is default)') + self.controller = ControllerSettings() + + def run(self): + args = self.parser.parse_args() + if args.action: + action = args.action.lower() + if hasattr(self, action): + # invoke method if it exists in self + return getattr(self, action)(args.key, args.value) + # unsupported action + else: + self.parser.print_help() + + def get(self, key, value=None): + key = self.controller.get(key) + return 1 if not key else key + + def set(self, key, value): + if self.controller.exists(key): + code = int(self.controller.update(key, value)) + else: + code = int(self.controller.create(key, value)) + return code + + def delete(self, key, value=None): + return int(self.controller.delete(key)) + + +if __name__ == '__main__': + x = SettingsCli().run() + exit(x) diff --git a/setup.py b/setup.py index 4f3ec38..fe439dc 100644 --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ from setuptools import setup setup( name='SWSCloudCore', - version='2.1.6', + version='2.1.7', author='Vyacheslav Anzhiganov', author_email='hello@anzhiganov.com', packages=[ @@ -77,21 +77,23 @@ setup( ] }, scripts=[ - 'exec/swscloud-db-init.py', - 'exec/swscloud-settings-init.py', - 'exec/swscloud-runserver.py', + 'cloud-db-init.py', + 'cloud-settings.py', + # + 'exec/cloud-settings-init.py', + 'exec/cloud-runserver.py', # accounts - 'exec/swscloud-admin-add.py', + 'exec/cloud-admin-add.py', # TODO: make it # 'exec/swscloud-admin-delete.py', - 'exec/swscloud-admin-ls.py', - 'exec/swscloud-admin-passwd.py', + 'exec/cloud-admin-ls.py', + 'exec/cloud-admin-password.py', # datacenters - 'exec/swscloud-dc-add.py', - 'exec/swscloud-dc-ls.py', + 'cloud-dc-add.py', + 'exec/cloud-dc-ls.py', # servers - 'exec/swscloud-server-add.py', - 'exec/swscloud-server-ls.py', + 'exec/cloud-server-add.py', + 'exec/cloud-server-ls.py', ], install_requires=[ 'Flask==0.10', diff --git a/swscloud-runserver.py b/swscloud-runserver.py deleted file mode 100644 index a771076..0000000 --- a/swscloud-runserver.py +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env python -# coding: utf-8 - -from SWSCloudCore import app - -if __name__ == '__main__': - app.run()