From 2b58817324b6a7afa634422c95192f428bd70808 Mon Sep 17 00:00:00 2001
From: Benjamin Bertrand <benjamin.bertrand@esss.se>
Date: Thu, 9 May 2019 21:35:06 +0200
Subject: [PATCH] Fix IOC indexation

Regression from b9c1b83818525964268acfb9a804e8fce9fe18fb

Calling utils.trigger_ioc_repository_creation runs launch_task
which does a db.session.add(task). This raises:

SAWarning: Usage of the 'Session.add()' operation is not currently
supported within the execution stage of the flush process. Results may
not be consistent.  Consider using alternative event listeners or
connection-level operations instead.

SAWarning: Attribute history events accumulated on 1 previously clean
instances within inner-flush event handlers have been reset, and will
not result in database updates.

The result is that the host is not added to the elasticsearch index.

We can't trigger the task in after_update/after_insert events.
Perform the call in the view instead. It's temporary anyway. This should
be handled by IOC Factory.

JIRA INFRA-1015
---
 app/models.py        | 11 -----------
 app/network/views.py |  6 ++++++
 2 files changed, 6 insertions(+), 11 deletions(-)

diff --git a/app/models.py b/app/models.py
index 823f97e..166074e 100644
--- a/app/models.py
+++ b/app/models.py
@@ -1768,17 +1768,6 @@ def before_flush(session, flush_context, instances):
     trigger_inventory_update(session)
 
 
-@sa.event.listens_for(Host, "after_update")
-@sa.event.listens_for(Host, "after_insert")
-def after_host_insert_update(mapper, connection, host):
-    """Listen on Host after update/insert
-
-    Trigger repository creation in GitLab
-    """
-    if host.is_ioc:
-        utils.trigger_ioc_repository_creation(host)
-
-
 # call configure_mappers after defining all the models
 # required by sqlalchemy_continuum
 sa.orm.configure_mappers()
diff --git a/app/network/views.py b/app/network/views.py
index 8909f56..6b469f3 100644
--- a/app/network/views.py
+++ b/app/network/views.py
@@ -116,6 +116,9 @@ def create_host():
             flash(f"{e}", "error")
         else:
             flash(f"Host {host} created!", "success")
+            if host.is_ioc:
+                utils.trigger_ioc_repository_creation(host)
+                db.session.commit()
         # Save network_id and device_type_id to the session to retrieve them after the redirect
         session["network_id"] = network_id
         session["device_type_id"] = device_type_id
@@ -277,6 +280,9 @@ def edit_host(name):
             flash(f"{e}", "error")
         else:
             flash(f"Host {host} updated!", "success")
+            if host.is_ioc:
+                utils.trigger_ioc_repository_creation(host)
+                db.session.commit()
         return redirect(url_for("network.view_host", name=host.name))
     return render_template("network/edit_host.html", form=form)
 
-- 
GitLab