From d5ecb734746d57f1ed89731ba409a710b32bfa1e Mon Sep 17 00:00:00 2001
From: Jorrit Schaap <schaap@astron.nl>
Date: Tue, 28 Nov 2023 17:34:58 +0100
Subject: [PATCH] TMSS-2836: added little helper service to automatically
 create a new lofar2 sibling for each new blueprint

---
 SAS/TMSS/backend/services/CMakeLists.txt      |  1 +
 .../services/lofar2_siblings/CMakeLists.txt   |  4 +
 .../tmss_lofar2_sibling_service               | 84 +++++++++++++++++++
 3 files changed, 89 insertions(+)
 create mode 100644 SAS/TMSS/backend/services/lofar2_siblings/CMakeLists.txt
 create mode 100755 SAS/TMSS/backend/services/lofar2_siblings/tmss_lofar2_sibling_service

diff --git a/SAS/TMSS/backend/services/CMakeLists.txt b/SAS/TMSS/backend/services/CMakeLists.txt
index fcf450a17b3..1b2e6dd08f6 100644
--- a/SAS/TMSS/backend/services/CMakeLists.txt
+++ b/SAS/TMSS/backend/services/CMakeLists.txt
@@ -11,4 +11,5 @@ lofar_add_package(TMSSSlackWebhookService slack_webhook)
 lofar_add_package(TMSSWebSocketService websocket)
 lofar_add_package(TMSSWorkflowService workflow_service)
 lofar_add_package(TMSSReportRefreshService report_refresh)
+lofar_add_package(TMSSLofar2SiblingService lofar2_siblings)
 
diff --git a/SAS/TMSS/backend/services/lofar2_siblings/CMakeLists.txt b/SAS/TMSS/backend/services/lofar2_siblings/CMakeLists.txt
new file mode 100644
index 00000000000..f6cf877a67f
--- /dev/null
+++ b/SAS/TMSS/backend/services/lofar2_siblings/CMakeLists.txt
@@ -0,0 +1,4 @@
+lofar_package(TMSSLofar2SiblingService 0.1 DEPENDS TMSSClient PyCommon PyMessaging)
+
+lofar_add_bin_scripts(tmss_lofar2_sibling_service)
+
diff --git a/SAS/TMSS/backend/services/lofar2_siblings/tmss_lofar2_sibling_service b/SAS/TMSS/backend/services/lofar2_siblings/tmss_lofar2_sibling_service
new file mode 100755
index 00000000000..29ed75889d9
--- /dev/null
+++ b/SAS/TMSS/backend/services/lofar2_siblings/tmss_lofar2_sibling_service
@@ -0,0 +1,84 @@
+#!/usr/bin/env python3
+
+# Copyright (C) 2012-2015  ASTRON (Netherlands Institute for Radio Astronomy)
+# P.O. Box 2, 7990 AA Dwingeloo, The Netherlands
+#
+# This file is part of the LOFAR software suite.
+# The LOFAR software suite is free software: you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as published
+# by the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# The LOFAR software suite is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along
+# with the LOFAR software suite. If not, see <http://www.gnu.org/licenses/>.
+
+
+import os
+from optparse import OptionParser, OptionGroup
+import logging
+logger = logging.getLogger(__name__)
+
+from lofar.sas.tmss.client.tmssbuslistener import *
+from lofar.sas.tmss.client.tmss_http_rest_client import TMSSsession
+
+
+class TMSSLofar2SiblingEventMessageHandler(TMSSEventMessageHandler):
+    '''
+    '''
+    def __init__(self, tmss_client_credentials_id: str="TMSSClient"):
+        super().__init__()
+        self.tmss_client = TMSSsession.create_from_dbcreds_for_ldap(tmss_client_credentials_id)
+
+    def start_handling(self):
+        self.tmss_client.open()
+
+    def stop_handling(self):
+        self.tmss_client.close()
+
+    def onSchedulingUnitBlueprintCreated(self, id: int):
+        lofar2_unit = self.tmss_client.create_lofar2_sibling_scheduling_unit(id)
+        if lofar2_unit is not None:
+            logger.info("created lofar2 unit: %s", lofar2_unit['url'])
+
+
+def create_lofar2_sibling_service(exchange: str=DEFAULT_BUSNAME, broker: str=DEFAULT_BROKER, tmss_client_credentials_id: str="TMSSClient"):
+    return TMSSBusListener(handler_type=TMSSLofar2SiblingEventMessageHandler,
+                           handler_kwargs={'tmss_client_credentials_id': tmss_client_credentials_id},
+                           exchange=exchange, broker=broker)
+
+
+def main():
+    # make sure we run in UTC timezone
+    os.environ['TZ'] = 'UTC'
+    logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.INFO)
+
+    # Check the invocation arguments
+    parser = OptionParser('%prog [options]',
+                          description='run the tmss_lofar2_sibling_service which automatically creates a Lofar2 "sibling" scheduling unit for each newly created lofar1 scheduling unit blueprint')
+
+    group = OptionGroup(parser, 'Messaging options')
+    group.add_option('-b', '--broker', dest='broker', type='string', default=DEFAULT_BROKER, help='Address of the message broker, default: %default')
+    group.add_option('-e', "--exchange", dest="exchange", type="string", default=DEFAULT_BUSNAME, help="exchange where the TMSS event messages are published. [default: %default]")
+    parser.add_option_group(group)
+
+    group = OptionGroup(parser, 'Django options')
+    parser.add_option_group(group)
+    group.add_option('-R', '--tmss_client_credentials_id', dest='tmss_client_credentials_id', type='string', default='TMSSClient', help='TMSS django REST API credentials name, default: %default')
+
+    (options, args) = parser.parse_args()
+
+    # check TMSS is up and running via the client
+    TMSSsession.check_connection_and_exit_on_error(options.tmss_client_credentials_id)
+
+    from lofar.common.util import waitForInterrupt
+
+    with create_lofar2_sibling_service(options.exchange, options.broker, options.tmss_client_credentials_id):
+        waitForInterrupt()
+
+if __name__ == '__main__':
+    main()
-- 
GitLab