Show More
@@ -0,0 +1,331 b'' | |||||
|
1 | """ A minimal application base mixin for all ZMQ based IPython frontends. | |||
|
2 | ||||
|
3 | This is not a complete console app, as subprocess will not be able to receive | |||
|
4 | input, there is no real readline support, among other limitations. This is a | |||
|
5 | refactoring of what used to be the IPython/qt/console/qtconsoleapp.py | |||
|
6 | """ | |||
|
7 | # Copyright (c) IPython Development Team. | |||
|
8 | # Distributed under the terms of the Modified BSD License. | |||
|
9 | ||||
|
10 | import atexit | |||
|
11 | import os | |||
|
12 | import signal | |||
|
13 | import sys | |||
|
14 | import uuid | |||
|
15 | ||||
|
16 | ||||
|
17 | from IPython.config.application import boolean_flag | |||
|
18 | from IPython.core.profiledir import ProfileDir | |||
|
19 | from IPython.kernel.blocking import BlockingKernelClient | |||
|
20 | from IPython.kernel import KernelManager | |||
|
21 | from IPython.kernel import tunnel_to_kernel, find_connection_file | |||
|
22 | from IPython.kernel.kernelspec import NoSuchKernel | |||
|
23 | from IPython.utils.path import filefind | |||
|
24 | from IPython.utils.traitlets import ( | |||
|
25 | Dict, List, Unicode, CUnicode, CBool, Any | |||
|
26 | ) | |||
|
27 | from IPython.kernel.zmq.session import Session | |||
|
28 | from IPython.kernel import connect | |||
|
29 | ConnectionFileMixin = connect.ConnectionFileMixin | |||
|
30 | ||||
|
31 | from IPython.utils.localinterfaces import localhost | |||
|
32 | ||||
|
33 | #----------------------------------------------------------------------------- | |||
|
34 | # Aliases and Flags | |||
|
35 | #----------------------------------------------------------------------------- | |||
|
36 | ||||
|
37 | flags = {} | |||
|
38 | ||||
|
39 | # the flags that are specific to the frontend | |||
|
40 | # these must be scrubbed before being passed to the kernel, | |||
|
41 | # or it will raise an error on unrecognized flags | |||
|
42 | app_flags = { | |||
|
43 | 'existing' : ({'IPythonConsoleApp' : {'existing' : 'kernel*.json'}}, | |||
|
44 | "Connect to an existing kernel. If no argument specified, guess most recent"), | |||
|
45 | } | |||
|
46 | app_flags.update(boolean_flag( | |||
|
47 | 'confirm-exit', 'IPythonConsoleApp.confirm_exit', | |||
|
48 | """Set to display confirmation dialog on exit. You can always use 'exit' or 'quit', | |||
|
49 | to force a direct exit without any confirmation. | |||
|
50 | """, | |||
|
51 | """Don't prompt the user when exiting. This will terminate the kernel | |||
|
52 | if it is owned by the frontend, and leave it alive if it is external. | |||
|
53 | """ | |||
|
54 | )) | |||
|
55 | flags.update(app_flags) | |||
|
56 | ||||
|
57 | aliases = {} | |||
|
58 | ||||
|
59 | # also scrub aliases from the frontend | |||
|
60 | app_aliases = dict( | |||
|
61 | ip = 'IPythonConsoleApp.ip', | |||
|
62 | transport = 'IPythonConsoleApp.transport', | |||
|
63 | hb = 'IPythonConsoleApp.hb_port', | |||
|
64 | shell = 'IPythonConsoleApp.shell_port', | |||
|
65 | iopub = 'IPythonConsoleApp.iopub_port', | |||
|
66 | stdin = 'IPythonConsoleApp.stdin_port', | |||
|
67 | existing = 'IPythonConsoleApp.existing', | |||
|
68 | f = 'IPythonConsoleApp.connection_file', | |||
|
69 | ||||
|
70 | kernel = 'IPythonConsoleApp.kernel_name', | |||
|
71 | ||||
|
72 | ssh = 'IPythonConsoleApp.sshserver', | |||
|
73 | ) | |||
|
74 | aliases.update(app_aliases) | |||
|
75 | ||||
|
76 | #----------------------------------------------------------------------------- | |||
|
77 | # Classes | |||
|
78 | #----------------------------------------------------------------------------- | |||
|
79 | ||||
|
80 | classes = [KernelManager, ProfileDir, Session] | |||
|
81 | ||||
|
82 | class IPythonConsoleApp(ConnectionFileMixin): | |||
|
83 | name = 'ipython-console-mixin' | |||
|
84 | ||||
|
85 | description = """ | |||
|
86 | The IPython Mixin Console. | |||
|
87 | ||||
|
88 | This class contains the common portions of console client (QtConsole, | |||
|
89 | ZMQ-based terminal console, etc). It is not a full console, in that | |||
|
90 | launched terminal subprocesses will not be able to accept input. | |||
|
91 | ||||
|
92 | The Console using this mixing supports various extra features beyond | |||
|
93 | the single-process Terminal IPython shell, such as connecting to | |||
|
94 | existing kernel, via: | |||
|
95 | ||||
|
96 | ipython <appname> --existing | |||
|
97 | ||||
|
98 | as well as tunnel via SSH | |||
|
99 | ||||
|
100 | """ | |||
|
101 | ||||
|
102 | classes = classes | |||
|
103 | flags = Dict(flags) | |||
|
104 | aliases = Dict(aliases) | |||
|
105 | kernel_manager_class = KernelManager | |||
|
106 | kernel_client_class = BlockingKernelClient | |||
|
107 | ||||
|
108 | kernel_argv = List(Unicode) | |||
|
109 | # frontend flags&aliases to be stripped when building kernel_argv | |||
|
110 | frontend_flags = Any(app_flags) | |||
|
111 | frontend_aliases = Any(app_aliases) | |||
|
112 | ||||
|
113 | # create requested profiles by default, if they don't exist: | |||
|
114 | auto_create = CBool(True) | |||
|
115 | # connection info: | |||
|
116 | ||||
|
117 | sshserver = Unicode('', config=True, | |||
|
118 | help="""The SSH server to use to connect to the kernel.""") | |||
|
119 | sshkey = Unicode('', config=True, | |||
|
120 | help="""Path to the ssh key to use for logging in to the ssh server.""") | |||
|
121 | ||||
|
122 | def _connection_file_default(self): | |||
|
123 | return 'kernel-%i.json' % os.getpid() | |||
|
124 | ||||
|
125 | existing = CUnicode('', config=True, | |||
|
126 | help="""Connect to an already running kernel""") | |||
|
127 | ||||
|
128 | kernel_name = Unicode('python', config=True, | |||
|
129 | help="""The name of the default kernel to start.""") | |||
|
130 | ||||
|
131 | confirm_exit = CBool(True, config=True, | |||
|
132 | help=""" | |||
|
133 | Set to display confirmation dialog on exit. You can always use 'exit' or 'quit', | |||
|
134 | to force a direct exit without any confirmation.""", | |||
|
135 | ) | |||
|
136 | ||||
|
137 | def build_kernel_argv(self, argv=None): | |||
|
138 | """build argv to be passed to kernel subprocess | |||
|
139 | ||||
|
140 | Override in subclasses if any args should be passed to the kernel | |||
|
141 | """ | |||
|
142 | self.kernel_argv = self.extra_args | |||
|
143 | ||||
|
144 | def init_connection_file(self): | |||
|
145 | """find the connection file, and load the info if found. | |||
|
146 | ||||
|
147 | The current working directory and the current profile's security | |||
|
148 | directory will be searched for the file if it is not given by | |||
|
149 | absolute path. | |||
|
150 | ||||
|
151 | When attempting to connect to an existing kernel and the `--existing` | |||
|
152 | argument does not match an existing file, it will be interpreted as a | |||
|
153 | fileglob, and the matching file in the current profile's security dir | |||
|
154 | with the latest access time will be used. | |||
|
155 | ||||
|
156 | After this method is called, self.connection_file contains the *full path* | |||
|
157 | to the connection file, never just its name. | |||
|
158 | """ | |||
|
159 | if self.existing: | |||
|
160 | try: | |||
|
161 | cf = find_connection_file(self.existing) | |||
|
162 | except Exception: | |||
|
163 | self.log.critical("Could not find existing kernel connection file %s", self.existing) | |||
|
164 | self.exit(1) | |||
|
165 | self.log.debug("Connecting to existing kernel: %s" % cf) | |||
|
166 | self.connection_file = cf | |||
|
167 | else: | |||
|
168 | # not existing, check if we are going to write the file | |||
|
169 | # and ensure that self.connection_file is a full path, not just the shortname | |||
|
170 | try: | |||
|
171 | cf = find_connection_file(self.connection_file) | |||
|
172 | except Exception: | |||
|
173 | # file might not exist | |||
|
174 | if self.connection_file == os.path.basename(self.connection_file): | |||
|
175 | # just shortname, put it in security dir | |||
|
176 | cf = os.path.join(self.profile_dir.security_dir, self.connection_file) | |||
|
177 | else: | |||
|
178 | cf = self.connection_file | |||
|
179 | self.connection_file = cf | |||
|
180 | try: | |||
|
181 | self.connection_file = filefind(self.connection_file, ['.', self.profile_dir.security_dir]) | |||
|
182 | except IOError: | |||
|
183 | self.log.debug("Connection File not found: %s", self.connection_file) | |||
|
184 | return | |||
|
185 | ||||
|
186 | # should load_connection_file only be used for existing? | |||
|
187 | # as it is now, this allows reusing ports if an existing | |||
|
188 | # file is requested | |||
|
189 | try: | |||
|
190 | self.load_connection_file() | |||
|
191 | except Exception: | |||
|
192 | self.log.error("Failed to load connection file: %r", self.connection_file, exc_info=True) | |||
|
193 | self.exit(1) | |||
|
194 | ||||
|
195 | def init_ssh(self): | |||
|
196 | """set up ssh tunnels, if needed.""" | |||
|
197 | if not self.existing or (not self.sshserver and not self.sshkey): | |||
|
198 | return | |||
|
199 | self.load_connection_file() | |||
|
200 | ||||
|
201 | transport = self.transport | |||
|
202 | ip = self.ip | |||
|
203 | ||||
|
204 | if transport != 'tcp': | |||
|
205 | self.log.error("Can only use ssh tunnels with TCP sockets, not %s", transport) | |||
|
206 | sys.exit(-1) | |||
|
207 | ||||
|
208 | if self.sshkey and not self.sshserver: | |||
|
209 | # specifying just the key implies that we are connecting directly | |||
|
210 | self.sshserver = ip | |||
|
211 | ip = localhost() | |||
|
212 | ||||
|
213 | # build connection dict for tunnels: | |||
|
214 | info = dict(ip=ip, | |||
|
215 | shell_port=self.shell_port, | |||
|
216 | iopub_port=self.iopub_port, | |||
|
217 | stdin_port=self.stdin_port, | |||
|
218 | hb_port=self.hb_port | |||
|
219 | ) | |||
|
220 | ||||
|
221 | self.log.info("Forwarding connections to %s via %s"%(ip, self.sshserver)) | |||
|
222 | ||||
|
223 | # tunnels return a new set of ports, which will be on localhost: | |||
|
224 | self.ip = localhost() | |||
|
225 | try: | |||
|
226 | newports = tunnel_to_kernel(info, self.sshserver, self.sshkey) | |||
|
227 | except: | |||
|
228 | # even catch KeyboardInterrupt | |||
|
229 | self.log.error("Could not setup tunnels", exc_info=True) | |||
|
230 | self.exit(1) | |||
|
231 | ||||
|
232 | self.shell_port, self.iopub_port, self.stdin_port, self.hb_port = newports | |||
|
233 | ||||
|
234 | cf = self.connection_file | |||
|
235 | base,ext = os.path.splitext(cf) | |||
|
236 | base = os.path.basename(base) | |||
|
237 | self.connection_file = os.path.basename(base)+'-ssh'+ext | |||
|
238 | self.log.info("To connect another client via this tunnel, use:") | |||
|
239 | self.log.info("--existing %s" % self.connection_file) | |||
|
240 | ||||
|
241 | def _new_connection_file(self): | |||
|
242 | cf = '' | |||
|
243 | while not cf: | |||
|
244 | # we don't need a 128b id to distinguish kernels, use more readable | |||
|
245 | # 48b node segment (12 hex chars). Users running more than 32k simultaneous | |||
|
246 | # kernels can subclass. | |||
|
247 | ident = str(uuid.uuid4()).split('-')[-1] | |||
|
248 | cf = os.path.join(self.profile_dir.security_dir, 'kernel-%s.json' % ident) | |||
|
249 | # only keep if it's actually new. Protect against unlikely collision | |||
|
250 | # in 48b random search space | |||
|
251 | cf = cf if not os.path.exists(cf) else '' | |||
|
252 | return cf | |||
|
253 | ||||
|
254 | def init_kernel_manager(self): | |||
|
255 | # Don't let Qt or ZMQ swallow KeyboardInterupts. | |||
|
256 | if self.existing: | |||
|
257 | self.kernel_manager = None | |||
|
258 | return | |||
|
259 | signal.signal(signal.SIGINT, signal.SIG_DFL) | |||
|
260 | ||||
|
261 | # Create a KernelManager and start a kernel. | |||
|
262 | try: | |||
|
263 | self.kernel_manager = self.kernel_manager_class( | |||
|
264 | ip=self.ip, | |||
|
265 | session=self.session, | |||
|
266 | transport=self.transport, | |||
|
267 | shell_port=self.shell_port, | |||
|
268 | iopub_port=self.iopub_port, | |||
|
269 | stdin_port=self.stdin_port, | |||
|
270 | hb_port=self.hb_port, | |||
|
271 | connection_file=self.connection_file, | |||
|
272 | kernel_name=self.kernel_name, | |||
|
273 | parent=self, | |||
|
274 | ipython_dir=self.ipython_dir, | |||
|
275 | ) | |||
|
276 | except NoSuchKernel: | |||
|
277 | self.log.critical("Could not find kernel %s", self.kernel_name) | |||
|
278 | self.exit(1) | |||
|
279 | ||||
|
280 | self.kernel_manager.client_factory = self.kernel_client_class | |||
|
281 | # FIXME: remove special treatment of IPython kernels | |||
|
282 | kwargs = {} | |||
|
283 | if self.kernel_manager.ipython_kernel: | |||
|
284 | kwargs['extra_arguments'] = self.kernel_argv | |||
|
285 | self.kernel_manager.start_kernel(**kwargs) | |||
|
286 | atexit.register(self.kernel_manager.cleanup_ipc_files) | |||
|
287 | ||||
|
288 | if self.sshserver: | |||
|
289 | # ssh, write new connection file | |||
|
290 | self.kernel_manager.write_connection_file() | |||
|
291 | ||||
|
292 | # in case KM defaults / ssh writing changes things: | |||
|
293 | km = self.kernel_manager | |||
|
294 | self.shell_port=km.shell_port | |||
|
295 | self.iopub_port=km.iopub_port | |||
|
296 | self.stdin_port=km.stdin_port | |||
|
297 | self.hb_port=km.hb_port | |||
|
298 | self.connection_file = km.connection_file | |||
|
299 | ||||
|
300 | atexit.register(self.kernel_manager.cleanup_connection_file) | |||
|
301 | ||||
|
302 | def init_kernel_client(self): | |||
|
303 | if self.kernel_manager is not None: | |||
|
304 | self.kernel_client = self.kernel_manager.client() | |||
|
305 | else: | |||
|
306 | self.kernel_client = self.kernel_client_class( | |||
|
307 | session=self.session, | |||
|
308 | ip=self.ip, | |||
|
309 | transport=self.transport, | |||
|
310 | shell_port=self.shell_port, | |||
|
311 | iopub_port=self.iopub_port, | |||
|
312 | stdin_port=self.stdin_port, | |||
|
313 | hb_port=self.hb_port, | |||
|
314 | connection_file=self.connection_file, | |||
|
315 | parent=self, | |||
|
316 | ) | |||
|
317 | ||||
|
318 | self.kernel_client.start_channels() | |||
|
319 | ||||
|
320 | ||||
|
321 | ||||
|
322 | def initialize(self, argv=None): | |||
|
323 | """ | |||
|
324 | Classes which mix this class in should call: | |||
|
325 | IPythonConsoleApp.initialize(self,argv) | |||
|
326 | """ | |||
|
327 | self.init_connection_file() | |||
|
328 | self.init_ssh() | |||
|
329 | self.init_kernel_manager() | |||
|
330 | self.init_kernel_client() | |||
|
331 |
@@ -1,331 +1,13 b'' | |||||
1 | """ A minimal application base mixin for all ZMQ based IPython frontends. |
|
1 | """ | |
2 |
|
2 | Shim to maintain backwards compatibility with old IPython.consoleapp imports. | ||
3 | This is not a complete console app, as subprocess will not be able to receive |
|
|||
4 | input, there is no real readline support, among other limitations. This is a |
|
|||
5 | refactoring of what used to be the IPython/qt/console/qtconsoleapp.py |
|
|||
6 | """ |
|
3 | """ | |
7 | # Copyright (c) IPython Development Team. |
|
4 | # Copyright (c) IPython Development Team. | |
8 | # Distributed under the terms of the Modified BSD License. |
|
5 | # Distributed under the terms of the Modified BSD License. | |
9 |
|
6 | |||
10 | import atexit |
|
|||
11 | import os |
|
|||
12 | import signal |
|
|||
13 | import sys |
|
7 | import sys | |
14 | import uuid |
|
8 | from warnings import warn | |
15 |
|
||||
16 |
|
||||
17 | from IPython.config.application import boolean_flag |
|
|||
18 | from IPython.core.profiledir import ProfileDir |
|
|||
19 | from IPython.kernel.blocking import BlockingKernelClient |
|
|||
20 | from IPython.kernel import KernelManager |
|
|||
21 | from IPython.kernel import tunnel_to_kernel, find_connection_file |
|
|||
22 | from IPython.kernel.kernelspec import NoSuchKernel |
|
|||
23 | from IPython.utils.path import filefind |
|
|||
24 | from IPython.utils.traitlets import ( |
|
|||
25 | Dict, List, Unicode, CUnicode, CBool, Any |
|
|||
26 | ) |
|
|||
27 | from IPython.kernel.zmq.session import Session |
|
|||
28 | from IPython.kernel import connect |
|
|||
29 | ConnectionFileMixin = connect.ConnectionFileMixin |
|
|||
30 |
|
||||
31 | from IPython.utils.localinterfaces import localhost |
|
|||
32 |
|
||||
33 | #----------------------------------------------------------------------------- |
|
|||
34 | # Aliases and Flags |
|
|||
35 | #----------------------------------------------------------------------------- |
|
|||
36 |
|
||||
37 | flags = {} |
|
|||
38 |
|
||||
39 | # the flags that are specific to the frontend |
|
|||
40 | # these must be scrubbed before being passed to the kernel, |
|
|||
41 | # or it will raise an error on unrecognized flags |
|
|||
42 | app_flags = { |
|
|||
43 | 'existing' : ({'IPythonConsoleApp' : {'existing' : 'kernel*.json'}}, |
|
|||
44 | "Connect to an existing kernel. If no argument specified, guess most recent"), |
|
|||
45 | } |
|
|||
46 | app_flags.update(boolean_flag( |
|
|||
47 | 'confirm-exit', 'IPythonConsoleApp.confirm_exit', |
|
|||
48 | """Set to display confirmation dialog on exit. You can always use 'exit' or 'quit', |
|
|||
49 | to force a direct exit without any confirmation. |
|
|||
50 | """, |
|
|||
51 | """Don't prompt the user when exiting. This will terminate the kernel |
|
|||
52 | if it is owned by the frontend, and leave it alive if it is external. |
|
|||
53 | """ |
|
|||
54 | )) |
|
|||
55 | flags.update(app_flags) |
|
|||
56 |
|
||||
57 | aliases = {} |
|
|||
58 |
|
||||
59 | # also scrub aliases from the frontend |
|
|||
60 | app_aliases = dict( |
|
|||
61 | ip = 'IPythonConsoleApp.ip', |
|
|||
62 | transport = 'IPythonConsoleApp.transport', |
|
|||
63 | hb = 'IPythonConsoleApp.hb_port', |
|
|||
64 | shell = 'IPythonConsoleApp.shell_port', |
|
|||
65 | iopub = 'IPythonConsoleApp.iopub_port', |
|
|||
66 | stdin = 'IPythonConsoleApp.stdin_port', |
|
|||
67 | existing = 'IPythonConsoleApp.existing', |
|
|||
68 | f = 'IPythonConsoleApp.connection_file', |
|
|||
69 |
|
||||
70 | kernel = 'IPythonConsoleApp.kernel_name', |
|
|||
71 |
|
||||
72 | ssh = 'IPythonConsoleApp.sshserver', |
|
|||
73 | ) |
|
|||
74 | aliases.update(app_aliases) |
|
|||
75 |
|
||||
76 | #----------------------------------------------------------------------------- |
|
|||
77 | # Classes |
|
|||
78 | #----------------------------------------------------------------------------- |
|
|||
79 |
|
||||
80 | classes = [KernelManager, ProfileDir, Session] |
|
|||
81 |
|
||||
82 | class IPythonConsoleApp(ConnectionFileMixin): |
|
|||
83 | name = 'ipython-console-mixin' |
|
|||
84 |
|
||||
85 | description = """ |
|
|||
86 | The IPython Mixin Console. |
|
|||
87 |
|
||||
88 | This class contains the common portions of console client (QtConsole, |
|
|||
89 | ZMQ-based terminal console, etc). It is not a full console, in that |
|
|||
90 | launched terminal subprocesses will not be able to accept input. |
|
|||
91 |
|
||||
92 | The Console using this mixing supports various extra features beyond |
|
|||
93 | the single-process Terminal IPython shell, such as connecting to |
|
|||
94 | existing kernel, via: |
|
|||
95 |
|
||||
96 | ipython <appname> --existing |
|
|||
97 |
|
||||
98 | as well as tunnel via SSH |
|
|||
99 |
|
||||
100 | """ |
|
|||
101 |
|
||||
102 | classes = classes |
|
|||
103 | flags = Dict(flags) |
|
|||
104 | aliases = Dict(aliases) |
|
|||
105 | kernel_manager_class = KernelManager |
|
|||
106 | kernel_client_class = BlockingKernelClient |
|
|||
107 |
|
||||
108 | kernel_argv = List(Unicode) |
|
|||
109 | # frontend flags&aliases to be stripped when building kernel_argv |
|
|||
110 | frontend_flags = Any(app_flags) |
|
|||
111 | frontend_aliases = Any(app_aliases) |
|
|||
112 |
|
||||
113 | # create requested profiles by default, if they don't exist: |
|
|||
114 | auto_create = CBool(True) |
|
|||
115 | # connection info: |
|
|||
116 |
|
||||
117 | sshserver = Unicode('', config=True, |
|
|||
118 | help="""The SSH server to use to connect to the kernel.""") |
|
|||
119 | sshkey = Unicode('', config=True, |
|
|||
120 | help="""Path to the ssh key to use for logging in to the ssh server.""") |
|
|||
121 |
|
||||
122 | def _connection_file_default(self): |
|
|||
123 | return 'kernel-%i.json' % os.getpid() |
|
|||
124 |
|
||||
125 | existing = CUnicode('', config=True, |
|
|||
126 | help="""Connect to an already running kernel""") |
|
|||
127 |
|
||||
128 | kernel_name = Unicode('python', config=True, |
|
|||
129 | help="""The name of the default kernel to start.""") |
|
|||
130 |
|
||||
131 | confirm_exit = CBool(True, config=True, |
|
|||
132 | help=""" |
|
|||
133 | Set to display confirmation dialog on exit. You can always use 'exit' or 'quit', |
|
|||
134 | to force a direct exit without any confirmation.""", |
|
|||
135 | ) |
|
|||
136 |
|
||||
137 | def build_kernel_argv(self, argv=None): |
|
|||
138 | """build argv to be passed to kernel subprocess |
|
|||
139 |
|
||||
140 | Override in subclasses if any args should be passed to the kernel |
|
|||
141 | """ |
|
|||
142 | self.kernel_argv = self.extra_args |
|
|||
143 |
|
||||
144 | def init_connection_file(self): |
|
|||
145 | """find the connection file, and load the info if found. |
|
|||
146 |
|
||||
147 | The current working directory and the current profile's security |
|
|||
148 | directory will be searched for the file if it is not given by |
|
|||
149 | absolute path. |
|
|||
150 |
|
||||
151 | When attempting to connect to an existing kernel and the `--existing` |
|
|||
152 | argument does not match an existing file, it will be interpreted as a |
|
|||
153 | fileglob, and the matching file in the current profile's security dir |
|
|||
154 | with the latest access time will be used. |
|
|||
155 |
|
||||
156 | After this method is called, self.connection_file contains the *full path* |
|
|||
157 | to the connection file, never just its name. |
|
|||
158 | """ |
|
|||
159 | if self.existing: |
|
|||
160 | try: |
|
|||
161 | cf = find_connection_file(self.existing) |
|
|||
162 | except Exception: |
|
|||
163 | self.log.critical("Could not find existing kernel connection file %s", self.existing) |
|
|||
164 | self.exit(1) |
|
|||
165 | self.log.debug("Connecting to existing kernel: %s" % cf) |
|
|||
166 | self.connection_file = cf |
|
|||
167 | else: |
|
|||
168 | # not existing, check if we are going to write the file |
|
|||
169 | # and ensure that self.connection_file is a full path, not just the shortname |
|
|||
170 | try: |
|
|||
171 | cf = find_connection_file(self.connection_file) |
|
|||
172 | except Exception: |
|
|||
173 | # file might not exist |
|
|||
174 | if self.connection_file == os.path.basename(self.connection_file): |
|
|||
175 | # just shortname, put it in security dir |
|
|||
176 | cf = os.path.join(self.profile_dir.security_dir, self.connection_file) |
|
|||
177 | else: |
|
|||
178 | cf = self.connection_file |
|
|||
179 | self.connection_file = cf |
|
|||
180 | try: |
|
|||
181 | self.connection_file = filefind(self.connection_file, ['.', self.profile_dir.security_dir]) |
|
|||
182 | except IOError: |
|
|||
183 | self.log.debug("Connection File not found: %s", self.connection_file) |
|
|||
184 | return |
|
|||
185 |
|
||||
186 | # should load_connection_file only be used for existing? |
|
|||
187 | # as it is now, this allows reusing ports if an existing |
|
|||
188 | # file is requested |
|
|||
189 | try: |
|
|||
190 | self.load_connection_file() |
|
|||
191 | except Exception: |
|
|||
192 | self.log.error("Failed to load connection file: %r", self.connection_file, exc_info=True) |
|
|||
193 | self.exit(1) |
|
|||
194 |
|
||||
195 | def init_ssh(self): |
|
|||
196 | """set up ssh tunnels, if needed.""" |
|
|||
197 | if not self.existing or (not self.sshserver and not self.sshkey): |
|
|||
198 | return |
|
|||
199 | self.load_connection_file() |
|
|||
200 |
|
||||
201 | transport = self.transport |
|
|||
202 | ip = self.ip |
|
|||
203 |
|
||||
204 | if transport != 'tcp': |
|
|||
205 | self.log.error("Can only use ssh tunnels with TCP sockets, not %s", transport) |
|
|||
206 | sys.exit(-1) |
|
|||
207 |
|
||||
208 | if self.sshkey and not self.sshserver: |
|
|||
209 | # specifying just the key implies that we are connecting directly |
|
|||
210 | self.sshserver = ip |
|
|||
211 | ip = localhost() |
|
|||
212 |
|
||||
213 | # build connection dict for tunnels: |
|
|||
214 | info = dict(ip=ip, |
|
|||
215 | shell_port=self.shell_port, |
|
|||
216 | iopub_port=self.iopub_port, |
|
|||
217 | stdin_port=self.stdin_port, |
|
|||
218 | hb_port=self.hb_port |
|
|||
219 | ) |
|
|||
220 |
|
||||
221 | self.log.info("Forwarding connections to %s via %s"%(ip, self.sshserver)) |
|
|||
222 |
|
||||
223 | # tunnels return a new set of ports, which will be on localhost: |
|
|||
224 | self.ip = localhost() |
|
|||
225 | try: |
|
|||
226 | newports = tunnel_to_kernel(info, self.sshserver, self.sshkey) |
|
|||
227 | except: |
|
|||
228 | # even catch KeyboardInterrupt |
|
|||
229 | self.log.error("Could not setup tunnels", exc_info=True) |
|
|||
230 | self.exit(1) |
|
|||
231 |
|
||||
232 | self.shell_port, self.iopub_port, self.stdin_port, self.hb_port = newports |
|
|||
233 |
|
||||
234 | cf = self.connection_file |
|
|||
235 | base,ext = os.path.splitext(cf) |
|
|||
236 | base = os.path.basename(base) |
|
|||
237 | self.connection_file = os.path.basename(base)+'-ssh'+ext |
|
|||
238 | self.log.info("To connect another client via this tunnel, use:") |
|
|||
239 | self.log.info("--existing %s" % self.connection_file) |
|
|||
240 |
|
||||
241 | def _new_connection_file(self): |
|
|||
242 | cf = '' |
|
|||
243 | while not cf: |
|
|||
244 | # we don't need a 128b id to distinguish kernels, use more readable |
|
|||
245 | # 48b node segment (12 hex chars). Users running more than 32k simultaneous |
|
|||
246 | # kernels can subclass. |
|
|||
247 | ident = str(uuid.uuid4()).split('-')[-1] |
|
|||
248 | cf = os.path.join(self.profile_dir.security_dir, 'kernel-%s.json' % ident) |
|
|||
249 | # only keep if it's actually new. Protect against unlikely collision |
|
|||
250 | # in 48b random search space |
|
|||
251 | cf = cf if not os.path.exists(cf) else '' |
|
|||
252 | return cf |
|
|||
253 |
|
||||
254 | def init_kernel_manager(self): |
|
|||
255 | # Don't let Qt or ZMQ swallow KeyboardInterupts. |
|
|||
256 | if self.existing: |
|
|||
257 | self.kernel_manager = None |
|
|||
258 | return |
|
|||
259 | signal.signal(signal.SIGINT, signal.SIG_DFL) |
|
|||
260 |
|
||||
261 | # Create a KernelManager and start a kernel. |
|
|||
262 | try: |
|
|||
263 | self.kernel_manager = self.kernel_manager_class( |
|
|||
264 | ip=self.ip, |
|
|||
265 | session=self.session, |
|
|||
266 | transport=self.transport, |
|
|||
267 | shell_port=self.shell_port, |
|
|||
268 | iopub_port=self.iopub_port, |
|
|||
269 | stdin_port=self.stdin_port, |
|
|||
270 | hb_port=self.hb_port, |
|
|||
271 | connection_file=self.connection_file, |
|
|||
272 | kernel_name=self.kernel_name, |
|
|||
273 | parent=self, |
|
|||
274 | ipython_dir=self.ipython_dir, |
|
|||
275 | ) |
|
|||
276 | except NoSuchKernel: |
|
|||
277 | self.log.critical("Could not find kernel %s", self.kernel_name) |
|
|||
278 | self.exit(1) |
|
|||
279 |
|
||||
280 | self.kernel_manager.client_factory = self.kernel_client_class |
|
|||
281 | # FIXME: remove special treatment of IPython kernels |
|
|||
282 | kwargs = {} |
|
|||
283 | if self.kernel_manager.ipython_kernel: |
|
|||
284 | kwargs['extra_arguments'] = self.kernel_argv |
|
|||
285 | self.kernel_manager.start_kernel(**kwargs) |
|
|||
286 | atexit.register(self.kernel_manager.cleanup_ipc_files) |
|
|||
287 |
|
||||
288 | if self.sshserver: |
|
|||
289 | # ssh, write new connection file |
|
|||
290 | self.kernel_manager.write_connection_file() |
|
|||
291 |
|
||||
292 | # in case KM defaults / ssh writing changes things: |
|
|||
293 | km = self.kernel_manager |
|
|||
294 | self.shell_port=km.shell_port |
|
|||
295 | self.iopub_port=km.iopub_port |
|
|||
296 | self.stdin_port=km.stdin_port |
|
|||
297 | self.hb_port=km.hb_port |
|
|||
298 | self.connection_file = km.connection_file |
|
|||
299 |
|
||||
300 | atexit.register(self.kernel_manager.cleanup_connection_file) |
|
|||
301 |
|
||||
302 | def init_kernel_client(self): |
|
|||
303 | if self.kernel_manager is not None: |
|
|||
304 | self.kernel_client = self.kernel_manager.client() |
|
|||
305 | else: |
|
|||
306 | self.kernel_client = self.kernel_client_class( |
|
|||
307 | session=self.session, |
|
|||
308 | ip=self.ip, |
|
|||
309 | transport=self.transport, |
|
|||
310 | shell_port=self.shell_port, |
|
|||
311 | iopub_port=self.iopub_port, |
|
|||
312 | stdin_port=self.stdin_port, |
|
|||
313 | hb_port=self.hb_port, |
|
|||
314 | connection_file=self.connection_file, |
|
|||
315 | parent=self, |
|
|||
316 | ) |
|
|||
317 |
|
||||
318 | self.kernel_client.start_channels() |
|
|||
319 |
|
||||
320 |
|
||||
321 |
|
9 | |||
322 | def initialize(self, argv=None): |
|
10 | warn("The `IPython.consoleapp` package has been deprecated. " | |
323 | """ |
|
11 | "You should import from jupyter_client.consoleapp instead.") | |
324 | Classes which mix this class in should call: |
|
|||
325 | IPythonConsoleApp.initialize(self,argv) |
|
|||
326 | """ |
|
|||
327 | self.init_connection_file() |
|
|||
328 | self.init_ssh() |
|
|||
329 | self.init_kernel_manager() |
|
|||
330 | self.init_kernel_client() |
|
|||
331 |
|
12 | |||
|
13 | from jupyter_client.consoleapp import * |
General Comments 0
You need to be logged in to leave comments.
Login now