##// END OF EJS Templates
FIX: updated ssh environment copying to escape special characters for posix compatibility
Satrajit Ghosh -
Show More
@@ -1,1033 +1,1041 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3
3
4 """Start an IPython cluster = (controller + engines)."""
4 """Start an IPython cluster = (controller + engines)."""
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008 The IPython Development Team
7 # Copyright (C) 2008 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import os
17 import os
18 import re
18 import re
19 import sys
19 import sys
20 import signal
20 import signal
21 import stat
21 import stat
22 import tempfile
22 import tempfile
23 pjoin = os.path.join
23 pjoin = os.path.join
24
24
25 from twisted.internet import reactor, defer
25 from twisted.internet import reactor, defer
26 from twisted.internet.protocol import ProcessProtocol
26 from twisted.internet.protocol import ProcessProtocol
27 from twisted.internet.error import ProcessDone, ProcessTerminated
27 from twisted.internet.error import ProcessDone, ProcessTerminated
28 from twisted.internet.utils import getProcessOutput
28 from twisted.internet.utils import getProcessOutput
29 from twisted.python import failure, log
29 from twisted.python import failure, log
30
30
31 from IPython.external import argparse
31 from IPython.external import argparse
32 from IPython.external import Itpl
32 from IPython.external import Itpl
33 from IPython.genutils import (
33 from IPython.genutils import (
34 get_ipython_dir,
34 get_ipython_dir,
35 get_log_dir,
35 get_log_dir,
36 get_security_dir,
36 get_security_dir,
37 num_cpus
37 num_cpus
38 )
38 )
39 from IPython.kernel.fcutil import have_crypto
39 from IPython.kernel.fcutil import have_crypto
40
40
41 # Create various ipython directories if they don't exist.
41 # Create various ipython directories if they don't exist.
42 # This must be done before IPython.kernel.config is imported.
42 # This must be done before IPython.kernel.config is imported.
43 from IPython.iplib import user_setup
43 from IPython.iplib import user_setup
44 if os.name == 'posix':
44 if os.name == 'posix':
45 rc_suffix = ''
45 rc_suffix = ''
46 else:
46 else:
47 rc_suffix = '.ini'
47 rc_suffix = '.ini'
48 user_setup(get_ipython_dir(), rc_suffix, mode='install', interactive=False)
48 user_setup(get_ipython_dir(), rc_suffix, mode='install', interactive=False)
49 get_log_dir()
49 get_log_dir()
50 get_security_dir()
50 get_security_dir()
51
51
52 from IPython.kernel.config import config_manager as kernel_config_manager
52 from IPython.kernel.config import config_manager as kernel_config_manager
53 from IPython.kernel.error import SecurityError, FileTimeoutError
53 from IPython.kernel.error import SecurityError, FileTimeoutError
54 from IPython.kernel.fcutil import have_crypto
54 from IPython.kernel.fcutil import have_crypto
55 from IPython.kernel.twistedutil import gatherBoth, wait_for_file
55 from IPython.kernel.twistedutil import gatherBoth, wait_for_file
56 from IPython.kernel.util import printer
56 from IPython.kernel.util import printer
57
57
58 #-----------------------------------------------------------------------------
58 #-----------------------------------------------------------------------------
59 # General process handling code
59 # General process handling code
60 #-----------------------------------------------------------------------------
60 #-----------------------------------------------------------------------------
61
61
62
62
63 class ProcessStateError(Exception):
63 class ProcessStateError(Exception):
64 pass
64 pass
65
65
66 class UnknownStatus(Exception):
66 class UnknownStatus(Exception):
67 pass
67 pass
68
68
69 class LauncherProcessProtocol(ProcessProtocol):
69 class LauncherProcessProtocol(ProcessProtocol):
70 """
70 """
71 A ProcessProtocol to go with the ProcessLauncher.
71 A ProcessProtocol to go with the ProcessLauncher.
72 """
72 """
73 def __init__(self, process_launcher):
73 def __init__(self, process_launcher):
74 self.process_launcher = process_launcher
74 self.process_launcher = process_launcher
75
75
76 def connectionMade(self):
76 def connectionMade(self):
77 self.process_launcher.fire_start_deferred(self.transport.pid)
77 self.process_launcher.fire_start_deferred(self.transport.pid)
78
78
79 def processEnded(self, status):
79 def processEnded(self, status):
80 value = status.value
80 value = status.value
81 if isinstance(value, ProcessDone):
81 if isinstance(value, ProcessDone):
82 self.process_launcher.fire_stop_deferred(0)
82 self.process_launcher.fire_stop_deferred(0)
83 elif isinstance(value, ProcessTerminated):
83 elif isinstance(value, ProcessTerminated):
84 self.process_launcher.fire_stop_deferred(
84 self.process_launcher.fire_stop_deferred(
85 {'exit_code':value.exitCode,
85 {'exit_code':value.exitCode,
86 'signal':value.signal,
86 'signal':value.signal,
87 'status':value.status
87 'status':value.status
88 }
88 }
89 )
89 )
90 else:
90 else:
91 raise UnknownStatus("unknown exit status, this is probably a bug in Twisted")
91 raise UnknownStatus("unknown exit status, this is probably a bug in Twisted")
92
92
93 def outReceived(self, data):
93 def outReceived(self, data):
94 log.msg(data)
94 log.msg(data)
95
95
96 def errReceived(self, data):
96 def errReceived(self, data):
97 log.err(data)
97 log.err(data)
98
98
99 class ProcessLauncher(object):
99 class ProcessLauncher(object):
100 """
100 """
101 Start and stop an external process in an asynchronous manner.
101 Start and stop an external process in an asynchronous manner.
102
102
103 Currently this uses deferreds to notify other parties of process state
103 Currently this uses deferreds to notify other parties of process state
104 changes. This is an awkward design and should be moved to using
104 changes. This is an awkward design and should be moved to using
105 a formal NotificationCenter.
105 a formal NotificationCenter.
106 """
106 """
107 def __init__(self, cmd_and_args):
107 def __init__(self, cmd_and_args):
108 self.cmd = cmd_and_args[0]
108 self.cmd = cmd_and_args[0]
109 self.args = cmd_and_args
109 self.args = cmd_and_args
110 self._reset()
110 self._reset()
111
111
112 def _reset(self):
112 def _reset(self):
113 self.process_protocol = None
113 self.process_protocol = None
114 self.pid = None
114 self.pid = None
115 self.start_deferred = None
115 self.start_deferred = None
116 self.stop_deferreds = []
116 self.stop_deferreds = []
117 self.state = 'before' # before, running, or after
117 self.state = 'before' # before, running, or after
118
118
119 @property
119 @property
120 def running(self):
120 def running(self):
121 if self.state == 'running':
121 if self.state == 'running':
122 return True
122 return True
123 else:
123 else:
124 return False
124 return False
125
125
126 def fire_start_deferred(self, pid):
126 def fire_start_deferred(self, pid):
127 self.pid = pid
127 self.pid = pid
128 self.state = 'running'
128 self.state = 'running'
129 log.msg('Process %r has started with pid=%i' % (self.args, pid))
129 log.msg('Process %r has started with pid=%i' % (self.args, pid))
130 self.start_deferred.callback(pid)
130 self.start_deferred.callback(pid)
131
131
132 def start(self):
132 def start(self):
133 if self.state == 'before':
133 if self.state == 'before':
134 self.process_protocol = LauncherProcessProtocol(self)
134 self.process_protocol = LauncherProcessProtocol(self)
135 self.start_deferred = defer.Deferred()
135 self.start_deferred = defer.Deferred()
136 self.process_transport = reactor.spawnProcess(
136 self.process_transport = reactor.spawnProcess(
137 self.process_protocol,
137 self.process_protocol,
138 self.cmd,
138 self.cmd,
139 self.args,
139 self.args,
140 env=os.environ
140 env=os.environ
141 )
141 )
142 return self.start_deferred
142 return self.start_deferred
143 else:
143 else:
144 s = 'the process has already been started and has state: %r' % \
144 s = 'the process has already been started and has state: %r' % \
145 self.state
145 self.state
146 return defer.fail(ProcessStateError(s))
146 return defer.fail(ProcessStateError(s))
147
147
148 def get_stop_deferred(self):
148 def get_stop_deferred(self):
149 if self.state == 'running' or self.state == 'before':
149 if self.state == 'running' or self.state == 'before':
150 d = defer.Deferred()
150 d = defer.Deferred()
151 self.stop_deferreds.append(d)
151 self.stop_deferreds.append(d)
152 return d
152 return d
153 else:
153 else:
154 s = 'this process is already complete'
154 s = 'this process is already complete'
155 return defer.fail(ProcessStateError(s))
155 return defer.fail(ProcessStateError(s))
156
156
157 def fire_stop_deferred(self, exit_code):
157 def fire_stop_deferred(self, exit_code):
158 log.msg('Process %r has stopped with %r' % (self.args, exit_code))
158 log.msg('Process %r has stopped with %r' % (self.args, exit_code))
159 self.state = 'after'
159 self.state = 'after'
160 for d in self.stop_deferreds:
160 for d in self.stop_deferreds:
161 d.callback(exit_code)
161 d.callback(exit_code)
162
162
163 def signal(self, sig):
163 def signal(self, sig):
164 """
164 """
165 Send a signal to the process.
165 Send a signal to the process.
166
166
167 The argument sig can be ('KILL','INT', etc.) or any signal number.
167 The argument sig can be ('KILL','INT', etc.) or any signal number.
168 """
168 """
169 if self.state == 'running':
169 if self.state == 'running':
170 self.process_transport.signalProcess(sig)
170 self.process_transport.signalProcess(sig)
171
171
172 # def __del__(self):
172 # def __del__(self):
173 # self.signal('KILL')
173 # self.signal('KILL')
174
174
175 def interrupt_then_kill(self, delay=1.0):
175 def interrupt_then_kill(self, delay=1.0):
176 self.signal('INT')
176 self.signal('INT')
177 reactor.callLater(delay, self.signal, 'KILL')
177 reactor.callLater(delay, self.signal, 'KILL')
178
178
179
179
180 #-----------------------------------------------------------------------------
180 #-----------------------------------------------------------------------------
181 # Code for launching controller and engines
181 # Code for launching controller and engines
182 #-----------------------------------------------------------------------------
182 #-----------------------------------------------------------------------------
183
183
184
184
185 class ControllerLauncher(ProcessLauncher):
185 class ControllerLauncher(ProcessLauncher):
186
186
187 def __init__(self, extra_args=None):
187 def __init__(self, extra_args=None):
188 if sys.platform == 'win32':
188 if sys.platform == 'win32':
189 # This logic is needed because the ipcontroller script doesn't
189 # This logic is needed because the ipcontroller script doesn't
190 # always get installed in the same way or in the same location.
190 # always get installed in the same way or in the same location.
191 from IPython.kernel.scripts import ipcontroller
191 from IPython.kernel.scripts import ipcontroller
192 script_location = ipcontroller.__file__.replace('.pyc', '.py')
192 script_location = ipcontroller.__file__.replace('.pyc', '.py')
193 # The -u option here turns on unbuffered output, which is required
193 # The -u option here turns on unbuffered output, which is required
194 # on Win32 to prevent wierd conflict and problems with Twisted.
194 # on Win32 to prevent wierd conflict and problems with Twisted.
195 # Also, use sys.executable to make sure we are picking up the
195 # Also, use sys.executable to make sure we are picking up the
196 # right python exe.
196 # right python exe.
197 args = [sys.executable, '-u', script_location]
197 args = [sys.executable, '-u', script_location]
198 else:
198 else:
199 args = ['ipcontroller']
199 args = ['ipcontroller']
200 self.extra_args = extra_args
200 self.extra_args = extra_args
201 if extra_args is not None:
201 if extra_args is not None:
202 args.extend(extra_args)
202 args.extend(extra_args)
203
203
204 ProcessLauncher.__init__(self, args)
204 ProcessLauncher.__init__(self, args)
205
205
206
206
207 class EngineLauncher(ProcessLauncher):
207 class EngineLauncher(ProcessLauncher):
208
208
209 def __init__(self, extra_args=None):
209 def __init__(self, extra_args=None):
210 if sys.platform == 'win32':
210 if sys.platform == 'win32':
211 # This logic is needed because the ipcontroller script doesn't
211 # This logic is needed because the ipcontroller script doesn't
212 # always get installed in the same way or in the same location.
212 # always get installed in the same way or in the same location.
213 from IPython.kernel.scripts import ipengine
213 from IPython.kernel.scripts import ipengine
214 script_location = ipengine.__file__.replace('.pyc', '.py')
214 script_location = ipengine.__file__.replace('.pyc', '.py')
215 # The -u option here turns on unbuffered output, which is required
215 # The -u option here turns on unbuffered output, which is required
216 # on Win32 to prevent wierd conflict and problems with Twisted.
216 # on Win32 to prevent wierd conflict and problems with Twisted.
217 # Also, use sys.executable to make sure we are picking up the
217 # Also, use sys.executable to make sure we are picking up the
218 # right python exe.
218 # right python exe.
219 args = [sys.executable, '-u', script_location]
219 args = [sys.executable, '-u', script_location]
220 else:
220 else:
221 args = ['ipengine']
221 args = ['ipengine']
222 self.extra_args = extra_args
222 self.extra_args = extra_args
223 if extra_args is not None:
223 if extra_args is not None:
224 args.extend(extra_args)
224 args.extend(extra_args)
225
225
226 ProcessLauncher.__init__(self, args)
226 ProcessLauncher.__init__(self, args)
227
227
228
228
229 class LocalEngineSet(object):
229 class LocalEngineSet(object):
230
230
231 def __init__(self, extra_args=None):
231 def __init__(self, extra_args=None):
232 self.extra_args = extra_args
232 self.extra_args = extra_args
233 self.launchers = []
233 self.launchers = []
234
234
235 def start(self, n):
235 def start(self, n):
236 dlist = []
236 dlist = []
237 for i in range(n):
237 for i in range(n):
238 print "starting engine:", i
238 print "starting engine:", i
239 el = EngineLauncher(extra_args=self.extra_args)
239 el = EngineLauncher(extra_args=self.extra_args)
240 d = el.start()
240 d = el.start()
241 self.launchers.append(el)
241 self.launchers.append(el)
242 dlist.append(d)
242 dlist.append(d)
243 dfinal = gatherBoth(dlist, consumeErrors=True)
243 dfinal = gatherBoth(dlist, consumeErrors=True)
244 dfinal.addCallback(self._handle_start)
244 dfinal.addCallback(self._handle_start)
245 return dfinal
245 return dfinal
246
246
247 def _handle_start(self, r):
247 def _handle_start(self, r):
248 log.msg('Engines started with pids: %r' % r)
248 log.msg('Engines started with pids: %r' % r)
249 return r
249 return r
250
250
251 def _handle_stop(self, r):
251 def _handle_stop(self, r):
252 log.msg('Engines received signal: %r' % r)
252 log.msg('Engines received signal: %r' % r)
253 return r
253 return r
254
254
255 def signal(self, sig):
255 def signal(self, sig):
256 dlist = []
256 dlist = []
257 for el in self.launchers:
257 for el in self.launchers:
258 d = el.get_stop_deferred()
258 d = el.get_stop_deferred()
259 dlist.append(d)
259 dlist.append(d)
260 el.signal(sig)
260 el.signal(sig)
261 dfinal = gatherBoth(dlist, consumeErrors=True)
261 dfinal = gatherBoth(dlist, consumeErrors=True)
262 dfinal.addCallback(self._handle_stop)
262 dfinal.addCallback(self._handle_stop)
263 return dfinal
263 return dfinal
264
264
265 def interrupt_then_kill(self, delay=1.0):
265 def interrupt_then_kill(self, delay=1.0):
266 dlist = []
266 dlist = []
267 for el in self.launchers:
267 for el in self.launchers:
268 d = el.get_stop_deferred()
268 d = el.get_stop_deferred()
269 dlist.append(d)
269 dlist.append(d)
270 el.interrupt_then_kill(delay)
270 el.interrupt_then_kill(delay)
271 dfinal = gatherBoth(dlist, consumeErrors=True)
271 dfinal = gatherBoth(dlist, consumeErrors=True)
272 dfinal.addCallback(self._handle_stop)
272 dfinal.addCallback(self._handle_stop)
273 return dfinal
273 return dfinal
274
274
275 class BatchEngineSet(object):
275 class BatchEngineSet(object):
276
276
277 # Subclasses must fill these in. See PBSEngineSet/SGEEngineSet
277 # Subclasses must fill these in. See PBSEngineSet/SGEEngineSet
278 name = ''
278 name = ''
279 submit_command = ''
279 submit_command = ''
280 delete_command = ''
280 delete_command = ''
281 job_id_regexp = ''
281 job_id_regexp = ''
282 job_array_regexp = ''
282 job_array_regexp = ''
283 job_array_template = ''
283 job_array_template = ''
284 queue_regexp = ''
284 queue_regexp = ''
285 queue_template = ''
285 queue_template = ''
286 default_template = ''
286 default_template = ''
287
287
288 def __init__(self, template_file, queue, **kwargs):
288 def __init__(self, template_file, queue, **kwargs):
289 self.template_file = template_file
289 self.template_file = template_file
290 self.queue = queue
290 self.queue = queue
291
291
292 def parse_job_id(self, output):
292 def parse_job_id(self, output):
293 m = re.search(self.job_id_regexp, output)
293 m = re.search(self.job_id_regexp, output)
294 if m is not None:
294 if m is not None:
295 job_id = m.group()
295 job_id = m.group()
296 else:
296 else:
297 raise Exception("job id couldn't be determined: %s" % output)
297 raise Exception("job id couldn't be determined: %s" % output)
298 self.job_id = job_id
298 self.job_id = job_id
299 log.msg('Job started with job id: %r' % job_id)
299 log.msg('Job started with job id: %r' % job_id)
300 return job_id
300 return job_id
301
301
302 def handle_error(self, f):
302 def handle_error(self, f):
303 f.printTraceback()
303 f.printTraceback()
304 f.raiseException()
304 f.raiseException()
305
305
306 def start(self, n):
306 def start(self, n):
307 log.msg("starting %d engines" % n)
307 log.msg("starting %d engines" % n)
308 self._temp_file = tempfile.NamedTemporaryFile()
308 self._temp_file = tempfile.NamedTemporaryFile()
309 os.chmod(self._temp_file.name, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
309 os.chmod(self._temp_file.name, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
310 if self.template_file:
310 if self.template_file:
311 log.msg("Using %s script %s" % (self.name, self.template_file))
311 log.msg("Using %s script %s" % (self.name, self.template_file))
312 contents = open(self.template_file, 'r').read()
312 contents = open(self.template_file, 'r').read()
313 new_script = contents
313 new_script = contents
314 regex = re.compile(self.job_array_regexp)
314 regex = re.compile(self.job_array_regexp)
315 if not regex.search(contents):
315 if not regex.search(contents):
316 log.msg("adding job array settings to %s script" % self.name)
316 log.msg("adding job array settings to %s script" % self.name)
317 new_script = self.job_array_template % n +'\n' + new_script
317 new_script = self.job_array_template % n +'\n' + new_script
318 print self.queue_regexp
318 print self.queue_regexp
319 regex = re.compile(self.queue_regexp)
319 regex = re.compile(self.queue_regexp)
320 print regex.search(contents)
320 print regex.search(contents)
321 if self.queue and not regex.search(contents):
321 if self.queue and not regex.search(contents):
322 log.msg("adding queue settings to %s script" % self.name)
322 log.msg("adding queue settings to %s script" % self.name)
323 new_script = self.queue_template % self.queue + '\n' + new_script
323 new_script = self.queue_template % self.queue + '\n' + new_script
324 if new_script != contents:
324 if new_script != contents:
325 self._temp_file.write(new_script)
325 self._temp_file.write(new_script)
326 self.template_file = self._temp_file.name
326 self.template_file = self._temp_file.name
327 else:
327 else:
328 default_script = self.default_template % n
328 default_script = self.default_template % n
329 if self.queue:
329 if self.queue:
330 default_script = self.queue_template % self.queue + \
330 default_script = self.queue_template % self.queue + \
331 '\n' + default_script
331 '\n' + default_script
332 log.msg("using default ipengine %s script: \n%s" %
332 log.msg("using default ipengine %s script: \n%s" %
333 (self.name, default_script))
333 (self.name, default_script))
334 self._temp_file.file.write(default_script)
334 self._temp_file.file.write(default_script)
335 self.template_file = self._temp_file.name
335 self.template_file = self._temp_file.name
336 self._temp_file.file.close()
336 self._temp_file.file.close()
337 d = getProcessOutput(self.submit_command,
337 d = getProcessOutput(self.submit_command,
338 [self.template_file],
338 [self.template_file],
339 env=os.environ)
339 env=os.environ)
340 d.addCallback(self.parse_job_id)
340 d.addCallback(self.parse_job_id)
341 d.addErrback(self.handle_error)
341 d.addErrback(self.handle_error)
342 return d
342 return d
343
343
344 def kill(self):
344 def kill(self):
345 d = getProcessOutput(self.delete_command,
345 d = getProcessOutput(self.delete_command,
346 [self.job_id],env=os.environ)
346 [self.job_id],env=os.environ)
347 return d
347 return d
348
348
349 class PBSEngineSet(BatchEngineSet):
349 class PBSEngineSet(BatchEngineSet):
350
350
351 name = 'PBS'
351 name = 'PBS'
352 submit_command = 'qsub'
352 submit_command = 'qsub'
353 delete_command = 'qdel'
353 delete_command = 'qdel'
354 job_id_regexp = '\d+'
354 job_id_regexp = '\d+'
355 job_array_regexp = '#PBS[ \t]+-t[ \t]+\d+'
355 job_array_regexp = '#PBS[ \t]+-t[ \t]+\d+'
356 job_array_template = '#PBS -t 1-%d'
356 job_array_template = '#PBS -t 1-%d'
357 queue_regexp = '#PBS[ \t]+-q[ \t]+\w+'
357 queue_regexp = '#PBS[ \t]+-q[ \t]+\w+'
358 queue_template = '#PBS -q %s'
358 queue_template = '#PBS -q %s'
359 default_template="""#!/bin/sh
359 default_template="""#!/bin/sh
360 #PBS -V
360 #PBS -V
361 #PBS -t 1-%d
361 #PBS -t 1-%d
362 #PBS -N ipengine
362 #PBS -N ipengine
363 eid=$(($PBS_ARRAYID - 1))
363 eid=$(($PBS_ARRAYID - 1))
364 ipengine --logfile=ipengine${eid}.log
364 ipengine --logfile=ipengine${eid}.log
365 """
365 """
366
366
367 class SGEEngineSet(PBSEngineSet):
367 class SGEEngineSet(PBSEngineSet):
368
368
369 name = 'SGE'
369 name = 'SGE'
370 job_array_regexp = '#\$[ \t]+-t[ \t]+\d+'
370 job_array_regexp = '#\$[ \t]+-t[ \t]+\d+'
371 job_array_template = '#$ -t 1-%d'
371 job_array_template = '#$ -t 1-%d'
372 queue_regexp = '#\$[ \t]+-q[ \t]+\w+'
372 queue_regexp = '#\$[ \t]+-q[ \t]+\w+'
373 queue_template = '#$ -q %s'
373 queue_template = '#$ -q %s'
374 default_template="""#$ -V
374 default_template="""#$ -V
375 #$ -S /bin/sh
375 #$ -S /bin/sh
376 #$ -t 1-%d
376 #$ -t 1-%d
377 #$ -N ipengine
377 #$ -N ipengine
378 eid=$(($SGE_TASK_ID - 1))
378 eid=$(($SGE_TASK_ID - 1))
379 ipengine --logfile=ipengine${eid}.log
379 ipengine --logfile=ipengine${eid}.log
380 """
380 """
381
381
382 class LSFEngineSet(PBSEngineSet):
382 class LSFEngineSet(PBSEngineSet):
383
383
384 name = 'LSF'
384 name = 'LSF'
385 submit_command = 'bsub'
385 submit_command = 'bsub'
386 delete_command = 'bkill'
386 delete_command = 'bkill'
387 job_array_regexp = '#BSUB[ \t]-J+\w+\[\d+-\d+\]'
387 job_array_regexp = '#BSUB[ \t]-J+\w+\[\d+-\d+\]'
388 job_array_template = '#BSUB -J ipengine[1-%d]'
388 job_array_template = '#BSUB -J ipengine[1-%d]'
389 queue_regexp = '#BSUB[ \t]+-q[ \t]+\w+'
389 queue_regexp = '#BSUB[ \t]+-q[ \t]+\w+'
390 queue_template = '#BSUB -q %s'
390 queue_template = '#BSUB -q %s'
391 default_template="""#!/bin/sh
391 default_template="""#!/bin/sh
392 #BSUB -J ipengine[1-%d]
392 #BSUB -J ipengine[1-%d]
393 eid=$(($LSB_JOBINDEX - 1))
393 eid=$(($LSB_JOBINDEX - 1))
394 ipengine --logfile=ipengine${eid}.log
394 ipengine --logfile=ipengine${eid}.log
395 """
395 """
396 bsub_wrapper="""#!/bin/sh
396 bsub_wrapper="""#!/bin/sh
397 bsub < $1
397 bsub < $1
398 """
398 """
399
399
400 def __init__(self, template_file, queue, **kwargs):
400 def __init__(self, template_file, queue, **kwargs):
401 self._bsub_wrapper = self._make_bsub_wrapper()
401 self._bsub_wrapper = self._make_bsub_wrapper()
402 self.submit_command = self._bsub_wrapper.name
402 self.submit_command = self._bsub_wrapper.name
403 PBSEngineSet.__init__(self,template_file, queue, **kwargs)
403 PBSEngineSet.__init__(self,template_file, queue, **kwargs)
404
404
405 def _make_bsub_wrapper(self):
405 def _make_bsub_wrapper(self):
406 bsub_wrapper = tempfile.NamedTemporaryFile()
406 bsub_wrapper = tempfile.NamedTemporaryFile()
407 bsub_wrapper.write(self.bsub_wrapper)
407 bsub_wrapper.write(self.bsub_wrapper)
408 bsub_wrapper.file.close()
408 bsub_wrapper.file.close()
409 os.chmod(bsub_wrapper.name, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
409 os.chmod(bsub_wrapper.name, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
410 return bsub_wrapper
410 return bsub_wrapper
411
411
412 sshx_template_prefix="""#!/bin/sh
412 sshx_template_prefix="""#!/bin/sh
413 """
413 """
414 sshx_template_suffix=""""$@" &> /dev/null &
414 sshx_template_suffix=""""$@" &> /dev/null &
415 echo $!
415 echo $!
416 """
416 """
417
417
418 engine_killer_template="""#!/bin/sh
418 engine_killer_template="""#!/bin/sh
419 ps -fu `whoami` | grep '[i]pengine' | awk '{print $2}' | xargs kill -TERM
419 ps -fu `whoami` | grep '[i]pengine' | awk '{print $2}' | xargs kill -TERM
420 """
420 """
421
421
422 def escape_strings(val):
423 val = val.replace('(','\(')
424 val = val.replace(')','\)')
425 if ' ' in val:
426 val = '"%s"'%val
427 return val
428
422 class SSHEngineSet(object):
429 class SSHEngineSet(object):
423 sshx_template_prefix=sshx_template_prefix
430 sshx_template_prefix=sshx_template_prefix
424 sshx_template_suffix=sshx_template_suffix
431 sshx_template_suffix=sshx_template_suffix
425 engine_killer_template=engine_killer_template
432 engine_killer_template=engine_killer_template
426
433
427 def __init__(self, engine_hosts, sshx=None, copyenvs=None, ipengine="ipengine"):
434 def __init__(self, engine_hosts, sshx=None, copyenvs=None, ipengine="ipengine"):
428 """Start a controller on localhost and engines using ssh.
435 """Start a controller on localhost and engines using ssh.
429
436
430 The engine_hosts argument is a dict with hostnames as keys and
437 The engine_hosts argument is a dict with hostnames as keys and
431 the number of engine (int) as values. sshx is the name of a local
438 the number of engine (int) as values. sshx is the name of a local
432 file that will be used to run remote commands. This file is used
439 file that will be used to run remote commands. This file is used
433 to setup the environment properly.
440 to setup the environment properly.
434 """
441 """
435
442
436 self.temp_dir = tempfile.gettempdir()
443 self.temp_dir = tempfile.gettempdir()
437 if sshx is not None:
444 if sshx is not None:
438 self.sshx = sshx
445 self.sshx = sshx
439 else:
446 else:
440 # Write the sshx.sh file locally from our template.
447 # Write the sshx.sh file locally from our template.
441 self.sshx = os.path.join(
448 self.sshx = os.path.join(
442 self.temp_dir,
449 self.temp_dir,
443 '%s-main-sshx.sh' % os.environ['USER']
450 '%s-main-sshx.sh' % os.environ['USER']
444 )
451 )
445 f = open(self.sshx, 'w')
452 f = open(self.sshx, 'w')
446 f.writelines(self.sshx_template_prefix)
453 f.writelines(self.sshx_template_prefix)
447 if copyenvs:
454 if copyenvs:
448 for key, val in os.environ.items():
455 for key, val in sorted(os.environ.items()):
449 f.writelines('export %s=%s\n'%(key,val))
456 newval = escape_strings(val)
457 f.writelines('export %s=%s\n'%(key,newval))
450 f.writelines(self.sshx_template_suffix)
458 f.writelines(self.sshx_template_suffix)
451 f.close()
459 f.close()
452 self.engine_command = ipengine
460 self.engine_command = ipengine
453 self.engine_hosts = engine_hosts
461 self.engine_hosts = engine_hosts
454 # Write the engine killer script file locally from our template.
462 # Write the engine killer script file locally from our template.
455 self.engine_killer = os.path.join(
463 self.engine_killer = os.path.join(
456 self.temp_dir,
464 self.temp_dir,
457 '%s-local-engine_killer.sh' % os.environ['USER']
465 '%s-local-engine_killer.sh' % os.environ['USER']
458 )
466 )
459 f = open(self.engine_killer, 'w')
467 f = open(self.engine_killer, 'w')
460 f.writelines(self.engine_killer_template)
468 f.writelines(self.engine_killer_template)
461 f.close()
469 f.close()
462
470
463 def start(self, send_furl=False):
471 def start(self, send_furl=False):
464 dlist = []
472 dlist = []
465 for host in self.engine_hosts.keys():
473 for host in self.engine_hosts.keys():
466 count = self.engine_hosts[host]
474 count = self.engine_hosts[host]
467 d = self._start(host, count, send_furl)
475 d = self._start(host, count, send_furl)
468 dlist.append(d)
476 dlist.append(d)
469 return gatherBoth(dlist, consumeErrors=True)
477 return gatherBoth(dlist, consumeErrors=True)
470
478
471 def _start(self, hostname, count=1, send_furl=False):
479 def _start(self, hostname, count=1, send_furl=False):
472 if send_furl:
480 if send_furl:
473 d = self._scp_furl(hostname)
481 d = self._scp_furl(hostname)
474 else:
482 else:
475 d = defer.succeed(None)
483 d = defer.succeed(None)
476 d.addCallback(lambda r: self._scp_sshx(hostname))
484 d.addCallback(lambda r: self._scp_sshx(hostname))
477 d.addCallback(lambda r: self._ssh_engine(hostname, count))
485 d.addCallback(lambda r: self._ssh_engine(hostname, count))
478 return d
486 return d
479
487
480 def _scp_furl(self, hostname):
488 def _scp_furl(self, hostname):
481 scp_cmd = "scp ~/.ipython/security/ipcontroller-engine.furl %s:.ipython/security/" % (hostname)
489 scp_cmd = "scp ~/.ipython/security/ipcontroller-engine.furl %s:.ipython/security/" % (hostname)
482 cmd_list = scp_cmd.split()
490 cmd_list = scp_cmd.split()
483 cmd_list[1] = os.path.expanduser(cmd_list[1])
491 cmd_list[1] = os.path.expanduser(cmd_list[1])
484 log.msg('Copying furl file: %s' % scp_cmd)
492 log.msg('Copying furl file: %s' % scp_cmd)
485 d = getProcessOutput(cmd_list[0], cmd_list[1:], env=os.environ)
493 d = getProcessOutput(cmd_list[0], cmd_list[1:], env=os.environ)
486 return d
494 return d
487
495
488 def _scp_sshx(self, hostname):
496 def _scp_sshx(self, hostname):
489 scp_cmd = "scp %s %s:%s/%s-sshx.sh" % (
497 scp_cmd = "scp %s %s:%s/%s-sshx.sh" % (
490 self.sshx, hostname,
498 self.sshx, hostname,
491 self.temp_dir, os.environ['USER']
499 self.temp_dir, os.environ['USER']
492 )
500 )
493 print
501 print
494 log.msg("Copying sshx: %s" % scp_cmd)
502 log.msg("Copying sshx: %s" % scp_cmd)
495 sshx_scp = scp_cmd.split()
503 sshx_scp = scp_cmd.split()
496 d = getProcessOutput(sshx_scp[0], sshx_scp[1:], env=os.environ)
504 d = getProcessOutput(sshx_scp[0], sshx_scp[1:], env=os.environ)
497 return d
505 return d
498
506
499 def _ssh_engine(self, hostname, count):
507 def _ssh_engine(self, hostname, count):
500 exec_engine = "ssh %s sh %s/%s-sshx.sh %s" % (
508 exec_engine = "ssh %s sh %s/%s-sshx.sh %s" % (
501 hostname, self.temp_dir,
509 hostname, self.temp_dir,
502 os.environ['USER'], self.engine_command
510 os.environ['USER'], self.engine_command
503 )
511 )
504 cmds = exec_engine.split()
512 cmds = exec_engine.split()
505 dlist = []
513 dlist = []
506 log.msg("about to start engines...")
514 log.msg("about to start engines...")
507 for i in range(count):
515 for i in range(count):
508 log.msg('Starting engines: %s' % exec_engine)
516 log.msg('Starting engines: %s' % exec_engine)
509 d = getProcessOutput(cmds[0], cmds[1:], env=os.environ)
517 d = getProcessOutput(cmds[0], cmds[1:], env=os.environ)
510 dlist.append(d)
518 dlist.append(d)
511 return gatherBoth(dlist, consumeErrors=True)
519 return gatherBoth(dlist, consumeErrors=True)
512
520
513 def kill(self):
521 def kill(self):
514 dlist = []
522 dlist = []
515 for host in self.engine_hosts.keys():
523 for host in self.engine_hosts.keys():
516 d = self._killall(host)
524 d = self._killall(host)
517 dlist.append(d)
525 dlist.append(d)
518 return gatherBoth(dlist, consumeErrors=True)
526 return gatherBoth(dlist, consumeErrors=True)
519
527
520 def _killall(self, hostname):
528 def _killall(self, hostname):
521 d = self._scp_engine_killer(hostname)
529 d = self._scp_engine_killer(hostname)
522 d.addCallback(lambda r: self._ssh_kill(hostname))
530 d.addCallback(lambda r: self._ssh_kill(hostname))
523 # d.addErrback(self._exec_err)
531 # d.addErrback(self._exec_err)
524 return d
532 return d
525
533
526 def _scp_engine_killer(self, hostname):
534 def _scp_engine_killer(self, hostname):
527 scp_cmd = "scp %s %s:%s/%s-engine_killer.sh" % (
535 scp_cmd = "scp %s %s:%s/%s-engine_killer.sh" % (
528 self.engine_killer,
536 self.engine_killer,
529 hostname,
537 hostname,
530 self.temp_dir,
538 self.temp_dir,
531 os.environ['USER']
539 os.environ['USER']
532 )
540 )
533 cmds = scp_cmd.split()
541 cmds = scp_cmd.split()
534 log.msg('Copying engine_killer: %s' % scp_cmd)
542 log.msg('Copying engine_killer: %s' % scp_cmd)
535 d = getProcessOutput(cmds[0], cmds[1:], env=os.environ)
543 d = getProcessOutput(cmds[0], cmds[1:], env=os.environ)
536 return d
544 return d
537
545
538 def _ssh_kill(self, hostname):
546 def _ssh_kill(self, hostname):
539 kill_cmd = "ssh %s sh %s/%s-engine_killer.sh" % (
547 kill_cmd = "ssh %s sh %s/%s-engine_killer.sh" % (
540 hostname,
548 hostname,
541 self.temp_dir,
549 self.temp_dir,
542 os.environ['USER']
550 os.environ['USER']
543 )
551 )
544 log.msg('Killing engine: %s' % kill_cmd)
552 log.msg('Killing engine: %s' % kill_cmd)
545 kill_cmd = kill_cmd.split()
553 kill_cmd = kill_cmd.split()
546 d = getProcessOutput(kill_cmd[0], kill_cmd[1:], env=os.environ)
554 d = getProcessOutput(kill_cmd[0], kill_cmd[1:], env=os.environ)
547 return d
555 return d
548
556
549 def _exec_err(self, r):
557 def _exec_err(self, r):
550 log.msg(r)
558 log.msg(r)
551
559
552 #-----------------------------------------------------------------------------
560 #-----------------------------------------------------------------------------
553 # Main functions for the different types of clusters
561 # Main functions for the different types of clusters
554 #-----------------------------------------------------------------------------
562 #-----------------------------------------------------------------------------
555
563
556 # TODO:
564 # TODO:
557 # The logic in these codes should be moved into classes like LocalCluster
565 # The logic in these codes should be moved into classes like LocalCluster
558 # MpirunCluster, PBSCluster, etc. This would remove alot of the duplications.
566 # MpirunCluster, PBSCluster, etc. This would remove alot of the duplications.
559 # The main functions should then just parse the command line arguments, create
567 # The main functions should then just parse the command line arguments, create
560 # the appropriate class and call a 'start' method.
568 # the appropriate class and call a 'start' method.
561
569
562
570
563 def check_security(args, cont_args):
571 def check_security(args, cont_args):
564 """Check to see if we should run with SSL support."""
572 """Check to see if we should run with SSL support."""
565 if (not args.x or not args.y) and not have_crypto:
573 if (not args.x or not args.y) and not have_crypto:
566 log.err("""
574 log.err("""
567 OpenSSL/pyOpenSSL is not available, so we can't run in secure mode.
575 OpenSSL/pyOpenSSL is not available, so we can't run in secure mode.
568 Try running ipcluster with the -xy flags: ipcluster local -xy -n 4""")
576 Try running ipcluster with the -xy flags: ipcluster local -xy -n 4""")
569 reactor.stop()
577 reactor.stop()
570 return False
578 return False
571 if args.x:
579 if args.x:
572 cont_args.append('-x')
580 cont_args.append('-x')
573 if args.y:
581 if args.y:
574 cont_args.append('-y')
582 cont_args.append('-y')
575 return True
583 return True
576
584
577
585
578 def check_reuse(args, cont_args):
586 def check_reuse(args, cont_args):
579 """Check to see if we should try to resuse FURL files."""
587 """Check to see if we should try to resuse FURL files."""
580 if args.r:
588 if args.r:
581 cont_args.append('-r')
589 cont_args.append('-r')
582 if args.client_port == 0 or args.engine_port == 0:
590 if args.client_port == 0 or args.engine_port == 0:
583 log.err("""
591 log.err("""
584 To reuse FURL files, you must also set the client and engine ports using
592 To reuse FURL files, you must also set the client and engine ports using
585 the --client-port and --engine-port options.""")
593 the --client-port and --engine-port options.""")
586 reactor.stop()
594 reactor.stop()
587 return False
595 return False
588 cont_args.append('--client-port=%i' % args.client_port)
596 cont_args.append('--client-port=%i' % args.client_port)
589 cont_args.append('--engine-port=%i' % args.engine_port)
597 cont_args.append('--engine-port=%i' % args.engine_port)
590 return True
598 return True
591
599
592
600
593 def _err_and_stop(f):
601 def _err_and_stop(f):
594 """Errback to log a failure and halt the reactor on a fatal error."""
602 """Errback to log a failure and halt the reactor on a fatal error."""
595 log.err(f)
603 log.err(f)
596 reactor.stop()
604 reactor.stop()
597
605
598
606
599 def _delay_start(cont_pid, start_engines, furl_file, reuse):
607 def _delay_start(cont_pid, start_engines, furl_file, reuse):
600 """Wait for controller to create FURL files and the start the engines."""
608 """Wait for controller to create FURL files and the start the engines."""
601 if not reuse:
609 if not reuse:
602 if os.path.isfile(furl_file):
610 if os.path.isfile(furl_file):
603 os.unlink(furl_file)
611 os.unlink(furl_file)
604 log.msg('Waiting for controller to finish starting...')
612 log.msg('Waiting for controller to finish starting...')
605 d = wait_for_file(furl_file, delay=0.2, max_tries=50)
613 d = wait_for_file(furl_file, delay=0.2, max_tries=50)
606 d.addCallback(lambda _: log.msg('Controller started'))
614 d.addCallback(lambda _: log.msg('Controller started'))
607 d.addCallback(lambda _: start_engines(cont_pid))
615 d.addCallback(lambda _: start_engines(cont_pid))
608 return d
616 return d
609
617
610
618
611 def main_local(args):
619 def main_local(args):
612 cont_args = []
620 cont_args = []
613 cont_args.append('--logfile=%s' % pjoin(args.logdir,'ipcontroller'))
621 cont_args.append('--logfile=%s' % pjoin(args.logdir,'ipcontroller'))
614
622
615 # Check security settings before proceeding
623 # Check security settings before proceeding
616 if not check_security(args, cont_args):
624 if not check_security(args, cont_args):
617 return
625 return
618
626
619 # See if we are reusing FURL files
627 # See if we are reusing FURL files
620 if not check_reuse(args, cont_args):
628 if not check_reuse(args, cont_args):
621 return
629 return
622
630
623 cl = ControllerLauncher(extra_args=cont_args)
631 cl = ControllerLauncher(extra_args=cont_args)
624 dstart = cl.start()
632 dstart = cl.start()
625 def start_engines(cont_pid):
633 def start_engines(cont_pid):
626 engine_args = []
634 engine_args = []
627 engine_args.append('--logfile=%s' % \
635 engine_args.append('--logfile=%s' % \
628 pjoin(args.logdir,'ipengine%s-' % cont_pid))
636 pjoin(args.logdir,'ipengine%s-' % cont_pid))
629 eset = LocalEngineSet(extra_args=engine_args)
637 eset = LocalEngineSet(extra_args=engine_args)
630 def shutdown(signum, frame):
638 def shutdown(signum, frame):
631 log.msg('Stopping local cluster')
639 log.msg('Stopping local cluster')
632 # We are still playing with the times here, but these seem
640 # We are still playing with the times here, but these seem
633 # to be reliable in allowing everything to exit cleanly.
641 # to be reliable in allowing everything to exit cleanly.
634 eset.interrupt_then_kill(0.5)
642 eset.interrupt_then_kill(0.5)
635 cl.interrupt_then_kill(0.5)
643 cl.interrupt_then_kill(0.5)
636 reactor.callLater(1.0, reactor.stop)
644 reactor.callLater(1.0, reactor.stop)
637 signal.signal(signal.SIGINT,shutdown)
645 signal.signal(signal.SIGINT,shutdown)
638 d = eset.start(args.n)
646 d = eset.start(args.n)
639 return d
647 return d
640 config = kernel_config_manager.get_config_obj()
648 config = kernel_config_manager.get_config_obj()
641 furl_file = config['controller']['engine_furl_file']
649 furl_file = config['controller']['engine_furl_file']
642 dstart.addCallback(_delay_start, start_engines, furl_file, args.r)
650 dstart.addCallback(_delay_start, start_engines, furl_file, args.r)
643 dstart.addErrback(_err_and_stop)
651 dstart.addErrback(_err_and_stop)
644
652
645
653
646 def main_mpi(args):
654 def main_mpi(args):
647 cont_args = []
655 cont_args = []
648 cont_args.append('--logfile=%s' % pjoin(args.logdir,'ipcontroller'))
656 cont_args.append('--logfile=%s' % pjoin(args.logdir,'ipcontroller'))
649
657
650 # Check security settings before proceeding
658 # Check security settings before proceeding
651 if not check_security(args, cont_args):
659 if not check_security(args, cont_args):
652 return
660 return
653
661
654 # See if we are reusing FURL files
662 # See if we are reusing FURL files
655 if not check_reuse(args, cont_args):
663 if not check_reuse(args, cont_args):
656 return
664 return
657
665
658 cl = ControllerLauncher(extra_args=cont_args)
666 cl = ControllerLauncher(extra_args=cont_args)
659 dstart = cl.start()
667 dstart = cl.start()
660 def start_engines(cont_pid):
668 def start_engines(cont_pid):
661 raw_args = [args.cmd]
669 raw_args = [args.cmd]
662 raw_args.extend(['-n',str(args.n)])
670 raw_args.extend(['-n',str(args.n)])
663 raw_args.append('ipengine')
671 raw_args.append('ipengine')
664 raw_args.append('-l')
672 raw_args.append('-l')
665 raw_args.append(pjoin(args.logdir,'ipengine%s-' % cont_pid))
673 raw_args.append(pjoin(args.logdir,'ipengine%s-' % cont_pid))
666 if args.mpi:
674 if args.mpi:
667 raw_args.append('--mpi=%s' % args.mpi)
675 raw_args.append('--mpi=%s' % args.mpi)
668 eset = ProcessLauncher(raw_args)
676 eset = ProcessLauncher(raw_args)
669 def shutdown(signum, frame):
677 def shutdown(signum, frame):
670 log.msg('Stopping local cluster')
678 log.msg('Stopping local cluster')
671 # We are still playing with the times here, but these seem
679 # We are still playing with the times here, but these seem
672 # to be reliable in allowing everything to exit cleanly.
680 # to be reliable in allowing everything to exit cleanly.
673 eset.interrupt_then_kill(1.0)
681 eset.interrupt_then_kill(1.0)
674 cl.interrupt_then_kill(1.0)
682 cl.interrupt_then_kill(1.0)
675 reactor.callLater(2.0, reactor.stop)
683 reactor.callLater(2.0, reactor.stop)
676 signal.signal(signal.SIGINT,shutdown)
684 signal.signal(signal.SIGINT,shutdown)
677 d = eset.start()
685 d = eset.start()
678 return d
686 return d
679 config = kernel_config_manager.get_config_obj()
687 config = kernel_config_manager.get_config_obj()
680 furl_file = config['controller']['engine_furl_file']
688 furl_file = config['controller']['engine_furl_file']
681 dstart.addCallback(_delay_start, start_engines, furl_file, args.r)
689 dstart.addCallback(_delay_start, start_engines, furl_file, args.r)
682 dstart.addErrback(_err_and_stop)
690 dstart.addErrback(_err_and_stop)
683
691
684
692
685 def main_pbs(args):
693 def main_pbs(args):
686 cont_args = []
694 cont_args = []
687 cont_args.append('--logfile=%s' % pjoin(args.logdir,'ipcontroller'))
695 cont_args.append('--logfile=%s' % pjoin(args.logdir,'ipcontroller'))
688
696
689 # Check security settings before proceeding
697 # Check security settings before proceeding
690 if not check_security(args, cont_args):
698 if not check_security(args, cont_args):
691 return
699 return
692
700
693 # See if we are reusing FURL files
701 # See if we are reusing FURL files
694 if not check_reuse(args, cont_args):
702 if not check_reuse(args, cont_args):
695 return
703 return
696
704
697 if args.pbsscript and not os.path.isfile(args.pbsscript):
705 if args.pbsscript and not os.path.isfile(args.pbsscript):
698 log.err('PBS script does not exist: %s' % args.pbsscript)
706 log.err('PBS script does not exist: %s' % args.pbsscript)
699 return
707 return
700
708
701 cl = ControllerLauncher(extra_args=cont_args)
709 cl = ControllerLauncher(extra_args=cont_args)
702 dstart = cl.start()
710 dstart = cl.start()
703 def start_engines(r):
711 def start_engines(r):
704 pbs_set = PBSEngineSet(args.pbsscript, args.pbsqueue)
712 pbs_set = PBSEngineSet(args.pbsscript, args.pbsqueue)
705 def shutdown(signum, frame):
713 def shutdown(signum, frame):
706 log.msg('Stopping PBS cluster')
714 log.msg('Stopping PBS cluster')
707 d = pbs_set.kill()
715 d = pbs_set.kill()
708 d.addBoth(lambda _: cl.interrupt_then_kill(1.0))
716 d.addBoth(lambda _: cl.interrupt_then_kill(1.0))
709 d.addBoth(lambda _: reactor.callLater(2.0, reactor.stop))
717 d.addBoth(lambda _: reactor.callLater(2.0, reactor.stop))
710 signal.signal(signal.SIGINT,shutdown)
718 signal.signal(signal.SIGINT,shutdown)
711 d = pbs_set.start(args.n)
719 d = pbs_set.start(args.n)
712 return d
720 return d
713 config = kernel_config_manager.get_config_obj()
721 config = kernel_config_manager.get_config_obj()
714 furl_file = config['controller']['engine_furl_file']
722 furl_file = config['controller']['engine_furl_file']
715 dstart.addCallback(_delay_start, start_engines, furl_file, args.r)
723 dstart.addCallback(_delay_start, start_engines, furl_file, args.r)
716 dstart.addErrback(_err_and_stop)
724 dstart.addErrback(_err_and_stop)
717
725
718 def main_sge(args):
726 def main_sge(args):
719 cont_args = []
727 cont_args = []
720 cont_args.append('--logfile=%s' % pjoin(args.logdir,'ipcontroller'))
728 cont_args.append('--logfile=%s' % pjoin(args.logdir,'ipcontroller'))
721
729
722 # Check security settings before proceeding
730 # Check security settings before proceeding
723 if not check_security(args, cont_args):
731 if not check_security(args, cont_args):
724 return
732 return
725
733
726 # See if we are reusing FURL files
734 # See if we are reusing FURL files
727 if not check_reuse(args, cont_args):
735 if not check_reuse(args, cont_args):
728 return
736 return
729
737
730 if args.sgescript and not os.path.isfile(args.sgescript):
738 if args.sgescript and not os.path.isfile(args.sgescript):
731 log.err('SGE script does not exist: %s' % args.sgescript)
739 log.err('SGE script does not exist: %s' % args.sgescript)
732 return
740 return
733
741
734 cl = ControllerLauncher(extra_args=cont_args)
742 cl = ControllerLauncher(extra_args=cont_args)
735 dstart = cl.start()
743 dstart = cl.start()
736 def start_engines(r):
744 def start_engines(r):
737 sge_set = SGEEngineSet(args.sgescript, args.sgequeue)
745 sge_set = SGEEngineSet(args.sgescript, args.sgequeue)
738 def shutdown(signum, frame):
746 def shutdown(signum, frame):
739 log.msg('Stopping sge cluster')
747 log.msg('Stopping sge cluster')
740 d = sge_set.kill()
748 d = sge_set.kill()
741 d.addBoth(lambda _: cl.interrupt_then_kill(1.0))
749 d.addBoth(lambda _: cl.interrupt_then_kill(1.0))
742 d.addBoth(lambda _: reactor.callLater(2.0, reactor.stop))
750 d.addBoth(lambda _: reactor.callLater(2.0, reactor.stop))
743 signal.signal(signal.SIGINT,shutdown)
751 signal.signal(signal.SIGINT,shutdown)
744 d = sge_set.start(args.n)
752 d = sge_set.start(args.n)
745 return d
753 return d
746 config = kernel_config_manager.get_config_obj()
754 config = kernel_config_manager.get_config_obj()
747 furl_file = config['controller']['engine_furl_file']
755 furl_file = config['controller']['engine_furl_file']
748 dstart.addCallback(_delay_start, start_engines, furl_file, args.r)
756 dstart.addCallback(_delay_start, start_engines, furl_file, args.r)
749 dstart.addErrback(_err_and_stop)
757 dstart.addErrback(_err_and_stop)
750
758
751 def main_lsf(args):
759 def main_lsf(args):
752 cont_args = []
760 cont_args = []
753 cont_args.append('--logfile=%s' % pjoin(args.logdir,'ipcontroller'))
761 cont_args.append('--logfile=%s' % pjoin(args.logdir,'ipcontroller'))
754
762
755 # Check security settings before proceeding
763 # Check security settings before proceeding
756 if not check_security(args, cont_args):
764 if not check_security(args, cont_args):
757 return
765 return
758
766
759 # See if we are reusing FURL files
767 # See if we are reusing FURL files
760 if not check_reuse(args, cont_args):
768 if not check_reuse(args, cont_args):
761 return
769 return
762
770
763 if args.lsfscript and not os.path.isfile(args.lsfscript):
771 if args.lsfscript and not os.path.isfile(args.lsfscript):
764 log.err('LSF script does not exist: %s' % args.lsfscript)
772 log.err('LSF script does not exist: %s' % args.lsfscript)
765 return
773 return
766
774
767 cl = ControllerLauncher(extra_args=cont_args)
775 cl = ControllerLauncher(extra_args=cont_args)
768 dstart = cl.start()
776 dstart = cl.start()
769 def start_engines(r):
777 def start_engines(r):
770 lsf_set = LSFEngineSet(args.lsfscript, args.lsfqueue)
778 lsf_set = LSFEngineSet(args.lsfscript, args.lsfqueue)
771 def shutdown(signum, frame):
779 def shutdown(signum, frame):
772 log.msg('Stopping LSF cluster')
780 log.msg('Stopping LSF cluster')
773 d = lsf_set.kill()
781 d = lsf_set.kill()
774 d.addBoth(lambda _: cl.interrupt_then_kill(1.0))
782 d.addBoth(lambda _: cl.interrupt_then_kill(1.0))
775 d.addBoth(lambda _: reactor.callLater(2.0, reactor.stop))
783 d.addBoth(lambda _: reactor.callLater(2.0, reactor.stop))
776 signal.signal(signal.SIGINT,shutdown)
784 signal.signal(signal.SIGINT,shutdown)
777 d = lsf_set.start(args.n)
785 d = lsf_set.start(args.n)
778 return d
786 return d
779 config = kernel_config_manager.get_config_obj()
787 config = kernel_config_manager.get_config_obj()
780 furl_file = config['controller']['engine_furl_file']
788 furl_file = config['controller']['engine_furl_file']
781 dstart.addCallback(_delay_start, start_engines, furl_file, args.r)
789 dstart.addCallback(_delay_start, start_engines, furl_file, args.r)
782 dstart.addErrback(_err_and_stop)
790 dstart.addErrback(_err_and_stop)
783
791
784
792
785 def main_ssh(args):
793 def main_ssh(args):
786 """Start a controller on localhost and engines using ssh.
794 """Start a controller on localhost and engines using ssh.
787
795
788 Your clusterfile should look like::
796 Your clusterfile should look like::
789
797
790 send_furl = False # True, if you want
798 send_furl = False # True, if you want
791 engines = {
799 engines = {
792 'engine_host1' : engine_count,
800 'engine_host1' : engine_count,
793 'engine_host2' : engine_count2
801 'engine_host2' : engine_count2
794 }
802 }
795 """
803 """
796 clusterfile = {}
804 clusterfile = {}
797 execfile(args.clusterfile, clusterfile)
805 execfile(args.clusterfile, clusterfile)
798 if not clusterfile.has_key('send_furl'):
806 if not clusterfile.has_key('send_furl'):
799 clusterfile['send_furl'] = False
807 clusterfile['send_furl'] = False
800
808
801 cont_args = []
809 cont_args = []
802 cont_args.append('--logfile=%s' % pjoin(args.logdir,'ipcontroller'))
810 cont_args.append('--logfile=%s' % pjoin(args.logdir,'ipcontroller'))
803
811
804 # Check security settings before proceeding
812 # Check security settings before proceeding
805 if not check_security(args, cont_args):
813 if not check_security(args, cont_args):
806 return
814 return
807
815
808 # See if we are reusing FURL files
816 # See if we are reusing FURL files
809 if not check_reuse(args, cont_args):
817 if not check_reuse(args, cont_args):
810 return
818 return
811
819
812 cl = ControllerLauncher(extra_args=cont_args)
820 cl = ControllerLauncher(extra_args=cont_args)
813 dstart = cl.start()
821 dstart = cl.start()
814 def start_engines(cont_pid):
822 def start_engines(cont_pid):
815 ssh_set = SSHEngineSet(clusterfile['engines'], sshx=args.sshx,
823 ssh_set = SSHEngineSet(clusterfile['engines'], sshx=args.sshx,
816 copyenvs=args.copyenvs)
824 copyenvs=args.copyenvs)
817 def shutdown(signum, frame):
825 def shutdown(signum, frame):
818 d = ssh_set.kill()
826 d = ssh_set.kill()
819 cl.interrupt_then_kill(1.0)
827 cl.interrupt_then_kill(1.0)
820 reactor.callLater(2.0, reactor.stop)
828 reactor.callLater(2.0, reactor.stop)
821 signal.signal(signal.SIGINT,shutdown)
829 signal.signal(signal.SIGINT,shutdown)
822 d = ssh_set.start(clusterfile['send_furl'])
830 d = ssh_set.start(clusterfile['send_furl'])
823 return d
831 return d
824 config = kernel_config_manager.get_config_obj()
832 config = kernel_config_manager.get_config_obj()
825 furl_file = config['controller']['engine_furl_file']
833 furl_file = config['controller']['engine_furl_file']
826 dstart.addCallback(_delay_start, start_engines, furl_file, args.r)
834 dstart.addCallback(_delay_start, start_engines, furl_file, args.r)
827 dstart.addErrback(_err_and_stop)
835 dstart.addErrback(_err_and_stop)
828
836
829
837
830 def get_args():
838 def get_args():
831 base_parser = argparse.ArgumentParser(add_help=False)
839 base_parser = argparse.ArgumentParser(add_help=False)
832 base_parser.add_argument(
840 base_parser.add_argument(
833 '-r',
841 '-r',
834 action='store_true',
842 action='store_true',
835 dest='r',
843 dest='r',
836 help='try to reuse FURL files. Use with --client-port and --engine-port'
844 help='try to reuse FURL files. Use with --client-port and --engine-port'
837 )
845 )
838 base_parser.add_argument(
846 base_parser.add_argument(
839 '--client-port',
847 '--client-port',
840 type=int,
848 type=int,
841 dest='client_port',
849 dest='client_port',
842 help='the port the controller will listen on for client connections',
850 help='the port the controller will listen on for client connections',
843 default=0
851 default=0
844 )
852 )
845 base_parser.add_argument(
853 base_parser.add_argument(
846 '--engine-port',
854 '--engine-port',
847 type=int,
855 type=int,
848 dest='engine_port',
856 dest='engine_port',
849 help='the port the controller will listen on for engine connections',
857 help='the port the controller will listen on for engine connections',
850 default=0
858 default=0
851 )
859 )
852 base_parser.add_argument(
860 base_parser.add_argument(
853 '-x',
861 '-x',
854 action='store_true',
862 action='store_true',
855 dest='x',
863 dest='x',
856 help='turn off client security'
864 help='turn off client security'
857 )
865 )
858 base_parser.add_argument(
866 base_parser.add_argument(
859 '-y',
867 '-y',
860 action='store_true',
868 action='store_true',
861 dest='y',
869 dest='y',
862 help='turn off engine security'
870 help='turn off engine security'
863 )
871 )
864 base_parser.add_argument(
872 base_parser.add_argument(
865 "--logdir",
873 "--logdir",
866 type=str,
874 type=str,
867 dest="logdir",
875 dest="logdir",
868 help="directory to put log files (default=$IPYTHONDIR/log)",
876 help="directory to put log files (default=$IPYTHONDIR/log)",
869 default=pjoin(get_ipython_dir(),'log')
877 default=pjoin(get_ipython_dir(),'log')
870 )
878 )
871 base_parser.add_argument(
879 base_parser.add_argument(
872 "-n",
880 "-n",
873 "--num",
881 "--num",
874 type=int,
882 type=int,
875 dest="n",
883 dest="n",
876 default=2,
884 default=2,
877 help="the number of engines to start"
885 help="the number of engines to start"
878 )
886 )
879
887
880 parser = argparse.ArgumentParser(
888 parser = argparse.ArgumentParser(
881 description='IPython cluster startup. This starts a controller and\
889 description='IPython cluster startup. This starts a controller and\
882 engines using various approaches. Use the IPYTHONDIR environment\
890 engines using various approaches. Use the IPYTHONDIR environment\
883 variable to change your IPython directory from the default of\
891 variable to change your IPython directory from the default of\
884 .ipython or _ipython. The log and security subdirectories of your\
892 .ipython or _ipython. The log and security subdirectories of your\
885 IPython directory will be used by this script for log files and\
893 IPython directory will be used by this script for log files and\
886 security files.'
894 security files.'
887 )
895 )
888 subparsers = parser.add_subparsers(
896 subparsers = parser.add_subparsers(
889 help='available cluster types. For help, do "ipcluster TYPE --help"')
897 help='available cluster types. For help, do "ipcluster TYPE --help"')
890
898
891 parser_local = subparsers.add_parser(
899 parser_local = subparsers.add_parser(
892 'local',
900 'local',
893 help='run a local cluster',
901 help='run a local cluster',
894 parents=[base_parser]
902 parents=[base_parser]
895 )
903 )
896 parser_local.set_defaults(func=main_local)
904 parser_local.set_defaults(func=main_local)
897
905
898 parser_mpirun = subparsers.add_parser(
906 parser_mpirun = subparsers.add_parser(
899 'mpirun',
907 'mpirun',
900 help='run a cluster using mpirun (mpiexec also works)',
908 help='run a cluster using mpirun (mpiexec also works)',
901 parents=[base_parser]
909 parents=[base_parser]
902 )
910 )
903 parser_mpirun.add_argument(
911 parser_mpirun.add_argument(
904 "--mpi",
912 "--mpi",
905 type=str,
913 type=str,
906 dest="mpi", # Don't put a default here to allow no MPI support
914 dest="mpi", # Don't put a default here to allow no MPI support
907 help="how to call MPI_Init (default=mpi4py)"
915 help="how to call MPI_Init (default=mpi4py)"
908 )
916 )
909 parser_mpirun.set_defaults(func=main_mpi, cmd='mpirun')
917 parser_mpirun.set_defaults(func=main_mpi, cmd='mpirun')
910
918
911 parser_mpiexec = subparsers.add_parser(
919 parser_mpiexec = subparsers.add_parser(
912 'mpiexec',
920 'mpiexec',
913 help='run a cluster using mpiexec (mpirun also works)',
921 help='run a cluster using mpiexec (mpirun also works)',
914 parents=[base_parser]
922 parents=[base_parser]
915 )
923 )
916 parser_mpiexec.add_argument(
924 parser_mpiexec.add_argument(
917 "--mpi",
925 "--mpi",
918 type=str,
926 type=str,
919 dest="mpi", # Don't put a default here to allow no MPI support
927 dest="mpi", # Don't put a default here to allow no MPI support
920 help="how to call MPI_Init (default=mpi4py)"
928 help="how to call MPI_Init (default=mpi4py)"
921 )
929 )
922 parser_mpiexec.set_defaults(func=main_mpi, cmd='mpiexec')
930 parser_mpiexec.set_defaults(func=main_mpi, cmd='mpiexec')
923
931
924 parser_pbs = subparsers.add_parser(
932 parser_pbs = subparsers.add_parser(
925 'pbs',
933 'pbs',
926 help='run a pbs cluster',
934 help='run a pbs cluster',
927 parents=[base_parser]
935 parents=[base_parser]
928 )
936 )
929 parser_pbs.add_argument(
937 parser_pbs.add_argument(
930 '-s',
938 '-s',
931 '--pbs-script',
939 '--pbs-script',
932 type=str,
940 type=str,
933 dest='pbsscript',
941 dest='pbsscript',
934 help='PBS script template',
942 help='PBS script template',
935 default=''
943 default=''
936 )
944 )
937 parser_pbs.add_argument(
945 parser_pbs.add_argument(
938 '-q',
946 '-q',
939 '--queue',
947 '--queue',
940 type=str,
948 type=str,
941 dest='pbsqueue',
949 dest='pbsqueue',
942 help='PBS queue to use when starting the engines',
950 help='PBS queue to use when starting the engines',
943 default=None,
951 default=None,
944 )
952 )
945 parser_pbs.set_defaults(func=main_pbs)
953 parser_pbs.set_defaults(func=main_pbs)
946
954
947 parser_sge = subparsers.add_parser(
955 parser_sge = subparsers.add_parser(
948 'sge',
956 'sge',
949 help='run an sge cluster',
957 help='run an sge cluster',
950 parents=[base_parser]
958 parents=[base_parser]
951 )
959 )
952 parser_sge.add_argument(
960 parser_sge.add_argument(
953 '-s',
961 '-s',
954 '--sge-script',
962 '--sge-script',
955 type=str,
963 type=str,
956 dest='sgescript',
964 dest='sgescript',
957 help='SGE script template',
965 help='SGE script template',
958 default='' # SGEEngineSet will create one if not specified
966 default='' # SGEEngineSet will create one if not specified
959 )
967 )
960 parser_sge.add_argument(
968 parser_sge.add_argument(
961 '-q',
969 '-q',
962 '--queue',
970 '--queue',
963 type=str,
971 type=str,
964 dest='sgequeue',
972 dest='sgequeue',
965 help='SGE queue to use when starting the engines',
973 help='SGE queue to use when starting the engines',
966 default=None,
974 default=None,
967 )
975 )
968 parser_sge.set_defaults(func=main_sge)
976 parser_sge.set_defaults(func=main_sge)
969
977
970 parser_lsf = subparsers.add_parser(
978 parser_lsf = subparsers.add_parser(
971 'lsf',
979 'lsf',
972 help='run an lsf cluster',
980 help='run an lsf cluster',
973 parents=[base_parser]
981 parents=[base_parser]
974 )
982 )
975
983
976 parser_lsf.add_argument(
984 parser_lsf.add_argument(
977 '-s',
985 '-s',
978 '--lsf-script',
986 '--lsf-script',
979 type=str,
987 type=str,
980 dest='lsfscript',
988 dest='lsfscript',
981 help='LSF script template',
989 help='LSF script template',
982 default='' # LSFEngineSet will create one if not specified
990 default='' # LSFEngineSet will create one if not specified
983 )
991 )
984
992
985 parser_lsf.add_argument(
993 parser_lsf.add_argument(
986 '-q',
994 '-q',
987 '--queue',
995 '--queue',
988 type=str,
996 type=str,
989 dest='lsfqueue',
997 dest='lsfqueue',
990 help='LSF queue to use when starting the engines',
998 help='LSF queue to use when starting the engines',
991 default=None,
999 default=None,
992 )
1000 )
993 parser_lsf.set_defaults(func=main_lsf)
1001 parser_lsf.set_defaults(func=main_lsf)
994
1002
995 parser_ssh = subparsers.add_parser(
1003 parser_ssh = subparsers.add_parser(
996 'ssh',
1004 'ssh',
997 help='run a cluster using ssh, should have ssh-keys setup',
1005 help='run a cluster using ssh, should have ssh-keys setup',
998 parents=[base_parser]
1006 parents=[base_parser]
999 )
1007 )
1000 parser_ssh.add_argument(
1008 parser_ssh.add_argument(
1001 '-e',
1009 '-e',
1002 '--copyenvs',
1010 '--copyenvs',
1003 action='store_true',
1011 action='store_true',
1004 dest='copyenvs',
1012 dest='copyenvs',
1005 help='Copy current shell environment to remote location',
1013 help='Copy current shell environment to remote location',
1006 default=False,
1014 default=False,
1007 )
1015 )
1008 parser_ssh.add_argument(
1016 parser_ssh.add_argument(
1009 '--clusterfile',
1017 '--clusterfile',
1010 type=str,
1018 type=str,
1011 dest='clusterfile',
1019 dest='clusterfile',
1012 help='python file describing the cluster',
1020 help='python file describing the cluster',
1013 default='clusterfile.py',
1021 default='clusterfile.py',
1014 )
1022 )
1015 parser_ssh.add_argument(
1023 parser_ssh.add_argument(
1016 '--sshx',
1024 '--sshx',
1017 type=str,
1025 type=str,
1018 dest='sshx',
1026 dest='sshx',
1019 help='sshx launcher helper'
1027 help='sshx launcher helper'
1020 )
1028 )
1021 parser_ssh.set_defaults(func=main_ssh)
1029 parser_ssh.set_defaults(func=main_ssh)
1022
1030
1023 args = parser.parse_args()
1031 args = parser.parse_args()
1024 return args
1032 return args
1025
1033
1026 def main():
1034 def main():
1027 args = get_args()
1035 args = get_args()
1028 reactor.callWhenRunning(args.func, args)
1036 reactor.callWhenRunning(args.func, args)
1029 log.startLogging(sys.stdout)
1037 log.startLogging(sys.stdout)
1030 reactor.run()
1038 reactor.run()
1031
1039
1032 if __name__ == '__main__':
1040 if __name__ == '__main__':
1033 main()
1041 main()
General Comments 0
You need to be logged in to leave comments. Login now