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