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