This commit is contained in:
Emmanuel Garette 2019-12-13 16:42:10 +01:00
parent a7934e37d7
commit eccc5c4098
42 changed files with 211 additions and 246 deletions

View File

@ -1,4 +1,4 @@
uri: applicationservices.dataset.updated uri: applicationservice.dataset.updated
description: | description: |
Initialise la table pour les services applicatifs. Initialise la table pour les services applicatifs.
@ -7,8 +7,6 @@ pattern: rpc
public: true public: true
domain: applicationservices-domain
parameters: parameters:
release_path: release_path:
type: String type: String

View File

@ -4,14 +4,10 @@ uri: config.configuration.server.deploy
description: | description: |
Déployer la configuration d'un serveur. Déployer la configuration d'un serveur.
sampleuse: ~
pattern: event pattern: event
public: false public: false
domain: config-domain
parameters: parameters:
server_id: server_id:
type: Number type: Number

View File

@ -4,14 +4,10 @@ uri: config.configuration.server.get
description: | description: |
Récupère le contenu de la configuration. Récupère le contenu de la configuration.
sampleuse: ~
pattern: rpc pattern: rpc
public: false public: false
domain: config-domain
parameters: parameters:
server_id: server_id:
type: Number type: Number

View File

@ -4,14 +4,10 @@ uri: config.configuration.server.updated
description: | description: |
Une configuration de serveur a été mise à jour. Une configuration de serveur a été mise à jour.
sampleuse: ~
pattern: event pattern: event
public: false public: false
domain: config-domain
parameters: parameters:
server_id: server_id:
type: Number type: Number

View File

@ -7,8 +7,6 @@ pattern: event
public: false public: false
domain: server-domain
parameters: parameters:
type: Server type: Server
description: Description du serveur. description: Description du serveur.

View File

@ -1,8 +1,6 @@
--- ---
uri: server.deleted uri: server.deleted
sampleuse: ~
description: | description: |
Un serveur a été supprimé. Un serveur a été supprimé.
@ -10,8 +8,6 @@ pattern: event
public: false public: false
domain: server-domain
parameters: parameters:
server_id: server_id:
type: Number type: Number

View File

@ -4,15 +4,10 @@ uri: server.list
description: | description: |
Liste les serveurs disponibles. Liste les serveurs disponibles.
sampleuse: |
zephir-client server.list
public: true public: true
pattern: rpc pattern: rpc
domain: server-domain
response: response:
type: '[]Server' type: '[]Server'
description: Retourne la liste des serveurs. description: Retourne la liste des serveurs.

View File

@ -7,8 +7,6 @@ pattern: event
public: false public: false
domain: servermodel-domain
parameters: parameters:
type: Servermodel type: Servermodel
description: Informations sur les modèles de serveur créés. description: Informations sur les modèles de serveur créés.

View File

@ -7,8 +7,6 @@ pattern: rpc
public: true public: true
domain: servermodel-domain
parameters: parameters:
release_path: release_path:
type: String type: String

View File

@ -4,15 +4,10 @@ uri: servermodel.describe
description: | description: |
Retourne les attributs détaillés d'un modèle de serveur. Retourne les attributs détaillés d'un modèle de serveur.
sampleuse: |
zephir-client servermodel.describe -s 1
pattern: rpc pattern: rpc
public: true public: true
domain: servermodel-domain
parameters: parameters:
servermodelid: servermodelid:
type: Number type: Number

View File

@ -4,15 +4,10 @@ uri: servermodel.list
description: | description: |
Retourne la liste des modèles de serveur disponibles. Retourne la liste des modèles de serveur disponibles.
sampleuse: |
zephir-client servermodel.list
pattern: rpc pattern: rpc
public: true public: true
domain: servermodel-domain
parameters: parameters:
sourceid: sourceid:
type: Number type: Number

View File

@ -7,8 +7,6 @@ pattern: event
public: false public: false
domain: servermodel-domain
parameters: parameters:
type: 'Servermodel' type: 'Servermodel'
description: Informations sur les modèles de serveur modifiés. description: Informations sur les modèles de serveur modifiés.

View File

@ -8,8 +8,6 @@ pattern: rpc
public: true public: true
domain: session-domain
parameters: parameters:
session_id: session_id:
type: String type: String

View File

@ -8,8 +8,6 @@ pattern: rpc
public: true public: true
domain: session-domain
parameters: parameters:
session_id: session_id:
type: String type: String

View File

@ -8,8 +8,6 @@ pattern: rpc
public: true public: true
domain: session-domain
parameters: parameters:
session_id: session_id:
type: String type: String

View File

@ -8,8 +8,6 @@ pattern: rpc
public: true public: true
domain: session-domain
response: response:
type: '[]Session' type: '[]Session'
description: | description: |

View File

@ -8,8 +8,6 @@ pattern: rpc
public: true public: true
domain: session-domain
parameters: parameters:
id: id:
type: Number type: Number

View File

@ -8,8 +8,6 @@ pattern: rpc
public: true public: true
domain: session-domain
parameters: parameters:
session_id: session_id:
ref: Config.SessionId ref: Config.SessionId

View File

@ -8,8 +8,6 @@ pattern: rpc
public: true public: true
domain: session-domain
parameters: parameters:
session_id: session_id:
ref: Config.SessionId ref: Config.SessionId

View File

@ -8,8 +8,6 @@ pattern: rpc
public: true public: true
domain: session-domain
parameters: parameters:
session_id: session_id:
type: String type: String

View File

@ -8,8 +8,6 @@ pattern: rpc
public: true public: true
domain: session-domain
parameters: parameters:
session_id: session_id:
type: String type: String

View File

@ -8,8 +8,6 @@ pattern: rpc
public: true public: true
domain: session-domain
parameters: parameters:
session_id: session_id:
type: String type: String

View File

@ -7,8 +7,6 @@ pattern: rpc
public: true public: true
domain: session-domain
response: response:
type: '[]Session' type: '[]Session'
description: | description: |

View File

@ -7,8 +7,6 @@ pattern: rpc
public: true public: true
domain: session-domain
parameters: parameters:
id: id:
type: Number type: Number

View File

@ -7,8 +7,6 @@ pattern: rpc
public: true public: true
domain: session-domain
parameters: parameters:
session_id: session_id:
ref: Config.SessionId ref: Config.SessionId

View File

@ -8,8 +8,6 @@ pattern: rpc
public: true public: true
domain: session-domain
parameters: parameters:
session_id: session_id:
ref: Config.SessionId ref: Config.SessionId

View File

@ -7,8 +7,6 @@ pattern: rpc
public: true public: true
domain: source-domain
parameters: parameters:
source_name: source_name:
type: String type: String

View File

@ -8,8 +8,6 @@ pattern: rpc
public: true public: true
domain: source-domain
response: response:
type: '[]Release' type: '[]Release'
description: Liste des versions disponibles. description: Liste des versions disponibles.

View File

@ -4,14 +4,10 @@ uri: template.generate
description: | description: |
Génère et récupère les templates générés. Génère et récupère les templates générés.
sampleuse: ~
pattern: rpc pattern: rpc
public: true public: true
domain: template-domain
parameters: parameters:
server_id: server_id:
type: Number type: Number

View File

@ -19,7 +19,7 @@ properties:
applicationservice_dependencies: applicationservice_dependencies:
type: array type: array
items: items:
type: integer type: number
description: Liste des services applicatifs déclarés en dépendance de ce service applicatif. description: Liste des services applicatifs déclarés en dépendance de ce service applicatif.
required: required:

View File

@ -3,55 +3,28 @@ title: Servermodel
type: object type: object
description: Description d'un modèle de serveur. description: Description d'un modèle de serveur.
properties: properties:
servermodelid: servermodel_id:
type: number type: number
description: ID du modèle de serveur. description: ID du modèle de serveur.
ref: Servermodel.ServermodelId ref: Servermodel.ServermodelId
servermodelname: servermodel_name:
type: string type: string
description: Nom du modèle de serveur. description: Nom du modèle de serveur.
servermodeldescription: servermodel_description:
type: string type: string
description: Description du modèle de serveur. description: Description du modèle de serveur.
servermodelparentsid: servermodel_parents_id:
type: array type: array
items: items:
type: number type: number
ref: Servermodel.ServermodelId ref: Servermodel.ServermodelId
description: ID du modèle de serveur parent. description: ID du modèle de serveur parent.
subreleaseid: release_id:
type: number type: number
ref: Servermodel.SubreleaseId ref: Servermodel.SubreleaseId
description: Version du modèle de serveur. description: Version du modèle de serveur.
subreleasename:
type: string
ref: SubRelease.SubReleaseName
description: Nom de la sous-version.
sourceid:
type: number
ref: ServermodelId.SourceId
description: ID de la sous-version.
services:
type: array
items:
type: object
description: Liste des services applicatifs déclarés pour ce modèle de serveur.
schema:
type: string
description: Contenu du schema.
probes:
type: string
description: Informations sur les sondes.
creolefuncs:
type: string
description: Fonctions Creole.
conffiles:
type: string
description: Fichiers creole au format tar encodé base64
required: required:
- servermodelid - servermodel_id
- servermodelname - servermodel_name
- servermodeldescription - servermodel_description
- servermodelsubreleaseid - release_id
- sourceid
- subreleasename

View File

@ -19,16 +19,16 @@ CREATE TABLE Release (
FOREIGN KEY (ReleaseSourceId) REFERENCES Source(SourceId) FOREIGN KEY (ReleaseSourceId) REFERENCES Source(SourceId)
); );
-- Création de la table ServerModel -- Création de la table Servermodel
CREATE TABLE ServerModel ( CREATE TABLE Servermodel (
ServerModelId SERIAL PRIMARY KEY, ServermodelId SERIAL PRIMARY KEY,
ServerModelName VARCHAR(255) NOT NULL, ServermodelName VARCHAR(255) NOT NULL,
ServerModelDescription VARCHAR(255) NOT NULL, ServermodelDescription VARCHAR(255) NOT NULL,
ServerModelParentsId INTEGER [] DEFAULT '{}', ServermodelParentsId INTEGER [] DEFAULT '{}',
ServerModelReleaseId INTEGER NOT NULL, ServermodelReleaseId INTEGER NOT NULL,
ServerModelApplicationServiceId INTEGER NOT NULL, ServermodelApplicationServiceId INTEGER NOT NULL,
ServerModelUsers hstore, ServermodelUsers hstore,
UNIQUE (ServerModelName, ServerModelReleaseId) UNIQUE (ServermodelName, ServermodelReleaseId)
); );
-- Création de la table ApplicationService -- Création de la table ApplicationService

View File

@ -8,7 +8,7 @@ CONFIGURATION_DIR = 'configurations'
TEMPLATE_DIR = 'templates' TEMPLATE_DIR = 'templates'
TMP_DIR = 'tmp' TMP_DIR = 'tmp'
ROUGAIL_DTD_PATH = '../rougail/data/creole.dtd' ROUGAIL_DTD_PATH = '../rougail/data/creole.dtd'
POSTGRESQL_ADDRESS = 'localhost' POSTGRESQL_ADDRESS = '192.168.56.106'
POSTGRESQL_PORT = 5432 POSTGRESQL_PORT = 5432
def get_config(): def get_config():

View File

@ -97,7 +97,10 @@ class CallDispatcher:
risotto_context.function = function_obj['function'] risotto_context.function = function_obj['function']
if function_obj['risotto_context']: if function_obj['risotto_context']:
kw['risotto_context'] = risotto_context kw['risotto_context'] = risotto_context
if function_obj['database']: # do not start a new database connection
if function_obj['database'] and hasattr(old_risotto_context, 'connection'):
risotto_context.connection = old_risotto_context.connection
if function_obj['database'] and not hasattr(risotto_context, 'connection'):
db_conf = get_config().get('database') db_conf = get_config().get('database')
pool = await asyncpg.create_pool(database=db_conf.get('dbname'), user=db_conf.get('user')) pool = await asyncpg.create_pool(database=db_conf.get('dbname'), user=db_conf.get('user'))
async with pool.acquire() as connection: async with pool.acquire() as connection:

View File

@ -42,8 +42,6 @@ class MessageDefinition:
__slots__ = ('version', __slots__ = ('version',
'uri', 'uri',
'description', 'description',
'sampleuse',
'domain',
'parameters', 'parameters',
'public', 'public',
'errors', 'errors',
@ -59,7 +57,6 @@ class MessageDefinition:
self.errors = [] self.errors = []
self.related = [] self.related = []
self.response = None self.response = None
self.sampleuse = None
# loads yaml information into object # loads yaml information into object
for key, value in raw_def.items(): for key, value in raw_def.items():
@ -502,7 +499,7 @@ def _parse_responses(message_def,
# FIXME # FIXME
'File': StrOption}.get(type_) 'File': StrOption}.get(type_)
if not option: if not option:
raise Exception(f'unknown param type {obj.type}') raise Exception(f'unknown param type {obj.type} in responses of message {message_def.uri}')
if hasattr(obj, 'default'): if hasattr(obj, 'default'):
kwargs['default'] = obj.default kwargs['default'] = obj.default
else: else:

View File

@ -0,0 +1 @@
from .applicationservice import Risotto

View File

@ -0,0 +1,70 @@
from os import listdir
from os.path import join
from traceback import print_exc
from yaml import load, SafeLoader
from typing import Dict
from ...controller import Controller
from ...register import register
from ...config import get_config
from ...error import ExecutionError
from ...context import Context
from ...utils import _
class Risotto(Controller):
async def _applicationservice_create(self,
risotto_context: Context,
applicationservice_name: str,
applicationservice_description: str,
release_id: int) -> Dict:
applicationservice_update_query = """INSERT INTO ApplicationService(ApplicationServiceName, ApplicationServiceDescription, ApplicationServiceReleaseId) VALUES ($1,$2,$3)
RETURNING ApplicationServiceId
"""
applicationservice_id = await risotto_context.connection.fetchval(applicationservice_update_query,
applicationservice_name,
applicationservice_description,
release_id)
return {'applicationservice_name': applicationservice_name,
'applicationservice_description': applicationservice_description,
'applicationservice_id': applicationservice_id}
@register('v1.applicationservice.create', None, database=True)
async def applicationservice_create(self,
risotto_context: Context,
applicationservice_name: str,
applicationservice_description: str,
release_id: int) -> Dict:
return await self._applicationservice_create(risotto_context,
applicationservice_name,
applicationservice_description,
release_id)
@register('v1.applicationservice.dataset.updated', None, database=True)
async def applicationservice_update(self,
risotto_context,
release_path: str,
release_id: int) -> Dict:
applicationservice_path = join(release_path, 'applicationservice')
for service in listdir(applicationservice_path):
try:
applicationservice_description_path = join(applicationservice_path,
service,
'applicationservice.yml')
with open(applicationservice_description_path, 'r') as applicationservice_yml:
applicationservice_description = load(applicationservice_yml,
Loader=SafeLoader)
except Exception as err:
if get_config().get('global').get('debug'):
print_exc()
raise ExecutionError(_(f'Error while reading {applicationservice_description_path}: {err}'))
try:
await self._applicationservice_create(risotto_context,
applicationservice_description['name'],
applicationservice_description['description'],
release_id)
except Exception as err:
if get_config().get('global').get('debug'):
print_exc()
raise ExecutionError(_(f"Error while injecting application service {applicationservice_description['name']} in database: {err}"))
return {'retcode': 0,
'returns': _('Application Services successfully loaded')}

View File

@ -1 +0,0 @@
from .application_services import Risotto

View File

@ -1,31 +0,0 @@
from ...controller import Controller
from ...register import register
class Risotto(Controller):
@register('v1.applicationservice.create', None, database=True)
async def applicationservice_create(self, risotto_context, applicationservice_name, applicationservice_description, release_id):
applicationservice_update_query = """INSERT INTO ApplicationService(ApplicationServiceName, ApplicationServiceDescription, ApplicationServiceReleaseId) VALUES ($1,$2,$3)
RETURNING ApplicationServiceId
"""
applicationservice_id = await risotto_context.connection.fetchval(applicationservice_update_query, applicationservice_description['name'], applicationservice_description['description'], release_id)
return {'applicationservice_name': applicationservice_name, 'applicationservice_description': applicationservice_description, 'applicationservice_id': applicationservice_id}
@register('v1.applicationservice.dataset.updated', None, database=True)
async def applicationservice_update(self, risotto_context, release_path, release_id):
applicationservice_path = os.path.join(release_path, 'applicationservice')
for service in os.listdir(applicationservice_path):
try:
applicationservice_description_path = os.path.join(applicationservice_path, service, 'applicationservice.yml')
with open(applicationservice_description_path, 'r') as applicationservice_yml:
applicationservice_description = yaml.load(applicationservice_yml, Loader=yaml.SafeLoader)
except Exception as err:
if get_config().get('global').get('debug'):
print_exc()
raise ExecutionError(_(f'Error while reading {applicationservice_description_path}: {err}'))
try:
await self.applicationservice_create(risotto_context, applicationservice_description['name'], applicationservice_description['description'], release_id)
except Exception as err:
if get_config().get('global').get('debug'):
print_exc()
raise ExecutionError(_(f"Error while injecting application service {applicationservice_description['name']} in database: {err}"))
return {'retcode': 0, 'returns': _('Application Services successfully loaded')}

View File

@ -18,14 +18,14 @@ from ...logger import log
class Risotto(Controller): class Risotto(Controller):
servermodel = {}
server = {}
def __init__(self) -> None: def __init__(self) -> None:
for dirname in [ROOT_CACHE_DIR, DATABASE_DIR]: for dirname in [ROOT_CACHE_DIR, DATABASE_DIR]:
if not isdir(dirname): if not isdir(dirname):
raise RegistrationError(_(f'unable to find the cache dir "{dirname}"')) raise RegistrationError(_(f'unable to find the cache dir "{dirname}"'))
self.save_storage = Storage(engine='sqlite3', dir_database=DATABASE_DIR) self.save_storage = Storage(engine='sqlite3', dir_database=DATABASE_DIR)
self.servermodel = {}
self.server = {}
super().__init__() super().__init__()
async def on_join(self, async def on_join(self,
@ -49,37 +49,37 @@ class Risotto(Controller):
for servermodel in servermodels: for servermodel in servermodels:
try: try:
await self.load_servermodel(risotto_context, await self.load_servermodel(risotto_context,
servermodel['servermodelid'], servermodel['servermodel_id'],
servermodel['servermodelname']) servermodel['servermodel_name'])
except CallError as err: except CallError as err:
pass pass
# do link to this servermodel # do link to this servermodel
for servermodel in servermodels: for servermodel in servermodels:
if 'servermodelparentsid' in servermodel: if 'servermodel_parents_id' in servermodel:
for servermodelparentid in servermodel['servermodelparentsid']: for servermodelparentid in servermodel['servermodel_parents_id']:
self.servermodel_legacy(risotto_context, self.servermodel_legacy(risotto_context,
servermodel['servermodelname'], servermodel['servermodel_name'],
servermodel['servermodelid'], servermodel['servermodel_id'],
servermodelparentid) servermodelparentid)
def get_funcs_filename(self, def get_funcs_filename(self,
servermodelid: int): servermodel_id: int):
return join(ROOT_CACHE_DIR, str(servermodelid)+".creolefuncs") return join(ROOT_CACHE_DIR, str(servermodel_id)+".creolefuncs")
async def load_servermodel(self, async def load_servermodel(self,
risotto_context: Context, risotto_context: Context,
servermodelid: int, servermodel_id: int,
servermodelname: str) -> None: servermodel_name: str) -> None:
""" Loads a servermodel """ Loads a servermodel
""" """
cache_file = join(ROOT_CACHE_DIR, str(servermodelid)+".xml") cache_file = join(ROOT_CACHE_DIR, str(servermodel_id)+".xml")
funcs_file = self.get_funcs_filename(servermodelid) funcs_file = self.get_funcs_filename(servermodel_id)
log.info_msg(risotto_context, log.info_msg(risotto_context,
None, None,
f'Load servermodel {servermodelname} ({servermodelid})') f'Load servermodel {servermodel_name} ({servermodel_id})')
# use file in cache if found, otherwise retrieve it in servermodel context # use file in cache if found, otherwise retrieve it in servermodel context
if isfile(cache_file): if isfile(cache_file):
@ -87,7 +87,7 @@ class Risotto(Controller):
else: else:
servermodel = await self.call('v1.servermodel.describe', servermodel = await self.call('v1.servermodel.describe',
risotto_context, risotto_context,
servermodelid=servermodelid, servermodel_id=servermodel_id,
inheritance=False, inheritance=False,
resolvdepends=False, resolvdepends=False,
schema=True, schema=True,
@ -104,20 +104,20 @@ class Risotto(Controller):
# loads tiramisu config and store it # loads tiramisu config and store it
xmlroot = parse(fileio).getroot() xmlroot = parse(fileio).getroot()
self.servermodel[servermodelid] = self.build_metaconfig(servermodelid, self.servermodel[servermodel_id] = self.build_metaconfig(servermodel_id,
servermodelname, servermodel_name,
xmlroot, xmlroot,
funcs_file) funcs_file)
def build_metaconfig(self, def build_metaconfig(self,
servermodelid: int, servermodel_id: int,
servermodelname: str, servermodel_name: str,
xmlroot: str, xmlroot: str,
funcs_file: str) -> MetaConfig: funcs_file: str) -> MetaConfig:
""" Build metaconfig for a servermodel """ Build metaconfig for a servermodel
""" """
# build tiramisu's session ID # build tiramisu's session ID
session_id = f'v_{servermodelid}' session_id = f'v_{servermodel_id}'
optiondescription = rougail_load(xmlroot, optiondescription = rougail_load(xmlroot,
ROUGAIL_DTD_PATH, ROUGAIL_DTD_PATH,
funcs_file) funcs_file)
@ -149,9 +149,9 @@ class Risotto(Controller):
metaconfig.permissive.add('expert') metaconfig.permissive.add('expert')
# set informtion and owner # set informtion and owner
metaconfig.owner.set('v_{}'.format(servermodelname)) metaconfig.owner.set('v_{}'.format(servermodel_name))
metaconfig.information.set('servermodel_id', servermodelid) metaconfig.information.set('servermodel_id', servermodel_id)
metaconfig.information.set('servermodel_name', servermodelname) metaconfig.information.set('servermodel_name', servermodel_name)
# return configuration # return configuration
return metaconfig return metaconfig
@ -221,7 +221,7 @@ class Risotto(Controller):
risotto_context: Context, risotto_context: Context,
server_id: int, server_id: int,
servername: str, servername: str,
servermodelid: int) -> None: servermodel_id: int) -> None:
""" Loads a server """ Loads a server
""" """
if server_id in self.server: if server_id in self.server:
@ -229,8 +229,8 @@ class Risotto(Controller):
log.info_msg(risotto_context, log.info_msg(risotto_context,
None, None,
f'Load server {servername} ({server_id})') f'Load server {servername} ({server_id})')
if not servermodelid in self.servermodel: if not servermodel_id in self.servermodel:
msg = f'unable to find servermodel with id {servermodelid}' msg = f'unable to find servermodel with id {servermodel_id}'
log.error_msg(risotto_context, log.error_msg(risotto_context,
None, None,
msg) msg)
@ -240,7 +240,7 @@ class Risotto(Controller):
session_id = f's_{server_id}' session_id = f's_{server_id}'
# get the servermodel's metaconfig # get the servermodel's metaconfig
metaconfig = self.servermodel[servermodelid] metaconfig = self.servermodel[servermodel_id]
# create server configuration and server 'to deploy' configuration and store it # create server configuration and server 'to deploy' configuration and store it
self.server[server_id] = {'server': self.build_config(session_id, self.server[server_id] = {'server': self.build_config(session_id,
@ -251,7 +251,7 @@ class Risotto(Controller):
server_id, server_id,
servername, servername,
metaconfig), metaconfig),
'funcs_file': self.get_funcs_filename(servermodelid)} 'funcs_file': self.get_funcs_filename(servermodel_id)}
def build_config(self, def build_config(self,
session_id: str, session_id: str,
@ -280,7 +280,7 @@ class Risotto(Controller):
self.load_server(risotto_context, self.load_server(risotto_context,
server_id, server_id,
servername, servername,
servermodelid) servermodel_id)
@register('v1.server.deleted') @register('v1.server.deleted')
async def server_deleted(self, async def server_deleted(self,
@ -298,35 +298,35 @@ class Risotto(Controller):
@register('v1.servermodel.created') @register('v1.servermodel.created')
async def servermodel_created(self, async def servermodel_created(self,
risotto_context: Context, risotto_context: Context,
servermodelid: int, servermodel_id: int,
servermodelname: str, servermodel_name: str,
servermodelparentsid: List[int]) -> None: servermodel_parents_id: List[int]) -> None:
""" when servermodels are created, load it and do link """ when servermodels are created, load it and do link
""" """
await self.load_and_link_servermodel(risotto_context, await self.load_and_link_servermodel(risotto_context,
servermodelid, servermodel_id,
servermodelname, servermodel_name,
servermodelparentsid) servermodel_parents_id)
async def load_and_link_servermodel(self, async def load_and_link_servermodel(self,
risotto_context: Context, risotto_context: Context,
servermodelid: int, servermodel_id: int,
servermodelname: str, servermodel_name: str,
servermodelparentsid: List[int]) -> None: servermodel_parents_id: List[int]) -> None:
await self.load_servermodel(risotto_context, await self.load_servermodel(risotto_context,
servermodelid, servermodel_id,
servermodelname) servermodel_name)
if servermodelparentsid is not None: if servermodel_parents_id is not None:
for servermodelparentid in servermodelparentsid: for servermodelparentid in servermodel_parents_id:
self.servermodel_legacy(risotto_context, self.servermodel_legacy(risotto_context,
servermodelname, servermodel_name,
servermodelid, servermodel_id,
servermodelparentid) servermodelparentid)
def servermodel_delete(self, def servermodel_delete(self,
servermodelid: int) -> List[MetaConfig]: servermodel_id: int) -> List[MetaConfig]:
metaconfig = self.servermodel.pop(servermodelid) metaconfig = self.servermodel.pop(servermodel_id)
mixconfig = next(metaconfig.config.list()) mixconfig = next(metaconfig.config.list())
children = [] children = []
for child in mixconfig.config.list(): for child in mixconfig.config.list():
@ -345,42 +345,42 @@ class Risotto(Controller):
@register('v1.servermodel.updated') @register('v1.servermodel.updated')
async def servermodel_updated(self, async def servermodel_updated(self,
risotto_context: Context, risotto_context: Context,
servermodelid: int, servermodel_id: int,
servermodelname: str, servermodel_name: str,
servermodelparentsid: List[int]) -> None: servermodel_parents_id: List[int]) -> None:
log.info_msg(risotto_context, log.info_msg(risotto_context,
None, None,
f'Reload servermodel {servermodelname} ({servermodelid})') f'Reload servermodel {servermodel_name} ({servermodel_id})')
# unlink cache to force download new aggregated file # unlink cache to force download new aggregated file
cache_file = join(ROOT_CACHE_DIR, str(servermodelid)+".xml") cache_file = join(ROOT_CACHE_DIR, str(servermodel_id)+".xml")
if isfile(cache_file): if isfile(cache_file):
unlink(cache_file) unlink(cache_file)
# store all informations # store all informations
if servermodelid in self.servermodel: if servermodel_id in self.servermodel:
old_values = self.servermodel[servermodelid].value.exportation() old_values = self.servermodel[servermodel_id].value.exportation()
old_permissives = self.servermodel[servermodelid].permissive.exportation() old_permissives = self.servermodel[servermodel_id].permissive.exportation()
old_properties = self.servermodel[servermodelid].property.exportation() old_properties = self.servermodel[servermodel_id].property.exportation()
children = self.servermodel_delete(servermodelid) children = self.servermodel_delete(servermodel_id)
else: else:
old_values = None old_values = None
# create new one # create new one
await self.load_and_link_servermodel(risotto_context, await self.load_and_link_servermodel(risotto_context,
servermodelid, servermodel_id,
servermodelname, servermodel_name,
servermodelparentsid) servermodel_parents_id)
# migrates informations # migrates informations
if old_values is not None: if old_values is not None:
self.servermodel[servermodelid].value.importation(old_values) self.servermodel[servermodel_id].value.importation(old_values)
self.servermodel[servermodelid].permissive.importation(old_permissives) self.servermodel[servermodel_id].permissive.importation(old_permissives)
self.servermodel[servermodelid].property.importation(old_properties) self.servermodel[servermodel_id].property.importation(old_properties)
for child in children: for child in children:
self.servermodel_legacy(risotto_context, self.servermodel_legacy(risotto_context,
child.information.get('servermodel_name'), child.information.get('servermodel_name'),
child.information.get('servermodel_id'), child.information.get('servermodel_id'),
servermodelid) servermodel_id)
@register('v1.config.configuration.server.get', None) @register('v1.config.configuration.server.get', None)
async def get_configuration(self, async def get_configuration(self,

View File

@ -1,40 +1,70 @@
from os import listdir
from os.path import join
from yaml import load, SafeLoader
from traceback import print_exc
from ...controller import Controller from ...controller import Controller
from ...register import register from ...register import register
from ...utils import _ from ...utils import _
import os from ...context import Context
import yaml
from traceback import print_exc
from ...config import get_config from ...config import get_config
from ...error import ExecutionError from ...error import ExecutionError
class Risotto(Controller): class Risotto(Controller):
@register('v1.servermodel.dataset.updated', None, database=True) @register('v1.servermodel.dataset.updated', None, database=True)
async def servermodel_update(self, risotto_context, release_path, release_id, applicationservice_įd): async def servermodel_update(self,
applicationservice_update = """INSERT INTO ApplicationService(ApplicationServiceName, ApplicationServiceDescription, ApplicationServiceReleaseId) VALUES ($1,$2,$3) risotto_context: Context,
RETURNING ApplicationServiceId release_path: str,
release_id: int):
servermodel_update = """INSERT INTO Servermodel(ServermodelName, ServermodelDescription, ServermodelParentsId, ServermodelReleaseId, ServermodelApplicationServiceId) VALUES ($1,$2,$3,$4,$5)
RETURNING ServermodelId
""" """
servermodel_path = os.path.join(release_path, 'servermodel') servermodel_path = join(release_path, 'servermodel')
for servermodel in os.listdir(servermodel_path): for servermodel in listdir(servermodel_path):
if not servermodel.endswith('.yml'):
continue
servermodel_description_path = join(servermodel_path, servermodel)
try: try:
with open(os.path.join(servermodel_path, servermodel), 'r') as applicationservice_yml: with open(servermodel_description_path, 'r') as servermodel_yml:
applicationservice_description = yaml.load(applicationservice_yml, Loader=yaml.SafeLoader) servermodel_description = load(servermodel_yml,
Loader=SafeLoader)
except Exception as err: except Exception as err:
if get_config().get('global').get('debug'): if get_config().get('global').get('debug'):
print_exc() print_exc()
raise ExecutionError(_(f'Error while reading {applicationservice_description_path}: {err}')) raise ExecutionError(_(f'Error while reading {servermodel_description_path}: {err}'))
sm_name = servermodel_description['name']
sm_description = servermodel_description['description']
sm_parentsid = servermodel_description['parent']
if sm_parentsid is None:
sm_parentsid = []
else:
sm_parentsid = [sm_parentsid]
as_name = f"local_{sm_name}"
as_description = f'local application service for {sm_name}'
applicationservice = await self.call('v1.applicationservice.create',
risotto_context,
applicationservice_name=as_name,
applicationservice_description=as_description,
release_id=release_id)
try: try:
await risotto_context.connection.fetch(applicationservice_update, applicationservice_description['name'], applicationservice_description['description'], release_id) await risotto_context.connection.fetch(servermodel_update,
sm_name,
sm_description,
sm_parentsid,
release_id,
applicationservice['applicationservice_id'])
except Exception as err: except Exception as err:
if get_config().get('global').get('debug'): if get_config().get('global').get('debug'):
print_exc() print_exc()
raise ExecutionError(_(f"Error while injecting application service {applicationservice_description['name']} in database: {err}")) raise ExecutionError(_(f"Error while injecting servermodel {servermodel_description['name']} in database: {err}"))
return {'retcode': 0, 'returns': _('Application Services successfully loaded')} return {'retcode': 0, 'returns': _('Servermodels successfully loaded')}
@register('v1.servermodel.list', None, database=True) @register('v1.servermodel.list', None, database=True)
async def servermodel_list(self, risotto_context, sourceid): async def servermodel_list(self,
risotto_context: Context,
sourceid: int):
sql = ''' sql = '''
SELECT * FROM ServerModel SELECT ServermodelId as servermodel_id, ServermodelName as servermodel_name, ServermodelDescription as servermodel_description, ServermodelParentsId as servermodel_parents_id, ServermodelReleaseId as release_id FROM Servermodel
''' '''
servermodels = await risotto_context.connection.fetch(sql) servermodels = await risotto_context.connection.fetch(sql)
return [dict(r) for r in servermodels] return [dict(r) for r in servermodels]