From 1275a63ac65ee91056c7fbe8a6bc05dcec6cb317 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Diemer?= <stephane.diemer@ubicast.eu>
Date: Wed, 21 Jun 2017 18:00:23 +0200
Subject: [PATCH] Continued script to set domain (refs #21163).

---
 set_app_domain.py | 89 ++++++++++++++++++++++++++++++++++-------------
 1 file changed, 65 insertions(+), 24 deletions(-)

diff --git a/set_app_domain.py b/set_app_domain.py
index 7c2fbc43..342b3391 100755
--- a/set_app_domain.py
+++ b/set_app_domain.py
@@ -64,13 +64,14 @@ class SetAppDomain():
             sys.exit(1)
         if args:
             app = args.pop()
-        # Change domain
+        # Get Nginx conf path and instance user
         instance = None
         if app == 'cm':
             nginx_conf = '/etc/nginx/sites-available/skyreach.conf'
-            self.change_cm_domain(new_domain)
+            key = 'CM_SERVER_NAME'
         elif app == 'mon':
             nginx_conf = '/etc/nginx/sites-available/msmonitor.conf'
+            key = 'MONITOR_SERVER_NAME'
         elif app == 'ms' or app.startswith('ms-'):
             if app.startswith('ms-'):
                 instance = app[3:].strip('. -\t\n')
@@ -80,13 +81,25 @@ class SetAppDomain():
             else:
                 instance = 'msuser'
             nginx_conf = '/etc/nginx/sites-available/mediaserver-%s.conf' % instance
-            self.change_ms_domain(new_domain, instance)
+            key = 'MS_SERVER_NAME'
         else:
             log('Invalid app name requested.')
             log(self.USAGE)
             sys.exit(1)
+        # Change domain
         self.change_nginx_domain(nginx_conf, new_domain)
         self.change_hosts_file(new_domain)
+        self.change_envsetup_conf(key, new_domain)
+        if app == 'cm':
+            warning = self.change_cm_domain(new_domain)
+        elif app == 'mon':
+            warning = None
+        else:
+            warning = self.change_ms_domain(new_domain, instance)
+        log('\033[92mDone\033[0m')
+        if warning:
+            log('\033[93mWarning:\033[0m')
+            log(warning)
         sys.exit(0)
 
     def change_nginx_domain(self, path, new_domain):
@@ -100,10 +113,9 @@ class SetAppDomain():
         changed_lines = 0
         for line in vhost.split('\n'):
             if re.match(r'\s*server_name\s+([\w\-\_\.\ ]+);', line):
-                new_vhost += re.sub(r'server_name\s+([\w\-\_\.\ ]+);', line, 'server_name %s;' % new_domain) + '\n'
+                line = re.sub(r'server_name\s+([\w\-\_\.\ ]+);', 'server_name %s;' % new_domain, line)
                 changed_lines += 1
-            else:
-                new_vhost += line + '\n'
+            new_vhost += line + '\n'
         if changed_lines != 2:
             log('Warning the number of server_name occurence changed in Nginx configuration is not the expected number (2) but is %s.' % changed_lines)
             if not self.force:
@@ -128,6 +140,7 @@ class SetAppDomain():
     def change_hosts_file(self, new_domain):
         with open('/etc/hosts', 'r') as fo:
             hosts = fo.read()
+        ori_hosts = hosts
         if ' ' + new_domain in hosts:
             hosts = hosts.replace(' ' + new_domain, '')
         elif '\t' + new_domain in hosts:
@@ -138,17 +151,39 @@ class SetAppDomain():
             new_hosts += '\n' + line
             if line.startswith('127.0.0.1'):
                 new_hosts += ' ' + new_domain
-        if new_hosts != hosts:
+        if new_hosts != ori_hosts:
             if self.debug:
                 log('New hosts:')
                 log(new_hosts)
             else:
                 with open('/etc/hosts', 'w') as fo:
                     fo.write(new_hosts)
-                log('The hosts file has been update.')
+                log('The "/etc/hosts" file has been update.')
                 utils.run_commands(['service nscd restart'])
         else:
-            log('The hosts file is already up to date.')
+            log('The "/etc/hosts" file is already up to date.')
+
+    def change_envsetup_conf(self, key, new_domain):
+        confs = (
+            'conf.sh',
+            'auto-generated-conf.sh',
+        )
+        replaced = False
+        for path in confs:
+            if os.path.exists(path):
+                with open(path, 'r') as fo:
+                    content = fo.read()
+                if key in content:
+                    content = re.sub(r'%s=.*' % key, '%s=\'%s\'' % (key, new_domain), content)
+                    with open(path, 'w') as fo:
+                        fo.write(content)
+                    replaced = True
+                    log('Envsetup configration file "%s" updated.' % path)
+                    break
+        if not replaced:
+            with open(confs[0], 'a') as fo:
+                fo.write('\n%s=\'%s\'' % (key, new_domain))
+            log('Envsetup configration file "%s" updated.' % confs[0])
 
     def change_ms_domain(self, new_domain, instance):
         try:
@@ -158,24 +193,29 @@ class SetAppDomain():
             log('Assuming that the new url is using HTTPS: "%s"' % new_url)
             cmds = [
                 # set site url in site settings
-                'python3', os.path.join(ms_path, 'scripts', 'mssiteconfig.py'), instance, 'site_url="%s"' % new_url,
+                'python3 %s %s site_url="%s"' % (os.path.join(ms_path, 'scripts', 'mssiteconfig.py'), instance, new_url),
                 # reset all local resources managers
-                'python3', os.path.join(ms_path, 'scripts', 'reset_service_resources.py'), instance, 'local',
-                # change configuration of worker on MS side
-                'sed -i "s@\'url\': \'\\(http[s]*\\)://.*\'@\'url\': \'\\1://%s\'@" /etc/celerity/config.py' % new_domain,
+                'python3 %s %s local' % (os.path.join(ms_path, 'scripts', 'reset_service_resources.py'), instance),
+                # change configuration of celerity on MS side
+                'sed -i "s@\'url\': \'\\(http[s]*\\)://.*\',@\'url\': \'\\1://%s\',@" /etc/celerity/config.py' % new_domain,
+                'sed -i "s@SERVER_URL.*@SERVER_URL = \'%s:6200\'@" /etc/celerity/config.py' % new_url,
+                # restart ms
+                'mscontroller.py restart -u %s' % instance,
             ]
             worker_ips = utils.get_conf('CELERITY_WORKER_IP') or '127.0.1.1'
-            # change configuration of worker on worker side
+            # change configuration of celerity on worker side
             for worker_ip in worker_ips.split(','):
-                cmds.append('ssh root@%s sed -i "s@\'url\': \'\\(http[s]*\\)://.*\'@\'url\': \'\\1://%s\'@" /etc/celerity/config.py' % (worker_ip, new_domain))
+                cmds.append('rsync -avz /etc/celerity/config.py root@%s:/etc/celerity/config.py' % worker_ip)
+                cmds.append('ssh root@%s service celerity-workers restart' % worker_ip)
             utils.run_commands(cmds)
         except Exception as e:
-            log('Unable to set MS domain:\n%s' % e)
+            log('Unable to set domain in MS database and Celerity config:\n%s' % e)
             sys.exit(1)
         else:
-            log('MS domain changed')
-        log('Some steps to change the domain should be done manually:')
-        log('  - Change the domain of MS used in CM stations configuration.')
+            log('Domain changed in MS database and Celerity config.')
+        msg = 'Some steps to change the domain should be done manually:'
+        msg += '\n  - Change the domain of MS used in CM stations configuration.'
+        return msg
 
     def change_cm_domain(self, new_domain):
         try:
@@ -183,16 +223,17 @@ class SetAppDomain():
             log('Assuming that the new url is using HTTPS: "%s"' % new_url)
             cmds = [
                 # set site url in site settings
-                'echo \'from skyreach_site.base.models import SiteSettings; ss = SiteSettings.get_singleton(); ss.url = "%s"; ss.save(); print("site settings saved")\' | su skyreach -c "python3 /home/skyreach/htdocs/skyreach_site/manage.py shell --plain --no-startup"' % new_url,
+                'echo \'from skyreach_site.base.models import SiteSettings; ss = SiteSettings.get_singleton(); ss.url = "%s"; ss.save(); print("Site settings saved.")\' | su skyreach -c "python3 /home/skyreach/htdocs/skyreach_site/manage.py shell --plain --no-startup"' % new_url,
             ]
             utils.run_commands(cmds)
         except Exception as e:
-            log('Unable to set CM domain:\n%s' % e)
+            log('Unable to set domain in CM database:\n%s' % e)
             sys.exit(1)
         else:
-            log('CM domain changed')
-        log('Some steps to change the domain should be done manually:')
-        log('  - Change the url of CM in the related MS.')
+            log('Domain changed in CM database.')
+        msg = 'Some steps to change the domain should be done manually:'
+        msg += '\n  - Change the url of CM in the related MS.'
+        return msg
 
 
 if __name__ == '__main__':
-- 
GitLab