~gandelman-a/pyjuju/mysql

« back to all changes in this revision

Viewing changes to formulas/mediawiki/hooks/db-relation-changed

  • Committer: Francis J. Lacoste
  • Date: 2011-05-27 15:21:22 UTC
  • Revision ID: francis.lacoste@canonical.com-20110527152122-l8akt2g34hwz1zpj
Split out from principia-tools.

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
 
 
33
 
upload_path = "/var/www/wp-uploads"
34
 
config_file_path_template = "/etc/mediawiki/config-%s.php"
35
 
hostname_url = "http://169.254.169.254/latest/meta-data/public-hostname"
36
 
 
37
 
def do(*args):
38
 
    print "do", args
39
 
    p = subprocess.Popen(args, close_fds=True)
40
 
    os.waitpid(p.pid, 0)
41
 
 
42
 
mediawiki_template = """\
43
 
<?php
44
 
$path = array( $IP, "$IP/includes", "$IP/languages" );
45
 
set_include_path( implode( PATH_SEPARATOR, $path ) . PATH_SEPARATOR . get_include_path() );
46
 
 
47
 
require_once( "$IP/includes/DefaultSettings.php" );
48
 
 
49
 
# If PHP's memory limit is very low, some operations may fail.
50
 
# ini_set( 'memory_limit', '20M' );
51
 
 
52
 
if ( $wgCommandLineMode ) {
53
 
        if ( isset( $_SERVER ) && array_key_exists( 'REQUEST_METHOD', $_SERVER ) ) {
54
 
                die( "This script must be run from the command line\n" );
55
 
        }
56
 
}
57
 
## Uncomment this to disable output compression
58
 
# $wgDisableOutputCompression = true;
59
 
 
60
 
$wgSitename         = "Ensemblized Wiki";
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
 
## UPO means: this is also a user preference option
70
 
 
71
 
$wgEnableEmail      = true;
72
 
$wgEnableUserEmail  = true; # UPO
73
 
 
74
 
$wgEmergencyContact = "webmaster@localhost";
75
 
$wgPasswordSender = "webmaster@localhost";
76
 
 
77
 
$wgEnotifUserTalk = true; # UPO
78
 
$wgEnotifWatchlist = true; # UPO
79
 
$wgEmailAuthentication = true;
80
 
 
81
 
## Database settings
82
 
$wgDBtype           = "mysql";
83
 
$wgDBserver         = "%(database_host)s";
84
 
$wgDBname           = "%(database)s";
85
 
$wgDBuser           = "%(database_user)s";
86
 
$wgDBpassword       = "%(database_password)s";
87
 
include("/etc/mediawiki/dbservers.php");
88
 
 
89
 
# MySQL specific settings
90
 
$wgDBprefix         = "";
91
 
 
92
 
# MySQL table options to use during installation or update
93
 
$wgDBTableOptions   = "ENGINE=InnoDB, DEFAULT CHARSET=binary";
94
 
 
95
 
# Experimental charset support for MySQL 4.1/5.0.
96
 
$wgDBmysql5 = true;
97
 
 
98
 
## Shared memory settings
99
 
$wgMainCacheType = CACHE_NONE;
100
 
$wgMemCachedServers = array();
101
 
include dirname(__FILE__).'/memcached_settings.php';
102
 
 
103
 
## To enable image uploads, make sure the 'images' directory
104
 
## is writable, then set this to true:
105
 
$wgEnableUploads       = false;
106
 
$wgUseImageMagick = true;
107
 
$wgImageMagickConvertCommand = "/usr/bin/convert";
108
 
 
109
 
## If you use ImageMagick (or any other shell command) on a
110
 
## Linux server, this will need to be set to the name of an
111
 
## available UTF-8 locale
112
 
$wgShellLocale = "en_US.utf8";
113
 
 
114
 
## If you want to use image uploads under safe mode,
115
 
## create the directories images/archive, images/thumb and
116
 
## images/temp, and make them all writable. Then uncomment
117
 
## this, if it's not already uncommented:
118
 
# $wgHashedUploadDirectory = false;
119
 
 
120
 
## If you have the appropriate support software installed
121
 
## you can enable inline LaTeX equations:
122
 
$wgUseTeX           = false;
123
 
 
124
 
$wgLocalInterwiki   = strtolower( $wgSitename );
125
 
 
126
 
$wgLanguageCode = "en";
127
 
 
128
 
$wgSecretKey = "%(secret_key)s";
129
 
 
130
 
## Default skin: you can change the default skin. Use the internal symbolic
131
 
## names, ie 'standard', 'nostalgia', 'cologneblue', 'monobook':
132
 
$wgDefaultSkin = 'monobook';
133
 
 
134
 
## For attaching licensing metadata to pages, and displaying an
135
 
## appropriate copyright notice / icon. GNU Free Documentation
136
 
## License and Creative Commons licenses are supported so far.
137
 
# $wgEnableCreativeCommonsRdf = true;
138
 
$wgRightsPage = ""; # Set to the title of a wiki page that describes your license/copyright
139
 
$wgRightsUrl = "";
140
 
$wgRightsText = "";
141
 
$wgRightsIcon = "";
142
 
# $wgRightsCode = ""; # Not yet used
143
 
 
144
 
$wgDiff3 = "/usr/bin/diff3";
145
 
 
146
 
# debian specific include:
147
 
if (is_file("/etc/mediawiki-extensions/extensions.php")) {
148
 
        include( "/etc/mediawiki-extensions/extensions.php" );
149
 
}
150
 
 
151
 
# When you make changes to this configuration file, this will make
152
 
# sure that cached pages are cleared.
153
 
$wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', @filemtime( __FILE__ ) ) );
154
 
"""
155
 
 
156
 
adminsettings_template = """
157
 
<?php
158
 
$wgDBadminuser = '%(database_user)s';
159
 
$wgDBadminpassword = '%(database_password)s';
160
 
$wgEnableProfileInfo = false;
161
 
"""
162
 
 
163
 
def setup_mediawiki():
164
 
 
165
 
    try:
166
 
        hostname = urllib.urlopen(hostname_url).read().strip()
167
 
    except:
168
 
        hostname = 'localhost'
169
 
    remote_unit = os.environ.get("ENSEMBLE_REMOTE_UNIT")
170
 
 
171
 
    print "remote unit", remote_unit
172
 
 
173
 
    # Check we haven't already been setup.
174
 
    #if os.path.exists(config_file_path_template % hostname):
175
 
    #    print "Already Configured, Exiting"
176
 
    #    return
177
 
 
178
 
    p = subprocess.Popen(["relation-get", "--format", "json"],
179
 
                         stdout=subprocess.PIPE, close_fds=True)
180
 
    settings = json.loads(p.stdout.read().strip())
181
 
    if len(settings) == 0:
182
 
        print "No settings yet, cannot configure."
183
 
        return
184
 
 
185
 
    print "Settings"
186
 
    import pprint
187
 
    pprint.pprint(settings)
188
 
 
189
 
    # Get the database settings
190
 
    database = settings.get("database")
191
 
    password = settings.get("password")
192
 
    user = settings.get("user")
193
 
    host = settings.get("host")
194
 
 
195
 
    # Generate this the same way the installer does
196
 
    secret_key = open("/dev/urandom","r").read(32).encode('hex')
197
 
 
198
 
    # Ensure the remote unit has self configured.
199
 
    config = {
200
 
        "database_host": host,
201
 
        "database": database,
202
 
        "database_password": password,
203
 
        "database_user": user,
204
 
        "hostname": hostname,
205
 
        "secret_key": secret_key}
206
 
 
207
 
    # Verify we have all of our database settings.
208
 
    broken = False
209
 
    for k, v in config.items():
210
 
        if not v:
211
 
            print "Do not have for %r: %r" % (k, v)
212
 
            broken = True
213
 
 
214
 
    if broken:
215
 
        print "Could not fetch database settings, exiting."
216
 
        return
217
 
 
218
 
    # Enable the Alias in the apache config
219
 
    do("sed", "-ie","s,^#Alias /mediawiki,Alias /mediawiki,","/etc/mediawiki/apache.conf")
220
 
 
221
 
    # Restart apache
222
 
    do("/etc/init.d/apache2", "reload")
223
 
 
224
 
    # Replace "It Works" with redirector to wiki
225
 
    ofile=tempfile.NamedTemporaryFile(dir="/var/www",delete=False)
226
 
    os.chmod(ofile.name, 0755)
227
 
    ofile.write("<?php header('Location: /mediawiki/');\n")
228
 
    ofile.close()
229
 
    try:
230
 
        os.unlink("/var/www/index.php")
231
 
        print "index.php removed"
232
 
    except OSError:
233
 
        print "index.php not present"
234
 
    os.rename(ofile.name, "/var/www/index.php")
235
 
 
236
 
    # This seems to take precedence
237
 
    try:
238
 
        os.unlink("/var/www/index.html")
239
 
        print "index.html removed"
240
 
    except OSError:
241
 
        print "index.html not present"
242
 
 
243
 
    # Write the adminsettings
244
 
    connection = MySQLdb.connect(user=user, host=host, passwd=password, db=database)
245
 
    cursor = connection.cursor()
246
 
    do_install = None
247
 
    try:
248
 
      # Try to create the "mediawiki_ensemble_setup" table and if its already there, skip some things
249
 
      cursor.execute("create table mediawiki_ensemble_setup (id int)")
250
 
      do_install = True
251
 
    except Exception as e:
252
 
      # If we can't create that table, it has likely already been initialized
253
 
      print 'Could not create mediawiki_ensemble_setup: ' + str(e)
254
 
      do_install = False
255
 
    if do_install:
256
 
      # First time setup, we have to POST to the db and capture the LocalSettings.php
257
 
      postargs = {'Sitename':'Ensemblized Wiki',
258
 
        'EmergencyContact':'webmaster@localhost',
259
 
        'LanguageCode':'en',
260
 
        'License':'none',
261
 
        'SysopName':'WikiSysop',
262
 
        'SysopPass':'change-me',
263
 
        'SysopPass2':'change-me',
264
 
        'Shm':'none',
265
 
        'Email':'email_enabled',
266
 
        'Emailuser':'emailuser_enabled',
267
 
        'Enotif':'enotif_disabled',
268
 
        'Eauthent':'eauthent_enabled',
269
 
        'DBtype':'mysql',
270
 
        'DBserver':host,
271
 
        'DBname':database,
272
 
        'DBuser':user,
273
 
        'DBpassword':password,
274
 
        'DBpassword2':password,
275
 
      }
276
 
      try:
277
 
        install = urllib.urlopen('http://localhost/mediawiki/config/index.php', urllib.urlencode(postargs))
278
 
        print "install URL returned ",install.getcode()
279
 
      except Exception as e:
280
 
        print "WARNING: could not post to installer!"
281
 
        print e
282
 
      # Sadly, we really have to discard this LocalSettings.php and re-build
283
 
      # it using the template, so that joins can just generate it without
284
 
      # trying to create the whole DB.
285
 
      #do("mv","/var/lib/mediawiki/config/LocalSettings.php","/etc/mediawiki/LocalSettings.php.generated")
286
 
 
287
 
    # Write the mediawiki config - broken until dbservers.php is created
288
 
    fh = open('/etc/mediawiki/LocalSettings.php', "w")
289
 
    do("chmod", "0644", '/etc/mediawiki/LocalSettings.php')
290
 
    fh.write(mediawiki_template % config)
291
 
    fh.close()
292
 
 
293
 
    # Write the AdminSettings config for updates
294
 
    fh = open('/etc/mediawiki/AdminSettings.php', "w")
295
 
    do("chmod", "0644", '/etc/mediawiki/AdminSettings.php')
296
 
    fh.write(adminsettings_template % config)
297
 
    fh.close()
298
 
 
299
 
    # Refresh slave settings
300
 
    scriptpath = os.dirname(__file__)
301
 
    subprocess.check_call(os.path.join([scriptpath,'combine-dbservers']))
302
 
 
303
 
setup_mediawiki()