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