github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/acceptancetests/repository/charms/mediawiki/hooks/db-relation-changed (about) 1 #!/usr/bin/env python 2 # 3 # db-relation-changed - hook to configure mediawiki when db changes 4 # 5 # Copyright (C) 2011 Canonical Ltd. 6 # Author: Clint Byrum <clint.byrum@canonical.com> 7 # 8 # Copied and modified version of wordpress db-relation-changed by 9 # Kapil Thangavelu, also Copyright 2011 Canonical 10 # 11 # This program is free software: you can redistribute it and/or modify 12 # it under the terms of the GNU General Public License as published by 13 # the Free Software Foundation, either version 3 of the License, or 14 # (at your option) any later version. 15 # 16 # This program is distributed in the hope that it will be useful, 17 # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 # GNU General Public License for more details. 20 # 21 # You should have received a copy of the GNU General Public License 22 # along with this program. If not, see <http://www.gnu.org/licenses/>. 23 # 24 25 import os 26 import urllib 27 import subprocess 28 import tempfile 29 import json 30 import time 31 import MySQLdb 32 from subprocess import check_output, check_call 33 34 upload_path = "/var/www/wp-uploads" 35 config_file_path_template = "/etc/mediawiki/config-%s.php" 36 37 INSTALL_SCRIPT = '/usr/share/mediawiki/maintenance/install.php' 38 39 def do(*args): 40 print "do", args 41 p = subprocess.Popen(args, close_fds=True) 42 os.waitpid(p.pid, 0) 43 44 mediawiki_template = """\ 45 <?php 46 $path = array( $IP, "$IP/includes", "$IP/languages" ); 47 set_include_path( implode( PATH_SEPARATOR, $path ) . PATH_SEPARATOR . get_include_path() ); 48 49 require_once( "$IP/includes/DefaultSettings.php" ); 50 51 # If PHP's memory limit is very low, some operations may fail. 52 # ini_set( 'memory_limit', '20M' ); 53 54 if ( $wgCommandLineMode ) { 55 if ( isset( $_SERVER ) && array_key_exists( 'REQUEST_METHOD', $_SERVER ) ) { 56 die( "This script must be run from the command line\n" ); 57 } 58 } 59 ## Uncomment this to disable output compression 60 # $wgDisableOutputCompression = true; 61 62 ## The URL base path to the directory containing the wiki; 63 ## defaults for all runtime URL paths are based off of this. 64 ## For more information on customizing the URLs please see: 65 ## http://www.mediawiki.org/wiki/Manual:Short_URL 66 $wgScriptPath = "/mediawiki"; 67 $wgScriptExtension = ".php"; 68 69 include dirname(__FILE__).'/config-settings.php'; 70 71 ## UPO means: this is also a user preference option 72 73 $wgEnableEmail = true; 74 $wgEnableUserEmail = true; # UPO 75 76 $wgEmergencyContact = "webmaster@localhost"; 77 $wgPasswordSender = "webmaster@localhost"; 78 79 $wgEnotifUserTalk = true; # UPO 80 $wgEnotifWatchlist = true; # UPO 81 $wgEmailAuthentication = true; 82 83 ## Database settings 84 $wgDBtype = "mysql"; 85 $wgDBserver = "%(database_host)s"; 86 $wgDBname = "%(database)s"; 87 $wgDBuser = "%(database_user)s"; 88 $wgDBpassword = "%(database_password)s"; 89 include("/etc/mediawiki/dbservers.php"); 90 91 # MySQL specific settings 92 $wgDBprefix = ""; 93 94 # MySQL table options to use during installation or update 95 $wgDBTableOptions = "ENGINE=InnoDB, DEFAULT CHARSET=binary"; 96 97 # Experimental charset support for MySQL 4.1/5.0. 98 $wgDBmysql5 = true; 99 100 ## Shared memory settings 101 $wgMainCacheType = CACHE_NONE; 102 $wgMemCachedServers = array(); 103 include dirname(__FILE__).'/memcached_settings.php'; 104 105 ## To enable image uploads, make sure the 'images' directory 106 ## is writable, then set this to true: 107 $wgEnableUploads = false; 108 $wgUseImageMagick = true; 109 $wgImageMagickConvertCommand = "/usr/bin/convert"; 110 111 ## If you use ImageMagick (or any other shell command) on a 112 ## Linux server, this will need to be set to the name of an 113 ## available UTF-8 locale 114 $wgShellLocale = "en_US.utf8"; 115 116 ## If you want to use image uploads under safe mode, 117 ## create the directories images/archive, images/thumb and 118 ## images/temp, and make them all writable. Then uncomment 119 ## this, if it's not already uncommented: 120 # $wgHashedUploadDirectory = false; 121 122 ## If you have the appropriate support software installed 123 ## you can enable inline LaTeX equations: 124 $wgUseTeX = false; 125 126 $wgLocalInterwiki = strtolower( $wgSitename ); 127 128 $wgLanguageCode = "en"; 129 130 $wgSecretKey = "%(secret_key)s"; 131 132 ## Default skin: you can change the default skin. Use the internal symbolic 133 ## names, ie 'standard', 'nostalgia', 'cologneblue', 'monobook': 134 135 ## For attaching licensing metadata to pages, and displaying an 136 ## appropriate copyright notice / icon. GNU Free Documentation 137 ## License and Creative Commons licenses are supported so far. 138 # $wgEnableCreativeCommonsRdf = true; 139 $wgRightsPage = ""; # Set to the title of a wiki page that describes your license/copyright 140 $wgRightsUrl = ""; 141 $wgRightsText = ""; 142 $wgRightsIcon = ""; 143 # $wgRightsCode = ""; # Not yet used 144 145 $wgDiff3 = "/usr/bin/diff3"; 146 147 # debian specific include: 148 if (is_file("/etc/mediawiki-extensions/extensions.php")) { 149 include( "/etc/mediawiki-extensions/extensions.php" ); 150 } 151 152 # When you make changes to this configuration file, this will make 153 # sure that cached pages are cleared. 154 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', @filemtime( __FILE__ ) ) ); 155 """ 156 157 adminsettings_template = """ 158 <?php 159 $wgDBadminuser = '%(database_user)s'; 160 $wgDBadminpassword = '%(database_password)s'; 161 $wgEnableProfileInfo = false; 162 """ 163 164 def setup_mediawiki(): 165 166 remote_unit = os.environ.get("JUJU_REMOTE_UNIT") 167 168 print "remote unit", remote_unit 169 170 p = subprocess.Popen(["relation-get", "--format", "json"], 171 stdout=subprocess.PIPE, close_fds=True) 172 settings = json.loads(p.stdout.read().strip()) 173 if len(settings) == 0: 174 print "No settings yet, cannot configure." 175 return 176 177 print "Settings" 178 import pprint 179 pprint.pprint(settings) 180 181 # Get the database settings 182 database = settings.get("database") 183 password = settings.get("password") 184 user = settings.get("user") 185 private_address = settings.get("private-address") 186 187 # Generate this the same way the installer does 188 secret_key = open("/dev/urandom","r").read(32).encode('hex') 189 190 # Ensure the remote unit has self configured. 191 config = { 192 "database_host": private_address, 193 "database": database, 194 "database_password": password, 195 "database_user": user, 196 "secret_key": secret_key} 197 198 # Verify we have all of our database settings. 199 broken = False 200 for k, v in config.items(): 201 if not v: 202 print "Do not have for %r: %r" % (k, v) 203 broken = True 204 205 if broken: 206 print "Could not fetch database settings, exiting." 207 return 208 209 # Enable the Alias in the apache config 210 do("sed", "-i","s,^#Alias /mediawiki,Alias /mediawiki,","/etc/mediawiki/apache.conf") 211 212 # Restart apache 213 do("/etc/init.d/apache2", "reload") 214 215 # Replace "It Works" with redirector to wiki 216 ofile=tempfile.NamedTemporaryFile(dir="/var/www",delete=False) 217 os.chmod(ofile.name, 0755) 218 ofile.write("<?php header('Location: /mediawiki/');\n") 219 ofile.close() 220 try: 221 os.unlink("/var/www/index.php") 222 print "index.php removed" 223 except OSError: 224 print "index.php not present" 225 os.rename(ofile.name, "/var/www/index.php") 226 227 # This seems to take precedence 228 try: 229 os.unlink("/var/www/index.html") 230 print "index.html removed" 231 except OSError: 232 print "index.html not present" 233 234 # Write the adminsettings 235 connection = MySQLdb.connect(user=user, host=private_address, passwd=password, db=database) 236 cursor = connection.cursor() 237 do_install = None 238 try: 239 # Try to create the "mediawiki_juju_setup" table and if its already there, skip some things 240 cursor.execute("create table mediawiki_juju_setup (id int)") 241 do_install = True 242 except Exception as e: 243 # If we can't create that table, it has likely already been initialized 244 print 'Could not create mediawiki_juju_setup: ' + str(e) 245 do_install = False 246 if do_install: 247 # First time setup, we have to POST to the db and capture the LocalSettings.php 248 # This sysop is irrelevant, admins can be created by config settings. 249 try: 250 sysop = check_output(['pwgen','16']).strip() 251 sysop_password = check_output(['pwgen','16']).strip() 252 if os.path.exists(INSTALL_SCRIPT): 253 install_result = check_call(['php', 254 INSTALL_SCRIPT, 255 '--dbuser',user, 256 '--dbpass',password, 257 '--dbname',database, 258 '--installdbuser',user, 259 '--installdbpass',password, 260 '--confpath','/etc/mediawiki', 261 '--dbserver',private_address, 262 '--dbtype','mysql', 263 '--pass',sysop_password, 264 check_output(['config-get','name']).strip(), 265 sysop]) 266 else: 267 postargs = {'Sitename':'juju-d Wiki', 268 'EmergencyContact':'webmaster@localhost', 269 'LanguageCode':'en', 270 'License':'none', 271 'SysopName':sysop, 272 'SysopPass':sysop_password, 273 'SysopPass2':sysop_password, 274 'Shm':'none', 275 'Email':'email_enabled', 276 'Emailuser':'emailuser_enabled', 277 'Enotif':'enotif_disabled', 278 'Eauthent':'eauthent_enabled', 279 'DBtype':'mysql', 280 'DBserver':private_address, 281 'DBname':database, 282 'DBuser':user, 283 'DBpassword':password, 284 'DBpassword2':password, 285 } 286 try: 287 install = urllib.urlopen('http://localhost/mediawiki/config/index.php', urllib.urlencode(postargs)) 288 print "install URL returned ",install.getcode() 289 except Exception as e: 290 print "WARNING: could not post to installer!" 291 print e 292 raise Exception 293 except Exception, e: 294 print "Dropping mediawiki_juju_setup" 295 print e 296 try: 297 cursor.execute("drop table mediawiki_juju_setup") 298 except Exception, e: 299 print "Could not drop mediawiki_juju_setup" 300 print e 301 # Sadly, we really have to discard this LocalSettings.php and re-build 302 # it using the template, so that joins can just generate it without 303 # trying to create the whole DB. 304 #do("mv","/var/lib/mediawiki/config/LocalSettings.php","/etc/mediawiki/LocalSettings.php.generated") 305 306 # Write the mediawiki config - broken until dbservers.php is created 307 fh = open('/etc/mediawiki/LocalSettings.php', "w") 308 do("chmod", "0640", '/etc/mediawiki/LocalSettings.php') 309 do("chgrp", "www-data", '/etc/mediawiki/LocalSettings.php') 310 fh.write(mediawiki_template % config) 311 fh.close() 312 313 # Write the AdminSettings config for updates 314 fh = open('/etc/mediawiki/AdminSettings.php', "w") 315 do("chmod", "0640", '/etc/mediawiki/AdminSettings.php') 316 do("chgrp", "www-data", '/etc/mediawiki/AdminSettings.php') 317 fh.write(adminsettings_template % config) 318 fh.close() 319 320 # Refresh slave settings 321 scriptpath = os.path.join(os.path.dirname(os.path.abspath(__file__)),'combine-dbservers') 322 print "Running " + scriptpath 323 subprocess.check_call(scriptpath) 324 325 subprocess.check_call(['open-port','80']) 326 327 subprocess.check_call(['status-set', 'maintenance', 'Configuring Database']) 328 329 setup_mediawiki() 330 331 subprocess.check_call(['status-set', 'active', 'Ready'])