Commit ecdfff77 authored by Alain Takoudjou's avatar Alain Takoudjou

slapgrid.promise: fix get promise result

parent 99c1d7ea
...@@ -220,26 +220,27 @@ class GenericPromise(object): ...@@ -220,26 +220,27 @@ class GenericPromise(object):
match = regex.match(line) match = regex.match(line)
if match is not None: if match is not None:
if not only_failure or (only_failure and match.groups()[1] == 'ERROR'): if not only_failure or (only_failure and match.groups()[1] == 'ERROR'):
result_list.append([ result_list.append({
match.groups()[0], 'date': match.groups()[0],
match.groups()[1], 'status': match.groups()[1],
(match.groups()[2] + line_part).strip(), 'message': (match.groups()[2] + line_part).strip(),
]) })
line_part = "" line_part = ""
else: else:
line_part += '\n' + line line_part += '\n' + line
result_list.reverse()
return result_list return result_list
def getLastPromiseResultList(self, latest_minute=1, only_failure=False): def getLastPromiseResultList(self, latest_minute=1, only_failure=False):
""" """
Return the latest log result of the promise Return the latest log result of the promise starting from the most recent
@param last_minute: the number of minutes in the past. If last_minute is @param last_minute: the number of minutes in the past. If last_minute is
1, it will return the log of the latest minute execution. 1, it will return the log of the latest minute execution.
@param only_failure: only return the lines which contain failures. @param only_failure: only return the lines which contain failures.
@return Return a list of logs. The format is [["DATE", "STATUS", MESSAGE]] @return Return a dict of logs. The format is
ex: [['2018-02-02 17:49:01', 'ERROR', "Promise has failed"], ...] [{"date": "DATE", "status": "STATUS", "message": MESSAGE}, ]
""" """
if self.__log_file is None: if self.__log_file is None:
...@@ -279,17 +280,16 @@ class GenericPromise(object): ...@@ -279,17 +280,16 @@ class GenericPromise(object):
break break
if not only_failure or \ if not only_failure or \
(only_failure and result.groups()[1] == 'ERROR'): (only_failure and result.groups()[1] == 'ERROR'):
line_list.append([ line_list.append({
result.groups()[0], 'date': result.groups()[0],
result.groups()[1], 'status': result.groups()[1],
(result.groups()[2] + line_part).strip(), 'message': (result.groups()[2] + line_part).strip(),
]) })
else: else:
line_part += '\n' + line line_part += '\n' + line
line = "" line = ""
continue continue
line = line_part = "" line = line_part = ""
line_list.reverse()
return line_list return line_list
def defaultTest(self, latest_minute=2, failure_amount=1, is_anomaly=False): def defaultTest(self, latest_minute=2, failure_amount=1, is_anomaly=False):
...@@ -312,24 +312,25 @@ class GenericPromise(object): ...@@ -312,24 +312,25 @@ class GenericPromise(object):
result_size = len(latest_result_list) result_size = len(latest_result_list)
if result_size == 0: if result_size == 0:
return module(problem=False, message="No result found!") return module(problem=False, message="No result found!")
if latest_result_list[0]['status'] != 'ERROR':
# latest execution is OK
return module(problem=False, message=latest_result_list[0]['message'])
i = 0 i = 1
failure_found = 0 failure_found = 1
latest_result_list.reverse()
# we test at most the `failure_amount` latest results
while i < result_size and failure_found < failure_amount: while i < result_size and failure_found < failure_amount:
if latest_result_list[i][1] == 'ERROR': if latest_result_list[i]['status'] == 'ERROR':
failure_found += 1 failure_found += 1
problem = True problem = True
i += 1 i += 1
if failure_found != failure_amount: if failure_found != failure_amount:
return module(problem=False, message=latest_result_list[0][2]) return module(problem=False, message=latest_result_list[0]['message'])
return module(problem=problem, message=latest_result_list[0][2]) return module(problem=problem, message=latest_result_list[0]['message'])
@abstractmethod @abstractmethod
def sense(self): def sense(self):
"""Run the promise code and store the result""" """Run the promise code and log the result"""
def anomaly(self): def anomaly(self):
"""Called to detect if there is an anomaly which require to bang.""" """Called to detect if there is an anomaly which require to bang."""
...@@ -464,7 +465,8 @@ class PromiseRunner(Process): ...@@ -464,7 +465,8 @@ class PromiseRunner(Process):
class PromiseLauncher(object): class PromiseLauncher(object):
def __init__(self, config=None, logger=None, save_method=None): def __init__(self, config=None, logger=None, save_method=None,
extra_config=None):
""" """
Promise launcher will run promises Promise launcher will run promises
...@@ -511,6 +513,7 @@ class PromiseLauncher(object): ...@@ -511,6 +513,7 @@ class PromiseLauncher(object):
Set to True if promise launcher is executed by slapgrid. Set to True if promise launcher is executed by slapgrid.
force force
Set to True if force run promises without check their periodicity Set to True if force run promises without check their periodicity
@param extra_config: A dictionary of extra config to send to all promises
""" """
self.save_method = save_method self.save_method = save_method
...@@ -535,6 +538,9 @@ class PromiseLauncher(object): ...@@ -535,6 +538,9 @@ class PromiseLauncher(object):
} }
if config is not None: if config is not None:
self.__config.update(config) self.__config.update(config)
self.__extra_config = {}
if extra_config is not None:
self.__extra_config = extra_config
for key, value in self.__config.items(): for key, value in self.__config.items():
setattr(self, key.replace('-', '_'), value or None) setattr(self, key.replace('-', '_'), value or None)
...@@ -757,6 +763,7 @@ class PromiseLauncher(object): ...@@ -757,6 +763,7 @@ class PromiseLauncher(object):
'computer-id': self.computer_id, 'computer-id': self.computer_id,
'queue': self.queue_result, 'queue': self.queue_result,
} }
base_config.update(self.__extra_config)
if os.path.exists(self.promise_folder) and os.path.isdir(self.promise_folder): if os.path.exists(self.promise_folder) and os.path.isdir(self.promise_folder):
# if there is no __init file, add it # if there is no __init file, add it
......
...@@ -798,8 +798,12 @@ class TestSlapOSGenericPromise(TestSlapOSPromiseMixin): ...@@ -798,8 +798,12 @@ class TestSlapOSGenericPromise(TestSlapOSPromiseMixin):
latest_message_list = promise.getLastPromiseResultList(latest_minute=1) latest_message_list = promise.getLastPromiseResultList(latest_minute=1)
date_string = date.strftime('%Y-%m-%d %H:%M:%S') date_string = date.strftime('%Y-%m-%d %H:%M:%S')
self.assertEquals(len(latest_message_list), 2) self.assertEquals(len(latest_message_list), 2)
self.assertEquals(latest_message_list[0], [date_string, 'INFO', 'Promise is running...']) self.assertEquals(
self.assertEquals(latest_message_list[1], [date_string, 'INFO', 'success']) latest_message_list[0],
{'date': date_string, 'status': 'INFO', 'message': 'success'})
self.assertEquals(
latest_message_list[1],
{'date': date_string, 'status': 'INFO', 'message': 'Promise is running...'})
def test_promise_resultfromlog_error(self): def test_promise_resultfromlog_error(self):
promise_content = 'self.logger.error("Promise is running...\\nmessage in new line")' promise_content = 'self.logger.error("Promise is running...\\nmessage in new line")'
...@@ -814,8 +818,13 @@ class TestSlapOSGenericPromise(TestSlapOSPromiseMixin): ...@@ -814,8 +818,13 @@ class TestSlapOSGenericPromise(TestSlapOSPromiseMixin):
latest_message_list = promise.getLastPromiseResultList(latest_minute=1) latest_message_list = promise.getLastPromiseResultList(latest_minute=1)
date_string = date.strftime('%Y-%m-%d %H:%M:%S') date_string = date.strftime('%Y-%m-%d %H:%M:%S')
self.assertEquals(len(latest_message_list), 2) self.assertEquals(len(latest_message_list), 2)
self.assertEquals(latest_message_list[0], [date_string, 'ERROR', 'Promise is running...\nmessage in new line']) self.assertEquals(
self.assertEquals(latest_message_list[1], [date_string, 'INFO', 'success']) latest_message_list[0],
{'date': date_string, 'status': 'INFO', 'message': 'success'})
self.assertEquals(
latest_message_list[1],
{'date': date_string, 'status': 'ERROR',
'message': 'Promise is running...\nmessage in new line'})
def test_promise_resultfromlog_no_logfolder(self): def test_promise_resultfromlog_no_logfolder(self):
self.log_dir = None self.log_dir = None
...@@ -834,8 +843,12 @@ class TestSlapOSGenericPromise(TestSlapOSPromiseMixin): ...@@ -834,8 +843,12 @@ class TestSlapOSGenericPromise(TestSlapOSPromiseMixin):
latest_message_list = promise.getLastPromiseResultList(latest_minute=1) latest_message_list = promise.getLastPromiseResultList(latest_minute=1)
date_string = date.strftime('%Y-%m-%d %H:%M:%S') date_string = date.strftime('%Y-%m-%d %H:%M:%S')
self.assertEquals(len(latest_message_list), 2) self.assertEquals(len(latest_message_list), 2)
self.assertEquals(latest_message_list[0], [date_string, 'INFO', 'Promise is running...']) self.assertEquals(
self.assertEquals(latest_message_list[1], [date_string, 'INFO', 'success']) latest_message_list[0],
{'date': date_string, 'status': 'INFO', 'message': 'success'})
self.assertEquals(
latest_message_list[1],
{'date': date_string, 'status': 'INFO', 'message': 'Promise is running...'})
def test_promise_resultfromlog_older_log(self): def test_promise_resultfromlog_older_log(self):
self.initialisePromise() self.initialisePromise()
...@@ -857,8 +870,12 @@ class TestSlapOSGenericPromise(TestSlapOSPromiseMixin): ...@@ -857,8 +870,12 @@ class TestSlapOSGenericPromise(TestSlapOSPromiseMixin):
start_date_string = start_date.strftime('%Y-%m-%d %H:%M:%S') start_date_string = start_date.strftime('%Y-%m-%d %H:%M:%S')
end_date_string = (start_date - timedelta(minutes=9)).strftime('%Y-%m-%d %H:%M:%S') end_date_string = (start_date - timedelta(minutes=9)).strftime('%Y-%m-%d %H:%M:%S')
self.assertEquals(len(latest_message_list), 10) self.assertEquals(len(latest_message_list), 10)
self.assertEquals(latest_message_list[-1], [start_date_string, 'INFO', 'Promise result 49']) self.assertEquals(
self.assertEquals(latest_message_list[0], [end_date_string, 'INFO', 'Promise result 40']) latest_message_list[0],
{'date': start_date_string, 'status': 'INFO', 'message': 'Promise result 49'})
self.assertEquals(
latest_message_list[-1],
{'date': end_date_string, 'status': 'INFO', 'message': 'Promise result 40'})
def test_promise_resultfromlog_older_log_more(self): def test_promise_resultfromlog_older_log_more(self):
self.initialisePromise() self.initialisePromise()
...@@ -886,8 +903,12 @@ class TestSlapOSGenericPromise(TestSlapOSPromiseMixin): ...@@ -886,8 +903,12 @@ class TestSlapOSGenericPromise(TestSlapOSPromiseMixin):
end_date_string = (start_date - timedelta(seconds=30*19)).strftime('%Y-%m-%d %H:%M:%S') end_date_string = (start_date - timedelta(seconds=30*19)).strftime('%Y-%m-%d %H:%M:%S')
# there is 2 result line per minutes # there is 2 result line per minutes
self.assertEquals(len(latest_message_list), 20) self.assertEquals(len(latest_message_list), 20)
self.assertEquals(latest_message_list[-1], [start_date_string, 'INFO', 'Promise result 0']) self.assertEquals(
self.assertEquals(latest_message_list[0], [end_date_string, 'INFO', 'Promise result 19']) latest_message_list[0],
{'date': start_date_string, 'status': 'INFO', 'message': 'Promise result 0'})
self.assertEquals(
latest_message_list[-1],
{'date': end_date_string, 'status': 'INFO', 'message': 'Promise result 19'})
def test_promise_defaulttest(self): def test_promise_defaulttest(self):
promise_content = 'self.logger.info("Promise is running...\\nmessage in new line")' promise_content = 'self.logger.info("Promise is running...\\nmessage in new line")'
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment