
    Ibv+                         d Z ddlZ	 ddlZddlmZmZ ddl	m
Z
 ddlmZ ddlmZ ddlmZ dd	lmZ  G d
 de
      Zy# e$ r	 ddlmZ Y ?w xY w)zA base class session manager.    N)dbapi2)genweb)LoggingConfigurable)unicode_type)Instance)maybe_future)InstanceFromClassesc                      e Zd Z ed      Z eddg      ZdZdZh dZ	e
d        Ze
d        Zd	 Zd
 Zej                   d        Zd Zej                   dd       Zej                   d        Zej                   dd       Zej                   d        Zej                   d        Zd Zej                   dd       Zej                   d        Zej                   d        Zy)SessionManagerz<notebook.services.kernels.kernelmanager.MappingKernelManagerz2notebook.services.contents.manager.ContentsManagerz8jupyter_server.services.contents.manager.ContentsManager)klassesN>   namepathtype	kernel_id
session_idc                     | j                   :| j                  j                         | _         | j                   j                  d       | j                   S )z5Start a cursor and create a database called 'session'zNCREATE TABLE session
                (session_id, path, name, type, kernel_id))_cursor
connectioncursorexecuteselfs    K/usr/lib/python3/dist-packages/notebook/services/sessions/sessionmanager.pyr   zSessionManager.cursor+   sC     <<??113DLLL   "= >||    c                     | j                   9t        j                  d      | _         t        j                  | j                   _        | j                   S )zStart a database connectionz:memory:)_connectionsqlite3connectRowrow_factoryr   s    r   r   zSessionManager.connection4   s?     #&z:D+2;;D(r   c                 `    | j                   "| j                   j                          d| _         yy)zClose the sqlite connectionN)r   closer   s    r   r#   zSessionManager.close<   s(    <<#LL DL $r   c                 $    | j                          y)z+Close connection once SessionManager closesN)r#   r   s    r   __del__zSessionManager.__del__B   s    

r   c              #      K   d}| j                   j                  d|f       | j                   j                         }|"t        | j	                  |d            }|d}t        j                  |      w)z2Check to see if the session of a given name existsFz"SELECT * FROM session WHERE path=?T)tolerate_culled)r   r   fetchoner	   row_to_modelr   Return)r   r   existsrowmodels        r   session_existszSessionManager.session_existsF   st      @4'Jkk""$? 't'8'8d'8'STTE jj  s   A3A5c                 <    t        t        j                               S )zCreate a uuid for a new session)r   uuiduuid4r   s    r   new_session_idzSessionManager.new_session_idW   s    DJJL))r   c           	   #      K   | j                         }||| j                  v rn| j                  |||||      }t        | j	                  |||||            }t        j                  |      w)z'Creates a session and returns its model)r   r   r   r   )r2   kernel_managerstart_kernel_for_sessionr	   save_sessionr   r*   )r   r   r   r   kernel_namer   r   results           r   create_sessionzSessionManager.create_session[   s      ((*
 Y$2E2E%E";;JdTXZeffI#jt$TU^_
 
 jj  s   A/A1c              #      K   | j                   j                  |      }t        | j                  j	                  ||            }t        j                  |      w)z'Start a new kernel for a given session.)r   )r   r7   )contents_managerget_kernel_pathr	   r4   start_kernelr   r*   )r   r   r   r   r   r7   kernel_pathr   s           r   r5   z'SessionManager.start_kernel_for_sessioni   sZ      ++;;;F&,,+;,W
 
	 jj##s   AAc              #      K   | j                   j                  d|||||f       t        | j                  |            }t	        j
                  |      w)a  Saves the items for the session with the given session_id

        Given a session_id (and any other of the arguments), this method
        creates a row in the sqlite session database that holds the information
        for a session.

        Parameters
        ----------
        session_id : str
            uuid for the session; this method must be given a session_id
        path : str
            the path for the given session
        name: str
            the name of the session
        type: string
            the type of the session
        kernel_id : str
            a uuid for the kernel associated with this session

        Returns
        -------
        model : dict
            a dictionary of the session model
        z&INSERT INTO session VALUES (?,?,?,?,?)r   )r   r   r	   get_sessionr   r*   )r   r   r   r   r   r   r8   s          r   r6   zSessionManager.save_sessiont   sW     4 	DtT95	
 $D$4$4
$4$KLLjj  s   AAc              +      K   |st        d      g }|j                         D ]0  }|| j                  vrt        d|      |j                  | d       2 ddj	                  |       }| j
                  j                  |t        |j                                      	 | j
                  j                         }|Xg }|j                         D ]  \  }}|j                  | d|        t        j                  dd	d
j	                  |             	 t        | j                  |            }	t!        j"                  |	      # t        $ r d}Y w xY w# t        $ r}
t        j                  dd	|
       d}
~
ww xY ww)aF  Returns the model for a particular session.

        Takes a keyword argument and searches for the value in the session
        database, then returns the rest of the session's info.

        Parameters
        ----------
        **kwargs : keyword argument
            must be given one of the keywords and values from the session database
            (i.e. session_id, path, name, type, kernel_id)

        Returns
        -------
        model : dict
            returns a dictionary that includes all the information from the
            session described by the kwarg.
        zmust specify a column to queryzNo such column: %r=?zSELECT * FROM session WHERE z AND N=i  zSession not found: , )	TypeErrorkeys_columnsappendjoinr   r   listvaluesr(   KeyErroritemsr   	HTTPErrorr	   r)   r   r*   )r   kwargs
conditionscolumnqueryr,   qkeyvaluer-   es              r   rA   zSessionManager.get_session   s|    & <==
kkm 	-FT]]* 4f==m,	-
 /w||J/G.HIE4#89	++&&(C
 ;A$lln -
UC5%+,- --':499Q<.%IJJ	@&t'8'8'=>>E jj  	C	  	@--':1#%>??	@sO   BE>E 7AE>E .E>EE>EE>	E;E66E;;E>c              +   r  K   t        | j                  |             |syg }|j                         D ]2  }|| j                  vrt	        d|      |j                  | d       4 ddj                  |       d}| j                  j                  |t        |j                               |gz          yw)a  Updates the values in the session database.

        Changes the values of the session with the given session_id
        with the values from the keyword arguments.

        Parameters
        ----------
        session_id : str
            a uuid that identifies a session in the sqlite3 database
        **kwargs : str
            the key must correspond to a column title in session database,
            and the value replaces the current value in the session
            with session_id.
        r@   NzNo such column: rC   zUPDATE session SET rE   z WHERE session_id=?)r	   rA   rG   rH   rF   rI   rJ   r   r   rK   rL   )r   r   rP   setsrR   rS   s         r   update_sessionzSessionManager.update_session   s       4++z+BCCkkm 	'FT]]*"26* =>>KK6("&	' &diio%66IJE4#8J<#GHs   B5B7c                     || j                   vS )zRChecks if the kernel is still considered alive and returns true if its not found. )r4   )r   r   s     r   kernel_culledzSessionManager.kernel_culled   s     3 333r   c              #     K   t        | j                  |d               }|ry| j                  j                  d|d   f       dj	                  |d   |d         }|r3| j
                  j                  |dz          t        j                  d      t        |      t        | j                  j                  |d               }|d   |d   |d	   |d
   |d}|d
   dk(  r|d   |d	   d|d<   t        j                  |      w)z@Takes sqlite database session row and turns it into a dictionaryr   &DELETE FROM session WHERE session_id=?r   zKernel '{kernel_id}' appears to have been culled or died unexpectedly, invalidating session '{session_id}'. The session has been removed.)r   r   z  Continuing...Nr   r   r   )idr   r   r   kernelnotebook)r   r   )r	   r\   r   r   formatlogwarningr   r*   rM   r4   kernel_model)r   r,   r'   r\   msgre   r-   s          r   r)   zSessionManager.row_to_model   s!     +4+=+=c+>N+OPP KK H!$\!2 46W[!1S=NO    '8!89jj&&3-)$*=*=*J*J3{K[*\]]l#KKK"
 v;*$),Vc&k JE*jjs   DDc              #     K   | j                   j                  d      }g }|j                         D ]0  }	 t        | j	                  |            }|j                  |       2 t        j                  |      # t        $ r Y Sw xY ww)z_Returns a list of dictionaries containing all the information from
        the session databasezSELECT * FROM session)	r   r   fetchallr	   r)   rI   rM   r   r*   )r   cr8   r,   r-   s        r   list_sessionszSessionManager.list_sessions  s      KK 78 ::< 	C*4+<+<S+ABBe$	 jj    s(   1B-A8!B8	BBBBc              #      K   t        | j                  |            }t        | j                  j                  |d   d                | j                  j                  d|f       yw)z=Deletes the row in the session database with given session_idr@   r`   r_   r^   N)r	   rA   r4   shutdown_kernelr   r   )r   r   sessions      r   delete_sessionzSessionManager.delete_session  sa      %T%5%5%5%LMM4..>>wx?PQU?VWXXDzmTs   A(A*)NNNNN)NNNN)F)__name__
__module____qualname__r   r4   r
   r;   r   r   rH   propertyr   r   r#   r%   r   	coroutiner.   r2   r9   r5   r6   rA   rZ   r\   r)   rj   rn    r   r   r   r      sO   \]N*@ G

 GKBH       	]]! ! * 	]]! ! 	]]$ $ 	]]! !> 	]]/  / b 	]]I I:4 	]]     D 	]]! ! 	]]U Ur   r   )__doc__r0   r   ImportError	pysqlite2r   tornador   r   traitlets.config.configurabler   ipython_genutils.py3compatr   	traitletsr   notebook.utilsr	   notebook.traittypesr
   r   rt   r   r   <module>r~      sN    #
 ,
  = 3  ' 3IU( IU  ,+,s   > AA