Compare commits

..

No commits in common. "cb4dde1dc4bec4b694694693fca01599c34d4d26" and "c740ec3fe3d33b2ac76bf262f6547625630e7786" have entirely different histories.

4 changed files with 113 additions and 152 deletions

View File

@ -48,8 +48,8 @@ class CallDispatcher:
except AttributeError: except AttributeError:
err = _(f'function {module_name}.{function_name} return the unknown parameter "{key}" for the uri "{risotto_context.version}.{risotto_context.message}"') err = _(f'function {module_name}.{function_name} return the unknown parameter "{key}" for the uri "{risotto_context.version}.{risotto_context.message}"')
raise CallError(err) raise CallError(err)
except ValueError as err: except ValueError:
err = _(f'function {module_name}.{function_name} return the invalid parameter "{key}" for the uri "{risotto_context.version}.{risotto_context.message}": {err}') err = _(f'function {module_name}.{function_name} return the parameter "{key}" with an unvalid value "{value}" for the uri "{risotto_context.version}.{risotto_context.message}"')
raise CallError(err) raise CallError(err)
await config.property.read_only() await config.property.read_only()
mandatories = await config.value.mandatory() mandatories = await config.value.mandatory()
@ -89,7 +89,6 @@ class CallDispatcher:
if hasattr(old_risotto_context, 'connection'): if hasattr(old_risotto_context, 'connection'):
# do not start a new database connection # do not start a new database connection
risotto_context.connection = old_risotto_context.connection risotto_context.connection = old_risotto_context.connection
risotto_context.log_connection = old_risotto_context.log_connection
await log.start(risotto_context, await log.start(risotto_context,
kwargs, kwargs,
info_msg, info_msg,
@ -109,84 +108,73 @@ class CallDispatcher:
config_arguments, config_arguments,
function_obj, function_obj,
) )
await log.success(risotto_context, except CallError as err:
ret,
)
except Exception as err:
await log.failed(risotto_context, await log.failed(risotto_context,
str(err), str(err),
) )
raise CallError(err) from err raise err from err
else: else:
error = None try:
async with self.pool.acquire() as log_connection: async with self.pool.acquire() as connection:
await log_connection.set_type_codec( await connection.set_type_codec(
'json', 'json',
encoder=dumps, encoder=dumps,
decoder=loads, decoder=loads,
schema='pg_catalog' schema='pg_catalog'
) )
async with log_connection.transaction(): risotto_context.connection = connection
try: async with connection.transaction():
risotto_context.log_connection = log_connection try:
async with self.pool.acquire() as connection: await log.start(risotto_context,
await connection.set_type_codec( kwargs,
'json', info_msg,
encoder=dumps, )
decoder=loads, await self.check_message_type(risotto_context,
schema='pg_catalog' kwargs,
) )
risotto_context.connection = connection config_arguments = await self.load_kwargs_to_config(risotto_context,
async with connection.transaction(): f'{version}.{message}',
try: kwargs,
await log.start(risotto_context, check_role,
internal,
)
ret = await self.launch(risotto_context,
kwargs, kwargs,
info_msg, config_arguments,
function_obj,
) )
await self.check_message_type(risotto_context, # log the success
kwargs, await log.success(risotto_context,
) ret,
config_arguments = await self.load_kwargs_to_config(risotto_context, )
f'{version}.{message}', if not internal and isinstance(ret, dict):
kwargs, ret['context_id'] = risotto_context.context_id
check_role, except CallError as err:
internal, if get_config()['global']['debug']:
) print_exc()
ret = await self.launch(risotto_context, await log.failed(risotto_context,
kwargs, str(err),
config_arguments, )
function_obj, raise err from err
) except CallError as err:
# log the success raise err from err
await log.success(risotto_context, except Exception as err:
ret, # if there is a problem with arguments, just send an error and do nothing
) if get_config()['global']['debug']:
if not internal and isinstance(ret, dict): print_exc()
ret['context_id'] = risotto_context.context_id async with self.pool.acquire() as connection:
except CallError as err: await connection.set_type_codec(
if get_config()['global']['debug']: 'json',
print_exc() encoder=dumps,
await log.failed(risotto_context, decoder=loads,
str(err), schema='pg_catalog'
) )
raise err from err risotto_context.connection = connection
except CallError as err: async with connection.transaction():
error = err
except Exception as err:
# if there is a problem with arguments, just send an error and do nothing
if get_config()['global']['debug']:
print_exc()
await log.failed(risotto_context, await log.failed(risotto_context,
str(err), str(err),
) )
error = err raise err from err
if error:
if not internal:
err = CallError(str(error))
err.context_id = risotto_context.context_id
else:
err = error
raise err from error
return ret return ret

View File

@ -101,31 +101,15 @@ async def handle(request):
internal=False, internal=False,
**kwargs, **kwargs,
) )
except NotAllowedError as err:
raise HTTPNotFound(reason=str(err))
except CallError as err:
raise HTTPBadRequest(reason=str(err).replace('\n', ' '))
except Exception as err: except Exception as err:
context_id = None if get_config()['global']['debug']:
if isinstance(err, NotAllowedError): print_exc()
error_type = HTTPNotFound raise HTTPInternalServerError(reason=str(err))
elif isinstance(err, CallError): return Response(text=dumps({'response': text}),
error_type = HTTPBadRequest
context_id = err.context_id
else:
if get_config()['global']['debug']:
print_exc()
error_type = HTTPInternalServerError
response = {'type': 'error',
'reason': str(err).replace('\n', ' '),
}
if context_id is not None:
response['context_id'] = context_id
err = dumps({'response': response,
'type': 'error',
})
raise error_type(text=err,
content_type='application/json',
)
return Response(text=dumps({'response': text,
'type': 'success',
}),
content_type='application/json', content_type='application/json',
) )

View File

@ -38,7 +38,7 @@ class Logger:
sql = insert + ') ' + values + ') RETURNING LogId' sql = insert + ') ' + values + ') RETURNING LogId'
try: try:
log_id = await risotto_context.log_connection.fetchval(sql, *args) log_id = await risotto_context.connection.fetchval(sql, *args)
if context_id is None and start: if context_id is None and start:
risotto_context.context_id = log_id risotto_context.context_id = log_id
if start: if start:
@ -60,14 +60,14 @@ class Logger:
sql += ' AND URI = $3' sql += ' AND URI = $3'
args.append(uri) args.append(uri)
ret = [] ret = []
for row in await risotto_context.log_connection.fetch(*args): for row in await risotto_context.connection.fetch(*args):
d = {} d = {}
for key, value in row.items(): for key, value in row.items():
if key == 'data': if key == 'data':
if not value: if not value:
value = {} value = {}
# else: else:
# value = loads(value) value = loads(value)
elif key in ['start_date', 'stop_date']: elif key in ['start_date', 'stop_date']:
value = str(value) value = str(value)
d[key] = value d[key] = value
@ -141,11 +141,7 @@ class Logger:
) -> None: ) -> None:
paths_msg = self._get_message_paths(risotto_context) paths_msg = self._get_message_paths(risotto_context)
if get_config()['global']['debug']: if get_config()['global']['debug']:
if risotto_context.context_id != None: print(_(f'{risotto_context.username}: START:{paths_msg}: {msg}'))
context = f'({risotto_context.context_id})'
else:
context = ''
print(_(f'{risotto_context.username}: START{context}:{paths_msg}: {msg}'))
await self.insert(msg, await self.insert(msg,
self._get_last_uri(risotto_context), self._get_last_uri(risotto_context),
paths_msg, paths_msg,
@ -161,7 +157,7 @@ class Logger:
) -> None: ) -> None:
if get_config()['global']['debug']: if get_config()['global']['debug']:
paths_msg = self._get_message_paths(risotto_context) paths_msg = self._get_message_paths(risotto_context)
print(_(f'{risotto_context.username}: SUCCESS({risotto_context.context_id}):{paths_msg}')) print(_(f'{risotto_context.username}: SUCCESS:{paths_msg}({risotto_context.context_id})'))
sql = """UPDATE RisottoLog sql = """UPDATE RisottoLog
SET StopDate = $2, SET StopDate = $2,
Level = 'SUCCESS' Level = 'SUCCESS'
@ -173,10 +169,10 @@ class Logger:
args.append(dumps(returns)) args.append(dumps(returns))
sql += """WHERE LogId = $1 sql += """WHERE LogId = $1
""" """
await risotto_context.log_connection.execute(sql, await risotto_context.connection.execute(sql,
risotto_context.start_id, risotto_context.start_id,
*args, *args,
) )
async def failed(self, async def failed(self,
risotto_context: Context, risotto_context: Context,
@ -184,22 +180,18 @@ class Logger:
) -> None: ) -> None:
if get_config()['global']['debug']: if get_config()['global']['debug']:
paths_msg = self._get_message_paths(risotto_context) paths_msg = self._get_message_paths(risotto_context)
if risotto_context.context_id != None: print(_(f'{risotto_context.username}: FAILED:{paths_msg}({risotto_context.context_id}): err'))
context = f'({risotto_context.context_id})'
else:
context = ''
print(_(f'{risotto_context.username}: FAILED({risotto_context.context_id}):{paths_msg}: err'))
sql = """UPDATE RisottoLog sql = """UPDATE RisottoLog
SET StopDate = $2, SET StopDate = $2,
Level = 'FAILED', Level = 'FAILED',
Msg = $3 Msg = $3
WHERE LogId = $1 WHERE LogId = $1
""" """
await risotto_context.log_connection.execute(sql, await risotto_context.connection.execute(sql,
risotto_context.start_id, risotto_context.start_id,
datetime.now(), datetime.now(),
err, err,
) )
async def info(self, async def info(self,
risotto_context, risotto_context,

View File

@ -297,38 +297,35 @@ class RegisterDispatcher:
truncate: bool=False, truncate: bool=False,
) -> None: ) -> None:
internal_user = get_config()['global']['internal_user'] internal_user = get_config()['global']['internal_user']
async with self.pool.acquire() as log_connection: async with self.pool.acquire() as connection:
async with log_connection.transaction(): await connection.set_type_codec(
async with self.pool.acquire() as connection: 'json',
await connection.set_type_codec( encoder=dumps,
'json', decoder=loads,
encoder=dumps, schema='pg_catalog'
decoder=loads, )
schema='pg_catalog' if truncate:
) async with connection.transaction():
if truncate: await connection.execute('TRUNCATE InfraServer, InfraSite, InfraZone, Log, ProviderDeployment, ProviderFactoryCluster, ProviderFactoryClusterNode, SettingApplicationservice, SettingApplicationServiceDependency, SettingRelease, SettingServer, SettingServermodel, SettingSource, UserRole, UserRoleURI, UserURI, UserUser, InfraServermodel, ProviderZone, ProviderServer, ProviderSource, ProviderApplicationservice, ProviderServermodel')
async with connection.transaction(): async with connection.transaction():
await connection.execute('TRUNCATE InfraServer, InfraSite, InfraZone, Log, ProviderDeployment, ProviderFactoryCluster, ProviderFactoryClusterNode, SettingApplicationservice, SettingApplicationServiceDependency, SettingRelease, SettingServer, SettingServermodel, SettingSource, UserRole, UserRoleURI, UserURI, UserUser, InfraServermodel, ProviderZone, ProviderServer, ProviderSource, ProviderApplicationservice, ProviderServermodel') for submodule_name, module in self.injected_self.items():
async with connection.transaction(): risotto_context = Context()
for submodule_name, module in self.injected_self.items(): risotto_context.username = internal_user
risotto_context = Context() risotto_context.paths.append(f'internal.{submodule_name}.on_join')
risotto_context.username = internal_user risotto_context.type = None
risotto_context.paths.append(f'internal.{submodule_name}.on_join') risotto_context.connection = connection
risotto_context.type = None risotto_context.module = submodule_name.split('.', 1)[0]
risotto_context.log_connection = log_connection info_msg = _(f'in function risotto_{submodule_name}.on_join')
risotto_context.connection = connection await log.info_msg(risotto_context,
risotto_context.module = submodule_name.split('.', 1)[0] None,
info_msg = _(f'in function risotto_{submodule_name}.on_join') info_msg)
await log.info_msg(risotto_context, try:
None, await module.on_join(risotto_context)
info_msg) except Exception as err:
try: if get_config()['global']['debug']:
await module.on_join(risotto_context) print_exc()
except Exception as err: msg = _(f'on_join returns an error in module {submodule_name}: {err}')
if get_config()['global']['debug']: await log.error_msg(risotto_context, {}, msg)
print_exc()
msg = _(f'on_join returns an error in module {submodule_name}: {err}')
await log.error_msg(risotto_context, {}, msg)
async def load(self): async def load(self):
# valid function's arguments # valid function's arguments