add support for migrations with sqlalchemy-migrate
[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     if [ -n "$1" ] ; then suffix="-$1" ; else suffix="" ; fi
68     dumpfile=/var/lib/pgsql/backups/$(date +"${SFA_DB_NAME}.${DATE}${suffix}.sql")
69     pg_dump -U $SFA_DB_USER $SFA_DB_NAME > $dumpfile
70     check
71 }
72
73 # Updates the database by applying migration scripts
74 # using sqlalchemy-migrate for this 
75 # migrate repo is /usr/share/sfa/migrations/
76 # and version scripts are thus in /usr/share/sfa/migrations/versions/
77 function db_migrate() {
78
79     # only if enabled
80     [ "$SFA_DB_ENABLED" == 1 ] || return
81
82     alchemy_url="postgresql+psycopg2://${SFA_DB_USER}:${SFA_DB_PASSWORD}@:${SFA_DB_PORT}/${SFA_DB_NAME}"
83     migrate_repo="/usr/share/sfa/migrations"
84     # check if under version control, and initialize it otherwise
85     if ! sqlalchemy-migrate db_version --url=$alchemy_url $migrate_repo >& /dev/null ; then
86         # at this point it would make sense to
87         # check that the 'users' table is in the db
88         # if not, backup/dump, and run a nuke/import
89         # and then only init the db version to 0
90         echo -n $"version init in db ${SFA_DB_NAME}" 
91         sqlalchemy-migrate version_control --url=$alchemy_url $migrate_repo 
92     fi
93     version_before=$(sqlalchemy-migrate db_version --url=$alchemy_url $migrate_repo)
94     check
95     sqlalchemy-migrate upgrade --url=$alchemy_url $migrate_repo 2> /dev/null
96     check
97     version_after=$(sqlalchemy-migrate db_version --url=$alchemy_url $migrate_repo)
98     if [ "$version_before" != "$version_after" -o "$ERRORS" != 0 ] ; then
99         MESSAGE=$"DB version: $version_before -> $version_after"
100         echo -n "$MESSAGE"
101         [ "$ERRORS" == 0 ] && success "$MESSAGE" || failure "$MESSAGE" ; echo
102     fi
103 }
104
105 # Regenerate configuration files - almost verbatim from plc.init
106 function reload () {
107     force=$1
108
109     # Regenerate the main configuration file from default values
110     # overlaid with site-specific and current values.
111     # Thierry -- 2007-07-05 : values in plc_config.xml are *not* taken into account here
112     files=( $sfa_default_config $sfa_local_config )
113     for file in "${files[@]}" ; do
114         if [ -n "$force" -o $file -nt $sfa_whole_config ] ; then
115             tmp=$(mktemp /tmp/sfa_config.xml.XXXXXX)
116             plc-config --xml "${files[@]}" >$tmp
117             if [ $? -eq 0 ] ; then
118                 mv $tmp $sfa_whole_config
119                 chmod 444 $sfa_whole_config
120             else
121                 echo "SFA: Warning: Invalid configuration file(s) detected"
122                 rm -f $tmp
123             fi
124             break
125         fi
126     done
127
128     # Convert configuration to various formats
129     if [ -n "$force" -o $sfa_whole_config -nt /etc/sfa/sfa_config ] ; then
130         plc-config --shell $sfa_whole_config > /etc/sfa/sfa_config
131     fi
132     if [ -n "$force" -o $sfa_whole_config -nt /etc/sfa/sfa_config.py ] ; then
133         plc-config --python $sfa_whole_config > /etc/sfa/sfa_config.py
134     fi
135 #    if [ -n "$force" -o $sfa_whole_config -nt /etc/sfa/php/sfa_config.php ] ; then
136 #       mkdir -p /etc/sfa/php
137 #       plc-config --php  $sfa_whole_config >/etc/sfa/php/sfa_config.php
138 #    fi
139
140     # [re]generate the sfa_component_config
141     # this is a server-side thing but produces a file that somehow needs to be pushed
142     # on the planetlab nodes; in the case where sfa and myplc run on different boxes 
143     # (or there is no myplc at all) this should be turned off
144     # as the component manager is not operational yet we skip this for now
145     #gen-sfa-cm-config.py        
146
147     # reload the shell version
148     [ -f /etc/sfa/sfa_config ] && . /etc/sfa/sfa_config
149
150 }
151
152 ### initialize DB (don't chkconfig postgresql on)
153 function db_start () {
154     
155     # only if enabled
156     [ "$SFA_DB_ENABLED" == 1 ] || return
157
158     if ! rpm -q myplc >& /dev/null; then
159
160         ######## standalone deployment - no colocated myplc
161
162         ######## sysconfig 
163         # Set data directory and redirect startup output to /var/log/pgsql
164         mkdir -p $(dirname $postgresql_sysconfig)
165         # remove previous definitions
166         touch $postgresql_sysconfig
167         tmp=${postgresql_sysconfig}.new
168         ( egrep -v '^(PGDATA=|PGLOG=|PGPORT=)' $postgresql_sysconfig 
169             echo "PGDATA=$PGDATA"
170             echo "PGLOG=/var/log/pgsql"
171             echo "PGPORT=$SFA_DB_PORT"
172         ) >> $tmp ; mv -f $tmp $postgresql_sysconfig
173
174         ######## /var/lib/pgsql/data 
175         # Fix ownership (rpm installation may have changed it)
176         chown -R -H postgres:postgres $(dirname $PGDATA)
177
178         # PostgreSQL must be started at least once to bootstrap
179         # /var/lib/pgsql/data
180         if [ ! -f $postgresql_conf ] ; then
181             service postgresql initdb &> /dev/null || :
182             check
183         fi
184
185         ######## /var/lib/pgsql/data/postgresql.conf
186         registry_ip=""
187         foo=$(python -c "import socket; print socket.gethostbyname(\"$SFA_REGISTRY_HOST\")") && registry_ip="$foo"
188         # Enable DB server. drop Postgresql<=7.x
189         # PostgreSQL >=8.0 defines listen_addresses
190         # listen on a specific IP + localhost, more robust when run within a vserver
191         sed -i -e '/^listen_addresses/d' $postgresql_conf
192         if [ -z "$registry_ip" ] ; then
193             echo "listen_addresses = 'localhost'" >> $postgresql_conf
194         else
195             echo "listen_addresses = '${registry_ip},localhost'" >> $postgresql_conf
196         fi
197         # tweak timezone to be 'UTC'
198         sed -i -e '/^timezone=/d' $postgresql_conf
199         echo "timezone='UTC'" >> $postgresql_conf
200
201         ######## /var/lib/pgsql/data/pg_hba.conf
202         # Disable access to all DBs from all hosts
203         sed -i -e '/^\(host\|local\)/d' $pghba_conf
204
205         # Enable passwordless localhost access
206         echo "local all all trust" >>$pghba_conf
207         # grant access
208         (
209             echo "host $SFA_DB_NAME $SFA_DB_USER 127.0.0.1/32 password"
210             [ -n "$registry_ip" ] && echo "host $SFA_DB_NAME $SFA_DB_USER ${registry_ip}/32 password"
211         ) >>$pghba_conf
212
213     if [ "$SFA_GENERIC_FLAVOUR" == "openstack" ] ; then
214         [ -n "$registry_ip" ] && echo "host nova nova ${registry_ip}/32 password" >> $pghba_conf
215     fi   
216         
217         # Fix ownership (sed -i changes it)
218         chown postgres:postgres $postgresql_conf $pghba_conf
219
220         ######## compute a password if needed
221         if [ -z "$SFA_DB_PASSWORD" ] ; then
222             SFA_DB_PASSWORD=$(uuidgen)
223             plc-config --category=sfa_db --variable=password --value="$SFA_DB_PASSWORD" --save=$sfa_local_config $sfa_local_config >& /dev/null
224             reload force
225         fi
226
227     else
228
229         ######## we are colocated with a myplc
230         # no need to worry about the pgsql setup (see /etc/plc.d/postgresql)
231         # myplc enforces the password for its user
232         PLC_DB_USER=$(plc-config --category=plc_db --variable=user)
233         PLC_DB_PASSWORD=$(plc-config --category=plc_db --variable=password)
234         # store this as the SFA user/password 
235         plc-config --category=sfa_db --variable=user --value=$PLC_DB_USER --save=$sfa_local_config $sfa_local_config >& /dev/null
236         plc-config --category=sfa_db --variable=password --value=$PLC_DB_PASSWORD --save=$sfa_local_config $sfa_local_config >& /dev/null
237         reload force
238     fi
239
240     ######## Start up the server
241     # not too nice, but.. when co-located with myplc we'll let it start/stop postgresql
242     if ! rpm -q myplc >& /dev/null ; then
243         echo STARTING...
244         service postgresql start >& /dev/null
245     fi
246     postgresql_check
247     check
248         
249     ######## make sure we have the user and db created
250     # user
251     if ! psql -U $SFA_DB_USER -c "" template1 >/dev/null 2>&1 ; then
252         psql -U postgres -c "CREATE USER $SFA_DB_USER PASSWORD '$SFA_DB_PASSWORD'" template1 >& /dev/null
253     else
254         psql -U postgres -c "ALTER USER $SFA_DB_USER WITH PASSWORD '$SFA_DB_PASSWORD'" template1 >& /dev/null
255     fi
256     check
257     
258     # db
259     if ! psql -U $SFA_DB_USER -c "" $SFA_DB_NAME >/dev/null 2>&1 ; then
260         createdb -U postgres --template=template0 --encoding=UNICODE --owner=$SFA_DB_USER $SFA_DB_NAME
261         check
262     fi
263     check
264
265     MESSAGE=$"Checking for PostgreSQL server"
266     echo -n "$MESSAGE"
267     [ "$ERRORS" == 0 ] && success "$MESSAGE" || failure "$MESSAGE" ; echo
268 }
269
270 # shutdown DB
271 function db_stop () {
272
273     # only if enabled
274     [ "$SFA_DB_ENABLED" == 1 ] || return
275
276     # not too nice, but.. when co-located with myplc we'll let it start/stop postgresql
277     if ! rpm -q myplc >& /dev/null ; then
278         service postgresql stop >& /dev/null
279         check
280         MESSAGE=$"Stopping PostgreSQL server"
281         echo -n "$MESSAGE"
282         [ "$ERRORS" == 0 ] && success "$MESSAGE" || failure "$MESSAGE" ; echo
283     fi
284 }
285
286 function start() {
287     
288     reload
289
290     db_start
291     db_migrate
292
293     # install peer certs
294     action $"SFA installing peer certs" daemon /usr/bin/sfa-start.py -t -d $OPTIONS 
295
296     [ "$SFA_REGISTRY_ENABLED" == 1 ] && action $"SFA Registry" daemon /usr/bin/sfa-start.py -r -d $OPTIONS
297     
298     [ "$SFA_AGGREGATE_ENABLED" == 1 ] && action $"SFA Aggregate" daemon /usr/bin/sfa-start.py -a -d $OPTIONS
299         
300     [ "$SFA_SM_ENABLED" == 1 ] && action "SFA SliceMgr" daemon /usr/bin/sfa-start.py -s -d $OPTIONS
301
302     [ "$SFA_FLASHPOLICY_ENABLED" == 1 ] && \
303         action "Flash Policy Server" daemon /usr/bin/sfa_flashpolicy.py --file="$SFA_FLASHPOLICY_CONFIG_FILE" --port=$SFA_FLASHPOLICY_PORT -d
304
305     touch /var/lock/subsys/sfa-start.py
306
307 }
308
309 function stop() {
310     action $"Shutting down SFA" killproc sfa-start.py
311
312     db_stop
313
314     rm -f /var/lock/subsys/sfa-start.py
315 }
316
317
318 case "$1" in
319     start) start ;;
320     stop) stop ;;
321     reload) reload force ;;
322     restart) stop; start ;;
323     condrestart)
324         if [ -f /var/lock/subsys/sfa-start.py ]; then
325             stop
326             start
327         fi
328         ;;
329     status)
330         status sfa-start.py
331         RETVAL=$?
332         ;;
333     *)
334         echo $"Usage: $0 {start|stop|reload|restart|condrestart|status}"
335         exit 1
336         ;;
337 esac
338
339 exit $RETVAL
340