Personal emacs config
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

279 lines
12 KiB

  1. ;;; ein-jupyter.el --- Manage the jupyter notebook server -*- lexical-binding: t -*-
  2. ;; Copyright (C) 2017 John M. Miller
  3. ;; Authors: John M. Miller <millejoh at mac.com>
  4. ;; This file is NOT part of GNU Emacs.
  5. ;; ein-jupyter.el is free software: you can redistribute it and/or modify
  6. ;; it under the terms of the GNU General Public License as published by
  7. ;; the Free Software Foundation, either version 3 of the License, or
  8. ;; (at your option) any later version.
  9. ;; ein-jupyter.el is distributed in the hope that it will be useful,
  10. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. ;; GNU General Public License for more details.
  13. ;; You should have received a copy of the GNU General Public License
  14. ;; along with ein-jupyter.el. If not, see <http://www.gnu.org/licenses/>.
  15. ;;; Commentary:
  16. ;;; Code:
  17. (require 'ein-core)
  18. (require 'ein-notebooklist)
  19. (require 'ein-dev)
  20. (defcustom ein:jupyter-server-buffer-name "*ein:jupyter-server*"
  21. "The name of the buffer for the jupyter notebook server
  22. session."
  23. :group 'ein
  24. :type 'string)
  25. (defcustom ein:jupyter-server-run-timeout 60000
  26. "Time, in milliseconds, to wait for the jupyter server to start before declaring timeout and cancelling the operation."
  27. :group 'ein
  28. :type 'integer)
  29. (defcustom ein:jupyter-server-args '("--no-browser")
  30. "Add any additional command line options you wish to include
  31. with the call to the jupyter notebook."
  32. :group 'ein
  33. :type '(repeat string))
  34. (defcustom ein:jupyter-default-notebook-directory nil
  35. "If you are tired of always being queried for the location of
  36. the notebook directory, you can set it here for future calls to
  37. `ein:jupyter-server-start'"
  38. :group 'ein
  39. :type '(directory))
  40. (defvar *ein:jupyter-server-accept-timeout* 60)
  41. (defvar *ein:jupyter-server-process-name* "EIN: Jupyter notebook server")
  42. (defvar *ein:last-jupyter-command* nil)
  43. (defvar *ein:last-jupyter-directory* nil)
  44. (defcustom ein:jupyter-default-server-command "jupyter"
  45. "The default command to start a jupyter notebook server.
  46. Changing this to `jupyter-notebook' requires customizing `ein:jupyter-server-use-subcommand' to nil.
  47. "
  48. :group 'ein
  49. :type '(file)
  50. :set (lambda (symbol value)
  51. (set-default symbol value)
  52. (setq *ein:last-jupyter-command* nil)))
  53. (defcustom ein:jupyter-server-use-subcommand "notebook"
  54. "Users of \"jupyter-notebook\" (as opposed to \"jupyter notebook\") need to `Omit'."
  55. :group 'ein
  56. :type '(choice (string :tag "Subcommand" "notebook")
  57. (const :tag "Omit" nil)))
  58. (defcustom ein:jupyter-default-kernel 'first-alphabetically
  59. "With which of ${XDG_DATA_HOME}/jupyter/kernels to create new notebooks."
  60. :group 'ein
  61. :type (append
  62. '(choice (other :tag "First alphabetically" first-alphabetically))
  63. (condition-case err
  64. (mapcar
  65. (lambda (x) `(const :tag ,(cdr x) ,(car x)))
  66. (cl-loop
  67. for (k . spec) in
  68. (alist-get
  69. 'kernelspecs
  70. (let ((json-object-type 'alist))
  71. (json-read-from-string
  72. (shell-command-to-string
  73. (format "%s kernelspec list --json"
  74. ein:jupyter-default-server-command)))))
  75. collect `(,k . ,(alist-get 'display_name (alist-get 'spec spec)))))
  76. (error (ein:log 'warn "ein:jupyter-default-kernel: %s" err)
  77. '((string :tag "Ask"))))))
  78. (defsubst ein:jupyter-server-process ()
  79. "Return the emacs process object of our session"
  80. (get-buffer-process (get-buffer ein:jupyter-server-buffer-name)))
  81. (defun ein:jupyter-server--run (buf cmd dir &optional args)
  82. (when ein:debug
  83. (add-to-list 'ein:jupyter-server-args "--debug"))
  84. (unless (stringp dir)
  85. (error "ein:jupyter-server--run: notebook directory required"))
  86. (let* ((vargs (append (ein:aif ein:jupyter-server-use-subcommand (list it))
  87. (list (format "--notebook-dir=%s" (convert-standard-filename dir)))
  88. args
  89. ein:jupyter-server-args))
  90. (proc (apply #'start-process
  91. *ein:jupyter-server-process-name* buf cmd vargs)))
  92. (ein:log 'info "ein:jupyter-server--run: %s %s" cmd (ein:join-str " " vargs))
  93. (set-process-query-on-exit-flag proc nil)
  94. proc))
  95. (defun ein:jupyter-server-conn-info (&optional buffer-name)
  96. "Return the url-or-port and password for BUFFER or the global session."
  97. (unless buffer-name
  98. (setq buffer-name ein:jupyter-server-buffer-name))
  99. (let ((buffer (get-buffer buffer-name))
  100. (result '(nil nil)))
  101. (if buffer
  102. (with-current-buffer buffer
  103. (save-excursion
  104. (goto-char (point-max))
  105. (re-search-backward (format "Process %s" *ein:jupyter-server-process-name*)
  106. nil "") ;; important if we start-stop-start
  107. (when (re-search-forward "\\([[:alnum:]]+\\) is\\( now\\)? running" nil t)
  108. (let ((hub-p (cl-search "jupyterhub" (downcase (match-string 1)))))
  109. (when (re-search-forward "\\(https?://[^:]*:[0-9]+\\)\\(?:/\\?token=\\([[:alnum:]]+\\)\\)?" nil t)
  110. (let ((raw-url (match-string 1))
  111. (token (or (match-string 2) (and (not hub-p) ""))))
  112. (setq result (list (ein:url raw-url) token)))))))))
  113. result))
  114. (defun ein:jupyter-server-login-and-open (&optional callback)
  115. "Log in and open a notebooklist buffer for a running jupyter notebook server.
  116. Determine if there is a running jupyter server (started via a
  117. call to `ein:jupyter-server-start') and then try to guess if
  118. token authentication is enabled. If a token is found use it to generate a
  119. call to `ein:notebooklist-login' and once authenticated open the notebooklist buffer
  120. via a call to `ein:notebooklist-open'."
  121. (interactive)
  122. (when (ein:jupyter-server-process)
  123. (cl-multiple-value-bind (url-or-port _password) (ein:jupyter-server-conn-info)
  124. (ein:notebooklist-login url-or-port callback))))
  125. (defsubst ein:set-process-sentinel (proc url-or-port)
  126. "URL-OR-PORT might get redirected from (ein:jupyter-server-conn-info).
  127. This is currently only the case for jupyterhub.
  128. Once login handshake provides the new URL-OR-PORT, we set various state as pertains
  129. our singleton jupyter server process here."
  130. ;; Would have used `add-function' if it didn't produce gv-ref warnings.
  131. (set-process-sentinel
  132. proc
  133. (apply-partially (lambda (url-or-port* sentinel proc* event)
  134. (ein:aif sentinel (funcall it proc* event))
  135. (funcall #'ein:notebooklist-sentinel url-or-port* proc* event))
  136. url-or-port (process-sentinel proc))))
  137. ;;;###autoload
  138. (defun ein:jupyter-server-start (server-cmd-path notebook-directory
  139. &optional no-login-p login-callback port)
  140. "Start SERVER-CMD_PATH with `--notebook-dir' NOTEBOOK-DIRECTORY. Login after connection established unless NO-LOGIN-P is set. LOGIN-CALLBACK takes two arguments, the buffer created by ein:notebooklist-open--finish, and the url-or-port argument of ein:notebooklist-open*.
  141. This command opens an asynchronous process running the jupyter
  142. notebook server and then tries to detect the url and password to
  143. generate automatic calls to `ein:notebooklist-login' and
  144. `ein:notebooklist-open'.
  145. With \\[universal-argument] prefix arg, it will prompt the user for the path to
  146. the jupyter executable first. Else, it will try to use the
  147. value of `*ein:last-jupyter-command*' or the value of the
  148. customizable variable `ein:jupyter-default-server-command'.
  149. Then it prompts the user for the path of the root directory
  150. containing the notebooks the user wants to access.
  151. The buffer named by `ein:jupyter-server-buffer-name' will contain
  152. the log of the running jupyter server."
  153. (interactive
  154. (let* ((default-command (or *ein:last-jupyter-command*
  155. ein:jupyter-default-server-command))
  156. (server-cmd-path
  157. (executable-find (if current-prefix-arg
  158. (read-file-name "Server command: " default-directory nil nil
  159. default-command)
  160. default-command)))
  161. (notebook-directory
  162. (read-directory-name "Notebook directory: "
  163. (or *ein:last-jupyter-directory*
  164. ein:jupyter-default-notebook-directory))))
  165. (list server-cmd-path notebook-directory nil #'(lambda (buffer _url-or-port)
  166. (pop-to-buffer buffer)))))
  167. (unless (and (stringp server-cmd-path)
  168. (file-exists-p server-cmd-path)
  169. (file-executable-p server-cmd-path))
  170. (error "Command %s not found or not executable"
  171. (or *ein:last-jupyter-command*
  172. ein:jupyter-default-server-command)))
  173. (setf *ein:last-jupyter-command* server-cmd-path
  174. *ein:last-jupyter-directory* notebook-directory)
  175. (if (ein:jupyter-server-process)
  176. (error "Please first M-x ein:stop"))
  177. (add-hook 'kill-emacs-hook #'(lambda ()
  178. (ignore-errors (ein:jupyter-server-stop t))))
  179. (let ((proc (ein:jupyter-server--run ein:jupyter-server-buffer-name
  180. *ein:last-jupyter-command*
  181. *ein:last-jupyter-directory*
  182. (if (numberp port)
  183. `("--port" ,(format "%s" port)
  184. "--port-retries" "0")))))
  185. (when (eql system-type 'windows-nt)
  186. (accept-process-output proc (/ ein:jupyter-server-run-timeout 1000)))
  187. (cl-loop repeat 30
  188. until (car (ein:jupyter-server-conn-info ein:jupyter-server-buffer-name))
  189. do (sleep-for 0 500)
  190. finally do
  191. (unless (car (ein:jupyter-server-conn-info ein:jupyter-server-buffer-name))
  192. (ein:log 'warn "Jupyter server failed to start, cancelling operation")
  193. (ein:jupyter-server-stop t)))
  194. (when (and (not no-login-p) (ein:jupyter-server-process))
  195. (unless login-callback
  196. (setq login-callback #'ignore))
  197. (add-function :after (var login-callback)
  198. (apply-partially (lambda (proc* _buffer url-or-port)
  199. (ein:set-process-sentinel proc* url-or-port))
  200. proc))
  201. (ein:jupyter-server-login-and-open login-callback))))
  202. ;;;###autoload
  203. (defalias 'ein:run 'ein:jupyter-server-start)
  204. ;;;###autoload
  205. (defalias 'ein:stop 'ein:jupyter-server-stop)
  206. (defun ein:undocumented-shutdown (url-or-port)
  207. (ein:query-singleton-ajax
  208. (list 'shutdown-server url-or-port)
  209. (ein:url url-or-port "api/shutdown")
  210. :type "POST"
  211. :timeout 3 ;; content-query-timeout and query-timeout default nil
  212. :sync t))
  213. ;;;###autoload
  214. (defun ein:jupyter-server-stop (&optional force log)
  215. (interactive)
  216. (ein:and-let* ((url-or-port (car (ein:jupyter-server-conn-info)))
  217. (ok (or force (y-or-n-p "Stop server and close notebooks?"))))
  218. (ein:notebook-close-notebooks t)
  219. (cl-loop repeat 10
  220. do (ein:query-running-process-table)
  221. until (zerop (hash-table-count ein:query-running-process-table))
  222. do (sleep-for 0 500))
  223. (if (eq system-type 'windows-nt)
  224. (progn
  225. (ein:undocumented-shutdown url-or-port)
  226. (ein:aif (ein:jupyter-server-process)
  227. (delete-process it)))
  228. (let* ((proc (ein:jupyter-server-process))
  229. (pid (process-id proc)))
  230. (ein:log 'info "Signaled %s with pid %s" proc pid)
  231. (signal-process pid 15)
  232. (run-at-time 2 nil
  233. (lambda ()
  234. (ein:log 'info "Resignaled %s with pid %s" proc pid)
  235. (signal-process pid 15)))))
  236. ;; `ein:notebooklist-sentinel' frequently does not trigger
  237. (ein:notebooklist-list-remove url-or-port)
  238. (kill-buffer (ein:notebooklist-get-buffer url-or-port))
  239. (when log
  240. (with-current-buffer ein:jupyter-server-buffer-name
  241. (write-region (point-min) (point-max) log)))))
  242. (provide 'ein-jupyter)