migrations need to kick in
[sfa.git] / init.d / sfa
1 #!/bin/bash
2 #
3 # sfa   Wraps PLCAPI into the SFA compliant API
4 #
5 # hopefully right after plc
6 # chkconfig: 2345 61 39
7 #
8 # description:   Wraps PLCAPI into the SFA compliant API
9 #
10
11 # source function library
12 . /etc/init.d/functions
13
14 # Default locations
15 PGDATA=/var/lib/pgsql/data
16 postgresql_conf=$PGDATA/postgresql.conf
17 pghba_conf=$PGDATA/pg_hba.conf
18 postgresql_sysconfig=/etc/sysconfig/pgsql
19
20 # PLC consolidated (merged) config file
21 plc_whole_config=/etc/planetlab/plc_config.xml
22 # SFA consolidated (merged) config file
23 sfa_whole_config=/etc/sfa/sfa_config.xml
24 # SFA default config (read-only template)
25 sfa_default_config=/etc/sfa/default_config.xml
26 # SFA local (site-dependent) file
27 sfa_local_config=/etc/sfa/configs/site.xml
28
29 # Source sfa shell config if present 
30 [ -f /etc/sfa/sfa_config ] && . /etc/sfa/sfa_config
31
32 # Export so that we do not have to specify -p to psql invocations
33 export PGPORT=$SFA_DB_PORT
34
35 ##########
36 # Total number of errors
37 ERRORS=0
38
39 # Count the exit status of the last command
40 check ()
41 {
42     ERRORS=$(($ERRORS+$?))
43 }
44
45 # can't trust the return of service postgresql start / nor status
46 function postgresql_check () {
47
48     # wait until postmaster is up and running - or 10s max
49     if status postmaster >& /dev/null && [ -f /var/lock/subsys/postgresql ] ; then
50         # The only way we can be sure is if we can access it
51         for i in $(seq 1 10) ; do
52             # Must do this as the postgres user initially (before we
53             # fix pg_hba.conf to passwordless localhost access).
54             su -c 'psql -U postgres -c "" template1' postgres && return 0
55             sleep 1
56         done
57     fi
58
59     return 1
60 }
61
62 # use a single date of this script invocation for the dump_*_db functions.
63 DATE=$(date +"%Y-%m-%d-%H-%M-%S")
64
65 # Dumps the database - optional argument to specify filename suffix
66 function dump_sfa_db()
67 {
68     if [ -n "$1" ] ; then suffix="-$1" ; else suffix="" ; fi
69     dumpfile=/var/lib/pgsql/backups/$(date +"${SFA_DB_NAME}.${DATE}${suffix}.sql")
70     pg_dump -U $SFA_DB_USER $SFA_DB_NAME > $dumpfile
71     check
72 }
73
74 # Updates the database by applying all migration scripts in
75 # /usr/share/sfa/migrations/N-up-*, where N is greater than the
76 # current subversion. At least one of the migration scripts with the
77 # same N must update sfa_db_version.subversion.
78 function migrate_db()
79 {
80     subversion=$(psql -U $SFA_DB_USER --quiet --tuples-only --no-align -c \
81                  "SELECT subversion FROM sfa_db_version LIMIT 1" \
82                  $SFA_DB_NAME 2>/dev/null || echo 0)
83     shopt -s nullglob
84     for file in /usr/share/sfa/migrations/[0-9]*-up-* ; do
85         script=$(basename $file)
86         index=${script%-up*}
87         extension=${script##*.}
88         if [ $index -gt $subversion ] ; then
89             if [ "$extension" = "sql" ] ; then
90                 dialog " - $script (dbdumped)"
91                 dump_sfa_db "before-$script"
92                 psql -U $SFA_DB_USER -f $file $SFA_DB_NAME
93             elif [ -x $file ] ; then
94                 dialog " - $script (dbdumped)"
95                 dump_sfa_db "before-$script"
96                 $file
97             else
98                 dialog "\nWarning: migration $file not executable"
99             fi
100             check
101         fi
102     done
103 }
104
105
106
107 # Regenerate configuration files - almost verbatim from plc.init
108 function reload () {
109     force=$1
110
111     # Regenerate the main configuration file from default values
112     # overlaid with site-specific and current values.
113     # Thierry -- 2007-07-05 : values in plc_config.xml are *not* taken into account here
114     files=( $sfa_default_config $sfa_local_config )
115     for file in "${files[@]}" ; do
116         if [ -n "$force" -o $file -nt $sfa_whole_config ] ; then
117             tmp=$(mktemp /tmp/sfa_config.xml.XXXXXX)
118             plc-config --xml "${files[@]}" >$tmp
119             if [ $? -eq 0 ] ; then
120                 mv $tmp $sfa_whole_config
121                 chmod 444 $sfa_whole_config
122             else
123                 echo "SFA: Warning: Invalid configuration file(s) detected"
124                 rm -f $tmp
125             fi
126             break
127         fi
128     done
129
130     # Convert configuration to various formats
131     if [ -n "$force" -o $sfa_whole_config -nt /etc/sfa/sfa_config ] ; then
132         plc-config --shell $sfa_whole_config > /etc/sfa/sfa_config
133     fi
134     if [ -n "$force" -o $sfa_whole_config -nt /etc/sfa/sfa_config.py ] ; then
135         plc-config --python $sfa_whole_config > /etc/sfa/sfa_config.py
136     fi
137 #    if [ -n "$force" -o $sfa_whole_config -nt /etc/sfa/php/sfa_config.php ] ; then
138 #       mkdir -p /etc/sfa/php
139 #       plc-config --php  $sfa_whole_config >/etc/sfa/php/sfa_config.php
140 #    fi
141
142     # [re]generate the sfa_component_config
143     # this is a server-side thing but produces a file that somehow needs to be pushed
144     # on the planetlab nodes; in the case where sfa and myplc run on different boxes 
145     # (or there is no myplc at all) this should be turned off
146     # as the component manager is not operational yet we skip this for now
147     #gen-sfa-cm-config.py        
148
149     # reload the shell version
150     [ -f /etc/sfa/sfa_config ] && . /etc/sfa/sfa_config
151
152 }
153
154 ### initialize DB (don't chkconfig postgresql on)
155 function db_start () {
156     
157     # only if enabled
158     [ "$SFA_DB_ENABLED" == 1 ] || return
159
160     if ! rpm -q myplc >& /dev/null; then
161
162         ######## standalone deployment - no colocated myplc
163
164         ######## sysconfig 
165         # Set data directory and redirect startup output to /var/log/pgsql
166         mkdir -p $(dirname $postgresql_sysconfig)
167         # remove previous definitions
168         touch $postgresql_sysconfig
169         tmp=${postgresql_sysconfig}.new
170         ( egrep -v '^(PGDATA=|PGLOG=|PGPORT=)' $postgresql_sysconfig 
171             echo "PGDATA=$PGDATA"
172             echo "PGLOG=/var/log/pgsql"
173             echo "PGPORT=$SFA_DB_PORT"
174         ) >> $tmp ; mv -f $tmp $postgresql_sysconfig
175
176         ######## /var/lib/pgsql/data 
177         # Fix ownership (rpm installation may have changed it)
178         chown -R -H postgres:postgres $(dirname $PGDATA)
179
180         # PostgreSQL must be started at least once to bootstrap
181         # /var/lib/pgsql/data
182         if [ ! -f $postgresql_conf ] ; then
183             service postgresql initdb &> /dev/null || :
184             check
185         fi
186
187         ######## /var/lib/pgsql/data/postgresql.conf
188         registry_ip=""
189         foo=$(python -c "import socket; print socket.gethostbyname(\"$SFA_REGISTRY_HOST\")") && registry_ip="$foo"
190         # Enable DB server. drop Postgresql<=7.x
191         # PostgreSQL >=8.0 defines listen_addresses
192         # listen on a specific IP + localhost, more robust when run within a vserver
193         sed -i -e '/^listen_addresses/d' $postgresql_conf
194         if [ -z "$registry_ip" ] ; then
195             echo "listen_addresses = 'localhost'" >> $postgresql_conf
196         else
197             echo "listen_addresses = '${registry_ip},localhost'" >> $postgresql_conf
198         fi
199         # tweak timezone to be 'UTC'
200         sed -i -e '/^timezone=/d' $postgresql_conf
201         echo "timezone='UTC'" >> $postgresql_conf
202
203         ######## /var/lib/pgsql/data/pg_hba.conf
204         # Disable access to all DBs from all hosts
205         sed -i -e '/^\(host\|local\)/d' $pghba_conf
206
207         # Enable passwordless localhost access
208         echo "local all all trust" >>$pghba_conf
209         # grant access
210         (
211             echo "host $SFA_DB_NAME $SFA_DB_USER 127.0.0.1/32 password"
212             [ -n "$registry_ip" ] && echo "host $SFA_DB_NAME $SFA_DB_USER ${registry_ip}/32 password"
213         ) >>$pghba_conf
214         
215         # Fix ownership (sed -i changes it)
216         chown postgres:postgres $postgresql_conf $pghba_conf
217
218         ######## compute a password if needed
219         if [ -z "$SFA_DB_PASSWORD" ] ; then
220             SFA_DB_PASSWORD=$(uuidgen)
221             plc-config --category=sfa_db --variable=password --value="$SFA_DB_PASSWORD" --save=$sfa_local_config $sfa_local_config >& /dev/null
222             reload force
223         fi
224
225     else
226
227         ######## we are colocated with a myplc
228         # no need to worry about the pgsql setup (see /etc/plc.d/postgresql)
229         # myplc enforces the password for its user
230         PLC_DB_USER=$(plc-config --category=plc_db --variable=user)
231         PLC_DB_PASSWORD=$(plc-config --category=plc_db --variable=password)
232         # store this as the SFA user/password 
233         plc-config --category=sfa_db --variable=user --value=$PLC_DB_USER --save=$sfa_local_config $sfa_local_config >& /dev/null
234         plc-config --category=sfa_db --variable=password --value=$PLC_DB_PASSWORD --save=$sfa_local_config $sfa_local_config >& /dev/null
235         reload force
236     fi
237
238     ######## Start up the server
239     # not too nice, but.. when co-located with myplc we'll let it start/stop postgresql
240     if ! rpm -q myplc >& /dev/null ; then
241         echo STARTING...
242         service postgresql start >& /dev/null
243     fi
244     postgresql_check
245     check
246         
247     ######## make sure we have the user and db created
248     # user
249     if ! psql -U $SFA_DB_USER -c "" template1 >/dev/null 2>&1 ; then
250         psql -U postgres -c "CREATE USER $SFA_DB_USER PASSWORD '$SFA_DB_PASSWORD'" template1 >& /dev/null
251     else
252         psql -U postgres -c "ALTER USER $SFA_DB_USER WITH PASSWORD '$SFA_DB_PASSWORD'" template1 >& /dev/null
253     fi
254     check
255     
256     # db
257     if ! psql -U $SFA_DB_USER -c "" $SFA_DB_NAME >/dev/null 2>&1 ; then
258         createdb -U postgres --template=template0 --encoding=UNICODE --owner=$SFA_DB_USER $SFA_DB_NAME
259         check
260         # install db schema
261         psql -U $SFA_DB_USER -f /usr/share/sfa/sfa.sql $SFA_DB_NAME
262         check
263     fi
264     check
265
266     MESSAGE=$"Checking for PostgreSQL server"
267     echo -n "$MESSAGE"
268     [ "$ERRORS" == 0 ] && success "$MESSAGE" || failure "$MESSAGE" ; echo
269 }
270
271 # shutdown DB
272 function db_stop () {
273
274     # only if enabled
275     [ "$SFA_DB_ENABLED" == 1 ] || return
276
277     # not too nice, but.. when co-located with myplc we'll let it start/stop postgresql
278     if ! rpm -q myplc >& /dev/null ; then
279         service postgresql stop >& /dev/null
280         check
281         MESSAGE=$"Stopping PostgreSQL server"
282         echo -n "$MESSAGE"
283         [ "$ERRORS" == 0 ] && success "$MESSAGE" || failure "$MESSAGE" ; echo
284     fi
285 }
286
287 function start() {
288     
289     reload
290
291     db_start
292
293     migrate_db
294
295     # install peer certs
296     action $"SFA installing peer certs" daemon /usr/bin/sfa-start.py -t -d $OPTIONS 
297
298     [ "$SFA_REGISTRY_ENABLED" == 1 ] && action $"SFA Registry" daemon /usr/bin/sfa-start.py -r -d $OPTIONS
299     
300     [ "$SFA_AGGREGATE_ENABLED" == 1 ] && action $"SFA Aggregate" daemon /usr/bin/sfa-start.py -a -d $OPTIONS
301         
302     [ "$SFA_SM_ENABLED" == 1 ] && action "SFA SliceMgr" daemon /usr/bin/sfa-start.py -s -d $OPTIONS
303
304     [ "$SFA_FLASHPOLICY_ENABLED" == 1 ] && \
305         action "Flash Policy Server" daemon /usr/bin/sfa_flashpolicy.py --file="$SFA_FLASHPOLICY_CONFIG_FILE" --port=$SFA_FLASHPOLICY_PORT -d
306
307     touch /var/lock/subsys/sfa-start.py
308
309 }
310
311 function stop() {
312     action $"Shutting down SFA" killproc sfa-start.py
313
314     db_stop
315
316     rm -f /var/lock/subsys/sfa-start.py
317 }
318
319
320 case "$1" in
321     start) start ;;
322     stop) stop ;;
323     reload) reload force ;;
324     restart) stop; start ;;
325     condrestart)
326         if [ -f /var/lock/subsys/sfa-start.py ]; then
327             stop
328             start
329         fi
330         ;;
331     status)
332         status sfa-start.py
333         RETVAL=$?
334         ;;
335     *)
336         echo $"Usage: $0 {start|stop|reload|restart|condrestart|status}"
337         exit 1
338         ;;
339 esac
340
341 exit $RETVAL
342