2 # -*- coding: utf-8 -*-
4 # This file is part of Karesansui.
6 # Copyright (C) 2010 HDE, Inc.
8 # This program is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU General Public License
10 # as published by the Free Software Foundation; either version 2
11 # of the License, or (at your option) any later version.
18 from optparse import OptionParser
20 from ksscommand import KssCommand, KssCommandException, KssCommandOptException
25 from karesansui import __version__
26 from karesansui.lib.utils import load_locale, execute_command
27 from karesansui.lib.iscsi import iscsi_parse_session
28 from karesansui.lib.const import ISCSI_CMD, \
29 ISCSI_CMD_OPTION_MODE, ISCSI_CMD_OPTION_MODE_SESSION, \
30 ISCSI_CMD_OPTION_MODE_NODE, ISCSI_CMD_OPTION_TARGETNAME, \
31 ISCSI_CMD_OPTION_PORTAL, ISCSI_CMD_OPTION_LOGIN, \
32 ISCSI_CMD_RES_NO_ACTIVE_SESSION
35 print >>sys.stderr, "[Error] karesansui package was not found."
40 usage = '%prog [options]'
43 optp = OptionParser(usage=usage, version=__version__)
44 optp.add_option('-t', '--target', dest='host', help=_('Target host name'), default=None)
45 optp.add_option('-i', '--iqn', dest='iqn', help=_('Target IQN'), default=None)
46 return optp.parse_args()
49 reg = re.compile("[^a-zA-Z0-9\._:-]")
52 if reg.search(opts.iqn):
53 raise KssCommandOptException('ERROR: Illigal option value. option=%s value=%s' % ('-i or --iqn', opts.iqn))
55 raise KssCommandOptException('ERROR: %s option is required.' % '-i or --iqn')
58 if reg.search(opts.host):
59 raise KssCommandOptException('ERROR: Illigal option value. option=%s value=%s' % ('-t or --target', opts.host))
61 class StartIscsi(KssCommand):
64 (opts, args) = getopts()
70 session_command_args = (ISCSI_CMD,
71 ISCSI_CMD_OPTION_MODE,
72 ISCSI_CMD_OPTION_MODE_SESSION
75 (session_rc, session_res) = execute_command(session_command_args)
77 raise KssCommandException('Failed to get iSCSI session. message=%s' % (session_res))
79 for session_line in session_res:
83 if session_line.find(ISCSI_CMD_RES_NO_ACTIVE_SESSION) != -1:
86 session = iscsi_parse_session(session_line)
87 if session['iqn'] == opts.iqn:
89 if opts.host != session['hostname']:
95 self.logger.info("[target: %s]: already exists" % (opts.iqn))
96 print >>sys.stdout, _("[target: %s]: already exists") % (opts.iqn)
98 login_command_args = [ISCSI_CMD,
99 ISCSI_CMD_OPTION_MODE,
100 ISCSI_CMD_OPTION_MODE_NODE,
101 ISCSI_CMD_OPTION_TARGETNAME,
105 login_command_args.append(ISCSI_CMD_OPTION_PORTAL)
106 login_command_args.append(opts.host)
108 login_command_args.append(ISCSI_CMD_OPTION_LOGIN)
110 (login_rc,login_res) = execute_command(login_command_args)
114 raise KssCommandException('Failed to login to iSCSI. - host=%s iqn=%s message=%s' % (opts.host, opts.iqn, login_res))
116 for line in login_res:
120 self.logger.info("%s" % (line))
121 print >>sys.stdout, _("%s") % (line)
125 if __name__ == "__main__":
126 target = StartIscsi()
127 sys.exit(target.run())