##// END OF EJS Templates
Change $.post to this.post in the kernel js file...
Jason Grout -
Show More
@@ -1,602 +1,603
1 1 //----------------------------------------------------------------------------
2 2 // Copyright (C) 2008-2011 The IPython Development Team
3 3 //
4 4 // Distributed under the terms of the BSD License. The full license is in
5 5 // the file COPYING, distributed as part of this software.
6 6 //----------------------------------------------------------------------------
7 7
8 8 //============================================================================
9 9 // Kernel
10 10 //============================================================================
11 11
12 12 /**
13 13 * @module IPython
14 14 * @namespace IPython
15 15 * @submodule Kernel
16 16 */
17 17
18 18 var IPython = (function (IPython) {
19 19 "use strict";
20 20
21 21 var utils = IPython.utils;
22 22
23 23 // Initialization and connection.
24 24 /**
25 25 * A Kernel Class to communicate with the Python kernel
26 26 * @Class Kernel
27 27 */
28 28 var Kernel = function (kernel_service_url) {
29 29 this.kernel_id = null;
30 30 this.shell_channel = null;
31 31 this.iopub_channel = null;
32 32 this.stdin_channel = null;
33 33 this.kernel_service_url = kernel_service_url;
34 34 this.running = false;
35 35 this.username = "username";
36 36 this.session_id = utils.uuid();
37 37 this._msg_callbacks = {};
38 this.post = $.post;
38 39
39 40 if (typeof(WebSocket) !== 'undefined') {
40 41 this.WebSocket = WebSocket;
41 42 } else if (typeof(MozWebSocket) !== 'undefined') {
42 43 this.WebSocket = MozWebSocket;
43 44 } else {
44 45 alert('Your browser does not have WebSocket support, please try Chrome, Safari or Firefox β‰₯ 6. Firefox 4 and 5 are also supported by you have to enable WebSockets in about:config.');
45 46 }
46 47
47 48 this.bind_events();
48 49 this.init_iopub_handlers();
49 50 this.comm_manager = new IPython.CommManager(this);
50 51 this.widget_manager = new IPython.WidgetManager(this.comm_manager);
51 52 };
52 53
53 54
54 55 Kernel.prototype._get_msg = function (msg_type, content, metadata) {
55 56 var msg = {
56 57 header : {
57 58 msg_id : utils.uuid(),
58 59 username : this.username,
59 60 session : this.session_id,
60 61 msg_type : msg_type
61 62 },
62 63 metadata : metadata || {},
63 64 content : content,
64 65 parent_header : {}
65 66 };
66 67 return msg;
67 68 };
68 69
69 70 Kernel.prototype.bind_events = function () {
70 71 var that = this;
71 72 $([IPython.events]).on('send_input_reply.Kernel', function(evt, data) {
72 73 that.send_input_reply(data);
73 74 });
74 75 };
75 76
76 77 // Initialize the iopub handlers
77 78
78 79 Kernel.prototype.init_iopub_handlers = function () {
79 80 var output_types = ['stream', 'display_data', 'pyout', 'pyerr'];
80 81 this._iopub_handlers = {};
81 82 this.register_iopub_handler('status', $.proxy(this._handle_status_message, this));
82 83 this.register_iopub_handler('clear_output', $.proxy(this._handle_clear_output, this));
83 84
84 85 for (var i=0; i < output_types.length; i++) {
85 86 this.register_iopub_handler(output_types[i], $.proxy(this._handle_output_message, this));
86 87 }
87 88 };
88 89
89 90 /**
90 91 * Start the Python kernel
91 92 * @method start
92 93 */
93 94 Kernel.prototype.start = function (params) {
94 95 params = params || {};
95 96 if (!this.running) {
96 97 var qs = $.param(params);
97 $.post(utils.url_join_encode(this.kernel_service_url) + '?' + qs,
98 this.post(utils.url_join_encode(this.kernel_service_url) + '?' + qs,
98 99 $.proxy(this._kernel_started, this),
99 100 'json'
100 101 );
101 102 }
102 103 };
103 104
104 105 /**
105 106 * Restart the python kernel.
106 107 *
107 108 * Emit a 'status_restarting.Kernel' event with
108 109 * the current object as parameter
109 110 *
110 111 * @method restart
111 112 */
112 113 Kernel.prototype.restart = function () {
113 114 $([IPython.events]).trigger('status_restarting.Kernel', {kernel: this});
114 115 if (this.running) {
115 116 this.stop_channels();
116 $.post(utils.url_join_encode(this.kernel_url, "restart"),
117 this.post(utils.url_join_encode(this.kernel_url, "restart"),
117 118 $.proxy(this._kernel_started, this),
118 119 'json'
119 120 );
120 121 }
121 122 };
122 123
123 124
124 125 Kernel.prototype._kernel_started = function (json) {
125 126 console.log("Kernel started: ", json.id);
126 127 this.running = true;
127 128 this.kernel_id = json.id;
128 129 // trailing 's' in https will become wss for secure web sockets
129 130 this.ws_host = location.protocol.replace('http', 'ws') + "//" + location.host;
130 131 this.kernel_url = utils.url_path_join(this.kernel_service_url, this.kernel_id);
131 132 this.start_channels();
132 133 };
133 134
134 135
135 136 Kernel.prototype._websocket_closed = function(ws_url, early) {
136 137 this.stop_channels();
137 138 $([IPython.events]).trigger('websocket_closed.Kernel',
138 139 {ws_url: ws_url, kernel: this, early: early}
139 140 );
140 141 };
141 142
142 143 /**
143 144 * Start the `shell`and `iopub` channels.
144 145 * Will stop and restart them if they already exist.
145 146 *
146 147 * @method start_channels
147 148 */
148 149 Kernel.prototype.start_channels = function () {
149 150 var that = this;
150 151 this.stop_channels();
151 152 var ws_host_url = this.ws_host + this.kernel_url;
152 153 console.log("Starting WebSockets:", ws_host_url);
153 154 this.shell_channel = new this.WebSocket(
154 155 this.ws_host + utils.url_join_encode(this.kernel_url, "shell")
155 156 );
156 157 this.stdin_channel = new this.WebSocket(
157 158 this.ws_host + utils.url_join_encode(this.kernel_url, "stdin")
158 159 );
159 160 this.iopub_channel = new this.WebSocket(
160 161 this.ws_host + utils.url_join_encode(this.kernel_url, "iopub")
161 162 );
162 163
163 164 var already_called_onclose = false; // only alert once
164 165 var ws_closed_early = function(evt){
165 166 if (already_called_onclose){
166 167 return;
167 168 }
168 169 already_called_onclose = true;
169 170 if ( ! evt.wasClean ){
170 171 that._websocket_closed(ws_host_url, true);
171 172 }
172 173 };
173 174 var ws_closed_late = function(evt){
174 175 if (already_called_onclose){
175 176 return;
176 177 }
177 178 already_called_onclose = true;
178 179 if ( ! evt.wasClean ){
179 180 that._websocket_closed(ws_host_url, false);
180 181 }
181 182 };
182 183 var channels = [this.shell_channel, this.iopub_channel, this.stdin_channel];
183 184 for (var i=0; i < channels.length; i++) {
184 185 channels[i].onopen = $.proxy(this._ws_opened, this);
185 186 channels[i].onclose = ws_closed_early;
186 187 }
187 188 // switch from early-close to late-close message after 1s
188 189 setTimeout(function() {
189 190 for (var i=0; i < channels.length; i++) {
190 191 if (channels[i] !== null) {
191 192 channels[i].onclose = ws_closed_late;
192 193 }
193 194 }
194 195 }, 1000);
195 196 this.shell_channel.onmessage = $.proxy(this._handle_shell_reply, this);
196 197 this.iopub_channel.onmessage = $.proxy(this._handle_iopub_message, this);
197 198 this.stdin_channel.onmessage = $.proxy(this._handle_input_request, this);
198 199 };
199 200
200 201 /**
201 202 * Handle a websocket entering the open state
202 203 * sends session and cookie authentication info as first message.
203 204 * Once all sockets are open, signal the Kernel.status_started event.
204 205 * @method _ws_opened
205 206 */
206 207 Kernel.prototype._ws_opened = function (evt) {
207 208 // send the session id so the Session object Python-side
208 209 // has the same identity
209 210 evt.target.send(this.session_id + ':' + document.cookie);
210 211
211 212 var channels = [this.shell_channel, this.iopub_channel, this.stdin_channel];
212 213 for (var i=0; i < channels.length; i++) {
213 214 // if any channel is not ready, don't trigger event.
214 215 if ( !channels[i].readyState ) return;
215 216 }
216 217 // all events ready, trigger started event.
217 218 $([IPython.events]).trigger('status_started.Kernel', {kernel: this});
218 219 };
219 220
220 221 /**
221 222 * Stop the websocket channels.
222 223 * @method stop_channels
223 224 */
224 225 Kernel.prototype.stop_channels = function () {
225 226 var channels = [this.shell_channel, this.iopub_channel, this.stdin_channel];
226 227 for (var i=0; i < channels.length; i++) {
227 228 if ( channels[i] !== null ) {
228 229 channels[i].onclose = null;
229 230 channels[i].close();
230 231 }
231 232 }
232 233 this.shell_channel = this.iopub_channel = this.stdin_channel = null;
233 234 };
234 235
235 236 // Main public methods.
236 237
237 238 // send a message on the Kernel's shell channel
238 239 Kernel.prototype.send_shell_message = function (msg_type, content, callbacks, metadata) {
239 240 var msg = this._get_msg(msg_type, content, metadata);
240 241 this.shell_channel.send(JSON.stringify(msg));
241 242 this.set_callbacks_for_msg(msg.header.msg_id, callbacks);
242 243 return msg.header.msg_id;
243 244 };
244 245
245 246 /**
246 247 * Get kernel info
247 248 *
248 249 * @param callback {function}
249 250 * @method object_info
250 251 *
251 252 * When calling this method, pass a callback function that expects one argument.
252 253 * The callback will be passed the complete `kernel_info_reply` message documented
253 254 * [here](http://ipython.org/ipython-doc/dev/development/messaging.html#kernel-info)
254 255 */
255 256 Kernel.prototype.kernel_info = function (callback) {
256 257 var callbacks;
257 258 if (callback) {
258 259 callbacks = { shell : { reply : callback } };
259 260 }
260 261 return this.send_shell_message("kernel_info_request", {}, callbacks);
261 262 };
262 263
263 264 /**
264 265 * Get info on an object
265 266 *
266 267 * @param objname {string}
267 268 * @param callback {function}
268 269 * @method object_info
269 270 *
270 271 * When calling this method, pass a callback function that expects one argument.
271 272 * The callback will be passed the complete `object_info_reply` message documented
272 273 * [here](http://ipython.org/ipython-doc/dev/development/messaging.html#object-information)
273 274 */
274 275 Kernel.prototype.object_info = function (objname, callback) {
275 276 var callbacks;
276 277 if (callback) {
277 278 callbacks = { shell : { reply : callback } };
278 279 }
279 280
280 281 if (typeof(objname) !== null && objname !== null) {
281 282 var content = {
282 283 oname : objname.toString(),
283 284 detail_level : 0,
284 285 };
285 286 return this.send_shell_message("object_info_request", content, callbacks);
286 287 }
287 288 return;
288 289 };
289 290
290 291 /**
291 292 * Execute given code into kernel, and pass result to callback.
292 293 *
293 294 * @async
294 295 * @method execute
295 296 * @param {string} code
296 297 * @param [callbacks] {Object} With the following keys (all optional)
297 298 * @param callbacks.shell.reply {function}
298 299 * @param callbacks.shell.payload.[payload_name] {function}
299 300 * @param callbacks.iopub.output {function}
300 301 * @param callbacks.iopub.clear_output {function}
301 302 * @param callbacks.input {function}
302 303 * @param {object} [options]
303 304 * @param [options.silent=false] {Boolean}
304 305 * @param [options.user_expressions=empty_dict] {Dict}
305 306 * @param [options.user_variables=empty_list] {List od Strings}
306 307 * @param [options.allow_stdin=false] {Boolean} true|false
307 308 *
308 309 * @example
309 310 *
310 311 * The options object should contain the options for the execute call. Its default
311 312 * values are:
312 313 *
313 314 * options = {
314 315 * silent : true,
315 316 * user_variables : [],
316 317 * user_expressions : {},
317 318 * allow_stdin : false
318 319 * }
319 320 *
320 321 * When calling this method pass a callbacks structure of the form:
321 322 *
322 323 * callbacks = {
323 324 * shell : {
324 325 * reply : execute_reply_callback,
325 326 * payload : {
326 327 * set_next_input : set_next_input_callback,
327 328 * }
328 329 * },
329 330 * iopub : {
330 331 * output : output_callback,
331 332 * clear_output : clear_output_callback,
332 333 * },
333 334 * input : raw_input_callback
334 335 * }
335 336 *
336 337 * Each callback will be passed the entire message as a single arugment.
337 338 * Payload handlers will be passed the corresponding payload and the execute_reply message.
338 339 */
339 340 Kernel.prototype.execute = function (code, callbacks, options) {
340 341
341 342 var content = {
342 343 code : code,
343 344 silent : true,
344 345 store_history : false,
345 346 user_variables : [],
346 347 user_expressions : {},
347 348 allow_stdin : false
348 349 };
349 350 callbacks = callbacks || {};
350 351 if (callbacks.input !== undefined) {
351 352 content.allow_stdin = true;
352 353 }
353 354 $.extend(true, content, options);
354 355 $([IPython.events]).trigger('execution_request.Kernel', {kernel: this, content:content});
355 356 return this.send_shell_message("execute_request", content, callbacks);
356 357 };
357 358
358 359 /**
359 360 * When calling this method, pass a function to be called with the `complete_reply` message
360 361 * as its only argument when it arrives.
361 362 *
362 363 * `complete_reply` is documented
363 364 * [here](http://ipython.org/ipython-doc/dev/development/messaging.html#complete)
364 365 *
365 366 * @method complete
366 367 * @param line {integer}
367 368 * @param cursor_pos {integer}
368 369 * @param callback {function}
369 370 *
370 371 */
371 372 Kernel.prototype.complete = function (line, cursor_pos, callback) {
372 373 var callbacks;
373 374 if (callback) {
374 375 callbacks = { shell : { reply : callback } };
375 376 }
376 377 var content = {
377 378 text : '',
378 379 line : line,
379 380 block : null,
380 381 cursor_pos : cursor_pos
381 382 };
382 383 return this.send_shell_message("complete_request", content, callbacks);
383 384 };
384 385
385 386
386 387 Kernel.prototype.interrupt = function () {
387 388 if (this.running) {
388 389 $([IPython.events]).trigger('status_interrupting.Kernel', {kernel: this});
389 $.post(utils.url_join_encode(this.kernel_url, "interrupt"));
390 this.post(utils.url_join_encode(this.kernel_url, "interrupt"));
390 391 }
391 392 };
392 393
393 394
394 395 Kernel.prototype.kill = function () {
395 396 if (this.running) {
396 397 this.running = false;
397 398 var settings = {
398 399 cache : false,
399 400 type : "DELETE"
400 401 };
401 402 $.ajax(utils.url_join_encode(this.kernel_url), settings);
402 403 }
403 404 };
404 405
405 406 Kernel.prototype.send_input_reply = function (input) {
406 407 var content = {
407 408 value : input,
408 409 };
409 410 $([IPython.events]).trigger('input_reply.Kernel', {kernel: this, content:content});
410 411 var msg = this._get_msg("input_reply", content);
411 412 this.stdin_channel.send(JSON.stringify(msg));
412 413 return msg.header.msg_id;
413 414 };
414 415
415 416
416 417 // Reply handlers
417 418
418 419 Kernel.prototype.register_iopub_handler = function (msg_type, callback) {
419 420 this._iopub_handlers[msg_type] = callback;
420 421 };
421 422
422 423 Kernel.prototype.get_iopub_handler = function (msg_type) {
423 424 // get iopub handler for a specific message type
424 425 return this._iopub_handlers[msg_type];
425 426 };
426 427
427 428
428 429 Kernel.prototype.get_callbacks_for_msg = function (msg_id) {
429 430 // get callbacks for a specific message
430 431 return this._msg_callbacks[msg_id];
431 432 };
432 433
433 434
434 435 Kernel.prototype.clear_callbacks_for_msg = function (msg_id) {
435 436 if (this._msg_callbacks[msg_id] !== undefined ) {
436 437 delete this._msg_callbacks[msg_id];
437 438 }
438 439 };
439 440
440 441 /* Set callbacks for a particular message.
441 442 * Callbacks should be a struct of the following form:
442 443 * shell : {
443 444 *
444 445 * }
445 446
446 447 */
447 448 Kernel.prototype.set_callbacks_for_msg = function (msg_id, callbacks) {
448 449 if (callbacks) {
449 450 // shallow-copy mapping, because we will modify it at the top level
450 451 var cbcopy = this._msg_callbacks[msg_id] = {};
451 452 cbcopy.shell = callbacks.shell;
452 453 cbcopy.iopub = callbacks.iopub;
453 454 cbcopy.input = callbacks.input;
454 455 this._msg_callbacks[msg_id] = cbcopy;
455 456 }
456 457 };
457 458
458 459
459 460 Kernel.prototype._handle_shell_reply = function (e) {
460 461 var reply = $.parseJSON(e.data);
461 462 $([IPython.events]).trigger('shell_reply.Kernel', {kernel: this, reply:reply});
462 463 var content = reply.content;
463 464 var metadata = reply.metadata;
464 465 var parent_id = reply.parent_header.msg_id;
465 466 var callbacks = this.get_callbacks_for_msg(parent_id);
466 467 if (!callbacks || !callbacks.shell) {
467 468 return;
468 469 }
469 470 var shell_callbacks = callbacks.shell;
470 471
471 472 // clear callbacks on shell
472 473 delete callbacks.shell;
473 474 delete callbacks.input;
474 475 if (!callbacks.iopub) {
475 476 this.clear_callbacks_for_msg(parent_id);
476 477 }
477 478
478 479 if (shell_callbacks.reply !== undefined) {
479 480 shell_callbacks.reply(reply);
480 481 }
481 482 if (content.payload && shell_callbacks.payload) {
482 483 this._handle_payloads(content.payload, shell_callbacks.payload, reply);
483 484 }
484 485 };
485 486
486 487
487 488 Kernel.prototype._handle_payloads = function (payloads, payload_callbacks, msg) {
488 489 var l = payloads.length;
489 490 // Payloads are handled by triggering events because we don't want the Kernel
490 491 // to depend on the Notebook or Pager classes.
491 492 for (var i=0; i<l; i++) {
492 493 var payload = payloads[i];
493 494 var callback = payload_callbacks[payload.source];
494 495 if (callback) {
495 496 callback(payload, msg);
496 497 }
497 498 }
498 499 };
499 500
500 501 Kernel.prototype._handle_status_message = function (msg) {
501 502 var execution_state = msg.content.execution_state;
502 503 var parent_id = msg.parent_header.msg_id;
503 504
504 505 // dispatch status msg callbacks, if any
505 506 var callbacks = this.get_callbacks_for_msg(parent_id);
506 507 if (callbacks && callbacks.iopub && callbacks.iopub.status) {
507 508 try {
508 509 callbacks.iopub.status(msg);
509 510 } catch (e) {
510 511 console.log("Exception in status msg handler", e, e.stack);
511 512 }
512 513 }
513 514
514 515 if (execution_state === 'busy') {
515 516 $([IPython.events]).trigger('status_busy.Kernel', {kernel: this});
516 517 } else if (execution_state === 'idle') {
517 518 // clear callbacks on idle, there can be no more
518 519 if (callbacks !== undefined) {
519 520 delete callbacks.iopub;
520 521 delete callbacks.input;
521 522 if (!callbacks.shell) {
522 523 this.clear_callbacks_for_msg(parent_id);
523 524 }
524 525 }
525 526 // trigger status_idle event
526 527 $([IPython.events]).trigger('status_idle.Kernel', {kernel: this});
527 528 } else if (execution_state === 'restarting') {
528 529 // autorestarting is distinct from restarting,
529 530 // in that it means the kernel died and the server is restarting it.
530 531 // status_restarting sets the notification widget,
531 532 // autorestart shows the more prominent dialog.
532 533 $([IPython.events]).trigger('status_autorestarting.Kernel', {kernel: this});
533 534 $([IPython.events]).trigger('status_restarting.Kernel', {kernel: this});
534 535 } else if (execution_state === 'dead') {
535 536 this.stop_channels();
536 537 $([IPython.events]).trigger('status_dead.Kernel', {kernel: this});
537 538 }
538 539 };
539 540
540 541
541 542 // handle clear_output message
542 543 Kernel.prototype._handle_clear_output = function (msg) {
543 544 var callbacks = this.get_callbacks_for_msg(msg.parent_header.msg_id);
544 545 if (!callbacks || !callbacks.iopub) {
545 546 return;
546 547 }
547 548 var callback = callbacks.iopub.clear_output;
548 549 if (callback) {
549 550 callback(msg);
550 551 }
551 552 };
552 553
553 554
554 555 // handle an output message (pyout, display_data, etc.)
555 556 Kernel.prototype._handle_output_message = function (msg) {
556 557 var callbacks = this.get_callbacks_for_msg(msg.parent_header.msg_id);
557 558 if (!callbacks || !callbacks.iopub) {
558 559 return;
559 560 }
560 561 var callback = callbacks.iopub.output;
561 562 if (callback) {
562 563 callback(msg);
563 564 }
564 565 };
565 566
566 567 // dispatch IOPub messages to respective handlers.
567 568 // each message type should have a handler.
568 569 Kernel.prototype._handle_iopub_message = function (e) {
569 570 var msg = $.parseJSON(e.data);
570 571
571 572 var handler = this.get_iopub_handler(msg.header.msg_type);
572 573 if (handler !== undefined) {
573 574 handler(msg);
574 575 }
575 576 };
576 577
577 578
578 579 Kernel.prototype._handle_input_request = function (e) {
579 580 var request = $.parseJSON(e.data);
580 581 var header = request.header;
581 582 var content = request.content;
582 583 var metadata = request.metadata;
583 584 var msg_type = header.msg_type;
584 585 if (msg_type !== 'input_request') {
585 586 console.log("Invalid input request!", request);
586 587 return;
587 588 }
588 589 var callbacks = this.get_callbacks_for_msg(request.parent_header.msg_id);
589 590 if (callbacks) {
590 591 if (callbacks.input) {
591 592 callbacks.input(request);
592 593 }
593 594 }
594 595 };
595 596
596 597
597 598 IPython.Kernel = Kernel;
598 599
599 600 return IPython;
600 601
601 602 }(IPython));
602 603
General Comments 0
You need to be logged in to leave comments. Login now