- fix ownership of pgsql data directory in case rpm installation changed it
[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: guest.init,v 1.1.1.1 2006/03/27 17:36:46 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             # Fix ownership (rpm installation may have changed it)
195             chown -R -H postgres:postgres $(dirname $PGDATA)
196
197             # PostgreSQL must be started at least once to bootstrap
198             # /var/lib/pgsql/data
199             if [ ! -f $postgresql_conf ] ; then
200                 service postgresql start
201                 service postgresql stop
202             fi
203
204             # Enable DB server. PostgreSQL >=8.0 defines listen_addresses,
205             # PostgreSQL 7.x uses tcpip_socket.
206             if grep -q listen_addresses $postgresql_conf ; then
207                 sed -i -e '/^listen_addresses/d' $postgresql_conf
208                 echo "listen_addresses = '*'" >>$postgresql_conf
209             elif grep -q tcpip_socket $postgresql_conf ; then
210                 sed -i -e '/^tcpip_socket/d' $postgresql_conf
211                 echo "tcpip_socket = true" >>$postgresql_conf
212             fi
213
214             # Disable access to all DBs from all hosts
215             sed -i -e '/^\(host\|local\)/d' $pghba_conf
216
217             # Enable passwordless localhost access
218             echo "local all all trust" >>$pghba_conf
219
220             # Enable access from the API and web servers
221             PLC_API_IP=$(gethostbyname $PLC_API_HOST)
222             PLC_WWW_IP=$(gethostbyname $PLC_WWW_HOST)
223             (
224                 echo "host $PLC_DB_NAME $PLC_DB_USER $PLC_API_IP/32 password"
225                 echo "host $PLC_DB_NAME $PLC_DB_USER $PLC_WWW_IP/32 password"
226             ) >>$pghba_conf
227
228             # Fix ownership (sed -i changes it)
229             chown postgres:postgres $postgresql_conf $pghba_conf
230
231             # Start up the server
232             service postgresql start
233             RETVAL=$?
234
235             # Create/update the unprivileged database user and password
236             if ! psql -U $PLC_DB_USER -c "" template1 >/dev/null 2>&1 ; then
237                 psql -U postgres -c "CREATE USER $PLC_DB_USER PASSWORD '$PLC_DB_PASSWORD'" template1
238             else
239                 psql -U postgres -c "ALTER USER $PLC_DB_USER WITH PASSWORD '$PLC_DB_PASSWORD'" template1
240             fi
241
242             # Create the database if necessary
243             if ! psql -U $PLC_DB_USER -c "" $PLC_DB_NAME >/dev/null 2>&1 ; then
244                 createdb -U postgres $PLC_DB_NAME
245                 psql -U $PLC_DB_USER -f /usr/share/pl_db/plc_schema_3.sql $PLC_DB_NAME
246             fi
247             ;;
248
249         stop)
250             # Drop the current user in case the username changes
251             psql -U postgres -c "DROP USER $PLC_DB_USER" template1
252
253             # WARNING: If the DB name changes, the old DB will be left
254             # intact and a new one will be created. If it changes
255             # back, the old DB will not be re-created.
256
257             # Shut down the server
258             service postgresql stop
259             RETVAL=$?
260             ;;
261     esac
262 }
263
264 # Generate GPG keys
265 config_gpg ()
266 {
267     case "$1" in
268         start)
269             # Generate GPG keyrings
270             if [ ! -f $PLC_ROOT_GPG_KEY_PUB -o ! -f $PLC_ROOT_GPG_KEY ] ; then
271                 mkdir -p $(dirname $PLC_ROOT_GPG_KEY_PUB)
272                 mkdir -p $(dirname $PLC_ROOT_GPG_KEY)
273
274                 # Temporarily replace /dev/random with /dev/urandom to
275                 # avoid running out of entropy.
276                 rm -f /dev/random
277                 mknod /dev/random c 1 9
278                 gpg --homedir=/root --batch --gen-key <<EOF
279 Key-Type: DSA
280 Key-Length: 1024
281 Subkey-Type: ELG-E
282 Subkey-Length: 1024
283 Name-Real: $PLC_NAME Central
284 Name-Comment: http://$PLC_WWW_HOST/
285 Name-Email: $PLC_MAIL_SUPPORT_ADDRESS
286 Expire-Date: 0
287 %pubring $PLC_ROOT_GPG_KEY_PUB
288 %secring $PLC_ROOT_GPG_KEY
289 %commit
290 EOF
291                 RETVAL=$?
292                 rm -f /dev/random
293                 mknod /dev/random c 1 8
294                 chmod 600 $PLC_ROOT_GPG_KEY_PUB $PLC_ROOT_GPG_KEY
295             fi
296             ;;
297     esac
298 }
299
300 symlink ()
301 {
302     mkdir -p $(dirname $2)
303     rm -f $2
304     ln -s $1 $2
305 }
306
307 # Generate SSL certificates
308 config_ssl ()
309 {
310     case "$1" in
311         start)
312             # Generate a self-signed SSL certificate. These nice
313             # commands came from the mod_ssl spec file for Fedora Core
314             # 2. We generate only a single certificate for the web
315             # server, then make copies for the API and boot
316             # servers. As always, these certificates may be overridden
317             # later.
318
319             # Generate SSL private key
320             if [ ! -f $PLC_WWW_SSL_KEY ] ; then
321                 mkdir -p $(dirname $PLC_WWW_SSL_KEY)
322                 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
323                 RETVAL=$(($RETVAL+$?))
324                 chmod 600 $PLC_WWW_SSL_KEY
325             fi
326
327             # Generate self-signed certificate
328             if [ ! -f $PLC_WWW_SSL_CRT ] ; then
329                 mkdir -p $(dirname $PLC_WWW_SSL_CRT)
330                 openssl req -new -x509 -days 365 -set_serial $RANDOM \
331                     -key $PLC_WWW_SSL_KEY -out $PLC_WWW_SSL_CRT <<EOF
332 --
333 State
334 City
335 Organization
336 $PLC_NAME Central
337 $PLC_WWW_HOST
338 $PLC_MAIL_SUPPORT_ADDRESS
339 EOF
340                 RETVAL=$(($RETVAL+$?))
341                 chmod 644 $PLC_WWW_SSL_CRT
342             fi
343
344             # Make copies for the API and boot servers
345             if [ ! -f $PLC_API_SSL_KEY ] ; then
346                 cp -a $PLC_WWW_SSL_KEY $PLC_API_SSL_KEY
347             fi
348             if [ ! -f $PLC_API_SSL_CRT ] ; then
349                 cp -a $PLC_WWW_SSL_CRT $PLC_API_SSL_CRT
350             fi
351             if [ ! -f $PLC_API_SSL_KEY ] ; then
352                 cp -a $PLC_WWW_SSL_KEY $PLC_API_SSL_KEY
353             fi
354             if [ ! -f $PLC_API_SSL_CRT ] ; then
355                 cp -a $PLC_WWW_SSL_CRT $PLC_API_SSL_CRT
356             fi
357
358             # Install into both /etc/pki (Fedora Core 4) and
359             # /etc/httpd/conf (Fedora Core 2). If the API, boot, and
360             # web servers are all running on the same machine, the web
361             # server certificate takes precedence.
362             for server in API BOOT WWW ; do
363                 eval enabled=\${PLC_${server}_ENABLED}
364                 if [ "$enabled" != "1" ] ; then
365                     continue
366                 fi
367                 eval ssl_crt=\${PLC_${server}_SSL_CRT}
368                 eval ssl_key=\${PLC_${server}_SSL_KEY}
369
370                 symlink $ssl_crt /etc/pki/tls/certs/localhost.crt
371                 symlink $ssl_key /etc/pki/tls/private/localhost.key
372                 symlink $ssl_crt /etc/httpd/conf/ssl.crt/server.crt
373                 symlink $ssl_key /etc/httpd/conf/ssl.key/server.key
374             done
375             ;;
376     esac
377 }
378
379 # Generate SSH keys
380 config_ssh ()
381 {
382     # XXX Could make these configurable
383     KEY_TYPE_ROOT=rsa
384     KEY_LEN_ROOT=1024
385     KEY_TYPE_DEBUG=rsa
386     KEY_LEN_DEBUG=2048  
387
388     case "$1" in
389         start)
390             tmp=$(mktemp -d /tmp/ssh.XXXXXX)
391
392             # Generate root SSH key
393             if [ ! -f $PLC_ROOT_SSH_KEY_PUB -o ! -f $PLC_ROOT_SSH_KEY ] ; then
394                 ssh-keygen -N "" -C "$PLC_NAME Central <$PLC_MAIL_SUPPORT_ADDRESS>" \
395                     -b $KEY_LEN_ROOT -t $KEY_TYPE_ROOT -f $tmp/root
396                 RETVAL=$(($RETVAL+$?))
397                 install -D -m 600 $tmp/root $PLC_ROOT_SSH_KEY
398                 install -D -m 600 $tmp/root.pub $PLC_ROOT_SSH_KEY_PUB
399             fi
400
401             # Generate debug SSH key
402             if [ ! -f $PLC_DEBUG_SSH_KEY_PUB -o ! -f $PLC_DEBUG_SSH_KEY ] ; then
403                 ssh-keygen -N "" -C "$PLC_NAME Central <$PLC_MAIL_SUPPORT_ADDRESS>" \
404                     -b $KEY_LEN_DEBUG -t $KEY_TYPE_DEBUG -f $tmp/debug
405                 RETVAL=$(($RETVAL+$?))
406                 install -D -m 600 $tmp/debug $PLC_DEBUG_SSH_KEY
407                 install -D -m 600 $tmp/debug.pub $PLC_DEBUG_SSH_KEY_PUB
408             fi
409
410             rm -rf $tmp
411             ;;
412     esac
413 }
414
415 # Configure Apache web server
416 config_apache ()
417 {
418     # Default locations
419     DocumentRoot=/var/www/html
420     php_ini=/etc/php.ini
421     httpd_conf=/etc/httpd/conf/httpd.conf
422     ssl_conf=/etc/httpd/conf.d/ssl.conf
423     plc_conf=/etc/httpd/conf.d/plc.conf
424
425     case "$1" in
426         start)
427             if [ "$PLC_API_ENABLED" != "1" -a \
428                  "$PLC_BOOT_ENABLED" != "1" -a \
429                  "$PLC_WWW_ENABLED" != "1" ] ; then
430                 return 0
431             fi
432
433             # Set the default include path
434             include_path=".:$DocumentRoot/includes:$DocumentRoot/generated:/etc/planetlab/php"
435             sed -i -e "s@;include_path = \"\.:.*\"@include_path = \"$include_path\"@" $php_ini
436
437             # Set the port numbers. If the API, boot, and web servers
438             # are all running on the same machine, the web server port
439             # numbers take precedence.
440             for server in API BOOT WWW ; do
441                 eval enabled=\${PLC_${server}_ENABLED}
442                 if [ "$enabled" != "1" ] ; then
443                     continue
444                 fi
445                 eval http_port=\${PLC_${server}_PORT}
446                 eval https_port=\${PLC_${server}_SSL_PORT}
447
448                 if [ -n "$http_port" ] ; then
449                     sed -i -e "s/^Listen .*/Listen $http_port/" $httpd_conf
450                 fi
451                 if [ -n "$https_port" ] ; then
452                     sed -i -e "s/^Listen .*/Listen $https_port/" $ssl_conf
453                 fi
454             done
455                     
456             # Set custom Apache directives
457             (
458                 if [ "$PLC_API_ENABLED" = "1" ] ; then
459                     cat <<EOF
460 <Location $PLC_API_PATH>
461     SetHandler python-program
462     PythonPath "sys.path + ['/usr/share/plc_api']"
463     PythonHandler mod_pythonXMLRPC
464 </Location>
465 EOF
466                 fi
467
468                 cat <<EOF
469 <VirtualHost $PLC_WWW_HOST:$PLC_WWW_PORT>
470     Redirect /db https://$PLC_WWW_HOST:$PLC_WWW_SSL_PORT/db
471 </VirtualHost>
472 EOF
473             ) >$plc_conf
474
475             # Make alpina-logs directory writable for bootmanager log upload
476             chown apache:apache $DocumentRoot/alpina-logs/nodes
477
478             service httpd start
479             RETVAL=$?
480             ;;
481
482         stop)
483             service httpd stop
484             RETVAL=$?
485             ;;
486     esac
487 }
488
489 config_api ()
490 {
491     case "$1" in
492         start)
493             if [ "$PLC_API_ENABLED" -ne 1 ] ; then
494                 return
495             fi
496
497             # Update the maintenance account username. This can't be
498             # done through the api-config script since it uses the
499             # maintenance account to access the API. The maintenance
500             # account should be person_id 1 since it is created by the
501             # DB schema itself.
502             psql -U $PLC_DB_USER -c "UPDATE persons SET email='$PLC_API_MAINTENANCE_USER' WHERE person_id=1" $PLC_DB_NAME
503
504             # Bootstrap the DB
505             api-config
506             RETVAL=$?
507             ;;
508     esac
509 }
510
511 config_cron ()
512 {
513     case "$1" in
514         start)
515             cat >/etc/cron.d/plc.cron <<EOF
516 SHELL=/bin/bash
517 PATH=/sbin:/bin:/usr/sbin:/usr/bin
518 MAILTO=$PLC_MAIL_SUPPORT_ADDRESS
519 HOME=/
520
521 # minute hour day-of-month month day-of-week user command
522 */5 * * * * root gen-slices-xml-05.py
523 */15 * * * * root gen-sites-xml.py
524 */15 * * * * root gen-static-content.py
525 EOF
526
527             # Run them once at startup
528             gen-slices-xml-05.py
529             gen-sites-xml.py
530             gen-static-content.py
531
532             service crond start
533             RETVAL=$?
534             ;;
535
536         stop)
537             service crond stop
538             RETVAL=$?
539             ;;
540     esac
541 }
542
543 usage()
544 {
545     echo "Usage: $0 [OPTION]... [COMMAND]"
546     echo "      -v              Be verbose"
547     echo "      -h              This message"
548     echo
549     echo "Commands:"
550     echo "      start           Start all PLC subsystems"
551     echo "      stop            Stop all PLC subsystems"
552     echo "      reload          Regenerate configuration files"
553     echo "      restart         Restart all PLC subsystems"
554     exit 1
555 }
556
557 # Get options
558 while getopts "vh" opt ; do
559     case $opt in
560         v)
561             verbose=1
562             set -x
563             ;;
564         h|*)
565             usage
566             ;;
567     esac
568 done
569
570 shift $(($OPTIND - 1))
571 if [ -z "$1" ] ; then
572     usage
573 fi
574
575 exec 3>&1
576 exec 4>&2
577 if [ $verbose -eq 0 ] ; then
578     exec 1>/dev/null
579     exec 2>/dev/null
580 fi
581
582 # Generate and load configuration
583 reload
584 . /etc/planetlab/plc_config
585
586 RETVAL=0
587
588 start ()
589 {
590     for step in "${steps[@]}" ; do
591         echo -n $"PLC: Starting $step: " >&3
592         RETVAL=0
593         config_$step start
594         if [ $RETVAL -eq 0 ] ; then
595             success $"PLC: $step startup" >&3
596         else
597             failure $"PLC: $step startup" >&3
598         fi
599         echo >&3
600     done
601 }
602
603 stop ()
604 {
605     for i in $(seq 1 $nsteps) ; do
606         step=${steps[$(($nsteps - $i))]}
607         echo -n $"PLC: Shutting down $step: " >&3
608         RETVAL=0
609         config_$step stop
610         if [ $RETVAL -eq 0 ] ; then
611             success $"PLC: $step shutdown" >&3
612         else
613             failure $"PLC: $step shutdown" >&3
614         fi
615         echo >&3
616     done
617 }
618
619 case "$1" in
620     start|stop)
621         $1
622         ;;
623
624     restart)
625         stop
626         start
627         ;;
628
629     reload)
630         ;;
631
632     *)
633         usage >&3
634         ;;
635 esac
636
637 exit $RETVAL