source: branches/locker-dev/locker/deploy/bin/rails @ 2279

Last change on this file since 2279 was 2279, checked in by glasgall, 10 years ago
Don't set RAILS_RELATIVE_URL_ROOT; it breaks accessing apps by hostname
  • Property svn:executable set to *
File size: 7.5 KB
Line 
1#!/usr/bin/perl
2use strict;
3use FindBin qw($Bin);
4use lib $Bin;
5use onserver;
6use Tie::File;
7use Cwd;
8
9setup();
10
11sub make_db {
12    my($type) = @_;
13    print "\nCreating $type SQL database for $sname...\n";
14    open GETPWD, '-|', "/mit/scripts/sql/bin$scriptsdev/get-password";
15    ($sqlhost, $sqluser, $sqlpass) = split(/\s/, <GETPWD>);
16    close GETPWD;
17    open SQLDB, '-|', "/mit/scripts/sql/bin$scriptsdev/get-next-database", "${addrlast}_${type}";
18    $sqldb = <SQLDB>;
19    close SQLDB;
20    open SQLDB, '-|', "/mit/scripts/sql/bin$scriptsdev/create-database", $sqldb;
21    $sqldb = <SQLDB>;
22    close SQLDB;
23    if($sqldb eq "") {
24        print "\nERROR:\n";
25        print "Your SQL account failed to create a SQL database.\n";
26        print "You should log in at http://sql.mit.edu to check whether\n";
27        print "your SQL account is at its database limit or its storage limit.\n";
28        print "If you cannot determine the cause of the problem, please\n";
29        print "feel free to contact sql\@mit.edu for assistance.\n";
30        exit 1;
31    }
32    return $sqldb;
33}
34
35my $dev_db = make_db("development");
36my $test_db = make_db("test");
37my $prod_db = make_db("production");
38
39my $cwd = getcwd;
40system("rails", "new", $cwd ,"-d", "mysql");
41my $appdir = `basename $cwd`;
42chomp $appdir;
43
44open APPLICATION_RB, "config/application.rb";
45my $appclass;
46while(<APPLICATION_RB>) {
47    if (/module (\w+)\n/) {
48        $appclass = $1;
49        last;
50    }
51}
52close APPLICATION_RB;
53if (!$appclass) {
54    die "Couldn't find application class name - plase email scripts\@mit.edu with the names of your locker and the application you tried to create. Sorry!";
55}
56
57open PUBLIC_HTACCESS, ">public/.htaccess";
58print PUBLIC_HTACCESS <<EOF;
59# General Apache options
60Options +FollowSymLinks +ExecCGI
61
62# If you don't want Rails to look in certain directories,
63# use the following rewrite rules so that Apache won't rewrite certain requests
64#
65# Example:
66#   RewriteCond %{REQUEST_URI} ^/notrails.*
67#   RewriteRule .* - [L]
68
69# Redirect all requests not available on the filesystem to Rails
70# By default the cgi dispatcher is used which is very slow
71#
72# For better performance replace the dispatcher with the fastcgi one
73#
74# Example:
75#   RewriteRule ^(.*)\$ dispatch.fcgi [QSA,L]
76RewriteEngine On
77
78# If your Rails application is accessed via an Alias directive,
79# then you MUST also set the RewriteBase in this htaccess file.
80#
81# Example:
82#   Alias /myrailsapp /path/to/myrailsapp/public
83#   RewriteBase /myrailsapp
84
85RewriteCond index.html -f
86RewriteRule ^\$ index.html [QSA]
87RewriteCond %{REQUEST_FILENAME} !-f
88RewriteRule ^(.*)\$ dispatch.fcgi/\$1 [QSA,L]
89
90# In case Rails experiences terminal errors
91# Instead of displaying this message you can supply a file here which will be rendered instead
92#
93# Example:
94#   ErrorDocument 500 /500.html
95
96EOF
97
98open HTACCESS, ">.htaccess";
99print HTACCESS <<EOF;
100RewriteEngine On
101RewriteRule ^(.*)\$ public/\$1 [QSA,L]
102
103EOF
104
105tie my @railsenv, 'Tie::File', 'config/environment.rb';
106unshift @railsenv, "# ENV['RAILS_ENV'] ||= 'production'";
107unshift @railsenv, "# Uncomment below to put Rails into production mode";
108unshift @railsenv, "";
109untie @railsenv;
110
111tie my @railsdb, 'Tie::File', 'config/database.yml';
112for (@railsdb) {
113    s/username:.*$/username: $sqluser/;
114    s/password:.*$/password: $sqlpass/;
115    s/host:.*$/host: $sqlhost/;
116    s/database:.*_development.*/database: $dev_db/;
117    s/database:.*_test.*/database: $test_db/;
118    s/database:.*_production.*/database: $prod_db/;
119}
120untie @railsdb;
121
122tie my @railswelcome, 'Tie::File', 'public/index.html';
123for (@railswelcome) {
124    s/Create your database/Sync your database/;
125    s/to create your database\..*/to create tables in your database.<\/p>/;
126}
127untie @railswelcome;
128
129tie my @railsfcgi, 'Tie::File', 'public/dispatch.fcgi';
130for (@railsfcgi) {
131    s/^[^#]*RailsFCGIHandler/## Commented out by scripts.mit.edu autoinstaller\n## RailsFCGIHandler/;
132}
133untie @railsfcgi;
134open RAILSFCGI, ">>public/dispatch.fcgi";
135print RAILSFCGI "#!/usr/bin/ruby\n";
136print RAILSFCGI <<EOF;
137require File.join(File.dirname(__FILE__), '../config/environment')       
138require 'rack'
139
140## Added by scripts.mit.edu autoinstaller to reload when app code changes
141Thread.abort_on_exception = true
142
143class Rack::PathInfoRewriter
144  def initialize(app)
145    \@app = app
146  end
147
148  def call(env)
149    env["SCRIPT_NAME"] = ""
150    parts = env['REQUEST_URI'].split('?')
151    env['PATH_INFO'] = parts[0]
152    env['QUERY_STRING'] = parts[1].to_s
153    \@app.call(env)
154  end
155end
156
157
158t1 = Thread.new do
159  dispatch_logger = Logger.new(File.join(Rails.root,'log/dispatcher.log'))
160
161  begin
162    Rack::Handler::FastCGI.run Rack::PathInfoRewriter.new(Rack::URLMap.new("/$appdir" => ${appclass}::Application,
163                                                                           "/" => ${appclass}::Application))
164  rescue => e
165   dispatch_logger.error(e)
166   raise e
167  end
168end
169t2 = Thread.new do
170   # List of directories to watch for changes before reload.
171   # You may want to also watch public or vendor, depending on your needs.
172   Thread.current[:watched_dirs] = ['app', 'config', 'db', 'lib']
173
174   # List of specific files to watch for changes.
175   Thread.current[:watched_files] = ['public/dispatch.fcgi',
176                                     'public/.htaccess']
177   # Sample filter: /(\.rb|\.erb)\$/.  Default filter: watch all files
178   Thread.current[:watched_extensions] = //
179   # Iterations since last reload
180   Thread.current[:iterations] = 0
181
182   def modified(file)
183     begin
184       mtime = File.stat(file).mtime
185     rescue
186       false
187     else
188       if Thread.current[:iterations] == 0
189         Thread.current[:modifications][file] = mtime
190       end
191       Thread.current[:modifications][file] != mtime
192     end
193   end
194
195   # Don't symlink yourself into a loop.  Please.  Things will still work
196   # (Linux limits your symlink depth) but you will be sad
197   def modified_dir(dir)
198     Dir.new(dir).each do |file|
199       absfile = File.join(dir, file)
200       if FileTest.directory? absfile
201         next if file == '.' or file == '..'
202         return true if modified_dir(absfile)
203       else
204         return true if Thread.current[:watched_extensions] =~ absfile &&
205           modified(absfile)
206       end
207     end
208     false
209   end
210
211   def reload
212     Thread.current[:modifications] = {}
213     Thread.current[:iterations] = 0
214     # This is a kludge, but at the same time it works.
215     # Will kill the current FCGI process so that it is reloaded
216     # at next request.
217     raise RuntimeError
218   end
219
220   Thread.current[:modifications] = {}
221   # Wait until the modify time changes, then reload.
222   while true
223     dir_modified = Thread.current[:watched_dirs].inject(false) {|z, dir| z || modified_dir(File.join(File.dirname(__FILE__), '..', dir))}
224     file_modified = Thread.current[:watched_files].inject(false) {|z, file| z || modified(File.join(File.dirname(__FILE__), '..', file))}
225     reload if dir_modified || file_modified
226     Thread.current[:iterations] += 1
227     sleep 1
228   end
229end
230
231t1.join
232t2.join
233## End of scripts.mit.edu autoinstaller additions
234EOF
235chmod 0755,'public/dispatch.fcgi';
236
237# static-cat doesn't whitelist .txt files
238chmod 0777, 'public/robots.txt'; 
239
240# have to explicitly take a dependency on fcgi
241# ruby1.9 means we need to take a dependency on minitest
242# for rails console to work
243open GEMFILE, ">>Gemfile";
244print GEMFILE "gem 'fcgi'\n";
245print GEMFILE "gem 'minitest'\n";
246close GEMFILE;
247
248print "Your application is located in:\n";
249print "  /mit/$USER/web_scripts/$addrend/\n";
250print "To run programs like rake or rails generate, run\n";
251print "  'ssh -k $USER\@scripts' and cd to the above directory.\n\n";
252press_enter;
253
254exit 0;
Note: See TracBrowser for help on using the repository browser.