From f3da983b945f429d12f10e9a8bb1bd9b61f72f56 Mon Sep 17 00:00:00 2001
From: David Trattnig <david.trattnig@o94.at>
Date: Fri, 28 Aug 2020 14:36:40 +0200
Subject: [PATCH] Store health info. aura/engine#29

---
 src/models.py                               | 18 ++++++-----
 src/rest/controllers/internal_controller.py |  2 +-
 src/service.py                              | 34 ++++++++++-----------
 3 files changed, 28 insertions(+), 26 deletions(-)

diff --git a/src/models.py b/src/models.py
index 6612570..8b710f0 100644
--- a/src/models.py
+++ b/src/models.py
@@ -97,10 +97,11 @@ class PlayLog(db.Model):
             filter(PlayLog.track_start <= str(now)).\
             order_by(PlayLog.track_start.desc()).first()
         
-        if track.track_start + datetime.timedelta(0,track.track_duration) < now:
-            return None
-        else:
-            return track
+        if track:
+            if track.track_start + datetime.timedelta(0,track.track_duration) > now:
+                return track
+
+        return None
 
 
     @staticmethod
@@ -275,14 +276,14 @@ class HealthHistory(db.Model):
     log_source           = Column(Integer)          # The source the history entry relates to
     is_healthy           = Column(Boolean)          # Indicates if source is "healthy enough" to be used for play-out
     is_synced            = Column(Boolean)          # Only relevant for main nodes, in a multi-node setup
-    health_info          = Column(String(2048))     # Stringified JSON object or other, if needed
+    health_info          = Column(String(4096))     # Stringified JSON object or other, if needed
 
 
-    def __init__(self, source_number, is_healthy, health_info):
+    def __init__(self, source_number, log_time, is_healthy, health_info):
         """
         Initializes an health entry.
         """
-        self.log_time = datetime.datetime.now()
+        self.log_time = log_time
         self.log_source = source_number
         self.is_healthy = is_healthy
         self.is_synced = False
@@ -294,7 +295,8 @@ class HealthHistory(db.Model):
         """
         Retrieves the most recent health history entry for the given source number.
         """
-        return db.session.query(HealthHistory).filter(HealthHistory.log_source == source_number).first()
+        return db.session.query(HealthHistory).filter(HealthHistory.log_source == source_number).\
+            order_by(HealthHistory.log_time.desc()).first()
 
 
     def save(self):
diff --git a/src/rest/controllers/internal_controller.py b/src/rest/controllers/internal_controller.py
index dd4d30e..7e75443 100644
--- a/src/rest/controllers/internal_controller.py
+++ b/src/rest/controllers/internal_controller.py
@@ -124,7 +124,7 @@ def log_source_health(body, number):  # noqa: E501
     if connexion.request.is_json:
         body = HealthLog.from_dict(connexion.request.get_json())  # noqa: E501
     service = current_app.config['SERVICE']
-    service.log_source_health(number, body)
+    service.log_source_health(number, body, connexion.request.get_json())
 
 
 def set_active_source(number):  # noqa: E501
diff --git a/src/service.py b/src/service.py
index f99d0dc..bc65787 100644
--- a/src/service.py
+++ b/src/service.py
@@ -277,7 +277,7 @@ class ApiService():
         return health_schema.dump(health)
 
 
-    def log_source_health(self, source_number, data):
+    def log_source_health(self, source_number, data, plain_json):
         """
         Logs an health entry for the given source
 
@@ -286,34 +286,34 @@ class ApiService():
             data (Object): The data to store in the health log
 
         """
-        if not data.log_source:
-            data.log_source = self.host_id
-
-        if self.config.get("enable_federation") == "false":
-            return
+        if not source_number:
+            source_number = self.host_id
 
         # Main Node: Alway log entry, independed of the source
         # Sync Node: Only log entry when it's coming from an active source
         if self.node_type == NodeType.MAIN or \
-            (self.node_type == NodeType.SYNC and data.log_source == self.active_source):
+            (self.node_type == NodeType.SYNC and source_number == self.active_source):
 
-            healthlog = HealthHistory(data.log_source, data.is_healthy, data.health_info)
+            healthlog = HealthHistory(source_number, data.log_time, data.is_healthy, data.details)
             healthlog.save()
-            self.logger.debug("Stored health info for '%s'" % healthlog.log_source)
+            self.logger.debug("Stored health info for '%s'" % str(source_number))
+
+            if self.config.get("enable_federation") == "false":
+                return
 
             # Main Node: Push to Sync Node, if enabled
             if self.node_type == NodeType.MAIN and self.sync_host and self.api_healthlog:
 
-                health_schema = HealthHistorySchema()
-                json_healthlog = health_schema.dump(healthlog)
+                # health_schema = HealthHistorySchema()
+                # json_healthlog = health_schema.dump(healthlog)
+                api_url = self.sync_host + self.api_healthlog + "/" + str(source_number)
 
-                try:
-                    api_url = self.sync_host + api_healthlog + "/" + data.log_source
-                    r = requests.post(api_url, json=json_healthlog)
+                try:                    
+                    r = requests.post(api_url, json=plain_json)
                     if r.status_code == 200:
-                        self.logger.info("Successfully pushed healthlog for source '%s' to '%s'" % (healthlog.log_source, self.sync_host))
-                        playlog.is_synced = True
-                        playlog.save()
+                        self.logger.info("Successfully pushed healthlog for source '%s' to '%s'" % (str(source_number), self.sync_host))
+                        healthlog.is_synced = True
+                        healthlog.save()
                     else:
                         self.logger.error("Error while pushing healthlog to sync-node: " + str(r.json()))
                 except Exception as e:
-- 
GitLab