1#! /bin/sh
2### BEGIN INIT INFO
3# Provides:
4# Required-Start:
5# Required-Stop:
6# Default-Start:
7# Default-Stop:
8# Short-Description: Starts and stops the iSCSI initiator services and logins to default targets
9### END INIT INFO
10#set -x
11PATH=/sbin:/bin:/usr/sbin:/usr/bin
12DAEMON=/usr/sbin/iscsid
13ADM=/usr/sbin/iscsiadm
14PIDFILE=/var/run/iscsid.pid
15
16[ -x "$DAEMON" ] || exit 0
17
18if [ ! -d /sys/class/ ]; then
19  echo "Failure:" "iSCSI requires a mounted sysfs, not started."
20  exit 1
21fi
22
23nodestartup_re='s/^node\.conn\[0]\.startup[ 	]*=[ 	]*//p'
24
25RETVAL=0
26
27start() {
28	echo "Starting iSCSI initiator service" "iscsid"
29	modprobe -q iscsi_tcp 2>/dev/null || :
30	modprobe -q ib_iser 2>/dev/null || :
31	if [ ! -f /etc/iscsi/initiatorname.iscsi ]; then
32		INITIATORNAME=$(iscsi-iname)
33		cat >/etc/iscsi/initiatorname.iscsi <<EOF
34## DO NOT EDIT OR REMOVE THIS FILE!
35## If you remove this file, the iSCSI daemon will not start.
36## If you change the InitiatorName, existing access control lists
37## may reject this initiator.  The InitiatorName must be unique
38## for each iSCSI initiator.  Do NOT duplicate iSCSI InitiatorNames.
39InitiatorName=$INITIATORNAME
40EOF
41	fi
42	start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON
43	RETVAL=$?
44	starttargets
45}
46
47starttargets() {
48	echo "Setting up iSCSI targets"
49	$ADM -m node --loginall=automatic
50}
51
52stoptargets() {
53	echo "Disconnecting iSCSI targets"
54	sync
55	$ADM -m node --logoutall=all
56	RETVAL=$?
57	#if RETVAL is 21, means no active sessions, consider ok
58	if [ "$RETVAL" = "21" ]; then
59		RETVAL=0
60	fi
61}
62
63stop() {
64	stoptargets
65	if [ $RETVAL -ne 0 ]; then
66		echo "Failure:" "Could not stop all targets, try again later"
67		return $RETVAL
68	fi
69
70	echo "Stopping iSCSI initiator service"
71	start-stop-daemon --stop --quiet --pidfile $PIDFILE --exec $DAEMON
72	rm -f $PIDFILE
73	status=0
74	modprobe -r ib_iser 2>/dev/null
75	if [ "$?" -ne "0" -a "$?" -ne "1" ]; then
76		status=1
77	fi
78	modprobe -r iscsi_tcp 2>/dev/null
79	if [ "$?" -ne "0" -a "$?" -ne "1" ]; then
80		status=1
81	fi
82}
83
84restart() {
85	stop
86	if [ $RETVAL -ne 0 ]; then
87		echo "Failure:" "Stopping iSCSI initiator service failed, not starting"
88		return $RETVAL
89	fi
90	start
91}
92
93restarttargets() {
94	stoptargets
95	if [ $RETVAL -ne 0 ]; then
96		echo "Failure:" "Could not stop all targets, try again later"
97		return $RETVAL
98	fi
99	starttargets
100}
101
102status() {
103	#XXX FIXME: what to do here?
104	#status iscsid
105	# list active sessions
106	echo Current active iSCSI sessions:
107	$ADM -m session
108}
109
110case "$1" in
111	start|starttargets|stop|stoptargets|restart|restarttargets|status)
112		$1
113		;;
114	*)
115		echo "Usage: $0 {start|stop|restart|status}"
116		exit 1
117		;;
118esac
119exit $RETVAL
120