MyPLC: portable self-contained PLC installation
[myplc.git] / guest.init
1 #!/bin/bash
2 #
3 # plc   Manages all PLC services on this machine
4 #
5 # chkconfig: 2345 5 99
6 #
7 # description:  Manages all PLC services on this machine
8 #
9 # $Id: plc.init,v 1.6 2005/04/24 19:48:11 mlhuang Exp $
10 #
11
12 PATH=/sbin:/bin:/usr/bin:/usr/sbin
13
14 # Source function library.
15 . /etc/init.d/functions
16
17 # Verbosity
18 verbose=0
19
20 # Keep in order! All steps should be idempotent. This means that you
21 # should be able to run them multiple times without depending on
22 # anything previously being run. The idea is that when the
23 # configuration changes, "service plc restart" is called, all
24 # dependencies are fixed up, and everything just works.
25 steps=(
26 network
27 syslog
28 postgresql
29 ssl
30 gpg
31 ssh
32 apache
33 api
34 cron
35 )
36 nsteps=${#steps[@]}
37
38 gethostbyname ()
39 {
40     perl -MSocket -e '($a,$b,$c,$d,@addrs) = gethostbyname($ARGV[0]); print inet_ntoa($addrs[0]) . "\n";' $1 2>/dev/null
41 }
42
43 # Regenerate configuration files
44 reload ()
45 {
46     # Load configuration
47     plc-config --shell >/etc/planetlab/plc_config
48     . /etc/planetlab/plc_config
49
50     # Generate various defaults
51     if [ -z "$PLC_DB_PASSWORD" ] ; then
52         PLC_DB_PASSWORD=$(uuidgen)
53         plc-config --category=plc_db --variable=password --value="$PLC_DB_PASSWORD" --save
54     fi
55
56     if [ -z "$PLC_API_MAINTENANCE_PASSWORD" ] ; then
57         PLC_API_MAINTENANCE_PASSWORD=$(uuidgen)
58         plc-config --category=plc_api --variable=maintenance_password --value="$PLC_API_MAINTENANCE_PASSWORD" --save
59     fi
60
61     if [ -z "$PLC_API_MAINTENANCE_SOURCES" ] ; then
62         for server in API BOOT WWW ; do
63             eval hostname=\${PLC_${server}_HOST}
64             ip=$(gethostbyname $hostname)
65             if [ -n "$ip" ] ; then
66                 if [ -n "$PLC_API_MAINTENANCE_SOURCES" ] ; then
67                     PLC_API_MAINTENANCE_SOURCES="$PLC_API_MAINTENANCE_SOURCES $ip"
68                 else
69                     PLC_API_MAINTENANCE_SOURCES=$ip
70                 fi
71             fi
72         done
73         plc-config --category=plc_api --variable=maintenance_sources --value="$PLC_API_MAINTENANCE_SOURCES" --save
74     fi
75
76     # Save configuration
77     mkdir -p /etc/planetlab/php
78     plc-config --php >/etc/planetlab/php/plc_config.php
79     plc-config --shell >/etc/planetlab/plc_config
80
81     # For backward compatibility, until we can convert all code to use
82     # the now standardized variable names.
83
84     # DB constants are all named the same
85     ln -sf plc_config /etc/planetlab/plc_db
86
87     # API constants
88     cat >/etc/planetlab/plc_api <<EOF
89 PL_API_SERVER='$PLC_API_HOST'
90 PL_API_PATH='$PLC_API_PATH'
91 PL_API_PORT=$PLC_API_SSL_PORT
92 PL_API_CAPABILITY_AUTH_METHOD='capability'
93 PL_API_CAPABILITY_PASS='$PLC_API_MAINTENANCE_PASSWORD'
94 PL_API_CAPABILITY_USERNAME='$PLC_API_MAINTENANCE_USER'
95 PL_API_TICKET_KEY_FILE='$PLC_API_TICKET_KEY'
96 PLANETLAB_SUPPORT_EMAIL='$PLC_MAIL_SUPPORT_ADDRESS'
97 BOOT_MESSAGES_EMAIL='$PLC_MAIL_BOOT_ADDRESS'
98 WWW_BASE='$PLC_WWW_HOST'
99 BOOT_BASE='$PLC_BOOT_HOST'
100 EOF
101
102     # The format is
103     #
104     # ip:max_role_id:organization_id:password
105     #
106     # It is unlikely that we will let federated sites use the
107     # maintenance account to access each others' APIs, so we always
108     # set organization_id to -1.
109     (
110         echo -n "PL_API_CAPABILITY_SOURCES='"
111         first=1
112         for ip in $PLC_API_MAINTENANCE_SOURCES ; do
113             if [ $first -ne 1 ] ; then
114                 echo -n " "
115             fi
116             first=0
117             echo -n "$ip:-1:-1:$PLC_API_MAINTENANCE_PASSWORD"
118         done
119         echo "'"
120     ) >>/etc/planetlab/plc_api
121
122     cat >/etc/planetlab/php/site_constants.php <<"EOF"
123 <?php
124 include('plc_config.php');
125
126 DEFINE('PL_API_SERVER', PLC_API_HOST);
127 DEFINE('PL_API_PATH', PLC_API_PATH);
128 DEFINE('PL_API_PORT', PLC_API_SSL_PORT);
129 DEFINE('PL_API_CAPABILITY_AUTH_METHOD', 'capability');
130 DEFINE('PL_API_CAPABILITY_PASS', PLC_API_MAINTENANCE_PASSWORD);
131 DEFINE('PL_API_CAPABILITY_USERNAME', PLC_API_MAINTENANCE_USER);
132 DEFINE('WWW_BASE', PLC_WWW_HOST);
133 DEFINE('BOOT_BASE', PLC_BOOT_HOST);
134 DEFINE('DEBUG', PLC_WWW_DEBUG);
135 DEFINE('API_CALL_DEBUG', PLC_API_DEBUG);
136 DEFINE('SENDMAIL', PLC_MAIL_ENABLED);
137 DEFINE('PLANETLAB_SUPPORT_EMAIL', PLC_NAME . 'Support <' . PLC_MAIL_SUPPORT_ADDRESS . '>');
138 DEFINE('PLANETLAB_SUPPORT_EMAIL_ONLY', PLC_MAIL_SUPPORT_ADDRESS);
139 ?>
140 EOF
141 }
142
143 config_network ()
144 {
145     case "$1" in
146         start)
147             # Minimal /etc/hosts
148             (
149                 echo "127.0.0.1 localhost.localdomain localhost"
150                 for server in API BOOT WWW ; do
151                     eval hostname=\${PLC_${server}_HOST}
152                     ip=$(gethostbyname $hostname)
153                     if [ -n "$ip" ] ; then
154                         echo "$ip       $hostname"
155                     fi
156                 done
157             ) >/etc/hosts
158
159             # Set up nameservers
160             (
161                 [ -n "$PLC_NET_DNS1" ] && echo "nameserver $PLC_NET_DNS1"
162                 [ -n "$PLC_NET_DNS2" ] && echo "nameserver $PLC_NET_DNS2"
163             ) >/etc/resolv.conf
164             ;;
165     esac
166 }
167
168 config_syslog ()
169 {
170     service syslog $1
171     RETVAL=$?
172 }
173
174 config_postgresql ()
175 {
176     # Default locations
177     PGDATA=/var/lib/pgsql/data
178     postgresql_conf=$PGDATA/postgresql.conf
179     pghba_conf=$PGDATA/pg_hba.conf
180
181     case "$1" in
182         start)
183             if [ "$PLC_DB_ENABLED" != "1" ] ; then
184                 return 0
185             fi
186
187             # Set data directory and redirect startup output to /var/log/pgsql
188             mkdir -p /etc/sysconfig/pgsql
189             (
190                 echo "PGDATA=$PGDATA"
191                 echo "PGLOG=/var/log/pgsql"
192             ) >>/etc/sysconfig/pgsql/postgresql
193
194             # PostgreSQL must be started at least once to bootstrap
195             # /var/lib/pgsql/data
196             if [ ! -f $postgresql_conf ] ; then
197                 service postgresql start
198                 service postgresql stop
199             fi
200
201             # Enable DB server. PostgreSQL >=8.0 defines listen_addresses,
202             # PostgreSQL 7.x uses tcpip_socket.
203             if grep -q listen_addresses $postgresql_conf ; then
204                 sed -i -e '/^listen_addresses/d' $postgresql_conf
205                 echo "listen_addresses = '*'" >>$postgresql_conf
206             elif grep -q tcpip_socket $postgresql_conf ; then
207                 sed -i -e '/^tcpip_socket/d' $postgresql_conf
208                 echo "tcpip_socket = true" >>$postgresql_conf
209             fi
210
211             # Disable access to all DBs from all hosts
212             sed -i -e '/^\(host\|local\)/d' $pghba_conf
213
214             # Enable passwordless localhost access
215             echo "local all all trust" >>$pghba_conf
216
217             # Enable access from the API and web servers
218             PLC_API_IP=$(gethostbyname $PLC_API_HOST)
219             PLC_WWW_IP=$(gethostbyname $PLC_WWW_HOST)
220             (
221                 echo "host $PLC_DB_NAME $PLC_DB_USER $PLC_API_IP/32 password"
222                 echo "host $PLC_DB_NAME $PLC_DB_USER $PLC_WWW_IP/32 password"
223             ) >>$pghba_conf
224
225             # Fix ownership (sed -i changes it)
226             chown postgres:postgres $postgresql_conf $pghba_conf
227
228             # Start up the server
229             service postgresql start
230             RETVAL=$?
231
232             # Create/update the unprivileged database user and password
233             if ! psql -U $PLC_DB_USER -c "" template1 >/dev/null 2>&1 ; then
234                 psql -U postgres -c "CREATE USER $PLC_DB_USER PASSWORD '$PLC_DB_PASSWORD'" template1
235             else
236                 psql -U postgres -c "ALTER USER $PLC_DB_USER WITH PASSWORD '$PLC_DB_PASSWORD'" template1
237             fi
238
239             # Create the database if necessary
240             if ! psql -U $PLC_DB_USER -c "" $PLC_DB_NAME >/dev/null 2>&1 ; then
241                 createdb -U postgres $PLC_DB_NAME
242                 psql -U $PLC_DB_USER -f /usr/share/pl_db/plc_schema_3.sql $PLC_DB_NAME
243             fi
244             ;;
245
246         stop)
247             # Drop the current user in case the username changes
248             psql -U postgres -c "DROP USER $PLC_DB_USER" template1
249
250             # WARNING: If the DB name changes, the old DB will be left
251             # intact and a new one will be created. If it changes
252             # back, the old DB will not be re-created.
253
254             # Shut down the server
255             service postgresql stop
256             RETVAL=$?
257             ;;
258     esac
259 }
260
261 # Generate GPG keys
262 config_gpg ()
263 {
264     case "$1" in
265         start)
266             # Generate GPG keyrings
267             if [ ! -f $PLC_ROOT_GPG_KEY_PUB -o ! -f $PLC_ROOT_GPG_KEY ] ; then
268                 mkdir -p $(dirname $PLC_ROOT_GPG_KEY_PUB)
269                 mkdir -p $(dirname $PLC_ROOT_GPG_KEY)
270
271                 # Temporarily replace /dev/random with /dev/urandom to
272                 # avoid running out of entropy.
273                 rm -f /dev/random
274                 mknod /dev/random c 1 9
275                 gpg --homedir=/root --batch --gen-key <<EOF
276 Key-Type: DSA
277 Key-Length: 1024
278 Subkey-Type: ELG-E
279 Subkey-Length: 1024
280 Name-Real: $PLC_NAME Central
281 Name-Comment: http://$PLC_WWW_HOST/
282 Name-Email: $PLC_MAIL_SUPPORT_ADDRESS
283 Expire-Date: 0
284 %pubring $PLC_ROOT_GPG_KEY_PUB
285 %secring $PLC_ROOT_GPG_KEY
286 %commit
287 EOF
288                 RETVAL=$?
289                 rm -f /dev/random
290                 mknod /dev/random c 1 8
291                 chmod 600 $PLC_ROOT_GPG_KEY_PUB $PLC_ROOT_GPG_KEY
292             fi
293             ;;
294     esac
295 }
296
297 symlink ()
298 {
299     mkdir -p $(dirname $2)
300     rm -f $2
301     ln -s $1 $2
302 }
303
304 # Generate SSL certificates
305 config_ssl ()
306 {
307     case "$1" in
308         start)
309             # Generate a self-signed SSL certificate. These nice
310             # commands came from the mod_ssl spec file for Fedora Core
311             # 2. We generate only a single certificate for the web
312             # server, then make copies for the API and boot
313             # servers. As always, these certificates may be overridden
314             # later.
315
316             # Generate SSL private key
317             if [ ! -f $PLC_WWW_SSL_KEY ] ; then
318                 mkdir -p $(dirname $PLC_WWW_SSL_KEY)
319                 openssl genrsa -rand /proc/apm:/proc/cpuinfo:/proc/dma:/proc/filesystems:/proc/interrupts:/proc/ioports:/proc/pci:/proc/rtc:/proc/uptime 1024 >$PLC_WWW_SSL_KEY
320                 RETVAL=$(($RETVAL+$?))
321                 chmod 600 $PLC_WWW_SSL_KEY
322             fi
323
324             # Generate self-signed certificate
325             if [ ! -f $PLC_WWW_SSL_CRT ] ; then
326                 mkdir -p $(dirname $PLC_WWW_SSL_CRT)
327                 openssl req -new -x509 -days 365 -set_serial $RANDOM \
328                     -key $PLC_WWW_SSL_KEY -out $PLC_WWW_SSL_CRT <<EOF
329 --
330 State
331 City
332 Organization
333 $PLC_NAME Central
334 $PLC_WWW_HOST
335 $PLC_MAIL_SUPPORT_ADDRESS
336 EOF
337                 RETVAL=$(($RETVAL+$?))
338                 chmod 644 $PLC_WWW_SSL_CRT
339             fi
340
341             # Make copies for the API and boot servers
342             if [ ! -f $PLC_API_SSL_KEY ] ; then
343                 cp -a $PLC_WWW_SSL_KEY $PLC_API_SSL_KEY
344             fi
345             if [ ! -f $PLC_API_SSL_CRT ] ; then
346                 cp -a $PLC_WWW_SSL_CRT $PLC_API_SSL_CRT
347             fi
348             if [ ! -f $PLC_API_SSL_KEY ] ; then
349                 cp -a $PLC_WWW_SSL_KEY $PLC_API_SSL_KEY
350             fi
351             if [ ! -f $PLC_API_SSL_CRT ] ; then
352                 cp -a $PLC_WWW_SSL_CRT $PLC_API_SSL_CRT
353             fi
354
355             # Install into both /etc/pki (Fedora Core 4) and
356             # /etc/httpd/conf (Fedora Core 2). If the API, boot, and
357             # web servers are all running on the same machine, the web
358             # server certificate takes precedence.
359             for server in API BOOT WWW ; do
360                 eval enabled=\${PLC_${server}_ENABLED}
361                 if [ "$enabled" != "1" ] ; then
362                     continue
363                 fi
364                 eval ssl_crt=\${PLC_${server}_SSL_CRT}
365                 eval ssl_key=\${PLC_${server}_SSL_KEY}
366
367                 symlink $ssl_crt /etc/pki/tls/certs/localhost.crt
368                 symlink $ssl_key /etc/pki/tls/private/localhost.key
369                 symlink $ssl_crt /etc/httpd/conf/ssl.crt/server.crt
370                 symlink $ssl_key /etc/httpd/conf/ssl.key/server.key
371             done
372             ;;
373     esac
374 }
375
376 # Generate SSH keys
377 config_ssh ()
378 {
379     # XXX Could make these configurable
380     KEY_TYPE_ROOT=rsa
381     KEY_LEN_ROOT=1024
382     KEY_TYPE_DEBUG=rsa
383     KEY_LEN_DEBUG=2048  
384
385     case "$1" in
386         start)
387             tmp=$(mktemp -d /tmp/ssh.XXXXXX)
388
389             # Generate root SSH key
390             if [ ! -f $PLC_ROOT_SSH_KEY_PUB -o ! -f $PLC_ROOT_SSH_KEY ] ; then
391                 ssh-keygen -N "" -C "$PLC_NAME Central <$PLC_MAIL_SUPPORT_ADDRESS>" \
392                     -b $KEY_LEN_ROOT -t $KEY_TYPE_ROOT -f $tmp/root
393                 RETVAL=$(($RETVAL+$?))
394                 install -D -m 600 $tmp/root $PLC_ROOT_SSH_KEY
395                 install -D -m 600 $tmp/root.pub $PLC_ROOT_SSH_KEY_PUB
396             fi
397
398             # Generate debug SSH key
399             if [ ! -f $PLC_DEBUG_SSH_KEY_PUB -o ! -f $PLC_DEBUG_SSH_KEY ] ; then
400                 ssh-keygen -N "" -C "$PLC_NAME Central <$PLC_MAIL_SUPPORT_ADDRESS>" \
401                     -b $KEY_LEN_DEBUG -t $KEY_TYPE_DEBUG -f $tmp/debug
402                 RETVAL=$(($RETVAL+$?))
403                 install -D -m 600 $tmp/debug $PLC_DEBUG_SSH_KEY
404                 install -D -m 600 $tmp/debug.pub $PLC_DEBUG_SSH_KEY_PUB
405             fi
406
407             rm -rf $tmp
408             ;;
409     esac
410 }
411
412 # Configure Apache web server
413 config_apache ()
414 {
415     # Default locations
416     DocumentRoot=/var/www/html
417     php_ini=/etc/php.ini
418     httpd_conf=/etc/httpd/conf/httpd.conf
419     ssl_conf=/etc/httpd/conf.d/ssl.conf
420     plc_conf=/etc/httpd/conf.d/plc.conf
421
422     case "$1" in
423         start)
424             if [ "$PLC_API_ENABLED" != "1" -a \
425                  "$PLC_BOOT_ENABLED" != "1" -a \
426                  "$PLC_WWW_ENABLED" != "1" ] ; then
427                 return 0
428             fi
429
430             # Set the default include path
431             include_path=".:$DocumentRoot/includes:$DocumentRoot/generated:/etc/planetlab/php"
432             sed -i -e "s@;include_path = \"\.:.*\"@include_path = \"$include_path\"@" $php_ini
433
434             # Set the port numbers. If the API, boot, and web servers
435             # are all running on the same machine, the web server port
436             # numbers take precedence.
437             for server in API BOOT WWW ; do
438                 eval enabled=\${PLC_${server}_ENABLED}
439                 if [ "$enabled" != "1" ] ; then
440                     continue
441                 fi
442                 eval http_port=\${PLC_${server}_PORT}
443                 eval https_port=\${PLC_${server}_SSL_PORT}
444
445                 if [ -n "$http_port" ] ; then
446                     sed -i -e "s/^Listen .*/Listen $http_port/" $httpd_conf
447                 fi
448                 if [ -n "$https_port" ] ; then
449                     sed -i -e "s/^Listen .*/Listen $https_port/" $ssl_conf
450                 fi
451             done
452                     
453             # Set custom Apache directives
454             (
455                 if [ "$PLC_API_ENABLED" = "1" ] ; then
456                     cat <<EOF
457 <Location $PLC_API_PATH>
458     SetHandler python-program
459     PythonPath "sys.path + ['/usr/share/plc_api']"
460     PythonHandler mod_pythonXMLRPC
461 </Location>
462 EOF
463                 fi
464
465                 cat <<EOF
466 <VirtualHost $PLC_WWW_HOST:$PLC_WWW_PORT>
467     Redirect /db https://$PLC_WWW_HOST:$PLC_WWW_SSL_PORT/db
468 </VirtualHost>
469 EOF
470             ) >$plc_conf
471
472             # Make alpina-logs directory writable for bootmanager log upload
473             chown apache:apache $DocumentRoot/alpina-logs/nodes
474
475             service httpd start
476             RETVAL=$?
477             ;;
478
479         stop)
480             service httpd stop
481             RETVAL=$?
482             ;;
483     esac
484 }
485
486 config_api ()
487 {
488     case "$1" in
489         start)
490             if [ "$PLC_API_ENABLED" -ne 1 ] ; then
491                 return
492             fi
493
494             # Update the maintenance account username. This can't be
495             # done through the api-config script since it uses the
496             # maintenance account to access the API. The maintenance
497             # account should be person_id 1 since it is created by the
498             # DB schema itself.
499             psql -U $PLC_DB_USER -c "UPDATE persons SET email='$PLC_API_MAINTENANCE_USER' WHERE person_id=1" $PLC_DB_NAME
500
501             # Bootstrap the DB
502             api-config
503             RETVAL=$?
504             ;;
505     esac
506 }
507
508 config_cron ()
509 {
510     case "$1" in
511         start)
512             cat >/etc/cron.d/plc.cron <<EOF
513 SHELL=/bin/bash
514 PATH=/sbin:/bin:/usr/sbin:/usr/bin
515 MAILTO=$PLC_MAIL_SUPPORT_ADDRESS
516 HOME=/
517
518 # minute hour day-of-month month day-of-week user command
519 */5 * * * * root gen-slices-xml-05.py
520 */15 * * * * root gen-sites-xml.py
521 */15 * * * * root gen-static-content.py
522 EOF
523
524             # Run them once at startup
525             gen-slices-xml-05.py
526             gen-sites-xml.py
527             gen-static-content.py
528
529             service crond start
530             RETVAL=$?
531             ;;
532
533         stop)
534             service crond stop
535             RETVAL=$?
536             ;;
537     esac
538 }
539
540 usage()
541 {
542     echo "Usage: $0 [OPTION]... [COMMAND]"
543     echo "      -v              Be verbose"
544     echo "      -h              This message"
545     echo
546     echo "Commands:"
547     echo "      start           Start all PLC subsystems"
548     echo "      stop            Stop all PLC subsystems"
549     echo "      reload          Regenerate configuration files"
550     echo "      restart         Restart all PLC subsystems"
551     exit 1
552 }
553
554 # Get options
555 while getopts "vh" opt ; do
556     case $opt in
557         v)
558             verbose=1
559             set -x
560             ;;
561         h|*)
562             usage
563             ;;
564     esac
565 done
566
567 shift $(($OPTIND - 1))
568 if [ -z "$1" ] ; then
569     usage
570 fi
571
572 exec 3>&1
573 exec 4>&2
574 if [ $verbose -eq 0 ] ; then
575     exec 1>/dev/null
576     exec 2>/dev/null
577 fi
578
579 # Generate and load configuration
580 reload
581 . /etc/planetlab/plc_config
582
583 RETVAL=0
584
585 start ()
586 {
587     for step in "${steps[@]}" ; do
588         echo -n $"PLC: Starting $step: " >&3
589         RETVAL=0
590         config_$step start
591         if [ $RETVAL -eq 0 ] ; then
592             success $"PLC: $step startup" >&3
593         else
594             failure $"PLC: $step startup" >&3
595         fi
596         echo >&3
597     done
598 }
599
600 stop ()
601 {
602     for i in $(seq 1 $nsteps) ; do
603         step=${steps[$(($nsteps - $i))]}
604         echo -n $"PLC: Shutting down $step: " >&3
605         RETVAL=0
606         config_$step stop
607         if [ $RETVAL -eq 0 ] ; then
608             success $"PLC: $step shutdown" >&3
609         else
610             failure $"PLC: $step shutdown" >&3
611         fi
612         echo >&3
613     done
614 }
615
616 case "$1" in
617     start|stop)
618         $1
619         ;;
620
621     restart)
622         stop
623         start
624         ;;
625
626     reload)
627         ;;
628
629     *)
630         usage >&3
631         ;;
632 esac
633
634 exit $RETVAL