]> scripts.mit.edu Git - wizard.git/blob - doc/create.rst
Change to production directory before running certain commands.
[wizard.git] / doc / create.rst
1 Creating a repository
2 =====================
3
4 :Author: Edward Z. Yang <ezyang@mit.edu>
5
6 .. highlight:: sh
7
8 Adding Wizard support for a web application requires some glue code
9 and a specially prepared repository.  Creating a new repository for an
10 application in Wizard involves placing :term:`pristine` versions of the source
11 code (from the upstream tarballs) and appropriately patched scripts versions
12 into a Git repository, as well as writing a :mod:`wizard.app` module for the
13 application that implements application specific logic, such as how to install,
14 upgrade or backup the installation.
15
16 Here is a tutorial for creating such a repository, using an old version of
17 Wordpress as an example.  We will implement only the functions necessary for
18 installing an application--upgrades and backups are not described here.
19 We assume that you have a working setup of Wizard; consult the
20 :doc:`setup documentation <setup>` for more details.
21
22 From this point on, we will assume you are doing development from an AFS directory
23 named ``$WIZARD``; note that application repositories live in ``$WIZARD/srv``.
24
25 .. supplement:: Conversions
26
27     One of Wizard's goals is to replace the previous autoinstaller
28     infrastructure.  These boxes will explain extra steps that you must perform
29     in order to carry out a conversion of old-style autoinstalls to a Wizard
30     autoinstall.  In brief, pre-wizard autoinstalls live in
31     :file:`/mit/scripts/deploy` and consist of a tarball from upstream,
32     possibly a scripts patch, and possibly some post-install munging (such as
33     the creation of a :file:`php.ini` file and appropriate symlinks).
34     Performing a conversion means that we will recreate these changes in our
35     Wizard autoinstall, and you will start you repository with the *earliest*
36     version of the application extant on our servers.
37
38 Pristine
39 --------
40
41 This is a tutorial centered around creating a `Wordpress <http://wordpress.org/>`_
42 repository.  For the sake of demonstration,
43 we shall assume that this repository hasn't been created yet.
44 The repository then doesn't exist, we should create it::
45
46     cd "$WIZARD/srv"
47     mkdir wordpress
48     cd wordpress
49     git init
50
51 We also have to create a module for the application, so we
52 create :file:`$WIZARD/wizard/app/wordpress.py` and fill it in with a bare bones template:
53
54 .. code-block:: python
55
56     import os
57     import re
58     import logging
59     import distutils
60
61     from wizard import app, install, resolve, sql, util
62     from wizard.app import php
63
64     class Application(app.Application):
65         pass
66
67 Now we are ready to put some code in our repository: the first thing we will
68 add is the :term:`pristine` branch, which contains verbatim the code from upstream.
69
70 .. supplement:: Conversions
71
72     If we were starting a new autoinstaller, we'd pop off and use the latest version,
73     but since we're dealing with legacy we want to start our repository history
74     with the *oldest* version still extant on our servers.  To find this out run::
75
76         wizard summary version APP
77
78     You'll need to be in the ``scripts-team`` list to have access rights to the
79     folder we store this information in: :file:`/mit/scripts/sec-tools/store/versions`.
80
81 For the purposes of demonstration, we'll use Wordpress 2.0.2; in reality you
82 should use the latest version.  Try running the following commands::
83
84     cd "$WIZARD/srv/wordpress"
85     wizard prepare-pristine wordpress-2.0.2
86
87 You should get an error complaining about :meth:`wizard.app.Application.download`
88 not being implemented yet. Let's fix that:
89
90 .. code-block:: python
91
92     class Application(app.Application):
93         # ...
94         def download(self, version):
95             return "http://wordpress.org/wordpress-%s.tar.gz" % version
96
97 We determined this by finding `Wordpress's Release Archive <http://wordpress.org/download/release-archive/>`_
98 and inferring the naming scheme by inspecting various links.  You should now
99 be able to run the prepare-pristine command successfully: when it is
100 done, you'll now have a bunch of files in your repository, and they
101 will be ready to be committed.  Inspect the files and commit (note that the
102 format of the commit message is a plain Appname Version.Number)::
103
104     git status
105     git commit -asm "Wordpress 2.0.2"
106     git tag wordpress-2.0.2
107
108 .. note::
109
110     Sometimes, ``http://wordpress.org/wordpress-2.0.2.tar.gz`` won't
111     actually exist anymore (it didn't exist when we did it).  In this case,
112     you'll probably be able to find the original tarball in
113     :file:`/mit/scripts/deploy/wordpress-2.0.2`, and you can feed it
114     manually to prepare pristine with
115     ``wizard prepare-pristine /mit/scripts/deploy/wordpress-2.0.2/wordpress-2.0.2.tar.gz``
116
117 Some last house-keeping bits:  now that you have a commit in a repository, you
118 can also create a pristine branch::
119
120     git branch pristine
121
122 Scriptsify
123 ----------
124
125 In a perfect world, the pristine version would be equivalent to the scriptsified
126 version that would actually get deployed.  However, we have historically needed
127 to apply patches and add extra configuration files to get applications to
128 work correctly.  Due to the way Git's merge algorithm works, the closer we are
129 able to reconstruct a version of the application that was actually used, the
130 better off we will be when we try to subsequently upgrade those applications.
131
132 First things first: verify that we are on the master branch::
133
134     git checkout master
135
136 .. supplement:: Conversions
137
138     Check for pre-existing patches in the old application directory,
139     :file:`/mit/scripts/deploy/wordpress-2.0.2` in the case of Wordpress,
140     and apply them::
141
142         patch -n0 < /mit/scripts/deploy/wordpress-2.0.2/wordpress.patch
143
144 If you are running a PHP application, you'll need to setup
145 a :file:`php.ini` and symlinks to it in all subdirectories.
146 As of November 2009, all PHP applications load the same :file:`php.ini` file;
147 so just grab one from another of the PHP projects.  We'll rob our own
148 crib in this case::
149
150     cp /mit/scripts/deploy/php.ini/wordpress php.ini
151     athrun scripts fix-php-ini
152     git add .
153
154 Now commit, but don't get too attached to your commit; we're going
155 to be heavily modifying it soon::
156
157     git commit -asm "Wordpress 2.0.2-scripts"
158
159 Installation
160 ------------
161
162 We now need to make it possible for a user to install the application.
163 The :meth:`~wizard.install.Application.install` method should take the
164 application from a just cloned working copy into a fully functioning web
165 application with configuration and a working database, etc.  Most web
166 applications have a number of web scripts for generating a configuration
167 file, so creating the install script tend to involve:
168
169
170     1. Deleting any placeholder files that were in the repository (there
171        aren't any now, but there will be soon.)
172
173     2. Determining what input values you will need from the user, such
174        as a title for the new application or database credentials; more
175        on this shortly.
176
177     3. Determining what POST values need to be sent to what URLs or to
178        what shell scripts (these are the install scripts the application
179        may have supplied to you.)
180
181 .. supplement:: Conversions
182
183     Since you're converting a repository, this job is even simpler: you
184     just need to port the Perl script that was originally used into
185     Python.
186
187 There's an in-depth explanation of named input values in
188 :mod:`wizard.install`.  The short version is that your application
189 contains a class-wide :data:`~wizard.app.Application.install_schema`
190 attribute that encodes this information.  Instantiate it with
191 :class:`wizard.install.ArgSchema` (passing in arguments to get
192 some pre-canned input values), and then add application specific
193 arguments by passing instances of :class:`wizard.install.Arg`
194 to the method :meth:`~wizard.install.ArgSchema.add`.  Usually you should
195 be able to get away with pre-canned attributes.  You can access
196 these arguments inside :meth:`~wizard.app.Application.install` via
197 the ``options`` value.
198
199 In particular, ``options.dsn`` is a :class:`sqlalchemy.engine.url.URL`
200 which contains member variables such as :meth:`~sqlalchemy.engine.url.URL.username`,
201 :meth:`~sqlalchemy.engine.url.URL.password`, :meth:`~sqlalchemy.engine.url.URL.host` and
202 :meth:`~sqlalchemy.engine.url.URL.database` which you can use to pass in POST.
203
204 Some tips and tricks for writing :meth:`wizard.app.Application.install`:
205
206     * Some configuration file generators will get unhappy if the
207       target directory is not chmod'ed to be writable; dropping
208       in a ``os.chmod(dir, 0777)`` and then undoing the chmod
209       when you're done is a decent workaround.
210
211     * :func:`wizard.install.fetch` is the standard workhorse for making
212       requests to applications.  It accepts three parameters; the first
213       is ``options`` (which was the third argument to ``install`` itself),
214       the second is the page to query, relative to the installation's
215       web root, and ``post`` is a dictionary of keys to values to POST.
216
217     * You should log any web page output using :func:`logging.debug`.
218
219     * If you need to manually manipulate the database afterwards, you
220       can use :func:`wizard.sql.connect` (passing it ``options.dsn``)
221       to get a `SQLAlchemy metadata object
222       <http://www.sqlalchemy.org/docs/05/sqlexpression.html>`_, which can
223       consequently be queried.  For convenience, we've bound metadata
224       to the connection, you can perform implicit execution.
225
226 To test if your installation function works, it's probably convenient to
227 create a test script in :file:`tests`; :file:`tests/test-install-wordpress.sh`
228 in the case of Wordpress.  It will look something like::
229
230     #!/bin/bash -e
231
232     DEFAULT_HEAD=1
233     TESTNAME="install_wordpress"
234     source ./setup
235
236     wizard install "wordpress-$VERSION-scripts" "$TESTDIR" --non-interactive -- --title="My Blog"
237
238 ``DEFAULT_HEAD=1`` indicates that this script can perform a reasonable
239 operation without any version specified (since we haven't tagged any of our
240 commits yet, we can't use the specific version functionality; not that we'd want
241 to, though).  ``TESTNAME`` is simply the name of the file with the leading
242 ``test-`` stripped and dashes converted to underscores.  Run the script with
243 verbose debugging information by using::
244
245     env WIZARD_DEBUG=1 ./test-install-wordpress.sh
246
247 The test scripts will try to conserve databases by running ``wizard remove`` on the
248 old directory, but this requires :meth:`~wizard.app.remove` be implemented.
249 Most of the time (namely, for single database setups), this simple template will suffice:
250
251 .. code-block:: python
252
253     class Application(app.Application):
254         # ...
255         def remove(self, deployment)
256             app.remove_database(deployment)
257
258 Versioning config
259 -----------------
260
261 A design decision that was made early on during Wizard's development was that
262 the scriptsified versions would contain generic copies of the configuration
263 files.  You're going to generate this generic copy now and in doing so,
264 overload your previous scripts commit.   Because some installers
265 exhibit different behavior depending on server configuration, you should run
266 the installation on a Scripts server.  You can do this manually or use
267 the test script you created::
268
269     env WIZARD_NO_COMMIT=1 ./test-install-wordpress.sh
270
271 :envvar:`WIZARD_NO_COMMIT` (command line equivalent to ``--no-commit``)
272 prevents the installer from generating a Git commit after the install, and will
273 make it easier for us to propagate the change back to the parent repository.
274
275 Change into the generated directory and look at the changes the installer made::
276
277     git status
278
279 There are probably now a few unversioned files lounging around; these are probably
280 the configuration files that the installer generated.
281
282 You will now need to implement the following data attributes and methods in your
283 :class:`~wizard.app.Application` class: :attr:`~wizard.app.Application.extractors`,
284 :attr:`~wizard.app.Application.substitutions`, :attr:`~wizard.app.Application.parametrized_files`,
285 :meth:`~wizard.app.Application.checkConfig` and :meth:`~wizard.app.Application.detectVersion`.
286 These are all closely related to the configuration files that the installer generated.
287
288 :meth:`~wizard.app.Application.checkConfig` is the most straightforward method to
289 write: you will usually only need to test for the existence of the configuration file.
290 Note that this function will always be called with the current working directory being
291 the deployment, so you can simplify your code accordingly:
292
293 .. code-block:: python
294
295     class Application(app.Application):
296         # ...
297         def checkConfig(self, deployment):
298             return os.path.isfile("wp-config.php")
299
300 :meth:`~wizard.app.Application.detectVersion` should detect the version of the application
301 by regexing it out of a source file.  We first have to figure out where the version number
302 is stored: a quick grep tells us that it's in :file:`wp-includes/version.php`:
303
304 .. code-block:: php
305
306     <?php
307
308     // This just holds the version number, in a separate file so we can bump it without cluttering the SVN
309
310     $wp_version = '2.0.4';
311     $wp_db_version = 3440;
312
313     ?>
314
315 We could now grab the :mod:`re` module and start constructing a regex to grab ``2.0.4``, but it
316 turns out this isn't necessary: :meth:`wizard.app.php.re_var` does this for us already!
317
318 With this function in hand, writing a version detection function is pretty straightforward:
319 we have a helper function that takes a file and a regex, and matches out the version number
320 for us.
321
322 .. code-block:: python
323
324     class Application(app.Application):
325         # ...
326         def detectVersion(self, deployment):
327             return self.detectVersionFromFile("wp-includes/version.php", php.re_var("wp_version"))
328
329 :attr:`~wizard.app.Application.parametrized_files` is a simple list of files that the
330 program's installer wrote or touched during the installation process.
331
332 .. code-block:: python
333
334     class Application(app.Application):
335         # ...
336         parametrized_files = ['wp-config.php']
337
338 This is actually is a lie: we also need to include changes to :file:`php.ini` that
339 we made:
340
341 .. code-block:: python
342
343     class Application(app.Application):
344         # ...
345         parametrized_files = ['wp-config.php'] + php.parametrized_files
346
347 .. _seed:
348
349 And finally, we have :attr:`~wizard.app.Application.extractors` and
350 :attr:`~wizard.app.Application.substitutions`.  At the bare metal, these
351 are simply dictionaries of variable names to functions: when you call the
352 function, it performs either an extraction or a substitution.  However, we can
353 use higher-level constructs to generate these functions for us.
354
355 The magic sauce is a data structure we'll refer to as ``seed``.  Its form is a
356 dictionary of variable names to a tuple ``(filename, regular expression)``.
357 The regular expression has a slightly special form (which we mentioned
358 earlier): it contains three (not two or four) subpatterns; the second
359 subpattern matches (quotes and all) the value that the regular expression is
360 actually looking for, and the first and third subpatterns match everything to
361 the left and right, respectively.
362
363 .. note::
364
365     The flanking subpatterns make it easier to use this regular expression
366     to perform a substitution: we are then allowed to use ``\1FOOBAR\3`` as
367     the replace value.
368
369 If we manually coded ``seed`` out, it might look like:
370
371 .. code-block:: python
372
373     seed = {
374         'WIZARD_DBSERVER': ('wp-config.php', re.compile(r'''^(define\('DB_HOST', )(.*)(\))''', re.M)),
375         'WIZARD_DBNAME': ('wp-config.php', re.compile(r'''^(define\('DB_NAME', )(.*)(\))''', re.M)),
376     }
377
378 There's a lot of duplication, though.  For one thing, the regular expressions are almost
379 identical, safe for a single substitution within the string.  We have a function
380 :meth:`wizard.app.php.re_define` that does this for us:
381
382 .. code-block:: python
383
384     seed = {
385         'WIZARD_DBSERVER': ('wp-config.php', php.re_define('DB_HOST')),
386         'WIZARD_DBNAME': ('wp-config.php', php.re_define('DB_NAME')),
387     }
388
389 .. note::
390
391     If you find yourself needing to define a custom regular expression generation function,
392     be sure to use :func:`wizard.app.expand_re`, which will escape an incoming variable
393     to be safe for inclusion in a regular expression, and also let you pass a list,
394     and have correct behavior.  Check out :mod:`wizard.app.php` for some examples.
395
396     Additionally, if you are implementing a function for another language, or a general pattern of
397     variables, consider placing it in an appropriate language module instead.
398
399 We can shorten this even further: in most cases, all of the configuration values live in
400 one file, so let's make ourselves a function that generates the whole tuple:
401
402 .. code-block:: python
403
404     def make_filename_regex_define(var):
405         return 'wp-config.php', php.re_define(var)
406
407 Then we can use :func:`wizard.util.dictmap` to apply this:
408
409 .. code-block:: python
410
411     seed = util.dictmap(make_filename_regex_define, {
412         'WIZARD_DBSERVER': 'DB_HOST',
413         'WIZARD_DBNAME': 'DB_NAME',
414         'WIZARD_DBUSER': 'DB_USER',
415         'WIZARD_DBPASSWORD': 'DB_PASSWORD',
416     })
417
418 Short and sweet.  From there, setting up :attr:`~wizard.app.Application.extractors` and
419 :attr:`~wizard.app.Application.substitutions` is easy:
420
421 .. code-block:: python
422
423     class Application(app.Application):
424         # ...
425         extractors = app.make_extractors(seed)
426         extractors.update(php.extractors)
427         substitutions = app.make_substitutions(seed)
428         substitutions.update(php.substitutions)
429
430 Note how we combine our own dictionaries with the dictionaries of :mod:`wizard.app.php`, much like
431 we did for :attr:`~wizard.app.Application.parametrized_files`.
432
433 With all of these pieces in place, run the following command::
434
435     wizard prepare-config
436
437 If everything is working, when you open up the configuration files, any user-specific
438 variables should have been replaced by ``WIZARD_FOOBAR`` variables.  If not, check
439 your regular expressions, and then try running the command again.
440
441 When you are satisfied with your changes, add your files, amend your previous
442 commit with these changes and force them back into the public repository::
443
444     git status
445     git add wp-config.php
446     git commit --amend -a
447     git push --force
448
449 You should test again if your install script works; it probably doesn't,
450 since you now have a configuration file hanging around.  Use
451 :func:`wizard.util.soft_unlink` to remove the file at the very beginning
452 of the install process.
453
454 Ending ceremonies
455 -----------------
456
457 Congratulations!  You have just implemented the installation code for a new install.
458 If you have other copies of the application checked out, you can pull the forced
459 change by doing::
460
461     git reset --hard HEAD~
462     git pull
463
464 One last thing to do: after you are sure that your commit is correct, tag the new
465 commit as ``appname-x.y.z-scripts``, or in this specific case::
466
467     git tag wordpress-2.0.4-scripts
468     git push --tags
469
470 Summary
471 -------
472
473 Here is short version for quick reference:
474
475 #. Create the new repository and new module,
476 #. Implement :meth:`~wizard.app.Application.download`,
477 #. *For Conversions:* Find the oldest extant version with ``wizard summary version $APP``,
478 #. Run ``wizard prepare-pristine $VERSION``,
479 #. Commit with ``-m "$APPLICATION $VERSION"`` and tag ``$APP-$VERSION``,
480 #. Create ``pristine`` branch, but stay on ``master`` branch,
481 #. *For Conversions:* Check for pre-existing patches, and apply them,
482 #. Run ``wizard prepare-new``,
483 #. *For PHP:* Copy in :file:`php.ini` file and run ``athrun scripts fix-php-ini``,
484 #. Commit with ``-m "$APPLICATION $VERSION"``, but *don't* tag,
485 #. Implement :data:`~wizard.app.Application.install_schema` and :meth:`~wizard.app.Application.install`,
486 #. Create :file:`tests/test-install-$APP.sh`,
487 #. On a scripts server, run ``wizard install $APP --no-commit`` and check changes with ``git status``,
488 #. Implement :attr:`~wizard.app.Application.extractors`,
489    :attr:`~wizard.app.Application.substitutions`, :attr:`~wizard.app.Application.parametrized_files`,
490    :meth:`~wizard.app.Application.checkConfig` and :meth:`~wizard.app.Application.detectVersion`,
491 #. Run ``wizard prepare-config``,
492 #. Amend commit and push back, and finally
493 #. Tag ``$APP-$VERSION-scripts``
494
495 Further reading
496 ---------------
497
498 You've only implemented a scriptsified version for only a single version; most applications
499 have multiple versions--you will have to do this process again.  Fortunately, the most
500 time consuming parts (implementing logic for :class:`wizard.app.Application`) are already,
501 done so the process of :doc:`creating upgrades <upgrade>` is much simpler.
502
503 There is still functionality yet undone: namely the methods for actually performing an
504 upgrade are not yet implemented.  You can find instructions for this on the
505 :doc:`creating upgrades <upgrade>` page under "Implementation".
506